Commit 89a5a196 authored by Igor Dejanovic's avatar Igor Dejanovic

Examples update

parent a3f51c06
...@@ -18,7 +18,7 @@ from arpeggio import RegExMatch as _ ...@@ -18,7 +18,7 @@ from arpeggio import RegExMatch as _
# Grammar # Grammar
def bibfile(): return ZeroOrMore([comment_entry, bibentry, comment]), EndOfFile def bibfile(): return ZeroOrMore([comment_entry, bibentry, comment]), EOF
def comment_entry(): return "@comment", "{", _(r'[^}]*'), "}" def comment_entry(): return "@comment", "{", _(r'[^}]*'), "}"
def bibentry(): return bibtype, "{", bibkey, ",", field, ZeroOrMore(",", field), "}" def bibentry(): return bibtype, "{", bibkey, ",", field, ZeroOrMore(",", field), "}"
def field(): return fieldname, "=", fieldvalue def field(): return fieldname, "=", fieldvalue
...@@ -38,6 +38,7 @@ def fieldvalue_braced_content(): return Combine(ZeroOrMore(Optional(And("{"), ...@@ -38,6 +38,7 @@ def fieldvalue_braced_content(): return Combine(ZeroOrMore(Optional(And("{"),
def fieldvalue_part(): return _(r'((\\")|[^{}])+') def fieldvalue_part(): return _(r'((\\")|[^{}])+')
def fieldvalue_inner(): return "{", fieldvalue_braced_content, "}" def fieldvalue_inner(): return "{", fieldvalue_braced_content, "}"
# Semantic actions # Semantic actions
class BibFileSem(SemanticAction): class BibFileSem(SemanticAction):
""" """
...@@ -122,11 +123,11 @@ if __name__ == "__main__": ...@@ -122,11 +123,11 @@ if __name__ == "__main__":
with open(sys.argv[1], "r") as bibtexfile: with open(sys.argv[1], "r") as bibtexfile:
bibtexfile_content = bibtexfile.read() bibtexfile_content = bibtexfile.read()
# We create a parse tree or abstract syntax tree out of
# We create a parse tree or abstract syntax tree out of textual input # textual input
parse_tree = parser.parse(bibtexfile_content) parse_tree = parser.parse(bibtexfile_content)
# Then we export it to a dot file in order to visualise it. # Then we export it to a dot file in order to visualize it.
PTDOTExporter().exportFile(parse_tree, "bib_parse_tree.dot") PTDOTExporter().exportFile(parse_tree, "bib_parse_tree.dot")
# getASG will start semantic analysis. # getASG will start semantic analysis.
...@@ -138,4 +139,3 @@ if __name__ == "__main__": ...@@ -138,4 +139,3 @@ if __name__ == "__main__":
else: else:
print("Usage: python bibtex.py file_to_parse") print("Usage: python bibtex.py file_to_parse")
...@@ -10,7 +10,8 @@ ...@@ -10,7 +10,8 @@
# notation. # notation.
####################################################################### #######################################################################
from arpeggio import Optional, ZeroOrMore, OneOrMore, EndOfFile, SemanticAction, ParserPython from arpeggio import Optional, ZeroOrMore, OneOrMore, EOF, SemanticAction,\
ParserPython
from arpeggio.export import PMDOTExporter, PTDOTExporter from arpeggio.export import PMDOTExporter, PTDOTExporter
from arpeggio import RegExMatch as _ from arpeggio import RegExMatch as _
...@@ -19,7 +20,7 @@ def factor(): return Optional(["+","-"]), [number, ...@@ -19,7 +20,7 @@ def factor(): return Optional(["+","-"]), [number,
("(", expression, ")")] ("(", expression, ")")]
def term(): return factor, ZeroOrMore(["*","/"], factor) def term(): return factor, ZeroOrMore(["*","/"], factor)
def expression(): return term, ZeroOrMore(["+", "-"], term) def expression(): return term, ZeroOrMore(["+", "-"], term)
def calc(): return OneOrMore(expression), EndOfFile def calc(): return OneOrMore(expression), EOF
# Semantic actions # Semantic actions
...@@ -31,6 +32,7 @@ class ToFloat(SemanticAction): ...@@ -31,6 +32,7 @@ class ToFloat(SemanticAction):
print("Converting {}.".format(node.value)) print("Converting {}.".format(node.value))
return float(node.value) return float(node.value)
class Factor(SemanticAction): class Factor(SemanticAction):
""" """
Removes parenthesis if exists and returns what was contained inside. Removes parenthesis if exists and returns what was contained inside.
...@@ -43,10 +45,8 @@ class Factor(SemanticAction): ...@@ -43,10 +45,8 @@ class Factor(SemanticAction):
next_chd = 0 next_chd = 0
if children[0] in ['+', '-']: if children[0] in ['+', '-']:
next_chd = 1 next_chd = 1
if children[next_chd] == '(': return sign * children[next_chd]
return sign * children[next_chd+1]
else:
return sign * children[next_chd]
class Term(SemanticAction): class Term(SemanticAction):
""" """
...@@ -57,13 +57,14 @@ class Term(SemanticAction): ...@@ -57,13 +57,14 @@ class Term(SemanticAction):
print("Term {}".format(children)) print("Term {}".format(children))
term = children[0] term = children[0]
for i in range(2, len(children), 2): for i in range(2, len(children), 2):
if children[i-1]=="*": if children[i-1] == "*":
term *= children[i] term *= children[i]
else: else:
term /= children[i] term /= children[i]
print("Term = {}".format(term)) print("Term = {}".format(term))
return term return term
class Expr(SemanticAction): class Expr(SemanticAction):
""" """
Adds or substracts terms. Adds or substracts terms.
...@@ -78,7 +79,7 @@ class Expr(SemanticAction): ...@@ -78,7 +79,7 @@ class Expr(SemanticAction):
start = 1 start = 1
for i in range(start, len(children), 2): for i in range(start, len(children), 2):
if i and children[i-1]=="-": if i and children[i - 1] == "-":
expr -= children[i] expr -= children[i]
else: else:
expr += children[i] expr += children[i]
...@@ -86,16 +87,12 @@ class Expr(SemanticAction): ...@@ -86,16 +87,12 @@ class Expr(SemanticAction):
print("Expression = {}".format(expr)) print("Expression = {}".format(expr))
return expr return expr
class Calc(SemanticAction):
def first_pass(self, parser, node, children):
return children[0]
# Connecting rules with semantic actions # Connecting rules with semantic actions
number.sem = ToFloat() number.sem = ToFloat()
factor.sem = Factor() factor.sem = Factor()
term.sem = Term() term.sem = Term()
expression.sem = Expr() expression.sem = Expr()
calc.sem = Calc()
if __name__ == "__main__": if __name__ == "__main__":
...@@ -108,7 +105,8 @@ if __name__ == "__main__": ...@@ -108,7 +105,8 @@ if __name__ == "__main__":
# This step is optional but it is handy for debugging purposes. # This step is optional but it is handy for debugging purposes.
# We can make a png out of it using dot (part of graphviz) like this # We can make a png out of it using dot (part of graphviz) like this
# dot -O -Tpng calc_parse_tree_model.dot # dot -O -Tpng calc_parse_tree_model.dot
PMDOTExporter().exportFile(parser.parser_model, "calc_parse_tree_model.dot") PMDOTExporter().exportFile(parser.parser_model,
"calc_parse_tree_model.dot")
# An expression we want to evaluate # An expression we want to evaluate
input_expr = "-(4-1)*5+(2+4.67)+5.89/(.2+7)" input_expr = "-(4-1)*5+(2+4.67)+5.89/(.2+7)"
...@@ -124,4 +122,3 @@ if __name__ == "__main__": ...@@ -124,4 +122,3 @@ if __name__ == "__main__":
# In this case semantic analysis will evaluate expression and # In this case semantic analysis will evaluate expression and
# returned value will be the result of the input_expr expression. # returned value will be the result of the input_expr expression.
print("{} = {}".format(input_expr, parser.getASG())) print("{} = {}".format(input_expr, parser.getASG()))
...@@ -18,7 +18,7 @@ from arpeggio.peg import ParserPEG ...@@ -18,7 +18,7 @@ from arpeggio.peg import ParserPEG
from arpeggio.export import PMDOTExporter, PTDOTExporter from arpeggio.export import PMDOTExporter, PTDOTExporter
# Semantic actions # Semantic actions
from calc import ToFloat, Factor, Term, Expr, Calc from calc import ToFloat, Factor, Term, Expr
# Grammar is defined using textual specification based on PEG language. # Grammar is defined using textual specification based on PEG language.
calc_grammar = """ calc_grammar = """
...@@ -36,7 +36,6 @@ sem_actions = { ...@@ -36,7 +36,6 @@ sem_actions = {
"factor" : Factor(), "factor" : Factor(),
"term" : Term(), "term" : Term(),
"expression" : Expr(), "expression" : Expr(),
"calc" : Calc()
} }
......
...@@ -14,7 +14,7 @@ def field(): return [quoted_field, field_content] ...@@ -14,7 +14,7 @@ def field(): return [quoted_field, field_content]
def quoted_field(): return '"', field_content_quoted, '"' def quoted_field(): return '"', field_content_quoted, '"'
def field_content(): return _(r'([^,\n])+') def field_content(): return _(r'([^,\n])+')
def field_content_quoted(): return _(r'(("")|([^"]))+') def field_content_quoted(): return _(r'(("")|([^"]))+')
def csvfile(): return OneOrMore([record, '\n']), EndOfFile def csvfile(): return OneOrMore([record, '\n']), EOF
if __name__ == "__main__": if __name__ == "__main__":
......
...@@ -92,5 +92,3 @@ if __name__ == "__main__": ...@@ -92,5 +92,3 @@ if __name__ == "__main__":
# Export parse tree for visualization # Export parse tree for visualization
PTDOTExporter().exportFile(parser.parse_tree, "json_parse_tree.dot") PTDOTExporter().exportFile(parser.parse_tree, "json_parse_tree.dot")
...@@ -24,7 +24,7 @@ from arpeggio import * ...@@ -24,7 +24,7 @@ from arpeggio import *
from arpeggio.export import PMDOTExporter, PTDOTExporter from arpeggio.export import PMDOTExporter, PTDOTExporter
# Grammar rules # Grammar rules
def program(): return Kwd('begin'), ZeroOrMore(command), Kwd('end'), EndOfFile def program(): return Kwd('begin'), ZeroOrMore(command), Kwd('end'), EOF
def command(): return [up, down, left, right] def command(): return [up, down, left, right]
def up(): return 'up' def up(): return 'up'
def down(): return 'down' def down(): return 'down'
...@@ -38,21 +38,25 @@ class Up(SemanticAction): ...@@ -38,21 +38,25 @@ class Up(SemanticAction):
print("Going up") print("Going up")
return (0, 1) return (0, 1)
class Down(SemanticAction): class Down(SemanticAction):
def first_pass(self, parser, node, children): def first_pass(self, parser, node, children):
print("Going down") print("Going down")
return (0, -1) return (0, -1)
class Left(SemanticAction): class Left(SemanticAction):
def first_pass(self, parser, node, children): def first_pass(self, parser, node, children):
print("Going left") print("Going left")
return (-1, 0) return (-1, 0)
class Right(SemanticAction): class Right(SemanticAction):
def first_pass(self, parser, node, children): def first_pass(self, parser, node, children):
print("Going right") print("Going right")
return (1, 0) return (1, 0)
class Command(SemanticAction): class Command(SemanticAction):
def first_pass(self, parser, node, children): def first_pass(self, parser, node, children):
print("Command") print("Command")
...@@ -79,7 +83,7 @@ right.sem = Right() ...@@ -79,7 +83,7 @@ right.sem = Right()
if __name__ == "__main__": if __name__ == "__main__":
# Program code # Program code
input = ''' input_program = '''
begin begin
up up
up up
...@@ -89,7 +93,6 @@ if __name__ == "__main__": ...@@ -89,7 +93,6 @@ if __name__ == "__main__":
end end
''' '''
# First we will make a parser - an instance of the robot parser model. # First we will make a parser - an instance of the robot parser model.
# Parser model is given in the form of python constructs therefore we # Parser model is given in the form of python constructs therefore we
# are using ParserPython class. # are using ParserPython class.
...@@ -103,7 +106,7 @@ if __name__ == "__main__": ...@@ -103,7 +106,7 @@ if __name__ == "__main__":
"robot_parser_model.dot") "robot_parser_model.dot")
# We create a parse tree out of textual input # We create a parse tree out of textual input
parse_tree = parser.parse(input) parse_tree = parser.parse(input_program)
# Then we export it to a dot file in order to visualize it. # Then we export it to a dot file in order to visualize it.
# dot -O -Tpng robot_parse_tree.dot # dot -O -Tpng robot_parse_tree.dot
...@@ -114,4 +117,3 @@ if __name__ == "__main__": ...@@ -114,4 +117,3 @@ if __name__ == "__main__":
# In this case semantic analysis will evaluate expression and # In this case semantic analysis will evaluate expression and
# returned value will be the final position of the robot. # returned value will be the final position of the robot.
print("position = ", parser.getASG()) print("position = ", parser.getASG())
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment