Docsity

Python Assignment: Abstract Syntax Trees and Recursive Functions in ECEN and CSCI - Prof. , Study notes 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 in this assignment are
•abstract syntax trees (AST),
•recursive functions over ASTs, and
•test-driven development.
1 The P0subset of Python
The first subset of Python that we consider is extremely simple: it consists
of print statements, integers and arithmetic operations, and the input()
function. We call this subset P0. The following is an example P0program.
print1-2+3/-4
Programs are written one character at a time but we do not think of
programs as sequences of characters. We think about programs in chunks
such as an if statements or a for loop. These chunks often have parts, for
example, an if statement has a then-clause and an else-clause. Inside the
compiler, we will often traverse over a program one chunk at a time and
from top to bottom, going from parent chunks to their parts, their children.
A data-structure that facilitates this kind of traversal is a tree. Each node in
the tree represents a chunk, a programming language construct, and each
node has edges that point to its children. When a tree is used to represent a
program, we call it an abstract syntax tree (AST). While trees in nature grow
up with their leaves at the top, we typically think of ASTs as growing down
with the leaves at the bottom.
Figure 1 shows the abstract syntax tree for the above P0program. Fortu-
nately, there is a standard Python library that turns a sequence of characters
into an AST, using a process called parsing that we’ll learn about in the next
1
pf3
pf4
pf5
pf8

Partial preview of the text

Download Python Assignment: Abstract Syntax Trees and Recursive Functions in ECEN and CSCI - Prof. and more Study notes 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 in this assignment are

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

1 The P 0 subset of Python

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

print 1 - 2 + 3 / - Programs are written one character at a time but we do not think of programs as sequences of characters. We think about programs in chunks such as an if statements or a for loop. These chunks often have parts, for example, an if statement has a then-clause and an else-clause. Inside the compiler, we will often traverse over a program one chunk at a time and from top to bottom, going from parent chunks to their parts, their children. A data-structure that facilitates this kind of traversal is a tree. Each node in the tree represents a chunk, a programming language construct, and each node has edges that point to its children. When a tree is used to represent a program, we call it an abstract syntax tree (AST). While trees in nature grow up with their leaves at the top, we typically think of ASTs as growing down with the leaves at the bottom. Figure 1 shows the abstract syntax tree for the above P 0 program. Fortu- nately, there is a standard Python library that turns a sequence of characters into an AST, using a process called parsing that we’ll learn about in the next

assignment. 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 repre- sented by an object, an instance of one of these classes. Figure 2 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 1: The abstract syntax tree for print 1 - 2 + 3 / -4.

2 The meaning of P 0 (the semantics)

The meaning of Python programs, that is, what happens when you run a Python program, is defined in the Python Reference Manual [3].

Exercise 2.1. Read the sections of the Python Reference Manual that apply to P 0 : 3.2, 5.2.2, 5.4, 5.5, 5.6, and 6.6. Also read the entry for the input function in the Python Library Reference, in section 2.1.

Sometimes it is difficult to understand the technical jargon in program- ming language reference manuals. Another way to learn about the mean- ing of Python programs, and perhaps a more fun way, is to experiment with the standard python interpreter. If there is an aspect of the language that you don’t understand, create a program that uses that aspect and run it! Suppose you’re not sure about a particular feature but have a guess, a hypothesis, about how it works. Think of a program that will produce one output if your hypothesis is correct and produce a different output if your hypothesis is incorrect. You can then run the python interpreter to validate or disprove your hypothesis. For example, suppose that you are not sure what happens when the result of an arithmetic operation results in a very large integer, an integer too large to be stored in a machine register (> 231 − 1 ). In the language C integer operations wrap around, so 2 × 230 produces − 2147483648 [1]. Does the same thing happen in Python? Let’s try it and see:

2 * 2** 2147483648L

No, the number does not wrap around. Instead, Python has two kinds of integers: plain integers for integers in the range − 231 to 231 − 1 and long integers for integers in a range that is only limited by the amount of (virtual) memory in your computer.

For P 0 we restrict our attention to just plain integers and say that operations that result in integers outside of the range − 231 to 231 − 1 are undefined. The built-in Python function input() reads in a line from standard in- put (stdin) and then interprets the string as if it were a Python expression, using the built-in eval function. For P 0 we only require a subset of this functionality. The input function need only deal with integer literals. A call to the input function, of the form "input()", is parsed into the func- tion call AST node CallFunc. You do not need to handle general function calls, just recognize the special case of a function call where the function being called is named "input".

