I've rewritten the TRAC interpreter from Recipe 577366 using a modern recursive descent style based on the Dragon book's lexer/parser model at the end of "Compliers: Principles, Techniques and Tools," Chapter 2, by Aho, Sethi, Ullman (1986).
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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 | import sys
import os
import unittest
EOF = ""
SEGMENT_GAP = "\xff"
class TracException(Exception):
pass
def list_get(list_, index, default=EOF):
try:
return list_[index]
except:
return default
class Io(object):
def __init__(self, s=""):
self.buffer = []
self.buffer += s
def pop(self, default=EOF):
try:
return self.buffer.pop(0)
except:
return default
def push(self, s):
self.buffer[0:0] += s
def delete(self, i, j):
del self.buffer[i:j]
def peek(self, count=1):
try:
chars = self.buffer[0:0 + count]
except:
chars = [EOF]
return "".join(chars)
def get_trac_string(self):
chars = []
c = self.pop()
while True:
if c == '#':
if self.peek(1) == '(' or self.peek(2) == '#(':
break
elif c in "(),":
break
else:
chars.append(c)
c = self.pop()
if c != EOF:
self.push(c)
s = "".join(chars)
return s
def get_trac_protected_string(self):
chars = []
paren_count = 0
matched = False
c = self.pop()
while c != EOF and not matched:
if c == '(':
paren_count += 1
elif c == ')':
paren_count -= 1
chars.append(c)
if paren_count != 0:
c = self.pop()
else:
matched = True
if not matched:
raise TracException, "%s: can't find matching end parenthesis" %("get_trac_protected_string")
s = "".join(chars[1:-1])
return s
class Tag(object):
CLOSE_PAREN = ')'
COMMA = ','
NONE = -1
STRING = 300
OPEN_ACTIVE_FUNC = 400
OPEN_NEUTRAL_FUNC = 500
DONE = 600
class Token(object):
def __init__(self, t, value=''):
self.tag = t
self.value = value
def __str__(self):
return "Token([%s] [%s])" % (str(self.tag), str(self.value))
class String(Token):
def __init__(self, v):
Token.__init__(self, Tag.STRING, v)
class Lexer(object):
def __init__(self):
self.lookahead = None
self.output = "" # last string printed to output by ps for unit testing
self.trace = True # flag for printing trace results of function evaluation
self.primitives = {"ds":self.ds, \
"ps":self.ps, \
"ss":self.ss, \
"cl":self.cl, \
"ad":self.ad, \
"su":self.su, \
"ml":self.ml, \
"dv":self.dv, \
"tn":self.tn, \
"tf":self.tf, \
"eq":self.eq \
}
def initialize(self, program=""):
self.forms = {}
self.io = Io(program)
def tn(self, args):
self.trace = True
return ""
def tf(self, args):
self.trace = False
return ""
def ds(self, args):
key = list_get(args, 0)
value = list_get(args, 1)
self.forms[key] = value
return ""
def ps(self, args):
try:
s = list_get(args, 0)
print s
self.output = s
except:
pass
return ""
def ad(self, args):
try:
num1 = int(list_get(args, 0))
num2 = int(list_get(args, 1))
return str(num1 + num2)
except:
return ""
def su(self, args):
try:
num1 = int(list_get(args, 0))
num2 = int(list_get(args, 1))
return str(num1 - num2)
except:
return ""
def ml(self, args):
try:
num1 = int(list_get(args, 0))
num2 = int(list_get(args, 1))
return str(num1 * num2)
except:
return ""
def dv(self, args):
try:
num1 = int(list_get(args, 0))
num2 = int(list_get(args, 1))
return str(num1 / num2)
except:
return ""
def eq(self, args):
try:
s1 = list_get(args, 0)
s2 = list_get(args, 1)
eq_result = list_get(args, 2)
neq_result = list_get(args, 3)
if s1 == s2:
return eq_result
else:
return neq_result
except:
return ""
def ss(self, args):
try:
form_key = args.pop(0)
form = self.forms[form_key]
form_marked = form
for i in range(len(args)):
arg = args[i]
marker = "%s%s" % (SEGMENT_GAP, chr(i))
form_marked = form_marked.replace(arg, marker)
self.forms[form_key] = form_marked
form_list = []
form_list += form_marked
return ""
except:
return ""
def cl(self, args):
try:
form_key = args.pop(0)
form = self.forms[form_key]
form_processed = form
for i in range(len(args)):
arg = args[i]
marker = "%s%s" % (SEGMENT_GAP, chr(i))
form_processed = form_processed.replace(marker, arg)
return form_processed
except:
return ""
def lexan(self):
token = None
while not token:
c = self.io.pop()
if c == '\t' or c == '\n':
pass # strip out white space
elif c == '(':
self.io.push(c)
s = self.io.get_trac_protected_string()
token = String(s)
elif c == ')':
token = Token(Tag.CLOSE_PAREN)
elif c == '#' and self.io.peek(1) == '(':
self.io.delete(0,1)
token = Token(Tag.OPEN_ACTIVE_FUNC)
elif c == '#' and self.io.peek(2) == '#(':
self.io.delete(0,2)
token = Token(Tag.OPEN_NEUTRAL_FUNC)
elif c == ',':
token = Token(Tag.COMMA)
elif c == EOF:
token = Token(Tag.DONE)
else:
self.io.push(c)
s = self.io.get_trac_string()
token = String(s)
return token
def func(self, tag=""):
result = ""
args = []
token = self.lookahead
if token.tag == Tag.STRING:
args.append(token.value)
self.factor()
while True:
token = self.lookahead
if token.tag in (Tag.STRING, Tag.OPEN_ACTIVE_FUNC,
Tag.OPEN_NEUTRAL_FUNC, Tag.COMMA):
if token.tag == Tag.STRING:
args.append(token.value)
result = self.factor()
if token.tag == Tag.OPEN_NEUTRAL_FUNC:
args.append(result)
else:
if tag:
result = self.eval_func(args)
break
return result
def factor(self):
result = None
token = self.lookahead
if token.tag == Tag.OPEN_ACTIVE_FUNC:
self.match(Tag.OPEN_ACTIVE_FUNC)
result = self.func(token.tag)
self.match(Tag.CLOSE_PAREN, result)
elif token.tag == Tag.OPEN_NEUTRAL_FUNC:
self.match(Tag.OPEN_NEUTRAL_FUNC)
result = self.func(token.tag)
self.match(Tag.CLOSE_PAREN)
elif token.tag == Tag.COMMA:
self.match(Tag.COMMA)
elif token.tag == Tag.STRING:
self.match(Tag.STRING)
elif self.lookahead.tag == Tag.DONE:
self.match(Tag.DONE)
else:
raise TracException("factor: bad token tag - %s" % token)
return result
def match(self, tag, result=None):
if self.lookahead.tag == tag:
if result != None:
self.io.push(result)
self.lookahead = self.lexan()
else:
raise TracException("match: tag %s doesn't match %s" % (tag, self.lookahead))
def eval_func(self, args):
result = ""
try:
func_name = args[0]
args = args[1:]
primitive = self.primitives.get(func_name, None)
if primitive:
result = primitive(args)
if self.trace:
print "eval: %s %s -> [%s]" % (func_name, args, result)
except Exception, e:
raise TracException, "%s: failed - %s" %("eval", e)
return result
def parse(self):
self.lookahead = self.lexan()
while self.lookahead.tag != Tag.DONE:
self.func()
self.match(Tag.DONE)
print "Forms: %s" % self.forms
print "Output: %s" % self.output
return self
class TestTrac(unittest.TestCase):
def setUp(self):
pass
def __test(self, program, output):
self.lexer = Lexer()
self.lexer.initialize(program)
self.lexer.parse()
self.assertEqual(self.lexer.output, output)
def test_1_ps(self):
self.__test("#(ps,Hello world)", "Hello world")
def test_2_equal(self):
self.__test("#(ps,#(eq,A,A,=,!=))", "=")
def test_3_not_equal(self):
self.__test("#(ps,#(eq,Cat,Dog,equal,not equal))", "not equal")
def test_4_ds(self):
self.__test("#(ds,AA,Cat)#(ps,#(cl,AA))", "Cat")
def test_5_protect_parens(self):
self.__test("#(ds,AA,Cat)#(ds,BB,(#(cl,AA)))#(ps,(#(cl,BB)))", "#(cl,BB)")
def test_6_neutral_func(self):
self.__test("#(ds,AA,Cat)#(ds,BB,(#(cl,AA)))#(ps,##(cl,BB))", "#(cl,AA)")
def test_7_indirection(self):
self.__test("#(ds,AA,Cat)#(ds,BB,(#(cl,AA)))#(ps,#(cl,BB))", "Cat")
def test_8_ss(self):
self.__test("#(ds,AA,Hello X)#(ss,AA,X)#(ps,#(cl,AA,world))", "Hello world")
def test_9_factorial(self):
self.__test("""
#(ds,Factorial,(#(eq,X,1,1,(#(ml,X,#(cl,Factorial,#(su,X,1)))))))
#(ss,Factorial,X)
#(ps,#(cl,Factorial,5))
""", "120")
if __name__ == "__main__":
print __file__
unittest.main()
|
This approach roughly halves the lines of code to implement the lexical analyzer portion of the interpreter than in the original algorithm specified by Calvin Mooers, TRAC's creator.
Assuming one is used to recursion, recursive descent is more comprehensible than the Mooers mechanism. Breaking the character stream into tokens allows one a better view of the overall structure.
For a discussion of the TRAC language, see http://code.activestate.com/recipes/577366-trac-interpreter-sixties-programming-language/ .