Docsity

Integer expressions and abstract syntax trees - Assignment 1 | ECEN 4553, Assignments of Electrical and Electronics Engineering

Toggle sidebar
bg1
Assignment 1: Integer expressions and abstract syntax trees
ECEN 4553 & 5013, CSCI 4555 & 5525
Prof. Jeremy G. Siek
The main concepts for this week are
•abstract syntax trees (AST),
•recursive functions over ASTs (to generate C code), and
•test-driven development.
1 Syntax of P0
The first subset of Python that we consider is extremely simple: it consists of print statements
with integers and arithmetic operations. We call this subset P0. The following is an example P0
program.
print1-2+3/-4
In general, the syntax of the source code for a language is called its concrete syntax. The concrete
syntax of P0specifies which programs, expressed as sequences of characters, are P0programs.
The concrete syntax of P0is shown in Figure 1. (If you need a refresher on how a context-free
grammar specifies a language, read Section 3.1 of [1].)
program ::= module
module ::= simple_statement+
simple_statement ::= "print" expression ("," expression)*
unary_op ::= "+" | "-"
binary_op ::= "+" | "-" | "*" | "/" | "%" | "**"
expression ::= integer
| unary_op expression
| expression binary_op expression
| "(" expression ")"
Figure 1: Concrete syntax for the P0subset of Python.
It would be tedious to write a compiler in terms of sequences of characters. Fortunately, there
is a standard Python library that parses a sequence of characters into a much more useful data-
structure, an abstract syntax tree (AST), which is an in-memory structure that represents a program
at a more conceptual level, with a node for each expression in the program. The structure forms a
tree, with each node containing references to the nodes for its subexpressions. Figure 2 shows the
abstract syntax tree for the above example P0program. The following interaction with the python
interpreter shows a call to the Python parser and the textual representation of the resulting AST.
1
pf3
pf4

Partial preview of the text

Download Integer expressions and abstract syntax trees - Assignment 1 | ECEN 4553 and more Assignments Electrical and Electronics Engineering in PDF only on Docsity!

Assignment 1: Integer expressions and abstract syntax trees

ECEN 4553 & 5013, CSCI 4555 & 5525

Prof. Jeremy G. Siek

The main concepts for this week are

  • abstract syntax trees (AST),
  • recursive functions over ASTs (to generate C code), and
  • test-driven development.

1 Syntax of P 0

The first subset of Python that we consider is extremely simple: it consists of print statements with integers and arithmetic operations. We call this subset P 0. The following is an example P 0 program.

print 1 - 2 + 3 / -

In general, the syntax of the source code for a language is called its concrete syntax. The concrete syntax of P 0 specifies which programs, expressed as sequences of characters, are P 0 programs. The concrete syntax of P 0 is shown in Figure 1. (If you need a refresher on how a context-free grammar specifies a language, read Section 3.1 of [1].)

program ::= module module ::= simple_statement+ simple_statement ::= "print" expression ("," expression)* unary_op ::= "+" | "-" binary_op ::= "+" | "-" | "" | "/" | "%" | "*" expression ::= integer | unary_op expression | expression binary_op expression | "(" expression ")"

Figure 1: Concrete syntax for the P 0 subset of Python.

It would be tedious to write a compiler in terms of sequences of characters. Fortunately, there is a standard Python library that parses a sequence of characters into a much more useful data- structure, an abstract syntax tree (AST), which is an in-memory structure that represents a program at a more conceptual level, with a node for each expression in the program. The structure forms a tree, with each node containing references to the nodes for its subexpressions. Figure 2 shows the abstract syntax tree for the above example P 0 program. The following interaction with the python interpreter shows a call to the Python parser and the textual representation of the resulting AST.

import compiler ast = compiler.parse("print 1 - 2 + 3 / -4") ast Module(None, Stmt([Printnl([Add((Sub((Const(1), Const(2))), Div((Const(3), UnarySub(Const(4))))))], None)]))

The AST produced by the Python parser is represented using several classes, one for each kind of node in the AST. Thus, each node in the AST is represented by an object, an instance of one of these classes. Figure 3 shows the Python classes for representing the AST nodes of the P 0 subset of Python.

Printnl

Sub

Add

Div

1 2 3 UnarySub

4

nodes[0]

left right

left right (^) left right

expr

Module node Stmt nodes[0]

Figure 2: The abstract syntax tree for print 1 - 2 + 3 / -4.

class Module(Node): def init(self, doc, node): self.doc = doc self.node = node class Stmt(Node): def init(self, nodes): self.nodes = nodes class Printnl(Node): def init(self, nodes, dest): self.nodes = nodes self.dest = dest class Const(Node): def init(self, value): self.value = value class UnaryAdd(Node): def init(self, expr): self.expr = expr class UnarySub(Node): def init(self, expr): self.expr = expr class Add(Node): def init(self, (left, right)): self.left = left self.right = right

class Sub(Node): def init(self, (left, right)): self.left = left self.right = right class Mul(Node): def init(self, (left, right)): self.left = left self.right = right class Div(Node): def init(self, (left, right)): self.left = left self.right = right class Mod(Node): def init(self, (left, right)): self.left = left self.right = right class Power(Node): def init(self, (left, right)): self.left = left self.right = right

Figure 3: The Python classes for representing P 0 ASTs.

from compiler.ast import * def ast_to_string(ast): if isinstance(ast, Module): return ’Module(None, ’ + ast_to_string(ast.node) + ’)’ elif isinstance(ast, Stmt): return ’Stmt([’ + ’, ’.join(map(ast_to_string, ast.nodes)) + ’])’ elif isinstance(ast, Printnl): return ’Printnl([’ + ’, ’.join(map(ast_to_string, ast.nodes)) + ’], None)’ elif isinstance(ast, Const): return ’%d’ % ast.value elif isinstance(ast, UnarySub): return ’UnarySub(’ + ast_to_string(ast.expr) + ’)’ elif isinstance(ast, Add): return ’Add(’ + ast_to_string(ast.left) \

  • ’, ’ + ast_to_string(ast.right) + ’)’ ...

Figure 4: Recursive function that traverses an AST and produces a string representation.

(Note: Change the example to num_nodes and use list comprehensions instead of map and filter.)

Exercise 3.1. Create a Python script named compile.py that reads in a file that containing a P 0 program and compiles it to a C file. The script must take a command-line argument that specifies the input file (a file with a .py extension) and the script must output the resulting C program standard output (stdout), for example by using the Pyhon print statement. Use test-driven devel- opment to create the compiler. Initially, the compiler should do nothing, and just output an empty file. Use the provided script run tests.py to compare the output of the generated C files to that of the standard python interpreter for all the test programs in directory test. Feel free to modify and customize the script as necessary. The compiler should initially fail all of the tests. Now begin to write a recursive function that translates a P 0 AST to the C programming language. Write the function incrementally, adding one or two cases at a time and re-running the tests to make sure that the new cases that you’ve added make the appropriate tests begin to succeed. The compiler is finished when all of the tests succeed.

References

[1] A. W. Appel and J. Palsberg. Modern Compiler Implementation in Java. Cambridge University Press, New York, NY, USA, 2003.

[2] G. van Rossum. Python Library Reference. Python Software Foundation, http://docs.python. org/lib/lib.html, 2.5 edition, September 2006.

[3] G. van Rossum. Python Reference Manual. Python Software Foundation, http://docs.python. org/ref/ref.html, 2.5 edition, September 2006.

[4] G. van Rossum. Python Tutorial. Python Software Foundation, http://docs.python.org/ tut/tut.html, 2.5 edition, September 2006.