XML, XML Schema, XSLT are a great combination to define a new extensible language. The mechanism is as follows:
XML | used to write a piece of code (compilation unit, if you will) |
---|
XML Schema | used to define the grammar of a language, you can use the import clause to build a language as an extension of another |
---|
XSLT | used to, either generate documentation (HTML and/or SVG for UML for example) or generate lower level language code |
---|
XML Schema provides a redefinition mechanism that allows to modify a schema construct by extension or reduction. In our first example, the original 'for' loop could be define as:
element:for
element:init ; the initialization part
element:type ; example: Iterator
element:name ; example: i
element:expression ; example: list.elements()
element:test ; the exit test
element:step ; the step between loops
element:body
The new construction could be defined as:
element:for redefines original:for
reduction:init
reduction:test
reduction:step
extension:item ; the item visited
element:type ; example: String
element:name ; example: s
extension:collection ; example: list.elements()
The transformation (sort of compilation) would be like:
<xsl:template match="for">
<o:for>
<o:init>
<o:type>Iterator</o:type>
<o:name>__i</o:name>
<o:expression><xsl:apply-templates select="collection"/></o:expression>
</o:init>
<o:next>
__i.hasNext()
</o:next>
<o:step/>
<o:body>
<xsl:apply-templates select="item/type"/><xsl:value select="item/name"/> =
(<xsl:apply-templates select="item/type"/>) __i.next(); // casting here
<xsl:apply-templates select="body"/>
</o:body>
</o:for>
</xsl:template>
With 'o' being the namespace of the original language. Yes, this is how easy writing a compiler could be. Of course, XML and XSLT are slow, but if the code is easier to write, bugs will have less room to hide and the loss of time during compilation will be regained during the debugging phase.