This link has been bookmarked by 18 people . It was first bookmarked on 30 Jun 2008, by harry palmer.
-
26 Aug 11
-
14 Sep 08
-
30 Jun 08
-
Python: Writing a Compiler and Interpreter in 160 lines of code
I started experimenting with Python a few weeks ago. As a learning project I set myself the task of writing a compiler and interpreter for a simple 'while' language. I was very please with the result. Writing Python is like a dream. The work flow goes like this: think of the problem you want to solve, try a solution in the top level eval loop, if doesn't work, try something else, if it works, put it in your module. With the built in lists, tuples, and dictionaries, thought turns into code with a minimum of friction. All I can say is WOW!
The language I implemented is very simple:
stmtlist := (statement)* statement := 'if' condition stmtlist ['else' stmtlist] 'endif' | 'while' condition stmtlist 'endwhile' | label '=' expression | 'print' expression condition := expression ('=='|'!=') expression expression := term ('+'|'-' term)* term := label|digitNow here is the code. For a lexer I just split the input file into a list of tokens (see parseFile()). I used a tuple to hold the current token (format is: token, yytext, yyval). I used lists of lists to hold the parse tree (see comments in doStatementList()). To evaluate I just do a depth first walk of the parse tree (see execStatementList()).
-
-
23 Jun 08
-
22 Jun 08
hideaki-tPython: Writing a Compiler and Interpreter in 160 lines of code
-
20 Jun 08
-
viniciusjlMany American corporations are dysfunctional because corporate democracy is a myth in the United States. They run like a decaying socialistic state.
code compiler example howto interpreter programming python tips
Would you like to comment?
Join Diigo for a free account, or sign in if you are already a member.