Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- A -> e* | (eUe)
- e -> any combination of chars from the grammar
- A -> e+ | '(' A 'U' A ')'
- e -> '0' | '1'
- class MySyntaxError(Exception):
- def __init__(self, text, index):
- self.text = text
- self.index = index
- def __str__(self):
- return "Syntax error at index " + repr(self.index) + ": " + self.text
- def parse(input):
- global index
- index = 0
- def eat_char(set):
- global index
- if index < len(input) and input[index] in set:
- index += 1
- else:
- raise MySyntaxError("expected char in " + repr(set), index)
- def e():
- eat_char(['0', '1'])
- def A():
- global index
- if index == len(input): # Successfully parsed
- return
- elif input[index] in ['0', '1']:
- while (input[index] in ['0', '1']):
- e()
- elif input[index] is '(':
- eat_char(['('])
- A()
- eat_char(['U'])
- A()
- eat_char([')'])
- else:
- raise MySyntaxError("expected char '0', '1' or '('", index)
- A()
- if index != len(input): # Parsing didn't reach the end of the string
- raise MySyntaxError("parsing ended before the end of the input", index)
- def test(string):
- try:
- parse(string)
- print "The string " + string + " have been successfully parsed"
- except MySyntaxError as e:
- print "The string " + string + " can't be parsed:"
- print e
- test("(01U(1U0))")
- test("(01U(1U0)") # Missing parenthesis, syntax error
- test("(01U(1U0)))") # Too many parenthesis, syntax error
- test("01U(1U0)") # No parenthesis, syntax error
- from state [1]
- read a '0' or a '1' and loop into state [1]
- read a '(', push the parenthesis and loop into state [1]
- read a 'U', when there is an open parenthesis on the top of stack, push the 'U' and loop into state [1]
- read a ')', when there is a 'U' on the top of the stack, pop the 'U', pop the opend parenthesis following, and loop into state[1]
- def parse(input):
- index = 0
- stack = [];
- def top():
- if len(stack) > 0:
- return stack[len(stack)-1]
- else:
- return None
- while index < len(input):
- if input[index] in ['0', '1']:
- pass
- elif input[index] is '(':
- stack.append('(')
- elif input[index] is 'U' and top() == '(':
- stack.append('U')
- elif input[index] is ')' and top() == 'U':
- stack.pop()
- stack.pop()
- else:
- raise MySyntaxError("Unexpected char '" + input[index] + "'", index)
- index += 1
- if len(stack):
- raise MySyntaxError("unterminated input", index)
Add Comment
Please, Sign In to add comment