Skip to content

Commit 2dba45c

Browse files
Merge pull request #8270 from dotty-staging/change-given-using-2
Drop given parameter syntax
2 parents 6a949f2 + d008b78 commit 2dba45c

File tree

47 files changed

+133
-178
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

47 files changed

+133
-178
lines changed

community-build/test/scala/dotty/communitybuild/CommunityBuildTest.scala

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ sealed trait CommunityProject:
4747
/** Is this project running in the test or update mode in the
4848
* context of the given suite? @see `run` for more details.
4949
*/
50-
final def isUpdateMode(given suite: CommunityBuildTest) =
50+
final def isUpdateMode(using suite: CommunityBuildTest) =
5151
suite.isInstanceOf[CommunityBuildUpdate]
5252

5353
/** Depending on the mode of operation, either
@@ -60,7 +60,7 @@ sealed trait CommunityProject:
6060
* and avoid network overhead. See https://github.com/lampepfl/dotty-drone
6161
* for more infrastructural details.
6262
*/
63-
final def run()(given suite: CommunityBuildTest) =
63+
final def run()(using suite: CommunityBuildTest) =
6464
val runCmd = if isUpdateMode then updateCommand else testCommand
6565
if !isUpdateMode then dependencies.foreach(_.publish())
6666
suite.test(project, binaryName, runCommandsArgs :+ runCmd)

