XMLMath
XMLMath
 
Font size:      

Stanzas

Using Stanzas

Declarations provide a valuable feature to xmlmath expressions, as they allow the result of sub-expression to be labeled with a name and then re-used at one or more other locations in the expression. However, xmlmath comes with another important declarative operator: <stanza>.

A stanza also offers a way to describe and label a sub-expression, but unlike declarations, stanzas are not evaluated in the scope where they are created. Instead, stanzas are used through the <inline> tag, which is substituted by a copy of the stanza's body during the parsing phase.

When the parsing phase is completed, all <stanza> and <inline> tags have been removed. Each <inline> tag has then been replaced by a copy of its stanza.

Because stanzas are never evaluated in the scope where they were created, it is possible to refer to declarations and other stanza's that may not yet be declared. This is illustrated below in an expression that contains a stanza which refers to an integer value "x" to calculate its squared value.
Variable "x" is only declared further down the expression tree, just before the stanza is inlined.

The result of the expression is the string: 4 squared = 16

							
<expression xmlns="http://xmlmath.org/1.0">

  <stanza name="squared">
    <product datatype="long">
      <linkLong name="x"/>
      <linkLong name="x"/>
    </product>
  </stanza>
	
  <strcat>
    <string value="4 squared = "/>
    <toString>

      <inline name="squared">
        <declare name="x">
          <long value="4"/>
        </declare>
      </inline>

    </toString>
  </strcat>
</expression>
						

Recursion

Because stanzas substitute their referring <inline> counterpart when the expression is being parsed, recursion is not possible. Attempting to use a stanza recursively (or creating a circular reference between different stanzas) will cause a StackOverflowError or OutOfMemoryError being dumped to stderr while the expression is being parsed.

The expression below illustrates the problem of recursive stanzas: it crashes during parsing:

							
<expression xmlns="http://xmlmath.org/1.0">
  <stanza name="foo">
    <inline name="foo"/>
  </stanza>
  <inline name="foo"/>
</expression>