Next: , Up: TC-2 Samples   [Contents][Index]


4.4.2.1 TC-2 Pretty-Printing Samples

The parser builds abstract syntax trees that can be output by a pretty-printing module:

/* Define a recursive function. */
let
  /* Calculate n!. */
  function fact (n : int) : int =
    if  n = 0
      then 1
      else n * fact (n - 1)
in
  fact (10)
end

File 4.8: simple-fact.tig

$ tc -XA simple-fact.tig
/* == Abstract Syntax Tree. == */

function _main() =
  (
    let
      function fact(n : int) : int =
        (if (n = 0)
          then 1
          else (n * fact((n - 1))))
    in
      fact(10)
    end;
    ()
  )

Example 4.10: tc -XA simple-fact.tig


The pretty-printed output must be valid and equivalent.

Valid means that any Tiger compiler must be able to parse with success your output. Pay attention to the banners such as ‘== Abstract...’: you should use comments: ‘/* == Abstract... */’. Pay attention to special characters too.

print("\"\x45\x50ITA\"\n")

File 4.9: string-escapes.tig

$ tc -XA string-escapes.tig
/* == Abstract Syntax Tree. == */

function _main() =
  (
    print("\"EPITA\"\n");
    ()
  )

Example 4.11: tc -XA string-escapes.tig

Equivalent means that, except for syntactic sugar, the output and the input are equal. Syntactic sugar refers to ‘&’, ‘|’, unary ‘-’, etc.

1 = 1 & 2 = 2

File 4.10: 1s-and-2s.tig

$ tc -XA 1s-and-2s.tig
/* == Abstract Syntax Tree. == */

function _main() =
  (
    (if (1 = 1)
      then ((2 = 2) <> 0)
      else 0);
    ()
  )

Example 4.12: tc -XA 1s-and-2s.tig

$ tc -XA 1s-and-2s.tig >output.tig

Example 4.13: tc -XA 1s-and-2s.tig >output.tig

$ tc -XA output.tig
/* == Abstract Syntax Tree. == */

function _main() =
  (
    (if (1 = 1)
      then ((2 = 2) <> 0)
      else 0);
    ()
  )

Example 4.14: tc -XA output.tig

Beware that for loops are encoded using a ast::VarDec: do not display the ‘var’:

for i := 0 to 100 do
   (print_int (i))

File 4.11: for-loop.tig

$ tc -XA for-loop.tig
/* == Abstract Syntax Tree. == */

function _main() =
  (
    (for i := 0 to 100 do
      print_int(i));
    ()
  )

Example 4.15: tc -XA for-loop.tig

Parentheses must not stack for free; you must even remove them as the following example demonstrates.

((((((((((0))))))))))

File 4.12: parens.tig

$ tc -XA parens.tig
/* == Abstract Syntax Tree. == */

function _main() =
  (
    0;
    ()
  )

Example 4.16: tc -XA parens.tig

This is not a pretty-printer trick: the ASTs of this program and that of ‘0’ are exactly the same: a single ast::IntExp.

As a result, anything output by ‘tc -A’ is equal to what ‘tc -A | tc -XA -’ displays!


Next: , Up: TC-2 Samples   [Contents][Index]