www.delorie.com/gnu/docs/kawa/kawa-tour_14.html   search  
 
Buy GNU books!


Kawa: Compiling Scheme to Java

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.13 Syntax and Macros

 
class Syntax {
  public abstract Expression rewrite (Object obj, Translator tr);
  ...
}

The rewrite method in Translator checks for syntactic keywords and macros. If the car of a "call" is a Syntax or if it is a Symbol that is bound to a Syntax, then its rewrite method is called.

As an example, this trivial class implements quote.

 
class quote extends Syntax {
  public Expression rewrite (Object obj, Translator tr)
  {
    // Error-checking is left out.
    Object value = ((Pair)obj).car;
    return new QuoteExp(value);
  }
  ...
}

Much more complicated is the Syntax that implements define-syntax.

 
class define_syntax extends Syntax {
  public Expression rewrite (Object obj, Translator tr)
  {
    enter (new SyntaxRules (...));
  }
  ...
}

The result is a SyntaxRules object, which contains an encoded representation of the patterns and templates in the syntax-rules. This is in its own right a Syntax object.

 
class SyntaxRules extends Syntax {
SyntaxRule[] rules;
  public Expression rewrite (Object obj, Translator tr)
  {
    Object[] v = new Object[maxVars];
    for (int i = 0;  i < rules.length;)
      {
        SyntaxRule r = rules[i++];
        if (r.match (obj, v))
          return r.execute_template(v, tr);
      }
    return tr.syntaxError ("no matching syntax-rule");
  }
  ...
}

Contrast evaluating a procedure definition (lambda), which causes a new sub-class of Procedure to be created and compiled, while evaluating a define-syntax only causes a new instance of SyntaxRules to be created. This is because the syntax-rules can be represented using relatively simple and compact data structures. A traditional low-level macro facility specifies the transformations using executable code, and that probably would need a new Procedure sub-class.


  webmaster   donations   bookstore     delorie software   privacy  
  Copyright © 2003   by The Free Software Foundation     Updated Jun 2003