Skip to content

Xml Interpolation #151

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

Closed
wants to merge 2 commits into from
Closed
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
21 changes: 19 additions & 2 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ scalaVersionsByJvm in ThisBuild := {
}

lazy val root = project.in(file("."))
.aggregate(xmlJS, xmlJVM)
.aggregate(xmlJS, xmlJVM, xmlquote)
.settings(publish := {}, publishLocal := {})

lazy val xml = crossProject.in(file("."))
lazy val xml = crossProject.in(file("xml"))
.settings(
name := "scala-xml",
version := "1.0.7-SNAPSHOT",
Expand Down Expand Up @@ -54,3 +54,20 @@ lazy val xml = crossProject.in(file("."))

lazy val xmlJVM = xml.jvm
lazy val xmlJS = xml.js

lazy val xmlquote = project.in(file("quote"))
.dependsOn(xmlJVM)
.settings(
name := "scala-xml-quote",
scalacOptions ++= Seq(
"-deprecation",
"-feature",
"-unchecked",
"-Xlint"
),
libraryDependencies ++= Seq(
"org.scala-lang" % "scala-reflect" % scalaVersion.value,
"com.lihaoyi" %% "fastparse" % "0.4.3",
"org.scalatest" %% "scalatest" % "3.0.1" % "test"
)
)
12 changes: 12 additions & 0 deletions quote/src/main/scala/scala/xml/quote/internal/Hole.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package scala.xml.quote.internal

import fastparse.all._

private[internal] object Hole {
// withing private use area
private val HoleStart = 0xE000.toChar.toString
private val HoleChar = 0xE001.toChar.toString

def encode(i: Int) = HoleStart + HoleChar * i
val Parser: P[Int] = P( HoleStart ~ HoleChar.rep ).!.map(_.length - 1)
}
192 changes: 192 additions & 0 deletions quote/src/main/scala/scala/xml/quote/internal/Liftables.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
package scala.xml.quote.internal

import scala.xml.quote.internal.ast._

/** Lift `ast.Node` to `c.universe.Tree`.
*
* At this point, `Node` are expected to be valid.
*
* Note: `$_scope` is used as a scope name because `$scope` is already taken.
*/
private[internal] trait Liftables { self: QuoteImpl =>
import Liftables.{Scope, TopScope}
import self.c.universe._

def lift(nodes: Seq[Node]): Tree = {
val tree =
if (nodes.size == 1) liftNode(TopScope)(nodes.head)
else liftNodes(TopScope)(nodes)
fixScopes(tree)
}


/** When we lift, we don't know if we are within an enclosing xml element
* which defines a scope. In some cases we will have to fix the scope.
*
* E.g:
* {{{
* xml"""<a xmlns:pre="scope0">${ xml"<b/>" }</a>"""
* }}}
* Here the scope of `<b/>` is `TopScope` but should be `scope0`
*/
private def fixScopes(tree: Tree): Tree = {
val typed = c.typecheck(tree)

var scopeSym = NoSymbol
c.internal.typingTransform(typed)((tree, api) => tree match {
case q"$_.TopScope" if scopeSym != NoSymbol =>
api.typecheck(q"$scopeSym")
case q"val $$_scope = $_" => // this assignment is only here when creating new scope
scopeSym = tree.symbol
tree
case _ =>
api.default(tree)
})
}

private val sx = q"_root_.scala.xml"

private implicit def liftNode(implicit outer: Scope): Liftable[Node] =
Liftable {
case n: Group => liftGroup(outer)(n)
case n: Elem => liftElem(outer)(n)
case n: Text => liftText(n)
case n: Placeholder => liftPlaceholder(n)
case n: Comment => liftComment(n)
case n: PCData => liftPCData(n)
case n: ProcInstr => liftProcInstr(n)
case n: Unparsed => liftUnparsed(n)
case n: EntityRef => liftEntityRef(n)
}

private implicit def liftNodes(implicit outer: Scope): Liftable[Seq[Node]] = Liftable { nodes =>
val additions = nodes.map(node => q"$$buf &+ $node")
q"""
{
val $$buf = new $sx.NodeBuffer
..$additions
$$buf
}
"""
}

private def liftGroup(implicit outer: Scope) = Liftable { gr: Group =>
q"new $sx.Group(${gr.nodes})"
}

private def liftElem(implicit outer: Scope) = Liftable { e: Elem =>
def outerScope =
if (outer.isTopScope) q"$sx.TopScope"
else q"$$_scope"

def liftAttributes(atts: Seq[Attribute]): Seq[Tree] = {
val metas = atts.reverse.map { a =>
val value = a.value match {
case Seq(v) => q"$v"
case vs => q"$vs"
}

val att =
if (a.prefix.isEmpty) q"new $sx.UnprefixedAttribute(${a.key}, $value, $$md)"
else q"new $sx.PrefixedAttribute(${a.prefix}, ${a.key}, $value, $$md)"

q"$$md = $att"
}

val init: Tree = q"var $$md: $sx.MetaData = $sx.Null"
init +: metas
}

def liftNameSpaces(nss: Seq[Attribute]): Seq[Tree] = {
val init: Tree = q"var $$tmpscope: $sx.NamespaceBinding = $outerScope"

val scopes = nss.map { ns =>
val prefix = if (ns.prefix.nonEmpty) q"${ns.key}" else q"null: String"
val uri = ns.value.head match {
case Text(text, _) => q"$text"
case scalaExpr => q"$scalaExpr"
}
q"$$tmpscope = new $sx.NamespaceBinding($prefix, $uri, $$tmpscope)"
}

init +: scopes
}

val (nss, atts) = e.attributes.partition(_.isNamespace)

val prefix: Tree =
if (e.prefix.isEmpty) q"null: String"
else q"${e.prefix}"

val label = q"${e.label}"

val (metapre, metaval) =
if (atts.isEmpty) (Nil, q"$sx.Null")
else (liftAttributes(atts), q"$$md")

val minimizeEmpty = q"${e.minimizeEmpty}"

def children = {
val newScope = new Scope(outer.isTopScope && nss.isEmpty)
liftNodes(newScope)(e.children)
}

def newElem(scope: Tree) =
if (e.children.isEmpty) q"new $sx.Elem($prefix, $label, $metaval, $scope, $minimizeEmpty)"
else q"new $sx.Elem($prefix, $label, $metaval, $scope, $minimizeEmpty, $children: _*)"

if (nss.isEmpty) {
q"""
{
..$metapre
${newElem(outerScope)}
}
"""
} else {
val scopepre = liftNameSpaces(nss)
q"""
{
..$scopepre;
{
val $$_scope = $$tmpscope
..$metapre
${newElem(q"$$_scope")}
}
}
"""
}
}

private val liftText = Liftable { t: Text =>
q"new $sx.Text(${t.text})"
}

private val liftPlaceholder = Liftable { p: Placeholder =>
self.arg(p.id)
}

private val liftComment = Liftable { c: Comment =>
q"new $sx.Comment(${c.text})"
}

private val liftPCData = Liftable { pcd: PCData =>
q"new $sx.PCData(${pcd.data})"
}

private val liftProcInstr = Liftable { pi: ProcInstr =>
q"new $sx.ProcInstr(${pi.target}, ${pi.proctext})"
}

private val liftUnparsed = Liftable { u: Unparsed =>
q"new $sx.Unparsed(${u.data})"
}

private val liftEntityRef = Liftable { er: EntityRef =>
q"new $sx.EntityRef(${er.name})"
}
}

private object Liftables {
class Scope(val isTopScope: Boolean) extends AnyVal
final val TopScope = new Scope(true)
}
86 changes: 86 additions & 0 deletions quote/src/main/scala/scala/xml/quote/internal/QuoteImpl.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package scala.xml.quote.internal

import fastparse.all._

import scala.collection.mutable.ArrayBuffer
import scala.reflect.macros.whitebox
import scala.xml.quote.internal.QuoteImpl._

class QuoteImpl(val c: whitebox.Context) extends Liftables with Transform {
import c.universe._

private lazy val q"$_($_(..$parts)).xml.apply[..$_](..$args)" = c.macroApplication

def apply[T](args: Tree*): Tree = {
val nodes = transform(parsedXml)
lift(nodes)
}

private[internal] def arg(i: Int): Tree = args(i)

private[internal] def abort(offset: Int, msg: String): Nothing = {
val pos = correspondingPosition(offset)
c.abort(pos, msg)
}

private lazy val (xmlStr, offsets) = {
val sb = new StringBuilder
val poss = ArrayBuffer.empty[Int]

def appendPart(part: Tree) = {
val q"${value: String}" = part
poss += sb.length
sb ++= value
poss += sb.length
}

def appendHole(i: Int) =
sb ++= Hole.encode(i)

for ((part, i) <- parts.init.zipWithIndex) {
appendPart(part)
appendHole(i)
}
appendPart(parts.last)

(sb.toString, poss.toArray)
}

/** Given an offset in the xmlString computes the corresponding position */
private def correspondingPosition(offset: Int): Position = {
val index = offsets.lastIndexWhere(offset >= _)
val isWithinHoleOrAtTheEnd = index % 2 != 0

if (isWithinHoleOrAtTheEnd) {
val prevPartIndex = (index - 1) / 2
val pos = parts(prevPartIndex).pos
val posOffset = offset - offsets(index - 1)
pos.withPoint(pos.point + posOffset)
} else {
val partIndex = index / 2
val pos = parts(partIndex).pos
val posOffset = offset - offsets(index)
pos.withPoint(pos.point + posOffset)
}
}

private def parsedXml: Seq[ast.Node] = {
xmlParser.XmlExpr.parse(xmlStr) match {
case Parsed.Success(nodes, _) => nodes
case Parsed.Failure(expected, offset, _) =>
abort(offset, s"expected: $expected")
}
}

def pp[T <: Tree](t: T): T = {
println(showCode(t, printIds = true))
t
}
}

private object QuoteImpl {
val xmlParser = {
val Placeholder = P( Index ~ Hole.Parser ).map { case (pos, id) => ast.Placeholder(id, pos) }
new XmlParser(Placeholder)
}
}
Loading