From acdee2082a4c42a1bb4f2d12260ce408dd8d660b Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Tue, 19 Jan 2021 09:57:09 +0100 Subject: [PATCH 1/9] Allow `with` after class --- .../dotty/tools/dotc/parsing/Parsers.scala | 48 ++++++++++++++----- .../dotty/tools/dotc/parsing/Scanners.scala | 12 ++--- docs/docs/internals/syntax.md | 18 ++++--- .../changed-features/compiler-plugins.md | 6 +-- .../implicit-conversions-spec.md | 2 +- .../changed-features/main-functions.md | 2 +- .../changed-features/numeric-literals.md | 6 +-- .../changed-features/pattern-matching.md | 4 +- .../changed-features/structural-types.md | 8 ++-- .../reference/contextual/context-functions.md | 4 +- docs/docs/reference/contextual/conversions.md | 8 ++-- .../reference/contextual/extension-methods.md | 10 ++-- docs/docs/reference/contextual/givens.md | 4 +- .../contextual/multiversal-equality.md | 2 +- .../docs/reference/contextual/type-classes.md | 12 ++--- .../reference/dropped-features/auto-apply.md | 4 +- docs/docs/reference/enums/adts.md | 6 +-- docs/docs/reference/enums/enums.md | 2 +- .../reference/metaprogramming/erased-terms.md | 6 +-- docs/docs/reference/metaprogramming/inline.md | 10 ++-- .../metaprogramming/tasty-inspect.md | 4 +- .../dependent-function-types-spec.md | 6 +-- .../reference/new-types/intersection-types.md | 2 +- .../creator-applications.md | 2 +- .../other-new-features/explicit-nulls.md | 12 ++--- .../reference/other-new-features/export.md | 6 +-- .../other-new-features/indentation.md | 4 +- .../reference/other-new-features/matchable.md | 4 +- .../other-new-features/open-classes.md | 4 +- .../other-new-features/safe-initialization.md | 20 ++++---- .../other-new-features/targetName.md | 10 ++-- .../threadUnsafe-annotation.md | 2 +- .../other-new-features/trait-parameters.md | 2 +- .../docs/release-notes/syntax-changes-0.22.md | 2 +- .../test/BootstrappedStdLibTASYyTest.scala | 4 +- stdlib-bootstrapped/test/Main.scala | 2 +- .../string-interpolation-macro/Test.scala | 2 +- tests/disabled/pos/i8311.scala | 4 +- .../explicit-nulls/byname-nullables.scala | 14 +++--- .../explicit-nulls/byname-nullables1.scala | 2 +- .../fatal-warnings/enum-variance.scala | 4 +- .../fatal-warnings/i8781b.scala | 2 +- .../fatal-warnings/opaque-match.scala | 4 +- .../fatal-warnings/supertraits.scala | 2 +- tests/neg-custom-args/infix.scala | 4 +- .../BigFloat/BigFloatFromDigitsImpl_1.scala | 2 +- .../GenericNumLits/EvenFromDigitsImpl_1.scala | 2 +- tests/neg-macros/i9972b/Test_2.scala | 2 +- .../GenericNumLits/EvenFromDigitsImpl_1.scala | 2 +- tests/neg/abstract-givens.scala | 4 +- tests/neg/abstract-inline-val.scala | 2 +- tests/neg/ambiref.scala | 36 +++++++------- tests/neg/bad-unapplies.scala | 8 ++-- tests/neg/case-semi.scala | 2 +- tests/neg/creator-ambiguous.scala | 4 +- tests/neg/curried-dependent-ift.scala | 4 +- tests/neg/endmarkers.scala | 12 ++--- tests/neg/endmarkers1.scala | 2 +- tests/neg/enum-values.scala | 12 ++--- tests/neg/enums.scala | 4 +- tests/neg/enumvalues.scala | 4 +- tests/neg/eql.scala | 4 +- tests/neg/exports1.scala | 12 ++--- tests/neg/exports2.scala | 6 +-- tests/neg/extend-java-enum-nonstatic.scala | 10 ++-- .../neg/gadt-approximation-interaction.scala | 24 +++++----- tests/neg/given-eta.scala | 2 +- tests/neg/i10546.scala | 2 +- tests/neg/i10817.scala | 2 +- tests/neg/i10857.scala | 10 ++-- tests/neg/i10870.scala | 2 +- tests/neg/i10901.scala | 4 +- tests/neg/i11066.scala | 6 +-- tests/neg/i11081.scala | 4 +- tests/neg/i1501.scala | 2 +- tests/neg/i3253.scala | 2 +- tests/neg/i6183.scala | 2 +- tests/neg/i6205.scala | 2 +- tests/neg/i6779.scala | 2 +- tests/neg/i7359-g.scala | 2 +- tests/neg/i7359.scala | 2 +- tests/neg/i7526.scala | 4 +- tests/neg/i7709.scala | 18 +++---- tests/neg/i7980.scala | 2 +- tests/neg/i8050.scala | 2 +- tests/neg/i8069.scala | 4 +- tests/neg/i8333.scala | 8 ++-- tests/neg/i8407.scala | 2 +- tests/neg/i8623.scala | 4 +- tests/neg/i8731.scala | 2 +- tests/neg/i9014.scala | 2 +- tests/neg/i9051.scala | 6 +-- tests/neg/i9437.scala | 2 +- tests/neg/i9562.scala | 4 +- tests/neg/i9790.scala | 2 +- tests/neg/i9928.scala | 6 +-- tests/neg/import-given.scala | 2 +- tests/neg/inline-abstract.scala | 4 +- tests/neg/missing-implicit1.scala | 2 +- tests/neg/missing-implicit2.scala | 2 +- tests/neg/missing-implicit5.scala | 2 +- tests/neg/name-hints.scala | 4 +- tests/neg/namedTypeParams.scala | 2 +- tests/neg/null-anyval.scala | 4 +- tests/neg/override-erasure-clash.scala | 2 +- tests/neg/override-inner-class.scala | 4 +- tests/neg/source-import.scala | 2 +- tests/neg/spaces-vs-tabs.scala | 4 +- tests/neg/targetName-override-2.scala | 2 +- tests/neg/transparent-inline.scala | 8 ++-- tests/new/test.scala | 5 +- tests/patmat/i10085.scala | 4 +- tests/patmat/i8922.scala | 4 +- tests/patmat/i8922c.scala | 4 +- tests/pending/pos/cps-async-failure.scala | 6 +-- tests/pending/pos/inlinetuple.scala | 2 +- tests/pos-custom-args/erased/i10848b.scala | 2 +- .../semanticdb/inline-unapply/Macro_1.scala | 2 +- tests/pos-macros/i10151/Macro_1.scala | 8 ++-- tests/pos-macros/i10211/Macro_1.scala | 10 ++-- tests/pos-macros/i10771/MacroA_1.scala | 2 +- tests/pos-macros/i10771/MacroB_1.scala | 2 +- tests/pos-macros/i10771/Test_2.scala | 2 +- tests/pos-macros/i10910/Macro_1.scala | 6 +-- tests/pos-macros/i8325/Macro_1.scala | 2 +- tests/pos-macros/i8325b/Macro_1.scala | 2 +- tests/pos-macros/i9812.scala | 2 +- tests/pos-macros/i9894/Macro_1.scala | 8 ++-- tests/pos-macros/nil-liftable.scala | 2 +- tests/pos-macros/quote-aliases.scala | 2 +- tests/pos-special/fatal-warnings/i10259.scala | 2 +- tests/pos-special/fatal-warnings/i9260.scala | 6 +-- .../fatal-warnings/patmat-exhaustive.scala | 2 +- .../fatal-warnings/type-test-matchable.scala | 4 +- tests/pos-special/i7296.scala | 2 +- tests/pos-special/indent-colons.scala | 14 +++--- tests/pos-special/notNull.scala | 2 +- .../sourcepath/outer/nested/indent1.scala | 4 +- tests/pos/abstract-inline-val.scala | 6 +-- tests/pos/consume.scala | 10 ++-- tests/pos/end-nested.scala | 2 +- tests/pos/endmarkers.scala | 10 ++-- tests/pos/enum-companion-first.scala | 4 +- tests/pos/enum-variance.scala | 4 +- tests/pos/enum-widen.scala | 6 +-- tests/pos/extmethods.scala | 4 +- tests/pos/i10080.scala | 2 +- tests/pos/i10082.scala | 2 +- tests/pos/i10253.scala | 8 ++-- tests/pos/i10295.scala | 4 +- tests/pos/i10311.scala | 2 +- tests/pos/i10495.scala | 4 +- tests/pos/i10634/BasicSupport.scala | 2 +- tests/pos/i10634/Context.scala | 4 +- tests/pos/i10951.scala | 2 +- tests/pos/i11081.scala | 4 +- tests/pos/i4561.scala | 4 +- tests/pos/i6375.scala | 2 +- tests/pos/i6734.scala | 2 +- tests/pos/i6900.scala | 6 +-- tests/pos/i6938.scala | 2 +- tests/pos/i7217.scala | 2 +- tests/pos/i7359.scala | 46 +++++++++--------- tests/pos/i7375.scala | 6 +-- tests/pos/i7413.scala | 8 ++-- tests/pos/i7428.scala | 4 +- tests/pos/i7648.scala | 2 +- tests/pos/i7700.scala | 6 +-- tests/pos/i7757.scala | 2 +- tests/pos/i7793.scala | 2 +- tests/pos/i7807.scala | 2 +- tests/pos/i8181.scala | 2 +- tests/pos/i8182.scala | 2 +- tests/pos/i8319.scala | 2 +- tests/pos/i8397.scala | 4 +- tests/pos/i8530.scala | 12 ++--- tests/pos/i8623.scala | 4 +- tests/pos/i8750.scala | 2 +- tests/pos/i8801.scala | 2 +- tests/pos/i8843.scala | 2 +- tests/pos/i8845.scala | 2 +- tests/pos/i8874.scala | 2 +- tests/pos/i8892.scala | 4 +- tests/pos/i8920/Qu_1.scala | 4 +- tests/pos/i8927.scala | 12 ++--- tests/pos/i8968.scala | 4 +- tests/pos/i8972.scala | 4 +- tests/pos/i8997.scala | 2 +- tests/pos/i9052/A.scala | 2 +- tests/pos/i9069/Wrapper.scala | 2 +- tests/pos/i9103.scala | 2 +- tests/pos/i9213.scala | 2 +- tests/pos/i9307.scala | 2 +- tests/pos/i9342b.scala | 2 +- tests/pos/i9342c.scala | 2 +- tests/pos/i9352.scala | 2 +- tests/pos/i9457.scala | 2 +- tests/pos/i9464.scala | 2 +- tests/pos/i9530.scala | 4 +- tests/pos/i9562.scala | 4 +- tests/pos/i9844.scala | 10 ++-- tests/pos/i9967.scala | 2 +- tests/pos/i9994.scala | 4 +- tests/pos/indent.scala | 12 ++--- tests/pos/indent2.scala | 4 +- tests/pos/indent4.scala | 2 +- tests/pos/inline-val-constValue-1.scala | 2 +- tests/pos/inline-val-constValue-2.scala | 2 +- .../pos/main-method-scheme-class-based.scala | 12 ++--- tests/pos/main-method-scheme.scala | 8 ++-- tests/pos/matches.scala | 2 +- tests/pos/matrixOps.scala | 2 +- tests/pos/opaques-queue.scala | 6 +-- tests/pos/packagings.scala | 4 +- tests/pos/postconditions.scala | 4 +- tests/pos/reference/adts.scala | 16 +++---- tests/pos/reference/auto-param-tupling.scala | 2 +- tests/pos/reference/compile-time.scala | 2 +- tests/pos/reference/delegate-match.scala | 2 +- tests/pos/reference/delegates.scala | 48 +++++++++---------- tests/pos/reference/extension-methods.scala | 18 +++---- .../pos/reference/structural-closeable.scala | 4 +- tests/pos/single-case.scala | 2 +- tests/pos/targetName-infer-result.scala | 14 +++--- tests/pos/targetName-override.scala | 4 +- tests/pos/targetName-refine.scala | 4 +- tests/pos/tasty-tags-obscure.scala | 8 ++-- tests/pos/typeclass-encoding3.scala | 2 +- tests/pos/widen-union.scala | 6 +-- .../tasty-inspector/i10359.scala | 2 +- .../tasty-inspector/i8163.scala | 2 +- .../tasty-inspector/i8460.scala | 2 +- .../tasty-inspector/i9970.scala | 2 +- .../BigFloat/BigFloatFromDigitsImpl_1.scala | 2 +- .../run-macros/enum-nat-macro/Macros_2.scala | 2 +- tests/run-macros/enum-nat-macro/Nat_1.scala | 2 +- tests/run-macros/i10464/Person_1.scala | 2 +- tests/run-macros/i7716/Macro_1.scala | 6 +-- tests/run-macros/i8530/Macro_1.scala | 2 +- tests/run-macros/i9812b/Macro_1.scala | 6 +-- tests/run-macros/paramSymss/Test_2.scala | 2 +- .../refined-selectable-macro/Macro_1.scala | 2 +- .../tasty-overload-secondargs/Macro_1.scala | 4 +- .../tasty-overload-secondargs/Test_2.scala | 2 +- .../run-macros/tasty-tree-map/quoted_1.scala | 4 +- tests/run-staging/abstract-int-quote.scala | 2 +- tests/run-staging/i7897.scala | 2 +- tests/run-staging/i8178.scala | 2 +- tests/run-staging/shonan-hmm-simple.scala | 34 ++++++------- tests/run-staging/shonan-hmm/PV.scala | 2 +- tests/run-with-compiler/intmaptest.scala | 10 ++-- tests/run-with-compiler/maptest.scala | 10 ++-- tests/run-with-compiler/settest.scala | 10 ++-- tests/run/ConfManagement.scala | 4 +- tests/run/LazyLists.scala | 6 +-- tests/run/Pouring.scala | 6 +-- tests/run/Signals.scala | 8 ++-- tests/run/Signals1.scala | 14 +++--- tests/run/Typeable.scala | 6 +-- tests/run/abstract-givens.scala | 4 +- tests/run/context-functions.scala | 8 ++-- tests/run/decorators/DocComment.scala | 2 +- tests/run/decorators/EntryPoint.scala | 14 +++--- tests/run/decorators/Test.scala | 2 +- tests/run/decorators/main.scala | 6 +-- tests/run/decorators/sample-adapters.scala | 12 ++--- tests/run/decorators/sample-program.scala | 6 +-- tests/run/defunctionalized.scala | 2 +- tests/run/enum-custom-toString.scala | 20 ++++---- tests/run/enum-nat.scala | 4 +- tests/run/enum-ordinal-java/Lib.scala | 4 +- tests/run/enum-ordinal-java/Test.scala | 4 +- tests/run/enum-values-order.scala | 4 +- tests/run/enum-values.scala | 14 +++--- tests/run/enums-precise.scala | 4 +- tests/run/enums-serialization-compat.scala | 10 ++-- tests/run/erased-inline-vals.scala | 8 ++-- tests/run/exports.scala | 4 +- tests/run/extension-override.scala | 4 +- tests/run/fragables-extension.scala | 2 +- tests/run/given-eta.scala | 2 +- tests/run/given-var.scala | 2 +- tests/run/i10082.scala | 2 +- tests/run/i10857.scala | 4 +- tests/run/i10884/Test_2.scala | 2 +- tests/run/i10905.scala | 2 +- tests/run/i7359.scala | 16 +++---- tests/run/i7788.scala | 2 +- tests/run/i8396.scala | 4 +- tests/run/i8530-b.scala | 2 +- tests/run/i8530.scala | 10 ++-- tests/run/i8931.scala | 12 ++--- tests/run/i9011.scala | 2 +- tests/run/i9068.scala | 2 +- tests/run/i9155.scala | 4 +- tests/run/i9530.scala | 2 +- tests/run/i9928.scala | 14 +++--- tests/run/ift-return.scala | 4 +- tests/run/inline-override.scala | 4 +- tests/run/instances.scala | 10 ++-- tests/run/lazy-impl.scala | 2 +- tests/run/option-extract.scala | 2 +- tests/run/outer-accessors.scala | 8 ++-- tests/run/quoted-sematics-1.scala | 6 +-- tests/run/selectable-new.scala | 4 +- tests/run/singleton-ops-flags.scala | 4 +- tests/run/structural-contextual.scala | 4 +- tests/run/targetName.scala | 10 ++-- tests/run/typable.scala | 2 +- tests/run/unambiref.scala | 4 +- tests/semanticdb/expect/Enums.expect.scala | 24 +++++----- tests/semanticdb/expect/Enums.scala | 24 +++++----- tests/semanticdb/expect/Givens.expect.scala | 4 +- tests/semanticdb/expect/Givens.scala | 4 +- .../expect/inlineconsume.expect.scala | 2 +- tests/semanticdb/expect/inlineconsume.scala | 2 +- .../semanticdb/expect/inlinedefs.expect.scala | 2 +- tests/semanticdb/expect/inlinedefs.scala | 2 +- .../testsuite/compiler/EnumTestScala3.scala | 14 +++--- 319 files changed, 874 insertions(+), 855 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala index b1511210323d..af607397d036 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala @@ -1288,7 +1288,7 @@ object Parsers { else in.nextToken() if in.token != INDENT && in.token != LBRACE then - syntaxErrorOrIncomplete(i"indented definitions expected, ${in}") + syntaxErrorOrIncomplete(i"indented definitions expected, ${in} found") else newLineOptWhenFollowedBy(LBRACE) @@ -2315,7 +2315,7 @@ object Parsers { possibleTemplateStart() val parents = if in.isNestedStart then Nil - else constrApps(commaOK = false) + else constrApp() :: withConstrApps() colonAtEOLOpt() possibleTemplateStart(isNew = true) parents match { @@ -3494,7 +3494,7 @@ object Parsers { val parents = if (in.token == EXTENDS) { in.nextToken() - constrApps(commaOK = true) + constrApps() } else Nil Template(constr, parents, Nil, EmptyValDef, Nil) @@ -3626,24 +3626,37 @@ object Parsers { // Using Ident(tpnme.ERROR) to avoid causing cascade errors on non-user-written code if in.token == LPAREN then parArgumentExprss(wrapNew(t)) else t - /** ConstrApps ::= ConstrApp {(‘,’ | ‘with’) ConstrApp} + /** ConstrApps ::= ConstrApp ({‘,’ ConstrApp} | {‘with’ ConstrApp}) */ - def constrApps(commaOK: Boolean): List[Tree] = + def constrApps(): List[Tree] = val t = constrApp() - val ts = - if in.token == WITH || commaOK && in.token == COMMA then - in.nextToken() - constrApps(commaOK) - else Nil + val ts = if in.token == COMMA then commaConstrApps() else withConstrApps() t :: ts + /** `{`,` ConstrApp} */ + def commaConstrApps(): List[Tree] = + if in.token == COMMA then + in.nextToken() + constrApp() :: commaConstrApps() + else Nil /** `{`with` ConstrApp} but no EOL allowed after `with`. */ def withConstrApps(): List[Tree] = def isTemplateStart = val la = in.lookahead - la.isAfterLineEnd || la.token == LBRACE + la.token == LBRACE + || la.isAfterLineEnd + && { + if migrateTo3 then + warning( + em"""In Scala 3, `with` at the end of a line will start definitions, + |so it cannot be used in front of a parent constructor anymore. + |Place the `with` at the beginning of the next line instead.""") + false + else + true + } if in.token == WITH && !isTemplateStart then in.nextToken() constrApp() :: withConstrApps() @@ -3662,7 +3675,7 @@ object Parsers { in.sourcePos()) Nil } - else constrApps(commaOK = true) + else constrApps() } else Nil newLinesOptWhenFollowedBy(nme.derives) @@ -3806,7 +3819,16 @@ object Parsers { } else { stats += first - acceptStatSepUnlessAtEnd(stats) + if in.token == WITH then + syntaxError( + i"""end of statement expected but ${showToken(WITH)} found + | + |Maybe you meant to write a mixin in an extends clause? + |Note that this requires the `with` to come first now. + |I.e. + | + | with $first""") + else acceptStatSepUnlessAtEnd(stats) } } var exitOnError = false diff --git a/compiler/src/dotty/tools/dotc/parsing/Scanners.scala b/compiler/src/dotty/tools/dotc/parsing/Scanners.scala index 2c9c0cabf1e9..94d4225f165a 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Scanners.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Scanners.scala @@ -1338,7 +1338,7 @@ object Scanners { * InBraces a pair of braces { ... } * Indented a pair of ... tokens */ - abstract class Region: + abstract class Region(val code: String): /** The region enclosing this one, or `null` for the outermost region */ def outer: Region | Null @@ -1367,17 +1367,17 @@ object Scanners { knownWidth = enclosing.knownWidth end Region - case class InString(multiLine: Boolean, outer: Region) extends Region - case class InParens(prefix: Token, outer: Region) extends Region - case class InBraces(outer: Region) extends Region - case class InCase(outer: Region) extends Region + case class InString(multiLine: Boolean, outer: Region) extends Region("IS") + case class InParens(prefix: Token, outer: Region) extends Region("IP") + case class InBraces(outer: Region) extends Region("IB") + case class InCase(outer: Region) extends Region("IC") /** A class describing an indentation region. * @param width The principal indendation width * @param others Other indendation widths > width of lines in the same region * @param prefix The token before the initial of the region */ - case class Indented(width: IndentWidth, others: Set[IndentWidth], prefix: Token, outer: Region | Null) extends Region: + case class Indented(width: IndentWidth, others: Set[IndentWidth], prefix: Token, outer: Region | Null) extends Region("II"): knownWidth = width def topLevelRegion(width: IndentWidth) = Indented(width, Set(), EMPTY, null) diff --git a/docs/docs/internals/syntax.md b/docs/docs/internals/syntax.md index 56648a81d4c2..59274eb85ab9 100644 --- a/docs/docs/internals/syntax.md +++ b/docs/docs/internals/syntax.md @@ -83,7 +83,6 @@ comment ::= ‘/*’ “any sequence of characters; nested comments ar nl ::= “new line character” semi ::= ‘;’ | nl {nl} -colonEol ::= ": at end of line that can start a template body" ``` ## Keywords @@ -218,9 +217,8 @@ SimpleExpr ::= SimpleRef | ‘$’ ‘{’ Block ‘}’ | Quoted | quoteId -- only inside splices - | ‘new’ ConstrApp {‘with’ ConstrApp} New(constr | templ) - [[colonEol] TemplateBody - | ‘new’ [colonEol] TemplateBody + | ‘new’ ConstrApp {‘with’ ConstrApp} [TemplateBody] New(constr | templ) + | ‘new’ TemplateBody | ‘(’ ExprsInParens ‘)’ Parens(exprs) | SimpleExpr ‘.’ id Select(expr, id) | SimpleExpr ‘.’ MatchClause @@ -386,15 +384,15 @@ ClassDef ::= id ClassConstr [Template] ClassConstr ::= [ClsTypeParamClause] [ConstrMods] ClsParamClauses with DefDef(_, , Nil, vparamss, EmptyTree, EmptyTree) as first stat ConstrMods ::= {Annotation} [AccessModifier] ObjectDef ::= id [Template] ModuleDef(mods, name, template) // no constructor -EnumDef ::= id ClassConstr InheritClauses [colonEol] EnumBody +EnumDef ::= id ClassConstr InheritClauses EnumBody GivenDef ::= [GivenSig] (Type [‘=’ Expr] | StructuralInstance) GivenSig ::= [id] [DefTypeParamClause] {UsingParamClause} ‘:’ -- one of `id`, `DefParamClause`, `UsingParamClause` must be present -StructuralInstance ::= ConstrApp {‘with’ ConstrApp} ‘with’ TemplateBody +StructuralInstance ::= ConstrApp {‘with’ ConstrApp} TemplateBody Extension ::= ‘extension’ [DefTypeParamClause] ‘(’ DefParam ‘)’ {UsingParamClause}] ExtMethods ExtMethods ::= ExtMethod | [nl] ‘{’ ExtMethod {semi ExtMethod ‘}’ ExtMethod ::= {Annotation [nl]} {Modifier} ‘def’ DefDef -Template ::= InheritClauses [colonEol] [TemplateBody] Template(constr, parents, self, stats) +Template ::= InheritClauses [TemplateBody] Template(constr, parents, self, stats) InheritClauses ::= [‘extends’ ConstrApps] [‘derives’ QualId {‘,’ QualId}] ConstrApps ::= ConstrApp ({‘,’ ConstrApp} | {‘with’ ConstrApp}) ConstrApp ::= SimpleType1 {Annotation} {ParArgumentExprs} Apply(tp, args) @@ -402,7 +400,7 @@ ConstrExpr ::= SelfInvocation | ‘{’ SelfInvocation {semi BlockStat} ‘}’ SelfInvocation ::= ‘this’ ArgumentExprs {ArgumentExprs} -TemplateBody ::= [nl] ‘{’ [SelfType] TemplateStat {semi TemplateStat} ‘}’ +TemplateBody ::= [nl | ‘with’] ‘{’ [SelfType] TemplateStat {semi TemplateStat} ‘}’ TemplateStat ::= Import | Export | {Annotation [nl]} {Modifier} Def @@ -414,7 +412,7 @@ TemplateStat ::= Import SelfType ::= id [‘:’ InfixType] ‘=>’ ValDef(_, name, tpt, _) | ‘this’ ‘:’ InfixType ‘=>’ -EnumBody ::= [nl] ‘{’ [SelfType] EnumStat {semi EnumStat} ‘}’ +EnumBody ::= [nl | ‘with’] ‘{’ [SelfType] EnumStat {semi EnumStat} ‘}’ EnumStat ::= TemplateStat | {Annotation [nl]} {Modifier} EnumCase EnumCase ::= ‘case’ (id ClassConstr [‘extends’ ConstrApps]] | ids) @@ -428,7 +426,7 @@ TopStat ::= Import | PackageObject | EndMarker | -Packaging ::= ‘package’ QualId [nl | colonEol] ‘{’ TopStatSeq ‘}’ Package(qid, stats) +Packaging ::= ‘package’ QualId [nl| ‘with’] ‘{’ TopStatSeq ‘}’ Package(qid, stats) PackageObject ::= ‘package’ ‘object’ ObjectDef object with package in mods. CompilationUnit ::= {‘package’ QualId semi} TopStatSeq Package(qid, stats) diff --git a/docs/docs/reference/changed-features/compiler-plugins.md b/docs/docs/reference/changed-features/compiler-plugins.md index 19f39ea759c4..7009659e0f1a 100644 --- a/docs/docs/reference/changed-features/compiler-plugins.md +++ b/docs/docs/reference/changed-features/compiler-plugins.md @@ -62,14 +62,14 @@ import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.plugins.{PluginPhase, StandardPlugin} import dotty.tools.dotc.transform.{Pickler, Staging} -class DivideZero extends StandardPlugin: +class DivideZero extends StandardPlugin with val name: String = "divideZero" override val description: String = "divide zero check" def init(options: List[String]): List[PluginPhase] = (new DivideZeroPhase) :: Nil -class DivideZeroPhase extends PluginPhase: +class DivideZeroPhase extends PluginPhase with import tpd._ val phaseName = "divideZero" @@ -108,7 +108,7 @@ import dotty.tools.dotc.core.Contexts.Context import dotty.tools.dotc.core.Phases.Phase import dotty.tools.dotc.plugins.ResearchPlugin -class DummyResearchPlugin extends ResearchPlugin: +class DummyResearchPlugin extends ResearchPlugin with val name: String = "dummy" override val description: String = "dummy research plugin" diff --git a/docs/docs/reference/changed-features/implicit-conversions-spec.md b/docs/docs/reference/changed-features/implicit-conversions-spec.md index 33557ecef72c..127bad7ef2cc 100644 --- a/docs/docs/reference/changed-features/implicit-conversions-spec.md +++ b/docs/docs/reference/changed-features/implicit-conversions-spec.md @@ -16,7 +16,7 @@ The standard library defines an abstract class `Conversion`: ```scala package scala @java.lang.FunctionalInterface -abstract class Conversion[-T, +U] extends Function1[T, U]: +abstract class Conversion[-T, +U] extends Function1[T, U] with def apply(x: T): U ``` diff --git a/docs/docs/reference/changed-features/main-functions.md b/docs/docs/reference/changed-features/main-functions.md index b6897762797b..29aac8f5f522 100644 --- a/docs/docs/reference/changed-features/main-functions.md +++ b/docs/docs/reference/changed-features/main-functions.md @@ -61,7 +61,7 @@ The Scala compiler generates a program from a `@main` method `f` as follows: For instance, the `happyBirthDay` method above would generate additional code equivalent to the following class: ```scala -final class happyBirthday: +final class happyBirthday with import scala.util.{CommandLineParser => CLP} def main(args: Array[String]): Unit = try diff --git a/docs/docs/reference/changed-features/numeric-literals.md b/docs/docs/reference/changed-features/numeric-literals.md index 3ac84541592f..397d4e57c7c2 100644 --- a/docs/docs/reference/changed-features/numeric-literals.md +++ b/docs/docs/reference/changed-features/numeric-literals.md @@ -130,7 +130,7 @@ class MalformedNumber(msg: String = "malformed number literal") extends FromDigi As a fully worked out example, here is an implementation of a new numeric class, `BigFloat`, that accepts numeric literals. `BigFloat` is defined in terms of a `BigInt` mantissa and an `Int` exponent: ```scala -case class BigFloat(mantissa: BigInt, exponent: Int): +case class BigFloat(mantissa: BigInt, exponent: Int) with override def toString = s"${mantissa}e${exponent}" ``` @@ -145,7 +145,7 @@ The companion object of `BigFloat` defines an `apply` constructor method to cons from a `digits` string. Here is a possible implementation: ```scala -object BigFloat: +object BigFloat with import scala.util.FromDigits def apply(digits: String): BigFloat = @@ -206,7 +206,7 @@ To do this, replace the `FromDigits` instance in the `BigFloat` object by the fo object BigFloat: ... - class FromDigits extends FromDigits.Floating[BigFloat]: + class FromDigits extends FromDigits.Floating[BigFloat] with def fromDigits(digits: String) = apply(digits) given FromDigits with diff --git a/docs/docs/reference/changed-features/pattern-matching.md b/docs/docs/reference/changed-features/pattern-matching.md index b61ce8fa886e..1f2ea964f95e 100644 --- a/docs/docs/reference/changed-features/pattern-matching.md +++ b/docs/docs/reference/changed-features/pattern-matching.md @@ -121,7 +121,7 @@ For example: ```scala -class FirstChars(s: String) extends Product: +class FirstChars(s: String) extends Product with def _1 = s.charAt(0) def _2 = s.charAt(1) @@ -147,7 +147,7 @@ object FirstChars: ```scala -class Nat(val x: Int): +class Nat(val x: Int) with def get: Int = x def isEmpty = x < 0 diff --git a/docs/docs/reference/changed-features/structural-types.md b/docs/docs/reference/changed-features/structural-types.md index 9a056fb2beee..059f9b353e5a 100644 --- a/docs/docs/reference/changed-features/structural-types.md +++ b/docs/docs/reference/changed-features/structural-types.md @@ -34,13 +34,13 @@ configure how fields and methods should be resolved. Here's an example of a structural type `Person`: ```scala - class Record(elems: (String, Any)*) extends Selectable: + class Record(elems: (String, Any)*) extends Selectable with private val fields = elems.toMap def selectDynamic(name: String): Any = fields(name) type Person = Record { val name: String; val age: Int } ``` - + The type `Person` adds a _refinement_ to its parent type `Record` that defines the two fields `name` and `age`. We say the refinement is _structural_ since `name` and `age` are not defined in the parent type. But they exist nevertheless as members of class `Person`. For instance, the following program would print "Emma is 42 years old.": @@ -82,10 +82,10 @@ Structural types can also be accessed using [Java reflection](https://www.oracle ```scala type Closeable = { def close(): Unit } - class FileInputStream: + class FileInputStream with def close(): Unit - class Channel: + class Channel with def close(): Unit ``` diff --git a/docs/docs/reference/contextual/context-functions.md b/docs/docs/reference/contextual/context-functions.md index 46b7ffa539ae..c63e9015cbdf 100644 --- a/docs/docs/reference/contextual/context-functions.md +++ b/docs/docs/reference/contextual/context-functions.md @@ -67,12 +67,12 @@ the aim is to construct tables like this: The idea is to define classes for `Table` and `Row` that allow the addition of elements via `add`: ```scala - class Table: + class Table with val rows = new ArrayBuffer[Row] def add(r: Row): Unit = rows += r override def toString = rows.mkString("Table(", ", ", ")") - class Row: + class Row with val cells = new ArrayBuffer[Cell] def add(c: Cell): Unit = cells += c override def toString = cells.mkString("Row(", ", ", ")") diff --git a/docs/docs/reference/contextual/conversions.md b/docs/docs/reference/contextual/conversions.md index 5dae928c9620..26476e1fc3c3 100644 --- a/docs/docs/reference/contextual/conversions.md +++ b/docs/docs/reference/contextual/conversions.md @@ -6,7 +6,7 @@ title: "Implicit Conversions" Implicit conversions are defined by given instances of the `scala.Conversion` class. This class is defined in package `scala` as follows: ```scala -abstract class Conversion[-T, +U] extends (T => U): +abstract class Conversion[-T, +U] extends (T => U) with def apply (x: T): U ``` For example, here is an implicit conversion from `String` to `Token`: @@ -43,15 +43,15 @@ conversion from `Int` to `java.lang.Integer` can be defined as follows: 2. The "magnet" pattern is sometimes used to express many variants of a method. Instead of defining overloaded versions of the method, one can also let the method take one or more arguments of specially defined "magnet" types, into which various argument types can be converted. Example: ```scala - object Completions: + object Completions with // The argument "magnet" type - enum CompletionArg: + enum CompletionArg with case Error(s: String) case Response(f: Future[HttpResponse]) case Status(code: Future[StatusCode]) - object CompletionArg: + object CompletionArg with // conversions defining the possible arguments to pass to `complete` // these always come with CompletionArg diff --git a/docs/docs/reference/contextual/extension-methods.md b/docs/docs/reference/contextual/extension-methods.md index a89658d14608..647fd95afc1e 100644 --- a/docs/docs/reference/contextual/extension-methods.md +++ b/docs/docs/reference/contextual/extension-methods.md @@ -174,7 +174,7 @@ There are four possible ways for an extension method to be applicable: Here is an example for the first rule: ```scala -trait IntOps: +trait IntOps with extension (i: Int) def isZero: Boolean = i == 0 extension (i: Int) def safeMod(x: Int): Option[Int] = @@ -182,13 +182,13 @@ trait IntOps: if x.isZero then None else Some(i % x) -object IntOpsEx extends IntOps: +object IntOpsEx extends IntOps with extension (i: Int) def safeDiv(x: Int): Option[Int] = // extension method brought into scope via inheritance from IntOps if x.isZero then None else Some(i / x) -trait SafeDiv: +trait SafeDiv with import IntOpsEx._ // brings safeDiv and safeMod into scope extension (i: Int) def divide(d: Int): Option[(Int, Int)] = @@ -209,9 +209,9 @@ given ops1: IntOps with {} // brings safeMod into scope By the third and fourth rule, an extension method is available if it is in the implicit scope of the receiver type or in a given instance in that scope. Example: ```scala -class List[T]: +class List[T] with ... -object List: +object List with ... extension [T](xs: List[List[T]]) def flatten: List[T] = xs.foldLeft(Nil: List[T])(_ ++ _) diff --git a/docs/docs/reference/contextual/givens.md b/docs/docs/reference/contextual/givens.md index 11b38ed31d43..4cb18a09a4f5 100644 --- a/docs/docs/reference/contextual/givens.md +++ b/docs/docs/reference/contextual/givens.md @@ -7,7 +7,7 @@ Given instances (or, simply, "givens") define "canonical" values of certain type that serve for synthesizing arguments to [context parameters](./using-clauses.md). Example: ```scala -trait Ord[T]: +trait Ord[T] with def compare(x: T, y: T): Int extension (x: T) def < (y: T) = compare(x, y) < 0 extension (x: T) def > (y: T) = compare(x, y) > 0 @@ -130,7 +130,7 @@ import scala.util.NotGiven trait Tagged[A] case class Foo[A](value: Boolean) -object Foo: +object Foo with given fooTagged[A](using Tagged[A]): Foo[A] = Foo(true) given fooNotTagged[A](using NotGiven[Tagged[A]]): Foo[A] = Foo(false) diff --git a/docs/docs/reference/contextual/multiversal-equality.md b/docs/docs/reference/contextual/multiversal-equality.md index 35a232903576..c3cc82bd688f 100644 --- a/docs/docs/reference/contextual/multiversal-equality.md +++ b/docs/docs/reference/contextual/multiversal-equality.md @@ -172,7 +172,7 @@ we are dealing with a refinement of pre-existing, universal equality. It is best Say you want to come up with a safe version of the `contains` method on `List[T]`. The original definition of `contains` in the standard library was: ```scala -class List[+T]: +class List[+T] with ... def contains(x: Any): Boolean ``` diff --git a/docs/docs/reference/contextual/type-classes.md b/docs/docs/reference/contextual/type-classes.md index 5911eff48eed..742e4022481a 100644 --- a/docs/docs/reference/contextual/type-classes.md +++ b/docs/docs/reference/contextual/type-classes.md @@ -16,10 +16,10 @@ Here are some examples of common type classes: Here's the `Monoid` type class definition: ```scala -trait SemiGroup[T]: +trait SemiGroup[T] with extension (x: T) def combine (y: T): T -trait Monoid[T] extends SemiGroup[T]: +trait Monoid[T] extends SemiGroup[T] with def unit: T ``` @@ -49,7 +49,7 @@ def combineAll[T: Monoid](xs: List[T]): T = To get rid of the `summon[...]` we can define a `Monoid` object as follows: ```scala -object Monoid: +object Monoid with def apply[T](using m: Monoid[T]) = m ``` @@ -68,7 +68,7 @@ Therefore we write it `F[_]`, hinting that the type `F` takes another type as ar The definition of a generic `Functor` would thus be written as: ```scala -trait Functor[F[_]]: +trait Functor[F[_]] with def map[A, B](x: F[A], f: A => B): F[B] ``` @@ -100,7 +100,7 @@ That's a first step, but in practice we probably would like the `map` function t As in the previous example of Monoids, [`extension` methods](extension-methods.md) help achieving that. Let's re-define the `Functor` type class with extension methods. ```scala -trait Functor[F[_]]: +trait Functor[F[_]] with extension [A](x: F[A]) def map[B](f: A => B): F[B] ``` @@ -138,7 +138,7 @@ That's where `Monad` comes in. A `Monad` for type `F[_]` is a `Functor[F]` with Here is the translation of this definition in Scala 3: ```scala -trait Monad[F[_]] extends Functor[F]: +trait Monad[F[_]] extends Functor[F] with /** The unit value for a monad */ def pure[A](x: A): F[A] diff --git a/docs/docs/reference/dropped-features/auto-apply.md b/docs/docs/reference/dropped-features/auto-apply.md index 9ff9aa648502..78d699e81596 100644 --- a/docs/docs/reference/dropped-features/auto-apply.md +++ b/docs/docs/reference/dropped-features/auto-apply.md @@ -73,10 +73,10 @@ by a nullary method or _vice versa_. Instead, both methods must agree exactly in their parameter lists. ```scala -class A: +class A with def next(): Int -class B extends A: +class B extends A with def next: Int // overriding error: incompatible type ``` diff --git a/docs/docs/reference/enums/adts.md b/docs/docs/reference/enums/adts.md index 6bfb188b349d..2cddf5d83fbb 100644 --- a/docs/docs/reference/enums/adts.md +++ b/docs/docs/reference/enums/adts.md @@ -8,7 +8,7 @@ types (ADTs) and their generalized version (GADTs). Here is an example how an `Option` type can be represented as an ADT: ```scala -enum Option[+T]: +enum Option[+T] with case Some(x: T) case None ``` @@ -23,7 +23,7 @@ The `extends` clauses that were omitted in the example above can also be given explicitly: ```scala -enum Option[+T]: +enum Option[+T] with case Some(x: T) extends Option[T] case None extends Option[Nothing] ``` @@ -59,7 +59,7 @@ As all other enums, ADTs can define methods. For instance, here is `Option` agai `isDefined` method and an `Option(...)` constructor in its companion object. ```scala -enum Option[+T]: +enum Option[+T] with case Some(x: T) case None diff --git a/docs/docs/reference/enums/enums.md b/docs/docs/reference/enums/enums.md index 219a831a445e..37dc5c842a83 100644 --- a/docs/docs/reference/enums/enums.md +++ b/docs/docs/reference/enums/enums.md @@ -153,7 +153,7 @@ For a more in-depth example of using Scala 3 enums from Java, see [this test](ht ### Implementation Enums are represented as `sealed` classes that extend the `scala.reflect.Enum` trait. -This trait defines a single public method, `ordinal`: +This trait defines a single public method, `ordinal` with ```scala package scala.reflect diff --git a/docs/docs/reference/metaprogramming/erased-terms.md b/docs/docs/reference/metaprogramming/erased-terms.md index dde296ebff83..1e7cde748d5a 100644 --- a/docs/docs/reference/metaprogramming/erased-terms.md +++ b/docs/docs/reference/metaprogramming/erased-terms.md @@ -23,7 +23,7 @@ class IsOff[S <: State] object IsOff: given isOff: IsOff[Off] = new IsOff[Off] -class Machine[S <: State]: +class Machine[S <: State] with def turnedOn(using IsOff[S]): Machine[On] = new Machine[On] val m = new Machine[Off] @@ -130,7 +130,7 @@ object IsOn: // require that this evidence exists at compile time erased given IsOn[On] = new IsOn[On] -class Machine[S <: State] private (): +class Machine[S <: State] private () with // ev will disappear from both functions def turnedOn(using erased ev: IsOff[S]): Machine[On] = new Machine[On] def turnedOff(using erased ev: IsOn[S]): Machine[Off] = new Machine[Off] @@ -163,7 +163,7 @@ sealed trait State final class On extends State final class Off extends State -class Machine[S <: State]: +class Machine[S <: State] with transparent inline def turnOn(): Machine[On] = inline erasedValue[S] match case _: Off => new Machine[On] diff --git a/docs/docs/reference/metaprogramming/inline.md b/docs/docs/reference/metaprogramming/inline.md index ba18f55d76d8..a77540af5099 100644 --- a/docs/docs/reference/metaprogramming/inline.md +++ b/docs/docs/reference/metaprogramming/inline.md @@ -143,11 +143,11 @@ Inline methods can override other non-inline methods. The rules are as follows: 1. If an inline method `f` implements or overrides another, non-inline method, the inline method can also be invoked at runtime. For instance, consider the scenario: ```scala - abstract class A: + abstract class A with def f: Int def g: Int = f - class B extends A: + class B extends A with inline def f = 22 override inline def g = f + 11 @@ -168,7 +168,7 @@ Inline methods can override other non-inline methods. The rules are as follows: 3. Inline methods can also be abstract. An abstract inline method can be implemented only by other inline methods. It cannot be invoked directly: ```scala - abstract class A: + abstract class A with inline def f: Int object B extends A: @@ -250,7 +250,7 @@ specialized to a more precise type upon expansion. Example: ```scala class A -class B extends A: +class B extends A with def m = true transparent inline def choose(b: Boolean): A = @@ -535,7 +535,7 @@ not. We can create a set of implicit definitions like this: ```scala trait SetFor[T, S <: Set[T]] -class LowPriority: +class LowPriority with implicit def hashSetFor[T]: SetFor[T, HashSet[T]] = ... object SetsFor extends LowPriority: diff --git a/docs/docs/reference/metaprogramming/tasty-inspect.md b/docs/docs/reference/metaprogramming/tasty-inspect.md index 3547b8939a3d..f02b7fdbdb08 100644 --- a/docs/docs/reference/metaprogramming/tasty-inspect.md +++ b/docs/docs/reference/metaprogramming/tasty-inspect.md @@ -21,7 +21,7 @@ To inspect the trees of a TASTy file a consumer can be defined in the following import scala.quoted._ import scala.tasty.inspector._ -class MyInspector extends TastyInspector: +class MyInspector extends TastyInspector with protected def processCompilationUnit(using Quotes)(tree: quotes.reflect.Tree): Unit = import quotes.reflect._ // Do something with the tree @@ -30,7 +30,7 @@ class MyInspector extends TastyInspector: Then the consumer can be instantiated with the following code to get the tree of the `foo/Bar.tasty` file. ```scala -object Test: +object Test with def main(args: Array[String]): Unit = new MyInspector().inspectTastyFiles("foo/Bar.tasty") ``` 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 5f9bf9cf5f6a..0cf3a8c00b16 100644 --- a/docs/docs/reference/new-types/dependent-function-types-spec.md +++ b/docs/docs/reference/new-types/dependent-function-types-spec.md @@ -75,7 +75,7 @@ In the following example the depend type `f.Eff` refers to the effect type `CanT trait Effect // Type X => Y -abstract class Fun[-X, +Y]: +abstract class Fun[-X, +Y] with type Eff <: Effect def apply(x: X): Eff ?=> Y @@ -85,11 +85,11 @@ class CanIO extends Effect given ct: CanThrow = new CanThrow given ci: CanIO = new CanIO -class I2S extends Fun[Int, String]: +class I2S extends Fun[Int, String] with type Eff = CanThrow def apply(x: Int) = x.toString -class S2I extends Fun[String, Int]: +class S2I extends Fun[String, Int] with type Eff = CanIO def apply(x: String) = x.length diff --git a/docs/docs/reference/new-types/intersection-types.md b/docs/docs/reference/new-types/intersection-types.md index a2cfc1f380c8..cf232c621ace 100644 --- a/docs/docs/reference/new-types/intersection-types.md +++ b/docs/docs/reference/new-types/intersection-types.md @@ -59,7 +59,7 @@ So if one defines a class `C` that inherits `A` and `B`, one needs to give at that point a definition of a `children` method with the required type. ```scala -class C extends A, B: +class C extends A, B with def children: List[A & B] = ??? ``` diff --git a/docs/docs/reference/other-new-features/creator-applications.md b/docs/docs/reference/other-new-features/creator-applications.md index 387202720f9c..0369e3f0c35b 100644 --- a/docs/docs/reference/other-new-features/creator-applications.md +++ b/docs/docs/reference/other-new-features/creator-applications.md @@ -9,7 +9,7 @@ function application, without needing to write `new`. Scala 3 generalizes this scheme to all concrete classes. Example: ```scala -class StringBuilder(s: String): +class StringBuilder(s: String) with def this() = this("") StringBuilder("abc") // same as new StringBuilder("abc") diff --git a/docs/docs/reference/other-new-features/explicit-nulls.md b/docs/docs/reference/other-new-features/explicit-nulls.md index b531774ac1d5..82f61eead706 100644 --- a/docs/docs/reference/other-new-features/explicit-nulls.md +++ b/docs/docs/reference/other-new-features/explicit-nulls.md @@ -39,7 +39,7 @@ The new type system is unsound with respect to `null`. This means there are stil The unsoundness happens because uninitialized fields in a class start out as `null`: ```scala -class C: +class C with val f: String = foo(f) def foo(f2: String): String = f2 @@ -114,7 +114,7 @@ Specifically, we patch ``` ==> ```scala - class C: + class C with val s: String|UncheckedNull val x: Int ``` @@ -132,7 +132,7 @@ Specifically, we patch Notice this is rule is sometimes too conservative, as witnessed by ```scala - class InScala: + class InScala with val c: C[Bool] = ??? // C as above val b: Bool = c.foo() // no longer typechecks, since foo now returns Bool|Null ``` @@ -169,7 +169,7 @@ Specifically, we patch ``` ==> ```scala - class BoxFactory[T]: + class BoxFactory[T] with def makeBox(): Box[T | UncheckedNull] | UncheckedNull def makeCrazyBoxes(): List[Box[List[T] | UncheckedNull]] | UncheckedNull ``` @@ -195,7 +195,7 @@ Specifically, we patch ``` ==> ```scala - class Constants: + class Constants with val NAME: String("name") = "name" val AGE: Int(0) = 0 val CHAR: Char('a') = 'a' @@ -215,7 +215,7 @@ Specifically, we patch ``` ==> ```scala - class C: + class C with val name: String def getNames(prefix: String | UncheckedNull): List[String] // we still need to nullify the paramter types def getBoxedName(): Box[String | UncheckedNull] // we don't append `UncheckedNull` to the outmost level, but we still need to nullify inside diff --git a/docs/docs/reference/other-new-features/export.md b/docs/docs/reference/other-new-features/export.md index 2a7aaada28ef..697939f053ae 100644 --- a/docs/docs/reference/other-new-features/export.md +++ b/docs/docs/reference/other-new-features/export.md @@ -9,16 +9,16 @@ An export clause defines aliases for selected members of an object. Example: class BitMap class InkJet -class Printer: +class Printer with type PrinterType def print(bits: BitMap): Unit = ??? def status: List[String] = ??? -class Scanner: +class Scanner with def scan(): BitMap = ??? def status: List[String] = ??? -class Copier: +class Copier with private val printUnit = new Printer { type PrinterType = InkJet } private val scanUnit = new Scanner diff --git a/docs/docs/reference/other-new-features/indentation.md b/docs/docs/reference/other-new-features/indentation.md index 1873e2be3e40..da943737267b 100644 --- a/docs/docs/reference/other-new-features/indentation.md +++ b/docs/docs/reference/other-new-features/indentation.md @@ -120,7 +120,7 @@ With these new rules, the following constructs are all valid: trait A: def f: Int -class C(x: Int) extends A: +class C(x: Int) extends A with def f = x object O: @@ -256,7 +256,7 @@ For instance, the following end markers are all legal: ```scala package p1.p2: - abstract class C(): + abstract class C() with def this(x: Int) = this() diff --git a/docs/docs/reference/other-new-features/matchable.md b/docs/docs/reference/other-new-features/matchable.md index c4814af64f3f..3513e0f20049 100644 --- a/docs/docs/reference/other-new-features/matchable.md +++ b/docs/docs/reference/other-new-features/matchable.md @@ -75,7 +75,7 @@ extended by both `AnyVal` and `AnyRef`. Since `Matchable` is a supertype of ever Here is the hierarchy of top-level classes and traits with their defined methods: ```scala -abstract class Any: +abstract class Any with def getClass def isInstanceOf def asInstanceOf @@ -102,7 +102,7 @@ Matchable warning is turned on. The most common such method is the universal `equals` method. It will have to be written as in the following example: ```scala -class C(val x: String): +class C(val x: String) with override def equals(that: Any): Boolean = that.asInstanceOf[Matchable] match diff --git a/docs/docs/reference/other-new-features/open-classes.md b/docs/docs/reference/other-new-features/open-classes.md index c1ee2def453b..1de2e57fc66d 100644 --- a/docs/docs/reference/other-new-features/open-classes.md +++ b/docs/docs/reference/other-new-features/open-classes.md @@ -8,7 +8,7 @@ An `open` modifier on a class signals that the class is planned for extensions. // File Writer.scala package p -open class Writer[T]: +open class Writer[T] with /** Sends to stdout, can be overridden */ def send(x: T) = println(x) @@ -20,7 +20,7 @@ end Writer // File EncryptedWriter.scala package p -class EncryptedWriter[T: Encryptable] extends Writer[T]: +class EncryptedWriter[T: Encryptable] extends Writer[T] with override def send(x: T) = super.send(encrypt(x)) ``` An open class typically comes with some documentation that describes diff --git a/docs/docs/reference/other-new-features/safe-initialization.md b/docs/docs/reference/other-new-features/safe-initialization.md index 2d115745bb57..1a23474de166 100644 --- a/docs/docs/reference/other-new-features/safe-initialization.md +++ b/docs/docs/reference/other-new-features/safe-initialization.md @@ -14,11 +14,11 @@ To get a feel of how it works, we first show several examples below. Given the following code snippet: ``` scala -abstract class AbstractFile: +abstract class AbstractFile with def name: String val extension: String = name.substring(4) -class RemoteFile(url: String) extends AbstractFile: +class RemoteFile(url: String) extends AbstractFile with val localFile: String = s"${url.##}.tmp" // error: usage of `localFile` before it's initialized def name: String = localFile ``` @@ -63,11 +63,11 @@ The checker will report: Given the code below: ``` scala -abstract class Parent: +abstract class Parent with val f: () => String = () => this.message def message: String -class Child extends Parent: +class Child extends Parent with val a = f() val b = "hello" // error def message: String = b @@ -122,11 +122,11 @@ following example shows: ``` scala class MyException(val b: B) extends Exception("") -class A: +class A with val b = try { new B } catch { case myEx: MyException => myEx.b } println(b.a) -class B: +class B with throw new MyException(this) val a: Int = 1 ``` @@ -141,10 +141,10 @@ field points to an initialized object may not later point to an object under initialization. As an example, the following code will be rejected: ``` scala -trait Reporter: +trait Reporter with def report(msg: String): Unit -class FileReporter(ctx: Context) extends Reporter: +class FileReporter(ctx: Context) extends Reporter with ctx.typer.reporter = this // ctx now reaches an uninitialized object val file: File = new File("report.txt") def report(msg: String) = file.write(msg) @@ -214,11 +214,11 @@ project boundaries. For example, the following code passes the check when the two classes are defined in the same project: ```Scala -class Base: +class Base with private val map: mutable.Map[Int, String] = mutable.Map.empty def enter(k: Int, v: String) = map(k) = v -class Child extends Base: +class Child extends Base with enter(1, "one") enter(2, "two") ``` diff --git a/docs/docs/reference/other-new-features/targetName.md b/docs/docs/reference/other-new-features/targetName.md index 572d7a5e2146..a1b8f9150c38 100644 --- a/docs/docs/reference/other-new-features/targetName.md +++ b/docs/docs/reference/other-new-features/targetName.md @@ -70,9 +70,9 @@ between two definitions that have otherwise the same names and types. So the fol ```scala import annotation.targetName -class A: +class A with def f(): Int = 1 -class B extends A: +class B extends A with @targetName("g") def f(): Int = 2 ``` @@ -98,9 +98,9 @@ be present in the original code. So the following example would also be in error ```scala import annotation.targetName -class A: +class A with def f(): Int = 1 -class B extends A: +class B extends A with @targetName("f") def g(): Int = 2 ``` @@ -109,7 +109,7 @@ different names. But once we switch to target names, there is a clash that is re ``` -- [E120] Naming Error: test.scala:4:6 ----------------------------------------- -4 |class B extends A: +4 |class B extends A with | ^ | Name clash between defined and inherited member: | def f(): Int in class A at line 3 and diff --git a/docs/docs/reference/other-new-features/threadUnsafe-annotation.md b/docs/docs/reference/other-new-features/threadUnsafe-annotation.md index 2c5a3df9c82c..56ae89ea7e96 100644 --- a/docs/docs/reference/other-new-features/threadUnsafe-annotation.md +++ b/docs/docs/reference/other-new-features/threadUnsafe-annotation.md @@ -12,6 +12,6 @@ a `lazy val`. When this annotation is used, the initialization of the ```scala import scala.annotation.threadUnsafe -class Hello: +class Hello with @threadUnsafe lazy val x: Int = 1 ``` diff --git a/docs/docs/reference/other-new-features/trait-parameters.md b/docs/docs/reference/other-new-features/trait-parameters.md index 1655e338b32c..fd200c92bf53 100644 --- a/docs/docs/reference/other-new-features/trait-parameters.md +++ b/docs/docs/reference/other-new-features/trait-parameters.md @@ -9,7 +9,7 @@ Scala 3 allows traits to have parameters, just like classes have parameters. trait Greeting(val name: String): def msg = s"How are you, $name" -class C extends Greeting("Bob"): +class C extends Greeting("Bob") with println(msg) ``` diff --git a/docs/docs/release-notes/syntax-changes-0.22.md b/docs/docs/release-notes/syntax-changes-0.22.md index 64207d72e9d1..cc5cf45ebf1e 100644 --- a/docs/docs/release-notes/syntax-changes-0.22.md +++ b/docs/docs/release-notes/syntax-changes-0.22.md @@ -94,7 +94,7 @@ class Str(str: String) extends Text: class Append(txt1: Text, txt2: Text) extends Text: def toString = txt1 ++ txt2 -object Empty extends Text: +object Empty extends Text with def toString = "" extension on (t: Text): diff --git a/stdlib-bootstrapped-tasty-tests/test/BootstrappedStdLibTASYyTest.scala b/stdlib-bootstrapped-tasty-tests/test/BootstrappedStdLibTASYyTest.scala index ef004baa191a..43f365410fc3 100644 --- a/stdlib-bootstrapped-tasty-tests/test/BootstrappedStdLibTASYyTest.scala +++ b/stdlib-bootstrapped-tasty-tests/test/BootstrappedStdLibTASYyTest.scala @@ -12,7 +12,7 @@ import scala.quoted._ import java.io.File.pathSeparator import java.io.File.separator -class BootstrappedStdLibTASYyTest: +class BootstrappedStdLibTASYyTest with import BootstrappedStdLibTASYyTest._ @@ -88,7 +88,7 @@ class BootstrappedStdLibTASYyTest: end BootstrappedStdLibTASYyTest -object BootstrappedStdLibTASYyTest: +object BootstrappedStdLibTASYyTest with def scalaLibJarPath = System.getProperty("dotty.scala.library") def scalaLibClassesPath = diff --git a/stdlib-bootstrapped/test/Main.scala b/stdlib-bootstrapped/test/Main.scala index 1dad89eceffc..8c2782b90b0e 100644 --- a/stdlib-bootstrapped/test/Main.scala +++ b/stdlib-bootstrapped/test/Main.scala @@ -3,7 +3,7 @@ package hello enum Color: case Red, Green, Blue -object HelloWorld: +object HelloWorld with def main(args: Array[String]): Unit = { println("hello dotty.superbootstrapped!") println(Color.Red) diff --git a/tests/bench/string-interpolation-macro/Test.scala b/tests/bench/string-interpolation-macro/Test.scala index e32eeea2fef7..094462aa175b 100644 --- a/tests/bench/string-interpolation-macro/Test.scala +++ b/tests/bench/string-interpolation-macro/Test.scala @@ -1,4 +1,4 @@ import Macro._ -class Test: +class Test with def test: String = x"a${1}b${2}c${3}d${4}e${5}f" diff --git a/tests/disabled/pos/i8311.scala b/tests/disabled/pos/i8311.scala index eeecd97a7e7e..0d4423d93fb8 100644 --- a/tests/disabled/pos/i8311.scala +++ b/tests/disabled/pos/i8311.scala @@ -1,12 +1,12 @@ -trait Show[O]: +trait Show[O] with extension (o: O) def show: String class Box[A] class Foo -object test: +object test with given box[A](using Show[A]): Show[Box[A]] = _.toString given foo: Show[Foo] = _.toString diff --git a/tests/neg-custom-args/explicit-nulls/byname-nullables.scala b/tests/neg-custom-args/explicit-nulls/byname-nullables.scala index 4da2659bbde6..ada838b269f6 100644 --- a/tests/neg-custom-args/explicit-nulls/byname-nullables.scala +++ b/tests/neg-custom-args/explicit-nulls/byname-nullables.scala @@ -1,4 +1,4 @@ -object Test1: +object Test1 with def f(x: String) = x ++ x @@ -9,7 +9,7 @@ object Test1: else x -object Test2: +object Test2 with def f(x: => String) = x ++ x @@ -19,7 +19,7 @@ object Test2: if x != null then f(x) // error: f is call-by-name else x -object Test3: +object Test3 with def f(x: String, y: String) = x @@ -31,7 +31,7 @@ object Test3: if x != null then f(x, 1) // OK: not-null check successfully dropped else x -object Test4: +object Test4 with def f(x: String, y: String) = x @@ -43,7 +43,7 @@ object Test4: if x != null then f(identity(x), 1) // error: dropping not null check fails typing else x -object Test5: +object Test5 with import compiletime.byName def f(x: String, y: String) = x @@ -56,7 +56,7 @@ object Test5: if x != null then f(byName(identity(x)), 1) // OK, byName avoids the flow typing else x -object Test6: +object Test6 with def f(x: String, y: String) = x @@ -68,7 +68,7 @@ object Test6: if x != null then f(x, 1) // error: dropping not null check typechecks OK, but gives incompatible result type else x -object Test7: +object Test7 with import compiletime.byName def f(x: String, y: String) = x diff --git a/tests/neg-custom-args/explicit-nulls/byname-nullables1.scala b/tests/neg-custom-args/explicit-nulls/byname-nullables1.scala index a1c1924c545e..eb28a5af96c0 100644 --- a/tests/neg-custom-args/explicit-nulls/byname-nullables1.scala +++ b/tests/neg-custom-args/explicit-nulls/byname-nullables1.scala @@ -1,7 +1,7 @@ def f(op: => Boolean): Unit = () def f(op: Int): Unit = () -class C: +class C with var fld: String | Null = null def test() = diff --git a/tests/neg-custom-args/fatal-warnings/enum-variance.scala b/tests/neg-custom-args/fatal-warnings/enum-variance.scala index efe0dbbc6cdd..b342a28091f2 100644 --- a/tests/neg-custom-args/fatal-warnings/enum-variance.scala +++ b/tests/neg-custom-args/fatal-warnings/enum-variance.scala @@ -1,10 +1,10 @@ -enum View[-T]: +enum View[-T] with case Refl(f: T => T) // error: enum case Refl requires explicit declaration of type T enum ExplicitView[-T]: // desugared version of View case Refl[-T](f: T => T) extends ExplicitView[T] // error: contravariant type T occurs in covariant position -enum InvariantView[-T, +U] extends (T => U): +enum InvariantView[-T, +U] extends (T => U) with case Refl[T](f: T => T) extends InvariantView[T, T] final def apply(t: T): U = this match diff --git a/tests/neg-custom-args/fatal-warnings/i8781b.scala b/tests/neg-custom-args/fatal-warnings/i8781b.scala index a30b0e5249c9..ebd3e02d42f8 100644 --- a/tests/neg-custom-args/fatal-warnings/i8781b.scala +++ b/tests/neg-custom-args/fatal-warnings/i8781b.scala @@ -1,4 +1,4 @@ -object Test: +object Test with println((3: Boolean | Int).isInstanceOf[Boolean]) diff --git a/tests/neg-custom-args/fatal-warnings/opaque-match.scala b/tests/neg-custom-args/fatal-warnings/opaque-match.scala index f48a11168274..8f167932406a 100644 --- a/tests/neg-custom-args/fatal-warnings/opaque-match.scala +++ b/tests/neg-custom-args/fatal-warnings/opaque-match.scala @@ -1,6 +1,6 @@ case class C() -object O: +object O with opaque type T <: C = C val x: T = C() (??? : Any) match @@ -17,7 +17,7 @@ def Test[T] = (??? : Any) match case _: List[O.T] => ??? // error (??? : Any) match - case _: List[O.T @unchecked] => ??? // OK + case _: List[O.T @unchecked] => ??? // OK (??? : Any) match case _: List[T] => ??? // error diff --git a/tests/neg-custom-args/fatal-warnings/supertraits.scala b/tests/neg-custom-args/fatal-warnings/supertraits.scala index 9337e2f925a3..039c2713a9d4 100644 --- a/tests/neg-custom-args/fatal-warnings/supertraits.scala +++ b/tests/neg-custom-args/fatal-warnings/supertraits.scala @@ -4,7 +4,7 @@ trait S case object a extends S, TA, TB case object b extends S, TA, TB -object Test: +object Test with def choose0[X](x: X, y: X): X = x def choose1[X <: TA](x: X, y: X): X = x diff --git a/tests/neg-custom-args/infix.scala b/tests/neg-custom-args/infix.scala index f6f3053087dd..cc77f40d24d4 100644 --- a/tests/neg-custom-args/infix.scala +++ b/tests/neg-custom-args/infix.scala @@ -1,11 +1,11 @@ // Compile with -strict -Xfatal-warnings -deprecation -class C: +class C with infix def op(x: Int): Int = ??? def meth(x: Int): Int = ??? def matching(x: Int => Int) = ??? def +(x: Int): Int = ??? -object C: +object C with given AnyRef with extension (x: C) infix def iop (y: Int) = ??? diff --git a/tests/neg-macros/BigFloat/BigFloatFromDigitsImpl_1.scala b/tests/neg-macros/BigFloat/BigFloatFromDigitsImpl_1.scala index a1ecc31b776e..093aa33c682d 100644 --- a/tests/neg-macros/BigFloat/BigFloatFromDigitsImpl_1.scala +++ b/tests/neg-macros/BigFloat/BigFloatFromDigitsImpl_1.scala @@ -3,7 +3,7 @@ import language.experimental.genericNumberLiterals import scala.util.FromDigits import scala.quoted._ -object BigFloatFromDigitsImpl: +object BigFloatFromDigitsImpl with def apply(digits: Expr[String])(using Quotes): Expr[BigFloat] = digits.value match case Some(ds) => diff --git a/tests/neg-macros/GenericNumLits/EvenFromDigitsImpl_1.scala b/tests/neg-macros/GenericNumLits/EvenFromDigitsImpl_1.scala index 1d2e484daa5d..80e2e80ea4e9 100644 --- a/tests/neg-macros/GenericNumLits/EvenFromDigitsImpl_1.scala +++ b/tests/neg-macros/GenericNumLits/EvenFromDigitsImpl_1.scala @@ -3,7 +3,7 @@ import scala.util.FromDigits import scala.quoted._ import Even._ -object EvenFromDigitsImpl: +object EvenFromDigitsImpl with def apply(digits: Expr[String])(using Quotes): Expr[Even] = digits.value match { case Some(ds) => val ev = diff --git a/tests/neg-macros/i9972b/Test_2.scala b/tests/neg-macros/i9972b/Test_2.scala index 1f94ccf18ee8..85c50e1880ad 100644 --- a/tests/neg-macros/i9972b/Test_2.scala +++ b/tests/neg-macros/i9972b/Test_2.scala @@ -1,5 +1,5 @@ class T[A] -object T: +object T with implicit inline def derived[A]: T[A] = new T[A] diff --git a/tests/neg-with-compiler/GenericNumLits/EvenFromDigitsImpl_1.scala b/tests/neg-with-compiler/GenericNumLits/EvenFromDigitsImpl_1.scala index 1d2e484daa5d..80e2e80ea4e9 100644 --- a/tests/neg-with-compiler/GenericNumLits/EvenFromDigitsImpl_1.scala +++ b/tests/neg-with-compiler/GenericNumLits/EvenFromDigitsImpl_1.scala @@ -3,7 +3,7 @@ import scala.util.FromDigits import scala.quoted._ import Even._ -object EvenFromDigitsImpl: +object EvenFromDigitsImpl with def apply(digits: Expr[String])(using Quotes): Expr[Even] = digits.value match { case Some(ds) => val ev = diff --git a/tests/neg/abstract-givens.scala b/tests/neg/abstract-givens.scala index 5aa5bdee88e3..fbfb1ba2adbe 100644 --- a/tests/neg/abstract-givens.scala +++ b/tests/neg/abstract-givens.scala @@ -1,9 +1,9 @@ -trait T: +trait T with given x: Int given y(using Int): String = summon[Int].toString given z[T](using T): List[T] -object Test extends T: +object Test extends T with given x: Int = 22 given y(using Int): String = summon[Int].toString * 22 // error given z[T](using T): Seq[T] = List(summon[T]) // error diff --git a/tests/neg/abstract-inline-val.scala b/tests/neg/abstract-inline-val.scala index 1bcca078ad52..4aa3ede2b578 100644 --- a/tests/neg/abstract-inline-val.scala +++ b/tests/neg/abstract-inline-val.scala @@ -1,4 +1,4 @@ -trait C: +trait C with inline def x: Int inline val y: Int diff --git a/tests/neg/ambiref.scala b/tests/neg/ambiref.scala index e7a5d5efbd7e..95dc06e1573f 100644 --- a/tests/neg/ambiref.scala +++ b/tests/neg/ambiref.scala @@ -1,43 +1,43 @@ -object test1: +object test1 with - class C: + class C with val x = 0 - object Test: + object Test with val x = 1 - class D extends C: + class D extends C with println(x) // error - new C: + new C with println(x) // error -object test2: +object test2 with def c(y: Float) = - class D: + class D with val y = 2 - new D: + new D with println(y) // error -object test3: +object test3 with def c(y: Float) = - class D: + class D with val y = 2 - class E extends D: - class F: + class E extends D with + class F with println(y) // error -object test4: +object test4 with - class C: + class C with val x = 0 - object Test: + object Test with val x = 1 - class D extends C: + class D extends C with def x(y: Int) = 3 val y: Int = this.x // OK val z: Int = x // OK end test4 val global = 0 -class C: +class C with val global = 1 -object D extends C: +object D extends C with println(global) // OK, since global is defined in package \ No newline at end of file diff --git a/tests/neg/bad-unapplies.scala b/tests/neg/bad-unapplies.scala index 6bf70c3ae6d3..ab898d6f86c3 100644 --- a/tests/neg/bad-unapplies.scala +++ b/tests/neg/bad-unapplies.scala @@ -1,19 +1,19 @@ trait A trait B class C extends A, B -object A: +object A with def unapply(x: A): Option[String] = Some(x.toString) def unapply(x: B): Option[String] = Some(x.toString) object B -object D: +object D with def unapply(x: A, y: B): Option[String] = Some(x.toString) -object E: +object E with val unapply: Option[String] = Some("") -object F: +object F with def unapply(x: Int): Boolean = true diff --git a/tests/neg/case-semi.scala b/tests/neg/case-semi.scala index b7dfe0a7e524..d05919805fa6 100644 --- a/tests/neg/case-semi.scala +++ b/tests/neg/case-semi.scala @@ -1,4 +1,4 @@ -object Test: +object Test with type X = Int val x: X = 1 diff --git a/tests/neg/creator-ambiguous.scala b/tests/neg/creator-ambiguous.scala index dd476933db1e..feed4083ff56 100644 --- a/tests/neg/creator-ambiguous.scala +++ b/tests/neg/creator-ambiguous.scala @@ -2,11 +2,11 @@ // This used to succeed with old creator methods scheme // What happened was: the overloading resolution gave an ambiguous // overload, but then the falblback picked the constructor -object Test: +object Test with case class Record(elems: (String, Any)*) - object Record: + object Record with inline def apply[R <: Record](elems: (String, Any)*) : R = new Record(elems: _*).asInstanceOf[R] diff --git a/tests/neg/curried-dependent-ift.scala b/tests/neg/curried-dependent-ift.scala index 359514505613..8aab2dd89ebe 100644 --- a/tests/neg/curried-dependent-ift.scala +++ b/tests/neg/curried-dependent-ift.scala @@ -1,9 +1,9 @@ -trait Ctx1: +trait Ctx1 with type T val x: T val y: T -trait Ctx2: +trait Ctx2 with type T val x: T val y: T diff --git a/tests/neg/endmarkers.scala b/tests/neg/endmarkers.scala index 5c7c1c686cd0..19880fbc7beb 100644 --- a/tests/neg/endmarkers.scala +++ b/tests/neg/endmarkers.scala @@ -1,4 +1,4 @@ -object Test: +object Test with locally { var x = 0 @@ -43,11 +43,11 @@ object Test: x < 10 do () -class Test2: +class Test2 with self => def foo = 1 - object x: + object x with new Test2 { override def foo = 2 end new // error: misaligned end marker @@ -56,16 +56,16 @@ class Test2: end Test2 // error: misaligned end marker end Test2 -class Test3: +class Test3 with self => def foo = 1 end Test3 // error: misaligned end marker import collection.mutable.HashMap -class Coder(words: List[String]): +class Coder(words: List[String]) with - class Foo: + class Foo with println() end Foo // error: misaligned end marker diff --git a/tests/neg/endmarkers1.scala b/tests/neg/endmarkers1.scala index b2b746c57371..2205395b0036 100644 --- a/tests/neg/endmarkers1.scala +++ b/tests/neg/endmarkers1.scala @@ -4,7 +4,7 @@ def f7[T](x: Option[T]) = x match case None => end if // error: misaligned end marker -object Test4: +object Test4 with def f[T](x: Option[T]) = x match case Some(y) => case None => diff --git a/tests/neg/enum-values.scala b/tests/neg/enum-values.scala index 08069251af0e..9bf531abae98 100644 --- a/tests/neg/enum-values.scala +++ b/tests/neg/enum-values.scala @@ -1,26 +1,26 @@ package example -enum Tag[T]: +enum Tag[T] with case Int extends Tag[Int] case String extends Tag[String] case OfClass[T]()(using val tag: reflect.ClassTag[T]) extends Tag[T] -enum ListLike[+T]: +enum ListLike[+T] with case Cons[T](head: T, tail: ListLike[T]) extends ListLike[T] case EmptyListLike -object ListLike: +object ListLike with def valuef(s: String): ListLike[?] = ??? // this will usually trigger a "- did you mean ListLike.valuef" addendum -object Extensions: +object Extensions with extension (foo: Nothing) // this will usually trigger an attempted extension method addendum def values: Array[Tag[?]] = ??? -enum TypeCtorsK[F[_]]: +enum TypeCtorsK[F[_]] with case List extends TypeCtorsK[List] case Option extends TypeCtorsK[Option] case Const[T]() extends TypeCtorsK[[U] =>> T] -object UnimportedExtensions: +object UnimportedExtensions with extension (TypeCtorsKModule: TypeCtorsK.type) // this will usually trigger an import suggestions addendum def valueOf(name: String): TypeCtorsK[?] = ??? diff --git a/tests/neg/enums.scala b/tests/neg/enums.scala index 6335def433c1..c43fb829d9b9 100644 --- a/tests/neg/enums.scala +++ b/tests/neg/enums.scala @@ -42,10 +42,10 @@ enum Option[+T] derives CanEqual { object DollarNew { - enum MyEnum: + enum MyEnum with case A - object MyEnum: + object MyEnum with def $new: MyEnum = new MyEnum with runtime.EnumValue { // error: anonymous class in method $new extends enum MyEnum, but extending enums is prohibited. override def $ordinal = 1 diff --git a/tests/neg/enumvalues.scala b/tests/neg/enumvalues.scala index f9d847f5fb63..10aa4f3eb6d9 100644 --- a/tests/neg/enumvalues.scala +++ b/tests/neg/enumvalues.scala @@ -1,7 +1,7 @@ -enum Color: +enum Color with case Red, Green, Blue -enum Option[+T]: +enum Option[+T] with case None extends Option[Nothing] import scala.runtime.EnumValue diff --git a/tests/neg/eql.scala b/tests/neg/eql.scala index 58378800bbc5..a68f73bd5a8a 100644 --- a/tests/neg/eql.scala +++ b/tests/neg/eql.scala @@ -1,6 +1,6 @@ -object lst: +object lst with opaque type Lst[+T] = Any - object Lst: + object Lst with given lstCanEqual[T, U]: CanEqual[Lst[T], Lst[U]] = CanEqual.derived val Empty: Lst[Nothing] = ??? end lst diff --git a/tests/neg/exports1.scala b/tests/neg/exports1.scala index ecd89c694043..698ab25ac7f8 100644 --- a/tests/neg/exports1.scala +++ b/tests/neg/exports1.scala @@ -1,20 +1,20 @@ -object A: +object A with def f: String = "" -trait B: +trait B with def f: String = "abc" -trait B2 extends B: +trait B2 extends B with override def f: String = "abc" -object D extends B: +object D extends B with object b extends B export b._ // ok -object D1 extends B: +object D1 extends B with object b extends B export b.f // error -object D2 extends B: +object D2 extends B with object b2 extends B2 export b2.f // error diff --git a/tests/neg/exports2.scala b/tests/neg/exports2.scala index 913248a2041a..6fa18ae52900 100644 --- a/tests/neg/exports2.scala +++ b/tests/neg/exports2.scala @@ -1,9 +1,9 @@ -object A: +object A with def f: String = "" -trait B: +trait B with def f: String = "abc" -object C extends B: +object C extends B with export A._ // error diff --git a/tests/neg/extend-java-enum-nonstatic.scala b/tests/neg/extend-java-enum-nonstatic.scala index 5f0b6d36f8a8..0bd72cc7d7da 100644 --- a/tests/neg/extend-java-enum-nonstatic.scala +++ b/tests/neg/extend-java-enum-nonstatic.scala @@ -1,22 +1,22 @@ import java.{lang => jl} -object TestSuite: +object TestSuite with def test(op: => Unit): Unit = op test { enum E extends jl.Enum[E] { case A } // error: enum extending java.lang.Enum must be declared in a static scope } -class Container: +class Container with enum E extends jl.Enum[E] { case A } // error: enum extending java.lang.Enum must be declared in a static scope -object Wrap: +object Wrap with def force = enum E extends jl.Enum[E] { case A } // error: enum extending java.lang.Enum must be declared in a static scope -trait Universe: +trait Universe with enum E extends jl.Enum[E] { case A } // error: enum extending java.lang.Enum must be declared in a static scope enum E extends jl.Enum[E] { case A } // ok, a declaration at package level is static. -object Static: +object Static with enum E extends jl.Enum[E] { case A } // ok, a declaration within a static object is static. diff --git a/tests/neg/gadt-approximation-interaction.scala b/tests/neg/gadt-approximation-interaction.scala index 683d0668f4a2..39ed7c1ce60b 100644 --- a/tests/neg/gadt-approximation-interaction.scala +++ b/tests/neg/gadt-approximation-interaction.scala @@ -1,5 +1,5 @@ object MemberHealing { - enum SUB[-A, +B]: + enum SUB[-A, +B] with case Refl[S]() extends SUB[S, S] def foo[T](t: T, ev: T SUB Int) = @@ -9,7 +9,7 @@ object MemberHealing { } object ImplicitLookup { - enum SUB[-A, +B]: + enum SUB[-A, +B] with case Refl[S]() extends SUB[S, S] class Tag[T] @@ -23,7 +23,7 @@ object ImplicitLookup { } object GivenLookup { - enum SUB[-A, +B]: + enum SUB[-A, +B] with case Refl[S]() extends SUB[S, S] class Tag[T] @@ -37,10 +37,10 @@ object GivenLookup { } object ImplicitConversion { - enum SUB[-A, +B]: + enum SUB[-A, +B] with case Refl[S]() extends SUB[S, S] - class Pow(self: Int): + class Pow(self: Int) with def **(other: Int): Int = math.pow(self, other).toInt implicit def pow(i: Int): Pow = Pow(i) @@ -57,10 +57,10 @@ object ImplicitConversion { } object GivenConversion { - enum SUB[-A, +B]: + enum SUB[-A, +B] with case Refl[S]() extends SUB[S, S] - class Pow(self: Int): + class Pow(self: Int) with def **(other: Int): Int = math.pow(self, other).toInt given Conversion[Int, Pow] = (i: Int) => Pow(i) @@ -77,7 +77,7 @@ object GivenConversion { } object ExtensionMethod { - enum SUB[-A, +B]: + enum SUB[-A, +B] with case Refl[S]() extends SUB[S, S] extension (x: Int) @@ -90,10 +90,10 @@ object ExtensionMethod { } object HKFun { - enum SUB[-A, +B]: + enum SUB[-A, +B] with case Refl[S]() extends SUB[S, S] - enum HKSUB[-F[_], +G[_]]: + enum HKSUB[-F[_], +G[_]] with case Refl[H[_]]() extends HKSUB[H, H] def foo[F[_], T](ft: F[T], hkev: F HKSUB Option, ev: T SUB Int) = @@ -107,7 +107,7 @@ object HKFun { } } - enum COVHKSUB[-F[+_], +G[+_]]: + enum COVHKSUB[-F[+_], +G[+_]] with case Refl[H[_]]() extends COVHKSUB[H, H] def bar[F[+_], T](ft: F[T], hkev: F COVHKSUB Option, ev: T SUB Int) = @@ -123,7 +123,7 @@ object HKFun { } object NestedConstrained { - enum SUB[-A, +B]: + enum SUB[-A, +B] with case Refl[S]() extends SUB[S, S] def foo[A, B](a: A, ev1: A SUB Option[B], ev2: B SUB Int) = diff --git a/tests/neg/given-eta.scala b/tests/neg/given-eta.scala index db9ab3744963..6b0ae63947e4 100644 --- a/tests/neg/given-eta.scala +++ b/tests/neg/given-eta.scala @@ -1,5 +1,5 @@ -trait D: +trait D with type T def trans(other: T): T diff --git a/tests/neg/i10546.scala b/tests/neg/i10546.scala index 33407872f77e..cfe31a7e9e38 100644 --- a/tests/neg/i10546.scala +++ b/tests/neg/i10546.scala @@ -1,4 +1,4 @@ -object test: +object test with def times(num : Int)(block : => Unit) : Unit = () times(10): println("ah") // error: end of statement expected but '(' found // error diff --git a/tests/neg/i10817.scala b/tests/neg/i10817.scala index c9388274fc25..6a3e01fca9ea 100644 --- a/tests/neg/i10817.scala +++ b/tests/neg/i10817.scala @@ -1,6 +1,6 @@ import annotation.static -class T: +class T with @static val foo = 10 // error val x = (new T).foo \ No newline at end of file diff --git a/tests/neg/i10857.scala b/tests/neg/i10857.scala index b9128933484f..1ab4d9d5091e 100644 --- a/tests/neg/i10857.scala +++ b/tests/neg/i10857.scala @@ -1,25 +1,25 @@ -object Module: +object Module with class Bar class Baz class Qux - object Givens: + object Givens with given GivenBar: Bar = new Bar() def GivenBar(ignored: Int): Bar = new Bar() class GivenBar - object Members: + object Members with given Member: Baz = new Baz() private def Member(ignored1: String)(ignored2: Int): Bar = new Bar() def Member(ignored: Int): Baz = new Baz() class Member - object Combined: + object Combined with given GivenQux: Qux = new Qux() def GivenQux(ignored: Int): Qux = new Qux() - enum Color: + enum Color with case Red, Green, Blue export Color._ // will only export synthetic defs with same name as standard definition diff --git a/tests/neg/i10870.scala b/tests/neg/i10870.scala index 55669d580dc5..9d840ad1f4a0 100644 --- a/tests/neg/i10870.scala +++ b/tests/neg/i10870.scala @@ -1,7 +1,7 @@ final case class A() final case class B(a:A) -object Test: +object Test with extension(a:A) def x = 5 diff --git a/tests/neg/i10901.scala b/tests/neg/i10901.scala index 9552047c402f..c163a8e427ea 100644 --- a/tests/neg/i10901.scala +++ b/tests/neg/i10901.scala @@ -52,10 +52,10 @@ object BugExp4Point2D { class C -object Container: +object Container with given C with {} -object Test: +object Test with extension (x: String)(using C) def foo: String = x diff --git a/tests/neg/i11066.scala b/tests/neg/i11066.scala index 4b8e16e85e9d..c61694f31cd0 100644 --- a/tests/neg/i11066.scala +++ b/tests/neg/i11066.scala @@ -1,12 +1,12 @@ class PreferredPrompt(val preference: String) -object Greeter: +object Greeter with def greet(name: String)(using prompt: PreferredPrompt) = println(s"Welcome, $name. The system is ready.") println(prompt.preference) -object JillsPrefs: +object JillsPrefs with given jillsPrompt: PreferredPrompt = PreferredPrompt("Your wish> ") -object JoesPrefs: +object JoesPrefs with given joesPrompt: PreferredPrompt = PreferredPrompt("relax> ") diff --git a/tests/neg/i11081.scala b/tests/neg/i11081.scala index 7c1e6ce6dec6..4385f7039984 100644 --- a/tests/neg/i11081.scala +++ b/tests/neg/i11081.scala @@ -1,6 +1,6 @@ -enum Outer: +enum Outer with case Foo(u: Unavailable) // error case Bar(u: DefinitelyNotAvailable) // error -object Outer: +object Outer with class Unavailable(i: Int) case class DefinitelyNotAvailable() diff --git a/tests/neg/i1501.scala b/tests/neg/i1501.scala index 68556640383a..dbc08a7ba442 100644 --- a/tests/neg/i1501.scala +++ b/tests/neg/i1501.scala @@ -24,5 +24,5 @@ object Test2 { trait TSubA extends SubA(2) // error: trait TSubA may not call constructor of class SubA - class Foo extends TA with TSubA // error: missing argument for parameter x of constructor SubA: + class Foo extends TA with TSubA // error: missing argument for parameter x of constructor SubA with } diff --git a/tests/neg/i3253.scala b/tests/neg/i3253.scala index 04a79bb73ea0..20965742046f 100644 --- a/tests/neg/i3253.scala +++ b/tests/neg/i3253.scala @@ -1,5 +1,5 @@ import Test.test -class A: +class A with def test = " " * 10 // error object Test extends A diff --git a/tests/neg/i6183.scala b/tests/neg/i6183.scala index 30eae3abdbe3..e9de3fde8ee8 100644 --- a/tests/neg/i6183.scala +++ b/tests/neg/i6183.scala @@ -1,4 +1,4 @@ -object Test: +object Test with extension [A](a: A) def render: String = "Hi" extension [B](b: B) def render(using DummyImplicit): Char = 'x' diff --git a/tests/neg/i6205.scala b/tests/neg/i6205.scala index 32537e5b2fbb..fd1d0202f552 100644 --- a/tests/neg/i6205.scala +++ b/tests/neg/i6205.scala @@ -1,6 +1,6 @@ class Contra[-T >: Null] -object Test: +object Test with def foo = // error class A new Contra[A] diff --git a/tests/neg/i6779.scala b/tests/neg/i6779.scala index c83a2368940e..805ae9c54eb2 100644 --- a/tests/neg/i6779.scala +++ b/tests/neg/i6779.scala @@ -3,7 +3,7 @@ type G[T] type Stuff given Stuff = ??? -object Test: +object Test with extension [T](x: T) def f(using Stuff): F[T] = ??? diff --git a/tests/neg/i7359-g.scala b/tests/neg/i7359-g.scala index ad7082dd21e3..e22b39e2b370 100644 --- a/tests/neg/i7359-g.scala +++ b/tests/neg/i7359-g.scala @@ -1,4 +1,4 @@ -trait SAMTrait: +trait SAMTrait with def first(): String def equals(obj: Int): Boolean diff --git a/tests/neg/i7359.scala b/tests/neg/i7359.scala index c65a33a66a18..e229af5e85ab 100644 --- a/tests/neg/i7359.scala +++ b/tests/neg/i7359.scala @@ -1,3 +1,3 @@ -trait SAMTrait: +trait SAMTrait with def first(): String def notify(): Unit // error diff --git a/tests/neg/i7526.scala b/tests/neg/i7526.scala index ed37df14aa73..57119abdf054 100644 --- a/tests/neg/i7526.scala +++ b/tests/neg/i7526.scala @@ -1,9 +1,9 @@ type Tr[-I, +O, +A] = I => (O, A) -trait NetApi: +trait NetApi with type Comp -trait NetDB extends NetApi: +trait NetDB extends NetApi with class Comp trait NetHelper extends NetApi diff --git a/tests/neg/i7709.scala b/tests/neg/i7709.scala index 80bc4d8d518f..2e7236c9fb8d 100644 --- a/tests/neg/i7709.scala +++ b/tests/neg/i7709.scala @@ -1,31 +1,31 @@ -object X: +object X with protected class Y -object A: +object A with class B extends X.Y // error class B2 extends X.Y: // error def this(n: Int) = this() class B3(x: Any) class B4 extends B3(new X.Y) // error - class B5(x: String): + class B5(x: String) with def this(n: Int) = this(new X.Y().toString) // error -trait T: +trait T with class B extends X.Y // error -class XX: +class XX with protected class Y -class C: +class C with def xx = new XX def y = new xx.Y // error -class D: +class D with def this(n: Int) = { this() def xx = new XX def y = new xx.Y // error } -class YY extends XX: +class YY extends XX with def y = new Y package p: - object X: + object X with protected class Y class Q extends X.Y // error diff --git a/tests/neg/i7980.scala b/tests/neg/i7980.scala index b2f769056dcb..6d950830e58a 100644 --- a/tests/neg/i7980.scala +++ b/tests/neg/i7980.scala @@ -1,6 +1,6 @@ trait Evidence[X] -trait Trait[X : Evidence]: +trait Trait[X : Evidence] with def method(x : X) : X given ev: Evidence[Int] = new Evidence[Int]{} diff --git a/tests/neg/i8050.scala b/tests/neg/i8050.scala index 029e8d8195d5..94520c3d3de7 100644 --- a/tests/neg/i8050.scala +++ b/tests/neg/i8050.scala @@ -1,4 +1,4 @@ -object stuff: +object stuff with def exec(dir: Int) = ??? extension (a: Int) diff --git a/tests/neg/i8069.scala b/tests/neg/i8069.scala index 50f8b7a3480e..fc94d7c057a1 100644 --- a/tests/neg/i8069.scala +++ b/tests/neg/i8069.scala @@ -1,7 +1,7 @@ -trait A: +trait A with type B -enum Test: +enum Test with case Test(a: A, b: a.B) // error: Implementation restriction: case classes cannot have dependencies between parameters case class Test2(a: A, b: a.B) // error: Implementation restriction: case classes cannot have dependencies between parameters diff --git a/tests/neg/i8333.scala b/tests/neg/i8333.scala index 12a35ac2d636..e5c19bd37228 100644 --- a/tests/neg/i8333.scala +++ b/tests/neg/i8333.scala @@ -1,12 +1,12 @@ -class A: +class A with type T = Int // can also be class T -class B(x: A, y: A): +class B(x: A, y: A) with export x._ export y._ // error: duplicate -class C(x: A): +class C(x: A) with type T = String export x._ // error: duplicate -class D(x: A): +class D(x: A) with export x._ // error: duplicate type T = String diff --git a/tests/neg/i8407.scala b/tests/neg/i8407.scala index 34d7fa20914c..941412d462b0 100644 --- a/tests/neg/i8407.scala +++ b/tests/neg/i8407.scala @@ -1,4 +1,4 @@ -object Test: +object Test with val xs = List(1, 2, 3, 4, 5) xs match { case List(1, 2, xs1 @ xs2: _*) => println(xs2) // error // error diff --git a/tests/neg/i8623.scala b/tests/neg/i8623.scala index f402a6ceeedd..f07a911a27c1 100644 --- a/tests/neg/i8623.scala +++ b/tests/neg/i8623.scala @@ -1,6 +1,6 @@ -trait QC: - object tasty: +trait QC with + object tasty with type Tree extension (tree: Tree) def pos: Tree = ??? diff --git a/tests/neg/i8731.scala b/tests/neg/i8731.scala index 97ae8308b20b..6f20519a5be7 100644 --- a/tests/neg/i8731.scala +++ b/tests/neg/i8731.scala @@ -1,4 +1,4 @@ -object test: +object test with 3 match case 3 => ??? diff --git a/tests/neg/i9014.scala b/tests/neg/i9014.scala index 2a82d54be9d9..287d29d392bf 100644 --- a/tests/neg/i9014.scala +++ b/tests/neg/i9014.scala @@ -1,4 +1,4 @@ trait Bar -object Bar: +object Bar with inline given Bar = compiletime.error("Failed to expand!") val tests = summon[Bar] // error diff --git a/tests/neg/i9051.scala b/tests/neg/i9051.scala index 360f3b20eec7..cb2908ce83de 100644 --- a/tests/neg/i9051.scala +++ b/tests/neg/i9051.scala @@ -1,11 +1,11 @@ package zio: class ZRef - object ZRef: + object ZRef with - private[zio] implicit class ZRefSyntax(private val self: ZRef): + private[zio] implicit class ZRefSyntax(private val self: ZRef) with def unsafeUpdate: Boolean = true -object Main: +object Main with val ref = new zio.ZRef println(ref.unsafeUpdate) // error diff --git a/tests/neg/i9437.scala b/tests/neg/i9437.scala index 13cb2e74dc7a..389945ba3985 100644 --- a/tests/neg/i9437.scala +++ b/tests/neg/i9437.scala @@ -1,7 +1,7 @@ class Bag extends reflect.Selectable @main def Test = - val x = new Bag: + val x = new Bag with val f1 = 23 println(x.f1()) // error \ No newline at end of file diff --git a/tests/neg/i9562.scala b/tests/neg/i9562.scala index 23d1bebdbba9..d73df61895df 100644 --- a/tests/neg/i9562.scala +++ b/tests/neg/i9562.scala @@ -1,7 +1,7 @@ -class Foo: +class Foo with def foo = 23 -object Unrelated: +object Unrelated with extension (f: Foo) def g = f.foo // OK diff --git a/tests/neg/i9790.scala b/tests/neg/i9790.scala index 3417c4b2c7b0..d247222ee0bc 100644 --- a/tests/neg/i9790.scala +++ b/tests/neg/i9790.scala @@ -1,4 +1,4 @@ -object A: +object A with def fn: Unit = if true then println(1) diff --git a/tests/neg/i9928.scala b/tests/neg/i9928.scala index a1034b1f20e9..44e4a35bb982 100644 --- a/tests/neg/i9928.scala +++ b/tests/neg/i9928.scala @@ -1,14 +1,14 @@ -trait Magic[F]: +trait Magic[F] with extension (x: Int) def read: F -object Magic: +object Magic with given Magic[String] with extension(x: Int) def read: String = println("In string") s"$x" opaque type Foo = String -object Foo: +object Foo with import Magic.given def apply(s: String): Foo = s diff --git a/tests/neg/import-given.scala b/tests/neg/import-given.scala index ddc3da2fa5cb..f1ad6aeb5880 100644 --- a/tests/neg/import-given.scala +++ b/tests/neg/import-given.scala @@ -25,6 +25,6 @@ object E { foo // ok foo(using tc) // ok } -object F: +object F with import A.{given ?} // error: unbound wildcard type diff --git a/tests/neg/inline-abstract.scala b/tests/neg/inline-abstract.scala index 2f4596f38ea6..95f67ae4ba5d 100644 --- a/tests/neg/inline-abstract.scala +++ b/tests/neg/inline-abstract.scala @@ -1,7 +1,7 @@ -class A: +class A with inline def f(): Int -class B extends A: +class B extends A with inline def f() = 1 def Test = diff --git a/tests/neg/missing-implicit1.scala b/tests/neg/missing-implicit1.scala index 66c70f446d37..30ba99904186 100644 --- a/tests/neg/missing-implicit1.scala +++ b/tests/neg/missing-implicit1.scala @@ -1,4 +1,4 @@ -object testObjectInstance: +object testObjectInstance with trait Zip[F[_]] trait Traverse[F[_]] { extension [A, B, G[_] : Zip](fa: F[A]) def traverse(f: A => G[B]): G[F[B]] diff --git a/tests/neg/missing-implicit2.scala b/tests/neg/missing-implicit2.scala index 53e30eeb9ee1..a673797e8738 100644 --- a/tests/neg/missing-implicit2.scala +++ b/tests/neg/missing-implicit2.scala @@ -1,6 +1,6 @@ trait X trait Y -object test: +object test with def f(using x: X) = ??? object instances { given y: Y = ??? diff --git a/tests/neg/missing-implicit5.scala b/tests/neg/missing-implicit5.scala index c294412da53b..a9132b0407d8 100644 --- a/tests/neg/missing-implicit5.scala +++ b/tests/neg/missing-implicit5.scala @@ -1,4 +1,4 @@ -object testObjectInstance: +object testObjectInstance with trait Zip[F[_]] trait Traverse[F[_]] { extension [A, B, G[_] : Zip](fa: F[A]) def traverse(f: A => G[B]): G[F[B]] diff --git a/tests/neg/name-hints.scala b/tests/neg/name-hints.scala index cb4cb8884087..aca20e067e0f 100644 --- a/tests/neg/name-hints.scala +++ b/tests/neg/name-hints.scala @@ -1,8 +1,8 @@ -object O: +object O with val abcde: Int = 0 val xy: Int = 1 -object Test: +object Test with val x1 = Int.maxvalue // error val x2 = Int.MxValue // error val x3 = Int.MaxxValue // error diff --git a/tests/neg/namedTypeParams.scala b/tests/neg/namedTypeParams.scala index 8ed7c92241ea..bc78ac09a208 100644 --- a/tests/neg/namedTypeParams.scala +++ b/tests/neg/namedTypeParams.scala @@ -1,7 +1,7 @@ class C[T] class D[type T] // error: identifier expected, but `type` found -object Test0: +object Test0 with def f[X, Y](x: X, y: Y): Int = ??? f[X = Int, Y = Int](1, 2) // error: experimental // error: experimental diff --git a/tests/neg/null-anyval.scala b/tests/neg/null-anyval.scala index 82b4b9ad9433..df54c48bfd8a 100644 --- a/tests/neg/null-anyval.scala +++ b/tests/neg/null-anyval.scala @@ -1,4 +1,4 @@ -object Test: +object Test with val x: Int = 0 val y: Int | Null = x // during erasure, x is boxed here, and Int | Null becomes Object val z0: Int = identity(y) // error @@ -8,5 +8,5 @@ object Test: class StrWrapper(x: String) extends AnyVal val z3: StrWrapper = null // error val z4: O.T = null // error -object O: +object O with opaque type T = String diff --git a/tests/neg/override-erasure-clash.scala b/tests/neg/override-erasure-clash.scala index 688eb816afcc..6706004964c5 100644 --- a/tests/neg/override-erasure-clash.scala +++ b/tests/neg/override-erasure-clash.scala @@ -1,5 +1,5 @@ import annotation.targetName -class A: +class A with def f(): Int = 1 class B extends A: // error @targetName("f") def g(): Int = 2 diff --git a/tests/neg/override-inner-class.scala b/tests/neg/override-inner-class.scala index 4c4daaccb88a..5ff65519f5bd 100644 --- a/tests/neg/override-inner-class.scala +++ b/tests/neg/override-inner-class.scala @@ -1,5 +1,5 @@ -class C: +class C with type T >: String <: Any -class D extends C: +class D extends C with class T // error diff --git a/tests/neg/source-import.scala b/tests/neg/source-import.scala index 5cb7f532ea5c..5479f823d91a 100644 --- a/tests/neg/source-import.scala +++ b/tests/neg/source-import.scala @@ -1,6 +1,6 @@ import language.`3.0` import language.`3.0` // error -class C: +class C with import language.`3.0-migration` // error diff --git a/tests/neg/spaces-vs-tabs.scala b/tests/neg/spaces-vs-tabs.scala index ff8d1a1c328e..c4e8bee9ada8 100644 --- a/tests/neg/spaces-vs-tabs.scala +++ b/tests/neg/spaces-vs-tabs.scala @@ -1,4 +1,4 @@ -object Test: +object Test with if true then println(1) // ok @@ -7,7 +7,7 @@ object Test: println(4) // error else () // error - object Test2: + object Test2 with if true then 1 diff --git a/tests/neg/targetName-override-2.scala b/tests/neg/targetName-override-2.scala index 531efbfd931f..05b2071d3481 100644 --- a/tests/neg/targetName-override-2.scala +++ b/tests/neg/targetName-override-2.scala @@ -1,6 +1,6 @@ import annotation.targetName -class Alpha[T]: +class Alpha[T] with def foo() = 1 diff --git a/tests/neg/transparent-inline.scala b/tests/neg/transparent-inline.scala index a5158d9b8a27..be6b5ad65bab 100644 --- a/tests/neg/transparent-inline.scala +++ b/tests/neg/transparent-inline.scala @@ -1,6 +1,6 @@ transparent def bar: Any = 2 // error: transparent can be used only with inline -object test1: +object test1 with def x: Int = baz(true) // error: type mismatch inline def baz(x: Boolean): Any = @@ -9,7 +9,7 @@ object test1: if x then 1 else "" def y: Int = bam(true) // error: type mismatch -object test2: +object test2 with def x: 1 = baz(true) // OK transparent inline def baz(x: Boolean) = @@ -18,7 +18,7 @@ object test2: if x then 1 else "" def y: 1 = bam(true) // OK -object test3: +object test3 with def x: Int = baz(true) // error: type mismatch inline def baz(x: Boolean) = @@ -27,7 +27,7 @@ object test3: if x then 1 else "" def y: Int = bam(true) // error: type mismatch -object test4: +object test4 with def x: 1 = baz(true) // OK transparent inline def baz(x: Boolean): Any = diff --git a/tests/new/test.scala b/tests/new/test.scala index ac8f67d1530f..924334fca8e1 100644 --- a/tests/new/test.scala +++ b/tests/new/test.scala @@ -1,3 +1,2 @@ -object Test: - - def test = ??? +object Test with + val x = 1 diff --git a/tests/patmat/i10085.scala b/tests/patmat/i10085.scala index 314f4253cde8..ac8d2b448eaf 100644 --- a/tests/patmat/i10085.scala +++ b/tests/patmat/i10085.scala @@ -1,10 +1,10 @@ -enum Bool: +enum Bool with case True case False import Bool._ -enum SBool[B <: Bool]: +enum SBool[B <: Bool] with case STrue extends SBool[True.type] case SFalse extends SBool[False.type] diff --git a/tests/patmat/i8922.scala b/tests/patmat/i8922.scala index 946b1834998f..8fd616dbae58 100644 --- a/tests/patmat/i8922.scala +++ b/tests/patmat/i8922.scala @@ -1,6 +1,6 @@ case class Token(tokenType: TokenType, lexeme: String, line: Int) -enum TokenType: +enum TokenType with // Single-character tokens. case MINUS, PLUS, SLASH, STAR, @@ -14,7 +14,7 @@ enum Expr { case Binary(left: Expr, operator: Token, right: Expr) } -object Interpreter: +object Interpreter with import Expr._ import TokenType._ diff --git a/tests/patmat/i8922c.scala b/tests/patmat/i8922c.scala index 63d968c80345..b6c07e43828c 100644 --- a/tests/patmat/i8922c.scala +++ b/tests/patmat/i8922c.scala @@ -1,6 +1,6 @@ case class Token(tokenType: TokenType, lexeme: String, line: Int) -enum TokenType: +enum TokenType with // Single-character tokens. case MINUS, PLUS, SLASH, STAR, @@ -14,7 +14,7 @@ enum Expr { case Binary(left: Expr, operator: Token, right: Expr) } -object Interpreter: +object Interpreter with import Expr._ import TokenType._ diff --git a/tests/pending/pos/cps-async-failure.scala b/tests/pending/pos/cps-async-failure.scala index 9f8da4c7f8b8..6cb8d2482989 100644 --- a/tests/pending/pos/cps-async-failure.scala +++ b/tests/pending/pos/cps-async-failure.scala @@ -1,7 +1,7 @@ import scala.quoted._ -trait App[F[_],CT]: +trait App[F[_],CT] with this: Base[F,CT] => import quotes.reflect._ @@ -39,10 +39,10 @@ trait Base[F[_]:Type,CT:Type] // Both :Type context bounds are necessary for fa extends Cps with Root[F, CT] with App[F, CT]: implicit val qctx: Quotes -trait Root[F[_], CT]: +trait Root[F[_], CT] with this: Base[F, CT] => def runRoot(): CpsTree = ??? -trait Cps: +trait Cps with sealed abstract class CpsTree diff --git a/tests/pending/pos/inlinetuple.scala b/tests/pending/pos/inlinetuple.scala index ac457ebfa0d9..1fdb6abfd02f 100644 --- a/tests/pending/pos/inlinetuple.scala +++ b/tests/pending/pos/inlinetuple.scala @@ -1,6 +1,6 @@ // TODO: Ensure that this inlines properly. So far only // x._1 inlines, but not x._2. -object Test: +object Test with def g(x: Int, y: Int) = x + y inline def f(inline x: (Int, Int)) = g(x._1, x._2) diff --git a/tests/pos-custom-args/erased/i10848b.scala b/tests/pos-custom-args/erased/i10848b.scala index 71292b1b859c..bb808b6238f5 100644 --- a/tests/pos-custom-args/erased/i10848b.scala +++ b/tests/pos-custom-args/erased/i10848b.scala @@ -1,4 +1,4 @@ -class Foo: +class Foo with erased given Int = 1 def foo(using erased x: Int): Unit = () foo diff --git a/tests/pos-custom-args/semanticdb/inline-unapply/Macro_1.scala b/tests/pos-custom-args/semanticdb/inline-unapply/Macro_1.scala index dc431c14ef14..b15e2282961a 100644 --- a/tests/pos-custom-args/semanticdb/inline-unapply/Macro_1.scala +++ b/tests/pos-custom-args/semanticdb/inline-unapply/Macro_1.scala @@ -1,6 +1,6 @@ import scala.quoted._ -object Succ: +object Succ with inline def unapply(n: Int): Option[Int] = ${ impl('n) } diff --git a/tests/pos-macros/i10151/Macro_1.scala b/tests/pos-macros/i10151/Macro_1.scala index f5170c83da12..b2ee78a860fa 100644 --- a/tests/pos-macros/i10151/Macro_1.scala +++ b/tests/pos-macros/i10151/Macro_1.scala @@ -2,20 +2,20 @@ package x import scala.quoted._ -trait CB[T]: +trait CB[T] with def map[S](f: T=>S): CB[S] = ??? def flatMap[S](f: T=>CB[S]): CB[S] = ??? -class MyArr[AK,AV]: +class MyArr[AK,AV] with def map1[BK,BV](f: ((AK,AV)) => (BK, BV)):MyArr[BK,BV] = ??? def map1Out[BK, BV](f: ((AK,AV)) => CB[(BK,BV)]): CB[MyArr[BK,BV]] = ??? def await[T](x:CB[T]):T = ??? -object CBM: +object CBM with def pure[T](t:T):CB[T] = ??? -object X: +object X with inline def process[T](inline f:T) = ${ processImpl[T]('f) diff --git a/tests/pos-macros/i10211/Macro_1.scala b/tests/pos-macros/i10211/Macro_1.scala index ebf9b76ff77e..72fa30e47cc7 100644 --- a/tests/pos-macros/i10211/Macro_1.scala +++ b/tests/pos-macros/i10211/Macro_1.scala @@ -2,11 +2,11 @@ package x import scala.quoted._ -trait CB[T]: +trait CB[T] with def map[S](f: T=>S): CB[S] = ??? -class MyArr[A]: +class MyArr[A] with def map[B](f: A=>B):MyArr[B] = ??? def mapOut[B](f: A=> CB[B]): CB[MyArr[B]] = ??? def flatMap[B](f: A=>MyArr[B]):MyArr[B] = ??? @@ -15,7 +15,7 @@ class MyArr[A]: def withFilterOut(p: A=>CB[Boolean]): DelayedWithFilter[A] = ??? def map2[B](f: A=>B):MyArr[B] = ??? -class DelayedWithFilter[A]: +class DelayedWithFilter[A] with def map[B](f: A=>B):MyArr[B] = ??? def mapOut[B](f: A=> CB[B]): CB[MyArr[B]] = ??? def flatMap[B](f: A=>MyArr[B]):MyArr[B] = ??? @@ -25,11 +25,11 @@ class DelayedWithFilter[A]: def await[T](x:CB[T]):T = ??? -object CBM: +object CBM with def pure[T](t:T):CB[T] = ??? def map[T,S](a:CB[T])(f:T=>S):CB[S] = ??? -object X: +object X with inline def process[T](inline f:T) = ${ processImpl[T]('f) diff --git a/tests/pos-macros/i10771/MacroA_1.scala b/tests/pos-macros/i10771/MacroA_1.scala index 88da14fe31ac..22b5be9e22c6 100644 --- a/tests/pos-macros/i10771/MacroA_1.scala +++ b/tests/pos-macros/i10771/MacroA_1.scala @@ -2,7 +2,7 @@ import scala.quoted._ case class MyQuoted(val ast: String, runtimeQuotes: List[String]) -object MyQuoteMacro: +object MyQuoteMacro with inline def myquote: MyQuoted = ${ MyQuoteMacro.apply } def apply(using Quotes): Expr[MyQuoted] = '{ MyQuoted("p", ${Expr.ofList(List( '{ "foo" } ))}) } diff --git a/tests/pos-macros/i10771/MacroB_1.scala b/tests/pos-macros/i10771/MacroB_1.scala index e9bfe73fb1a2..4eb1566461dd 100644 --- a/tests/pos-macros/i10771/MacroB_1.scala +++ b/tests/pos-macros/i10771/MacroB_1.scala @@ -1,6 +1,6 @@ import scala.quoted._ -object PullAst: +object PullAst with def applyImpl(quoted: Expr[MyQuoted])(using qctx: Quotes): Expr[String] = '{ $quoted.ast.toString } inline def apply(inline quoted: MyQuoted): String = diff --git a/tests/pos-macros/i10771/Test_2.scala b/tests/pos-macros/i10771/Test_2.scala index 7777454cfc36..30203c7cf9e2 100644 --- a/tests/pos-macros/i10771/Test_2.scala +++ b/tests/pos-macros/i10771/Test_2.scala @@ -1,3 +1,3 @@ -object Test: +object Test with def main(args: Array[String]): Unit = println( PullAst.apply( MyQuoteMacro.myquote ) ) diff --git a/tests/pos-macros/i10910/Macro_1.scala b/tests/pos-macros/i10910/Macro_1.scala index ae5643b1a9ea..ccb32baa03d7 100644 --- a/tests/pos-macros/i10910/Macro_1.scala +++ b/tests/pos-macros/i10910/Macro_1.scala @@ -2,15 +2,15 @@ package x import scala.quoted._ -trait CB[T]: +trait CB[T] with def map[S](f: T=>S): CB[S] = ??? def await[T](x:CB[T]):T = ??? -object CBM: +object CBM with def pure[T](t:T):CB[T] = ??? -object X: +object X with inline def process[T](inline f:T) = ${ processImpl[T]('f) diff --git a/tests/pos-macros/i8325/Macro_1.scala b/tests/pos-macros/i8325/Macro_1.scala index b3f14e80157c..037d995f23d7 100644 --- a/tests/pos-macros/i8325/Macro_1.scala +++ b/tests/pos-macros/i8325/Macro_1.scala @@ -3,7 +3,7 @@ package a import scala.quoted._ -object A: +object A with inline def transform[A](inline expr: A): A = ${ transformImplExpr('expr) diff --git a/tests/pos-macros/i8325b/Macro_1.scala b/tests/pos-macros/i8325b/Macro_1.scala index aa4255f6f3a0..70808b82c8d7 100644 --- a/tests/pos-macros/i8325b/Macro_1.scala +++ b/tests/pos-macros/i8325b/Macro_1.scala @@ -3,7 +3,7 @@ package a import scala.quoted._ -object A: +object A with inline def transform[A](inline expr: A): A = ${ transformImplExpr('expr) diff --git a/tests/pos-macros/i9812.scala b/tests/pos-macros/i9812.scala index e09db34fea2a..0764a1eeb827 100644 --- a/tests/pos-macros/i9812.scala +++ b/tests/pos-macros/i9812.scala @@ -2,7 +2,7 @@ import quoted._ sealed abstract class SomeEnum -object SomeEnum: +object SomeEnum with final val Foo = new SomeEnum {} def quoteFoo: Quotes ?=> Expr[SomeEnum.Foo.type] = '{SomeEnum.Foo} diff --git a/tests/pos-macros/i9894/Macro_1.scala b/tests/pos-macros/i9894/Macro_1.scala index 7135cb6a7029..aa0e902ba300 100644 --- a/tests/pos-macros/i9894/Macro_1.scala +++ b/tests/pos-macros/i9894/Macro_1.scala @@ -2,19 +2,19 @@ package x import scala.quoted._ -trait CB[T]: +trait CB[T] with def map[S](f: T=>S): CB[S] = ??? -class MyArr[A]: +class MyArr[A] with def map1[B](f: A=>B):MyArr[B] = ??? def map1Out[B](f: A=> CB[B]): CB[MyArr[B]] = ??? def await[T](x:CB[T]):T = ??? -object CBM: +object CBM with def pure[T](t:T):CB[T] = ??? -object X: +object X with inline def process[T](inline f:T) = ${ processImpl[T]('f) diff --git a/tests/pos-macros/nil-liftable.scala b/tests/pos-macros/nil-liftable.scala index 490291bc48f7..2771baff7078 100644 --- a/tests/pos-macros/nil-liftable.scala +++ b/tests/pos-macros/nil-liftable.scala @@ -1,6 +1,6 @@ import scala.quoted._ -class Test: +class Test with given NilToExpr: ToExpr[Nil.type] with { def apply(xs: Nil.type)(using Quotes): Expr[Nil.type] = '{ Nil } diff --git a/tests/pos-macros/quote-aliases.scala b/tests/pos-macros/quote-aliases.scala index e6c0e50593fb..50b1b1b4566f 100644 --- a/tests/pos-macros/quote-aliases.scala +++ b/tests/pos-macros/quote-aliases.scala @@ -1,6 +1,6 @@ import scala.quoted._ -object Test: +object Test with def f1(using Quotes)(t: quotes.reflect.Tree): Unit = () diff --git a/tests/pos-special/fatal-warnings/i10259.scala b/tests/pos-special/fatal-warnings/i10259.scala index 5b4c628cd126..a089814cce80 100644 --- a/tests/pos-special/fatal-warnings/i10259.scala +++ b/tests/pos-special/fatal-warnings/i10259.scala @@ -1,4 +1,4 @@ -trait S[T] extends (T => T): +trait S[T] extends (T => T) with def apply(x: T) = ??? extension (x: T) def show: String diff --git a/tests/pos-special/fatal-warnings/i9260.scala b/tests/pos-special/fatal-warnings/i9260.scala index df548f393eea..a930a0b803a0 100644 --- a/tests/pos-special/fatal-warnings/i9260.scala +++ b/tests/pos-special/fatal-warnings/i9260.scala @@ -1,14 +1,14 @@ package asts -enum Ast[-T >: Null]: +enum Ast[-T >: Null] with case DefDef() -trait AstImpl[T >: Null]: +trait AstImpl[T >: Null] with type Ast = asts.Ast[T] type DefDef = Ast.DefDef[T] end AstImpl -object untpd extends AstImpl[Null]: +object untpd extends AstImpl[Null] with def DefDef(ast: Ast): DefDef = ast match case ast: DefDef => ast diff --git a/tests/pos-special/fatal-warnings/patmat-exhaustive.scala b/tests/pos-special/fatal-warnings/patmat-exhaustive.scala index c5c95c455b8c..796ada8a13a8 100644 --- a/tests/pos-special/fatal-warnings/patmat-exhaustive.scala +++ b/tests/pos-special/fatal-warnings/patmat-exhaustive.scala @@ -1,5 +1,5 @@ def foo: Unit = - object O: + object O with sealed abstract class A class B extends O.A class C extends O.A diff --git a/tests/pos-special/fatal-warnings/type-test-matchable.scala b/tests/pos-special/fatal-warnings/type-test-matchable.scala index 5becee6f2e9f..8e1acaa6dc44 100644 --- a/tests/pos-special/fatal-warnings/type-test-matchable.scala +++ b/tests/pos-special/fatal-warnings/type-test-matchable.scala @@ -1,13 +1,13 @@ import scala.language.`3.1-migration` import scala.reflect.TypeTest -trait Foo: +trait Foo with type X type Y <: X def x: X given TypeTest[X, Y] = ??? -object Test: +object Test with def test(foo: Foo): Unit = foo.x match case x: foo.Y => diff --git a/tests/pos-special/i7296.scala b/tests/pos-special/i7296.scala index 3b582ad284b8..6811c80d7e77 100644 --- a/tests/pos-special/i7296.scala +++ b/tests/pos-special/i7296.scala @@ -1,2 +1,2 @@ -class Foo: +class Foo with private var blah: Double = 0L \ No newline at end of file diff --git a/tests/pos-special/indent-colons.scala b/tests/pos-special/indent-colons.scala index 44fe09b39cd4..e5b712ef2e77 100644 --- a/tests/pos-special/indent-colons.scala +++ b/tests/pos-special/indent-colons.scala @@ -1,4 +1,4 @@ -object Test: +object Test with locally: var x = 0 @@ -56,26 +56,26 @@ object Test: x < 10 do () -class Test2: +class Test2 with self => def foo = 1 val x = - new Test2: + new Test2 with override def foo = 2 end new end x end Test2 -class Test3: +class Test3 with self => def foo = 1 import collection.mutable.HashMap -class Coder(words: List[String]): +class Coder(words: List[String]) with - class Foo: + class Foo with println() end Foo @@ -114,5 +114,5 @@ class Coder(words: List[String]): case (digit, str) => str map (ltr => ltr -> digit) end Coder -object Test22: +object Test22 with def foo: Int = 22 \ No newline at end of file diff --git a/tests/pos-special/notNull.scala b/tests/pos-special/notNull.scala index 11a506d8184d..bcc0154b0a80 100644 --- a/tests/pos-special/notNull.scala +++ b/tests/pos-special/notNull.scala @@ -1,4 +1,4 @@ -object Test: +object Test with def notNull[A](x: A | Null): x.type & A = assert(x != null) x.asInstanceOf // TODO: drop the .asInstanceOf when explicit nulls are implemented diff --git a/tests/pos-special/sourcepath/outer/nested/indent1.scala b/tests/pos-special/sourcepath/outer/nested/indent1.scala index cba9ddddece1..0b2d74832f28 100644 --- a/tests/pos-special/sourcepath/outer/nested/indent1.scala +++ b/tests/pos-special/sourcepath/outer/nested/indent1.scala @@ -1,8 +1,8 @@ package outer package nested -object indent1: - object inner: +object indent1 with + object inner with def x: Int = 1 end inner val y: Int = 2 diff --git a/tests/pos/abstract-inline-val.scala b/tests/pos/abstract-inline-val.scala index 6ea95eea5151..ccf2ebd6ff60 100644 --- a/tests/pos/abstract-inline-val.scala +++ b/tests/pos/abstract-inline-val.scala @@ -1,11 +1,11 @@ -trait C: +trait C with inline def x: Int inline val y: Int -class C1 extends C: +class C1 extends C with inline val x = 1 inline val y = 2 -class C2 extends C: +class C2 extends C with inline def x = 3 inline val y = 4 diff --git a/tests/pos/consume.scala b/tests/pos/consume.scala index d17638bb84a0..41965b522682 100644 --- a/tests/pos/consume.scala +++ b/tests/pos/consume.scala @@ -1,4 +1,4 @@ -object Test1: +object Test1 with def consume(xs: List[Int], limit: Int): List[Int] = xs match case x :: xs1 if limit > 0 => consume(xs1, limit - x) case _ => xs @@ -16,18 +16,18 @@ object Test2 { } } -object math3: - trait Ord[T]: +object math3 with + trait Ord[T] with extension (x: T) def > (t: T): Boolean = ??? extension (x: T) def <= (t: T): Boolean = ??? - trait Numeric[T] extends Ord[T]: + trait Numeric[T] extends Ord[T] with extension (x: T) def + (y: T): T = ??? extension (x: T) def - (y: T): T = ??? extension (x: Int) def numeric: T = ??? end math3 -object Test3: +object Test3 with import math3.Numeric import collection.immutable.Seq diff --git a/tests/pos/end-nested.scala b/tests/pos/end-nested.scala index 38e8cce6c8a9..96c25c2b1ea2 100644 --- a/tests/pos/end-nested.scala +++ b/tests/pos/end-nested.scala @@ -3,7 +3,7 @@ def f[T](x: Option[T]) = x match case None => end f -object Test: +object Test with try List(1, 2, 3) match case x :: xs => println(x) case Nil => println("Nil") diff --git a/tests/pos/endmarkers.scala b/tests/pos/endmarkers.scala index 5b85ce3763cd..13c3b92912b7 100644 --- a/tests/pos/endmarkers.scala +++ b/tests/pos/endmarkers.scala @@ -1,5 +1,5 @@ -trait T: - object O: +trait T with + object O with def foo = 1 end foo @@ -13,7 +13,7 @@ end T package p1.p2: - abstract class C(): + abstract class C() with def this(x: Int) = this() @@ -42,9 +42,9 @@ package p1.p2: def f: String end C - object C: + object C with given C = - new C: + new C with def f = "!" end f end new diff --git a/tests/pos/enum-companion-first.scala b/tests/pos/enum-companion-first.scala index d4c1eb370031..014066fb43f4 100644 --- a/tests/pos/enum-companion-first.scala +++ b/tests/pos/enum-companion-first.scala @@ -1,7 +1,7 @@ -object Planet: +object Planet with final val G = 6.67300E-11 -enum Planet(mass: Double, radius: Double) extends Enum[Planet]: +enum Planet(mass: Double, radius: Double) extends Enum[Planet] with def surfaceGravity = Planet.G * mass / (radius * radius) def surfaceWeight(otherMass: Double) = otherMass * surfaceGravity diff --git a/tests/pos/enum-variance.scala b/tests/pos/enum-variance.scala index 82fa5bdf91a0..ca13c44d7a3f 100644 --- a/tests/pos/enum-variance.scala +++ b/tests/pos/enum-variance.scala @@ -1,14 +1,14 @@ class Animal class Dog extends Animal -enum Opt[+T]: +enum Opt[+T] with case Sm(t: T) case None val smDog: Opt.Sm[Dog] = new Opt.Sm(Dog()) val smAnimal: Opt.Sm[Animal] = smDog -enum Show[-T]: +enum Show[-T] with case Refl(op: T => String) def show(t: T): String = this match diff --git a/tests/pos/enum-widen.scala b/tests/pos/enum-widen.scala index 32bbcf9a3242..8fb4e8707da1 100644 --- a/tests/pos/enum-widen.scala +++ b/tests/pos/enum-widen.scala @@ -1,6 +1,6 @@ -object test: +object test with - enum Option[+T]: + enum Option[+T] with case Some[T](x: T) extends Option[T] case None @@ -13,7 +13,7 @@ object test: x = None xc = None - enum Nat: + enum Nat with case Z case S[N <: Z.type | S[_]](pred: N) import Nat._ diff --git a/tests/pos/extmethods.scala b/tests/pos/extmethods.scala index 368b4f439916..b8bc0f25dea6 100644 --- a/tests/pos/extmethods.scala +++ b/tests/pos/extmethods.scala @@ -32,7 +32,7 @@ val y1: List[Int] = y val z = (1 :: Nil).concat(Nil) val z1: List[Int] = z -trait TT: +trait TT with type A val m: A def f[B <: A](x: B): A = if ??? then m else x @@ -40,7 +40,7 @@ trait TT: extension (x: TT) def foo[B <: x.A](y: B) = x.f(y) -object CC extends TT: +object CC extends TT with type A = Seq[Int] val m = Nil diff --git a/tests/pos/i10080.scala b/tests/pos/i10080.scala index 81146e18ed82..15ca51e93a42 100644 --- a/tests/pos/i10080.scala +++ b/tests/pos/i10080.scala @@ -1,4 +1,4 @@ -trait Foo: +trait Foo with end Foo trait Bar diff --git a/tests/pos/i10082.scala b/tests/pos/i10082.scala index a1dc6160788e..5c989ecceffe 100644 --- a/tests/pos/i10082.scala +++ b/tests/pos/i10082.scala @@ -1,4 +1,4 @@ -object Kotlin: +object Kotlin with def it[T](using t: T) = t def fun[T, U](fn: T ?=> U)(x: T): U = fn(using x) diff --git a/tests/pos/i10253.scala b/tests/pos/i10253.scala index 15f872c59be0..aedd93ce45dd 100644 --- a/tests/pos/i10253.scala +++ b/tests/pos/i10253.scala @@ -1,9 +1,9 @@ -object test: +object test with def foo(qc: QC): Unit = object treeMap extends qc.reflect.TreeMap -trait QC: +trait QC with val reflect: Reflection - trait Reflection: - trait TreeMap: + trait Reflection with + trait TreeMap with def transformTree: Unit = ??? \ No newline at end of file diff --git a/tests/pos/i10295.scala b/tests/pos/i10295.scala index 8fc237e2e853..a100cca18cf8 100644 --- a/tests/pos/i10295.scala +++ b/tests/pos/i10295.scala @@ -1,6 +1,6 @@ -trait M: +trait M with type X - object X: + object X with def foo(): X = ??? inline def m(using m: M): m.type = m diff --git a/tests/pos/i10311.scala b/tests/pos/i10311.scala index bfa0c15f3493..c89083446405 100644 --- a/tests/pos/i10311.scala +++ b/tests/pos/i10311.scala @@ -7,7 +7,7 @@ object Module { extension (self: MyInt) def y: Int = self.y } } -object test: +object test with import Module._ val a = new MyInt(42, 43) diff --git a/tests/pos/i10495.scala b/tests/pos/i10495.scala index 931e5fe73f72..9eb2bb9b4976 100644 --- a/tests/pos/i10495.scala +++ b/tests/pos/i10495.scala @@ -1,7 +1,7 @@ -class Foo: +class Foo with extension(x: String) def run: Unit = ??? -object Bar extends Foo: +object Bar extends Foo with def run(v: Int): Unit = ??? "ABC".run // Failed before: Reference to run is ambiguous... diff --git a/tests/pos/i10634/BasicSupport.scala b/tests/pos/i10634/BasicSupport.scala index cf4ae7190ce4..0e4f0fa31a82 100644 --- a/tests/pos/i10634/BasicSupport.scala +++ b/tests/pos/i10634/BasicSupport.scala @@ -1,5 +1,5 @@ // BasicSupport.scala -trait BasicSupport: +trait BasicSupport with self: Parser => object SymOps extends SymOps[ctx.type](ctx) diff --git a/tests/pos/i10634/Context.scala b/tests/pos/i10634/Context.scala index 0e22fd29d17d..76ae72ae3f6b 100644 --- a/tests/pos/i10634/Context.scala +++ b/tests/pos/i10634/Context.scala @@ -1,8 +1,8 @@ // Context.scala -trait Context: +trait Context with type Symbol -trait SymOps[C <: Context](val c: C): +trait SymOps[C <: Context](val c: C) with extension (sym: c.Symbol) def getVisibility(): Int = 0 diff --git a/tests/pos/i10951.scala b/tests/pos/i10951.scala index 2520536a491c..fd71ca59c073 100644 --- a/tests/pos/i10951.scala +++ b/tests/pos/i10951.scala @@ -1,6 +1,6 @@ import scala.language.dynamics -object Dyn extends Dynamic: +object Dyn extends Dynamic with def selectDynamic[T](name: String): Option[T] = None val a: Option[(Int, Int)] = Dyn.asdf[Tuple2[Int, Int]] diff --git a/tests/pos/i11081.scala b/tests/pos/i11081.scala index cd333d7e407d..d77f56505d7b 100644 --- a/tests/pos/i11081.scala +++ b/tests/pos/i11081.scala @@ -1,6 +1,6 @@ -enum Outer: +enum Outer with case Foo -object Outer: +object Outer with trait Bar case class Baz(bar: Bar) case class Bam(bar: Bar = new Bar() {}) diff --git a/tests/pos/i4561.scala b/tests/pos/i4561.scala index 5a51cb668a37..a0791313633a 100644 --- a/tests/pos/i4561.scala +++ b/tests/pos/i4561.scala @@ -1,6 +1,6 @@ -object abc: +object abc with trait Test0 - trait Test1[T]: + trait Test1[T] with def apply(f: T => T): Unit def apply(s: String): Unit diff --git a/tests/pos/i6375.scala b/tests/pos/i6375.scala index aa682483b52d..4df662e3c1ec 100644 --- a/tests/pos/i6375.scala +++ b/tests/pos/i6375.scala @@ -28,7 +28,7 @@ } } */ -class Test: +class Test with given Int = 0 def f(): Int ?=> Boolean = true : (Int ?=> Boolean) diff --git a/tests/pos/i6734.scala b/tests/pos/i6734.scala index fa7d9946ada4..904b36aa9e9b 100644 --- a/tests/pos/i6734.scala +++ b/tests/pos/i6734.scala @@ -1,4 +1,4 @@ -object Bug: +object Bug with extension [A, B, Z](ab: (A, B)) def pipe2(f: (A, B) => Z): Z = f(ab._1, ab._2) diff --git a/tests/pos/i6900.scala b/tests/pos/i6900.scala index 55587a18b4ba..75999b25e7ec 100644 --- a/tests/pos/i6900.scala +++ b/tests/pos/i6900.scala @@ -1,15 +1,15 @@ object Test1 { - trait Foo[A]: + trait Foo[A] with def foo[C]: C => A // Works with old-style conversion - implicit def i2f[A](a: A): Foo[A] = new Foo[A]: + implicit def i2f[A](a: A): Foo[A] = new Foo[A] with def foo[C]: C => A = _ => a // But not with newstyle /* given [A]: Conversion[A, Foo[A]] with - def apply(a: A) = new Foo[A]: + def apply(a: A) = new Foo[A] with def foo[C]: C => A = _ => a */ diff --git a/tests/pos/i6938.scala b/tests/pos/i6938.scala index e58ab2829cf9..706aee5d3c1d 100644 --- a/tests/pos/i6938.scala +++ b/tests/pos/i6938.scala @@ -1,5 +1,5 @@ trait Foo[T] -object Foo: +object Foo with given [T]: Foo[Tuple1[T]] with {} given [T, U]: Foo[(T, U)] with {} given [T, U, V]: Foo[(T, U, V)] with {} \ No newline at end of file diff --git a/tests/pos/i7217.scala b/tests/pos/i7217.scala index 1c2a92c731b7..2a3c3f64fa6a 100644 --- a/tests/pos/i7217.scala +++ b/tests/pos/i7217.scala @@ -1,4 +1,4 @@ -class Foo(p1: String, p2: String): +class Foo(p1: String, p2: String) with def this(p1: String) = this(p1, "blah") val x = { Foo("blah", "hah") } diff --git a/tests/pos/i7359.scala b/tests/pos/i7359.scala index 697b20b23cd0..97908254e99d 100644 --- a/tests/pos/i7359.scala +++ b/tests/pos/i7359.scala @@ -1,95 +1,95 @@ package test -trait ObjectInterface: +trait ObjectInterface with def equals(obj: Any): Boolean def hashCode(): Int def toString(): String -trait SAMPlain: +trait SAMPlain with def first(): String -trait SAMPlainWithOverriddenObjectMethods: +trait SAMPlainWithOverriddenObjectMethods with def first(): String def equals(obj: Any): Boolean def hashCode(): Int def toString(): String -trait SAMPlainWithExtends extends ObjectInterface: +trait SAMPlainWithExtends extends ObjectInterface with def first(): String -trait SAMPlainWithExtendsAndOverride extends ObjectInterface: +trait SAMPlainWithExtendsAndOverride extends ObjectInterface with def first(): String override def equals(obj: Any): Boolean override def hashCode(): Int override def toString(): String -trait SAMPlainCovariantOut[+O]: +trait SAMPlainCovariantOut[+O] with def first(): O -trait SAMCovariantOut[+O]: +trait SAMCovariantOut[+O] with def first(): O def equals(obj: Any): Boolean def hashCode(): Int def toString(): String -trait SAMCovariantOutExtends[+O] extends ObjectInterface: +trait SAMCovariantOutExtends[+O] extends ObjectInterface with def first(): O -trait SAMCovariantOutExtendsAndOverride[+O] extends ObjectInterface: +trait SAMCovariantOutExtendsAndOverride[+O] extends ObjectInterface with def first(): O override def equals(obj: Any): Boolean override def hashCode(): Int override def toString(): String -trait SAMPlainContravariantIn[-I]: +trait SAMPlainContravariantIn[-I] with def first(in: I): Unit -trait SAMContravariantIn[-I]: +trait SAMContravariantIn[-I] with def first(in: I): Unit def equals(obj: Any): Boolean def hashCode(): Int def toString(): String -trait SAMContravariantInExtends[-I] extends ObjectInterface: +trait SAMContravariantInExtends[-I] extends ObjectInterface with def first(in: I): Unit -trait SAMContravariantInExtendsAndOverride[-I] extends ObjectInterface: +trait SAMContravariantInExtendsAndOverride[-I] extends ObjectInterface with def first(in: I): Unit override def equals(obj: Any): Boolean override def hashCode(): Int override def toString(): String -trait SAMPlainInvariant[T]: +trait SAMPlainInvariant[T] with def first(in: T): T -trait SAMInvariant[T]: +trait SAMInvariant[T] with def first(in: T): T def equals(obj: Any): Boolean def hashCode(): Int def toString(): String -trait SAMInvariantExtends[T] extends ObjectInterface: +trait SAMInvariantExtends[T] extends ObjectInterface with def first(in: T): T -trait SAMInvariantExtendsAndOverride[T] extends ObjectInterface: +trait SAMInvariantExtendsAndOverride[T] extends ObjectInterface with def first(in: T): T override def equals(obj: Any): Boolean override def hashCode(): Int override def toString(): String -trait SAMPlainInOut[-I, +O]: +trait SAMPlainInOut[-I, +O] with def first(in: I): O -trait SAMInOut[-I, +O]: +trait SAMInOut[-I, +O] with def first(in: I): O def equals(obj: Any): Boolean def hashCode(): Int def toString(): String -trait SAMInOutExtends[-I, +O] extends ObjectInterface: +trait SAMInOutExtends[-I, +O] extends ObjectInterface with def first(in: I): O -trait SAMInOutExtendsAndOverride[-I, +O] extends ObjectInterface: +trait SAMInOutExtendsAndOverride[-I, +O] extends ObjectInterface with def first(in: I): O override def equals(obj: Any): Boolean override def hashCode(): Int @@ -99,13 +99,13 @@ type CustomString = String type CustomBoolean = Boolean type CustomInt = Int -trait SAMWithCustomAliases: +trait SAMWithCustomAliases with def first(): String def equals(obj: Any): CustomBoolean def hashCode(): CustomInt def toString(): CustomString -object Main: +object Main with def main(args: Array[String]) = val samPlain : SAMPlain = () => "Hello, World!" val samPlainWithOverriddenObjectMethods: SAMPlainWithOverriddenObjectMethods = () => "Hello, World!" diff --git a/tests/pos/i7375.scala b/tests/pos/i7375.scala index 9da548f99ce7..96bdd0b41b50 100644 --- a/tests/pos/i7375.scala +++ b/tests/pos/i7375.scala @@ -1,10 +1,10 @@ -trait Entity[M, T, P]: +trait Entity[M, T, P] with extension (me: M) def receive(sender: T)(msg: P)(using Entity[T, M, P]): Unit extension (me: M) def name(): String class GreetingPerson(private val name: String) -object GreetingPerson: +object GreetingPerson with given GreetingPersonEntity: Entity[GreetingPerson, GreetedPerson, String] with extension (me: GreetingPerson) def receive(sender: GreetedPerson)(msg: String)(using Entity[GreetedPerson, GreetingPerson, String]): Unit = println(f"Thanks for saying $msg, ${sender.name()}") @@ -14,7 +14,7 @@ object GreetingPerson: class GreetedPerson(private val name: String) -object GreetedPerson: +object GreetedPerson with given GreetedPersonEntity: Entity[GreetedPerson, GreetingPerson, String] with extension (me: GreetedPerson) def receive(sender: GreetingPerson)(msg: String)(using Entity[GreetingPerson, GreetedPerson, String]): Unit = println(f"Thanks for saying $msg, ${sender.name()}") diff --git a/tests/pos/i7413.scala b/tests/pos/i7413.scala index ebc0c5b2777a..5b04cee445cf 100644 --- a/tests/pos/i7413.scala +++ b/tests/pos/i7413.scala @@ -2,20 +2,20 @@ import scala.language.implicitConversions trait Fixture[A] extends Conversion[0, A] -trait TestFramework[A]: +trait TestFramework[A] with extension (testName: String) def in(test: Fixture[A] ?=> Unit): Unit = ??? -trait Greeter: +trait Greeter with def greet(name: String): String = s"Hello $name" case class MyFixture(name: String, greeter: Greeter) -object Test1: +object Test1 with given conv: Conversion[0, Greeter] with def apply(x: 0): Greeter = ??? val g: Greeter = 0 -class MyTest extends TestFramework[MyFixture]: +class MyTest extends TestFramework[MyFixture] with "say hello" in { assert(0.greeter.greet(0.name) == s"Hello ${0.name}") } diff --git a/tests/pos/i7428.scala b/tests/pos/i7428.scala index b702c7146cc5..e1ab2ffd91e8 100644 --- a/tests/pos/i7428.scala +++ b/tests/pos/i7428.scala @@ -1,5 +1,5 @@ -class ABug: - enum Tag: +class ABug with + enum Tag with case first import Tag.first val xx = first diff --git a/tests/pos/i7648.scala b/tests/pos/i7648.scala index 12e4a025f859..13dd1376c9e5 100644 --- a/tests/pos/i7648.scala +++ b/tests/pos/i7648.scala @@ -11,7 +11,7 @@ class Stream[+F[_], +A] { } } -object Test: +object Test with implicit val ioMonad: Monad[IO] = null diff --git a/tests/pos/i7700.scala b/tests/pos/i7700.scala index fdcfc23c9105..56151dc5554c 100644 --- a/tests/pos/i7700.scala +++ b/tests/pos/i7700.scala @@ -1,12 +1,12 @@ package test -trait Show[-A]: +trait Show[-A] with def show(a: A): String -object Macros: +object Macros with extension (sc: StringContext) inline def show(args: =>Any*): String = ??? -object Show: +object Show with extension [A] (a: A) def show(using S: Show[A]): String = S.show(a) export Macros.show \ No newline at end of file diff --git a/tests/pos/i7757.scala b/tests/pos/i7757.scala index cebd6fc3ad84..f1c7b2b48122 100644 --- a/tests/pos/i7757.scala +++ b/tests/pos/i7757.scala @@ -1,7 +1,7 @@ val m: Map[Int, String] = ??? val _ = m.map((a, b) => a + b.length) -trait Foo: +trait Foo with def g(f: ((Int, Int)) => Int): Int = 1 def g(f: ((Int, Int)) => (Int, Int)): String = "2" diff --git a/tests/pos/i7793.scala b/tests/pos/i7793.scala index 3458315c48c5..f0c394208a07 100644 --- a/tests/pos/i7793.scala +++ b/tests/pos/i7793.scala @@ -1,4 +1,4 @@ -trait Foo: +trait Foo with def g(f: Int => Int): Int = 1 def g(using String)(f: Int => String): String = "2" diff --git a/tests/pos/i7807.scala b/tests/pos/i7807.scala index df8a41ddcf8d..36193f26a972 100644 --- a/tests/pos/i7807.scala +++ b/tests/pos/i7807.scala @@ -1,4 +1,4 @@ -object Test: +object Test with def flip: (x: 0 | 1) => x.type match { case 0 => 1 case 1 => 0 } = ??? diff --git a/tests/pos/i8181.scala b/tests/pos/i8181.scala index d36214c3068a..5afdf5950ba4 100644 --- a/tests/pos/i8181.scala +++ b/tests/pos/i8181.scala @@ -1,4 +1,4 @@ -object Main: +object Main with def main(args: Array[String]): Unit = extension (a: AnyRef) def putout(): Unit = println(a) diff --git a/tests/pos/i8182.scala b/tests/pos/i8182.scala index 9acf2941c570..8679ad224ec1 100644 --- a/tests/pos/i8182.scala +++ b/tests/pos/i8182.scala @@ -1,6 +1,6 @@ package example -trait Show[-A]: +trait Show[-A] with extension (a: A) def show: String given (using rec: Show[String]): Show[String] = ??? // must be Show[String] as the argument diff --git a/tests/pos/i8319.scala b/tests/pos/i8319.scala index d08ba85e7115..412d33260be1 100644 --- a/tests/pos/i8319.scala +++ b/tests/pos/i8319.scala @@ -5,7 +5,7 @@ case class Lam[T,U]() extends Tree[Any] case class App[T,U]() extends Tree[Any] case class Var() extends Tree[Any] -object Branch: +object Branch with def unapply(branch: Lam[?,?] | App[?,?]): true = true private def foo(s: Option[Tree[?]]) = s match // seems to only occur in a nested pattern diff --git a/tests/pos/i8397.scala b/tests/pos/i8397.scala index d0b97f84129d..e0e126d60687 100644 --- a/tests/pos/i8397.scala +++ b/tests/pos/i8397.scala @@ -3,13 +3,13 @@ given foo(using x: Int): AnyRef with // #7859 -trait Lub2[A, B]: +trait Lub2[A, B] with type Output given [A <: C, B <: C, C]: Lub2[A, B] with type Output = C -trait Lub[Union]: +trait Lub[Union] with type Output given [A]: Lub[A] with diff --git a/tests/pos/i8530.scala b/tests/pos/i8530.scala index 2eab9f9e74c8..e0b1963cb7bc 100644 --- a/tests/pos/i8530.scala +++ b/tests/pos/i8530.scala @@ -1,19 +1,19 @@ -object MyBoooleanUnapply: +object MyBoooleanUnapply with inline def unapply(x: Int): Boolean = true -object MyOptionUnapply: +object MyOptionUnapply with inline def unapply(x: Int): Option[Long] = Some(x) -object MyUnapplyImplicits: +object MyUnapplyImplicits with inline def unapply(x: Int)(using DummyImplicit): Option[Long] = Some(x) -object MyPolyUnapply: +object MyPolyUnapply with inline def unapply[T](x: T): Option[T] = Some(x) -object MySeqUnapply: +object MySeqUnapply with inline def unapplySeq(x: Int): Seq[Int] = Seq(x, x) -object MyWhiteboxUnapply: +object MyWhiteboxUnapply with transparent inline def unapply(x: Int): Option[Any] = Some(x) def test: Unit = diff --git a/tests/pos/i8623.scala b/tests/pos/i8623.scala index e0df48811e1c..3f505ca54f47 100644 --- a/tests/pos/i8623.scala +++ b/tests/pos/i8623.scala @@ -1,6 +1,6 @@ -trait QC: - object tasty: +trait QC with + object tasty with type Tree extension (tree: Tree) def pos: Tree = ??? diff --git a/tests/pos/i8750.scala b/tests/pos/i8750.scala index a88cfb51acd2..5fb9c68a8d75 100644 --- a/tests/pos/i8750.scala +++ b/tests/pos/i8750.scala @@ -1,4 +1,4 @@ -class Abc: +class Abc with opaque type Log = Double val v : Abc = new Abc \ No newline at end of file diff --git a/tests/pos/i8801.scala b/tests/pos/i8801.scala index f925a60dbfe3..2b122340e3a7 100644 --- a/tests/pos/i8801.scala +++ b/tests/pos/i8801.scala @@ -1,4 +1,4 @@ -object Foo: +object Foo with locally { case class Baz() } diff --git a/tests/pos/i8843.scala b/tests/pos/i8843.scala index d6744d4096f5..aac14dfa838b 100644 --- a/tests/pos/i8843.scala +++ b/tests/pos/i8843.scala @@ -1,4 +1,4 @@ -class C: +class C with type X <: Tuple inline def f(c: C): Unit = { diff --git a/tests/pos/i8845.scala b/tests/pos/i8845.scala index 52e41cbc9605..c30fa6b51e8e 100644 --- a/tests/pos/i8845.scala +++ b/tests/pos/i8845.scala @@ -1,4 +1,4 @@ -trait IntToLong: +trait IntToLong with def apply(v: Int) : Long inline def convert1( f: IntToLong) = ??? diff --git a/tests/pos/i8874.scala b/tests/pos/i8874.scala index cc19ee330ac0..a458e5c2ddc6 100644 --- a/tests/pos/i8874.scala +++ b/tests/pos/i8874.scala @@ -1,4 +1,4 @@ -trait Abc: +trait Abc with opaque type Log = Double class AbcClass extends Abc diff --git a/tests/pos/i8892.scala b/tests/pos/i8892.scala index f08b12341d3b..6763e8fdc895 100644 --- a/tests/pos/i8892.scala +++ b/tests/pos/i8892.scala @@ -1,7 +1,7 @@ -trait Reporter: +trait Reporter with def report(m: String): Unit -class Dummy extends Reporter: +class Dummy extends Reporter with def report(m: String) = () object ABug { diff --git a/tests/pos/i8920/Qu_1.scala b/tests/pos/i8920/Qu_1.scala index c0ddfdcaae8e..08c6e3e90ffa 100644 --- a/tests/pos/i8920/Qu_1.scala +++ b/tests/pos/i8920/Qu_1.scala @@ -1,9 +1,9 @@ package scala.collection.mutable -class Qu[A] protected (array: Array[AnyRef], start: Int, end: Int): +class Qu[A] protected (array: Array[AnyRef], start: Int, end: Int) with def this(initialSize: Int = ArrayDeque.DefaultInitialSize) = this(ArrayDeque.alloc(initialSize), start = 0, end = 0) -object Qu: +object Qu with def f[A](array: Array[AnyRef], start: Int, end: Int) = 1 def f[A](initialSize: Int = 1) = 2 diff --git a/tests/pos/i8927.scala b/tests/pos/i8927.scala index 2dfb419abab3..1cf45c0045fa 100644 --- a/tests/pos/i8927.scala +++ b/tests/pos/i8927.scala @@ -1,14 +1,14 @@ import scala.language.implicitConversions -trait Eq[k <: AnyKind, K[_ <: k]]: +trait Eq[k <: AnyKind, K[_ <: k]] with extension [A <: k, B <: k](k: K[A]) def isEq (k2: K[B]): Eq.GEQ[k, K, A, B] -object Eq: - enum GEQ[k <: AnyKind, K[_ <: k], A <: k, B <: k]: +object Eq with + enum GEQ[k <: AnyKind, K[_ <: k], A <: k, B <: k] with case Y[k <: AnyKind, K[_ <: k], A <: k](res: K[A]) extends GEQ[k, K, A, A] case N() -sealed trait DPair[k <: AnyKind, K[_ <: k], +V[_ <: k]]: +sealed trait DPair[k <: AnyKind, K[_ <: k], +V[_ <: k]] with type A <: k val key: K[A] val value: V[A] @@ -16,8 +16,8 @@ sealed trait DPair[k <: AnyKind, K[_ <: k], +V[_ <: k]]: case y: Eq.GEQ.Y[k, K, A] => Some(value) case _ => None -object DPair: +object DPair with given pair [k, K[_ <: k], V[_ <: k], C <: k]: Conversion[(K[C], V[C]), DPair[k, K, V]] = tup => - case class dpair(key: K[C], value: V[C]) extends DPair[k, K, V]: + case class dpair(key: K[C], value: V[C]) extends DPair[k, K, V] with type A = C dpair(tup._1, tup._2) diff --git a/tests/pos/i8968.scala b/tests/pos/i8968.scala index ac76dd5ca56c..915eb2681561 100644 --- a/tests/pos/i8968.scala +++ b/tests/pos/i8968.scala @@ -1,7 +1,7 @@ -object Foo: +object Foo with inline def get = 0 -object Bar: +object Bar with export Foo._ val v = Bar.get diff --git a/tests/pos/i8972.scala b/tests/pos/i8972.scala index e4678718aa4f..ffa003d65424 100644 --- a/tests/pos/i8972.scala +++ b/tests/pos/i8972.scala @@ -1,7 +1,7 @@ -trait Num: +trait Num with type Nat -object IsInt: +object IsInt with def unapply(using num: Num)(sc: num.Nat): Option[Int] = ??? def test(using num: Num)(x: num.Nat) = diff --git a/tests/pos/i8997.scala b/tests/pos/i8997.scala index 4a34902b97c4..9e5fba6a77cf 100644 --- a/tests/pos/i8997.scala +++ b/tests/pos/i8997.scala @@ -1,4 +1,4 @@ -object Foo: +object Foo with def unapply(n: Int)(using x: DummyImplicit)(using y: Int): Option[Int] = ??? def test = diff --git a/tests/pos/i9052/A.scala b/tests/pos/i9052/A.scala index 1ff6fa0df82e..cc24250c7c91 100644 --- a/tests/pos/i9052/A.scala +++ b/tests/pos/i9052/A.scala @@ -1,4 +1,4 @@ -object impl: +object impl with case object UNone import impl._ diff --git a/tests/pos/i9069/Wrapper.scala b/tests/pos/i9069/Wrapper.scala index 1c3952b683e1..f25c128a5f4c 100644 --- a/tests/pos/i9069/Wrapper.scala +++ b/tests/pos/i9069/Wrapper.scala @@ -1,4 +1,4 @@ sealed trait Foo -object Foo: +object Foo with case object Baz extends Foo case class Bar(x: Int) extends Foo diff --git a/tests/pos/i9103.scala b/tests/pos/i9103.scala index c33eb8166201..e84d194d299f 100644 --- a/tests/pos/i9103.scala +++ b/tests/pos/i9103.scala @@ -1,4 +1,4 @@ -object a: +object a with trait Foo[T] given Foo[Unit] = ??? diff --git a/tests/pos/i9213.scala b/tests/pos/i9213.scala index 1a6488c4c0fb..e8fc2a862292 100644 --- a/tests/pos/i9213.scala +++ b/tests/pos/i9213.scala @@ -1,5 +1,5 @@ trait A(a: Any, b: Int) -trait B(a: Any, b: Int): +trait B(a: Any, b: Int) with var x = 0 class C(a: String, b: Int) diff --git a/tests/pos/i9307.scala b/tests/pos/i9307.scala index a795f1d3fc62..4b5f7fae1708 100644 --- a/tests/pos/i9307.scala +++ b/tests/pos/i9307.scala @@ -1,4 +1,4 @@ -class Foo: +class Foo with private var foo1: Int = _ private var foo2: Array[Int] = _ private[this] var foo3: Array[Int] = _ diff --git a/tests/pos/i9342b.scala b/tests/pos/i9342b.scala index e317391f9bb8..39e224d528e0 100644 --- a/tests/pos/i9342b.scala +++ b/tests/pos/i9342b.scala @@ -1,4 +1,4 @@ -trait Label[A]: +trait Label[A] with def apply(v: A): String given [A]: Label[A] = _.toString diff --git a/tests/pos/i9342c.scala b/tests/pos/i9342c.scala index eed9d45326f1..27efc0baabdc 100644 --- a/tests/pos/i9342c.scala +++ b/tests/pos/i9342c.scala @@ -1,4 +1,4 @@ -trait Label[A]: +trait Label[A] with def apply(v: A): String def g[A]: Label[A] = _.toString diff --git a/tests/pos/i9352.scala b/tests/pos/i9352.scala index db757b48b027..ee45cdebee2a 100644 --- a/tests/pos/i9352.scala +++ b/tests/pos/i9352.scala @@ -1,6 +1,6 @@ abstract class Foo[B] extends Bar[B] -trait Bar[A]: +trait Bar[A] with self: Foo[A] => def foo : Unit = bar(???) diff --git a/tests/pos/i9457.scala b/tests/pos/i9457.scala index c210e3dc92ff..32550e351ebb 100644 --- a/tests/pos/i9457.scala +++ b/tests/pos/i9457.scala @@ -1,4 +1,4 @@ -object inlinetuple: +object inlinetuple with def test: Int = f((1, 2)) inline def f(inline p: (Int, Int)): Int = diff --git a/tests/pos/i9464.scala b/tests/pos/i9464.scala index 56cef7aedff8..d0a94ed3dd9f 100644 --- a/tests/pos/i9464.scala +++ b/tests/pos/i9464.scala @@ -1,4 +1,4 @@ -trait T: +trait T with type X def x: X diff --git a/tests/pos/i9530.scala b/tests/pos/i9530.scala index 32b2f26dbd6c..aa5e0d1b04e0 100644 --- a/tests/pos/i9530.scala +++ b/tests/pos/i9530.scala @@ -1,12 +1,12 @@ trait Food case class Banana(color: String) extends Food -trait Diet[A <: Animal]: +trait Diet[A <: Animal] with type F <: Food def food: Seq[F] trait Animal -object Animal: +object Animal with extension [A <: Animal](using diet: Diet[A])(animal: A) def food1 = diet.food extension [A <: Animal](animal: A)(using diet: Diet[A]) def food2 = diet.food diff --git a/tests/pos/i9562.scala b/tests/pos/i9562.scala index 9f58ff309d3c..a1cd86a2993b 100644 --- a/tests/pos/i9562.scala +++ b/tests/pos/i9562.scala @@ -1,7 +1,7 @@ -class Foo: +class Foo with def foo = 23 -object Unrelated: +object Unrelated with extension (f: Foo) def g = f.foo // OK diff --git a/tests/pos/i9844.scala b/tests/pos/i9844.scala index a660c5046c5b..f4c2427fde90 100644 --- a/tests/pos/i9844.scala +++ b/tests/pos/i9844.scala @@ -1,4 +1,4 @@ -object test1: +object test1 with trait Foo[A] trait Baz[A] { @@ -8,13 +8,13 @@ object test1: } } -object test2: +object test2 with - trait Foo: + trait Foo with private var f = "abc" trait Baz { - trait Bam: + trait Bam with val f = 0 trait Bar extends Bam { this: Foo => @@ -23,7 +23,7 @@ object test2: } } -object test3: +object test3 with object DetSkipOctree { sealed trait Leaf [PL] sealed trait Branch[PL] diff --git a/tests/pos/i9967.scala b/tests/pos/i9967.scala index 4e915a27bfbf..0b506d5323df 100644 --- a/tests/pos/i9967.scala +++ b/tests/pos/i9967.scala @@ -1,6 +1,6 @@ import collection.mutable -class MaxSizeMap[K, V](maxSize: Int)(using o: Ordering[K]): +class MaxSizeMap[K, V](maxSize: Int)(using o: Ordering[K]) with val sortedMap: mutable.TreeMap[K, V] = mutable.TreeMap.empty[K, V](o) export sortedMap._ diff --git a/tests/pos/i9994.scala b/tests/pos/i9994.scala index d2125fe07df9..d94e5d4d8f77 100644 --- a/tests/pos/i9994.scala +++ b/tests/pos/i9994.scala @@ -1,7 +1,7 @@ package pkg -trait Foo: +trait Foo with def foo: this.type -final class Bar extends Foo: +final class Bar extends Foo with def foo: this.type = this diff --git a/tests/pos/indent.scala b/tests/pos/indent.scala index 03502a26fe79..c6289884980a 100644 --- a/tests/pos/indent.scala +++ b/tests/pos/indent.scala @@ -1,4 +1,4 @@ -object Test: +object Test with locally { var x = 0 @@ -82,7 +82,7 @@ object Test: x < 10 do () -class Test2: +class Test2 with self => def foo(x: Int) = if x < 0 then throw @@ -97,15 +97,15 @@ class Test2: end x end Test2 -class Test3: +class Test3 with self => def foo = 1 import collection.mutable.HashMap -class Coder(words: List[String]): +class Coder(words: List[String]) with - class Foo: + class Foo with println() end Foo @@ -146,5 +146,5 @@ class Coder(words: List[String]): } end Coder -object Test22: +object Test22 with def foo: Int = 22 \ No newline at end of file diff --git a/tests/pos/indent2.scala b/tests/pos/indent2.scala index bbe07dae959a..6df51b51cf81 100644 --- a/tests/pos/indent2.scala +++ b/tests/pos/indent2.scala @@ -1,6 +1,6 @@ -object testindent: +object testindent with - class C: + class C with val x = 0 val c = new C diff --git a/tests/pos/indent4.scala b/tests/pos/indent4.scala index fa80b62d7db4..ee76ea84186c 100644 --- a/tests/pos/indent4.scala +++ b/tests/pos/indent4.scala @@ -1,4 +1,4 @@ -object testindent: +object testindent with if (true) val x = 1 diff --git a/tests/pos/inline-val-constValue-1.scala b/tests/pos/inline-val-constValue-1.scala index efd482cd5c09..f9cec9f466ad 100644 --- a/tests/pos/inline-val-constValue-1.scala +++ b/tests/pos/inline-val-constValue-1.scala @@ -1,6 +1,6 @@ import compiletime._ -class C: +class C with type X <: Tuple def test: Unit = diff --git a/tests/pos/inline-val-constValue-2.scala b/tests/pos/inline-val-constValue-2.scala index 33ae23069fa2..2ff62a31d34f 100644 --- a/tests/pos/inline-val-constValue-2.scala +++ b/tests/pos/inline-val-constValue-2.scala @@ -1,6 +1,6 @@ import compiletime._ -class C: +class C with type N <: Int def test: Unit = diff --git a/tests/pos/main-method-scheme-class-based.scala b/tests/pos/main-method-scheme-class-based.scala index 86393d05c953..41b51432afe6 100644 --- a/tests/pos/main-method-scheme-class-based.scala +++ b/tests/pos/main-method-scheme-class-based.scala @@ -11,7 +11,7 @@ import collection.mutable * or `command.argsGetter` if is a final varargs parameter, * - a call to `command.run` with the closure of user-main applied to all arguments. */ -trait MainAnnotation extends StaticAnnotation: +trait MainAnnotation extends StaticAnnotation with /** The class used for argument string parsing. E.g. `scala.util.CommandLineParser.FromString`, * but could be something else @@ -25,7 +25,7 @@ trait MainAnnotation extends StaticAnnotation: def command(args: Array[String]): Command /** A class representing a command to run */ - abstract class Command: + abstract class Command with /** The getter for the next argument of type `T` */ def argGetter[T](argName: String, fromString: ArgumentParser[T], defaultValue: Option[T] = None): () => T @@ -42,12 +42,12 @@ end MainAnnotation //Sample main class, can be freely implemented: -class main extends MainAnnotation: +class main extends MainAnnotation with type ArgumentParser[T] = util.CommandLineParser.FromString[T] type MainResultType = Any - def command(args: Array[String]): Command = new Command: + def command(args: Array[String]): Command = new Command with /** A buffer of demanded argument names, plus * "?" if it has a default @@ -135,7 +135,7 @@ end main // Sample main method -object myProgram: +object myProgram with /** Adds two numbers */ @main def add(num: Int, inc: Int = 1): Unit = @@ -145,7 +145,7 @@ end myProgram // Compiler generated code: -object add extends main: +object add extends main with def main(args: Array[String]) = val cmd = command(args) val arg1 = cmd.argGetter[Int]("num", summon[ArgumentParser[Int]]) diff --git a/tests/pos/main-method-scheme.scala b/tests/pos/main-method-scheme.scala index c65f7c928efd..df6ec31692d2 100644 --- a/tests/pos/main-method-scheme.scala +++ b/tests/pos/main-method-scheme.scala @@ -1,7 +1,7 @@ import annotation.StaticAnnotation import collection.mutable -trait MainAnnotation extends StaticAnnotation: +trait MainAnnotation extends StaticAnnotation with type ArgumentParser[T] @@ -18,7 +18,7 @@ end MainAnnotation //Sample main class, can be freely implemented: -class main(progName: String, args: Array[String], docComment: String) extends MainAnnotation: +class main(progName: String, args: Array[String], docComment: String) extends MainAnnotation with def this() = this("", Array(), "") @@ -106,7 +106,7 @@ end main // Sample main method -object myProgram: +object myProgram with /** Adds two numbers */ @main def add(num: Int, inc: Int = 1) = @@ -116,7 +116,7 @@ end myProgram // Compiler generated code: -object add: +object add with def main(args: Array[String]) = val cmd = new main("add", args, "Adds two numbers") val arg1 = cmd.getArg[Int]("num", summon[cmd.ArgumentParser[Int]]) diff --git a/tests/pos/matches.scala b/tests/pos/matches.scala index 7b590d5bb422..3f724dbef756 100644 --- a/tests/pos/matches.scala +++ b/tests/pos/matches.scala @@ -1,5 +1,5 @@ package matches -object Test: +object Test with 2 min 3 match case 2 => "OK" case 3 => "?" diff --git a/tests/pos/matrixOps.scala b/tests/pos/matrixOps.scala index ab96a09389a5..44fc5bc2052d 100644 --- a/tests/pos/matrixOps.scala +++ b/tests/pos/matrixOps.scala @@ -1,4 +1,4 @@ -object Test: +object Test with type Matrix = Array[Array[Double]] type Vector = Array[Double] diff --git a/tests/pos/opaques-queue.scala b/tests/pos/opaques-queue.scala index 079ef7fde4f6..b03b9c8e0210 100644 --- a/tests/pos/opaques-queue.scala +++ b/tests/pos/opaques-queue.scala @@ -1,11 +1,11 @@ class Elem -trait QueueSignature: +trait QueueSignature with type Queue def empty: Queue def append(q: Queue, e: Elem): Queue def pop(q: Queue): Option[(Elem, Queue)] val QueueModule: QueueSignature = - object QueueImpl extends QueueSignature: + object QueueImpl extends QueueSignature with type Queue = (List[Elem], List[Elem]) def empty = (Nil, Nil) def append(q: Queue, e: Elem): Queue = (q._1, e :: q._2) @@ -15,7 +15,7 @@ val QueueModule: QueueSignature = case (Nil, ys) => pop((ys.reverse, Nil)) QueueImpl -object queues: +object queues with opaque type Queue = (List[Elem], List[Elem]) def empty = (Nil, Nil) def append(q: Queue, e: Elem): Queue = (q._1, e :: q._2) diff --git a/tests/pos/packagings.scala b/tests/pos/packagings.scala index 47e1df204b34..96ce1a66e34c 100644 --- a/tests/pos/packagings.scala +++ b/tests/pos/packagings.scala @@ -1,10 +1,10 @@ package foo: package bar: - object A: + object A with def foo = 1 end bar end foo package baz: - object B: + object B with def f = foo.bar.A.foo end baz diff --git a/tests/pos/postconditions.scala b/tests/pos/postconditions.scala index 90117c17b207..c492231d517f 100644 --- a/tests/pos/postconditions.scala +++ b/tests/pos/postconditions.scala @@ -1,4 +1,4 @@ -object PostConditions: +object PostConditions with opaque type WrappedResult[T] = T def result[T](using r: WrappedResult[T]): T = r @@ -8,6 +8,6 @@ object PostConditions: assert(condition) x -object Test: +object Test with import PostConditions.{ensuring, result} val s = List(1, 2, 3).sum.ensuring(result == 6) diff --git a/tests/pos/reference/adts.scala b/tests/pos/reference/adts.scala index 41ea6660638e..e93bb843f97c 100644 --- a/tests/pos/reference/adts.scala +++ b/tests/pos/reference/adts.scala @@ -1,25 +1,25 @@ package adts -object t1: +object t1 with - enum Option[+T]: + enum Option[+T] with case Some[T](x: T) extends Option[T] case None -object t2: +object t2 with - enum Option[+T]: + enum Option[+T] with case Some[T](x: T) extends Option[T] case None extends Option[Nothing] -enum Color(val rgb: Int): +enum Color(val rgb: Int) with case Red extends Color(0xFF0000) case Green extends Color(0x00FF00) case Blue extends Color(0x0000FF) case Mix(mix: Int) extends Color(mix) -object t3: +object t3 with - enum Option[+T]: + enum Option[+T] with case Some[T](x: T) extends Option[T] case None @@ -27,6 +27,6 @@ object t3: case None => false case some => true - object Option: + object Option with def apply[T >: Null](x: T): Option[T] = if (x == null) None else Some(x) diff --git a/tests/pos/reference/auto-param-tupling.scala b/tests/pos/reference/auto-param-tupling.scala index c32173867fe6..c2dd9889fa98 100644 --- a/tests/pos/reference/auto-param-tupling.scala +++ b/tests/pos/reference/auto-param-tupling.scala @@ -1,6 +1,6 @@ package autoParamTupling -object t1: +object t1 with val xs: List[(Int, Int)] = ??? xs.map { diff --git a/tests/pos/reference/compile-time.scala b/tests/pos/reference/compile-time.scala index 32ea7660c898..119d16f51718 100644 --- a/tests/pos/reference/compile-time.scala +++ b/tests/pos/reference/compile-time.scala @@ -1,6 +1,6 @@ package compiletime -class Test: +class Test with import scala.compiletime.{constValue, erasedValue, S} trait Nat diff --git a/tests/pos/reference/delegate-match.scala b/tests/pos/reference/delegate-match.scala index 3ab00cc46701..bf026b2d4ea8 100644 --- a/tests/pos/reference/delegate-match.scala +++ b/tests/pos/reference/delegate-match.scala @@ -1,6 +1,6 @@ package implicitmatch -class Test extends App: +class Test extends App with import scala.collection.immutable.{TreeSet, HashSet} import scala.compiletime.summonFrom diff --git a/tests/pos/reference/delegates.scala b/tests/pos/reference/delegates.scala index 88002d939330..35bd6ebdddff 100644 --- a/tests/pos/reference/delegates.scala +++ b/tests/pos/reference/delegates.scala @@ -1,30 +1,30 @@ -class Common: +class Common with - trait Ord[T]: + trait Ord[T] with extension (x: T) def compareTo(y: T): Int extension (x: T) def < (y: T) = x.compareTo(y) < 0 extension (x: T) def > (y: T) = x.compareTo(y) > 0 - trait Convertible[From, To]: + trait Convertible[From, To] with extension (x: From) def convert: To - trait SemiGroup[T]: + trait SemiGroup[T] with extension (x: T) def combine(y: T): T - trait Monoid[T] extends SemiGroup[T]: + trait Monoid[T] extends SemiGroup[T] with def unit: T - trait Functor[F[_]]: + trait Functor[F[_]] with extension [A](x: F[A]) def map[B](f: A => B): F[B] - trait Monad[F[_]] extends Functor[F]: + trait Monad[F[_]] extends Functor[F] with extension [A](x: F[A]) def flatMap[B](f: A => F[B]): F[B] extension [A](x: F[A]) def map[B](f: A => B) = x.flatMap(f `andThen` pure) def pure[A](x: A): F[A] end Common -object Instances extends Common: +object Instances extends Common with given intOrd: Ord[Int] with extension (x: Int) def compareTo(y: Int) = @@ -64,7 +64,7 @@ object Instances extends Common: def maximum[T](xs: List[T])(using Ord[T]): T = xs.reduceLeft((x, y) => if (x < y) y else x) - def descending[T](using asc: Ord[T]): Ord[T] = new Ord[T]: + def descending[T](using asc: Ord[T]): Ord[T] = new Ord[T] with extension (x: T) def compareTo(y: T) = asc.compareTo(y)(x) def minimum[T](xs: List[T])(using Ord[T]) = @@ -85,20 +85,20 @@ object Instances extends Common: class B val ab: (x: A, y: B) ?=> Int = (a: A, b: B) ?=> 22 - trait TastyAPI: + trait TastyAPI with type Symbol - trait SymDeco: + trait SymDeco with extension (sym: Symbol) def name: String given symDeco: SymDeco - object TastyImpl extends TastyAPI: + object TastyImpl extends TastyAPI with type Symbol = String given symDeco: SymDeco with extension (sym: Symbol) def name = sym class D[T] - class C(using ctx: Context): + class C(using ctx: Context) with def f() = locally { given Context = this.ctx @@ -121,14 +121,14 @@ object Instances extends Common: class Token(str: String) - object Token: + object Token with given StringToToken: Conversion[String, Token] with def apply(str: String): Token = new Token(str) val x: Token = "if" end Instances -object PostConditions: +object PostConditions with opaque type WrappedResult[T] = T def result[T](using x: WrappedResult[T]): T = x @@ -139,7 +139,7 @@ object PostConditions: x end PostConditions -object AnonymousInstances extends Common: +object AnonymousInstances extends Common with given Ord[Int] with extension (x: Int) def compareTo(y: Int) = if (x < y) -1 else if (x > y) +1 else 0 @@ -173,12 +173,12 @@ object AnonymousInstances extends Common: xs.foldLeft(summon[Monoid[T]].unit)(_.combine(_)) end AnonymousInstances -object Implicits extends Common: - implicit object IntOrd extends Ord[Int]: +object Implicits extends Common with + implicit object IntOrd extends Ord[Int] with extension (x: Int) def compareTo(y: Int) = if (x < y) -1 else if (x > y) +1 else 0 - class ListOrd[T: Ord] extends Ord[List[T]]: + class ListOrd[T: Ord] extends Ord[List[T]] with extension (xs: List[T]) def compareTo(ys: List[T]): Int = (xs, ys).match case (Nil, Nil) => 0 case (Nil, _) => -1 @@ -199,31 +199,31 @@ object Implicits extends Common: (implicit cmp: Ord[T]): T = xs.reduceLeft((x, y) => if (x < y) y else x) - def descending[T](implicit asc: Ord[T]): Ord[T] = new Ord[T]: + def descending[T](implicit asc: Ord[T]): Ord[T] = new Ord[T] with extension (x: T) def compareTo(y: T) = asc.compareTo(y)(x) def minimum[T](xs: List[T])(implicit cmp: Ord[T]) = maximum(xs)(descending) -object Test extends App: +object Test extends App with Instances.test() import PostConditions.{result, ensuring} val s = List(1, 2, 3).sum s.ensuring(result == 6) end Test -object Completions: +object Completions with class Future[T] class HttpResponse class StatusCode // The argument "magnet" type - enum CompletionArg: + enum CompletionArg with case Error(s: String) case Response(f: Future[HttpResponse]) case Status(code: Future[StatusCode]) - object CompletionArg: + object CompletionArg with // conversions defining the possible arguments to pass to `complete` // these always come with CompletionArg diff --git a/tests/pos/reference/extension-methods.scala b/tests/pos/reference/extension-methods.scala index daa187cafa50..15c8da3f6586 100644 --- a/tests/pos/reference/extension-methods.scala +++ b/tests/pos/reference/extension-methods.scala @@ -1,4 +1,4 @@ -object ExtMethods: +object ExtMethods with case class Circle(x: Double, y: Double, radius: Double) @@ -44,7 +44,7 @@ object ExtMethods: val limit = smallest(n).max xs.zipWithIndex.collect { case (x, i) if x <= limit => i } - trait IntOps: + trait IntOps with extension (i: Int) def isZero: Boolean = i == 0 extension (i: Int) def safeMod(x: Int): Option[Int] = @@ -53,13 +53,13 @@ object ExtMethods: else Some(i % x) end IntOps - object IntOpsEx extends IntOps: + object IntOpsEx extends IntOps with extension (i: Int) def safeDiv(x: Int): Option[Int] = // extension method brought into scope via inheritance from IntOps if x.isZero then None else Some(i / x) - trait SafeDiv: + trait SafeDiv with import IntOpsEx._ // brings safeDiv and safeMod into scope extension (i: Int) def divide(d: Int) : Option[(Int, Int)] = @@ -73,19 +73,19 @@ object ExtMethods: given ops1: IntOps with {} // brings safeMod into scope 1.safeMod(2) - class Lst[T](xs: T*): + class Lst[T](xs: T*) with private val elems = xs.toList def foldLeft[U](x: U)(op: (U, T) => U): U = elems.foldLeft(x)(op) def ++ (other: Lst[T]): Lst[T] = Lst(elems ++ other.elems: _*) - trait Ord[T]: + trait Ord[T] with extension (x: T) def less (y: T): Boolean - object Ord: + object Ord with given Ord[Int] with extension (x: Int) def less (y: Int): Boolean = x < y end Ord - object Lst: + object Lst with extension [T](xs: Lst[Lst[T]]) def flatten: Lst[T] = xs.foldLeft(Lst())(_ ++ _) @@ -110,7 +110,7 @@ object ExtMethods: if n < s.length && s(n) != ch then position(ch, n + 1) else n - object DoubleOps: + object DoubleOps with extension (x: Double) def ** (exponent: Int): Double = require(exponent > 0) if exponent == 0 then 1 else x * (x ** (exponent - 1)) diff --git a/tests/pos/reference/structural-closeable.scala b/tests/pos/reference/structural-closeable.scala index 771a6ae4ebc8..c396555ac6ab 100644 --- a/tests/pos/reference/structural-closeable.scala +++ b/tests/pos/reference/structural-closeable.scala @@ -2,10 +2,10 @@ type Closeable = { def close(): Unit } -class FileInputStream: +class FileInputStream with def close(): Unit = () -class Channel: +class Channel with def close(): Unit = () import scala.reflect.Selectable.reflectiveSelectable diff --git a/tests/pos/single-case.scala b/tests/pos/single-case.scala index 2552f05129a6..82466ec31733 100644 --- a/tests/pos/single-case.scala +++ b/tests/pos/single-case.scala @@ -1,4 +1,4 @@ -object test: +object test with try println("hi") diff --git a/tests/pos/targetName-infer-result.scala b/tests/pos/targetName-infer-result.scala index 7e732395a483..42da8d36b457 100644 --- a/tests/pos/targetName-infer-result.scala +++ b/tests/pos/targetName-infer-result.scala @@ -1,23 +1,23 @@ import annotation.targetName -enum Tree: +enum Tree with case Bind(sym: Symbol, body: Tree) class Symbol -object Test1: - abstract class TreeAccumulator[X]: +object Test1 with + abstract class TreeAccumulator[X] with def app(x: X, tree: Tree): X def app(x: X, trees: List[Tree]): X = ??? - val acc = new TreeAccumulator[List[Symbol]]: + val acc = new TreeAccumulator[List[Symbol]] with def app(syms: List[Symbol], tree: Tree) = tree match case Tree.Bind(sym, body) => app(sym :: syms, body) -object Test2: - abstract class TreeAccumulator[X]: +object Test2 with + abstract class TreeAccumulator[X] with @targetName("apply") def app(x: X, tree: Tree): X def app(x: X, trees: List[Tree]): X = ??? - val acc = new TreeAccumulator[List[Symbol]]: + val acc = new TreeAccumulator[List[Symbol]] with @targetName("apply") def app(syms: List[Symbol], tree: Tree) = tree match case Tree.Bind(sym, body) => app(sym :: syms, body) diff --git a/tests/pos/targetName-override.scala b/tests/pos/targetName-override.scala index a15ce5594a76..202f0a272ca5 100644 --- a/tests/pos/targetName-override.scala +++ b/tests/pos/targetName-override.scala @@ -1,11 +1,11 @@ import scala.annotation.targetName -class A: +class A with @targetName("ff") def f(x: => Int): Int = x def f(x: => String): Int = x.length -class B extends A: +class B extends A with @targetName("ff") override def f(x: => Int): Int = x // OK override def f(x: => String): Int = x.length // OK diff --git a/tests/pos/targetName-refine.scala b/tests/pos/targetName-refine.scala index eaa02b8b7976..ae6206a18de0 100644 --- a/tests/pos/targetName-refine.scala +++ b/tests/pos/targetName-refine.scala @@ -1,7 +1,7 @@ import annotation.targetName -trait T: +trait T with @targetName("f2") def f: Any -class C extends T: +class C extends T with @targetName("f2") def f: Int = 1 val x: T { def f: Int } = C() diff --git a/tests/pos/tasty-tags-obscure.scala b/tests/pos/tasty-tags-obscure.scala index cd883ee0aeba..8a73d714272e 100644 --- a/tests/pos/tasty-tags-obscure.scala +++ b/tests/pos/tasty-tags-obscure.scala @@ -1,15 +1,15 @@ -object ObscureTasty: +object ObscureTasty with def foo(f: [t] => List[t] ?=> Unit) = ??? def test1 = foo([t] => (a: List[t]) ?=> ()) // POLYtype => GIVENMETHODType def bar(f: [t] => List[t] => Unit) = ??? def test2 = bar([t] => (a: List[t]) => ()) // POLYtype => METHODType - class Bar: + class Bar with final val bar = "Bar.bar" - class Foo extends Bar: - object A: + class Foo extends Bar with + object A with def unapply(a: Any): Some[Foo.super.bar.type] = ??? def foo = diff --git a/tests/pos/typeclass-encoding3.scala b/tests/pos/typeclass-encoding3.scala index 363826d2d6bd..7ae34427acb9 100644 --- a/tests/pos/typeclass-encoding3.scala +++ b/tests/pos/typeclass-encoding3.scala @@ -45,7 +45,7 @@ object Test { class Str(val s: String) extends Monoid def combine(that: Str): Str = new Str(this.s + that.s) - object Str: + object Str with def unit = "" extension for String : Monoid diff --git a/tests/pos/widen-union.scala b/tests/pos/widen-union.scala index b0b64f0dc6c6..6cd2e7787660 100644 --- a/tests/pos/widen-union.scala +++ b/tests/pos/widen-union.scala @@ -1,10 +1,10 @@ -object Test1: +object Test1 with val x: Int | String = 1 val y = x val z: Int | String = y -object Test2: +object Test2 with type Sig = Int | String def consistent(x: Sig, y: Sig): Boolean = ???// x == y @@ -12,7 +12,7 @@ object Test2: xs.corresponds(ys)(consistent) // OK || xs.corresponds(ys)(consistent(_, _)) // error, found: Any, required: Int | String -object Test3: +object Test3 with def g[X](x: X | String): Int = ??? def y: Boolean | String = ??? diff --git a/tests/run-custom-args/tasty-inspector/i10359.scala b/tests/run-custom-args/tasty-inspector/i10359.scala index b724d0431b4a..c2c9dad128a0 100644 --- a/tests/run-custom-args/tasty-inspector/i10359.scala +++ b/tests/run-custom-args/tasty-inspector/i10359.scala @@ -33,7 +33,7 @@ object Test { } } -class TestInspector() extends TastyInspector: +class TestInspector() extends TastyInspector with protected def processCompilationUnit(using Quotes)(root: quotes.reflect.Tree): Unit = import quotes.reflect._ diff --git a/tests/run-custom-args/tasty-inspector/i8163.scala b/tests/run-custom-args/tasty-inspector/i8163.scala index 2ac769b321f1..e2bfba37aede 100644 --- a/tests/run-custom-args/tasty-inspector/i8163.scala +++ b/tests/run-custom-args/tasty-inspector/i8163.scala @@ -20,7 +20,7 @@ object Test { } } -class TestInspector() extends TastyInspector: +class TestInspector() extends TastyInspector with protected def processCompilationUnit(using Quotes)(root: quotes.reflect.Tree): Unit = inspectClass(root) diff --git a/tests/run-custom-args/tasty-inspector/i8460.scala b/tests/run-custom-args/tasty-inspector/i8460.scala index 4f2d9ba6df44..4e1c590cbf11 100644 --- a/tests/run-custom-args/tasty-inspector/i8460.scala +++ b/tests/run-custom-args/tasty-inspector/i8460.scala @@ -33,7 +33,7 @@ object Test { } } -class TestInspector_Children() extends TastyInspector: +class TestInspector_Children() extends TastyInspector with var kids: List[String] = Nil diff --git a/tests/run-custom-args/tasty-inspector/i9970.scala b/tests/run-custom-args/tasty-inspector/i9970.scala index fc76ea5e0fb5..6bf79569cbfd 100644 --- a/tests/run-custom-args/tasty-inspector/i9970.scala +++ b/tests/run-custom-args/tasty-inspector/i9970.scala @@ -46,7 +46,7 @@ object Test { // Inspector that performs the actual tests -class TestInspector() extends TastyInspector: +class TestInspector() extends TastyInspector with private var foundIOApp: Boolean = false private var foundSimple: Boolean = false diff --git a/tests/run-macros/BigFloat/BigFloatFromDigitsImpl_1.scala b/tests/run-macros/BigFloat/BigFloatFromDigitsImpl_1.scala index d77cf6334f2f..324a583aead3 100644 --- a/tests/run-macros/BigFloat/BigFloatFromDigitsImpl_1.scala +++ b/tests/run-macros/BigFloat/BigFloatFromDigitsImpl_1.scala @@ -3,7 +3,7 @@ import language.experimental.genericNumberLiterals import scala.util.FromDigits import scala.quoted._ -object BigFloatFromDigitsImpl: +object BigFloatFromDigitsImpl with def apply(digits: Expr[String])(using Quotes): Expr[BigFloat] = digits.value match case Some(ds) => diff --git a/tests/run-macros/enum-nat-macro/Macros_2.scala b/tests/run-macros/enum-nat-macro/Macros_2.scala index 19339ef403e8..d92878e1443f 100644 --- a/tests/run-macros/enum-nat-macro/Macros_2.scala +++ b/tests/run-macros/enum-nat-macro/Macros_2.scala @@ -4,7 +4,7 @@ import Nat._ inline def ZeroMacro: Zero.type = ${ Macros.natZero } transparent inline def toNatMacro(inline int: Int): Nat = ${ Macros.toNatImpl('int) } - object Macros: + object Macros with import quoted._ def toIntImpl(nat: Expr[Nat])(using Quotes): Expr[Int] = diff --git a/tests/run-macros/enum-nat-macro/Nat_1.scala b/tests/run-macros/enum-nat-macro/Nat_1.scala index fbb209698469..14733b4b57e2 100644 --- a/tests/run-macros/enum-nat-macro/Nat_1.scala +++ b/tests/run-macros/enum-nat-macro/Nat_1.scala @@ -1,3 +1,3 @@ -enum Nat: +enum Nat with case Zero case Succ[N <: Nat](n: N) diff --git a/tests/run-macros/i10464/Person_1.scala b/tests/run-macros/i10464/Person_1.scala index 3973f018dd83..4c0845973a48 100644 --- a/tests/run-macros/i10464/Person_1.scala +++ b/tests/run-macros/i10464/Person_1.scala @@ -1,4 +1,4 @@ -trait Person: +trait Person with def name: String case class PersonA(name: String) extends Person diff --git a/tests/run-macros/i7716/Macro_1.scala b/tests/run-macros/i7716/Macro_1.scala index 01f4e5184a12..fe4b1c413c0a 100644 --- a/tests/run-macros/i7716/Macro_1.scala +++ b/tests/run-macros/i7716/Macro_1.scala @@ -1,14 +1,14 @@ import scala.quoted._ -trait Foo: +trait Foo with def mcrImpl1(e: Expr[Any])(using ctx: Quotes): Expr[Any] = '{println(s"Hello ${$e}")} -object Foo extends Foo: +object Foo extends Foo with def mcrImpl2(e: Expr[Any])(using ctx: Quotes): Expr[Any] = '{println(s"Hello ${$e}")} -object Bar: +object Bar with import Foo._ inline def mcr1(e: => Any) = ${mcrImpl1('e)} diff --git a/tests/run-macros/i8530/Macro_1.scala b/tests/run-macros/i8530/Macro_1.scala index dc431c14ef14..b15e2282961a 100644 --- a/tests/run-macros/i8530/Macro_1.scala +++ b/tests/run-macros/i8530/Macro_1.scala @@ -1,6 +1,6 @@ import scala.quoted._ -object Succ: +object Succ with inline def unapply(n: Int): Option[Int] = ${ impl('n) } diff --git a/tests/run-macros/i9812b/Macro_1.scala b/tests/run-macros/i9812b/Macro_1.scala index ed1873195323..8b2e6f46cc52 100644 --- a/tests/run-macros/i9812b/Macro_1.scala +++ b/tests/run-macros/i9812b/Macro_1.scala @@ -6,14 +6,14 @@ trait Liftable[T] { def toExpr(x: T): Quotes ?=> Expr[T] } -object Lift: +object Lift with def apply[T: Liftable](t: T)(using q: Quotes, ev: Liftable[T]): Expr[T] = ev.toExpr(t) sealed abstract class SomeEnum -object SomeEnum: +object SomeEnum with final val Foo = new SomeEnum {} final case class Bar[S <: SomeEnum](s: S) extends SomeEnum - object Bar: + object Bar with def apply[S <: SomeEnum](s: S): SomeEnum = new Bar(s) given LiftFoo: Liftable[Foo.type] with diff --git a/tests/run-macros/paramSymss/Test_2.scala b/tests/run-macros/paramSymss/Test_2.scala index 4e2b53060c8b..2ca016ddbcf6 100644 --- a/tests/run-macros/paramSymss/Test_2.scala +++ b/tests/run-macros/paramSymss/Test_2.scala @@ -16,5 +16,5 @@ object Test { println(showParamSyms(new Test(1, 2))) } -class Test[T](a: T): +class Test[T](a: T) with def this(a: Int, b: T) = this(b) diff --git a/tests/run-macros/refined-selectable-macro/Macro_1.scala b/tests/run-macros/refined-selectable-macro/Macro_1.scala index 27dcbaa01082..05471dfd0adc 100644 --- a/tests/run-macros/refined-selectable-macro/Macro_1.scala +++ b/tests/run-macros/refined-selectable-macro/Macro_1.scala @@ -2,7 +2,7 @@ import scala.quoted._ object Macro { - trait Selectable extends scala.Selectable: + trait Selectable extends scala.Selectable with def selectDynamic(name: String): Any trait SelectableRecord extends Selectable { diff --git a/tests/run-macros/tasty-overload-secondargs/Macro_1.scala b/tests/run-macros/tasty-overload-secondargs/Macro_1.scala index 91c74945c92b..5a5b6137d5df 100644 --- a/tests/run-macros/tasty-overload-secondargs/Macro_1.scala +++ b/tests/run-macros/tasty-overload-secondargs/Macro_1.scala @@ -1,6 +1,6 @@ import scala.quoted._ -object X: +object X with def andThen[A,B](a:A)(f: A => B): B = println("totalFunction") @@ -11,7 +11,7 @@ object X: f.lift.apply(a) -object Macro: +object Macro with inline def mThen[A,B](inline x:A=>B):B = ${ mThenImpl[A,B,A=>B,B]('x) diff --git a/tests/run-macros/tasty-overload-secondargs/Test_2.scala b/tests/run-macros/tasty-overload-secondargs/Test_2.scala index 2584ed01346f..458cee275906 100644 --- a/tests/run-macros/tasty-overload-secondargs/Test_2.scala +++ b/tests/run-macros/tasty-overload-secondargs/Test_2.scala @@ -1,4 +1,4 @@ -object Test: +object Test with def main(args:Array[String]):Unit = val x1 = X.andThen(1){case x if (x%2 == 0) => x} diff --git a/tests/run-macros/tasty-tree-map/quoted_1.scala b/tests/run-macros/tasty-tree-map/quoted_1.scala index a4363f60b599..4d7a101c5583 100644 --- a/tests/run-macros/tasty-tree-map/quoted_1.scala +++ b/tests/run-macros/tasty-tree-map/quoted_1.scala @@ -1,9 +1,9 @@ import scala.quoted._ -object Macros: +object Macros with implicit inline def identityMaped[T](x: => T): T = ${ MacrosImpl.impl('x) } -object MacrosImpl: +object MacrosImpl with def impl[T: Type](x: Expr[T])(using Quotes) : Expr[T] = { import quotes.reflect._ val identityMap = new TreeMap { } diff --git a/tests/run-staging/abstract-int-quote.scala b/tests/run-staging/abstract-int-quote.scala index c3070086104b..f518d7372d77 100644 --- a/tests/run-staging/abstract-int-quote.scala +++ b/tests/run-staging/abstract-int-quote.scala @@ -1,7 +1,7 @@ import scala.quoted._ import scala.quoted.staging._ -object Test: +object Test with given Compiler = Compiler.make(getClass.getClassLoader) diff --git a/tests/run-staging/i7897.scala b/tests/run-staging/i7897.scala index 2b0952971761..d7d0ea558846 100644 --- a/tests/run-staging/i7897.scala +++ b/tests/run-staging/i7897.scala @@ -1,6 +1,6 @@ import scala.quoted._, staging._ -object Test: +object Test with given Compiler = Compiler.make(getClass.getClassLoader) val f: Array[Int] => Int = run { diff --git a/tests/run-staging/i8178.scala b/tests/run-staging/i8178.scala index c0aeb545bad2..bb2f95f7bdee 100644 --- a/tests/run-staging/i8178.scala +++ b/tests/run-staging/i8178.scala @@ -5,7 +5,7 @@ def foo(n: Int, t: Expr[Int])(using Quotes): Expr[Int] = if (n == 0) t else '{ val a = ${Expr(n)}; ${foo(n - 1, 'a)} + $t } -object Test: +object Test with def main(args: Array[String]) = { // make available the necessary toolbox for runtime code generation given Compiler = Compiler.make(getClass.getClassLoader) diff --git a/tests/run-staging/shonan-hmm-simple.scala b/tests/run-staging/shonan-hmm-simple.scala index e17c998ed65e..3cde9885bbe7 100644 --- a/tests/run-staging/shonan-hmm-simple.scala +++ b/tests/run-staging/shonan-hmm-simple.scala @@ -1,7 +1,7 @@ import scala.quoted._ import scala.quoted.staging._ -trait Ring[T]: +trait Ring[T] with val zero: T val one: T val add: (x: T, y: T) => T @@ -9,7 +9,7 @@ trait Ring[T]: val mul: (x: T, y: T) => T end Ring -class RingInt extends Ring[Int]: +class RingInt extends Ring[Int] with val zero = 0 val one = 1 val add = (x, y) => x + y @@ -17,30 +17,30 @@ class RingInt extends Ring[Int]: val mul = (x, y) => x * y -class RingIntExpr(using Quotes) extends Ring[Expr[Int]]: +class RingIntExpr(using Quotes) extends Ring[Expr[Int]] with val zero = '{0} val one = '{1} val add = (x, y) => '{$x + $y} val sub = (x, y) => '{$x - $y} val mul = (x, y) => '{$x * $y} -class RingComplex[U](u: Ring[U]) extends Ring[Complex[U]]: +class RingComplex[U](u: Ring[U]) extends Ring[Complex[U]] with val zero = Complex(u.zero, u.zero) val one = Complex(u.one, u.zero) val add = (x, y) => Complex(u.add(x.re, y.re), u.add(x.im, y.im)) val sub = (x, y) => Complex(u.sub(x.re, y.re), u.sub(x.im, y.im)) val mul = (x, y) => Complex(u.sub(u.mul(x.re, y.re), u.mul(x.im, y.im)), u.add(u.mul(x.re, y.im), u.mul(x.im, y.re))) -sealed trait PV[T]: +sealed trait PV[T] with def expr(using ToExpr[T], Quotes): Expr[T] -case class Sta[T](x: T) extends PV[T]: +case class Sta[T](x: T) extends PV[T] with def expr(using ToExpr[T], Quotes): Expr[T] = Expr(x) -case class Dyn[T](x: Expr[T]) extends PV[T]: +case class Dyn[T](x: Expr[T]) extends PV[T] with def expr(using ToExpr[T], Quotes): Expr[T] = x -class RingPV[U: ToExpr](u: Ring[U], eu: Ring[Expr[U]])(using Quotes) extends Ring[PV[U]]: +class RingPV[U: ToExpr](u: Ring[U], eu: Ring[Expr[U]])(using Quotes) extends Ring[PV[U]] with val zero: PV[U] = Sta(u.zero) val one: PV[U] = Sta(u.one) val add = (x: PV[U], y: PV[U]) => (x, y) match @@ -62,28 +62,28 @@ class RingPV[U: ToExpr](u: Ring[U], eu: Ring[Expr[U]])(using Quotes) extends Rin case class Complex[T](re: T, im: T) -object Complex: - implicit def isToExpr[T: Type: ToExpr]: ToExpr[Complex[T]] = new ToExpr[Complex[T]]: +object Complex with + implicit def isToExpr[T: Type: ToExpr]: ToExpr[Complex[T]] = new ToExpr[Complex[T]] with def apply(comp: Complex[T])(using Quotes) = '{Complex(${Expr(comp.re)}, ${Expr(comp.im)})} -case class Vec[Idx, T](size: Idx, get: Idx => T): +case class Vec[Idx, T](size: Idx, get: Idx => T) with def map[U](f: T => U): Vec[Idx, U] = Vec(size, i => f(get(i))) def zipWith[U, V](other: Vec[Idx, U], f: (T, U) => V): Vec[Idx, V] = Vec(size, i => f(get(i), other.get(i))) -object Vec: +object Vec with def from[T](elems: T*): Vec[Int, T] = new Vec(elems.size, i => elems(i)) -trait VecOps[Idx, T]: +trait VecOps[Idx, T] with val reduce: ((T, T) => T, T, Vec[Idx, T]) => T -class StaticVecOps[T] extends VecOps[Int, T]: +class StaticVecOps[T] extends VecOps[Int, T] with val reduce: ((T, T) => T, T, Vec[Int, T]) => T = (plus, zero, vec) => var sum = zero for (i <- 0 until vec.size) sum = plus(sum, vec.get(i)) sum -class ExprVecOps[T: Type](using Quotes) extends VecOps[Expr[Int], Expr[T]]: +class ExprVecOps[T: Type](using Quotes) extends VecOps[Expr[Int], Expr[T]] with val reduce: ((Expr[T], Expr[T]) => Expr[T], Expr[T], Vec[Expr[Int], Expr[T]]) => Expr[T] = (plus, zero, vec) => '{ var sum = $zero var i = 0 @@ -93,10 +93,10 @@ class ExprVecOps[T: Type](using Quotes) extends VecOps[Expr[Int], Expr[T]]: sum } -class Blas1[Idx, T](r: Ring[T], ops: VecOps[Idx, T]): +class Blas1[Idx, T](r: Ring[T], ops: VecOps[Idx, T]) with def dot(v1: Vec[Idx, T], v2: Vec[Idx, T]): T = ops.reduce(r.add, r.zero, v1.zipWith(v2, r.mul)) -object Test: +object Test with given Compiler = Compiler.make(getClass.getClassLoader) def main(args: Array[String]): Unit = diff --git a/tests/run-staging/shonan-hmm/PV.scala b/tests/run-staging/shonan-hmm/PV.scala index 46e56b7d4ab7..bb81d2648b87 100644 --- a/tests/run-staging/shonan-hmm/PV.scala +++ b/tests/run-staging/shonan-hmm/PV.scala @@ -7,7 +7,7 @@ case class Sta[T](x: T) extends PV[T] case class Dyn[T](x: Expr[T]) extends PV[T] -object Dyn: +object Dyn with def apply[T: ToExpr](x: T)(using Quotes): Dyn[T] = Dyn(Expr(x)) object Dyns { diff --git a/tests/run-with-compiler/intmaptest.scala b/tests/run-with-compiler/intmaptest.scala index c12cb03e979d..c5ded14b5728 100644 --- a/tests/run-with-compiler/intmaptest.scala +++ b/tests/run-with-compiler/intmaptest.scala @@ -1,12 +1,12 @@ -trait Generator[+T]: +trait Generator[+T] with self => def generate: T - def map[S](f: T => S) = new Generator[S]: + def map[S](f: T => S) = new Generator[S] with def generate: S = f(self.generate) - def flatMap[S](f: T => Generator[S]) = new Generator[S]: + def flatMap[S](f: T => Generator[S]) = new Generator[S] with def generate: S = f(self.generate).generate -object Generator: +object Generator with val NumLimit = 300 val Iterations = 10000 @@ -20,7 +20,7 @@ object Generator: def range(end: Int): Generator[Int] = integers.map(x => (x % end).abs) - enum Op: + enum Op with case Lookup, Update, Remove export Op._ diff --git a/tests/run-with-compiler/maptest.scala b/tests/run-with-compiler/maptest.scala index 9a4b42981d94..1e1f5d0eb63f 100644 --- a/tests/run-with-compiler/maptest.scala +++ b/tests/run-with-compiler/maptest.scala @@ -1,12 +1,12 @@ -trait Generator[+T]: +trait Generator[+T] with self => def generate: T - def map[S](f: T => S) = new Generator[S]: + def map[S](f: T => S) = new Generator[S] with def generate: S = f(self.generate) - def flatMap[S](f: T => Generator[S]) = new Generator[S]: + def flatMap[S](f: T => Generator[S]) = new Generator[S] with def generate: S = f(self.generate).generate -object Generator: +object Generator with val NumLimit = 300 val Iterations = 10000 @@ -20,7 +20,7 @@ object Generator: def range(end: Int): Generator[Int] = integers.map(x => (x % end).abs) - enum Op: + enum Op with case Lookup, Update, Remove export Op._ diff --git a/tests/run-with-compiler/settest.scala b/tests/run-with-compiler/settest.scala index 3a725990b840..c7d1e048ab9e 100644 --- a/tests/run-with-compiler/settest.scala +++ b/tests/run-with-compiler/settest.scala @@ -1,12 +1,12 @@ -trait Generator[+T]: +trait Generator[+T] with self => def generate: T - def map[S](f: T => S) = new Generator[S]: + def map[S](f: T => S) = new Generator[S] with def generate: S = f(self.generate) - def flatMap[S](f: T => Generator[S]) = new Generator[S]: + def flatMap[S](f: T => Generator[S]) = new Generator[S] with def generate: S = f(self.generate).generate -object Generator: +object Generator with val NumLimit = 300 val Iterations = 10000 @@ -20,7 +20,7 @@ object Generator: def range(end: Int): Generator[Int] = integers.map(x => (x % end).abs) - enum Op: + enum Op with case Lookup, Update, Remove export Op._ diff --git a/tests/run/ConfManagement.scala b/tests/run/ConfManagement.scala index f73445b5af08..12305a99728f 100644 --- a/tests/run/ConfManagement.scala +++ b/tests/run/ConfManagement.scala @@ -1,12 +1,12 @@ case class Person(name: String) case class Paper(title: String, authors: List[Person], body: String) -object ConfManagement: +object ConfManagement with opaque type Viewers = Set[Person] def viewers(using vs: Viewers) = vs type Viewed[T] = Viewers ?=> T - class Conference(ratings: (Paper, Int)*): + class Conference(ratings: (Paper, Int)*) with private val realScore = ratings.toMap def papers: List[Paper] = ratings.map(_._1).toList diff --git a/tests/run/LazyLists.scala b/tests/run/LazyLists.scala index 6cf8c8cf8e50..3d7ecc626af1 100644 --- a/tests/run/LazyLists.scala +++ b/tests/run/LazyLists.scala @@ -1,7 +1,7 @@ package xcollections: import annotation.unchecked.uncheckedVariance - abstract class LazyList[+T]: + abstract class LazyList[+T] with private var myHead: T = _ private var myTail: LazyList[T] = _ @@ -40,12 +40,12 @@ package xcollections: case xs: LazyList[T] @unchecked => xs case _ => LazyList.fromIterator(xs.iterator) - object LazyList: + object LazyList with val empty: LazyList[Nothing] = new: protected def force(): LazyList[Nothing] = this - object #:: : + object #:: with def unapply[T](xs: LazyList[T]): Option[(T, LazyList[T])] = if xs.isEmpty then None else Some((xs.head, xs.tail)) diff --git a/tests/run/Pouring.scala b/tests/run/Pouring.scala index 6f4611af8bfc..e1db06c23d89 100644 --- a/tests/run/Pouring.scala +++ b/tests/run/Pouring.scala @@ -1,8 +1,8 @@ -class Pouring(capacity: Vector[Int]): +class Pouring(capacity: Vector[Int]) with type Glass = Int type Content = Vector[Int] - enum Move: + enum Move with def apply(content: Content): Content = this match case Empty(g) => content.updated(g, 0) case Fill(g) => content.updated(g, capacity(g)) @@ -23,7 +23,7 @@ class Pouring(capacity: Vector[Int]): ++ (for g <- glasses yield Move.Fill(g)) ++ (for g1 <- glasses; g2 <- glasses if g1 != g2 yield Move.Pour(g1, g2)) - class Path(history: List[Move], val endContent: Content): + class Path(history: List[Move], val endContent: Content) with def extend(move: Move) = Path(move :: history, move(endContent)) override def toString = s"${history.reverse.mkString(" ")} --> $endContent" end Path diff --git a/tests/run/Signals.scala b/tests/run/Signals.scala index 18a1947dcaf0..33a5c929bb39 100644 --- a/tests/run/Signals.scala +++ b/tests/run/Signals.scala @@ -2,7 +2,7 @@ import annotation.unchecked._ package frp: - sealed class Signal[+T](expr: Signal.Caller ?=> T): + sealed class Signal[+T](expr: Signal.Caller ?=> T) with private var myExpr: Signal.Caller => T = _ private var myValue: T = _ private var observers: Set[Signal.Caller] = Set() @@ -26,19 +26,19 @@ package frp: observers = Set() obs.foreach(_.computeValue()) - object Signal: + object Signal with type Caller = Signal[?] given noCaller: Caller(???) with override def computeValue() = () end Signal - class Var[T](expr: Signal.Caller ?=> T) extends Signal[T](expr): + class Var[T](expr: Signal.Caller ?=> T) extends Signal[T](expr) with def update(expr: Signal.Caller ?=> T): Unit = changeTo(expr) end Var end frp import frp._ -class BankAccount: +class BankAccount with def balance: Signal[Int] = myBalance private var myBalance: Var[Int] = Var(0) diff --git a/tests/run/Signals1.scala b/tests/run/Signals1.scala index 129965b4c2a5..178c1b276c0a 100644 --- a/tests/run/Signals1.scala +++ b/tests/run/Signals1.scala @@ -2,12 +2,12 @@ import annotation.unchecked._ package frp: - trait Signal[+T]: + trait Signal[+T] with def apply()(using caller: Signal.Caller): T - object Signal: + object Signal with - abstract class AbstractSignal[+T] extends Signal[T]: + abstract class AbstractSignal[+T] extends Signal[T] with private var currentValue: T = _ private var observers: Set[Caller] = Set() @@ -29,11 +29,11 @@ package frp: end AbstractSignal def apply[T](expr: Caller ?=> T): Signal[T] = - new AbstractSignal[T]: + new AbstractSignal[T] with protected val eval = expr(using _) computeValue() - class Var[T](expr: Caller ?=> T) extends AbstractSignal[T]: + class Var[T](expr: Caller ?=> T) extends AbstractSignal[T] with protected var eval: Caller => T = expr(using _) computeValue() @@ -43,7 +43,7 @@ package frp: end Var opaque type Caller = AbstractSignal[?] - given noCaller: Caller = new AbstractSignal[Nothing]: + given noCaller: Caller = new AbstractSignal[Nothing] with override def eval = ??? override def computeValue() = () @@ -51,7 +51,7 @@ package frp: end frp import frp._ -class BankAccount: +class BankAccount with def balance: Signal[Int] = myBalance private val myBalance: Signal.Var[Int] = Signal.Var(0) diff --git a/tests/run/Typeable.scala b/tests/run/Typeable.scala index 18bf9a4deb6a..c2a76335c382 100644 --- a/tests/run/Typeable.scala +++ b/tests/run/Typeable.scala @@ -16,15 +16,15 @@ * it's unclear whether this should expand to `C[T].unapply(x)`, (as it does now) * or to `C.unapply[T](x)` (which is what TypeLevel Scala 4 did, I believe) */ -trait Typeable[T]: +trait Typeable[T] with def cast(x: Any): Option[T] def describe: String override def toString = s"Typeable[$describe]" -object Typeable: +object Typeable with def apply[T: Typeable]: Typeable[T] = summon - class instanceOf[T: Typeable]: + class instanceOf[T: Typeable] with def unapply(x: Any): Option[T] = Typeable[T].cast(x) given int: Typeable[Int] with diff --git a/tests/run/abstract-givens.scala b/tests/run/abstract-givens.scala index 6ff966411dde..18f8a5aface1 100644 --- a/tests/run/abstract-givens.scala +++ b/tests/run/abstract-givens.scala @@ -1,9 +1,9 @@ -trait T: +trait T with given x: Int given y(using Int): String given z[T](using T): Seq[T] -object Test extends T, App: +object Test extends T, App with given x: Int = 22 override given y(using Int): String = summon[Int].toString given z[T](using T): Seq[T] with diff --git a/tests/run/context-functions.scala b/tests/run/context-functions.scala index e71f0de10378..64da62d3de88 100644 --- a/tests/run/context-functions.scala +++ b/tests/run/context-functions.scala @@ -1,4 +1,4 @@ -trait A: +trait A with type Ctx[T] type Mega[T] @@ -14,7 +14,7 @@ trait A: def trans(x: Ctx[Int]): Ctx[Int] = x end A -object m extends A: +object m extends A with type Ctx[T] = String ?=> T type Mega[T] = (Int, Int, Int, Int, Int, @@ -36,7 +36,7 @@ object m extends A: def mega: Mega[Int] = summon[String].length end m -trait B: +trait B with type Ctx[T] @@ -45,7 +45,7 @@ trait B: def id[T](x: T): T = drop(wrap(x)) end B -object n extends B: +object n extends B with type Ctx[T] = String ?=> Int ?=> T def wrap[T](x: T): Ctx[T] = x diff --git a/tests/run/decorators/DocComment.scala b/tests/run/decorators/DocComment.scala index 85b30fbce393..5b1402fdd588 100644 --- a/tests/run/decorators/DocComment.scala +++ b/tests/run/decorators/DocComment.scala @@ -5,7 +5,7 @@ * `body` what comes before the first tagged line */ case class DocComment(body: String, tags: Map[String, List[String]]) -object DocComment: +object DocComment with def fromString(str: String): DocComment = val lines = str.linesIterator.toList def tagged(line: String): Option[(String, String)] = diff --git a/tests/run/decorators/EntryPoint.scala b/tests/run/decorators/EntryPoint.scala index f87519fabee0..5f3c341ad5c2 100644 --- a/tests/run/decorators/EntryPoint.scala +++ b/tests/run/decorators/EntryPoint.scala @@ -1,7 +1,7 @@ import collection.mutable /** A framework for defining stackable entry point wrappers */ -object EntryPoint: +object EntryPoint with /** A base trait for wrappers of entry points. * Sub-traits: Annotation#Wrapper @@ -26,14 +26,14 @@ object EntryPoint: * * The wrapper class has this outline: * - * object : + * object with * @WrapperAnnotation def (args: ) = * ... * * Here `` and `` are obtained from an * inline call to the `wrapperName` method. */ - trait Annotation extends annotation.StaticAnnotation: + trait Annotation extends annotation.StaticAnnotation with /** The class used for argument parsing. E.g. `scala.util.FromString`, if * arguments are strings, but it could be something else. @@ -56,7 +56,7 @@ object EntryPoint: def wrapper(entryPointName: String, docComment: String): Wrapper /** Base class for descriptions of an entry point wrappers */ - abstract class Wrapper extends EntryPoint.Wrapper: + abstract class Wrapper extends EntryPoint.Wrapper with /** The type of the wrapper argument. E.g., for Java main methods: `Array[String]` */ type Argument @@ -80,7 +80,7 @@ object EntryPoint: def call(arg: Argument): Call /** A class representing a wrapper call */ - abstract class Call: + abstract class Call with /** The getter for the next argument of type `T` */ def nextArgGetter[T](argName: String, fromString: ArgumentParser[T], defaultValue: Option[T] = None): () => T @@ -124,7 +124,7 @@ object EntryPoint: * created from @logged, @transactional, and @main, respectively. * - `x` is the argument of the outer $logged$wrapper. */ - trait Adapter extends annotation.StaticAnnotation: + trait Adapter extends annotation.StaticAnnotation with /** Creates a new wrapper around `wrapped` */ def wrapper(wrapped: EntryPoint.Wrapper): Wrapper @@ -169,7 +169,7 @@ object EntryPoint: * keep the `adapt` type contract implicit (types are still checked when adapts * are generated, of course). */ - abstract class Wrapper extends EntryPoint.Wrapper: + abstract class Wrapper extends EntryPoint.Wrapper with /** The wrapper that this wrapped in turn by this wrapper */ val wrapped: EntryPoint.Wrapper diff --git a/tests/run/decorators/Test.scala b/tests/run/decorators/Test.scala index 1d821d2109d2..6e840ab26bd0 100644 --- a/tests/run/decorators/Test.scala +++ b/tests/run/decorators/Test.scala @@ -1,4 +1,4 @@ -object Test: +object Test with def main(args: Array[String]) = def testAdd(args: String) = println(s"> java add $args") diff --git a/tests/run/decorators/main.scala b/tests/run/decorators/main.scala index a6fecc00b6e6..feb6d7a6567e 100644 --- a/tests/run/decorators/main.scala +++ b/tests/run/decorators/main.scala @@ -3,7 +3,7 @@ import collection.mutable /** A sample @main entry point annotation. * Generates a main function. */ -class main extends EntryPoint.Annotation: +class main extends EntryPoint.Annotation with type ArgumentParser[T] = util.CommandLineParser.FromString[T] type EntryPointResult = Unit @@ -13,11 +13,11 @@ class main extends EntryPoint.Annotation: def wrapper(name: String, doc: String): MainWrapper = new MainWrapper(name, doc) - class MainWrapper(val entryPointName: String, val docComment: String) extends Wrapper: + class MainWrapper(val entryPointName: String, val docComment: String) extends Wrapper with type Argument = Array[String] type Result = Unit - def call(args: Array[String]) = new Call: + def call(args: Array[String]) = new Call with /** A buffer of demanded argument names, plus * "?" if it has a default diff --git a/tests/run/decorators/sample-adapters.scala b/tests/run/decorators/sample-adapters.scala index 77622261d16e..5cb868949e17 100644 --- a/tests/run/decorators/sample-adapters.scala +++ b/tests/run/decorators/sample-adapters.scala @@ -1,10 +1,10 @@ // Sample adapters: -class logged extends EntryPoint.Adapter: +class logged extends EntryPoint.Adapter with def wrapper(wrapped: EntryPoint.Wrapper): LoggedWrapper = LoggedWrapper(wrapped) - class LoggedWrapper(val wrapped: EntryPoint.Wrapper) extends Wrapper: + class LoggedWrapper(val wrapped: EntryPoint.Wrapper) extends Wrapper with def adapt[A, R](op: A => R)(args: A): R = val argsString: String = args match case args: Array[_] => args.mkString(", ") @@ -17,18 +17,18 @@ class logged extends EntryPoint.Adapter: end LoggedWrapper end logged -class split extends EntryPoint.Adapter: +class split extends EntryPoint.Adapter with def wrapper(wrapped: EntryPoint.Wrapper): SplitWrapper = SplitWrapper(wrapped) - class SplitWrapper(val wrapped: EntryPoint.Wrapper) extends Wrapper: + class SplitWrapper(val wrapped: EntryPoint.Wrapper) extends Wrapper with def adapt[R](op: Array[String] => R)(args: String): R = op(args.split(" ")) end split -class join extends EntryPoint.Adapter: +class join extends EntryPoint.Adapter with def wrapper(wrapped: EntryPoint.Wrapper): JoinWrapper = JoinWrapper(wrapped) - class JoinWrapper(val wrapped: EntryPoint.Wrapper) extends Wrapper: + class JoinWrapper(val wrapped: EntryPoint.Wrapper) extends Wrapper with def adapt[R](op: String => R)(args: Array[String]): R = op(args.mkString(" ")) end join diff --git a/tests/run/decorators/sample-program.scala b/tests/run/decorators/sample-program.scala index 1f58f4cd3260..7447d40981e6 100644 --- a/tests/run/decorators/sample-program.scala +++ b/tests/run/decorators/sample-program.scala @@ -1,4 +1,4 @@ -object myProgram: +object myProgram with /** Adds two numbers * @param num the first number @@ -15,7 +15,7 @@ end myProgram // Compiler generated code: -object add: +object add with private val $main = new main() private val $main$wrapper = $main.wrapper( "MyProgram.add", @@ -29,7 +29,7 @@ object add: cll.run(myProgram.add(arg1(), arg2())) end add -object addAll: +object addAll with private val $main = new main() private val $split = new split() private val $logged = new logged() diff --git a/tests/run/defunctionalized.scala b/tests/run/defunctionalized.scala index aa236b8d22fb..c48b1bb6ad9a 100644 --- a/tests/run/defunctionalized.scala +++ b/tests/run/defunctionalized.scala @@ -1,4 +1,4 @@ -enum Filter: +enum Filter with case IsOdd case IsPrime case LessThan(bound: Int) diff --git a/tests/run/enum-custom-toString.scala b/tests/run/enum-custom-toString.scala index 7432bde87ff9..9ef9ff044679 100644 --- a/tests/run/enum-custom-toString.scala +++ b/tests/run/enum-custom-toString.scala @@ -1,23 +1,23 @@ -enum ES: +enum ES with case A override def toString: String = "overridden" -enum EJ extends java.lang.Enum[EJ]: +enum EJ extends java.lang.Enum[EJ] with case B override def toString: String = "overridden" -trait Mixin extends reflect.Enum: +trait Mixin extends reflect.Enum with override def productPrefix: String = "noprefix" override def toString: String = "overridden" -enum EM extends Mixin: +enum EM extends Mixin with case C -enum ET[T] extends java.lang.Enum[ET[_]]: +enum ET[T] extends java.lang.Enum[ET[_]] with case D extends ET[Unit] override def toString: String = "overridden" -enum EZ: +enum EZ with case E(arg: Int) override def toString: String = "overridden" @@ -25,20 +25,20 @@ enum EC: // control case case F case G(arg: Int) -enum EO: +enum EO with case H case I(arg: Int) override def productPrefix: String = "noprefix" override def toString: String = "overridden" end EO -enum EQ: +enum EQ with case J extends EQ with Mixin case K(arg: Int) extends EQ with Mixin abstract class Tag[T] extends reflect.Enum -object Tag: - private final class IntTagImpl extends Tag[Int] with runtime.EnumValue: +object Tag with + private final class IntTagImpl extends Tag[Int] with runtime.EnumValue with def ordinal = 0 override def hashCode = 123 final val IntTag: Tag[Int] = IntTagImpl() diff --git a/tests/run/enum-nat.scala b/tests/run/enum-nat.scala index 47bddcc665cd..25149c8d2b48 100644 --- a/tests/run/enum-nat.scala +++ b/tests/run/enum-nat.scala @@ -1,11 +1,11 @@ import Nat._ import compiletime._ -enum Nat: +enum Nat with case Zero case Succ[N <: Nat.Refract](n: N) -object Nat: +object Nat with type Refract = Zero.type | Succ[_] inline def toIntTypeLevel[N <: Nat]: Int = inline erasedValue[N] match diff --git a/tests/run/enum-ordinal-java/Lib.scala b/tests/run/enum-ordinal-java/Lib.scala index 75b9003e5553..69fc8190e02e 100644 --- a/tests/run/enum-ordinal-java/Lib.scala +++ b/tests/run/enum-ordinal-java/Lib.scala @@ -1,5 +1,5 @@ -object Lib1: +object Lib1 with trait MyJavaEnum[E <: java.lang.Enum[E]] extends java.lang.Enum[E] -object Lib2: +object Lib2 with type JavaEnumAlias[E <: java.lang.Enum[E]] = java.lang.Enum[E] diff --git a/tests/run/enum-ordinal-java/Test.scala b/tests/run/enum-ordinal-java/Test.scala index 082ea85f7044..83625d581082 100644 --- a/tests/run/enum-ordinal-java/Test.scala +++ b/tests/run/enum-ordinal-java/Test.scala @@ -1,7 +1,7 @@ -enum Color1 extends Lib1.MyJavaEnum[Color1]: +enum Color1 extends Lib1.MyJavaEnum[Color1] with case Red, Green, Blue -enum Color2 extends Lib2.JavaEnumAlias[Color2]: +enum Color2 extends Lib2.JavaEnumAlias[Color2] with case Red, Green, Blue @main def Test = diff --git a/tests/run/enum-values-order.scala b/tests/run/enum-values-order.scala index 400cdbc8aac5..3721728fc2a0 100644 --- a/tests/run/enum-values-order.scala +++ b/tests/run/enum-values-order.scala @@ -5,9 +5,9 @@ enum LatinAlphabet2 extends java.lang.Enum[LatinAlphabet2] { case A, B, C, D, E, enum LatinAlphabet3[+T] extends java.lang.Enum[LatinAlphabet3[_]] { case A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z } -object Color: +object Color with trait Pretty -enum Color extends java.lang.Enum[Color]: +enum Color extends java.lang.Enum[Color] with case Red, Green, Blue case Aqua extends Color with Color.Pretty case Grey, Black, White diff --git a/tests/run/enum-values.scala b/tests/run/enum-values.scala index a7b838ba73cd..f858d47a6792 100644 --- a/tests/run/enum-values.scala +++ b/tests/run/enum-values.scala @@ -1,31 +1,31 @@ import reflect.Selectable.reflectiveSelectable import deriving.Mirror -enum Color: +enum Color with case Red, Green, Blue -enum Suits extends java.lang.Enum[Suits]: +enum Suits extends java.lang.Enum[Suits] with case Clubs, Spades, Diamonds, Hearts -enum Tag[T]: +enum Tag[T] with case Int extends Tag[Int] case OfClass[T]()(using val tag: reflect.ClassTag[T]) extends Tag[T] // mix order of class and value case String extends Tag[String] -enum Expr[-T >: Null]: +enum Expr[-T >: Null] with case EmptyTree extends Expr[Null] case AnyTree -enum ListLike[+T]: +enum ListLike[+T] with case Cons[T](head: T, tail: ListLike[T]) extends ListLike[T] case EmptyListLike -enum TypeCtorsK[F[_]]: +enum TypeCtorsK[F[_]] with case List extends TypeCtorsK[List] case Const[T]() extends TypeCtorsK[[U] =>> T] // mix order of class and value case Option extends TypeCtorsK[Option] -enum MixedParams[F[_], G[X,Y] <: collection.Map[X,Y], T]: +enum MixedParams[F[_], G[X,Y] <: collection.Map[X,Y], T] with case Foo extends MixedParams[List, collection.mutable.LinkedHashMap, Unit] enum ClassOnly: // this should still generate the `ordinal` and `fromOrdinal` companion methods diff --git a/tests/run/enums-precise.scala b/tests/run/enums-precise.scala index 1ae98ca6664f..59867e9f6100 100644 --- a/tests/run/enums-precise.scala +++ b/tests/run/enums-precise.scala @@ -1,8 +1,8 @@ -enum NonEmptyList[+T]: +enum NonEmptyList[+T] with case Many[+U](head: U, tail: NonEmptyList[U]) extends NonEmptyList[U] case One [+U](value: U) extends NonEmptyList[U] -enum Ast: +enum Ast with case Binding(name: String, tpe: String) case Lambda(args: NonEmptyList[Binding], rhs: Ast) // reference to another case of the enum case Ident(name: String) diff --git a/tests/run/enums-serialization-compat.scala b/tests/run/enums-serialization-compat.scala index 940e726c05a0..dfa8a7d06ee1 100644 --- a/tests/run/enums-serialization-compat.scala +++ b/tests/run/enums-serialization-compat.scala @@ -1,22 +1,22 @@ import java.io._ import scala.util.Using -enum JColor extends java.lang.Enum[JColor]: +enum JColor extends java.lang.Enum[JColor] with case Red // java enum has magic JVM support -enum SColor: +enum SColor with case Green // simple case last -enum SColorTagged[T]: +enum SColorTagged[T] with case Blue extends SColorTagged[Unit] case Rgb(r: Byte, g: Byte, b: Byte) extends SColorTagged[(Byte, Byte, Byte)] // mixing pattern kinds case Indigo extends SColorTagged[Unit] case Cmyk(c: Byte, m: Byte, y: Byte, k: Byte) extends SColorTagged[(Byte, Byte, Byte, Byte)] // class case last -enum Nucleobase: +enum Nucleobase with case A,C,G,T // patdef last -enum MyClassTag[T](wrapped: Class[?]): +enum MyClassTag[T](wrapped: Class[?]) with case IntTag extends MyClassTag[Int](classOf[Int]) case UnitTag extends MyClassTag[Unit](classOf[Unit]) // value case last diff --git a/tests/run/erased-inline-vals.scala b/tests/run/erased-inline-vals.scala index 57e2901a62ea..b74d2bfe2151 100644 --- a/tests/run/erased-inline-vals.scala +++ b/tests/run/erased-inline-vals.scala @@ -1,17 +1,17 @@ -abstract class A: +abstract class A with def x: Int val y: Int -class B extends A: +class B extends A with inline def x: Int = 1 inline val y = 2 -class C extends A: +class C extends A with final val x: Int = 3 final val y = 4 -class D: +class D with inline def x: Int = 5 inline val y = 6 diff --git a/tests/run/exports.scala b/tests/run/exports.scala index f68312ca54e2..ee409f95fbc1 100644 --- a/tests/run/exports.scala +++ b/tests/run/exports.scala @@ -48,8 +48,8 @@ final class Foo { export foo._ // nothing is exported } -class A: +class A with val x: Int = 1 -class B(a: A): +class B(a: A) with export a.x object B extends B(A()) \ No newline at end of file diff --git a/tests/run/extension-override.scala b/tests/run/extension-override.scala index 00246f611391..e77faa18b199 100644 --- a/tests/run/extension-override.scala +++ b/tests/run/extension-override.scala @@ -1,8 +1,8 @@ -class A: +class A with extension (s: String) def len: Int = s.length -object B extends A: +object B extends A with extension (s: String) override def len: Int = s.length + 1 diff --git a/tests/run/fragables-extension.scala b/tests/run/fragables-extension.scala index 417a612a3f04..071cc4fd78d1 100644 --- a/tests/run/fragables-extension.scala +++ b/tests/run/fragables-extension.scala @@ -3,7 +3,7 @@ trait Frag case class IntFrag(x: Int) extends Frag case class StringFrag(x: String) extends Frag -trait Fragable[T]: +trait Fragable[T] with extension (x: T) def toFrags: List[Frag] diff --git a/tests/run/given-eta.scala b/tests/run/given-eta.scala index 1eaf6fd16c49..07b088e0188e 100644 --- a/tests/run/given-eta.scala +++ b/tests/run/given-eta.scala @@ -1,6 +1,6 @@ class C(val x: Int) -trait D: +trait D with type T def trans(other: T): T diff --git a/tests/run/given-var.scala b/tests/run/given-var.scala index fa4ee45e77e6..13fc9c9f8755 100644 --- a/tests/run/given-var.scala +++ b/tests/run/given-var.scala @@ -1,5 +1,5 @@ // Demonstrates that monomorphic givens are cached -object a: +object a with private var x = 1 given Int = x def init(x: Int) = this.x = x diff --git a/tests/run/i10082.scala b/tests/run/i10082.scala index 299083da3567..b3b24f1d7a6f 100644 --- a/tests/run/i10082.scala +++ b/tests/run/i10082.scala @@ -1,4 +1,4 @@ -object Kotlin: +object Kotlin with class Ctx[T](val x: T) extends AnyVal def fun[T, U](fn: Ctx[T] ?=> U): T => U = (x: T) => fn(using Ctx(x)) diff --git a/tests/run/i10857.scala b/tests/run/i10857.scala index c8b28d04651e..9af4f88e19a6 100644 --- a/tests/run/i10857.scala +++ b/tests/run/i10857.scala @@ -1,6 +1,6 @@ -object Module: +object Module with - enum Foo: + enum Foo with case Value case Parameterised(i: Int) diff --git a/tests/run/i10884/Test_2.scala b/tests/run/i10884/Test_2.scala index 72e7fafa9674..c336613bc414 100644 --- a/tests/run/i10884/Test_2.scala +++ b/tests/run/i10884/Test_2.scala @@ -1,4 +1,4 @@ -object Exporter: +object Exporter with export JavaExporter_1._ import Exporter._ diff --git a/tests/run/i10905.scala b/tests/run/i10905.scala index 2637d69cc8a2..af8baafc9099 100644 --- a/tests/run/i10905.scala +++ b/tests/run/i10905.scala @@ -1,5 +1,5 @@ class C(val x: Int) extends TypeHelpers -abstract class TypeHelpers: +abstract class TypeHelpers with self: C => def f = x @main def Test = diff --git a/tests/run/i7359.scala b/tests/run/i7359.scala index c01b9d05f274..b10967e06479 100644 --- a/tests/run/i7359.scala +++ b/tests/run/i7359.scala @@ -1,34 +1,34 @@ -trait ObjectInterface: +trait ObjectInterface with def equals(obj: Any): Boolean def hashCode(): Int def toString(): String -trait SAMPlainWithExtends extends ObjectInterface: +trait SAMPlainWithExtends extends ObjectInterface with def first(): String -trait SAMCovariantOutExtends[+O] extends ObjectInterface: +trait SAMCovariantOutExtends[+O] extends ObjectInterface with def first(): O -trait SAMContravariantInExtends[-I] extends ObjectInterface: +trait SAMContravariantInExtends[-I] extends ObjectInterface with def first(in: I): Unit -trait SAMInvariantExtends[T] extends ObjectInterface: +trait SAMInvariantExtends[T] extends ObjectInterface with def first(in: T): T -trait SAMInOutExtends[-I, +O] extends ObjectInterface: +trait SAMInOutExtends[-I, +O] extends ObjectInterface with def first(in: I): O type CustomString = String type CustomBoolean = Boolean type CustomInt = Int -trait SAMWithCustomAliases: +trait SAMWithCustomAliases with def first(): String def equals(obj: Any): CustomBoolean def hashCode(): CustomInt def toString(): CustomString -object Test: +object Test with def main(args: Array[String]): Unit = val samPlainWithExtends : SAMPlainWithExtends = () => "o" diff --git a/tests/run/i7788.scala b/tests/run/i7788.scala index 99d16ba1521c..83341f80a4c2 100644 --- a/tests/run/i7788.scala +++ b/tests/run/i7788.scala @@ -1,4 +1,4 @@ -trait Show[-A]: +trait Show[-A] with def show(a:A): String given Show[String] = x => x diff --git a/tests/run/i8396.scala b/tests/run/i8396.scala index 3e44e3898dc5..602f425d29c0 100644 --- a/tests/run/i8396.scala +++ b/tests/run/i8396.scala @@ -1,7 +1,7 @@ -trait Show[A]: +trait Show[A] with def show(a: A): String = a.toString -object Prefix: +object Prefix with type AbstractType type UpperBoundedType <: String type FullyBoundedType >: String <: String diff --git a/tests/run/i8530-b.scala b/tests/run/i8530-b.scala index 80171bc4d178..ff3a8d76943e 100644 --- a/tests/run/i8530-b.scala +++ b/tests/run/i8530-b.scala @@ -1,6 +1,6 @@ import scala.compiletime.erasedValue -class MyRegex[Pattern <: String & Singleton/*Literal constant*/]: +class MyRegex[Pattern <: String & Singleton/*Literal constant*/] with inline def unapplySeq(s: CharSequence): Option[List[String]] = inline erasedValue[Pattern] match case "foo" => if s == "foo" then Some(Nil) else None diff --git a/tests/run/i8530.scala b/tests/run/i8530.scala index bbbc52587ee0..66a93344e433 100644 --- a/tests/run/i8530.scala +++ b/tests/run/i8530.scala @@ -1,16 +1,16 @@ -object MyBoooleanUnapply: +object MyBoooleanUnapply with inline def unapply(x: Int): Boolean = true -object MyOptionUnapply: +object MyOptionUnapply with inline def unapply(x: Int): Option[Long] = Some(x) -object MyPolyUnapply: +object MyPolyUnapply with inline def unapply[T](x: T): Option[T] = Some(x) -object MySeqUnapply: +object MySeqUnapply with inline def unapplySeq(x: Int): Seq[Int] = Seq(x, x + 1) -object MyWhiteboxUnapply: +object MyWhiteboxUnapply with transparent inline def unapply(x: Int): Option[Any] = Some(x) diff --git a/tests/run/i8931.scala b/tests/run/i8931.scala index 555d15d0121d..ab1ed7f54a23 100644 --- a/tests/run/i8931.scala +++ b/tests/run/i8931.scala @@ -1,4 +1,4 @@ -object test1: +object test1 with trait Trait @@ -18,7 +18,7 @@ object test1: } } -object test2: +object test2 with trait Trait @@ -38,16 +38,16 @@ object test2: } } -object test3: +object test3 with trait Trait - trait Managed[T]: + trait Managed[T] with def flatMap[U](f: T => Managed[U]) = - class C: + class C with def make() = - class D: + class D with def bar(): T = ??? val t: T = ??? val u = diff --git a/tests/run/i9011.scala b/tests/run/i9011.scala index c75871a865bb..495bd924fad0 100644 --- a/tests/run/i9011.scala +++ b/tests/run/i9011.scala @@ -1,4 +1,4 @@ -enum Opt[+T] derives Eq: +enum Opt[+T] derives Eq with case Sm[T](t: T) extends Opt[T] case Nn diff --git a/tests/run/i9068.scala b/tests/run/i9068.scala index c66dc72dbab1..b0dedaad21de 100644 --- a/tests/run/i9068.scala +++ b/tests/run/i9068.scala @@ -1,4 +1,4 @@ -case class MyClass(v1: Int, v2: Int, v3: Int, v4: Int) extends Product3[Int, Int, Int]: +case class MyClass(v1: Int, v2: Int, v3: Int, v4: Int) extends Product3[Int, Int, Int] with val _1: Int = v2 def _2: Int = v3 var _3: Int = v4 diff --git a/tests/run/i9155.scala b/tests/run/i9155.scala index 2f5bf086c8eb..d5ae94b24c2d 100644 --- a/tests/run/i9155.scala +++ b/tests/run/i9155.scala @@ -1,7 +1,7 @@ -object Foo: +object Foo with @scala.annotation.targetName("w") def \/\/ = "W" -object Bar: +object Bar with export Foo._ @main def Test = diff --git a/tests/run/i9530.scala b/tests/run/i9530.scala index e0262764039f..0db77c1cadd3 100644 --- a/tests/run/i9530.scala +++ b/tests/run/i9530.scala @@ -1,4 +1,4 @@ -trait Scope: +trait Scope with type Expr type Value def expr(x: String): Expr diff --git a/tests/run/i9928.scala b/tests/run/i9928.scala index 3a3f818b17d3..3dc08a8553db 100644 --- a/tests/run/i9928.scala +++ b/tests/run/i9928.scala @@ -1,17 +1,17 @@ -trait Magic[F]: +trait Magic[F] with extension (x: Int) def read: F -trait LowPrio: +trait LowPrio with given Magic[String] with extension(x: Int) def read: String = println("In string") s"$x" -object test1: +object test1 with object Magic extends LowPrio opaque type Foo = String - object Foo extends LowPrio: + object Foo extends LowPrio with import Magic.given def apply(s: String): Foo = s @@ -23,15 +23,15 @@ object test1: def test: Unit = (3.read: Foo) -object test2: - object Magic extends LowPrio: +object test2 with + object Magic extends LowPrio with given Magic[Foo] with extension (x: Int) def read: Foo = println("In foo") Foo(s"$x") opaque type Foo = String - object Foo extends LowPrio: + object Foo extends LowPrio with import Magic.given def apply(s: String): Foo = s diff --git a/tests/run/ift-return.scala b/tests/run/ift-return.scala index 021c73173051..f67028b712b7 100644 --- a/tests/run/ift-return.scala +++ b/tests/run/ift-return.scala @@ -1,7 +1,7 @@ -trait A: +trait A with val x: Int -trait Ctx: +trait Ctx with type T val x: T val y: T diff --git a/tests/run/inline-override.scala b/tests/run/inline-override.scala index a128002fc4ba..83a6a61424e7 100644 --- a/tests/run/inline-override.scala +++ b/tests/run/inline-override.scala @@ -1,12 +1,12 @@ import annotation.targetName -abstract class A: +abstract class A with def f(x: Int) = s"dynamic $x" def h(x: Int): String @targetName("h2") def h1(x: Int): String inline def i(x: Int): String -class B extends A: +class B extends A with inline override def f(x: Int) = g(x) inline def g(x: Int) = s"inline $x" inline def h(x: Int) = g(x) diff --git a/tests/run/instances.scala b/tests/run/instances.scala index 128ea0700e02..bbb6fc22312a 100644 --- a/tests/run/instances.scala +++ b/tests/run/instances.scala @@ -40,10 +40,10 @@ object Test extends App { assert(List(names, List("!")).flattened == names :+ "!") assert(Nil.flattened == Nil) - trait SemiGroup[T]: + trait SemiGroup[T] with extension (x: T) def combine(y: T): T - trait Monoid[T] extends SemiGroup[T]: + trait Monoid[T] extends SemiGroup[T] with def unit: T given StringMonoid: Monoid[String] with @@ -56,7 +56,7 @@ object Test extends App { println(sum(names)) - trait Ord[T]: + trait Ord[T] with extension (x: T) def compareTo(y: T): Int extension (x: T) def < (y: T) = x.compareTo(y) < 0 extension (x: T) def > (y: T) = x.compareTo(y) > 0 @@ -88,11 +88,11 @@ object Test extends App { println(max(List(1, 2, 3), List(2))) - trait Functor[F[_]]: + trait Functor[F[_]] with extension [A](x: F[A]) def map[B](f: A => B): F[B] end Functor - trait Monad[F[_]] extends Functor[F]: + trait Monad[F[_]] extends Functor[F] with extension [A](x: F[A]) def flatMap[B](f: A => F[B]): F[B] extension [A](x: F[A]) def map[B](f: A => B) = x.flatMap(f `andThen` pure) diff --git a/tests/run/lazy-impl.scala b/tests/run/lazy-impl.scala index a941dc89100a..ca7ed5852c2b 100644 --- a/tests/run/lazy-impl.scala +++ b/tests/run/lazy-impl.scala @@ -46,7 +46,7 @@ * The code makes use of the following runtime class: - class Waiting: + class Waiting with private var done = false def release(): Unit = synchronized: done = true diff --git a/tests/run/option-extract.scala b/tests/run/option-extract.scala index 7b87ad28bc68..588ab1c445d0 100644 --- a/tests/run/option-extract.scala +++ b/tests/run/option-extract.scala @@ -1,5 +1,5 @@ -enum Option[+A]: +enum Option[+A] with case Some(x: A) case None diff --git a/tests/run/outer-accessors.scala b/tests/run/outer-accessors.scala index 47d7a5b1849d..b8378a8337cd 100644 --- a/tests/run/outer-accessors.scala +++ b/tests/run/outer-accessors.scala @@ -1,15 +1,15 @@ -class A: +class A with val a = 2 - class B: + class B with val b = 3 - trait T: + trait T with def t = a + b val bb = B() - class C extends bb.T: + class C extends bb.T with def result = a + t @main def Test = diff --git a/tests/run/quoted-sematics-1.scala b/tests/run/quoted-sematics-1.scala index ed2d05224d73..6f77a0ec2903 100644 --- a/tests/run/quoted-sematics-1.scala +++ b/tests/run/quoted-sematics-1.scala @@ -25,7 +25,7 @@ object Name { } -enum Term: +enum Term with case Nat(n: Int) case Ref(name: Name) case Lambda(name: Name, tpe: Type, body: Term) @@ -37,7 +37,7 @@ enum Term: case Fix(term: Term) -enum Pattern: +enum Pattern with case PNat(n: Int) case PRef(name: Name) case PApp(fun: Pattern, arg: Pattern) @@ -46,7 +46,7 @@ enum Pattern: case PFun(name: Name) -enum Type: +enum Type with case NatType case LambdaType(arg: Type, res: Type) case BoxType(inner: Type) diff --git a/tests/run/selectable-new.scala b/tests/run/selectable-new.scala index e460ca631b56..d8cf18d228ca 100644 --- a/tests/run/selectable-new.scala +++ b/tests/run/selectable-new.scala @@ -1,10 +1,10 @@ @main def Test = val x = - class C extends reflect.Selectable: + class C extends reflect.Selectable with def name: String = "hello" new C - val y = new reflect.Selectable: + val y = new reflect.Selectable with def name: String = "hello" assert(x.name == "hello") diff --git a/tests/run/singleton-ops-flags.scala b/tests/run/singleton-ops-flags.scala index 8e2cda6a38c7..2f316ab56a92 100644 --- a/tests/run/singleton-ops-flags.scala +++ b/tests/run/singleton-ops-flags.scala @@ -3,7 +3,7 @@ package example { import compiletime.S import compiletime.ops.int.<< - object TastyFlags: + object TastyFlags with final val EmptyFlags = baseFlags final val Erased = EmptyFlags.next @@ -40,7 +40,7 @@ package example { case Open => "Open" }) mkString(" | ") - object opaques: + object opaques with opaque type FlagSet = Int opaque type EmptyFlagSet <: FlagSet = 0 diff --git a/tests/run/structural-contextual.scala b/tests/run/structural-contextual.scala index e1d0890b73cd..b12f6fee348b 100644 --- a/tests/run/structural-contextual.scala +++ b/tests/run/structural-contextual.scala @@ -1,7 +1,7 @@ -trait Resolver: +trait Resolver with def resolve(label: String): Any -class ResolvingSelectable extends Selectable: +class ResolvingSelectable extends Selectable with def selectDynamic(label: String)(using r: Resolver): Any = r.resolve(label) def applyDynamic(label: String)(args: Any*)(using r: Resolver): Any = diff --git a/tests/run/targetName.scala b/tests/run/targetName.scala index 7774922c7b12..721c614c37a9 100644 --- a/tests/run/targetName.scala +++ b/tests/run/targetName.scala @@ -1,23 +1,23 @@ import annotation.targetName -object A: +object A with def f(x: => String): Int = x.length @targetName("f2") def f(x: => Int): Int = x import A._ -trait T: +trait T with def f(x: => String): Int @targetName("f2") def f(x: => Int): Int -class C: +class C with def f(x: => String): Int = x.length @targetName("f2") def f(x: => Int): Int = x -object B1 extends C, T: +object B1 extends C, T with @targetName("f2") override def f(x: => Int): Int = x + 1 -object B2 extends C, T: +object B2 extends C, T with override def f(x: => String): Int = x.length + 1 @targetName("fooString") def foo(ps: String*) : Unit = println(s"strings: $ps") diff --git a/tests/run/typable.scala b/tests/run/typable.scala index 7fe253023740..b47cde8eb3e8 100644 --- a/tests/run/typable.scala +++ b/tests/run/typable.scala @@ -1,6 +1,6 @@ import scala.reflect._ -object Test: +object Test with def main(args: Array[String]): Unit = assert(f[String]) assert(!f[Int]) diff --git a/tests/run/unambiref.scala b/tests/run/unambiref.scala index 1dc617aefa4c..d8c74d6ed919 100644 --- a/tests/run/unambiref.scala +++ b/tests/run/unambiref.scala @@ -1,5 +1,5 @@ -class A(val x: Int): - class B extends A(2): +class A(val x: Int) with + class B extends A(2) with println(x) @main def Test = diff --git a/tests/semanticdb/expect/Enums.expect.scala b/tests/semanticdb/expect/Enums.expect.scala index d74e49ccf98d..0a9888c07457 100644 --- a/tests/semanticdb/expect/Enums.expect.scala +++ b/tests/semanticdb/expect/Enums.expect.scala @@ -1,17 +1,17 @@ -object Enums/*<-_empty_::Enums.*/: +object Enums/*<-_empty_::Enums.*/ with import <:_empty_::Enums.`<:<`.*/._ - enum Colour/*<-_empty_::Enums.Colour#*/: + enum Colour/*<-_empty_::Enums.Colour#*/ with import Colour/*->_empty_::Enums.Colour.*/.Red/*->_empty_::Enums.Colour.Red.*/ case Red/*<-_empty_::Enums.Colour.Red.*/, Green/*<-_empty_::Enums.Colour.Green.*/, Blue/*<-_empty_::Enums.Colour.Blue.*/ - enum Directions/*<-_empty_::Enums.Directions#*/: + enum Directions/*<-_empty_::Enums.Directions#*/ with case North/*<-_empty_::Enums.Directions.North.*/, East/*<-_empty_::Enums.Directions.East.*/, South/*<-_empty_::Enums.Directions.South.*/, West/*<-_empty_::Enums.Directions.West.*/ - enum Suits/*<-_empty_::Enums.Suits#*/ derives /*->scala::CanEqual.derived.*/CanEqual: + enum Suits/*<-_empty_::Enums.Suits#*/ derives /*->scala::CanEqual.derived.*/CanEqual with case Hearts/*<-_empty_::Enums.Suits.Hearts.*/, Spades/*<-_empty_::Enums.Suits.Spades.*/, Clubs/*<-_empty_::Enums.Suits.Clubs.*/, Diamonds/*<-_empty_::Enums.Suits.Diamonds.*/ - object Suits/*<-_empty_::Enums.Suits.*/: + object Suits/*<-_empty_::Enums.Suits.*/ with extension (suit/*<-_empty_::Enums.Suits.isRed().(suit)*/: Suits/*->_empty_::Enums.Suits#*/) def isRed/*<-_empty_::Enums.Suits.isRed().*/: Boolean/*->scala::Boolean#*/ = suit/*->_empty_::Enums.Suits.isRed().(suit)*/ ==/*->scala::Any#`==`().*/ Hearts/*->_empty_::Enums.Suits.Hearts.*/ ||/*->scala::Boolean#`||`().*/ suit/*->_empty_::Enums.Suits.isRed().(suit)*/ ==/*->scala::Any#`==`().*/ Diamonds/*->_empty_::Enums.Suits.Diamonds.*/ @@ -19,7 +19,7 @@ object Enums/*<-_empty_::Enums.*/: case Spades/*->_empty_::Enums.Suits.Spades.*/ | Clubs/*->_empty_::Enums.Suits.Clubs.*/ => true case _ => false - enum WeekDays/*<-_empty_::Enums.WeekDays#*/: + enum WeekDays/*<-_empty_::Enums.WeekDays#*/ with case Monday/*<-_empty_::Enums.WeekDays.Monday.*/ case Tuesday/*<-_empty_::Enums.WeekDays.Tuesday.*/ case Wednesday/*<-_empty_::Enums.WeekDays.Wednesday.*/ @@ -28,25 +28,25 @@ object Enums/*<-_empty_::Enums.*/: case Saturday/*<-_empty_::Enums.WeekDays.Saturday.*/ case Sunday/*<-_empty_::Enums.WeekDays.Sunday.*/ - enum Coin/*<-_empty_::Enums.Coin#*/(value/*<-_empty_::Enums.Coin#value.*/: Int/*->scala::Int#*/): + enum Coin/*<-_empty_::Enums.Coin#*/(value/*<-_empty_::Enums.Coin#value.*/: Int/*->scala::Int#*/) with case Penny/*<-_empty_::Enums.Coin.Penny.*/ extends Coin/*->_empty_::Enums.Coin#*/(1)/*->scala::runtime::EnumValue#*/ case Nickel/*<-_empty_::Enums.Coin.Nickel.*/ extends Coin/*->_empty_::Enums.Coin#*/(5)/*->scala::runtime::EnumValue#*/ case Dime/*<-_empty_::Enums.Coin.Dime.*/ extends Coin/*->_empty_::Enums.Coin#*/(10)/*->scala::runtime::EnumValue#*/ case Quarter/*<-_empty_::Enums.Coin.Quarter.*/ extends Coin/*->_empty_::Enums.Coin#*/(25)/*->scala::runtime::EnumValue#*/ case Dollar/*<-_empty_::Enums.Coin.Dollar.*/ extends Coin/*->_empty_::Enums.Coin#*/(100)/*->scala::runtime::EnumValue#*/ - enum Maybe/*<-_empty_::Enums.Maybe#*/[+A/*<-_empty_::Enums.Maybe#[A]*/]: + enum Maybe/*<-_empty_::Enums.Maybe#*/[+A/*<-_empty_::Enums.Maybe#[A]*/] with case Just/*<-_empty_::Enums.Maybe.Just#*/(value/*<-_empty_::Enums.Maybe.Just#value.*/: A/*->_empty_::Enums.Maybe.Just#[A]*/) case None/*<-_empty_::Enums.Maybe.None.*//*->scala::runtime::EnumValue#*/ - enum Tag/*<-_empty_::Enums.Tag#*/[A/*<-_empty_::Enums.Tag#[A]*/]: + enum Tag/*<-_empty_::Enums.Tag#*/[A/*<-_empty_::Enums.Tag#[A]*/] with case IntTag/*<-_empty_::Enums.Tag.IntTag.*/ extends Tag/*->_empty_::Enums.Tag#*/[Int/*->scala::Int#*/]/*->scala::runtime::EnumValue#*/ case BooleanTag/*<-_empty_::Enums.Tag.BooleanTag.*/ extends Tag/*->_empty_::Enums.Tag#*/[Boolean/*->scala::Boolean#*/]/*->scala::runtime::EnumValue#*/ - enum <:_empty_::Enums.`<:<`.Refl#[C]*/ <:_empty_::Enums.`<:<`#*/ C/*->_empty_::Enums.`<:<`.Refl#[C]*/) - object <:_empty_::Enums.`<:<`.given_T().[T]*/ <:_empty_::Enums.`<:<`#*/ T/*->_empty_::Enums.`<:<`.given_T().[T]*/) = Refl/*->_empty_::Enums.`<:<`.Refl.*//*->_empty_::Enums.`<:<`.Refl.apply().*/() extension [A/*<-_empty_::Enums.unwrap().[A]*/, B/*<-_empty_::Enums.unwrap().[B]*/](opt/*<-_empty_::Enums.unwrap().(opt)*/: Option/*->scala::Option#*/[A/*->_empty_::Enums.unwrap().[A]*/]) def unwrap/*<-_empty_::Enums.unwrap().*/(using ev/*<-_empty_::Enums.unwrap().(ev)*/: A/*->_empty_::Enums.unwrap().[A]*/ <:_empty_::Enums.`<:<`#*/ Option/*->scala::Option#*/[B/*->_empty_::Enums.unwrap().[B]*/]): Option/*->scala::Option#*/[B/*->_empty_::Enums.unwrap().[B]*/] = ev/*->_empty_::Enums.unwrap().(ev)*/ match @@ -54,7 +54,7 @@ object Enums/*<-_empty_::Enums.*/: val some1/*<-_empty_::Enums.some1.*/ = /*->_empty_::Enums.unwrap().*/Some/*->scala::Some.*//*->scala::Some.apply().*/(Some/*->scala::Some.*//*->scala::Some.apply().*/(1)).unwrap/*->_empty_::Enums.`<:<`.given_T().*/ - enum Planet/*<-_empty_::Enums.Planet#*/(mass/*<-_empty_::Enums.Planet#mass.*/: Double/*->scala::Double#*/, radius/*<-_empty_::Enums.Planet#radius.*/: Double/*->scala::Double#*/) extends Enum/*->java::lang::Enum#*/[Planet/*->_empty_::Enums.Planet#*/]/*->java::lang::Enum#``().*/: + enum Planet/*<-_empty_::Enums.Planet#*/(mass/*<-_empty_::Enums.Planet#mass.*/: Double/*->scala::Double#*/, radius/*<-_empty_::Enums.Planet#radius.*/: Double/*->scala::Double#*/) extends Enum/*->java::lang::Enum#*/[Planet/*->_empty_::Enums.Planet#*/]/*->java::lang::Enum#``().*/ with private final val G/*<-_empty_::Enums.Planet#G.*/ = 6.67300E-11 def surfaceGravity/*<-_empty_::Enums.Planet#surfaceGravity().*/ = G/*->_empty_::Enums.Planet#G.*/ */*->scala::Double#`*`(+6).*/ mass/*->_empty_::Enums.Planet#mass.*/ //*->scala::Double#`::`(+6).*/ (radius/*->_empty_::Enums.Planet#radius.*/ */*->scala::Double#`*`(+6).*/ radius/*->_empty_::Enums.Planet#radius.*/) def surfaceWeight/*<-_empty_::Enums.Planet#surfaceWeight().*/(otherMass/*<-_empty_::Enums.Planet#surfaceWeight().(otherMass)*/: Double/*->scala::Double#*/) = otherMass/*->_empty_::Enums.Planet#surfaceWeight().(otherMass)*/ */*->scala::Double#`*`(+6).*/ surfaceGravity/*->_empty_::Enums.Planet#surfaceGravity().*/ diff --git a/tests/semanticdb/expect/Enums.scala b/tests/semanticdb/expect/Enums.scala index 3d666fb618a9..353b9206f905 100644 --- a/tests/semanticdb/expect/Enums.scala +++ b/tests/semanticdb/expect/Enums.scala @@ -1,17 +1,17 @@ -object Enums: +object Enums with import <:<._ - enum Colour: + enum Colour with import Colour.Red case Red, Green, Blue - enum Directions: + enum Directions with case North, East, South, West - enum Suits derives CanEqual: + enum Suits derives CanEqual with case Hearts, Spades, Clubs, Diamonds - object Suits: + object Suits with extension (suit: Suits) def isRed: Boolean = suit == Hearts || suit == Diamonds @@ -19,7 +19,7 @@ object Enums: case Spades | Clubs => true case _ => false - enum WeekDays: + enum WeekDays with case Monday case Tuesday case Wednesday @@ -28,25 +28,25 @@ object Enums: case Saturday case Sunday - enum Coin(value: Int): + enum Coin(value: Int) with case Penny extends Coin(1) case Nickel extends Coin(5) case Dime extends Coin(10) case Quarter extends Coin(25) case Dollar extends Coin(100) - enum Maybe[+A]: + enum Maybe[+A] with case Just(value: A) case None - enum Tag[A]: + enum Tag[A] with case IntTag extends Tag[Int] case BooleanTag extends Tag[Boolean] - enum <:<[-A, B]: + enum <:<[-A, B] with case Refl[C]() extends (C <:< C) - object <:< : + object <:< with given [T]: (T <:< T) = Refl() extension [A, B](opt: Option[A]) def unwrap(using ev: A <:< Option[B]): Option[B] = ev match @@ -54,7 +54,7 @@ object Enums: val some1 = Some(Some(1)).unwrap - enum Planet(mass: Double, radius: Double) extends Enum[Planet]: + enum Planet(mass: Double, radius: Double) extends Enum[Planet] with private final val G = 6.67300E-11 def surfaceGravity = G * mass / (radius * radius) def surfaceWeight(otherMass: Double) = otherMass * surfaceGravity diff --git a/tests/semanticdb/expect/Givens.expect.scala b/tests/semanticdb/expect/Givens.expect.scala index 126c1f8e9919..4089ad837ed3 100644 --- a/tests/semanticdb/expect/Givens.expect.scala +++ b/tests/semanticdb/expect/Givens.expect.scala @@ -1,7 +1,7 @@ package a package b -object Givens/*<-a::b::Givens.*/: +object Givens/*<-a::b::Givens.*/ with extension [A/*<-a::b::Givens.sayHello().[A]*/](any/*<-a::b::Givens.sayHello().(any)*/: A/*->a::b::Givens.sayHello().[A]*/) def sayHello/*<-a::b::Givens.sayHello().*/ = s"/*->scala::StringContext.apply().*/Hello, I am $any/*->a::b::Givens.sayHello().(any)*/"/*->scala::StringContext#s().*/ @@ -14,7 +14,7 @@ object Givens/*<-a::b::Givens.*/: val goodbye1/*<-a::b::Givens.goodbye1.*/ = /*->a::b::Givens.sayGoodbye().*/1.sayGoodbye val soLong1/*<-a::b::Givens.soLong1.*/ = /*->a::b::Givens.saySoLong().*/1.saySoLong - trait Monoid/*<-a::b::Givens.Monoid#*/[A/*<-a::b::Givens.Monoid#[A]*/]: + trait Monoid/*<-a::b::Givens.Monoid#*/[A/*<-a::b::Givens.Monoid#[A]*/] with def empty/*<-a::b::Givens.Monoid#empty().*/: A/*->a::b::Givens.Monoid#[A]*/ extension (x/*<-a::b::Givens.Monoid#combine().(x)*/: A/*->a::b::Givens.Monoid#[A]*/) def combine/*<-a::b::Givens.Monoid#combine().*/(y/*<-a::b::Givens.Monoid#combine().(y)*/: A/*->a::b::Givens.Monoid#[A]*/): A/*->a::b::Givens.Monoid#[A]*/ diff --git a/tests/semanticdb/expect/Givens.scala b/tests/semanticdb/expect/Givens.scala index 819d70cfadca..5f22df9416b6 100644 --- a/tests/semanticdb/expect/Givens.scala +++ b/tests/semanticdb/expect/Givens.scala @@ -1,7 +1,7 @@ package a package b -object Givens: +object Givens with extension [A](any: A) def sayHello = s"Hello, I am $any" @@ -14,7 +14,7 @@ object Givens: val goodbye1 = 1.sayGoodbye val soLong1 = 1.saySoLong - trait Monoid[A]: + trait Monoid[A] with def empty: A extension (x: A) def combine(y: A): A diff --git a/tests/semanticdb/expect/inlineconsume.expect.scala b/tests/semanticdb/expect/inlineconsume.expect.scala index 8ffe432064d4..7126236c1205 100644 --- a/tests/semanticdb/expect/inlineconsume.expect.scala +++ b/tests/semanticdb/expect/inlineconsume.expect.scala @@ -2,5 +2,5 @@ package inlineconsume import inlinedefs.FakePredef/*->inlinedefs::FakePredef.*/.assert/*->inlinedefs::FakePredef.assert().*/ -class Foo/*<-inlineconsume::Foo#*/: +class Foo/*<-inlineconsume::Foo#*/ with def test/*<-inlineconsume::Foo#test().*/ = assert/*->inlinedefs::FakePredef.assert().*/(3 >/*->scala::Int#`>`(+3).*/ 2) diff --git a/tests/semanticdb/expect/inlineconsume.scala b/tests/semanticdb/expect/inlineconsume.scala index db7130c50515..3c15686f66a9 100644 --- a/tests/semanticdb/expect/inlineconsume.scala +++ b/tests/semanticdb/expect/inlineconsume.scala @@ -2,5 +2,5 @@ package inlineconsume import inlinedefs.FakePredef.assert -class Foo: +class Foo with def test = assert(3 > 2) diff --git a/tests/semanticdb/expect/inlinedefs.expect.scala b/tests/semanticdb/expect/inlinedefs.expect.scala index c0e1a8913c0a..9e3da263e558 100644 --- a/tests/semanticdb/expect/inlinedefs.expect.scala +++ b/tests/semanticdb/expect/inlinedefs.expect.scala @@ -1,6 +1,6 @@ package inlinedefs -object FakePredef/*<-inlinedefs::FakePredef.*/: +object FakePredef/*<-inlinedefs::FakePredef.*/ with /** Super long padded documentation * Lorem ipsum dolor sit amet, consectetur adipiscing elit, diff --git a/tests/semanticdb/expect/inlinedefs.scala b/tests/semanticdb/expect/inlinedefs.scala index 7902a9750b4b..0598d2dee4d0 100644 --- a/tests/semanticdb/expect/inlinedefs.scala +++ b/tests/semanticdb/expect/inlinedefs.scala @@ -1,6 +1,6 @@ package inlinedefs -object FakePredef: +object FakePredef with /** Super long padded documentation * Lorem ipsum dolor sit amet, consectetur adipiscing elit, diff --git a/tests/sjs-junit/test/org/scalajs/testsuite/compiler/EnumTestScala3.scala b/tests/sjs-junit/test/org/scalajs/testsuite/compiler/EnumTestScala3.scala index 01bdb6ccc954..93b135de6576 100644 --- a/tests/sjs-junit/test/org/scalajs/testsuite/compiler/EnumTestScala3.scala +++ b/tests/sjs-junit/test/org/scalajs/testsuite/compiler/EnumTestScala3.scala @@ -3,7 +3,7 @@ package org.scalajs.testsuite.compiler import org.junit.Assert._ import org.junit.Test -class EnumTestScala3: +class EnumTestScala3 with import EnumTestScala3._ @Test def testColor1(): Unit = @@ -141,26 +141,26 @@ class EnumTestScala3: end testOpt -object EnumTestScala3: +object EnumTestScala3 with - enum Color1 derives CanEqual: + enum Color1 derives CanEqual with case Red, Green, Blue - enum Color2 extends java.lang.Enum[Color2] derives CanEqual: + enum Color2 extends java.lang.Enum[Color2] derives CanEqual with case Red, Green, Blue // test "non-simple" cases with anonymous subclasses - enum Currency1(val dollarValue: Double) derives CanEqual: + enum Currency1(val dollarValue: Double) derives CanEqual with case Dollar extends Currency1(1.0) case SwissFanc extends Currency1(1.09) case Euro extends Currency1(1.18) - enum Currency2(val dollarValue: Double) extends java.lang.Enum[Currency2] derives CanEqual: + enum Currency2(val dollarValue: Double) extends java.lang.Enum[Currency2] derives CanEqual with case Dollar extends Currency2(1.0) case SwissFanc extends Currency2(1.09) case Euro extends Currency2(1.18) - enum Opt[+T]: + enum Opt[+T] with case Sm[+T1](value: T1) extends Opt[T1] case Nn extends Opt[Nothing] From 4da2806da2ab109ff6f1b0d307c6fb7973f17a68 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Tue, 19 Jan 2021 18:52:09 +0100 Subject: [PATCH 2/9] Allow self types after with --- .../dotty/tools/dotc/parsing/Parsers.scala | 117 +++++++++++++----- .../dotty/tools/dotc/reporting/messages.scala | 1 + docs/docs/internals/syntax.md | 7 +- tests/neg/with-template.check | 22 ++++ tests/neg/with-template.scala | 14 +++ tests/pos/i10080.scala | 3 - tests/pos/indent.scala | 7 +- 7 files changed, 131 insertions(+), 40 deletions(-) create mode 100644 tests/neg/with-template.check create mode 100644 tests/neg/with-template.scala diff --git a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala index af607397d036..786625925712 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala @@ -196,6 +196,7 @@ object Parsers { def isTemplateIntro = templateIntroTokens contains in.token def isDclIntro = dclIntroTokens contains in.token def isStatSeqEnd = in.isNestedEnd || in.token == EOF || in.token == RPAREN + def isTemplateBodyStart = in.token == WITH || in.isNestedStart def mustStartStat = mustStartStatTokens contains in.token /** Is current token a hard or soft modifier (in modifier position or not)? */ @@ -919,6 +920,39 @@ object Parsers { val next = in.lookahead.token next == LBRACKET || next == LPAREN + /** Does a template start after `with`? This is the case if either + * - the next token is `{` + * - the `with` is at the end of a line + * (except for source = 3.0-migration, when a warning is issued) + * - the next tokens is `` or `this` and the one after it is `:` or `=>` + * (i.e. we see the start of a self type) + */ + def followingIsTemplateStart() = + val lookahead = in.LookaheadScanner() + lookahead.nextToken() + lookahead.token == LBRACE + || lookahead.isAfterLineEnd + && { + if migrateTo3 then + warning( + em"""In Scala 3, `with` at the end of a line will start definitions, + |so it cannot be used in front of a parent constructor anymore. + |Place the `with` at the beginning of the next line instead.""") + false + else + true + } + || (lookahead.isIdent || lookahead.token == THIS) + && { + lookahead.nextToken() + lookahead.token == COLON + && { // needed only as long as we support significant colon at eol + lookahead.nextToken() + !lookahead.isAfterLineEnd + } + || lookahead.token == ARROW + } + /* --------- OPERAND/OPERATOR STACK --------------------------------------- */ var opStack: List[OpInfo] = Nil @@ -1281,14 +1315,14 @@ object Parsers { in.sourcePos()) patch(source, Span(in.offset), " ") - def possibleTemplateStart(isNew: Boolean = false): Unit = + def possibleTemplateStart(): Unit = in.observeColonEOL() - if in.token == COLONEOL || in.token == WITH then + if in.token == COLONEOL then if in.lookahead.isIdent(nme.end) then in.token = NEWLINE else in.nextToken() if in.token != INDENT && in.token != LBRACE then - syntaxErrorOrIncomplete(i"indented definitions expected, ${in} found") + syntaxErrorOrIncomplete(ExpectedTokenButFound(INDENT, in.token)) else newLineOptWhenFollowedBy(LBRACE) @@ -2313,13 +2347,11 @@ object Parsers { val start = in.skipToken() def reposition(t: Tree) = t.withSpan(Span(start, in.lastOffset)) possibleTemplateStart() - val parents = - if in.isNestedStart then Nil - else constrApp() :: withConstrApps() + val parents = if isTemplateBodyStart then Nil else constrApp() :: withConstrApps() colonAtEOLOpt() - possibleTemplateStart(isNew = true) + possibleTemplateStart() parents match { - case parent :: Nil if !in.isNestedStart => + case parent :: Nil if !isTemplateBodyStart => reposition(if (parent.isType) ensureApplied(wrapNew(parent)) else parent) case _ => New(reposition(templateBodyOpt(emptyConstructor, parents, Nil))) @@ -3643,21 +3675,7 @@ object Parsers { /** `{`with` ConstrApp} but no EOL allowed after `with`. */ def withConstrApps(): List[Tree] = - def isTemplateStart = - val la = in.lookahead - la.token == LBRACE - || la.isAfterLineEnd - && { - if migrateTo3 then - warning( - em"""In Scala 3, `with` at the end of a line will start definitions, - |so it cannot be used in front of a parent constructor anymore. - |Place the `with` at the beginning of the next line instead.""") - false - else - true - } - if in.token == WITH && !isTemplateStart then + if in.token == WITH && !followingIsTemplateStart() then in.nextToken() constrApp() :: withConstrApps() else Nil @@ -3701,18 +3719,20 @@ object Parsers { template(constr) else possibleTemplateStart() - if in.isNestedStart then + if isTemplateBodyStart then template(constr) else checkNextNotIndented() Template(constr, Nil, Nil, EmptyValDef, Nil) - /** TemplateBody ::= [nl] `{' TemplateStatSeq `}' - * EnumBody ::= [nl] ‘{’ [SelfType] EnumStat {semi EnumStat} ‘}’ + /** TemplateBody ::= [nl | ‘with’] `{' TemplateStatSeq `}' + * | ‘with’ [SelfType] indent TemplateStats outdent + * EnumBody ::= [nl | ‘with’] ‘{’ [SelfType] EnumStats ‘}’ + * | ‘with’ [SelfType] indent EnumStats outdent */ def templateBodyOpt(constr: DefDef, parents: List[Tree], derived: List[Tree]): Template = val (self, stats) = - if in.isNestedStart then + if isTemplateBodyStart then templateBody() else checkNextNotIndented() @@ -3720,13 +3740,45 @@ object Parsers { Template(constr, parents, derived, self, stats) def templateBody(): (ValDef, List[Tree]) = - val r = inDefScopeBraces(templateStatSeq(), rewriteWithColon = true) + val givenSelf = + if in.token == WITH then + in.nextToken() + selfDefOpt() + else EmptyValDef + val r = inDefScopeBraces(templateStatSeq(givenSelf), rewriteWithColon = true) if in.token == WITH then syntaxError(EarlyDefinitionsNotSupported()) in.nextToken() template(emptyConstructor) r + /** SelfType ::= id [‘:’ InfixType] ‘=>’ + * | ‘this’ ‘:’ InfixType ‘=>’ + * Only called immediately after a `with`, in which case it must in turn + * be followed by `INDENT`. + */ + def selfDefOpt(): ValDef = atSpan(in.offset) { + val vd = + if in.isIdent then + val selfName = ident() + if in.token == COLON then + in.nextToken() + makeSelfDef(selfName, infixType()) + else + makeSelfDef(selfName, TypeTree()) + else if in.token == THIS then + in.nextToken() + accept(COLON) + makeSelfDef(nme.WILDCARD, infixType()) + else + EmptyValDef + if !vd.isEmpty then + accept(ARROW) + if in.token != INDENT then + syntaxErrorOrIncomplete(ExpectedTokenButFound(INDENT, in.token)) + vd + } + /** with Template, with EOL interpreted */ def withTemplate(constr: DefDef, parents: List[Tree]): Template = if in.token != WITH then syntaxError(em"`with` expected") @@ -3800,10 +3852,10 @@ object Parsers { * EnumStat ::= TemplateStat * | Annotations Modifiers EnumCase */ - def templateStatSeq(): (ValDef, List[Tree]) = checkNoEscapingPlaceholders { - var self: ValDef = EmptyValDef + def templateStatSeq(givenSelf: ValDef = EmptyValDef): (ValDef, List[Tree]) = checkNoEscapingPlaceholders { + var self = givenSelf val stats = new ListBuffer[Tree] - if (isExprIntro && !isDefIntro(modifierTokens)) { + if (self.isEmpty && isExprIntro && !isDefIntro(modifierTokens)) { val first = expr1() if (in.token == ARROW) { first match { @@ -3956,7 +4008,7 @@ object Parsers { possibleTemplateStart() if in.token == EOF then ts += makePackaging(start, pkg, List()) - else if in.isNestedStart then + else if isTemplateBodyStart then ts += inDefScopeBraces(makePackaging(start, pkg, topStatSeq()), rewriteWithColon = true) continue = true else @@ -3994,6 +4046,7 @@ object Parsers { } override def templateBody(): (ValDef, List[Thicket]) = { + if in.token == WITH then in.nextToken() skipBraces() (EmptyValDef, List(EmptyTree)) } diff --git a/compiler/src/dotty/tools/dotc/reporting/messages.scala b/compiler/src/dotty/tools/dotc/reporting/messages.scala index f79ae8e2c929..e7d0f407a5bf 100644 --- a/compiler/src/dotty/tools/dotc/reporting/messages.scala +++ b/compiler/src/dotty/tools/dotc/reporting/messages.scala @@ -1126,6 +1126,7 @@ import transform.SymUtils._ def msg = val expectedText = if (Tokens.isIdentifier(expected)) "an identifier" + else if expected == Tokens.INDENT then "indented definitions" else Tokens.showToken(expected) em"""${expectedText} expected, but ${foundText} found""" diff --git a/docs/docs/internals/syntax.md b/docs/docs/internals/syntax.md index 59274eb85ab9..3d7ed647501e 100644 --- a/docs/docs/internals/syntax.md +++ b/docs/docs/internals/syntax.md @@ -148,7 +148,7 @@ FunParamClause ::= ‘(’ TypedFunParam {‘,’ TypedFunParam } ‘)’ TypedFunParam ::= id ‘:’ Type MatchType ::= InfixType `match` ‘{’ TypeCaseClauses ‘}’ InfixType ::= RefinedType {id [nl] RefinedType} InfixOp(t1, op, t2) -RefinedType ::= WithType {[nl] Refinement} RefinedTypeTree(t, ds) +RefinedType ::= WithType {[nl | ‘with’] Refinement} RefinedTypeTree(t, ds) WithType ::= AnnotType {‘with’ AnnotType} (deprecated) AnnotType ::= SimpleType {Annotation} Annotated(t, annot) @@ -401,6 +401,7 @@ ConstrExpr ::= SelfInvocation SelfInvocation ::= ‘this’ ArgumentExprs {ArgumentExprs} TemplateBody ::= [nl | ‘with’] ‘{’ [SelfType] TemplateStat {semi TemplateStat} ‘}’ + | ‘with’ [SelfType] indent TemplateStats outdent TemplateStat ::= Import | Export | {Annotation [nl]} {Modifier} Def @@ -412,7 +413,9 @@ TemplateStat ::= Import SelfType ::= id [‘:’ InfixType] ‘=>’ ValDef(_, name, tpt, _) | ‘this’ ‘:’ InfixType ‘=>’ -EnumBody ::= [nl | ‘with’] ‘{’ [SelfType] EnumStat {semi EnumStat} ‘}’ +EnumBody ::= [nl | ‘with’] ‘{’ [SelfType] EnumStats ‘}’ + | ‘with’ [SelfType] indent EnumStats outdent +EnumStats ::= EnumStat {semi EnumStat} EnumStat ::= TemplateStat | {Annotation [nl]} {Modifier} EnumCase EnumCase ::= ‘case’ (id ClassConstr [‘extends’ ConstrApps]] | ids) diff --git a/tests/neg/with-template.check b/tests/neg/with-template.check new file mode 100644 index 000000000000..fd33b39c16f6 --- /dev/null +++ b/tests/neg/with-template.check @@ -0,0 +1,22 @@ +-- Error: tests/neg/with-template.scala:6:5 ---------------------------------------------------------------------------- +6 | B with // error // error this one allows an informative hint + | ^^^^ + | end of statement expected but 'with' found + | + | Maybe you meant to write a mixin in an extends clause? + | Note that this requires the `with` to come first now. + | I.e. + | + | with B +-- [E006] Not Found Error: tests/neg/with-template.scala:6:2 ----------------------------------------------------------- +6 | B with // error // error this one allows an informative hint + | ^ + | Not found: B + +longer explanation available when compiling with `-explain` +-- [E006] Not Found Error: tests/neg/with-template.scala:10:2 ---------------------------------------------------------- +10 | B { // error this one is harder since it is syntactically correct + | ^ + | Not found: B + +longer explanation available when compiling with `-explain` diff --git a/tests/neg/with-template.scala b/tests/neg/with-template.scala new file mode 100644 index 000000000000..f3f888226d4f --- /dev/null +++ b/tests/neg/with-template.scala @@ -0,0 +1,14 @@ +class A +trait B +trait C + +object Test extends A with + B with // error // error this one allows an informative hint + C + +object Test2 extends A with + B { // error this one is harder since it is syntactically correct + println("foo") + } + + diff --git a/tests/pos/i10080.scala b/tests/pos/i10080.scala index 15ca51e93a42..7fd859210910 100644 --- a/tests/pos/i10080.scala +++ b/tests/pos/i10080.scala @@ -1,5 +1,2 @@ -trait Foo with -end Foo - trait Bar end Bar diff --git a/tests/pos/indent.scala b/tests/pos/indent.scala index c6289884980a..9b389c360d1f 100644 --- a/tests/pos/indent.scala +++ b/tests/pos/indent.scala @@ -82,8 +82,7 @@ object Test with x < 10 do () -class Test2 with - self => +class Test2 with self: Test2 => def foo(x: Int) = if x < 0 then throw val ex = new AssertionError() @@ -98,9 +97,11 @@ class Test2 with end Test2 class Test3 with - self => + self => def foo = 1 +class Test4 with { val x = 5 } + import collection.mutable.HashMap class Coder(words: List[String]) with From 4b76087bb109023b7bf30a3e6316116f334bbf21 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Wed, 20 Jan 2021 12:50:49 +0100 Subject: [PATCH 3/9] Drop debug code in Scanner --- compiler/src/dotty/tools/dotc/parsing/Scanners.scala | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/parsing/Scanners.scala b/compiler/src/dotty/tools/dotc/parsing/Scanners.scala index 94d4225f165a..2c9c0cabf1e9 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Scanners.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Scanners.scala @@ -1338,7 +1338,7 @@ object Scanners { * InBraces a pair of braces { ... } * Indented a pair of ... tokens */ - abstract class Region(val code: String): + abstract class Region: /** The region enclosing this one, or `null` for the outermost region */ def outer: Region | Null @@ -1367,17 +1367,17 @@ object Scanners { knownWidth = enclosing.knownWidth end Region - case class InString(multiLine: Boolean, outer: Region) extends Region("IS") - case class InParens(prefix: Token, outer: Region) extends Region("IP") - case class InBraces(outer: Region) extends Region("IB") - case class InCase(outer: Region) extends Region("IC") + case class InString(multiLine: Boolean, outer: Region) extends Region + case class InParens(prefix: Token, outer: Region) extends Region + case class InBraces(outer: Region) extends Region + case class InCase(outer: Region) extends Region /** A class describing an indentation region. * @param width The principal indendation width * @param others Other indendation widths > width of lines in the same region * @param prefix The token before the initial of the region */ - case class Indented(width: IndentWidth, others: Set[IndentWidth], prefix: Token, outer: Region | Null) extends Region("II"): + case class Indented(width: IndentWidth, others: Set[IndentWidth], prefix: Token, outer: Region | Null) extends Region: knownWidth = width def topLevelRegion(width: IndentWidth) = Indented(width, Set(), EMPTY, null) From b0933d368d0a79778d924451c565180d29e9b855 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Wed, 20 Jan 2021 15:35:06 +0100 Subject: [PATCH 4/9] Adapt given instance definitions --- .../dotty/tools/dotc/parsing/Parsers.scala | 27 +++++++------------ docs/docs/internals/syntax.md | 3 +-- docs/docs/reference/contextual/givens.md | 3 +-- tests/pos-custom-args/erased/i7868.scala | 5 ++-- 4 files changed, 14 insertions(+), 24 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala index 786625925712..2b18ca28f663 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala @@ -3549,7 +3549,7 @@ object Parsers { syntaxError(i"extension clause can only define methods", stat.span) } - /** GivenDef ::= [GivenSig] (Type [‘=’ Expr] | StructuralInstance) + /** GivenDef ::= [GivenSig] (Type [‘=’ Expr] | ConstrApps TemplateBody) * GivenSig ::= [id] [DefTypeParamClause] {UsingParamClauses} ‘:’ */ def givenDef(start: Offset, mods: Modifiers, givenMod: Mod) = atSpan(start, nameStart) { @@ -3567,10 +3567,9 @@ object Parsers { newLinesOpt() val noParams = tparams.isEmpty && vparamss.isEmpty if !(name.isEmpty && noParams) then accept(COLON) - val parents = - if isSimpleLiteral then toplevelTyp() :: Nil - else constrApp() :: withConstrApps() + val parents = if isSimpleLiteral then toplevelTyp() :: Nil else constrApps() val parentsIsType = parents.length == 1 && parents.head.isType + newLineOptWhenFollowedBy(LBRACE) if in.token == EQUALS && parentsIsType then accept(EQUALS) mods1 |= Final @@ -3579,17 +3578,17 @@ object Parsers { ValDef(name, parents.head, subExpr()) else DefDef(name, joinParams(tparams, vparamss), parents.head, subExpr()) - else if in.token != WITH && parentsIsType then - if name.isEmpty then - syntaxError(em"anonymous given cannot be abstract") - DefDef(name, joinParams(tparams, vparamss), parents.head, EmptyTree) - else + else if isTemplateBodyStart then val tparams1 = tparams.map(tparam => tparam.withMods(tparam.mods | PrivateLocal)) val vparamss1 = vparamss.map(_.map(vparam => vparam.withMods(vparam.mods &~ Param | ParamAccessor | Protected))) - val templ = withTemplate(makeConstructor(tparams1, vparamss1), parents) + val templ = templateBodyOpt(makeConstructor(tparams1, vparamss1), parents, Nil) if noParams then ModuleDef(name, templ) else TypeDef(name.toTypeName, templ) + else + if name.isEmpty then + syntaxError(em"anonymous given cannot be abstract") + DefDef(name, joinParams(tparams, vparamss), parents.head, EmptyTree) end gdef finalizeDef(gdef, mods1, start) } @@ -3779,14 +3778,6 @@ object Parsers { vd } - /** with Template, with EOL interpreted */ - def withTemplate(constr: DefDef, parents: List[Tree]): Template = - if in.token != WITH then syntaxError(em"`with` expected") - possibleTemplateStart() // consumes a WITH token - val (self, stats) = templateBody() - Template(constr, parents, Nil, self, stats) - .withSpan(Span(constr.span.orElse(parents.head.span).start, in.lastOffset)) - /* -------- STATSEQS ------------------------------------------- */ /** Create a tree representing a packaging */ diff --git a/docs/docs/internals/syntax.md b/docs/docs/internals/syntax.md index 3d7ed647501e..31249aa4614e 100644 --- a/docs/docs/internals/syntax.md +++ b/docs/docs/internals/syntax.md @@ -385,9 +385,8 @@ ClassConstr ::= [ClsTypeParamClause] [ConstrMods] ClsParamClauses ConstrMods ::= {Annotation} [AccessModifier] ObjectDef ::= id [Template] ModuleDef(mods, name, template) // no constructor EnumDef ::= id ClassConstr InheritClauses EnumBody -GivenDef ::= [GivenSig] (Type [‘=’ Expr] | StructuralInstance) +GivenDef ::= [GivenSig] (Type [‘=’ Expr] | ConstrApps TemplateBody) GivenSig ::= [id] [DefTypeParamClause] {UsingParamClause} ‘:’ -- one of `id`, `DefParamClause`, `UsingParamClause` must be present -StructuralInstance ::= ConstrApp {‘with’ ConstrApp} TemplateBody Extension ::= ‘extension’ [DefTypeParamClause] ‘(’ DefParam ‘)’ {UsingParamClause}] ExtMethods ExtMethods ::= ExtMethod | [nl] ‘{’ ExtMethod {semi ExtMethod ‘}’ diff --git a/docs/docs/reference/contextual/givens.md b/docs/docs/reference/contextual/givens.md index 4cb18a09a4f5..c630c1d30e8a 100644 --- a/docs/docs/reference/contextual/givens.md +++ b/docs/docs/reference/contextual/givens.md @@ -153,11 +153,10 @@ Here is the syntax for given instances: ``` TmplDef ::= ... | ‘given’ GivenDef -GivenDef ::= [GivenSig] StructuralInstance +GivenDef ::= [GivenSig] ConstrApps TemplateBody | [GivenSig] Type ‘=’ Expr | [GivenSig] Type GivenSig ::= [id] [DefTypeParamClause] {UsingParamClause} ‘:’ -StructuralInstance ::= ConstrApp {‘with’ ConstrApp} ‘with’ TemplateBody ``` A given instance starts with the reserved word `given` and an optional _signature_. The signature diff --git a/tests/pos-custom-args/erased/i7868.scala b/tests/pos-custom-args/erased/i7868.scala index 2753cf444af4..1676c31bab2f 100644 --- a/tests/pos-custom-args/erased/i7868.scala +++ b/tests/pos-custom-args/erased/i7868.scala @@ -12,13 +12,14 @@ object Coproduct { object At { - given atHead[Head, Tail]: At[Head +: Tail, Head, 0] with { + given atHead[Head, Tail]: At[Head +: Tail, Head, 0] { def cast: Head <:< Head +: Tail = summon[Head <:< Head +: Tail] } given atTail[Head, Tail, Value, NextIndex <: Int] (using atNext: At[Tail, Value, NextIndex]) - : At[Head +: Tail, Value, S[NextIndex]] with + : At[Head +: Tail, Value, S[NextIndex]] + with val cast: Value <:< Head +: Tail = atNext.cast given [A](using A): (() => A) = { () => summon[A]} From d31eba1e860254d0cc661cc043d1ad4a53f891fe Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Wed, 20 Jan 2021 15:58:20 +0100 Subject: [PATCH 5/9] Restrict given instance syntax If a type is implemented, it must be an `AnnotType`, which is the only kind of type allowed in a ConstrApp or extends clause. --- compiler/src/dotty/tools/dotc/parsing/Parsers.scala | 6 ++++-- docs/docs/internals/syntax.md | 2 +- docs/docs/reference/contextual/givens.md | 4 ++-- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala index 2b18ca28f663..f13ab300d683 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala @@ -3549,7 +3549,7 @@ object Parsers { syntaxError(i"extension clause can only define methods", stat.span) } - /** GivenDef ::= [GivenSig] (Type [‘=’ Expr] | ConstrApps TemplateBody) + /** GivenDef ::= [GivenSig] (AnnotType [‘=’ Expr] | ConstrApps TemplateBody) * GivenSig ::= [id] [DefTypeParamClause] {UsingParamClauses} ‘:’ */ def givenDef(start: Offset, mods: Modifiers, givenMod: Mod) = atSpan(start, nameStart) { @@ -3567,7 +3567,9 @@ object Parsers { newLinesOpt() val noParams = tparams.isEmpty && vparamss.isEmpty if !(name.isEmpty && noParams) then accept(COLON) - val parents = if isSimpleLiteral then toplevelTyp() :: Nil else constrApps() + val parents = + if isSimpleLiteral then rejectWildcardType(annotType()) :: Nil + else constrApps() val parentsIsType = parents.length == 1 && parents.head.isType newLineOptWhenFollowedBy(LBRACE) if in.token == EQUALS && parentsIsType then diff --git a/docs/docs/internals/syntax.md b/docs/docs/internals/syntax.md index 31249aa4614e..17a1e0fddfe9 100644 --- a/docs/docs/internals/syntax.md +++ b/docs/docs/internals/syntax.md @@ -385,7 +385,7 @@ ClassConstr ::= [ClsTypeParamClause] [ConstrMods] ClsParamClauses ConstrMods ::= {Annotation} [AccessModifier] ObjectDef ::= id [Template] ModuleDef(mods, name, template) // no constructor EnumDef ::= id ClassConstr InheritClauses EnumBody -GivenDef ::= [GivenSig] (Type [‘=’ Expr] | ConstrApps TemplateBody) +GivenDef ::= [GivenSig] (AnnotType [‘=’ Expr] | ConstrApps TemplateBody) GivenSig ::= [id] [DefTypeParamClause] {UsingParamClause} ‘:’ -- one of `id`, `DefParamClause`, `UsingParamClause` must be present Extension ::= ‘extension’ [DefTypeParamClause] ‘(’ DefParam ‘)’ {UsingParamClause}] ExtMethods diff --git a/docs/docs/reference/contextual/givens.md b/docs/docs/reference/contextual/givens.md index c630c1d30e8a..2f3b8c61121e 100644 --- a/docs/docs/reference/contextual/givens.md +++ b/docs/docs/reference/contextual/givens.md @@ -154,8 +154,8 @@ Here is the syntax for given instances: TmplDef ::= ... | ‘given’ GivenDef GivenDef ::= [GivenSig] ConstrApps TemplateBody - | [GivenSig] Type ‘=’ Expr - | [GivenSig] Type + | [GivenSig] AnnotType ‘=’ Expr + | [GivenSig] AnnotType GivenSig ::= [id] [DefTypeParamClause] {UsingParamClause} ‘:’ ``` From 280f094577f0009623c72d98ddfffb36976108c9 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Wed, 20 Jan 2021 16:05:38 +0100 Subject: [PATCH 6/9] Allow `with` in refinements --- .../dotty/tools/dotc/parsing/Parsers.scala | 23 +++++++++---------- tests/pos/abstract-givens.scala | 9 ++++++++ tests/pos/refinements.scala | 4 ++++ 3 files changed, 24 insertions(+), 12 deletions(-) create mode 100644 tests/pos/abstract-givens.scala diff --git a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala index f13ab300d683..179193f538f6 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala @@ -1566,33 +1566,32 @@ object Parsers { def infixTypeRest(t: Tree): Tree = infixOps(t, canStartTypeTokens, refinedType, isType = true, isOperator = !isPostfixStar) - /** RefinedType ::= WithType {[nl] Refinement} + /** RefinedType ::= WithType {[nl | ‘with’] Refinement} */ val refinedType: () => Tree = () => refinedTypeRest(withType()) - def refinedTypeRest(t: Tree): Tree = { + def refinedTypeRest(t: Tree): Tree = argumentStart() - if (in.isNestedStart) + if isTemplateBodyStart then + if in.token == WITH then in.nextToken() refinedTypeRest(atSpan(startOffset(t)) { RefinedTypeTree(rejectWildcardType(t), refinement(indentOK = true)) }) else t - } /** WithType ::= AnnotType {`with' AnnotType} (deprecated) */ def withType(): Tree = withTypeRest(annotType()) def withTypeRest(t: Tree): Tree = - if in.token == WITH then - val withOffset = in.offset + def isRefinementStart = + val la = in.lookahead + la.isAfterLineEnd || la.token == LBRACE + if in.token == WITH && !isRefinementStart then in.nextToken() - if in.token == LBRACE || in.token == INDENT then - t - else - if sourceVersion.isAtLeast(`3.1`) then - deprecationWarning(DeprecatedWithOperator(), withOffset) - atSpan(startOffset(t)) { makeAndType(t, withType()) } + if sourceVersion.isAtLeast(`3.1`) then + deprecationWarning(DeprecatedWithOperator()) + atSpan(startOffset(t)) { makeAndType(t, withType()) } else t /** AnnotType ::= SimpleType {Annotation} diff --git a/tests/pos/abstract-givens.scala b/tests/pos/abstract-givens.scala new file mode 100644 index 000000000000..9e8b23b127bf --- /dev/null +++ b/tests/pos/abstract-givens.scala @@ -0,0 +1,9 @@ +class C { type T } +trait A with + given C with {} // concrete + given c0: C {} // concrete + given c1: C {} // concrete + given c2: (C {type T <: Int}) // abstract with refinement + +object B extends A with + override given c2: C with { type T = Int } diff --git a/tests/pos/refinements.scala b/tests/pos/refinements.scala index 3e509228584d..c59524e91924 100644 --- a/tests/pos/refinements.scala +++ b/tests/pos/refinements.scala @@ -10,6 +10,10 @@ trait UU { type UX val u: UX val x: this.type & { type UX = Int } + val x1: this.type { type UX = Int } + val x2: this.type with { type UX = Int } + val x3: this.type with + type UX = Int val y: Int = x.u val z: x.UX = y } From c45b7c90939994c3928e335817c21e037feaf79c Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Wed, 20 Jan 2021 16:37:18 +0100 Subject: [PATCH 7/9] More doc pages updates --- docs/docs/internals/explicit-nulls.md | 2 +- .../changed-features/implicit-resolution.md | 2 +- .../reference/changed-features/numeric-literals.md | 4 ++-- .../reference/changed-features/pattern-matching.md | 12 ++++++------ .../reference/changed-features/structural-types.md | 2 +- docs/docs/reference/contextual/context-functions.md | 2 +- docs/docs/reference/contextual/derivation-macro.md | 4 ++-- docs/docs/reference/contextual/derivation.md | 6 +++--- docs/docs/reference/contextual/given-imports.md | 8 ++++---- .../reference/contextual/multiversal-equality.md | 2 +- docs/docs/reference/dropped-features/delayed-init.md | 2 +- docs/docs/reference/enums/adts.md | 2 +- docs/docs/reference/enums/enums.md | 4 ++-- docs/docs/reference/metaprogramming/erased-terms.md | 10 +++++----- docs/docs/reference/metaprogramming/inline.md | 6 +++--- docs/docs/reference/metaprogramming/macros-spec.md | 2 +- docs/docs/reference/metaprogramming/macros.md | 10 +++++----- docs/docs/reference/new-types/intersection-types.md | 6 +++--- .../other-new-features/creator-applications.md | 2 +- .../docs/reference/other-new-features/indentation.md | 12 ++++++------ .../reference/other-new-features/opaques-details.md | 8 ++++---- docs/docs/reference/other-new-features/opaques.md | 8 ++++---- .../other-new-features/safe-initialization.md | 2 +- docs/docs/reference/other-new-features/targetName.md | 2 +- docs/docs/reference/other-new-features/type-test.md | 8 ++++---- 25 files changed, 64 insertions(+), 64 deletions(-) diff --git a/docs/docs/internals/explicit-nulls.md b/docs/docs/internals/explicit-nulls.md index 87348b46098d..c884a0a05642 100644 --- a/docs/docs/internals/explicit-nulls.md +++ b/docs/docs/internals/explicit-nulls.md @@ -111,7 +111,7 @@ The reason for casting to `x.type & T`, as opposed to just `T`, is that it allow support flow typing for paths of length greater than one. ```scala -abstract class Node: +abstract class Node with val x: String val next: Node | Null diff --git a/docs/docs/reference/changed-features/implicit-resolution.md b/docs/docs/reference/changed-features/implicit-resolution.md index ed212bb44085..49a2eec3c6ff 100644 --- a/docs/docs/reference/changed-features/implicit-resolution.md +++ b/docs/docs/reference/changed-features/implicit-resolution.md @@ -44,7 +44,7 @@ no longer applies. given a: A = A() - object o: + object o with given b: B = B() type C ``` diff --git a/docs/docs/reference/changed-features/numeric-literals.md b/docs/docs/reference/changed-features/numeric-literals.md index 397d4e57c7c2..ac39e4a060c5 100644 --- a/docs/docs/reference/changed-features/numeric-literals.md +++ b/docs/docs/reference/changed-features/numeric-literals.md @@ -86,7 +86,7 @@ whole numbers with a given radix, for numbers with a decimal point, and for numbers that can have both a decimal point and an exponent: ```scala -object FromDigits: +object FromDigits with /** A subclass of `FromDigits` that also allows to convert whole * number literals with a radix other than 10 @@ -203,7 +203,7 @@ into a macro, i.e. make it an inline method with a splice as right-hand side. To do this, replace the `FromDigits` instance in the `BigFloat` object by the following two definitions: ```scala -object BigFloat: +object BigFloat with ... class FromDigits extends FromDigits.Floating[BigFloat] with diff --git a/docs/docs/reference/changed-features/pattern-matching.md b/docs/docs/reference/changed-features/pattern-matching.md index 1f2ea964f95e..96e23336c71d 100644 --- a/docs/docs/reference/changed-features/pattern-matching.md +++ b/docs/docs/reference/changed-features/pattern-matching.md @@ -100,7 +100,7 @@ For example: ```scala -object Even: +object Even with def unapply(s: String): Boolean = s.size % 2 == 0 "even" match @@ -130,7 +130,7 @@ class FirstChars(s: String) extends Product with def productArity: Int = ??? def productElement(n: Int): Any = ??? -object FirstChars: +object FirstChars with def unapply(s: String): FirstChars = new FirstChars(s) "Hi!" match @@ -151,7 +151,7 @@ class Nat(val x: Int) with def get: Int = x def isEmpty = x < 0 -object Nat: +object Nat with def unapply(x: Int): Nat = new Nat(x) 5 match @@ -167,7 +167,7 @@ object Nat: - Pattern-matching on exactly `N` patterns with types `P1, P2, ..., PN` ```Scala -object ProdEmpty: +object ProdEmpty with def _1: Int = ??? def _2: String = ??? def isEmpty = true @@ -199,7 +199,7 @@ type X = { ```scala -object CharList: +object CharList with def unapplySeq(s: String): Option[Seq[Char]] = Some(s.toList) "example" match @@ -221,7 +221,7 @@ object CharList: ```Scala class Foo(val name: String, val children: Int *) -object Foo: +object Foo with def unapplySeq(f: Foo): Option[(String, Seq[Int])] = Some((f.name, f.children)) diff --git a/docs/docs/reference/changed-features/structural-types.md b/docs/docs/reference/changed-features/structural-types.md index 059f9b353e5a..5f2d49b455bb 100644 --- a/docs/docs/reference/changed-features/structural-types.md +++ b/docs/docs/reference/changed-features/structural-types.md @@ -152,7 +152,7 @@ defines the necessary `selectDynamic` member. `Vehicle` could also extend some other subclass of `scala.Selectable` that implements `selectDynamic` and `applyDynamic` differently. But if it does not extend a `Selectable` at all, the code would no longer typecheck: ```scala -trait Vehicle: +trait Vehicle with val wheels: Int val i3 = new Vehicle: // i3: Vehicle diff --git a/docs/docs/reference/contextual/context-functions.md b/docs/docs/reference/contextual/context-functions.md index c63e9015cbdf..56cfbf30fcc0 100644 --- a/docs/docs/reference/contextual/context-functions.md +++ b/docs/docs/reference/contextual/context-functions.md @@ -116,7 +116,7 @@ With that setup, the table construction code above compiles and expands to: 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. ```scala -object PostConditions: +object PostConditions with opaque type WrappedResult[T] = T def result[T](using r: WrappedResult[T]): T = r diff --git a/docs/docs/reference/contextual/derivation-macro.md b/docs/docs/reference/contextual/derivation-macro.md index 012da07abfee..44ab32612f32 100644 --- a/docs/docs/reference/contextual/derivation-macro.md +++ b/docs/docs/reference/contextual/derivation-macro.md @@ -142,7 +142,7 @@ import scala.quoted._ trait Eq[T]: def eqv(x: T, y: T): Boolean -object Eq: +object Eq with given Eq[String] with def eqv(x: String, y: String) = x == y @@ -195,7 +195,7 @@ object Eq: end derived end Eq -object Macro3: +object Macro3 with extension [T](inline x: T) inline def === (inline y: T)(using eq: Eq[T]): Boolean = eq.eqv(x, y) diff --git a/docs/docs/reference/contextual/derivation.md b/docs/docs/reference/contextual/derivation.md index c2fbb9ecda63..bd6e29c07dc6 100644 --- a/docs/docs/reference/contextual/derivation.md +++ b/docs/docs/reference/contextual/derivation.md @@ -40,7 +40,7 @@ They also provide minimal term level infrastructure to allow higher level librar derivation support. ```scala -sealed trait Mirror: +sealed trait Mirror with /** the type being mirrored */ type MirroredType @@ -57,7 +57,7 @@ sealed trait Mirror: /** The names of the elements of the type */ type MirroredElemLabels <: Tuple -object Mirror: +object Mirror with /** The Mirror for a product type */ trait Product extends Mirror: @@ -242,7 +242,7 @@ inline def summonAll[T <: Tuple]: List[Eq[_]] = trait Eq[T]: def eqv(x: T, y: T): Boolean -object Eq: +object Eq with given Eq[Int] with def eqv(x: Int, y: Int) = x == y diff --git a/docs/docs/reference/contextual/given-imports.md b/docs/docs/reference/contextual/given-imports.md index a6d813d06ee6..c3c342b571bf 100644 --- a/docs/docs/reference/contextual/given-imports.md +++ b/docs/docs/reference/contextual/given-imports.md @@ -6,12 +6,12 @@ title: "Importing Givens" A special form of import wildcard selector is used to import given instances. Example: ```scala -object A: +object A with class TC given tc: TC = ??? def f(using TC) = ??? -object B: +object B with import A._ import A.given ... @@ -22,7 +22,7 @@ of `A` _except_ the given instance `tc`. Conversely, the second import `import A The two import clauses can also be merged into one: ```scala -object B: +object B with import A.{given, _} ... ``` @@ -58,7 +58,7 @@ Importing all given instances of a parameterized type is expressed by wildcard a For instance, assuming the object ```scala -object Instances: +object Instances with given intOrd: Ordering[Int] = ... given listOrd[T: Ordering]: Ordering[List[T]] = ... given ec: ExecutionContext = ... diff --git a/docs/docs/reference/contextual/multiversal-equality.md b/docs/docs/reference/contextual/multiversal-equality.md index c3cc82bd688f..8df384b28de8 100644 --- a/docs/docs/reference/contextual/multiversal-equality.md +++ b/docs/docs/reference/contextual/multiversal-equality.md @@ -54,7 +54,7 @@ import annotation.implicitNotFound @implicitNotFound("Values of types ${L} and ${R} cannot be compared with == or !=") sealed trait CanEqual[-L, -R] -object CanEqual: +object CanEqual with object derived extends CanEqual[Any, Any] ``` diff --git a/docs/docs/reference/dropped-features/delayed-init.md b/docs/docs/reference/dropped-features/delayed-init.md index ca640185252d..f1bab9687e10 100644 --- a/docs/docs/reference/dropped-features/delayed-init.md +++ b/docs/docs/reference/dropped-features/delayed-init.md @@ -20,7 +20,7 @@ for benchmarking! Also, if you want to access the command line arguments, you need to use an explicit `main` method for that. ```scala -object Hello: +object Hello with def main(args: Array[String]) = println(s"Hello, ${args(0)}") ``` diff --git a/docs/docs/reference/enums/adts.md b/docs/docs/reference/enums/adts.md index 2cddf5d83fbb..463378d2391d 100644 --- a/docs/docs/reference/enums/adts.md +++ b/docs/docs/reference/enums/adts.md @@ -67,7 +67,7 @@ enum Option[+T] with case None => false case some => true -object Option: +object Option with def apply[T >: Null](x: T): Option[T] = if x == null then None else Some(x) diff --git a/docs/docs/reference/enums/enums.md b/docs/docs/reference/enums/enums.md index 37dc5c842a83..877aac6d3a66 100644 --- a/docs/docs/reference/enums/enums.md +++ b/docs/docs/reference/enums/enums.md @@ -6,7 +6,7 @@ title: "Enumerations" An enumeration is used to define a type consisting of a set of named values. ```scala -enum Color: +enum Color with case Red, Green, Blue ``` @@ -79,7 +79,7 @@ end Planet It is also possible to define an explicit companion object for an enum: ```scala -object Planet: +object Planet with def main(args: Array[String]) = val earthWeight = args(0).toDouble val mass = earthWeight / Earth.surfaceGravity diff --git a/docs/docs/reference/metaprogramming/erased-terms.md b/docs/docs/reference/metaprogramming/erased-terms.md index 1e7cde748d5a..bd5e861408c7 100644 --- a/docs/docs/reference/metaprogramming/erased-terms.md +++ b/docs/docs/reference/metaprogramming/erased-terms.md @@ -20,7 +20,7 @@ final class Off extends State @implicitNotFound("State must be Off") class IsOff[S <: State] -object IsOff: +object IsOff with given isOff: IsOff[Off] = new IsOff[Off] class Machine[S <: State] with @@ -118,14 +118,14 @@ final class Off extends State @implicitNotFound("State must be Off") class IsOff[S <: State] -object IsOff: +object IsOff with // will not be called at runtime for turnedOn, the // compiler will only require that this evidence exists given IsOff[Off] = new IsOff[Off] @implicitNotFound("State must be On") class IsOn[S <: State] -object IsOn: +object IsOn with // will not exist at runtime, the compiler will only // require that this evidence exists at compile time erased given IsOn[On] = new IsOn[On] @@ -135,7 +135,7 @@ class Machine[S <: State] private () with def turnedOn(using erased ev: IsOff[S]): Machine[On] = new Machine[On] def turnedOff(using erased ev: IsOn[S]): Machine[Off] = new Machine[Off] -object Machine: +object Machine with def newMachine(): Machine[Off] = new Machine[Off] @main def test = @@ -174,7 +174,7 @@ class Machine[S <: State] with case _: On => new Machine[Off] case _: Off => error("Turning off an already turned off machine") -object Machine: +object Machine with def newMachine(): Machine[Off] = println("newMachine") new Machine[Off] diff --git a/docs/docs/reference/metaprogramming/inline.md b/docs/docs/reference/metaprogramming/inline.md index a77540af5099..6484cf2cac83 100644 --- a/docs/docs/reference/metaprogramming/inline.md +++ b/docs/docs/reference/metaprogramming/inline.md @@ -9,10 +9,10 @@ title: Inline definition will be inlined at the point of use. Example: ```scala -object Config: +object Config with inline val logging = false -object Logger: +object Logger with private var indent = 0 @@ -235,7 +235,7 @@ inline val four: 4 = 4 It is also possible to have inline vals of types that do not have a syntax, such as `Short(4)`. ```scala -trait InlineConstants: +trait InlineConstants with inline val myShort: Short object Constants extends InlineConstants: diff --git a/docs/docs/reference/metaprogramming/macros-spec.md b/docs/docs/reference/metaprogramming/macros-spec.md index 8bdee4ba1eba..e855dd7a7746 100644 --- a/docs/docs/reference/metaprogramming/macros-spec.md +++ b/docs/docs/reference/metaprogramming/macros-spec.md @@ -211,7 +211,7 @@ given AsFunction1[T, U]: Conversion[Expr[T => U], Expr[T] => Expr[U]] with ``` This assumes an extractor ```scala -object Lambda: +object Lambda with def unapply[T, U](x: Expr[T => U]): Option[Expr[T] => Expr[U]] ``` Once we allow inspection of code via extractors, it’s tempting to also diff --git a/docs/docs/reference/metaprogramming/macros.md b/docs/docs/reference/metaprogramming/macros.md index 997252176fc3..09da411faa15 100644 --- a/docs/docs/reference/metaprogramming/macros.md +++ b/docs/docs/reference/metaprogramming/macros.md @@ -168,7 +168,7 @@ In some cases we want to remove the lambda from the code, for this we provide th describing a function into a function mapping trees to trees. ```scala -object Expr: +object Expr with ... def betaReduce[...](...)(...): ... = ... ``` @@ -231,7 +231,7 @@ a compiler through staging. ```scala import scala.quoted._ -enum Exp: +enum Exp with case Num(n: Int) case Plus(e1: Exp, e2: Exp) case Var(x: String) @@ -284,7 +284,7 @@ The `Expr.apply` method is defined in package `quoted`: ```scala package quoted -object Expr: +object Expr with ... def apply[T: ToExpr](x: T)(using Quotes): Expr[T] = summon[ToExpr[T]].toExpr(x) @@ -391,7 +391,7 @@ a macro library and a quoted program. For instance, here’s the `assert` macro again together with a program that calls `assert`. ```scala -object Macros: +object Macros with inline def assert(inline expr: Boolean): Unit = ${ assertImpl('expr) } @@ -525,7 +525,7 @@ Assume we have two methods, one `map` that takes an `Expr[Array[T]]` and a function `f` and one `sum` that performs a sum by delegating to `map`. ```scala -object Macros: +object Macros with def map[T](arr: Expr[Array[T]], f: Expr[T] => Expr[Unit]) (using Type[T], Quotes): Expr[Unit] = '{ diff --git a/docs/docs/reference/new-types/intersection-types.md b/docs/docs/reference/new-types/intersection-types.md index cf232c621ace..1cbb99f1e9f0 100644 --- a/docs/docs/reference/new-types/intersection-types.md +++ b/docs/docs/reference/new-types/intersection-types.md @@ -10,7 +10,7 @@ Used on types, the `&` operator creates an intersection type. The type `S & T` represents values that are of the type `S` and `T` at the same time. ```scala -trait Resettable: +trait Resettable with def reset(): Unit trait Growable[T]: @@ -34,10 +34,10 @@ If a member appears in both `A` and `B`, its type in `A & B` is the intersection of its type in `A` and its type in `B`. For instance, assume the definitions: ```scala -trait A: +trait A with def children: List[A] -trait B: +trait B with def children: List[B] val x: A & B = new C diff --git a/docs/docs/reference/other-new-features/creator-applications.md b/docs/docs/reference/other-new-features/creator-applications.md index 0369e3f0c35b..6604edd8dc12 100644 --- a/docs/docs/reference/other-new-features/creator-applications.md +++ b/docs/docs/reference/other-new-features/creator-applications.md @@ -20,7 +20,7 @@ This works since a companion object with two `apply` methods is generated together with the class. The object looks like this: ```scala -object StringBuilder: +object StringBuilder with inline def apply(s: String): StringBuilder = new StringBuilder(s) inline def apply(): StringBuilder = new StringBuilder() ``` diff --git a/docs/docs/reference/other-new-features/indentation.md b/docs/docs/reference/other-new-features/indentation.md index da943737267b..223633f020df 100644 --- a/docs/docs/reference/other-new-features/indentation.md +++ b/docs/docs/reference/other-new-features/indentation.md @@ -117,16 +117,16 @@ Analogous rules apply for enum bodies and local packages containing nested defin With these new rules, the following constructs are all valid: ```scala -trait A: +trait A with def f: Int class C(x: Int) extends A with def f = x -object O: +object O with def f = 3 -enum Color: +enum Color with case Red, Green, Blue new A: @@ -285,7 +285,7 @@ package p1.p2: def f: String end C - object C: + object C with given C = new C: def f = "!" @@ -327,7 +327,7 @@ TopStat ::= ... | EndMarker 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. ```scala -enum IndentWidth: +enum IndentWidth with case Run(ch: Char, n: Int) case Conc(l: IndentWidth, r: Run) @@ -356,7 +356,7 @@ enum IndentWidth: case Conc(l, r) => s"$l, $r" -object IndentWidth: +object IndentWidth with private inline val MaxCached = 40 private val spaces = IArray.tabulate(MaxCached + 1)(new Run(' ', _)) diff --git a/docs/docs/reference/other-new-features/opaques-details.md b/docs/docs/reference/other-new-features/opaques-details.md index ef8d6ab0492f..ba7f843dcd28 100644 --- a/docs/docs/reference/other-new-features/opaques-details.md +++ b/docs/docs/reference/other-new-features/opaques-details.md @@ -33,7 +33,7 @@ type T >: L <: U A special case arises if the opaque type alias is defined in an object. Example: ```scala -object o: +object o with opaque type T = R ``` @@ -44,7 +44,7 @@ that `o.this.T` equals `R`. The two equalities compose. That is, inside `o`, it also known that `o.T` is equal to `R`. This means the following code type-checks: ```scala -object o: +object o with opaque type T = Int val x: Int = id(2) def id(x: o.T): o.T = x @@ -88,7 +88,7 @@ objects and classes and in all other source files. Example: opaque type A = String val x: A = "abc" -object obj: +object obj with val y: A = "abc" // error: found: "abc", required: A // in test2.scala @@ -100,7 +100,7 @@ object test1$package: opaque type A = String val x: A = "abc" -object obj: +object obj with val y: A = "abc" // error: cannot assign "abc" to opaque type alias A ``` The opaque type alias `A` is transparent in its scope, which includes the definition of `x`, but not the definitions of `obj` and `y`. diff --git a/docs/docs/reference/other-new-features/opaques.md b/docs/docs/reference/other-new-features/opaques.md index 5bed38293b21..9a19cdeb2b35 100644 --- a/docs/docs/reference/other-new-features/opaques.md +++ b/docs/docs/reference/other-new-features/opaques.md @@ -6,11 +6,11 @@ title: "Opaque Type Aliases" Opaque types aliases provide type abstraction without any overhead. Example: ```scala -object Logarithms: +object Logarithms with opaque type Logarithm = Double - object Logarithm: + object Logarithm with // These are the two ways to lift to the Logarithm type @@ -63,7 +63,7 @@ l / l2 // error: `/` is not a member of Logarithm Opaque type aliases can also come with bounds. Example: ```scala -object Access: +object Access with opaque type Permissions = Int opaque type PermissionChoice = Int @@ -110,7 +110,7 @@ it known outside the `Access` object that `Permission` is a subtype of the other two types. Hence, the following usage scenario type-checks. ```scala -object User: +object User with import Access._ case class Item(rights: Permissions) diff --git a/docs/docs/reference/other-new-features/safe-initialization.md b/docs/docs/reference/other-new-features/safe-initialization.md index 1a23474de166..34ef34c6f85f 100644 --- a/docs/docs/reference/other-new-features/safe-initialization.md +++ b/docs/docs/reference/other-new-features/safe-initialization.md @@ -39,7 +39,7 @@ The checker will report: Given the code below: ``` scala -object Trees: +object Trees with class ValDef { counter += 1 } class EmptyValDef extends ValDef val theEmptyValDef = new EmptyValDef diff --git a/docs/docs/reference/other-new-features/targetName.md b/docs/docs/reference/other-new-features/targetName.md index a1b8f9150c38..ef43e1086897 100644 --- a/docs/docs/reference/other-new-features/targetName.md +++ b/docs/docs/reference/other-new-features/targetName.md @@ -8,7 +8,7 @@ A `@targetName` annotation on a definition defines an alternate name for the imp ```scala import scala.annotation.targetName -object VecOps: +object VecOps with extension [T](xs: Vec[T]) @targetName("append") def ++= [T] (ys: Vec[T]): Vec[T] = ... diff --git a/docs/docs/reference/other-new-features/type-test.md b/docs/docs/reference/other-new-features/type-test.md index 72323c4a0bc4..52a10713db49 100644 --- a/docs/docs/reference/other-new-features/type-test.md +++ b/docs/docs/reference/other-new-features/type-test.md @@ -19,7 +19,7 @@ The second case is when an extractor takes an argument that is not a subtype of (x: X) match case y @ Y(n) => -object Y: +object Y with def unapply(x: Y): Some[Int] = ... ``` @@ -115,7 +115,7 @@ Given the following abstract definition of Peano numbers that provides two given ```scala import scala.reflect._ -trait Peano: +trait Peano with type Nat type Zero <: Nat type Succ <: Nat @@ -125,11 +125,11 @@ trait Peano: val Zero: Zero val Succ: SuccExtractor - trait SuccExtractor: + trait SuccExtractor with def apply(nat: Nat): Succ def unapply(nat: Succ): Option[Nat] - given typeTestOfZero: TypeTest[Nat, Zero] + given typeTestOfZero: TypeTest[Nat, Zero] given typeTestOfSucc: TypeTest[Nat, Succ] ``` From 95437d181044bfd689b9276ab92a959908745fc3 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Wed, 20 Jan 2021 18:20:58 +0100 Subject: [PATCH 8/9] Better prediction after `with` in types Also: generalize notion to get next token while suppressing indentation insertion --- .../dotty/tools/dotc/parsing/Parsers.scala | 46 +++++++++++-------- .../dotty/tools/dotc/parsing/Scanners.scala | 7 ++- .../src/dotty/tools/dotc/parsing/Tokens.scala | 1 - tests/neg/with-template.scala | 6 +++ 4 files changed, 39 insertions(+), 21 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala index 179193f538f6..819db0ad3d27 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala @@ -920,6 +920,16 @@ object Parsers { val next = in.lookahead.token next == LBRACKET || next == LPAREN + private def withEndMigrationWarning(): Boolean = + migrateTo3 + && { + warning( + em"""In Scala 3, `with` at the end of a line will start definitions, + |so it cannot be used in front of a parent constructor anymore. + |Place the `with` at the beginning of the next line instead.""") + true + } + /** Does a template start after `with`? This is the case if either * - the next token is `{` * - the `with` is at the end of a line @@ -931,17 +941,7 @@ object Parsers { val lookahead = in.LookaheadScanner() lookahead.nextToken() lookahead.token == LBRACE - || lookahead.isAfterLineEnd - && { - if migrateTo3 then - warning( - em"""In Scala 3, `with` at the end of a line will start definitions, - |so it cannot be used in front of a parent constructor anymore. - |Place the `with` at the beginning of the next line instead.""") - false - else - true - } + || lookahead.isAfterLineEnd && !withEndMigrationWarning() || (lookahead.isIdent || lookahead.token == THIS) && { lookahead.nextToken() @@ -953,6 +953,20 @@ object Parsers { || lookahead.token == ARROW } + /** Does a refinement start after `with`? This is the case if either + * - the next token is `{` + * - the `with` is at the end of a line and is followed by a token that starts a declaration + */ + def followingIsRefinementStart() = + val lookahead = in.LookaheadScanner() + lookahead.nextToken() + lookahead.token == LBRACE + || lookahead.isAfterLineEnd + && { + if lookahead.token == INDENT then lookahead.nextToken() + dclIntroTokens.contains(lookahead.token) + } + /* --------- OPERAND/OPERATOR STACK --------------------------------------- */ var opStack: List[OpInfo] = Nil @@ -1584,11 +1598,8 @@ object Parsers { def withType(): Tree = withTypeRest(annotType()) def withTypeRest(t: Tree): Tree = - def isRefinementStart = - val la = in.lookahead - la.isAfterLineEnd || la.token == LBRACE - if in.token == WITH && !isRefinementStart then - in.nextToken() + if in.token == WITH && !followingIsRefinementStart() then + in.nextTokenNoIndent() if sourceVersion.isAtLeast(`3.1`) then deprecationWarning(DeprecatedWithOperator()) atSpan(startOffset(t)) { makeAndType(t, withType()) } @@ -3858,8 +3869,7 @@ object Parsers { if (name != nme.ERROR) self = makeSelfDef(name, tpt).withSpan(first.span) } - in.token = SELFARROW // suppresses INDENT insertion after `=>` - in.nextToken() + in.nextTokenNoIndent() } else { stats += first diff --git a/compiler/src/dotty/tools/dotc/parsing/Scanners.scala b/compiler/src/dotty/tools/dotc/parsing/Scanners.scala index 2c9c0cabf1e9..dccd1a41dab1 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Scanners.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Scanners.scala @@ -323,6 +323,11 @@ object Scanners { printState() } + /** Like nextToken, but don't insert indent characters afterwards */ + def nextTokenNoIndent(): Unit = + token = EMPTY // this will suppress newline and indent insertion + nextToken() + final def printState() = if debugTokenStream && (showLookAheadOnDebug || !isInstanceOf[LookaheadScanner]) then print(s"[$show${if isInstanceOf[LookaheadScanner] then "(LA)" else ""}]") @@ -493,8 +498,6 @@ object Scanners { if canStartIndentTokens.contains(lastToken) then currentRegion = Indented(nextWidth, Set(), lastToken, currentRegion) insert(INDENT, offset) - else if lastToken == SELFARROW then - currentRegion.knownWidth = nextWidth else if (lastWidth != nextWidth) errorButContinue(spaceTabMismatchMsg(lastWidth, nextWidth)) currentRegion match { diff --git a/compiler/src/dotty/tools/dotc/parsing/Tokens.scala b/compiler/src/dotty/tools/dotc/parsing/Tokens.scala index c5f77533094d..bcaaaeda805f 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Tokens.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Tokens.scala @@ -204,7 +204,6 @@ object Tokens extends TokensCommon { final val QUOTE = 87; enter(QUOTE, "'") final val COLONEOL = 88; enter(COLONEOL, ":", ": at eol") - final val SELFARROW = 89; enter(SELFARROW, "=>") // reclassified ARROW following self-type /** XML mode */ final val XMLSTART = 99; enter(XMLSTART, "$XMLSTART$<") // TODO: deprecate diff --git a/tests/neg/with-template.scala b/tests/neg/with-template.scala index f3f888226d4f..881c78781c85 100644 --- a/tests/neg/with-template.scala +++ b/tests/neg/with-template.scala @@ -11,4 +11,10 @@ object Test2 extends A with println("foo") } +def foo: A with + B with + C = ??? + + + From 1173fccc51e215d51510696d3ac5614f1984ab75 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Wed, 20 Jan 2021 19:12:25 +0100 Subject: [PATCH 9/9] Special error message for extension (...) with --- compiler/src/dotty/tools/dotc/parsing/Parsers.scala | 7 +++++-- tests/neg/extension-colon.check | 4 ---- tests/neg/extension-colon.scala | 2 -- tests/neg/extension-with.check | 6 ++++++ tests/neg/extension-with.scala | 2 ++ 5 files changed, 13 insertions(+), 8 deletions(-) delete mode 100644 tests/neg/extension-colon.check delete mode 100644 tests/neg/extension-colon.scala create mode 100644 tests/neg/extension-with.check create mode 100644 tests/neg/extension-with.scala diff --git a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala index 819db0ad3d27..b5b3bc5beeb1 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala @@ -3619,8 +3619,11 @@ object Parsers { isUsingClause(extParams) do () leadParamss ++= paramClauses(givenOnly = true, numLeadParams = nparams) - if in.token == COLON then - syntaxError("no `:` expected here") + if in.token == WITH then + syntaxError( + i"""No `with` expected here. + | + |An extension clause is simply followed by one or more method definitions.""") in.nextToken() val methods = if isDefIntro(modifierTokens) then diff --git a/tests/neg/extension-colon.check b/tests/neg/extension-colon.check deleted file mode 100644 index 1760afe1ff50..000000000000 --- a/tests/neg/extension-colon.check +++ /dev/null @@ -1,4 +0,0 @@ --- Error: tests/neg/extension-colon.scala:1:18 ------------------------------------------------------------------------- -1 |extension (x: Int): // error - | ^ - | no `:` expected here diff --git a/tests/neg/extension-colon.scala b/tests/neg/extension-colon.scala deleted file mode 100644 index 61585d5488c2..000000000000 --- a/tests/neg/extension-colon.scala +++ /dev/null @@ -1,2 +0,0 @@ -extension (x: Int): // error - def foo = x diff --git a/tests/neg/extension-with.check b/tests/neg/extension-with.check new file mode 100644 index 000000000000..b331d7e5b783 --- /dev/null +++ b/tests/neg/extension-with.check @@ -0,0 +1,6 @@ +-- Error: tests/neg/extension-with.scala:1:19 -------------------------------------------------------------------------- +1 |extension (x: Int) with // error + | ^^^^ + | No `with` expected here. + | + | An extension clause is simply followed by one or more method definitions. diff --git a/tests/neg/extension-with.scala b/tests/neg/extension-with.scala new file mode 100644 index 000000000000..0e19cc70466b --- /dev/null +++ b/tests/neg/extension-with.scala @@ -0,0 +1,2 @@ +extension (x: Int) with // error + def foo = x