op_util.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. # -*- coding: utf-8 -*-
  2. """
  3. Part of the astor library for Python AST manipulation.
  4. License: 3-clause BSD
  5. Copyright (c) 2015 Patrick Maupin
  6. This module provides data and functions for mapping
  7. AST nodes to symbols and precedences.
  8. """
  9. import ast
  10. op_data = """
  11. GeneratorExp 1
  12. Assign 1
  13. AnnAssign 1
  14. AugAssign 0
  15. Expr 0
  16. Yield 1
  17. YieldFrom 0
  18. If 1
  19. For 0
  20. AsyncFor 0
  21. While 0
  22. Return 1
  23. Slice 1
  24. Subscript 0
  25. Index 1
  26. ExtSlice 1
  27. comprehension_target 1
  28. Tuple 0
  29. FormattedValue 0
  30. Comma 1
  31. NamedExpr 1
  32. Assert 0
  33. Raise 0
  34. call_one_arg 1
  35. Lambda 1
  36. IfExp 0
  37. comprehension 1
  38. Or or 1
  39. And and 1
  40. Not not 1
  41. Eq == 1
  42. Gt > 0
  43. GtE >= 0
  44. In in 0
  45. Is is 0
  46. NotEq != 0
  47. Lt < 0
  48. LtE <= 0
  49. NotIn not in 0
  50. IsNot is not 0
  51. BitOr | 1
  52. BitXor ^ 1
  53. BitAnd & 1
  54. LShift << 1
  55. RShift >> 0
  56. Add + 1
  57. Sub - 0
  58. Mult * 1
  59. Div / 0
  60. Mod % 0
  61. FloorDiv // 0
  62. MatMult @ 0
  63. PowRHS 1
  64. Invert ~ 1
  65. UAdd + 0
  66. USub - 0
  67. Pow ** 1
  68. Await 1
  69. Num 1
  70. Constant 1
  71. """
  72. op_data = [x.split() for x in op_data.splitlines()]
  73. op_data = [[x[0], ' '.join(x[1:-1]), int(x[-1])] for x in op_data if x]
  74. for index in range(1, len(op_data)):
  75. op_data[index][2] *= 2
  76. op_data[index][2] += op_data[index - 1][2]
  77. precedence_data = dict((getattr(ast, x, None), z) for x, y, z in op_data)
  78. symbol_data = dict((getattr(ast, x, None), y) for x, y, z in op_data)
  79. def get_op_symbol(obj, fmt='%s', symbol_data=symbol_data, type=type):
  80. """Given an AST node object, returns a string containing the symbol.
  81. """
  82. return fmt % symbol_data[type(obj)]
  83. def get_op_precedence(obj, precedence_data=precedence_data, type=type):
  84. """Given an AST node object, returns the precedence.
  85. """
  86. return precedence_data[type(obj)]
  87. class Precedence(object):
  88. vars().update((x, z) for x, y, z in op_data)
  89. highest = max(z for x, y, z in op_data) + 2