elif self.text[ix] in string.digits:
str = ''
while self.text[ix] in string.digits:
str += self.text[ix]
ix += 1
if self.text[ix] == '.':
str += '.'
ix += 1
while self.text[ix] in string.digits:
str += self.text[ix]
ix += 1
self.token = 'num'
self.value = float(str)
else:
self.token = 'num'
self.value = int(str) # subsumes long() in 3.x
elif self.text[ix] in string.ascii_letters:
str = ''
while self.text[ix] in (string.digits + string.ascii_letters):
str += self.text[ix]
ix += 1
if str.lower() == 'set':
self.token = 'set'
else:
self.token = 'var'
self.value = str
else:
raise LexicalError()
self.next = ix
The parser module’s class creates and embeds a scanner for its lexical chores and han-
dles interpretation of the expression grammar’s rules and evaluation of the expression’s
result, as shown in Example 19-14.
Example 19-14. PP4E\Lang\Parser\parser1.py
"""
################################################################################
the parser (syntax analyser, evaluates during parse)
################################################################################
"""
class UndefinedError(Exception): pass
from scanner import Scanner, LexicalError, SyntaxError
class Parser:
def init(self, text=''):
self.lex = Scanner(text) # embed a scanner
self.vars = {'pi': 3.14159} # add a variable
def parse(self, *text):
if text: # main entry-point
Custom Language Parsers| 1443