Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(329)

Side by Side Diff: tools/lexer_generator/action.py

Issue 137883006: Experimental parser: use Terms instead of tuples (Closed) Base URL: https://v8.googlecode.com/svn/branches/experimental/parser
Patch Set: Created 6 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « no previous file | tools/lexer_generator/automaton.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 # Copyright 2014 the V8 project authors. All rights reserved.
2 # Redistribution and use in source and binary forms, with or without
3 # modification, are permitted provided that the following conditions are
4 # met:
5 #
6 # * Redistributions of source code must retain the above copyright
7 # notice, this list of conditions and the following disclaimer.
8 # * Redistributions in binary form must reproduce the above
9 # copyright notice, this list of conditions and the following
10 # disclaimer in the documentation and/or other materials provided
11 # with the distribution.
12 # * Neither the name of Google Inc. nor the names of its
13 # contributors may be used to endorse or promote products derived
14 # from this software without specific prior written permission.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 from types import StringType, IntType
29
30 class Term(object):
31 '''A class representing a function and its arguments.
32 f(a,b,c) would be represented as ('f', a, b, c) where
33 a, b, and c are strings or Terms.'''
34
35 __empty_term = None
36
37 @staticmethod
38 def empty_term():
39 if Term.__empty_term == None:
40 Term.__empty_term = Term('')
41 return Term.__empty_term
42
43 def __init__(self, name, *args):
44 assert type(name) == StringType
45 if not name:
46 assert not args, 'empty term must not have args'
47 for v in args:
48 if type(v) == StringType:
49 assert v, 'string args must be non empty'
50 else:
51 assert isinstance(v, Term)
52 self.__tuple = tuple([name] + list(args))
53 self.__str = None
54
55 def name(self):
56 return self.__tuple[0]
57
58 def args(self):
59 return self.__tuple[1:]
60
61 def __hash__(self):
62 return hash(self.__tuple)
63
64 def __nonzero__(self):
65 return bool(self.__tuple[0])
66
67 def __eq__(self, other):
68 return (isinstance(other, self.__class__) and self.__tuple == other.__tuple)
69
70 # TODO(dcarney): escape '(', ')' and ',' in strings
71 def __str__(self):
72 if self.__str == None:
73 self.__str = '(%s)' % ','.join(map(str, self.__tuple))
74 return self.__str
75
76 def to_dot(self):
77 node_ix = [0]
78 node_template = 'node [label="%s"]; N_%d;'
79 edge_template = 'N_%d -> N_%d'
80 nodes = []
81 edges = []
82
83 def escape(v):
84 v = str(v)
85 v = v.replace('\r', '\\\\r').replace('\t', '\\\\t').replace('\n', '\\\\n')
86 v = v.replace('\\', '\\\\').replace('\"', '\\\"')
87 return v
88
89 def process(term):
90 if isinstance(term, str):
91 node_ix[0] += 1
92 nodes.append(node_template % (escape(term), node_ix[0]))
93 return node_ix[0]
94 elif isinstance(term, Term):
95 child_ixs = map(process, term.args())
96 node_ix[0] += 1
97 nodes.append(node_template % (escape(term.name()), node_ix[0]))
98 for child_ix in child_ixs:
99 edges.append(edge_template % (node_ix[0], child_ix))
100 return node_ix[0]
101 raise Exception
102
103 process(self)
104 return 'digraph { %s %s }' % ('\n'.join(nodes), '\n'.join(edges))
105
106 class Action(object):
107
108 __empty_action = None
109
110 @staticmethod
111 def empty_action():
112 if Action.__empty_action == None:
113 Action.__empty_action = Action(Term.empty_term(), Term.empty_term())
114 return Action.__empty_action
115
116 @staticmethod
117 def dominant_action(state_set):
118 action = Action.empty_action()
119 for state in state_set:
120 if not state.action():
121 continue
122 if not action:
123 action = state.action()
124 continue
125 if state.action().precedence() == action.precedence():
126 assert state.action() == action
127 elif state.action().precedence() < action.precedence():
128 action = state.action()
129 return action
130
131 def __init__(self, entry_action, match_action, precedence = -1):
132 assert isinstance(match_action, Term)
133 assert isinstance(entry_action, Term)
134 assert type(precedence) == IntType
135 self.__entry_action = entry_action
136 self.__match_action = match_action
137 self.__precedence = precedence
138
139 def entry_action(self):
140 return self.__entry_action
141
142 def match_action(self):
143 return self.__match_action
144
145 def precedence(self):
146 return self.__precedence
147
148 def to_term(self):
149 return Term(
150 'action_serialization',
151 self.__entry_action, self.__match_action, str(self.__precedence))
152
153 @staticmethod
154 def from_term(term):
155 assert term.name() == 'action_serialization'
156 return Action(term.args()[0], term.args()[1], int(term.args()[2]))
157
158 def __nonzero__(self):
159 return bool(self.__entry_action) or bool(self.__match_action)
160
161 def __hash__(self):
162 return hash((self.__entry_action, self.__match_action))
163
164 def __eq__(self, other):
165 return (isinstance(other, self.__class__) and
166 self.__entry_action == other.__entry_action and
167 self.__match_action == other.__match_action)
168
169 def __str__(self):
170 parts = []
171 for action in [self.__entry_action, self.__match_action]:
172 parts.append('' if not action else str(action))
173 return "action< %s >" % " | ".join(parts)
OLDNEW
« no previous file with comments | « no previous file | tools/lexer_generator/automaton.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698