1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#######################################################################
# Name: robot_peg.py
# Purpose: Simple DSL for defining robot movement (PEG version).
# Author: Igor R. Dejanovic <igor DOT dejanovic AT gmail DOT com>
# Copyright: (c) 2011 Igor R. Dejanovic <igor DOT dejanovic AT gmail DOT com>
# License: MIT License
#
# This example is inspired by an example from LISA tool (http://labraj.uni-mb.si/lisa/)
# presented during the lecture given by prof. Marjan Mernik (http://lpm.uni-mb.si/mernik/)
# at the University of Novi Sad in June, 2011.
#
# An example of the robot program:
# begin
# up
# up
# left
# down
# right
# end
#######################################################################
from __future__ import print_function
from arpeggio import *
from arpeggio.peg import ParserPEG
# Grammar rules
robot_grammar = '''
robot <- 'begin' (command)* 'end' EOF;
command <- UP/DOWN/LEFT/RIGHT;
UP <- 'up';
DOWN <- 'down';
LEFT <- 'left';
RIGHT <- 'right';
'''
# Semantic actions
from robot import Up, Down, Left, Right, Command, Robot
semantic_actions = {
'robot': Robot(),
'command': Command(),
'UP': Up(),
'DOWN': Down(),
'LEFT': Left(),
'RIGHT': Right()
}
def main(debug=False):
# Program code
input = '''
begin
up
up
left
down
right
end
'''
# First we will make a parser - an instance of the robot parser model.
# Parser model is given in the form of PEG specification therefore we
# are using ParserPEG class.
parser = ParserPEG(robot_grammar, 'robot', debug=debug)
# We create a parse tree out of textual input
parse_tree = parser.parse(input)
# getASG will start semantic analysis.
# In this case semantic analysis will evaluate expression and
# returned value will be the final position of the robot.
return parser.getASG(sem_actions=semantic_actions)
if __name__ == "__main__":
# In debug mode dot (graphviz) files for parser model
# and parse tree will be created for visualization.
# Checkout current folder for .dot files.
print("position = ", main(debug=True))