compiler/src/dotty/tools/dotc/core/Flags.scala

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ object Flags {
2222

2323
type Flag = opaques.Flag
2424

25-
given extension (x: FlagSet) with
25+
extension on (x: FlagSet) {
2626

2727
def bits: Long = opaques.toBits(x)
2828

@@ -150,7 +150,7 @@ object Flags {
150150

151151
/** The string representation of the given flag set */
152152
def flagsString: String = x.flagStrings("").mkString(" ")
153-
end given
153+
}
154154

155155
def termFlagSet(x: Long) = FlagSet(TERMS | x)
156156

compiler/src/dotty/tools/dotc/parsing/Parsers.scala

Lines changed: 46 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -917,7 +917,7 @@ object Parsers {
917917
def followingIsParamOrGivenType() =
918918
val lookahead = in.LookaheadScanner()
919919
lookahead.nextToken()
920-
if startParamOrGivenTypeTokens.contains(lookahead.token)
920+
if startParamTokens.contains(lookahead.token)
921921
|| lookahead.isIdent(nme.using)
922922
then true
923923
else if lookahead.token == IDENTIFIER then
@@ -1450,8 +1450,6 @@ object Parsers {
14501450
case MATCH => matchType(t)
14511451
case FORSOME => syntaxError(ExistentialTypesNoLongerSupported()); t
14521452
case _ =>
1453-
if (imods.isOneOf(GivenOrImplicit) && !t.isInstanceOf[FunctionWithMods])
1454-
syntaxError(ImplicitTypesCanOnlyBeFunctionTypes(), implicitKwPos(start))
14551453
if (imods.is(Erased) && !t.isInstanceOf[FunctionWithMods])
14561454
syntaxError(ErasedTypesCanOnlyBeFunctionTypes(), implicitKwPos(start))
14571455
t
@@ -2299,7 +2297,7 @@ object Parsers {
22992297
def parArgumentExprs(): (List[Tree], Boolean) = inParens {
23002298
if in.token == RPAREN then
23012299
(Nil, false)
2302-
else if in.token == GIVEN || isIdent(nme.using) then
2300+
else if isIdent(nme.using) then
23032301
in.nextToken()
23042302
(commaSeparated(argumentExpr), true)
23052303
else
@@ -2786,7 +2784,7 @@ object Parsers {
27862784
normalize(loop(start))
27872785
}
27882786

2789-
val funTypeArgMods: BitSet = BitSet(GIVEN, ERASED)
2787+
val funTypeArgMods: BitSet = BitSet(ERASED)
27902788

27912789
/** Wrap annotation or constructor in New(...).<init> */
27922790
def wrapNew(tpt: Tree): Select = Select(New(tpt), nme.CONSTRUCTOR)
@@ -2912,7 +2910,7 @@ object Parsers {
29122910
def paramMods() =
29132911
if in.token == IMPLICIT then addParamMod(() => Mod.Implicit())
29142912
else
2915-
if in.token == GIVEN || isIdent(nme.using) then addParamMod(() => Mod.Given())
2913+
if isIdent(nme.using) then addParamMod(() => Mod.Given())
29162914
if in.token == ERASED then addParamMod(() => Mod.Erased())
29172915

29182916
def param(): ValDef = {
@@ -3508,70 +3506,54 @@ object Parsers {
35083506
var mods1 = addMod(mods, instanceMod)
35093507
val hasGivenSig = followingIsGivenSig()
35103508
val nameStart = in.offset
3511-
val (name, isOldExtension) =
3512-
if isIdent && hasGivenSig then
3513-
(ident(), in.token == COLON && in.lookaheadIn(nme.extension))
3514-
else
3515-
(EmptyTermName, isIdent(nme.extension))
3509+
val name = if isIdent && hasGivenSig then ident() else EmptyTermName
35163510

35173511
val gdef = in.endMarkerScope(if name.isEmpty then GIVEN else name) {
3518-
if isOldExtension then
3519-
if (in.token == COLON) in.nextToken()
3520-
assert(ident() == nme.extension)
3521-
val tparams = typeParamClauseOpt(ParamOwner.Def)
3522-
val extParams = paramClause(0, prefix = true)
3523-
val givenParamss = paramClauses(givenOnly = true)
3524-
possibleTemplateStart()
3525-
val templ = templateBodyOpt(
3526-
makeConstructor(tparams, extParams :: givenParamss), Nil, Nil)
3527-
templ.body.foreach(checkExtensionMethod(tparams, _))
3528-
ModuleDef(name, templ)
3529-
else
3530-
val hasLabel = !name.isEmpty && in.token == COLON || isIdent(nme.as)
3531-
if hasLabel then in.nextToken()
3532-
val tparams = typeParamClauseOpt(ParamOwner.Def)
3533-
val paramsStart = in.offset
3534-
val vparamss =
3535-
if in.token == LPAREN && followingIsParamOrGivenType()
3536-
then paramClauses()
3537-
else Nil
3538-
def checkAllGivens(vparamss: List[List[ValDef]], what: String) =
3539-
vparamss.foreach(_.foreach(vparam =>
3540-
if !vparam.mods.is(Given) then syntaxError(em"$what must be preceded by `using`", vparam.span)))
3541-
checkAllGivens(vparamss, "parameter of given instance")
3542-
val parents =
3543-
if in.token == SUBTYPE && !hasLabel then
3544-
if !mods.is(Inline) then
3545-
syntaxError("`<:` is only allowed for given with `inline` modifier")
3512+
val hasLabel = !name.isEmpty && in.token == COLON || isIdent(nme.as)
3513+
if hasLabel then in.nextToken()
3514+
val tparams = typeParamClauseOpt(ParamOwner.Def)
3515+
val paramsStart = in.offset
3516+
val vparamss =
3517+
if in.token == LPAREN && followingIsParamOrGivenType()
3518+
then paramClauses()
3519+
else Nil
3520+
def checkAllGivens(vparamss: List[List[ValDef]], what: String) =
3521+
vparamss.foreach(_.foreach(vparam =>
3522+
if !vparam.mods.is(Given) then syntaxError(em"$what must be preceded by `using`", vparam.span)))
3523+
checkAllGivens(vparamss, "parameter of given instance")
3524+
val parents =
3525+
if in.token == SUBTYPE && !hasLabel then
3526+
if !mods.is(Inline) then
3527+
syntaxError("`<:` is only allowed for given with `inline` modifier")
3528+
in.nextToken()
3529+
TypeBoundsTree(EmptyTree, toplevelTyp()) :: Nil
3530+
else
3531+
if !hasLabel && !(name.isEmpty && tparams.isEmpty && vparamss.isEmpty) then
3532+
if in.token == COLON then in.nextToken()
3533+
else accept(nme.as)
3534+
if in.token == USCORE then
35463535
in.nextToken()
3536+
accept(SUBTYPE)
35473537
TypeBoundsTree(EmptyTree, toplevelTyp()) :: Nil
35483538
else
3549-
if !hasLabel && !(name.isEmpty && tparams.isEmpty && vparamss.isEmpty) then
3550-
if in.token == COLON then in.nextToken()
3551-
else accept(nme.as)
3552-
if in.token == USCORE then
3553-
in.nextToken()
3554-
accept(SUBTYPE)
3555-
TypeBoundsTree(EmptyTree, toplevelTyp()) :: Nil
3556-
else
3557-
constrApps(commaOK = true, templateCanFollow = true)
3539+
constrApps(commaOK = true, templateCanFollow = true)
35583540

3559-
if in.token == EQUALS && parents.length == 1 && parents.head.isType then
3560-
in.nextToken()
3561-
mods1 |= Final
3562-
DefDef(name, tparams, vparamss, parents.head, subExpr())
3563-
else
3564-
parents match
3565-
case (_: TypeBoundsTree) :: _ => syntaxError("`=` expected")
3566-
case _ =>
3567-
possibleTemplateStart()
3568-
val tparams1 = tparams.map(tparam => tparam.withMods(tparam.mods | PrivateLocal))
3569-
val vparamss1 = vparamss.map(_.map(vparam =>
3570-
vparam.withMods(vparam.mods &~ Param | ParamAccessor | PrivateLocal)))
3571-
val templ = templateBodyOpt(makeConstructor(tparams1, vparamss1), parents, Nil)
3572-
if tparams.isEmpty && vparamss.isEmpty then ModuleDef(name, templ)
3573-
else TypeDef(name.toTypeName, templ)
3574-
}
3541+
if in.token == EQUALS && parents.length == 1 && parents.head.isType then
3542+
in.nextToken()
3543+
mods1 |= Final
3544+
DefDef(name, tparams, vparamss, parents.head, subExpr())
3545+
else
3546+
parents match
3547+
case (_: TypeBoundsTree) :: _ => syntaxError("`=` expected")
3548+
case _ =>
3549+
possibleTemplateStart()
3550+
val tparams1 = tparams.map(tparam => tparam.withMods(tparam.mods | PrivateLocal))
3551+
val vparamss1 = vparamss.map(_.map(vparam =>
3552+
vparam.withMods(vparam.mods &~ Param | ParamAccessor | PrivateLocal)))
3553+
val templ = templateBodyOpt(makeConstructor(tparams1, vparamss1), parents, Nil)
3554+
if tparams.isEmpty && vparamss.isEmpty then ModuleDef(name, templ)
3555+
else TypeDef(name.toTypeName, templ)
3556+
}
35753557
finalizeDef(gdef, mods1, start)
35763558
}
35773559

compiler/src/dotty/tools/dotc/parsing/Tokens.scala

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ object Tokens extends TokensCommon {
257257
AT, CASE)
258258

259259
final val canEndStatTokens: TokenSet = atomicExprTokens | BitSet(
260-
TYPE, GIVEN, RPAREN, RBRACE, RBRACKET, OUTDENT)
260+
TYPE, GIVEN, RPAREN, RBRACE, RBRACKET, OUTDENT) // TODO: remove GIVEN once old import syntax is dropped
261261

262262
/** Tokens that stop a lookahead scan search for a `<-`, `then`, or `do`.
263263
* Used for disambiguating between old and new syntax.
@@ -280,12 +280,6 @@ object Tokens extends TokensCommon {
280280
*/
281281
final val startParamTokens: BitSet = modifierTokens | BitSet(VAL, VAR, AT)
282282

283-
/** Faced with the choice of a type `(...)` or a parameter or given type list
284-
* in `(...)`, the following tokens after the opening `(` determine it's
285-
* a parameter or given type list.
286-
*/
287-
final val startParamOrGivenTypeTokens: BitSet = startParamTokens | BitSet(GIVEN, ERASED)
288-
289283
final val scala3keywords = BitSet(ENUM, ERASED, GIVEN)
290284

291285
final val softModifierNames = Set(nme.inline, nme.opaque, nme.open)

compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ class PlainPrinter(_ctx: Context) extends Printer {
188188
case tp: MethodType =>
189189
changePrec(GlobalPrec) {
190190
"("
191-
~ keywordText("given ").provided(tp.isContextualMethod)
191+
~ keywordText("using ").provided(tp.isContextualMethod)
192192
~ keywordText("erased ").provided(tp.isErasedMethod)
193193
~ keywordText("implicit ").provided(tp.isImplicitMethod && !tp.isContextualMethod)
194194
~ paramsText(tp)

compiler/src/dotty/tools/dotc/reporting/diagnostic/ErrorMessageID.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ enum ErrorMessageID extends java.lang.Enum[ErrorMessageID] {
150150
UnknownNamedEnclosingClassOrObjectID,
151151
IllegalCyclicTypeReferenceID,
152152
MissingTypeParameterInTypeAppID,
153-
ImplicitTypesCanOnlyBeFunctionTypesID,
153+
UNUSED_ImplicitTypesCanOnlyBeFunctionTypesID,
154154
ErasedTypesCanOnlyBeFunctionTypesID,
155155
CaseClassMissingNonImplicitParamListID,
156156
EnumerationsShouldNotBeEmptyID,

compiler/src/dotty/tools/dotc/reporting/diagnostic/messages.scala

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2376,17 +2376,10 @@ object messages {
23762376
""".stripMargin
23772377
}
23782378

2379-
case class IllegalCyclicTypeReference(sym: Symbol, where: String, lastChecked: Type)(implicit val ctx: Context)
2380-
extends Message(IllegalCyclicTypeReferenceID) {
2381-
val kind: String = "Cyclic"
2382-
val msg: String = i"illegal cyclic type reference: ${where} ${hl(lastChecked.show)} of $sym refers back to the type itself"
2383-
val explanation: String = ""
2384-
}
2385-
2386-
case class ImplicitTypesCanOnlyBeFunctionTypes()(implicit val ctx: Context) // TODO remove when (given ...) => is removed
2387-
extends Message(ImplicitTypesCanOnlyBeFunctionTypesID) {
2388-
val kind: String = "Syntax"
2389-
val msg: String = "Types with given keyword can only be function types `(given ...) => ...`"
2379+
case class IllegalCyclicTypeReference(sym: Symbol, where: String, lastChecked: Type)(implicit val ctx: Context)
2380+
extends Message(IllegalCyclicTypeReferenceID) {
2381+
val kind: String = "Cyclic"
2382+
val msg: String = i"illegal cyclic type reference: ${where} ${hl(lastChecked.show)} of $sym refers back to the type itself"
23902383
val explanation: String = ""
23912384
}
23922385

compiler/src/dotty/tools/dotc/semanticdb/ExtractSemanticDB.scala

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ import java.nio.file.Paths
1717

1818
import PartialFunction.condOpt
1919

20-
import ast.untpd.given
21-
import NameOps.given
20+
import ast.untpd.{given _}
21+
import NameOps.{given _}
2222

2323
import scala.annotation.{ threadUnsafe => tu, tailrec }
2424

@@ -28,8 +28,8 @@ import scala.annotation.{ threadUnsafe => tu, tailrec }
2828
* TODO: Also extract type information
2929
*/
3030
class ExtractSemanticDB extends Phase with
31-
import Scala3.{_, given}
32-
import Symbols.given
31+
import Scala3.{_, given _}
32+
import Symbols.{given _}
3333

3434
override val phaseName: String = ExtractSemanticDB.name
3535

@@ -509,10 +509,9 @@ class ExtractSemanticDB extends Phase with
509509
else limit
510510
Span(start max limit, end)
511511

512-
private given extension (span: Span) with
512+
private extension on (span: Span):
513513
def hasLength: Boolean = span.start != span.end
514514
def zeroLength: Boolean = span.start == span.end
515-
end given
516515

517516
/**Consume head while not an import statement.
518517
* Returns the rest of the list after the first import, or else the empty list

compiler/src/dotty/tools/dotc/typer/Applications.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -863,7 +863,7 @@ trait Applications extends Compatibility {
863863
new ApplyToTyped(tree, fun1, funRef, proto.typedArgs(), pt)
864864
else
865865
new ApplyToUntyped(tree, fun1, funRef, proto, pt)(
866-
given fun1.nullableInArgContext(using argCtx(tree)))
866+
using fun1.nullableInArgContext(using argCtx(tree)))
867867
convertNewGenericArray(
868868
postProcessByNameArgs(funRef, app.result).computeNullable())
869869
case _ =>

compiler/src/dotty/tools/dotc/typer/ImportSuggestions.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ trait ImportSuggestions with
184184
try
185185
timer.schedule(task, testOneImplicitTimeOut)
186186
typedImplicit(candidate, expectedType, argument, span)(
187-
given ctx.fresh.setExploreTyperState()).isSuccess
187+
using ctx.fresh.setExploreTyperState()).isSuccess
188188
finally
189189
if task.cancel() then // timer task has not run yet
190190
assert(!ctx.run.isCancelled)

compiler/src/dotty/tools/dotc/typer/Typer.scala

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1232,8 +1232,8 @@ class Typer extends Namer
12321232

12331233
val pat1 = typedPattern(tree.pat, wideSelType)(gadtCtx)
12341234
caseRest(pat1)(
1235-
given Nullables.caseContext(sel, pat1)(
1236-
given gadtCtx.fresh.setNewScope))
1235+
using Nullables.caseContext(sel, pat1)(
1236+
using gadtCtx.fresh.setNewScope))
12371237
}
12381238

12391239
def typedLabeled(tree: untpd.Labeled)(implicit ctx: Context): Labeled = {
@@ -2345,7 +2345,7 @@ class Typer extends Namer
23452345
// in preceding statements (unless the DefTree is completed ahead of time,
23462346
// then it is impossible).
23472347
sym.info = Completer(completer.original)(
2348-
given completer.creationContext.withNotNullInfos(ctx.notNullInfos))
2348+
using completer.creationContext.withNotNullInfos(ctx.notNullInfos))
23492349
true
23502350
case _ =>
23512351
// If it has been completed, then it must be because there is a forward reference

compiler/test-resources/repl/defs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,5 @@ scala> def id(x: 4): 4 = x
1010
def id(x: 4): 4
1111
scala> id(4)
1212
val res0: Int = 4
13-
scala> def f(given Int) = 1
14-
def f(given x$1: Int): Int
13+
scala> def f(using Int) = 1
14+
def f(using x$1: Int): Int
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
scala> def f(given erased a: Int): Int = ???
2-
def f(given erased a: Int): Int
1+
scala> def f(using erased a: Int): Int = ???
2+
def f(using erased a: Int): Int

compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTests.scala

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1685,23 +1685,10 @@ class ErrorMessagesTests extends ErrorMessagesTest {
16851685
assertEquals("List[X]", lastChecked.show)
16861686
}
16871687

1688-
@Test def implicitTypesCanOnlyBeFunctionTypesSuccess() =
1689-
checkMessagesAfter(RefChecks.name) ("def foo(f: (given Int) => Int): Int = 1")
1690-
.expectNoErrors
1691-
16921688
@Test def erasedTypesCanOnlyBeFunctionTypesSuccess() =
16931689
checkMessagesAfter(FrontEnd.name) ("def foo(f: (erased Int) => Int): Int = 1")
16941690
.expectNoErrors
16951691

1696-
@Test def implicitTypesCanOnlyBeFunctionTypesFailed() =
1697-
checkMessagesAfter(FrontEnd.name) ("def foo(f: (given Int)): Int = 1")
1698-
.expect { (ictx, messages) =>
1699-
implicit val ctx: Context = ictx
1700-
assertMessageCount(1, messages)
1701-
val ImplicitTypesCanOnlyBeFunctionTypes() :: Nil = messages
1702-
assertEquals("Types with given keyword can only be function types `(given ...) => ...`", messages.head.msg)
1703-
}
1704-
17051692
@Test def erasedTypesCanOnlyBeFunctionTypesFailed() =
17061693
checkMessagesAfter(FrontEnd.name) ("def foo(f: (erased Int)): Int = 1")
17071694
.expect { (ictx, messages) =>
@@ -1726,11 +1713,11 @@ class ErrorMessagesTests extends ErrorMessagesTest {
17261713
}
17271714

17281715
@Test def caseClassMissingNonImplicitParamListSuccessful =
1729-
checkMessagesAfter(FrontEnd.name) ("case class Test()(given foo: String)")
1716+
checkMessagesAfter(FrontEnd.name) ("case class Test()(using foo: String)")
17301717
.expectNoErrors
17311718

17321719
@Test def caseClassMissingNonImplicitParamListFailed =
1733-
checkMessagesAfter(FrontEnd.name) ("case class Test(given foo: String)")
1720+
checkMessagesAfter(FrontEnd.name) ("case class Test(using foo: String)")
17341721
.expect {
17351722
(ictx, messages) =>
17361723
implicit val ctx: Context = ictx

0 commit comments

Comments
 (0)