Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update scalafmt-core to 3.7.17 #110

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@ f6bdd1574b34dd2f7eb6737863bff6dbb876bbb2

# Scala Steward: Reformat with scalafmt 3.7.2
306a9a501c20a74348d8640da8f2b1cb89172706

# Scala Steward: Reformat with scalafmt 3.7.17
1d3a9ba3d19b8a74d6523a4d5f0c2f733cea5ed3
2 changes: 1 addition & 1 deletion .scalafmt.conf
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
version = "3.7.3"
version = "3.7.17"

project.git = true

Expand Down
2 changes: 1 addition & 1 deletion mainargs/src-2/Macros.scala
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ class Macros(val c: Context) {

val defaults = for ((arg0, i) <- flattenedArgLists.zipWithIndex) yield {
val arg = TermName(c.freshName())
hasDefault(i) match{
hasDefault(i) match {
case None => q"_root_.scala.None"
case Some(defaultName) =>
q"_root_.scala.Some[$curCls => ${arg0.info}](($arg: $curCls) => $arg.${newTermName(defaultName)}: ${arg0.info})"
Expand Down
116 changes: 69 additions & 47 deletions mainargs/src-3/Macros.scala
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ object Macros {
val annotatedMethodsWithMainAnnotations = allMethods.flatMap { methodSymbol =>
methodSymbol.getAnnotation(mainAnnotation).map(methodSymbol -> _)
}.sortBy(_._1.pos.map(_.start))
val mainDatas = Expr.ofList(annotatedMethodsWithMainAnnotations.map { (annotatedMethod, mainAnnotationInstance) =>
createMainData[Any, B](annotatedMethod, mainAnnotationInstance)
val mainDatas = Expr.ofList(annotatedMethodsWithMainAnnotations.map {
(annotatedMethod, mainAnnotationInstance) =>
createMainData[Any, B](annotatedMethod, mainAnnotationInstance)
})

'{
Expand All @@ -26,13 +27,13 @@ object Macros {
import quotes.reflect._
val typeReprOfB = TypeRepr.of[B]
val companionModule = typeReprOfB match {
case TypeRef(a,b) => TermRef(a,b)
case TypeRef(a, b) => TermRef(a, b)
}
val typeSymbolOfB = typeReprOfB.typeSymbol
val companionModuleType = typeSymbolOfB.companionModule.tree.asInstanceOf[ValDef].tpt.tpe.asType
val companionModuleExpr = Ident(companionModule).asExpr
val mainAnnotationInstance = typeSymbolOfB.getAnnotation(mainAnnotation).getOrElse {
'{new mainargs.main()}.asTerm // construct a default if not found.
'{ new mainargs.main() }.asTerm // construct a default if not found.
}
val ctor = typeSymbolOfB.primaryConstructor
val ctorParams = ctor.paramSymss.flatten
Expand All @@ -58,13 +59,13 @@ object Macros {
// parameters, so use those for getting the annotations instead
TypeRepr.of[B].typeSymbol.primaryConstructor.paramSymss
)
val erasedMainData = '{$mainData.asInstanceOf[MainData[B, Any]]}
val erasedMainData = '{ $mainData.asInstanceOf[MainData[B, Any]] }
'{ new ParserForClass[B]($erasedMainData, () => ${ Ident(companionModule).asExpr }) }
}

def createMainData[T: Type, B: Type](using Quotes)
(method: quotes.reflect.Symbol,
mainAnnotation: quotes.reflect.Term): Expr[MainData[T, B]] = {
def createMainData[T: Type, B: Type](using
Quotes
)(method: quotes.reflect.Symbol, mainAnnotation: quotes.reflect.Term): Expr[MainData[T, B]] = {
createMainData[T, B](method, mainAnnotation, method.paramSymss)
}

Expand All @@ -73,9 +74,12 @@ object Macros {
import quotes.reflect.*
tpe match {
case AnnotatedType(AppliedType(_, Seq(arg)), x) // Scala 3 repeated parameter
if x.tpe =:= defn.RepeatedAnnot.typeRef => Some(arg)
case AppliedType(TypeRef(pre, "<repeated>"), Seq(arg)) // Scala 2 repeated parameter, can be read from Scala 3
if pre =:= defn.ScalaPackage.termRef => Some(arg)
if x.tpe =:= defn.RepeatedAnnot.typeRef => Some(arg)
case AppliedType(
TypeRef(pre, "<repeated>"),
Seq(arg)
) // Scala 2 repeated parameter, can be read from Scala 3
if pre =:= defn.ScalaPackage.termRef => Some(arg)
case _ => None
}
}
Expand All @@ -87,14 +91,18 @@ object Macros {
}
}

def createMainData[T: Type, B: Type](using Quotes)
(method: quotes.reflect.Symbol,
mainAnnotation: quotes.reflect.Term,
annotatedParamsLists: List[List[quotes.reflect.Symbol]]): Expr[MainData[T, B]] = {
def createMainData[T: Type, B: Type](using Quotes)(
method: quotes.reflect.Symbol,
mainAnnotation: quotes.reflect.Term,
annotatedParamsLists: List[List[quotes.reflect.Symbol]]
): Expr[MainData[T, B]] = {

import quotes.reflect.*
val params = method.paramSymss.headOption.getOrElse(report.throwError("Multiple parameter lists not supported"))
val defaultParams = if (params.exists(_.flags.is(Flags.HasDefault))) getDefaultParams(method) else Map.empty
val params = method.paramSymss.headOption.getOrElse(
report.throwError("Multiple parameter lists not supported")
)
val defaultParams =
if (params.exists(_.flags.is(Flags.HasDefault))) getDefaultParams(method) else Map.empty
val argSigsExprs = params.zip(annotatedParamsLists.flatten).map { paramAndAnnotParam =>
val param = paramAndAnnotParam._1
val annotParam = paramAndAnnotParam._2
Expand All @@ -104,7 +112,9 @@ object Macros {
case VarargTypeRepr(AsType('[t])) => TypeRepr.of[Leftover[t]]
case _ => paramTpe
}
val arg = annotParam.getAnnotation(argAnnotation).map(_.asExprOf[mainargs.arg]).getOrElse('{ new mainargs.arg() })
val arg = annotParam.getAnnotation(argAnnotation).map(_.asExprOf[mainargs.arg]).getOrElse('{
new mainargs.arg()
})
readerTpe.asType match {
case '[t] =>
def applyAndCast(f: Expr[Any] => Expr[Any], arg: Expr[B]): Expr[t] = {
Expand All @@ -119,10 +129,10 @@ object Macros {
case err: Exception =>
report.errorAndAbort(
s"""Failed to convert default value for parameter ${param.name},
|expected type: ${paramTpe.show},
|but default value ${expr.show} is of type: ${expr.asTerm.tpe.widen.show}
|while converting type caught an exception with message: ${err.getMessage}
|There might be a bug in mainargs.""".stripMargin,
|expected type: ${paramTpe.show},
|but default value ${expr.show} is of type: ${expr.asTerm.tpe.widen.show}
|while converting type caught an exception with message: ${err.getMessage}
|There might be a bug in mainargs.""".stripMargin,
param.pos.getOrElse(Position.ofMacroExpansion)
)
recoveredType
Expand All @@ -139,7 +149,10 @@ object Macros {
method.pos.getOrElse(Position.ofMacroExpansion)
)
}
'{ (ArgSig.create[t, B](${ Expr(param.name) }, ${ arg }, ${ defaultParam })(using ${ tokensReader })) }
'{
(ArgSig.create[t, B](${ Expr(param.name) }, ${ arg }, ${ defaultParam })(using
${ tokensReader }))
}
}
}
val argSigs = Expr.ofList(argSigsExprs)
Expand All @@ -151,28 +164,35 @@ object Macros {

'{ (b: B, params: Seq[Any]) => ${ callOf('b, 'params) } }
}
'{ MainData.create[T, B](${ Expr(method.name) }, ${ mainAnnotation.asExprOf[mainargs.main] }, ${ argSigs }, ${ invokeRaw }) }
'{
MainData.create[T, B](
${ Expr(method.name) },
${ mainAnnotation.asExprOf[mainargs.main] },
${ argSigs },
${ invokeRaw }
)
}
}

/** Call a method given by its symbol.
*
* E.g.
*
* assuming:
*
* def foo(x: Int, y: String)(z: Int)
*
* val argss: List[List[Any]] = ???
*
* then:
*
* call(<symbol of foo>, '{argss})
*
* will expand to:
*
* foo(argss(0)(0), argss(0)(1))(argss(1)(0))
*
*/
/**
* Call a method given by its symbol.
*
* E.g.
*
* assuming:
*
* def foo(x: Int, y: String)(z: Int)
*
* val argss: List[List[Any]] = ???
*
* then:
*
* call(<symbol of foo>, '{argss})
*
* will expand to:
*
* foo(argss(0)(0), argss(0)(1))(argss(1)(0))
*/
private def call(using Quotes)(
methodOwner: Expr[Any],
method: quotes.reflect.Symbol,
Expand All @@ -197,23 +217,25 @@ object Macros {
for (i <- params.indices.toList) yield {
val param = params(i)
val tpe = methodType.memberType(param)
val untypedRef = '{ $ref(${Expr(i)}) }
val untypedRef = '{ $ref(${ Expr(i) }) }
tpe match {
case VarargTypeRepr(AsType('[t])) =>
Typed(
'{ $untypedRef.asInstanceOf[Leftover[t]].value }.asTerm,
Inferred(AppliedType(defn.RepeatedParamClass.typeRef, List(TypeRepr.of[t])))
)
case _ => tpe.asType match
case '[t] => '{ $untypedRef.asInstanceOf[t] }.asTerm
case '[t] => '{ $untypedRef.asInstanceOf[t] }.asTerm
}
}

methodOwner.asTerm.select(method).appliedToArgs(accesses(args)).asExpr
}

/** Lookup default values for a method's parameters. */
private def getDefaultParams(using Quotes)(method: quotes.reflect.Symbol): Map[quotes.reflect.Symbol, Expr[Any] => Expr[Any]] = {
private def getDefaultParams(using
Quotes
)(method: quotes.reflect.Symbol): Map[quotes.reflect.Symbol, Expr[Any] => Expr[Any]] = {
// Copy pasted from Cask.
// https://github.com/com-lihaoyi/cask/blob/65b9c8e4fd528feb71575f6e5ef7b5e2e16abbd9/cask/src-3/cask/router/Macros.scala#L38
import quotes.reflect._
Expand All @@ -226,7 +248,7 @@ object Macros {

val idents = method.owner.tree.asInstanceOf[ClassDef].body

idents.foreach{
idents.foreach {
case deff @ DefDef(Name(idx), _, _, _) =>
val expr = (owner: Expr[Any]) => Select(owner.asTerm, deff.symbol).asExpr
defaults += (params(idx.toInt - 1) -> expr)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ package mainargs

import scala.language.experimental.macros

private [mainargs] trait ParserForClassCompanionVersionSpecific {
private[mainargs] trait ParserForClassCompanionVersionSpecific {
inline def apply[T]: ParserForClass[T] = ${ Macros.parserForClass[T] }
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package mainargs

private [mainargs] trait ParserForMethodsCompanionVersionSpecific {
private[mainargs] trait ParserForMethodsCompanionVersionSpecific {
inline def apply[B](base: B): ParserForMethods[B] = ${ Macros.parserForMethods[B]('base) }
}
21 changes: 13 additions & 8 deletions mainargs/src/Invoker.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ object Invoker {
cep: TokensReader.Class[T],
args: Seq[String],
allowPositional: Boolean,
allowRepeats: Boolean,
allowRepeats: Boolean
): Result[T] = construct(cep, args, allowPositional, allowRepeats, Util.nullNameMapper)

def construct[T](
Expand Down Expand Up @@ -40,9 +40,9 @@ object Invoker {
Right(ParamResult.Success(Flag(kvs.contains(a)).asInstanceOf[T]))
case r: TokensReader.Simple[T] => Right(makeReadCall(kvs, base, a, r))
case r: TokensReader.Constant[T] => Right(r.read() match {
case Left(s) => ParamResult.Failure(Seq(Result.ParamError.Failed(a, Nil, s)))
case Right(v) => ParamResult.Success(v)
})
case Left(s) => ParamResult.Failure(Seq(Result.ParamError.Failed(a, Nil, s)))
case Right(v) => ParamResult.Success(v)
})
case r: TokensReader.Leftover[T, _] => Right(makeReadVarargsCall(a, extras, r))
case r: TokensReader.Class[T] =>
Left(
Expand Down Expand Up @@ -91,7 +91,8 @@ object Invoker {
mains: MethodMains[B],
args: Seq[String],
allowPositional: Boolean,
allowRepeats: Boolean): Either[Result.Failure.Early, (MainData[Any, B], Result[Any])] = {
allowRepeats: Boolean
): Either[Result.Failure.Early, (MainData[Any, B], Result[Any])] = {
runMains(mains, args, allowPositional, allowRepeats, Util.nullNameMapper)
}
def runMains[B](
Expand Down Expand Up @@ -126,16 +127,20 @@ object Invoker {
case Seq(main) => groupArgs(main, args)
case multiple =>
args.toList match {
case List() => Left(Result.Failure.Early.SubcommandNotSpecified(multiple.map(_.name(nameMapper))))
case List() =>
Left(Result.Failure.Early.SubcommandNotSpecified(multiple.map(_.name(nameMapper))))
case head :: tail =>
if (head.startsWith("-")) {
Left(Result.Failure.Early.SubcommandSelectionDashes(head))
} else {
multiple.find{ m =>
multiple.find { m =>
val name = m.name(nameMapper)
name == head || (m.mainName.isEmpty && m.defaultName == head)
} match {
case None => Left(Result.Failure.Early.UnableToFindSubcommand(multiple.map(_.name(nameMapper)), head))
case None => Left(Result.Failure.Early.UnableToFindSubcommand(
multiple.map(_.name(nameMapper)),
head
))
case Some(main) => groupArgs(main, tail)
}
}
Expand Down
Loading