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

Give elements default labels #467

Open
wants to merge 1 commit into
base: develop
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: 2 additions & 1 deletion cli/src/main/resources/scalaxb.scala.template
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ trait CanReadXML[A] {
}

trait CanWriteXML[A] {
def defaultElementLabel: Option[String] = None
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure if doing is this in CanWriteXML[A] makes sense. A represents the inside of the <x>1</x> element, not x. Whereas DataRecord[A] represents both.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are situations where the element name is obvious, but in those cases maybe we need typeclass instance for DataRecord[A], or maybe a new typclass that extends CanWriteXML.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your feedback, Eugene. I'm not sure how to implement these suggestions without making significant changes to the code base. Can you think of a (relatively easy) way to do this?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My impression was that A has a 1-1 correspondence with the schema from which it was generated. I figure scalaxb should know about that top-level element name for that type, because it was in that schema. I'd like to be able to retrieve that without parsing the xsd myself - which kind of defeats some of the point of scalaxb for me.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The use case is that there be some kind of "ToXML" typeclass that includes enough information to render an instance of that type as an XML document, e.g. for an HTTP response (where the user can choose to have the instance rendered as JSON or XML). Such as is done for http://hackage.haskell.org/package/servant-xml-1.0.1.2/docs/Servant-XML.html

def writes(obj: A, namespace: Option[String], elementLabel: Option[String],
scope: NamespaceBinding, typeAttribute: Boolean): NodeSeq
}
Expand Down Expand Up @@ -733,7 +734,7 @@ trait CanWriteChildNodes[A] extends CanWriteXML[A] {
def writes(obj: A, namespace: Option[String], elementLabel: Option[String],
scope: scala.xml.NamespaceBinding, typeAttribute: Boolean): scala.xml.NodeSeq = {
val elem = scala.xml.Elem(Helper.getPrefix(namespace, scope).orNull,
elementLabel getOrElse { sys.error("missing element label.") },
elementLabel orElse defaultElementLabel getOrElse { sys.error("missing element label.") },
writesAttribute(obj, scope),
scope, true,
writesChildNodes(obj, scope): _*)
Expand Down
9 changes: 7 additions & 2 deletions cli/src/main/scala/scalaxb/compiler/xsd/GenSource.scala
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,8 @@ class GenSource(val schema: SchemaDecl,
}}
case _ => Left("reads failed: seq must be scala.xml.Node")
}}


override val defaultElementLabel: Option[String] = { quote(decl.family.headOption) }
def writes(__obj: {fqn}, __namespace: Option[String], __elementLabel: Option[String],
__scope: scala.xml.NamespaceBinding, __typeAttribute: Boolean): scala.xml.NodeSeq = __obj match {{
{ val cases = for (sub <- context.baseToSubs(decl))
Expand Down Expand Up @@ -388,6 +389,7 @@ class GenSource(val schema: SchemaDecl,

def defaultFormats = if (simpleFromXml) <source> trait Default{formatterName} extends scalaxb.XMLFormat[{fqn}] with scalaxb.CanWriteChildNodes[{fqn}] {{
val targetNamespace: Option[String] = { quote(schema.targetNamespace) }
override val defaultElementLabel: Option[String] = { quote(decl.family.headOption) }
import scalaxb.ElemName._

def reads(seq: scala.xml.NodeSeq, stack: List[scalaxb.ElemName]): Either[String, {fqn}] = seq match {{
Expand All @@ -398,6 +400,7 @@ class GenSource(val schema: SchemaDecl,
{makeWritesAttribute}{makeWritesChildNodes}
}}</source>
else <source> trait Default{formatterName} extends {defaultFormatSuperNames.mkString(" with ")} {{
override val defaultElementLabel: Option[String] = { quote(decl.family.headOption) }
val targetNamespace: Option[String] = { quote(schema.targetNamespace) }

{ if (decl.isNamed) "override def typeName: Option[String] = Some(" + quote(decl.name) + ")" + newline + newline + indent(2)
Expand Down Expand Up @@ -492,6 +495,7 @@ class GenSource(val schema: SchemaDecl,
Snippet(<source>{ buildComment(seq) }case class {localName}({paramsString}){superString}</source>,
<source/>,
<source> trait Default{formatterName} extends scalaxb.XMLFormat[{fqn}] {{
final override def defaultElementLabel: Option[String] = None // sequences have no label
def reads(seq: scala.xml.NodeSeq, stack: List[scalaxb.ElemName]): Either[String, {fqn}] = Left("don't call me.")

{makeWritesXML}
Expand Down Expand Up @@ -642,6 +646,7 @@ object {localName} {{
<source> def build{formatterName} = new Default{formatterName} {{}}
trait Default{formatterName} extends scalaxb.XMLFormat[{fqn}] {{
val targetNamespace: Option[String] = { quote(schema.targetNamespace) }
override val defaultElementLabel: Option[String] = { quote(decl.family.headOption) }

def fromString(value: String, scope: scala.xml.NamespaceBinding): {fqn} = {valueCode} match {{
{ enums.map(e => makeCaseEntry(e)) }
Expand All @@ -655,7 +660,7 @@ object {localName} {{
def writes(__obj: {fqn}, __namespace: Option[String], __elementLabel: Option[String],
__scope: scala.xml.NamespaceBinding, __typeAttribute: Boolean): scala.xml.NodeSeq =
scala.xml.Elem(scalaxb.Helper.getPrefix(__namespace, __scope).orNull,
__elementLabel getOrElse {{ sys.error("missing element label.") }},
__elementLabel orElse defaultElementLabel getOrElse {{ sys.error("missing element label.") }},
scala.xml.Null, __scope, true, scala.xml.Text(__obj.toString))
}}</source>,
makeImplicitValue(fqn, formatterName))
Expand Down
25 changes: 25 additions & 0 deletions integration/src/test/resources/can_write_default_label.xsd
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:defaultLabels="http://www.example.com/default-labels"
targetNamespace="http://www.example.com/default-labels">

<element name="docdata">
<complexType>
<choice minOccurs="0" maxOccurs="unbounded">
<element ref="defaultLabels:docid"/>
<element ref="defaultLabels:urgency"/>
</choice>
</complexType>
</element>

<element name="urgency">
<complexType>
<attribute name="urg" type="NMTOKEN"/>
</complexType>
</element>
<element name="docid">
<complexType>
<attribute name="idstring" type="string"/>
</complexType>
</element>
</schema>
28 changes: 28 additions & 0 deletions integration/src/test/scala/CanWriteDefaultLabelTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import scalaxb.compiler.Config
import scalaxb.compiler.ConfigEntry._

object CanWriteDefaultLabelTest extends TestBase {
private val schemaFile = resource("can_write_default_label.xsd")

private def generate() = {
val config = Config.default.update(Outdir(tmp)).update(PackageNames(Map(None -> Some("defaultLabels"))))
module.process(schemaFile, config)
}

"XML generation falls back to default labels if none are specified" >> {
repl(generate())(
s"""
import defaultLabels._
import scalaxb.DataRecord

val urgency = Urgency()
val docId = Docid()
val options = Seq(DataRecord(urgency), DataRecord(None, Some("customDocIdTag"), docId))
scalaxb.toXML(Docdata(options), "docdata", scala.xml.TopScope).toString
""", expectedResult = scala.xml.Utility.trim(
<docdata>
<urgency />
<customDocIdTag />
</docdata>).toString)
}
}