parser.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import sys
  2. class ParserWrapper(object):
  3. def __init__(self, base_class, **kwargs):
  4. self.input_buffer = []
  5. self.input_position = 0
  6. self.verbose = kwargs.get('verbose', False)
  7. # Overwrite parser read() method
  8. def read(nbytes):
  9. buf = ''
  10. try:
  11. buf = self.input_buffer[self.input_position]
  12. if self.verbose:
  13. print 'read:', buf
  14. except IndexError:
  15. return ''
  16. self.input_position += 1
  17. return buf
  18. self.parser = base_class(**kwargs)
  19. self.parser.read = read
  20. def run(self, input_buffer, *args, **kwargs):
  21. map(self.append, input_buffer)
  22. return self.parser.run(*args, **kwargs)
  23. def append(self, input):
  24. self.input_buffer.append(input + '\n')
  25. def run_expressions(base_class, expressions, keepfiles=1, fail=True,
  26. silent=False, verbose=0):
  27. """
  28. Run a list of mathematical expression through the term rewriting system and
  29. check if the output matches the expected output. The list of EXPRESSIONS
  30. consists of tuples (expression, output), where expression is the
  31. mathematical expression to evaluate (String) and output is the expected
  32. output of the evaluation (thus, the output can be Float, Int or None).
  33. If KEEPFILES is non-zero or True, the generated Flex and Bison files will
  34. be kept. Otherwise, those temporary files will be deleted. If FAIL is True,
  35. and the output of the expression is not equal to the expected output, an
  36. assertion error is raised. If SILENT is False, and an assertion error is
  37. raised, an error message is printed on stderr. If SILENT is True, no error
  38. message will be printed.
  39. If VERBOSE is non-zero and a positive integer number, verbosity of the term
  40. rewriting system will be increased. This will output debug messages and a
  41. higher value will print more types of debug messages.
  42. """
  43. parser = ParserWrapper(base_class, keepfiles=keepfiles, verbose=verbose)
  44. for exp, out in expressions:
  45. res = None
  46. try:
  47. res = parser.run([exp])
  48. assert res == out
  49. except:
  50. if not silent:
  51. print >>sys.stderr, 'error: %s = %s, but expected: %s' \
  52. % (exp, str(res), str(out))
  53. if fail:
  54. raise