Interpreter.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """
  2. This module deals with interpreting the parse tree as Python
  3. would have done, in the compiler.
  4. For now this only covers parse tree to value conversion of
  5. compile-time values.
  6. """
  7. from __future__ import absolute_import
  8. from .Nodes import *
  9. from .ExprNodes import *
  10. from .Errors import CompileError
  11. class EmptyScope(object):
  12. def lookup(self, name):
  13. return None
  14. empty_scope = EmptyScope()
  15. def interpret_compiletime_options(optlist, optdict, type_env=None, type_args=()):
  16. """
  17. Tries to interpret a list of compile time option nodes.
  18. The result will be a tuple (optlist, optdict) but where
  19. all expression nodes have been interpreted. The result is
  20. in the form of tuples (value, pos).
  21. optlist is a list of nodes, while optdict is a DictNode (the
  22. result optdict is a dict)
  23. If type_env is set, all type nodes will be analysed and the resulting
  24. type set. Otherwise only interpretateable ExprNodes
  25. are allowed, other nodes raises errors.
  26. A CompileError will be raised if there are problems.
  27. """
  28. def interpret(node, ix):
  29. if ix in type_args:
  30. if type_env:
  31. type = node.analyse_as_type(type_env)
  32. if not type:
  33. raise CompileError(node.pos, "Invalid type.")
  34. return (type, node.pos)
  35. else:
  36. raise CompileError(node.pos, "Type not allowed here.")
  37. else:
  38. if (sys.version_info[0] >=3 and
  39. isinstance(node, StringNode) and
  40. node.unicode_value is not None):
  41. return (node.unicode_value, node.pos)
  42. return (node.compile_time_value(empty_scope), node.pos)
  43. if optlist:
  44. optlist = [interpret(x, ix) for ix, x in enumerate(optlist)]
  45. if optdict:
  46. assert isinstance(optdict, DictNode)
  47. new_optdict = {}
  48. for item in optdict.key_value_pairs:
  49. new_key, dummy = interpret(item.key, None)
  50. new_optdict[new_key] = interpret(item.value, item.key.value)
  51. optdict = new_optdict
  52. return (optlist, new_optdict)