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

Examples update

parent a3f51c06
......@@ -18,7 +18,7 @@ from arpeggio import RegExMatch as _
# 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 bibentry(): return bibtype, "{", bibkey, ",", field, ZeroOrMore(",", field), "}"
def field(): return fieldname, "=", fieldvalue
......@@ -38,6 +38,7 @@ def fieldvalue_braced_content(): return Combine(ZeroOrMore(Optional(And("{"),
def fieldvalue_part(): return _(r'((\\")|[^{}])+')
def fieldvalue_inner(): return "{", fieldvalue_braced_content, "}"
# Semantic actions
class BibFileSem(SemanticAction):
"""
......@@ -122,11 +123,11 @@ if __name__ == "__main__":
with open(sys.argv[1], "r") as bibtexfile:
bibtexfile_content = bibtexfile.read()
# We create a parse tree or abstract syntax tree out of textual input
# We create a parse tree or abstract syntax tree out of
# textual input
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")
# getASG will start semantic analysis.
......@@ -138,4 +139,3 @@ if __name__ == "__main__":
else:
print("Usage: python bibtex.py file_to_parse")
......@@ -10,7 +10,8 @@
# 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 import RegExMatch as _
......@@ -19,7 +20,7 @@ def factor(): return Optional(["+","-"]), [number,
("(", expression, ")")]
def term(): return factor, ZeroOrMore(["*","/"], factor)
def expression(): return term, ZeroOrMore(["+", "-"], term)
def calc(): return OneOrMore(expression), EndOfFile
def calc(): return OneOrMore(expression), EOF
# Semantic actions
......@@ -31,6 +32,7 @@ class ToFloat(SemanticAction):
print("Converting {}.".format(node.value))
return float(node.value)
class Factor(SemanticAction):
"""
Removes parenthesis if exists and returns what was contained inside.
......@@ -43,10 +45,8 @@ class Factor(SemanticAction):
next_chd = 0
if children[0] in ['+', '-']:
next_chd = 1
if children[next_chd] == '(':
return sign * children[next_chd+1]
else:
return sign * children[next_chd]
return sign * children[next_chd]
class Term(SemanticAction):
"""
......@@ -57,13 +57,14 @@ class Term(SemanticAction):
print("Term {}".format(children))
term = children[0]
for i in range(2, len(children), 2):
if children[i-1]=="*":
if children[i-1] == "*":
term *= children[i]
else:
term /= children[i]
print("Term = {}".format(term))
return term
class Expr(SemanticAction):
"""
Adds or substracts terms.
......@@ -78,7 +79,7 @@ class Expr(SemanticAction):
start = 1
for i in range(start, len(children), 2):
if i and children[i-1]=="-":
if i and children[i - 1] == "-":
expr -= children[i]
else:
expr += children[i]
......@@ -86,16 +87,12 @@ class Expr(SemanticAction):
print("Expression = {}".format(expr))
return expr
class Calc(SemanticAction):
def first_pass(self, parser, node, children):
return children[0]
# Connecting rules with semantic actions
number.sem = ToFloat()
factor.sem = Factor()
term.sem = Term()
expression.sem = Expr()
calc.sem = Calc()
if __name__ == "__main__":
......@@ -108,7 +105,8 @@ if __name__ == "__main__":
# 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
# 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
input_expr = "-(4-1)*5+(2+4.67)+5.89/(.2+7)"
......@@ -124,4 +122,3 @@ if __name__ == "__main__":
# In this case semantic analysis will evaluate expression and
# returned value will be the result of the input_expr expression.
print("{} = {}".format(input_expr, parser.getASG()))
......@@ -18,7 +18,7 @@ from arpeggio.peg import ParserPEG
from arpeggio.export import PMDOTExporter, PTDOTExporter
# 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.
calc_grammar = """
......@@ -36,7 +36,6 @@ sem_actions = {
"factor" : Factor(),
"term" : Term(),
"expression" : Expr(),
"calc" : Calc()
}
......
......@@ -14,7 +14,7 @@ def field(): return [quoted_field, field_content]
def quoted_field(): return '"', field_content_quoted, '"'
def field_content(): return _(r'([^,\n])+')
def field_content_quoted(): return _(r'(("")|([^"]))+')
def csvfile(): return OneOrMore([record, '\n']), EndOfFile
def csvfile(): return OneOrMore([record, '\n']), EOF
if __name__ == "__main__":
......
......@@ -92,5 +92,3 @@ if __name__ == "__main__":
# Export parse tree for visualization
PTDOTExporter().exportFile(parser.parse_tree, "json_parse_tree.dot")
......@@ -24,7 +24,7 @@ from arpeggio import *
from arpeggio.export import PMDOTExporter, PTDOTExporter
# 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 up(): return 'up'
def down(): return 'down'
......@@ -38,21 +38,25 @@ class Up(SemanticAction):
print("Going up")
return (0, 1)
class Down(SemanticAction):
def first_pass(self, parser, node, children):
print("Going down")
return (0, -1)
class Left(SemanticAction):
def first_pass(self, parser, node, children):
print("Going left")
return (-1, 0)
class Right(SemanticAction):
def first_pass(self, parser, node, children):
print("Going right")
return (1, 0)
class Command(SemanticAction):
def first_pass(self, parser, node, children):
print("Command")
......@@ -79,7 +83,7 @@ right.sem = Right()
if __name__ == "__main__":
# Program code
input = '''
input_program = '''
begin
up
up
......@@ -89,7 +93,6 @@ if __name__ == "__main__":
end
'''
# 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
# are using ParserPython class.
......@@ -103,7 +106,7 @@ if __name__ == "__main__":
"robot_parser_model.dot")
# 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.
# dot -O -Tpng robot_parse_tree.dot
......@@ -114,4 +117,3 @@ if __name__ == "__main__":
# In this case semantic analysis will evaluate expression and
# returned value will be the final position of the robot.
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