Skip to content

Commit

Permalink
formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
octonato committed May 26, 2020
1 parent a5567fb commit fadf9a2
Show file tree
Hide file tree
Showing 10 changed files with 257 additions and 215 deletions.
9 changes: 5 additions & 4 deletions api/shared/src/main/scala/play/twirl/api/Content.scala
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,11 @@ abstract class BufferedContent[A <: BufferedContent[A]](

def body = builtBody

override def equals(obj: Any): Boolean = obj match {
case other: BufferedContent[_] if this.getClass == other.getClass => body == other.body
case _ => false
}
override def equals(obj: Any): Boolean =
obj match {
case other: BufferedContent[_] if this.getClass == other.getClass => body == other.body
case _ => false
}

override def hashCode(): Int = this.getClass.hashCode() + body.hashCode()
}
17 changes: 9 additions & 8 deletions api/shared/src/main/scala/play/twirl/api/TemplateMagic.scala
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,15 @@ object TemplateMagic {
// --- DEFAULT

case class Default(default: Any) {
def ?:(x: Any) = x match {
case "" => default
case Nil => default
case false => default
case 0 => default
case None => default
case _ => x
}
def ?:(x: Any) =
x match {
case "" => default
case Nil => default
case false => default
case 0 => default
case None => default
case _ => x
}
}

implicit def anyToDefault(x: Any) = Default(x)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,14 @@ object TwirlFeatureImports {
* the default value.
*/
implicit class TwirlDefaultValue(default: Any) {
def ?:(x: Any): Any = x match {
case "" => default
case Nil => default
case false => default
case 0 => default
case None => default
case _ => x
}
def ?:(x: Any): Any =
x match {
case "" => default
case Nil => default
case false => default
case 0 => default
case None => default
case _ => x
}
}
}
21 changes: 11 additions & 10 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,8 @@ lazy val parser = project
mimaSettings,
name := "twirl-parser",
libraryDependencies += "org.scala-lang.modules" %% "scala-parser-combinators" % ScalaParserCombinatorsVersion % "optional",
libraryDependencies += "com.novocode" % "junit-interface" % "0.11" % "test",
libraryDependencies += "org.scalatest" %%% "scalatest" % ScalaTestVersion % "test",
libraryDependencies += "com.novocode" % "junit-interface" % "0.11" % "test",
libraryDependencies += "org.scalatest" %%% "scalatest" % ScalaTestVersion % "test",
)

lazy val compiler = project
Expand All @@ -149,7 +149,7 @@ lazy val compiler = project
commonSettings,
mimaSettings,
name := "twirl-compiler",
libraryDependencies += "org.scala-lang" % "scala-compiler" % scalaVersion.value,
libraryDependencies += "org.scala-lang" % "scala-compiler" % scalaVersion.value,
libraryDependencies += "org.scala-lang.modules" %% "scala-parser-combinators" % ScalaParserCombinatorsVersion % "optional",
fork in run := true,
)
Expand Down Expand Up @@ -190,12 +190,13 @@ playBuildExtraPublish := {

// Version file

def generateVersionFile = Def.task {
val version = (Keys.version in apiJvm).value
val file = (resourceManaged in Compile).value / "twirl.version.properties"
val content = s"twirl.api.version=$version"
IO.write(file, content)
Seq(file)
}
def generateVersionFile =
Def.task {
val version = (Keys.version in apiJvm).value
val file = (resourceManaged in Compile).value / "twirl.version.properties"
val content = s"twirl.api.version=$version"
IO.write(file, content)
Seq(file)
}

addCommandAlias("validateCode", ";headerCheckAll;scalafmtCheckAll;scalafmtSbtCheck")
188 changes: 99 additions & 89 deletions compiler/src/main/scala/play/twirl/compiler/TwirlCompiler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ object Hash {
digest.reset()
digest.update(bytes)
imports.foreach(i => digest.update(i.getBytes("utf-8")))
digest.digest().map(0xFF & _).map { "%02x".format(_) }.foldLeft("") { _ + _ }
digest.digest().map(0xff & _).map { "%02x".format(_) }.foldLeft("") { _ + _ }
}
}

Expand Down Expand Up @@ -373,7 +373,7 @@ object TwirlCompiler {
case ScalaExp(parts) =>
previous :+ parts.map {
case s @ Simple(code) => Source(code, s.pos)
case b @ Block(whitespace, args, content) if (content.forall(_.isInstanceOf[ScalaExp])) =>
case b @ Block(whitespace, args, content) if content.forall(_.isInstanceOf[ScalaExp]) =>
Nil :+ Source(whitespace + "{" + args.getOrElse(""), b.pos) :+ visit(content, Nil) :+ "}"
case b @ Block(whitespace, args, content) =>
Nil :+ Source(whitespace + "{" + args.getOrElse(""), b.pos) :+ displayVisitedChildren(
Expand All @@ -390,13 +390,19 @@ object TwirlCompiler {
val defs = (template.sub ++ template.defs).map {
case t: Template if t.name.toString == "" => templateCode(t, resultType)
case t: Template => {
Nil :+ (if (t.name.str.startsWith("implicit")) "implicit def " else "def ") :+ Source(t.name.str, t.name.pos) :+ Source(
Nil :+ (if (t.name.str.startsWith("implicit")) "implicit def " else "def ") :+ Source(
t.name.str,
t.name.pos
) :+ Source(
t.params.str,
t.params.pos
) :+ ":" :+ resultType :+ " = {_display_(" :+ templateCode(t, resultType) :+ ")};"
}
case Def(name, params, block) => {
Nil :+ (if (name.str.startsWith("implicit")) "implicit def " else "def ") :+ Source(name.str, name.pos) :+ Source(
Nil :+ (if (name.str.startsWith("implicit")) "implicit def " else "def ") :+ Source(
name.str,
name.pos
) :+ Source(
params.str,
params.pos
) :+ " = {" :+ block.code :+ "};"
Expand Down Expand Up @@ -510,102 +516,103 @@ package """ :+ packageName :+ """
/** The maximum time in milliseconds to wait for a compiler response to finish. */
private val Timeout = 10000

def getFunctionMapping(signature: String, returnType: String): (String, String, String) = synchronized {
def filterType(t: String) =
t.replace("_root_.scala.<repeated>", "Array")
.replace("<synthetic>", "")
def getFunctionMapping(signature: String, returnType: String): (String, String, String) =
synchronized {
def filterType(t: String) =
t.replace("_root_.scala.<repeated>", "Array")
.replace("<synthetic>", "")

def findSignature(tree: Tree): Option[DefDef] = {
tree match {
case t: DefDef if t.name.toString == "signature" => Some(t)
case t: Tree => t.children.flatMap(findSignature).headOption
def findSignature(tree: Tree): Option[DefDef] = {
tree match {
case t: DefDef if t.name.toString == "signature" => Some(t)
case t: Tree => t.children.flatMap(findSignature).headOption
}
}
}

val params =
findSignature(PresentationCompiler.treeFrom("object FT { def signature" + signature + " }")).get.vparamss

val resp = PresentationCompiler.global
.askForResponse { () =>
val functionType = "(" + params
.map(group =>
"(" + group
.map {
case ByNameParam(_, paramType) => " => " + paramType
case a => filterType(a.tpt.toString)
}
.mkString(",") + ")"
)
.mkString(" => ") + " => " + returnType + ")"
val params =
findSignature(PresentationCompiler.treeFrom("object FT { def signature" + signature + " }")).get.vparamss

val renderCall = "def render%s: %s = apply%s".format(
"(" + params.flatten
.map {
case ByNameParam(name, paramType) => name + ":" + paramType
case a => a.name.toString + ":" + filterType(a.tpt.toString)
}
.mkString(",") + ")",
returnType,
params
val resp = PresentationCompiler.global
.askForResponse { () =>
val functionType = "(" + params
.map(group =>
"(" + group
.map { p =>
p.name.toString + Option(p.tpt.toString)
.filter(_.startsWith("_root_.scala.<repeated>"))
.map(_ => ".toIndexedSeq:_*")
.getOrElse("")
.map {
case ByNameParam(_, paramType) => " => " + paramType
case a => filterType(a.tpt.toString)
}
.mkString(",") + ")"
)
.mkString
)
.mkString(" => ") + " => " + returnType + ")"

val templateType = "_root_.play.twirl.api.Template%s[%s%s]".format(
params.flatten.size,
params.flatten
.map {
case ByNameParam(_, paramType) => paramType
case a => filterType(a.tpt.toString)
}
.mkString(","),
(if (params.flatten.isEmpty) "" else ",") + returnType
)
val renderCall = "def render%s: %s = apply%s".format(
"(" + params.flatten
.map {
case ByNameParam(name, paramType) => name + ":" + paramType
case a => a.name.toString + ":" + filterType(a.tpt.toString)
}
.mkString(",") + ")",
returnType,
params
.map(group =>
"(" + group
.map { p =>
p.name.toString + Option(p.tpt.toString)
.filter(_.startsWith("_root_.scala.<repeated>"))
.map(_ => ".toIndexedSeq:_*")
.getOrElse("")
}
.mkString(",") + ")"
)
.mkString
)

val f = "def f:%s = %s => apply%s".format(
functionType,
params.map(group => "(" + group.map(_.name.toString).mkString(",") + ")").mkString(" => "),
params
.map(group =>
"(" + group
.map { p =>
p.name.toString + Option(p.tpt.toString)
.filter(_.startsWith("_root_.scala.<repeated>"))
.map(_ => ".toIndexedSeq:_*")
.getOrElse("")
}
.mkString(",") + ")"
)
.mkString
)
val templateType = "_root_.play.twirl.api.Template%s[%s%s]".format(
params.flatten.size,
params.flatten
.map {
case ByNameParam(_, paramType) => paramType
case a => filterType(a.tpt.toString)
}
.mkString(","),
(if (params.flatten.isEmpty) "" else ",") + returnType
)

(renderCall, f, templateType)
}
.get(Timeout)

resp match {
case None =>
PresentationCompiler.global.reportThrowable(new Throwable("Timeout in getFunctionMapping"))
("", "", "")
case Some(res) =>
res match {
case Right(t) =>
PresentationCompiler.global.reportThrowable(new Throwable("Throwable in getFunctionMapping", t))
("", "", "")
case Left(res) =>
res
val f = "def f:%s = %s => apply%s".format(
functionType,
params.map(group => "(" + group.map(_.name.toString).mkString(",") + ")").mkString(" => "),
params
.map(group =>
"(" + group
.map { p =>
p.name.toString + Option(p.tpt.toString)
.filter(_.startsWith("_root_.scala.<repeated>"))
.map(_ => ".toIndexedSeq:_*")
.getOrElse("")
}
.mkString(",") + ")"
)
.mkString
)

(renderCall, f, templateType)
}
.get(Timeout)

resp match {
case None =>
PresentationCompiler.global.reportThrowable(new Throwable("Timeout in getFunctionMapping"))
("", "", "")
case Some(res) =>
res match {
case Right(t) =>
PresentationCompiler.global.reportThrowable(new Throwable("Throwable in getFunctionMapping", t))
("", "", "")
case Left(res) =>
res
}
}
}
}

class CompilerInstance {
def additionalClassPathEntry: Option[String] = None
Expand Down Expand Up @@ -639,9 +646,12 @@ package """ :+ packageName :+ """
((origBootclasspath :: pathList) ::: additionalClassPathEntry.toList).mkString(File.pathSeparator)
}

val compiler = new Global(settings, new ConsoleReporter(settings) {
override def display(pos: Position, msg: String, severity: Severity): Unit = ()
})
val compiler = new Global(
settings,
new ConsoleReporter(settings) {
override def display(pos: Position, msg: String, severity: Severity): Unit = ()
}
)

// Everything must be done on the compiler thread, because the presentation compiler is a fussy piece of work.
compiler.ask(() => new compiler.Run)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -340,14 +340,17 @@ object Helper {
settings.outdir.value = generatedClasses.getAbsolutePath
}

val compiler = new Global(settings, new ConsoleReporter(settings) {
override def display(pos: Position, msg: String, severity: Severity): Unit = {
pos match {
case scala.reflect.internal.util.NoPosition => // do nothing
case _ => compileErrors.append(CompilationError(msg, pos.line, pos.point))
val compiler = new Global(
settings,
new ConsoleReporter(settings) {
override def display(pos: Position, msg: String, severity: Severity): Unit = {
pos match {
case scala.reflect.internal.util.NoPosition => // do nothing
case _ => compileErrors.append(CompilationError(msg, pos.line, pos.point))
}
}
}
})
)

compiler
}
Expand Down
9 changes: 6 additions & 3 deletions parser/src/main/scala/play/twirl/parser/TwirlParser.scala
Original file line number Diff line number Diff line change
Expand Up @@ -316,8 +316,8 @@ class TwirlParser(val shouldParseInclusiveDot: Boolean) {
}

/** Match zero or more `parser` */
def several[T, BufferType <: mutable.Buffer[T]](parser: () => T, provided: BufferType = null)(
implicit manifest: Manifest[BufferType]
def several[T, BufferType <: mutable.Buffer[T]](parser: () => T, provided: BufferType = null)(implicit
manifest: Manifest[BufferType]
): BufferType = {
val ab = if (provided != null) provided else manifest.runtimeClass.newInstance().asInstanceOf[BufferType]
var parsed = parser()
Expand Down Expand Up @@ -582,7 +582,10 @@ class TwirlParser(val shouldParseInclusiveDot: Boolean) {
if (parens != null) {
val blk = block(blockArgsAllowed = true)
if (blk != null) {
result = Display(ScalaExp(ListBuffer(position(Simple("for" + parens + " yield "), p + 1), blk))) // don't include pos of @
result =
Display(
ScalaExp(ListBuffer(position(Simple("for" + parens + " yield "), p + 1), blk))
) // don't include pos of @
}
}
}
Expand Down
Loading

0 comments on commit fadf9a2

Please sign in to comment.