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 17: simple-fact.tig
$ tc -A simple-fact.tig /* == Abstract Syntax Tree. == */ let function fact (n : int) : int = if (n = 0) then 1 else (n * fact ((n - 1))) in fact (10) end Example 18: tc -A simple-fact.tig
Passing -D, --ast-delete, reclaims the memory associated to the AST. Valgrind will be used to check that no memory leaks, see Valgrind.
No heroic effort is asked for silly options combinations.
$ tc -D simple-fact.tig Example 19: tc -D simple-fact.tig
$ tc -DA simple-fact.tig error-->tasks.cc:22: Precondition `the_program' failed. =>134 Example 20: tc -DA 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 21: string-escapes.tig
$ tc -AD string-escapes.tig /* == Abstract Syntax Tree. == */ print ("\"EPITA\n\"") Example 22: tc -AD 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 23: 1s-and-2s.tig
$ tc -AD 1s-and-2s.tig /* == Abstract Syntax Tree. == */ if (1 = 1) then (2 = 2) else 0 Example 24: tc -AD 1s-and-2s.tig
$ tc -AD 1s-and-2s.tig >output.tig Example 25: tc -AD 1s-and-2s.tig >output.tig
$ tc -AD output.tig /* == Abstract Syntax Tree. == */ if (1 = 1) then (2 = 2) else 0 Example 26: tc -AD output.tig
For loops must be properly displayed, i.e., although we use a
ast::VarDec
for the index of the loop, you must not display
var:
/* Valid let and for. */
let
var a := 0
in
for i := 0 to 100 do (a := a+1; ())
end
File 27: for-loop.tig
$ tc -AD for-loop.tig /* == Abstract Syntax Tree. == */ let var a := 0 in for i := 0 to 100 do ( a := (a + 1); () ) end Example 28: tc -AD for-loop.tig
Parentheses must not stack for free; in fact, you must even remove them.
((((((((((0))))))))))
File 29: parens.tig
$ tc -AD parens.tig /* == Abstract Syntax Tree. == */ 0 Example 30: tc -AD parens.tig
As a result, anything output by tc -AD is equal to what tc -AD | tc -AD - displays!