PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/interpreter/astcompiler/misc.py

https://bitbucket.org/pypy/pypy/
Python | 118 lines | 116 code | 2 blank | 0 comment | 0 complexity | 109a09c73dadd8ef6b26f06f02db5cc6 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. from pypy.interpreter import gateway
  2. from rpython.rlib.objectmodel import we_are_translated
  3. from rpython.rlib.unroll import unrolling_iterable
  4. app = gateway.applevel("""
  5. def syntax_warning(msg, fn, lineno, offset):
  6. import warnings
  7. try:
  8. warnings.warn_explicit(msg, SyntaxWarning, fn, lineno)
  9. except SyntaxWarning:
  10. raise SyntaxError(msg, fn, lineno, offset)
  11. """, filename=__file__)
  12. _emit_syntax_warning = app.interphook("syntax_warning")
  13. del app
  14. def syntax_warning(space, msg, fn, lineno, offset):
  15. """Raise an applevel SyntaxWarning.
  16. If the user has set this warning to raise an error, a SyntaxError will be
  17. raised."""
  18. w_msg = space.wrap(msg)
  19. w_filename = space.wrap(fn)
  20. w_lineno = space.wrap(lineno)
  21. w_offset = space.wrap(offset)
  22. _emit_syntax_warning(space, w_msg, w_filename, w_lineno, w_offset)
  23. def parse_future(tree, feature_flags):
  24. from pypy.interpreter.astcompiler import ast
  25. future_lineno = 0
  26. future_column = 0
  27. flags = 0
  28. have_docstring = False
  29. body = None
  30. if isinstance(tree, ast.Module):
  31. body = tree.body
  32. elif isinstance(tree, ast.Interactive):
  33. body = tree.body
  34. if body is None:
  35. return 0, 0, 0
  36. for stmt in body:
  37. if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Str):
  38. if have_docstring:
  39. break
  40. else:
  41. have_docstring = True
  42. elif isinstance(stmt, ast.ImportFrom):
  43. if stmt.module == "__future__":
  44. future_lineno = stmt.lineno
  45. future_column = stmt.col_offset
  46. for alias in stmt.names:
  47. assert isinstance(alias, ast.alias)
  48. # If this is an invalid flag, it will be caught later in
  49. # codegen.py.
  50. flags |= feature_flags.get(alias.name, 0)
  51. else:
  52. break
  53. else:
  54. break
  55. return flags, future_lineno, future_column
  56. class ForbiddenNameAssignment(Exception):
  57. def __init__(self, name, node):
  58. self.name = name
  59. self.node = node
  60. def check_forbidden_name(name, node=None):
  61. """Raise an error if the name cannot be assigned to."""
  62. if name in ("None", "__debug__"):
  63. raise ForbiddenNameAssignment(name, node)
  64. # XXX Warn about using True and False
  65. def dict_to_switch(d):
  66. """Convert of dictionary with integer keys to a switch statement."""
  67. def lookup(query):
  68. if we_are_translated():
  69. for key, value in unrolling_iteritems:
  70. if key == query:
  71. return value
  72. else:
  73. raise KeyError
  74. else:
  75. return d[query]
  76. lookup._always_inline_ = True
  77. unrolling_iteritems = unrolling_iterable(d.iteritems())
  78. return lookup
  79. def mangle(name, klass):
  80. if not name.startswith('__'):
  81. return name
  82. # Don't mangle __id__ or names with dots. The only time a name with a dot
  83. # can occur is when we are compiling an import statement that has a package
  84. # name.
  85. if name.endswith('__') or '.' in name:
  86. return name
  87. try:
  88. i = 0
  89. while klass[i] == '_':
  90. i = i + 1
  91. except IndexError:
  92. return name
  93. return "_%s%s" % (klass[i:], name)
  94. def intern_if_common_string(space, w_const):
  95. # only intern identifier-like strings
  96. if not space.is_w(space.type(w_const), space.w_str):
  97. return w_const
  98. for c in space.str_w(w_const):
  99. if not (c.isalnum() or c == '_'):
  100. return w_const
  101. return space.new_interned_w_str(w_const)