diff --git a/docs/_docs/internals/backend.md b/docs/_docs/internals/backend.md index 1861ed6c1508..e3215c3993ae 100644 --- a/docs/_docs/internals/backend.md +++ b/docs/_docs/internals/backend.md @@ -30,7 +30,7 @@ BCodeIdiomatic ----------------> utilities for code generation, e.g. The `BTypes.scala` class contains the `BType` class and predefined BTypes -### Data Flow ### +## Data Flow ## Compiler creates a `GenBCode` `Phase`, calls `runOn(compilationUnits)`, which calls `run(context)`. This: @@ -51,12 +51,12 @@ which calls `run(context)`. This: - `GenBCodePipeline.drainQ3` writes byte arrays to disk -### Architecture ### +## Architecture ## The architecture of `GenBCode` is the same as in Scalac. It can be partitioned into weakly coupled components (called "subsystems" below): -#### (a) The queue subsystem #### +### (a) The queue subsystem ### Queues mediate between processors, queues don't know what each processor does. The first queue contains AST trees for compilation units, the second queue @@ -70,7 +70,7 @@ serialization to disk. This subsystem is described in detail in `GenBCode.scala` -#### (b) Bytecode-level types, BType #### +### (b) Bytecode-level types, BType ### The previous bytecode emitter goes to great lengths to reason about bytecode-level types in terms of Symbols. @@ -89,7 +89,7 @@ spec (that's why they aren't documented in `GenBCode`, just read the [JVM 8 spec All things `BType` can be found in `BCodeGlue.scala` -#### (c) Utilities offering a more "high-level" API to bytecode emission #### +### (c) Utilities offering a more "high-level" API to bytecode emission ### Bytecode can be emitted one opcode at a time, but there are recurring patterns that call for a simpler API. @@ -100,7 +100,7 @@ of two strategies. All these utilities are encapsulated in file `BCodeIdiomatic.scala`. They know nothing about the type checker (because, just between us, they don't need to). -#### (d) Mapping between type-checker types and BTypes #### +### (d) Mapping between type-checker types and BTypes ### So that (c) can remain oblivious to what AST trees contain, some bookkeepers are needed: @@ -115,7 +115,7 @@ final def exemplar(csym0: Symbol): Tracked = { ... } Details in `BTypes.scala` -#### (e) More "high-level" utilities for bytecode emission #### +### (e) More "high-level" utilities for bytecode emission ### In the spirit of `BCodeIdiomatic`, utilities are added in `BCodeHelpers` for emitting: @@ -125,5 +125,5 @@ emitting: - annotations -#### (f) Building an ASM ClassNode given an AST TypeDef #### +### (f) Building an ASM ClassNode given an AST TypeDef ### It's done by `PlainClassBuilder`(see `GenBCode.scala`). diff --git a/docs/_docs/internals/contexts.md b/docs/_docs/internals/contexts.md index 3674f03e2e51..4129787ad3f6 100644 --- a/docs/_docs/internals/contexts.md +++ b/docs/_docs/internals/contexts.md @@ -16,7 +16,7 @@ The `Context` contains the state of the compiler, for example * `typerState` (for example undetermined type variables) * ... -### Contexts in the typer ### +## Contexts in the typer ## The type checker passes contexts through all methods and adapts fields where necessary, e.g. @@ -26,7 +26,7 @@ case tree: untpd.Block => typedBlock(desugar.block(tree), pt)(ctx.fresh.withNewS A number of fields in the context are typer-specific (`mode`, `typerState`). -### In other phases ### +## In other phases ## Other phases need a context for many things, for example to access the denotation of a symbols (depends on the period). However they typically don't need to modify / extend the context while traversing the AST. For these phases @@ -36,7 +36,7 @@ all members. **Careful**: beware of memory leaks. Don't hold on to contexts in long lived objects. -### Using contexts ### +## Using contexts ## Nested contexts should be named `ctx` to enable implicit shadowing: ```scala diff --git a/docs/_docs/internals/dotc-scalac.md b/docs/_docs/internals/dotc-scalac.md index a8de3bfff00e..3f88502934b7 100644 --- a/docs/_docs/internals/dotc-scalac.md +++ b/docs/_docs/internals/dotc-scalac.md @@ -6,7 +6,7 @@ title: "Differences between Scalac and Dotty" Overview explanation how symbols, named types and denotations hang together: [Denotations1] -### Denotation ### +## Denotation ## Comment with a few details: [Denotations2] A `Denotation` is the result of a name lookup during a given period @@ -21,7 +21,7 @@ A `Denotation` is the result of a name lookup during a given period Denotations of methods have a signature ([Signature1]), which uniquely identifies overloaded methods. -#### Denotation vs. SymDenotation #### +### Denotation vs. SymDenotation ### A `SymDenotation` is an extended denotation that has symbol-specific properties (that may change over phases) * `flags` @@ -31,7 +31,7 @@ A `SymDenotation` is an extended denotation that has symbol-specific properties `SymDenotation` implements lazy types (similar to scalac). The type completer assigns the denotation's `info`. -#### Implicit Conversion #### +### Implicit Conversion ### There is an implicit conversion: ```scala core.Symbols.toDenot(sym: Symbol)(implicit ctx: Context): SymDenotation @@ -42,7 +42,7 @@ implicit conversion does **not** need to be imported, it is part of the implicit scope of the type `Symbol` (check the Scala spec). However, it can only be applied if an implicit `Context` is in scope. -### Symbol ### +## Symbol ## * `Symbol` instances have a `SymDenotation` * Most symbol properties in the Scala 2 compiler are now in the denotation (in the Scala 3 compiler). @@ -57,7 +57,7 @@ if (sym is Flags.PackageClass) // Scala 3 (*) `(*)` Symbols are implicitly converted to their denotation, see above. Each `SymDenotation` has flags that can be queried using the `is` method. -### Flags ### +## Flags ## * Flags are instances of the value class `FlagSet`, which encapsulates a `Long` * Each flag is either valid for types, terms, or both @@ -74,7 +74,7 @@ if (sym is Flags.PackageClass) // Scala 3 (*) `ModuleVal` / `ModuleClass` for either of the two. * `flags.is(Method | Param)`: true if `flags` has either of the two -### Tree ### +## Tree ## * Trees don't have symbols - `tree.symbol` is `tree.denot.symbol` - `tree.denot` is `tree.tpe.denot` where the `tpe` is a `NamdedType` (see @@ -87,7 +87,7 @@ if (sym is Flags.PackageClass) // Scala 3 (*) using `prefix.member(name)`. -### Type ### +## Type ## * `MethodType(paramSyms, resultType)` from scalac => `mt @ MethodType(paramNames, paramTypes)`. Result type is `mt.resultType` diff --git a/docs/_docs/internals/syntax-3.1.md b/docs/_docs/internals/syntax-3.1.md index ef18bd1486b1..4d4d3b6d858d 100644 --- a/docs/_docs/internals/syntax-3.1.md +++ b/docs/_docs/internals/syntax-3.1.md @@ -16,7 +16,7 @@ hexDigit ::= ‘0’ | … | ‘9’ | ‘A’ | … | ‘F’ | ‘a’ | Informal descriptions are typeset as `“some comment”`. -### Lexical Syntax +## Lexical Syntax The lexical syntax of Scala is given by the following grammar in EBNF form. diff --git a/docs/_docs/internals/syntax.md b/docs/_docs/internals/syntax.md index 8c8f83450397..bae8e6d3ec8d 100644 --- a/docs/_docs/internals/syntax.md +++ b/docs/_docs/internals/syntax.md @@ -30,7 +30,7 @@ hexDigit ::= ‘0’ | … | ‘9’ | ‘A’ | … | ‘F’ | ‘a’ | Informal descriptions are typeset as `“some comment”`. -### Lexical Syntax +## Lexical Syntax The lexical syntax of Scala is given by the following grammar in EBNF form. diff --git a/docs/_docs/reference/changed-features/imports.md b/docs/_docs/reference/changed-features/imports.md index 43e8704192ee..2058ef08b7db 100644 --- a/docs/_docs/reference/changed-features/imports.md +++ b/docs/_docs/reference/changed-features/imports.md @@ -38,13 +38,13 @@ import scala.annotation as ann import java as j ``` -### Migration +## Migration To support cross-building, Scala 3.0 supports the old import syntax with `_` for wildcards and `=>` for renamings in addition to the new one. The old syntax will be dropped in a future versions. Automatic rewritings from old to new syntax are offered under settings `-source 3.1-migration -rewrite`. -### Syntax +## Syntax ``` Import ::= ‘import’ ImportExpr {‘,’ ImportExpr} diff --git a/docs/_docs/reference/changed-features/wildcards.md b/docs/_docs/reference/changed-features/wildcards.md index 6ef3e66c5e24..0d3e13c3d7e0 100644 --- a/docs/_docs/reference/changed-features/wildcards.md +++ b/docs/_docs/reference/changed-features/wildcards.md @@ -10,7 +10,7 @@ List[?] Map[? <: AnyRef, ? >: Null] ``` -### Motivation +## Motivation We would like to use the underscore syntax `_` to stand for an anonymous type parameter, aligning it with its meaning in value parameter lists. So, just as `f(_)` is a shorthand for the lambda `x => f(x)`, in the future `C[_]` will be a shorthand @@ -21,7 +21,7 @@ In the future, `F[_]` will mean the same thing, no matter where it is used. We pick `?` as a replacement syntax for wildcard types, since it aligns with [Java's syntax](https://docs.oracle.com/javase/tutorial/java/generics/wildcardGuidelines.html). -### Migration Strategy +## Migration Strategy The migration to the new scheme is complicated, in particular since the [kind projector](https://github.com/typelevel/kind-projector) compiler plugin still uses the reverse convention, with `?` meaning parameter placeholder instead of wildcard. Fortunately, kind projector has added `*` as an alternative syntax for `?`. diff --git a/docs/_docs/reference/contextual/by-name-context-parameters.md b/docs/_docs/reference/contextual/by-name-context-parameters.md index 593ebc6be7cc..3004bfb2c4c2 100644 --- a/docs/_docs/reference/contextual/by-name-context-parameters.md +++ b/docs/_docs/reference/contextual/by-name-context-parameters.md @@ -59,7 +59,7 @@ val s = summon[Test.Codec[Option[Int]]]( No local given instance was generated because the synthesized argument is not recursive. -### Reference +## Reference For more information, see [Issue #1998](https://github.com/lampepfl/dotty/issues/1998) and the associated [Scala SIP](https://docs.scala-lang.org/sips/byname-implicits.html). diff --git a/docs/_docs/reference/contextual/context-functions-spec.md b/docs/_docs/reference/contextual/context-functions-spec.md index 66a5bed432ce..109513e9da86 100644 --- a/docs/_docs/reference/contextual/context-functions-spec.md +++ b/docs/_docs/reference/contextual/context-functions-spec.md @@ -74,6 +74,6 @@ See the section on Expressiveness from [Simplicitly: foundations and applications of implicit function types](https://dl.acm.org/citation.cfm?id=3158130). -### Type Checking +## Type Checking After desugaring no additional typing rules are required for context function types. diff --git a/docs/_docs/reference/contextual/context-functions.md b/docs/_docs/reference/contextual/context-functions.md index 6eb838896fc9..0ad3c8757782 100644 --- a/docs/_docs/reference/contextual/context-functions.md +++ b/docs/_docs/reference/contextual/context-functions.md @@ -48,7 +48,7 @@ For example, continuing with the previous definitions, g((ctx: ExecutionContext) ?=> f(3)(using ctx)) // is left as it is ``` -### Example: Builder Pattern +## Example: Builder Pattern Context function types have considerable expressive power. For instance, here is how they can support the "builder pattern", where @@ -112,7 +112,7 @@ With that setup, the table construction code above compiles and expands to: }(using $t) } ``` -### Example: Postconditions +## Example: Postconditions As a larger example, here is a way to define constructs for checking arbitrary postconditions using an extension method `ensuring` so that the checked result can be referred to simply by `result`. The example combines opaque type aliases, context function types, and extension methods to provide a zero-overhead abstraction. @@ -146,7 +146,7 @@ val s = assert(result == 6) result ``` -### Reference +## Reference For more information, see the [blog article](https://www.scala-lang.org/blog/2016/12/07/implicit-function-types.html), (which uses a different syntax that has been superseded). diff --git a/docs/_docs/reference/contextual/contextual.md b/docs/_docs/reference/contextual/contextual.md index a2eaa8a27d2f..fda63397f8f9 100644 --- a/docs/_docs/reference/contextual/contextual.md +++ b/docs/_docs/reference/contextual/contextual.md @@ -4,7 +4,7 @@ title: "Contextual Abstractions" nightlyOf: https://docs.scala-lang.org/scala3/reference/contextual.html --- -### Critique of the Status Quo +## Critique of the Status Quo Scala's implicits are its most distinguished feature. They are _the_ fundamental way to abstract over context. They represent a unified paradigm with a great variety of use cases, among them: implementing type classes, establishing context, dependency injection, expressing capabilities, computing new types and proving relationships between them. @@ -46,7 +46,7 @@ Historically, many of these shortcomings come from the way implicits were gradua Existing Scala programmers by and large have gotten used to the status quo and see little need for change. But for newcomers this status quo presents a big hurdle. I believe if we want to overcome that hurdle, we should take a step back and allow ourselves to consider a radically new design. -### The New Design +## The New Design The following pages introduce a redesign of contextual abstractions in Scala. They introduce four fundamental changes: diff --git a/docs/_docs/reference/contextual/derivation.md b/docs/_docs/reference/contextual/derivation.md index a81df53d573d..bad47dcb0096 100644 --- a/docs/_docs/reference/contextual/derivation.md +++ b/docs/_docs/reference/contextual/derivation.md @@ -26,7 +26,7 @@ given [T: Show] : Show[Tree[T]] = Show.derived We say that `Tree` is the _deriving type_ and that the `Eq`, `Ordering` and `Show` instances are _derived instances_. -### Types supporting `derives` clauses +## Types supporting `derives` clauses All data types can have a `derives` clause. This document focuses primarily on data types which also have a given instance of the `Mirror` type class available. @@ -158,7 +158,7 @@ Note the following properties of `Mirror` types, + The methods `ordinal` and `fromProduct` are defined in terms of `MirroredMonoType` which is the type of kind-`*` which is obtained from `MirroredType` by wildcarding its type parameters. -### Type classes supporting automatic deriving +## Type classes supporting automatic deriving A trait or class can appear in a `derives` clause if its companion object defines a method named `derived`. The signature and implementation of a `derived` method for a type class `TC[_]` are arbitrary but it is typically of the @@ -186,7 +186,7 @@ authors would normally implement a `derived` method in this way, however this wa authors of the higher level derivation libraries that we expect typical type class authors will use (for a fully worked out example of such a library, see [Shapeless 3](https://github.com/milessabin/shapeless/tree/shapeless-3)). -#### How to write a type class `derived` method using low level mechanisms +## How to write a type class `derived` method using low level mechanisms The low-level method we will use to implement a type class `derived` method in this example exploits three new type-level constructs in Scala 3: inline methods, inline matches, and implicit searches via `summonInline` or `summonFrom`. Given this definition of the @@ -360,7 +360,7 @@ The framework described here enables all three of these approaches without manda For a brief discussion on how to use macros to write a type class `derived` method please read more at [How to write a type class `derived` method using macros](./derivation-macro.md). -### Deriving instances elsewhere +## Deriving instances elsewhere Sometimes one would like to derive a type class instance for an ADT after the ADT is defined, without being able to change the code of the ADT itself. To do this, simply define an instance using the `derived` method of the type class @@ -374,7 +374,7 @@ Assuming the `Ordering.derived` method has a context parameter of type `Mirror[T compiler generated `Mirror` instance for `Option` and the derivation of the instance will be expanded on the right hand side of this definition in the same way as an instance defined in ADT companion objects. -### Syntax +## Syntax ``` Template ::= InheritClauses [TemplateBody] @@ -397,7 +397,7 @@ It is equivalent to the old form class A extends B with C { ... } ``` -### Discussion +## Discussion This type class derivation framework is intentionally very small and low-level. There are essentially two pieces of infrastructure in compiler-generated `Mirror` instances, diff --git a/docs/_docs/reference/contextual/extension-methods.md b/docs/_docs/reference/contextual/extension-methods.md index 77e06ee687b2..d23cadf513d7 100644 --- a/docs/_docs/reference/contextual/extension-methods.md +++ b/docs/_docs/reference/contextual/extension-methods.md @@ -20,7 +20,7 @@ val circle = Circle(0, 0, 1) circle.circumference ``` -### Translation of Extension Methods +## Translation of Extension Methods An extension method translates to a specially labelled method that takes the leading parameter section as its first argument list. The label, expressed as `` here, is compiler-internal. So, the definition of `circumference` above translates to the following method, and can also be invoked as such: @@ -31,7 +31,7 @@ as `` here, is compiler-internal. So, the definition of `circumferenc assert(circle.circumference == circumference(circle)) ``` -### Operators +## Operators The extension method syntax can also be used to define operators. Examples: @@ -63,7 +63,7 @@ compiler preprocesses an infix operation `x +: xs` to `xs.+:(x)`, so the extensi method ends up being applied to the sequence as first argument (in other words, the two swaps cancel each other out). See [here for details](./right-associative-extension-methods.md). -### Generic Extensions +## Generic Extensions It is also possible to extend generic types by adding type parameters to an extension. For instance: @@ -109,7 +109,7 @@ extension [T](x: T)(using n: Numeric[T]) def + (y: T): T = n.plus(x, y) ``` -### Collective Extensions +## Collective Extensions Sometimes, one wants to define several extension methods that share the same left-hand parameter type. In this case one can "pull out" the common parameters into @@ -166,7 +166,7 @@ extension [T](xs: List[T])(using Ordering[T]) xs.zipWithIndex.collect { case (x, i) if x <= limit => i } ``` -### Translation of Calls to Extension Methods +## Translation of Calls to Extension Methods To convert a reference to an extension method, the compiler has to know about the extension method. We say in this case that the extension method is _applicable_ at the point of reference. @@ -280,7 +280,7 @@ def position(s: String)(ch: Char, n: Int): Int = else n ``` -### Syntax +## Syntax Here are the syntax changes for extension methods and collective extensions relative to the [current syntax](../syntax.md). diff --git a/docs/_docs/reference/contextual/given-imports.md b/docs/_docs/reference/contextual/given-imports.md index c5936a58a4a6..6a55368979b1 100644 --- a/docs/_docs/reference/contextual/given-imports.md +++ b/docs/_docs/reference/contextual/given-imports.md @@ -40,7 +40,7 @@ There are two main benefits arising from these rules: can be anonymous, so the usual recourse of using named imports is not practical. -### Importing By Type +## Importing By Type Since givens can be anonymous it is not always practical to import them by their name, and wildcard imports are typically used instead. By-type imports provide a more specific alternative to wildcard imports, which makes it clearer what is imported. Example: @@ -82,7 +82,7 @@ import Instances.{im, given Ordering[?]} would import `im`, `intOrd`, and `listOrd` but leave out `ec`. -### Migration +## Migration The rules for imports stated above have the consequence that a library would have to migrate in lockstep with all its users from old style implicits and @@ -101,7 +101,7 @@ These rules mean that library users can use `given` selectors to access old-styl and will be gently nudged and then forced to do so in later versions. Libraries can then switch to given instances once their user base has migrated. -### Syntax +## Syntax ``` Import ::= ‘import’ ImportExpr {‘,’ ImportExpr} diff --git a/docs/_docs/reference/contextual/type-classes.md b/docs/_docs/reference/contextual/type-classes.md index 71403ee6b9c3..9fc0d2eec864 100644 --- a/docs/_docs/reference/contextual/type-classes.md +++ b/docs/_docs/reference/contextual/type-classes.md @@ -12,7 +12,7 @@ A _type class_ is an abstract, parameterized type that lets you add new behavior Therefore in Scala 3, _type classes_ are just _traits_ with one or more parameters whose implementations are not defined through the `extends` keyword, but by **given instances**. Here are some examples of common type classes: -### Semigroups and monoids +## Semigroups and monoids Here's the `Monoid` type class definition: @@ -61,7 +61,7 @@ def combineAll[T: Monoid](xs: List[T]): T = xs.foldLeft(Monoid[T].unit)(_.combine(_)) ``` -### Functors +## Functors A `Functor` for a type provides the ability for its values to be "mapped over", i.e. apply a function that transforms inside a value while remembering its shape. For example, to modify every element of a collection without dropping or adding elements. We can represent all types that can be "mapped over" with `F`. It's a type constructor: the type of its values becomes concrete when provided a type argument. @@ -127,7 +127,7 @@ The `map` method is now directly used on `original`. It is available as an exten since `original`'s type is `F[A]` and a given instance for `Functor[F[A]]` which defines `map` is in scope. -### Monads +## Monads Applying `map` in `Functor[List]` to a mapping function of type `A => B` results in a `List[B]`. So applying it to a mapping function of type `A => List[B]` results in a `List[List[B]]`. To avoid managing lists of lists, we may want to "flatten" the values in a single list. @@ -154,7 +154,7 @@ trait Monad[F[_]] extends Functor[F]: end Monad ``` -#### List +### List A `List` can be turned into a monad via this `given` instance: @@ -171,7 +171,7 @@ Since `Monad` is a subtype of `Functor`, `List` is also a functor. The Functor's operation is already provided by the `Monad` trait, so the instance does not need to define it explicitly. -#### Option +### Option `Option` is an other type having the same kind of behaviour: @@ -185,7 +185,7 @@ given optionMonad: Monad[Option] with case None => None ``` -#### Reader +### Reader Another example of a `Monad` is the _Reader_ Monad, which acts on functions instead of data types like `List` or `Option`. It can be used to combine multiple functions @@ -271,7 +271,7 @@ given readerMonad[Ctx]: Monad[[X] =>> Ctx => X] with end readerMonad ``` -### Summary +## Summary The definition of a _type class_ is expressed with a parameterised type with abstract members, such as a `trait`. The main difference between subtype polymorphism and ad-hoc polymorphism with _type classes_ is how the definition of the _type class_ is implemented, in relation to the type it acts upon. diff --git a/docs/_docs/reference/dropped-features/auto-apply.md b/docs/_docs/reference/dropped-features/auto-apply.md index 154bd2620635..eadfe2f429ea 100644 --- a/docs/_docs/reference/dropped-features/auto-apply.md +++ b/docs/_docs/reference/dropped-features/auto-apply.md @@ -84,13 +84,13 @@ class B extends A: Methods overriding Java or Scala 2 methods are again exempted from this requirement. -### Migrating code +## Migrating code Existing Scala code with inconsistent parameters can still be compiled in Scala 3 under `-source 3.0-migration`. When paired with the `-rewrite` option, the code will be automatically rewritten to conform to Scala 3's stricter checking. -### Reference +## Reference For more information, see [Issue #2570](https://github.com/lampepfl/dotty/issues/2570) and [PR #2716](https://github.com/lampepfl/dotty/pull/2716). diff --git a/docs/_docs/reference/dropped-features/do-while.md b/docs/_docs/reference/dropped-features/do-while.md index be86a73fd40d..08a730b8b5a7 100644 --- a/docs/_docs/reference/dropped-features/do-while.md +++ b/docs/_docs/reference/dropped-features/do-while.md @@ -35,7 +35,7 @@ while do print(".") ``` -### Why Drop The Construct? +## Why Drop The Construct? - `do-while` is used relatively rarely and it can be expressed faithfully using just `while`. So there seems to be little point in having it as a separate syntax construct. - Under the [new syntax rules](../other-new-features/control-syntax.md) `do` is used as a statement continuation, which would clash with its meaning as a statement introduction. diff --git a/docs/_docs/reference/dropped-features/weak-conformance-spec.md b/docs/_docs/reference/dropped-features/weak-conformance-spec.md index 78fa0f553fd5..07625dcfe885 100644 --- a/docs/_docs/reference/dropped-features/weak-conformance-spec.md +++ b/docs/_docs/reference/dropped-features/weak-conformance-spec.md @@ -38,7 +38,7 @@ assigning a type to a constant expression. The new rule is: - an `Int -> Short` conversion of a constant `c` if `c.toShort.toInt != c`. -### Examples +## Examples ```scala inline val b = 33 diff --git a/docs/_docs/reference/enums/adts.md b/docs/_docs/reference/enums/adts.md index 818db9ee61be..3ab8c9f3b45b 100644 --- a/docs/_docs/reference/enums/adts.md +++ b/docs/_docs/reference/enums/adts.md @@ -91,7 +91,7 @@ enum Color(val rgb: Int): case Mix(mix: Int) extends Color(mix) ``` -### Parameter Variance of Enums +## Parameter Variance of Enums By default, parameterized cases of enums with type parameters will copy the type parameters of their parent, along with any variance notations. As usual, it is important to use type parameters carefully when they are variant, as shown @@ -147,7 +147,7 @@ enum View[-T, +U] extends (T => U): case refl: Refl[r] => refl.f(t) ``` -### Syntax of Enums +## Syntax of Enums Changes to the syntax fall in two categories: enum definitions and cases inside enums. The changes are specified below as deltas with respect to the Scala syntax given [here](../syntax.md) @@ -168,6 +168,6 @@ The changes are specified below as deltas with respect to the Scala syntax given EnumCase ::= `case' (id ClassConstr [`extends' ConstrApps]] | ids) ``` -### Reference +## Reference For more information, see [Issue #1970](https://github.com/lampepfl/dotty/issues/1970). diff --git a/docs/_docs/reference/enums/desugarEnums.md b/docs/_docs/reference/enums/desugarEnums.md index a06736feb1f0..477653d670bb 100644 --- a/docs/_docs/reference/enums/desugarEnums.md +++ b/docs/_docs/reference/enums/desugarEnums.md @@ -159,7 +159,7 @@ map into `case class`es or `val`s. as long as that type is still compatible with the expected type at the point of application. A call `t.copy(ts)` of `C`'s `copy` method is treated in the same way. -### Translation of Enums with Singleton Cases +## Translation of Enums with Singleton Cases An enum `E` (possibly generic) that defines one or more singleton cases will define the following additional synthetic members in its companion object (where `E'` denotes `E` with @@ -189,7 +189,7 @@ The `ordinal` method is only generated if the enum does not extend from `java.la `java.lang.Enum` defines it. Similarly there is no need to override `toString` as that is defined in terms of `name` in `java.lang.Enum`. Finally, `productPrefix` will call `this.name` when `E` extends `java.lang.Enum`. -### Scopes for Enum Cases +## Scopes for Enum Cases A case in an `enum` is treated similarly to a secondary constructor. It can access neither the enclosing `enum` using `this`, nor its value parameters or instance members using simple identifiers. @@ -197,7 +197,7 @@ identifiers. Even though translated enum cases are located in the enum's companion object, referencing this object or its members via `this` or a simple identifier is also illegal. The compiler typechecks enum cases in the scope of the enclosing companion object but flags any such illegal accesses as errors. -### Translation of Java-compatible enums +## Translation of Java-compatible enums A Java-compatible enum is an enum that extends `java.lang.Enum`. The translation rules are the same as above, with the reservations defined in this section. @@ -205,7 +205,7 @@ It is a compile-time error for a Java-compatible enum to have class cases. Cases such as `case C` expand to a `@static val` as opposed to a `val`. This allows them to be generated as static fields of the enum type, thus ensuring they are represented the same way as Java enums. -### Other Rules +## Other Rules - A normal case class which is not produced from an enum case is not allowed to extend `scala.reflect.Enum`. This ensures that the only cases of an enum are the ones that are diff --git a/docs/_docs/reference/enums/enums.md b/docs/_docs/reference/enums/enums.md index 2760fb037b2d..65051bdfb39f 100644 --- a/docs/_docs/reference/enums/enums.md +++ b/docs/_docs/reference/enums/enums.md @@ -15,7 +15,7 @@ This defines a new `sealed` class, `Color`, with three values, `Color.Red`, `Color.Green`, `Color.Blue`. The color values are members of `Color`s companion object. -### Parameterized enums +## Parameterized enums Enums can be parameterized. @@ -29,7 +29,7 @@ enum Color(val rgb: Int): As the example shows, you can define the parameter value by using an explicit extends clause. -### Methods defined for enums +## Methods defined for enums The values of an enum correspond to unique integers. The integer associated with an enum value is returned by its `ordinal` method: @@ -56,7 +56,7 @@ scala> Color.fromOrdinal(0) val res2: Color = Red ``` -### User-defined members of enums +## User-defined members of enums It is possible to add your own definitions to an enum. Example: @@ -77,7 +77,7 @@ enum Planet(mass: Double, radius: Double): end Planet ``` -### User-defined companion object of enums +## User-defined companion object of enums It is also possible to define an explicit companion object for an enum: ```scala @@ -90,7 +90,7 @@ object Planet: end Planet ``` -### Restrictions on Enum Cases +## Restrictions on Enum Cases Enum case declarations are similar to secondary constructors: they are scoped outside of the enum template, despite being declared within it. @@ -117,7 +117,7 @@ The fields referenced by `Mercury` are not visible, and the fields referenced by be referenced directly (using `import Planet.*`). You must use an indirect reference, such as demonstrated with `Earth`. -### Deprecation of Enum Cases +## Deprecation of Enum Cases As a library author, you may want to signal that an enum case is no longer intended for use. However you could still want to gracefully handle the removal of a case from your public API, such as special casing deprecated cases. @@ -161,7 +161,7 @@ object Planet { We could imagine that a library may use [type class derivation](../contextual/derivation.md) to automatically provide an instance for `Deprecations`. -### Compatibility with Java Enums +## Compatibility with Java Enums If you want to use the Scala-defined enums as [Java enums](https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html), you can do so by extending the class `java.lang.Enum`, which is imported by default, as follows: @@ -182,7 +182,7 @@ val res15: Int = -1 For a more in-depth example of using Scala 3 enums from Java, see [this test](https://github.com/lampepfl/dotty/tree/main/tests/run/enum-java). In the test, the enums are defined in the `MainScala.scala` file and used from a Java source, `Test.java`. -### Implementation +## Implementation Enums are represented as `sealed` classes that extend the `scala.reflect.Enum` trait. This trait defines a single public method, `ordinal`: @@ -216,7 +216,7 @@ definition of value `Color.Red` above would expand to: val Red: Color = $new(0, "Red") ``` -### Reference +## Reference For more information, see [Issue #1970](https://github.com/lampepfl/dotty/issues/1970) and [PR #4003](https://github.com/lampepfl/dotty/pull/4003). diff --git a/docs/_docs/reference/experimental/overview.md b/docs/_docs/reference/experimental/overview.md index 0f2aa543ebbb..6127fcd1ef7e 100644 --- a/docs/_docs/reference/experimental/overview.md +++ b/docs/_docs/reference/experimental/overview.md @@ -5,7 +5,7 @@ nightlyOf: https://docs.scala-lang.org/scala3/reference/experimental/overview.ht redirectFrom: overview.html --- -### Experimental language features +## Experimental language features All experimental language features can be found under the `scala.language.experimental` package. They are enabled by importing the feature or using the `-language` compiler flag. @@ -16,12 +16,12 @@ They are enabled by importing the feature or using the `-language` compiler flag * [`namedTypeArguments`](./named-typeargs.md): Enable support for named type arguments * [`saferExceptions`](./canthrow.md): Enable support for checked exceptions. -### Experimental language imports +## Experimental language imports In general, experimental language features can be imported in an experimental scope (see [experimental definitions](../other-new-features/experimental-defs.md)). They can be imported at the top-level if all top-level definitions are `@experimental`. -### Experimental language features supported by special compiler options +## Experimental language features supported by special compiler options Some experimental language features that are still in research and development can be enabled with special compiler options. These include diff --git a/docs/_docs/reference/metaprogramming/inline.md b/docs/_docs/reference/metaprogramming/inline.md index 065b7a1e9e71..8516957c6412 100644 --- a/docs/_docs/reference/metaprogramming/inline.md +++ b/docs/_docs/reference/metaprogramming/inline.md @@ -224,7 +224,7 @@ If a `inline` modifier is given for parameters, corresponding arguments must be pure expressions of constant type. --> -#### The definition of constant expression +### The definition of constant expression Right-hand sides of inline values and of arguments for inline parameters must be constant expressions in the sense defined by the [SLS §6.24](https://www.scala-lang.org/files/archive/spec/2.13/06-expressions.html#constant-expressions), @@ -384,6 +384,6 @@ val intTwo: 2 = natTwo `natTwo` is inferred to have the singleton type 2. -### Reference +## Reference For more information about the semantics of `inline`, see the [Scala 2020: Semantics-preserving inlining for metaprogramming](https://dl.acm.org/doi/10.1145/3426426.3428486) paper. diff --git a/docs/_docs/reference/new-types/dependent-function-types-spec.md b/docs/_docs/reference/new-types/dependent-function-types-spec.md index 984a44d25e37..f3237ddf7b9a 100644 --- a/docs/_docs/reference/new-types/dependent-function-types-spec.md +++ b/docs/_docs/reference/new-types/dependent-function-types-spec.md @@ -120,6 +120,6 @@ def composeFn[A, B, C]: assert(composeFn(i2s)(s2i)(22) == 2) ``` -### Type Checking +## Type Checking After desugaring no additional typing rules are required for dependent function types. diff --git a/docs/_docs/reference/new-types/type-lambdas-spec.md b/docs/_docs/reference/new-types/type-lambdas-spec.md index 15487e4d8cde..52f88dab4217 100644 --- a/docs/_docs/reference/new-types/type-lambdas-spec.md +++ b/docs/_docs/reference/new-types/type-lambdas-spec.md @@ -13,7 +13,7 @@ TypeParam ::= {Annotation} (id [HkTypeParamClause] | ‘_’) TypeBounds TypeBounds ::= [‘>:’ Type] [‘<:’ Type] ``` -### Type Checking +## Type Checking A type lambda such as `[X] =>> F[X]` defines a function from types to types. The parameter(s) may carry bounds. If a parameter is bounded, as in `[X >: L <: U] =>> F[X]` it is checked that arguments to the parameters conform to the bounds `L` and `U`. diff --git a/docs/_docs/reference/other-new-features/control-syntax.md b/docs/_docs/reference/other-new-features/control-syntax.md index 574e53406e27..92204690f0b7 100644 --- a/docs/_docs/reference/other-new-features/control-syntax.md +++ b/docs/_docs/reference/other-new-features/control-syntax.md @@ -41,7 +41,7 @@ The rules in detail are: - A `catch` can be followed by a single case on the same line. If there are multiple cases, these have to appear within braces (just like in Scala 2) or an indented block. -### Rewrites +## Rewrites The Scala 3 compiler can rewrite source code from old syntax to new syntax and back. When invoked with options `-rewrite -new-syntax` it will rewrite from old to new syntax, dropping parentheses and braces in conditions and enumerators. When invoked with options `-rewrite -old-syntax` it will rewrite in the reverse direction, inserting parentheses and braces as needed. diff --git a/docs/_docs/reference/other-new-features/creator-applications.md b/docs/_docs/reference/other-new-features/creator-applications.md index a7b0366210c0..81f09d897955 100644 --- a/docs/_docs/reference/other-new-features/creator-applications.md +++ b/docs/_docs/reference/other-new-features/creator-applications.md @@ -50,7 +50,7 @@ Constructor proxies are also not allowed to shadow normal definitions. That is, if an identifier resolves to a constructor proxy, and the same identifier is also defined or imported in some other scope, an ambiguity is reported. -### Motivation +## Motivation Leaving out `new` hides an implementation detail and makes code more pleasant to read. Even though it requires a new rule, it will likely increase the perceived regularity of the language, since case diff --git a/docs/_docs/reference/other-new-features/indentation.md b/docs/_docs/reference/other-new-features/indentation.md index 284eca93810a..e931030ab696 100644 --- a/docs/_docs/reference/other-new-features/indentation.md +++ b/docs/_docs/reference/other-new-features/indentation.md @@ -12,7 +12,7 @@ Scala 3 enforces some rules on indentation and allows some occurrences of braces These changes can be turned off with the compiler flag `-no-indent`. -### Indentation Rules +## Indentation Rules The compiler enforces two rules for well-indented programs, flagging violations as warnings. @@ -42,7 +42,7 @@ any restrictions on indentation within expressions, nor do they require that all The rules are generally helpful in pinpointing the root cause of errors related to missing opening or closing braces. These errors are often quite hard to diagnose, in particular in large programs. -### Optional Braces +## Optional Braces The compiler will insert `` or `` tokens at certain line breaks. Grammatically, pairs of `` and `` tokens have the same effect as pairs of braces `{` and `}`. @@ -130,7 +130,7 @@ else d ``` is parsed as `if x then a + b + c else d`. -### Optional Braces Around Template Bodies +## Optional Braces Around Template Bodies The Scala grammar uses the term _template body_ for the definitions of a class, trait, or object that are normally enclosed in braces. The braces around a template body can also be omitted by means of the following rule. @@ -186,11 +186,11 @@ Refinement ::= :<<< [RefineDcl] {semi [RefineDcl]} >>> Packaging ::= ‘package’ QualId :<<< TopStats >>> ``` -### Spaces vs Tabs +## Spaces vs Tabs Indentation prefixes can consist of spaces and/or tabs. Indentation widths are the indentation prefixes themselves, ordered by the string prefix relation. So, so for instance "2 tabs, followed by 4 spaces" is strictly less than "2 tabs, followed by 5 spaces", but "2 tabs, followed by 4 spaces" is incomparable to "6 tabs" or to "4 spaces, followed by 2 tabs". It is an error if the indentation width of some line is incomparable with the indentation width of the region that's current at that point. To avoid such errors, it is a good idea not to mix spaces and tabs in the same source file. -### Indentation and Braces +## Indentation and Braces Indentation can be mixed freely with braces `{...}`, as well as brackets `[...]` and parentheses `(...)`. For interpreting indentation inside such regions, the following rules apply. @@ -224,7 +224,7 @@ statement starting with `val`). (i.e. the indentation width of `y + 1`). - Finally, the indentation width of the last region in parentheses starting with `(x` is 6 (i.e. the indentation width of the indented region following the `=>`. -### Special Treatment of Case Clauses +## Special Treatment of Case Clauses The indentation rules for `match` expressions and `catch` clauses are refined as follows: @@ -247,7 +247,7 @@ case 5 => print("V") println(".") ``` -### Using Indentation to Signal Statement Continuation +## Using Indentation to Signal Statement Continuation Indentation is used in some situations to decide whether to insert a virtual semicolon between two consecutive lines or to treat them as one statement. Virtual semicolon insertion is @@ -279,7 +279,7 @@ The Scala-2 behavior is retained under source `-no-indent` or `-source 3.0-migra -### The End Marker +## The End Marker Indentation-based syntax has many advantages over other conventions. But one possible problem is that it makes it hard to discern when a large indentation region ends, since there is no specific token that delineates the end. Braces are not much better since a brace by itself also contains no information about what region is closed. @@ -364,7 +364,7 @@ package p1.p2: end p2 ``` -#### When to Use End Markers +### When to Use End Markers It is recommended that `end` markers are used for code where the extent of an indentation region is not immediately apparent "at a glance". People will have different preferences what this means, but one can nevertheless give some guidelines that stem from experience. An end marker makes sense if @@ -374,7 +374,7 @@ It is recommended that `end` markers are used for code where the extent of an in If none of these criteria apply, it's often better to not use an end marker since the code will be just as clear and more concise. If there are several ending regions that satisfy one of the criteria above, we usually need an end marker only for the outermost closed region. So cascades of end markers as in the example above are usually better avoided. -#### Syntax +### Syntax ``` EndMarker ::= ‘end’ EndMarkerTag -- when followed by EOL @@ -385,7 +385,7 @@ TemplateStat ::= ... | EndMarker TopStat ::= ... | EndMarker ``` -### Example +## Example Here is a (somewhat meta-circular) example of code using indentation. It provides a concrete representation of indentation widths as defined above together with efficient operations for constructing and comparing indentation widths. @@ -438,7 +438,7 @@ object IndentWidth: end IndentWidth ``` -### Settings and Rewrites +## Settings and Rewrites Significant indentation is enabled by default. It can be turned off by giving any of the options `-no-indent`, `-old-syntax` and `-source 3.0-migration`. If indentation is turned off, it is nevertheless checked that indentation conforms to the logical program structure as defined by braces. If that is not the case, the compiler issues a warning. @@ -448,7 +448,7 @@ indented regions where possible. When invoked with options `-rewrite -no-indent` The `-indent` option only works on [new-style syntax](./control-syntax.md). So to go from old-style syntax to new-style indented code one has to invoke the compiler twice, first with options `-rewrite -new-syntax`, then again with options `-rewrite -indent`. To go in the opposite direction, from indented code to old-style syntax, it's `-rewrite -no-indent`, followed by `-rewrite -old-syntax`. -### Variant: Indentation Marker `:` for Arguments +## Variant: Indentation Marker `:` for Arguments Generally, the possible indentation regions coincide with those regions where braces `{...}` are also legal, no matter whether the braces enclose an expression or a set of definitions. There is one exception, though: Arguments to functions can be enclosed in braces but they cannot be simply indented instead. Making indentation always significant for function arguments would be too restrictive and fragile. diff --git a/docs/_docs/reference/other-new-features/matchable.md b/docs/_docs/reference/other-new-features/matchable.md index bd0daba189ee..234fdf03220c 100644 --- a/docs/_docs/reference/other-new-features/matchable.md +++ b/docs/_docs/reference/other-new-features/matchable.md @@ -6,7 +6,7 @@ nightlyOf: https://docs.scala-lang.org/scala3/reference/other-new-features/match A new trait [`Matchable`](https://scala-lang.org/api/3.x/scala/Matchable.html) controls the ability to pattern match. -### The Problem +## The Problem The Scala 3 standard library has a type [`IArray`](https://scala-lang.org/api/3.x/scala.html#IArray-0) for immutable arrays that is defined like this: @@ -47,7 +47,7 @@ f(imm) Finally, note that the problem is not linked to just [opaque types](opaques.md). No unbounded type parameter or abstract type should be decomposable with a pattern match. -### The Solution +## The Solution There is a new type [`scala.Matchable`](https://scala-lang.org/api/3.x/scala/Matchable.html) that controls pattern matching. When typing a pattern match of a constructor pattern `C(...)` or a type pattern `_: C` it is required that the selector type conforms @@ -95,7 +95,7 @@ class Object extends Any, Matchable [`Matchable`](https://scala-lang.org/api/3.x/scala/Matchable.html) is currently a marker trait without any methods. Over time we might migrate methods `getClass` and `isInstanceOf` to it, since these are closely related to pattern-matching. -### `Matchable` and Universal Equality +## `Matchable` and Universal Equality Methods that pattern-match on selectors of type `Any` will need a cast once the Matchable warning is turned on. The most common such method is the universal diff --git a/docs/_docs/reference/other-new-features/opaques.md b/docs/_docs/reference/other-new-features/opaques.md index b87d45485a93..d8c4d37bcb3b 100644 --- a/docs/_docs/reference/other-new-features/opaques.md +++ b/docs/_docs/reference/other-new-features/opaques.md @@ -59,7 +59,7 @@ l * 2 // error: found: Int(2), required: Logarithm l / l2 // error: `/` is not a member of Logarithm ``` -### Bounds For Opaque Type Aliases +## Bounds For Opaque Type Aliases Opaque type aliases can also come with bounds. Example: @@ -147,7 +147,7 @@ On the other hand, the call `roItem.rights.isOneOf(ReadWrite)` would give a type `Permissions` and `PermissionChoice` are different, unrelated types outside `Access`. -### Opaque Type Members on Classes +## Opaque Type Members on Classes While typically, opaque types are used together with objects to hide implementation details of a module, they can also be used with classes. For example, we can redefine the above example of Logarithms as a class. diff --git a/docs/_docs/reference/other-new-features/targetName.md b/docs/_docs/reference/other-new-features/targetName.md index a2b7d96a9f94..63c4cf1ec0df 100644 --- a/docs/_docs/reference/other-new-features/targetName.md +++ b/docs/_docs/reference/other-new-features/targetName.md @@ -23,7 +23,7 @@ VecOps.append(vec1, vec2) The [`@targetName`](https://scala-lang.org/api/3.x/scala/annotation/targetName.html) annotation has no bearing on Scala usages. Any application of that method in Scala has to use `++=`, not `append`. -### Details +## Details 1. `@targetName` is defined in package `scala.annotation`. It takes a single argument of type `String`. That string is called the _external name_ of the definition @@ -40,7 +40,7 @@ The [`@targetName`](https://scala-lang.org/api/3.x/scala/annotation/targetName.h 5. Definitions with names in backticks that are not legal host platform names should also have a [`@targetName`](https://scala-lang.org/api/3.x/scala/annotation/targetName.html) annotation. -### Relationship with Overriding +## Relationship with Overriding [`@targetName`](https://scala-lang.org/api/3.x/scala/annotation/targetName.html) annotations are significant for matching two method definitions to decide whether they conflict or override each other. Two method definitions match if they have the same name, signature, and erased name. Here, diff --git a/docs/_docs/reference/other-new-features/threadUnsafe-annotation.md b/docs/_docs/reference/other-new-features/threadUnsafe-annotation.md index 0068d0a6fe53..ae1af1e4b671 100644 --- a/docs/_docs/reference/other-new-features/threadUnsafe-annotation.md +++ b/docs/_docs/reference/other-new-features/threadUnsafe-annotation.md @@ -8,7 +8,7 @@ A new annotation [`@threadUnsafe`](https://scala-lang.org/api/3.x/scala/annotati a `lazy val`. When this annotation is used, the initialization of the [`lazy val`](../changed-features/lazy-vals-init.md) will use a faster mechanism which is not thread-safe. -### Example +## Example ```scala import scala.annotation.threadUnsafe diff --git a/docs/_docs/reference/other-new-features/trait-parameters.md b/docs/_docs/reference/other-new-features/trait-parameters.md index 1d13574bce03..c704e73ce9b8 100644 --- a/docs/_docs/reference/other-new-features/trait-parameters.md +++ b/docs/_docs/reference/other-new-features/trait-parameters.md @@ -53,7 +53,7 @@ The correct way to write `E` is to extend both `Greeting` and class E extends Greeting("Bob"), FormalGreeting ``` -### Traits With Context Parameters +## Traits With Context Parameters This "explicit extension required" rule is relaxed if the missing trait contains only [context parameters](../contextual/using-clauses.md). In that case the trait reference is diff --git a/docs/_docs/reference/syntax.md b/docs/_docs/reference/syntax.md index 2072da165966..e11629c8eaf9 100644 --- a/docs/_docs/reference/syntax.md +++ b/docs/_docs/reference/syntax.md @@ -31,7 +31,7 @@ hexDigit ::= ‘0’ | … | ‘9’ | ‘A’ | … | ‘F’ | ‘a’ | Informal descriptions are typeset as `“some comment”`. -### Lexical Syntax +## Lexical Syntax The lexical syntax of Scala is given by the following grammar in EBNF form.