blob: ff27c896686a2b0c4bf352e79868d6180f3f7ff2 [file] [log] [blame]
Brian Silverman70325d62015-09-20 17:00:43 -04001#!/usr/bin/env python
2#
3# Copyright (c) 2008, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10# * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12# * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16# * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31# ---
32#
33# Create a state machine object based on a definition file.
34#
35
36__author__ = 'falmeida@google.com (Filipe Almeida)'
37
38class OrderedDict:
39 """Ordered dictionary implementation."""
40
41 # Define the minimum functionality we need for our application.
42 # Easiser would be to subclass from UserDict.DictMixin, and only
43 # define __getitem__, __setitem__, __delitem__, and keys, but that's
44 # not as portable. We don't need to define much more, so we just do.
45
46 def __init__(self):
47 self._dict = {}
48 self._keys = []
49
50 def __getitem__(self, key):
51 return self._dict[key]
52
53 def __setitem__(self, key, value):
54 if key not in self._keys:
55 self._keys.append(key)
56 self._dict[key] = value
57
58 def __delitem__(self, key):
59 self._keys.remove(key)
60 del self._dict[key]
61
62 def keys(self):
63 return self._keys
64
65 # Below are all we have to define in addition to what DictMixin would need
66 def __len__(self):
67 return len(self.keys())
68
69 def __contains__(self, key):
70 return self.has_key(key)
71
72 def __iter__(self):
73 # It's not as portable -- though it would be more space-efficient -- to do
74 # for k in self.keys(): yield k
75 return iter(self.keys())
76
77class State(object):
78 """Contains information about a specific state."""
79
80 def __init__(self):
81 pass
82
83 name = None
84 external_name = None
85 transitions = []
86
87
88class Transition(object):
89 """Contains information about a specific transition."""
90
91 def __init__(self, condition, source, destination):
92 self.condition = condition
93 self.source = source
94 self.destination = destination
95
96
97class FSMConfig(object):
98 """Container for the statemachine definition."""
99
100 sm = {} # dictionary that contains the finite state machine definition
101 # loaded from a config file.
102 transitions = [] # List of transitions.
103 conditions = {} # Mapping between the condition name and the bracket
104 # expression.
105 states = OrderedDict() # Ordered dictionary of states.
106 name = None
107 comment = None
108
109 def AddState(self, **dic):
110 """Called from the definition file with the description of the state.
111
112 Receives a dictionary and populates internal structures based on it. The
113 dictionary is in the following format:
114
115 {'name': state_name,
116 'external': exposed state name,
117 'transitions': [
118 [condition, destination_state ],
119 [condition, destination_state ]
120 ]
121 }
122
123 """
124
125 state = State()
126 state.name = dic['name']
127 state.external_name = dic['external']
128
129 state_transitions = []
130
131 for (condition, destination) in dic['transitions']:
132 transition = Transition(condition, state.name, destination)
133 state_transitions.append(transition)
134
135 self.transitions.extend(state_transitions)
136 state.transitions = state_transitions
137 self.states[state.name] = state
138
139 def AddCondition(self, name, expression):
140 """Called from the definition file with the definition of a condition.
141
142 Receives the name of the condition and it's expression.
143 """
144 self.conditions[name] = expression
145
146 def Load(self, filename):
147 """Load the state machine definition file.
148
149 In the definition file, which is based on the python syntax, the following
150 variables and functions are defined.
151
152 name: Name of the state machine
153 comment: Comment line on the generated file.
154 condition(): A mapping between condition names and bracket expressions.
155 state(): Defines a state and it's transitions. It accepts the following
156 attributes:
157 name: name of the state
158 external: exported name of the state. The exported name can be used
159 multiple times in order to create a super state.
160 transitions: List of pairs containing the condition for the transition
161 and the destination state. Transitions are ordered so if
162 a default rule is used, it must be the last one in the list.
163
164 Example:
165
166 name = 'c comment parser'
167
168 condition('/', '/')
169 condition('*', '*')
170 condition('linefeed', '\\n')
171 condition('default', '[:default:]')
172
173 state(name = 'text',
174 external = 'comment',
175 transitions = [
176 [ '/', 'comment_start' ],
177 [ 'default', 'text' ]
178 ])
179
180 state(name = 'comment_start',
181 external = 'comment',
182 transitions = [
183 [ '/', 'comment_line' ],
184 [ '*', 'comment_multiline' ],
185 [ 'default', 'text' ]
186 ])
187
188 state(name = 'comment_line',
189 external = 'comment',
190 transitions = [
191 [ 'linefeed', 'text' ],
192 [ 'default', 'comment_line' ]
193 ])
194
195 state(name = 'comment_multiline',
196 external = 'comment',
197 transitions = [
198 [ '*', 'comment_multiline_close' ],
199 [ 'default', 'comment_multiline' ]
200 ])
201
202 state(name = 'comment_multiline_close',
203 external = 'comment',
204 transitions = [
205 [ '/', 'text' ],
206 [ 'default', 'comment_multiline' ]
207 ])
208
209 """
210
211 self.sm['state'] = self.AddState
212 self.sm['condition'] = self.AddCondition
213 execfile(filename, self.sm)
214 self.name = self.sm['name']
215 if not self.name.isalnum():
216 raise Exception("State machine name must consist of only alphanumeric"
217 "characters.")
218 self.comment = self.sm['comment']
219
220 def __init__(self):
221 pass