Finished editing PythonLangImpl6.rst.

This commit is contained in:
Maggie Mari 2012-08-21 17:59:44 -05:00
commit 16860436d4

View file

@ -105,7 +105,9 @@ keywords:
pass pass
class UnaryToken(object): class UnaryToken(object):
pass pass
... ...
def Tokenize(string): def Tokenize(string):
... ...
elif identifier == 'in': elif identifier == 'in':
@ -295,7 +297,8 @@ whenever we define a new binary operator:
def main(): def main():
... ...
g_binop_precedence['<'] = 10 g_binop_precedence['<'] = 10
g_binop_precedence['+'] = 20 g_binop_precedence['-'] = 20 g_binop_precedence['+'] = 20
g_binop_precedence['-'] = 20
g_binop_precedence['*'] = 40 g_binop_precedence['*'] = 40
... ...
@ -347,8 +350,8 @@ simple: we'll add a new function to do it:
def ParseUnary(self): def ParseUnary(self):
# If the current token is not an operator, it must be a primary expression. # If the current token is not an operator, it must be a primary expression.
if (not isinstance(self.current, CharacterToken) or if (not isinstance(self.current, CharacterToken) or
self.current in [CharacterToken('('), CharacterToken(',')]): self.current in [CharacterToken('('), CharacterToken(',')]):
return self.ParsePrimary() return self.ParsePrimary()
# If this is a unary operator, read it. # If this is a unary operator, read it.
operator = self.current.chara operator = self.current.chara
@ -826,11 +829,13 @@ Lexer
class UnaryToken(object): class UnaryToken(object):
pass pass
class IdentifierToken(object): def __init__(self, name): class IdentifierToken(object):
self.name = name def __init__(self, name):
self.name = name
class NumberToken(object): def __init__(self, value): class NumberToken(object):
self.value = value def __init__(self, value):
self.value = value
class CharacterToken(object): class CharacterToken(object):
def __init__(self, char): def __init__(self, char):
@ -894,12 +899,12 @@ Lexer
yield CharacterToken(string[0]) yield CharacterToken(string[0])
string = string[1:] string = string[1:]
yield EOFToken() yield EOFToken()
Abstract Syntax Tree (aka Parse Tree) Abstract Syntax Tree (aka Parse Tree)
------------------------------------- -------------------------------------
.. code-block:: python .. code-block:: python
# Base class for all expression nodes. # Base class for all expression nodes.
class ExpressionNode(object): class ExpressionNode(object):
@ -911,7 +916,8 @@ Abstract Syntax Tree (aka Parse Tree)
def __init__(self, value): def __init__(self, value):
self.value = value self.value = value
def CodeGen(self): return Constant.real(Type.double(), self.value) def CodeGen(self):
return Constant.real(Type.double(), self.value)
# Expression class for referencing a variable, like "a". # Expression class for referencing a variable, like "a".
class VariableExpressionNode(ExpressionNode): class VariableExpressionNode(ExpressionNode):
@ -978,7 +984,9 @@ Abstract Syntax Tree (aka Parse Tree)
self.then_branch = then_branch self.then_branch = then_branch
self.else_branch = else_branch self.else_branch = else_branch
def CodeGen(self): condition = self.condition.CodeGen() def CodeGen(self):
condition = self.condition.CodeGen()
# Convert condition to a bool by comparing equal to 0.0. # Convert condition to a bool by comparing equal to 0.0.
condition_bool = g_llvm_builder.fcmp( condition_bool = g_llvm_builder.fcmp(
@ -1114,370 +1122,436 @@ Abstract Syntax Tree (aka Parse Tree)
# Expression class for a unary operator. # Expression class for a unary operator.
class UnaryExpressionNode(ExpressionNode): class UnaryExpressionNode(ExpressionNode):
def __init__(self, operator, operand): self.operator = operator def __init__(self, operator, operand):
self.operand = operand self.operator = operator
self.operand = operand
def CodeGen(self): operand = self.operand.CodeGen() function = def CodeGen(self):
g_llvm_module.get_function_named('unary' + self.operator) return operand = self.operand.CodeGen()
g_llvm_builder.call(function, [operand], 'unop') function = g_llvm_module.get_function_named('unary' + self.operator)
return g_llvm_builder.call(function, [operand], 'unop')
# This class represents the "prototype" for a function, which captures its name, # This class represents the "prototype" for a function, which captures its name,
# and its argument names (thus implicitly the number of arguments the function # and its argument names (thus implicitly the number of arguments the function
# takes), as well as if it is an operator. # takes), as well as if it is an operator.
class PrototypeNode(object): class PrototypeNode(object):
def __init__(self, name, args, is_operator=False, precedence=0): def __init__(self, name, args, is_operator=False, precedence=0):
self.name = name self.args = args self.is_operator = is_operator self.name = name
self.precedence = precedence self.args = args
self.is_operator = is_operator
self.precedence = precedence
def IsBinaryOp(self): return self.is_operator and len(self.args) == 2 def IsBinaryOp(self):
return self.is_operator and len(self.args) == 2
def GetOperatorName(self): assert self.is_operator return self.name[-1] def GetOperatorName(self):
assert self.is_operator
return self.name[-1]
def CodeGen(self): # Make the function type, eg. double(double,double). def CodeGen(self):
funct_type = Type.function( Type.double(), [Type.double()] * # Make the function type, eg. double(double,double).
len(self.args), False) funct_type = Type.function(
Type.double(), [Type.double()] * len(self.args), False)
:: function = Function.new(g_llvm_module, funct_type, self.name)
function = Function.new(g_llvm_module, funct_type, self.name) # If the name conflicted, there was already something with the same name.
# If it has a body, don't allow redefinition or reextern.
if function.name != self.name:
function.delete()
function = g_llvm_module.get_function_named(self.name)
# If the name conflicted, there was already something with the same name. # If the function already has a body, reject this.
# If it has a body, don't allow redefinition or reextern. if not function.is_declaration:
if function.name != self.name: raise RuntimeError('Redefinition of function.')
function.delete()
function = g_llvm_module.get_function_named(self.name)
# If the function already has a body, reject this. # If the function took a different number of args, reject.
if not function.is_declaration: if len(function.args) != len(self.args):
raise RuntimeError('Redefinition of function.') raise RuntimeError('Redeclaration of a function with different number '
'of args.')
# If the function took a different number of args, reject. # Set names for all arguments and add them to the variables symbol table.
if len(function.args) != len(self.args): for arg, arg_name in zip(function.args, self.args):
raise RuntimeError('Redeclaration of a function with different number ' arg.name = arg_name
'of args.') # Add arguments to variable symbol table.
g_named_values[arg_name] = arg
# Set names for all arguments and add them to the variables symbol table. return function
for arg, arg_name in zip(function.args, self.args):
arg.name = arg_name
# Add arguments to variable symbol table.
g_named_values[arg_name] = arg
return function
# This class represents a function definition itself. # This class represents a function definition itself.
class FunctionNode(object): class FunctionNode(object):
def __init__(self, prototype, body): self.prototype = prototype def __init__(self, prototype, body):
self.body = body self.prototype = prototype
self.body = body
def CodeGen(self): # Clear scope. g_named_values.clear() def CodeGen(self):
# Clear scope.
g_named_values.clear()
:: # Create a function object.
function = self.prototype.CodeGen()
# Create a function object. # If this is a binary operator, install its precedence.
function = self.prototype.CodeGen() if self.prototype.IsBinaryOp():
operator = self.prototype.GetOperatorName()
g_binop_precedence[operator] = self.prototype.precedence
# If this is a binary operator, install its precedence. # Create a new basic block to start insertion into.
if self.prototype.IsBinaryOp(): block = function.append_basic_block('entry')
operator = self.prototype.GetOperatorName() global g_llvm_builder
g_binop_precedence[operator] = self.prototype.precedence g_llvm_builder = Builder.new(block)
# Create a new basic block to start insertion into. # Finish off the function.
block = function.append_basic_block('entry') try:
global g_llvm_builder return_value = self.body.CodeGen()
g_llvm_builder = Builder.new(block) g_llvm_builder.ret(return_value)
# Finish off the function. # Validate the generated code, checking for consistency.
try: function.verify()
return_value = self.body.CodeGen()
g_llvm_builder.ret(return_value)
# Validate the generated code, checking for consistency. # Optimize the function.
function.verify() g_llvm_pass_manager.run(function)
except:
function.delete()
if self.prototype.IsBinaryOp():
del g_binop_precedence[self.prototype.GetOperatorName()]
raise
# Optimize the function. return function
g_llvm_pass_manager.run(function)
except:
function.delete()
if self.prototype.IsBinaryOp():
del g_binop_precedence[self.prototype.GetOperatorName()]
raise
return function Parser
------
Parser .. code-block:: python
------
class Parser(object): class Parser(object):
def __init__(self, tokens): self.tokens = tokens self.Next() def __init__(self, tokens):
self.tokens = tokens
self.Next()
# Provide a simple token buffer. Parser.current is the current token the # Provide a simple token buffer. Parser.current is the current token the
# parser is looking at. Parser.Next() reads another token from the lexer # parser is looking at. Parser.Next() reads another token from the lexer and
and # updates Parser.current with its results. def Next(self): # updates Parser.current with its results.
self.current = self.tokens.next() def Next(self):
self.current = self.tokens.next()
# Gets the precedence of the current token, or -1 if the token is not a # Gets the precedence of the current token, or -1 if the token is not a binary
binary # operator. def GetCurrentTokenPrecedence(self): if # operator.
isinstance(self.current, CharacterToken): return def GetCurrentTokenPrecedence(self):
g_binop_precedence.get(self.current.char, -1) else: return -1 if isinstance(self.current, CharacterToken):
return g_binop_precedence.get(self.current.char, -1)
else:
return -1
# identifierexpr ::= identifier | identifier '(' expression* ')' def # identifierexpr ::= identifier | identifier '(' expression* ')'
ParseIdentifierExpr(self): identifier_name = self.current.name def ParseIdentifierExpr(self):
self.Next() # eat identifier. identifier_name = self.current.name
self.Next() # eat identifier.
:: if self.current != CharacterToken('('): # Simple variable reference.
return VariableExpressionNode(identifier_name)
if self.current != CharacterToken('('): # Simple variable reference.
return VariableExpressionNode(identifier_name) # Call.
self.Next() # eat '('.
# Call. args = []
self.Next() # eat '('. if self.current != CharacterToken(')'):
args = [] while True:
if self.current != CharacterToken(')'): args.append(self.ParseExpression())
while True: if self.current == CharacterToken(')'):
args.append(self.ParseExpression()) break
if self.current == CharacterToken(')'): elif self.current != CharacterToken(','):
break raise RuntimeError('Expected ")" or "," in argument list.')
elif self.current != CharacterToken(','): self.Next()
raise RuntimeError('Expected ")" or "," in argument list.')
self.Next() self.Next() # eat ')'.
return CallExpressionNode(identifier_name, args)
self.Next() # eat ')'.
return CallExpressionNode(identifier_name, args) # numberexpr ::= number
def ParseNumberExpr(self):
# numberexpr ::= number def ParseNumberExpr(self): result = result = NumberExpressionNode(self.current.value)
NumberExpressionNode(self.current.value) self.Next() # consume the self.Next() # consume the number.
number. return result return result
# parenexpr ::= '(' expression ')' def ParseParenExpr(self): self.Next() # parenexpr ::= '(' expression ')'
# eat '('. def ParseParenExpr(self):
self.Next() # eat '('.
::
contents = self.ParseExpression()
contents = self.ParseExpression()
if self.current != CharacterToken(')'):
if self.current != CharacterToken(')'): raise RuntimeError('Expected ")".')
raise RuntimeError('Expected ")".') self.Next() # eat ')'.
self.Next() # eat ')'.
return contents
return contents
# ifexpr ::= 'if' expression 'then' expression 'else' expression
# ifexpr ::= 'if' expression 'then' expression 'else' expression def def ParseIfExpr(self):
ParseIfExpr(self): self.Next() # eat the if. self.Next() # eat the if.
:: # condition.
condition = self.ParseExpression()
# condition.
condition = self.ParseExpression() if not isinstance(self.current, ThenToken):
raise RuntimeError('Expected "then".')
if not isinstance(self.current, ThenToken): self.Next() # eat the then.
raise RuntimeError('Expected "then".')
self.Next() # eat the then. then_branch = self.ParseExpression()
then_branch = self.ParseExpression() if not isinstance(self.current, ElseToken):
raise RuntimeError('Expected "else".')
if not isinstance(self.current, ElseToken): self.Next() # eat the else.
raise RuntimeError('Expected "else".')
self.Next() # eat the else. else_branch = self.ParseExpression()
else_branch = self.ParseExpression() return IfExpressionNode(condition, then_branch, else_branch)
return IfExpressionNode(condition, then_branch, else_branch) # forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
def ParseForExpr(self):
# forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' self.Next() # eat the for.
expression def ParseForExpr(self): self.Next() # eat the for.
if not isinstance(self.current, IdentifierToken):
:: raise RuntimeError('Expected identifier after for.')
if not isinstance(self.current, IdentifierToken): loop_variable = self.current.name
raise RuntimeError('Expected identifier after for.') self.Next() # eat the identifier.
loop_variable = self.current.name if self.current != CharacterToken('='):
self.Next() # eat the identifier. raise RuntimeError('Expected "=" after for variable.')
self.Next() # eat the '='.
if self.current != CharacterToken('='):
raise RuntimeError('Expected "=" after for variable.') start = self.ParseExpression()
self.Next() # eat the '='.
if self.current != CharacterToken(','):
start = self.ParseExpression() raise RuntimeError('Expected "," after for start value.')
self.Next() # eat the ','.
if self.current != CharacterToken(','):
raise RuntimeError('Expected "," after for start value.') end = self.ParseExpression()
self.Next() # eat the ','.
# The step value is optional.
end = self.ParseExpression() if self.current == CharacterToken(','):
self.Next() # eat the ','.
# The step value is optional. step = self.ParseExpression()
if self.current == CharacterToken(','): else:
self.Next() # eat the ','. step = None
step = self.ParseExpression()
else: if not isinstance(self.current, InToken):
step = None raise RuntimeError('Expected "in" after for variable specification.')
self.Next() # eat 'in'.
if not isinstance(self.current, InToken):
raise RuntimeError('Expected "in" after for variable specification.') body = self.ParseExpression()
self.Next() # eat 'in'.
return ForExpressionNode(loop_variable, start, end, step, body)
body = self.ParseExpression()
# primary ::= identifierexpr | numberexpr | parenexpr | ifexpr | forexpr
return ForExpressionNode(loop_variable, start, end, step, body) def ParsePrimary(self):
if isinstance(self.current, IdentifierToken):
# primary ::= identifierexpr | numberexpr | parenexpr | ifexpr | return self.ParseIdentifierExpr()
forexpr def ParsePrimary(self): if isinstance(self.current, elif isinstance(self.current, NumberToken):
IdentifierToken): return self.ParseIdentifierExpr() elif return self.ParseNumberExpr()
isinstance(self.current, NumberToken): return self.ParseNumberExpr() elif isinstance(self.current, IfToken):
elif isinstance(self.current, IfToken): return self.ParseIfExpr() elif return self.ParseIfExpr()
isinstance(self.current, ForToken): return self.ParseForExpr() elif elif isinstance(self.current, ForToken):
self.current == CharacterToken('('): return self.ParseParenExpr() else: return self.ParseForExpr()
raise RuntimeError('Unknown token when expecting an expression.') elif self.current == CharacterToken('('):
return self.ParseParenExpr()
# unary ::= primary | unary_operator unary def ParseUnary(self): # If else:
the current token is not an operator, it must be a primary expression. raise RuntimeError('Unknown token when expecting an expression.')
if (not isinstance(self.current, CharacterToken) or self.current in
[CharacterToken('('), CharacterToken(',')]): return self.ParsePrimary() # unary ::= primary | unary_operator unary
def ParseUnary(self):
:: # If the current token is not an operator, it must be a primary expression.
if (not isinstance(self.current, CharacterToken) or
# If this is a unary operator, read it. self.current in [CharacterToken('('), CharacterToken(',')]):
operator = self.current.char return self.ParsePrimary()
self.Next() # eat the operator.
return UnaryExpressionNode(operator, self.ParseUnary()) # If this is a unary operator, read it.
operator = self.current.char
# binoprhs ::= (binary_operator unary)* def ParseBinOpRHS(self, left, self.Next() # eat the operator.
left_precedence): # If this is a binary operator, find its precedence. return UnaryExpressionNode(operator, self.ParseUnary())
while True: precedence = self.GetCurrentTokenPrecedence()
# binoprhs ::= (binary_operator unary)*
:: def ParseBinOpRHS(self, left, left_precedence):
# If this is a binary operator, find its precedence.
# If this is a binary operator that binds at least as tightly as the while True:
# current one, consume it; otherwise we are done. precedence = self.GetCurrentTokenPrecedence()
if precedence < left_precedence:
return left # If this is a binary operator that binds at least as tightly as the
# current one, consume it; otherwise we are done.
binary_operator = self.current.char if precedence < left_precedence:
self.Next() # eat the operator. return left
# Parse the unary expression after the binary operator. binary_operator = self.current.char
right = self.ParseUnary() self.Next() # eat the operator.
# If binary_operator binds less tightly with right than the operator after # Parse the unary expression after the binary operator.
# right, let the pending operator take right as its left. right = self.ParseUnary()
next_precedence = self.GetCurrentTokenPrecedence()
if precedence < next_precedence: # If binary_operator binds less tightly with right than the operator after
right = self.ParseBinOpRHS(right, precedence + 1) # right, let the pending operator take right as its left.
next_precedence = self.GetCurrentTokenPrecedence()
# Merge left/right. if precedence < next_precedence:
left = BinaryOperatorExpressionNode(binary_operator, left, right) right = self.ParseBinOpRHS(right, precedence + 1)
# expression ::= unary binoprhs def ParseExpression(self): left = # Merge left/right.
self.ParseUnary() return self.ParseBinOpRHS(left, 0) left = BinaryOperatorExpressionNode(binary_operator, left, right)
# prototype # ::= id '(' id* ')' # ::= binary LETTER number? (id, id) # # expression ::= unary binoprhs
::= unary LETTER (id) def ParsePrototype(self): precedence = None if def ParseExpression(self):
isinstance(self.current, IdentifierToken): kind = 'normal' left = self.ParseUnary()
function_name = self.current.name self.Next() # eat function name. elif return self.ParseBinOpRHS(left, 0)
isinstance(self.current, UnaryToken): kind = 'unary' self.Next() # eat
'unary'. if not isinstance(self.current, CharacterToken): raise # prototype # ::= id '(' id* ')'
RuntimeError('Expected an operator after "unary".') function_name = # ::= binary LETTER number? (id, id)
'unary' + self.current.char self.Next() # eat the operator. elif # ::= unary LETTER (id)
isinstance(self.current, BinaryToken): kind = 'binary' self.Next() # eat def ParsePrototype(self):
'binary'. if not isinstance(self.current, CharacterToken): raise precedence = None
RuntimeError('Expected an operator after "binary".') function_name = if isinstance(self.current, IdentifierToken):
'binary' + self.current.char self.Next() # eat the operator. if kind = 'normal'
isinstance(self.current, NumberToken): if not 1 <= self.current.value <= function_name = self.current.name
100: raise RuntimeError('Invalid precedence: must be in range [1, self.Next() # eat function name.
100].') precedence = self.current.value self.Next() # eat the elif isinstance(self.current, UnaryToken):
precedence. else: raise RuntimeError('Expected function name, "unary" or kind = 'unary'
"binary" in ' 'prototype.') self.Next() # eat 'unary'.
if not isinstance(self.current, CharacterToken):
:: raise RuntimeError('Expected an operator after "unary".')
function_name = 'unary' + self.current.char
if self.current != CharacterToken('('): self.Next() # eat the operator.
raise RuntimeError('Expected "(" in prototype.') elif isinstance(self.current, BinaryToken):
self.Next() # eat '('. kind = 'binary'
self.Next() # eat 'binary'.
arg_names = [] if not isinstance(self.current, CharacterToken):
while isinstance(self.current, IdentifierToken): raise RuntimeError('Expected an operator after "binary".')
arg_names.append(self.current.name) function_name = 'binary' + self.current.char
self.Next() self.Next() # eat the operator.
if isinstance(self.current, NumberToken):
if self.current != CharacterToken(')'): if not 1 <= self.current.value <= 100:
raise RuntimeError('Expected ")" in prototype.') raise RuntimeError('Invalid precedence: must be in range [1, 100].')
precedence = self.current.value
# Success. self.Next() # eat the precedence.
self.Next() # eat ')'. else:
raise RuntimeError('Expected function name, "unary" or "binary" in '
if kind == 'unary' and len(arg_names) != 1: 'prototype.')
raise RuntimeError('Invalid number of arguments for a unary operator.')
elif kind == 'binary' and len(arg_names) != 2: if self.current != CharacterToken('('):
raise RuntimeError('Invalid number of arguments for a binary operator.') raise RuntimeError('Expected "(" in prototype.')
self.Next() # eat '('.
return PrototypeNode(function_name, arg_names, kind != 'normal', precedence)
arg_names = []
# definition ::= 'def' prototype expression def ParseDefinition(self): while isinstance(self.current, IdentifierToken):
self.Next() # eat def. proto = self.ParsePrototype() body = arg_names.append(self.current.name)
self.ParseExpression() return FunctionNode(proto, body) self.Next()
# toplevelexpr ::= expression def ParseTopLevelExpr(self): proto = if self.current != CharacterToken(')'):
PrototypeNode('', []) return FunctionNode(proto, self.ParseExpression()) raise RuntimeError('Expected ")" in prototype.')
# external ::= 'extern' prototype def ParseExtern(self): self.Next() # # Success.
eat extern. return self.ParsePrototype() self.Next() # eat ')'.
# Top-Level parsing def HandleDefinition(self): if kind == 'unary' and len(arg_names) != 1:
self.Handle(self.ParseDefinition, 'Read a function definition:') raise RuntimeError('Invalid number of arguments for a unary operator.')
elif kind == 'binary' and len(arg_names) != 2:
def HandleExtern(self): self.Handle(self.ParseExtern, 'Read an extern:') raise RuntimeError('Invalid number of arguments for a binary operator.')
def HandleTopLevelExpression(self): try: function = return PrototypeNode(function_name, arg_names, kind != 'normal', precedence)
self.ParseTopLevelExpr().CodeGen() result =
g_llvm_executor.run_function(function, []) print 'Evaluated to:', # definition ::= 'def' prototype expression
result.as_real(Type.double()) except Exception, e: print 'Error:', e def ParseDefinition(self):
try: self.Next() # Skip for error recovery. except: pass self.Next() # eat def.
proto = self.ParsePrototype()
def Handle(self, function, message): try: print message, body = self.ParseExpression()
function().CodeGen() except Exception, e: print 'Error:', e try: return FunctionNode(proto, body)
self.Next() # Skip for error recovery. except: pass
# toplevelexpr ::= expression
Main driver code. def ParseTopLevelExpr(self):
----------------- proto = PrototypeNode('', [])
return FunctionNode(proto, self.ParseExpression())
def main(): # Set up the optimizer pipeline. Start with registering info
about how the # target lays out data structures. # external ::= 'extern' prototype
g_llvm_pass_manager.add(g_llvm_executor.target_data) # Do simple def ParseExtern(self):
"peephole" optimizations and bit-twiddling optzns. self.Next() # eat extern.
g_llvm_pass_manager.add(PASS_INSTRUCTION_COMBINING) # Reassociate return self.ParsePrototype()
expressions. g_llvm_pass_manager.add(PASS_REASSOCIATE) # Eliminate
Common SubExpressions. g_llvm_pass_manager.add(PASS_GVN) # Simplify # Top-Level parsing
the control flow graph (deleting unreachable blocks, etc). def HandleDefinition(self):
g_llvm_pass_manager.add(PASS_CFG_SIMPLIFICATION) self.Handle(self.ParseDefinition, 'Read a function definition:')
g_llvm_pass_manager.initialize() def HandleExtern(self):
self.Handle(self.ParseExtern, 'Read an extern:')
# Install standard binary operators. # 1 is lowest possible precedence.
40 is the highest. g_binop_precedence['<'] = 10 def HandleTopLevelExpression(self):
g_binop_precedence['+'] = 20 g_binop_precedence['-'] = 20 try:
g_binop_precedence['*'] = 40 function = self.ParseTopLevelExpr().CodeGen()
result = g_llvm_executor.run_function(function, [])
# Run the main "interpreter loop". while True: print 'ready>', try: raw print 'Evaluated to:', result.as_real(Type.double())
= raw_input() except KeyboardInterrupt: break except Exception, e:
print 'Error:', e
:: try:
self.Next() # Skip for error recovery.
parser = Parser(Tokenize(raw)) except:
while True: pass
# top ::= definition | external | expression | EOF
if isinstance(parser.current, EOFToken): def Handle(self, function, message):
break try:
if isinstance(parser.current, DefToken): print message, function().CodeGen()
parser.HandleDefinition() except Exception, e:
elif isinstance(parser.current, ExternToken): print 'Error:', e
parser.HandleExtern() try:
else: self.Next() # Skip for error recovery.
parser.HandleTopLevelExpression() except:
pass
# Print out all of the generated code. print '', g_llvm_module
Main driver code.
if **name** == '__main__': main() -----------------
.. code-block:: python
def main():
# Set up the optimizer pipeline. Start with registering info about how the
# target lays out data structures.
g_llvm_pass_manager.add(g_llvm_executor.target_data)
# Do simple "peephole" optimizations and bit-twiddling optzns.
g_llvm_pass_manager.add(PASS_INSTRUCTION_COMBINING)
# Reassociate expressions.
g_llvm_pass_manager.add(PASS_REASSOCIATE)
# Eliminate Common SubExpressions.
g_llvm_pass_manager.add(PASS_GVN)
# Simplify the control flow graph (deleting unreachable blocks, etc).
g_llvm_pass_manager.add(PASS_CFG_SIMPLIFICATION)
g_llvm_pass_manager.initialize()
# Install standard binary operators.
# 1 is lowest possible precedence. 40 is the highest.
g_binop_precedence['<'] = 10
g_binop_precedence['+'] = 20
g_binop_precedence['-'] = 20
g_binop_precedence['*'] = 40
# Run the main "interpreter loop".
while True:
print 'ready>',
try:
raw = raw_input()
except KeyboardInterrupt:
break
parser = Parser(Tokenize(raw))
while True:
# top ::= definition | external | expression | EOF
if isinstance(parser.current, EOFToken):
break
if isinstance(parser.current, DefToken):
parser.HandleDefinition()
elif isinstance(parser.current, ExternToken):
parser.HandleExtern()
else:
parser.HandleTopLevelExpression()
# Print out all of the generated code.
print '', g_llvm_module
if __name__ == '__main__':
main()