Exercise 2.2. Write at least five programs in the P 0 subset of Python that help you understand the language. Look for corner cases or unusual as- pects of the language to test in your programs. Later in this assignment you will use these programs to test your compiler, so the tests should be thorough and should exercise all the features of P 0. If the tests are not thor- ough, then your compiler may pass all the tests but still have bugs that will

be caught when your compiler is tested by the grader. Run the programs using the standard python interpreter. Add your test programs to the test directory. For the tests that use the input function, also put an input file in the test directory with the same name as the test file but with an file extension of .in instead of .py.

3 Recursive functions

The main programming technique for analyzing and manipulating ASTs is to write recursive functions that traverse the tree. As an example, we’ll create a function called num nodes that counts the number of nodes in an AST. Figure 3 shows a schematic of how this function works. Each triangle represents a call to num nodes and is responsible for counting the number of nodes in the sub-tree whose root is the argument to num nodes. In the figure, the largest triangle is responsible for counting the number of nodes in the sub-tree rooted at Add. The key to writing a recursive function is to be lazy! Let the recursion do the work for you. Just process one node and let the recursion handle the child sub-trees. In Figure 3 we make the recursive calls num nodes(left) and num nodes(right) to count the nodes in the child sub-trees. All we have to do to then is to add the two numbers and add one more to count the current node. Figure 4 shows the definition of the num nodes function.

Add

left right

num_nodes(Add)

num_nodes(left) num_nodes(right)

Figure 3: Schematic for a recursive function processing an AST.

When a node has a list of children, as is the case for Stmt and Printnl, a convenient way to process the children is to use List Comprehensions, described in the Python Tutorial [4]. A list comprehension has the form [compute for variable in list]

and performs some computation for each element in a given list, resulting in a list holding the results of the computations. For example, in Figure 4 in the case for Stmt we write [num_nodes(x) for x in n.nodes]. This makes a recursive call to num_nodes for each child node in the list n.nodes. The result of this list comprehension is a list of numbers, which we then add up using the sum function, which is documented under Built-in Functions in the Python Library Manual [2].

4 Interpreting P 0 and compiling to C

An interpreter is something that takes as input a program and then exe- cutes the program. An interpreter can be a machine, for example, an Intel computer can be viewed as an interpreter for x86 assembly language^1. An interpreter can also be a program. A compiler is a program that translates a program in one language into a program in another language. The target language is usually the assembly language of a particular computer, but this doesn’t have to be the case. Figure 5

Program in Language 1

Program in Language 2 Output of the Program

compile

interpret

interpret

Figure 5: Diagram depicting interpretation and compilation.

Exercise 4.1. Create a Python script named interp.py that reads in a file containing a P 0 program and interprets the program, printing the output of the program to the standard output (stdout). Your interpreter should be a recursive function patterned after the num_nodes function. You are not allowed to use Python’s built-in eval function.

Exercise 4.2. Create a Python script named compile.py that reads in a file containing a P 0 program and compiles it to a C file. The script must take a

(^1) Intel computers are really interpreters of the x86 machine language, but there is little conception difference between the machine language and the assembly language.

command-line argument that specifies the input file (a file with a .py exten- sion) and the script must output the resulting C program standard output (stdout), for example by using the Python print statement. Use test-driven development to create the compiler. Initially, the compiler should do noth- ing, and just output an empty file. Use the provided script run tests.py to compare the output of compiling and running the generated C files to that of the standard python interpreter for all the test programs in direc- tory 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 ap- propriate tests begin to succeed. The compiler is finished when all of the tests succeed.

References

[1] B. W. Kernighan and D. M. Ritchie. The C programming language. Pren- tice Hall Press, Upper Saddle River, NJ, USA, 1988.

[2] G. van Rossum. Python Library Reference. Python Software Foundation, 2.5 edition, September 2006.

[3] G. van Rossum. Python Reference Manual. Python Software Foundation, 2.5 edition, September 2006.

[4] G. van Rossum. Python Tutorial. Python Software Foundation, 2.5 edi- tion, September 2006.