PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/js/src/config/Expression.py

https://github.com/neonux/mozilla-all
Python | 176 lines | 166 code | 1 blank | 9 comment | 0 complexity | 1fad7460f099978191961296f7664ae6 MD5 | raw file
  1. # This Source Code Form is subject to the terms of the Mozilla Public
  2. # License, v. 2.0. If a copy of the MPL was not distributed with this
  3. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. """
  5. Parses and evaluates simple statements for Preprocessor:
  6. Expression currently supports the following grammar, whitespace is ignored:
  7. expression :
  8. unary ( ( '==' | '!=' ) unary ) ? ;
  9. unary :
  10. '!'? value ;
  11. value :
  12. [0-9]+ # integer
  13. | \w+ # string identifier or value;
  14. """
  15. import re
  16. class Expression:
  17. def __init__(self, expression_string):
  18. """
  19. Create a new expression with this string.
  20. The expression will already be parsed into an Abstract Syntax Tree.
  21. """
  22. self.content = expression_string
  23. self.offset = 0
  24. self.__ignore_whitespace()
  25. self.e = self.__get_equality()
  26. if self.content:
  27. raise Expression.ParseError, self
  28. def __get_equality(self):
  29. """
  30. Production: unary ( ( '==' | '!=' ) unary ) ?
  31. """
  32. if not len(self.content):
  33. return None
  34. rv = Expression.__AST("equality")
  35. # unary
  36. rv.append(self.__get_unary())
  37. self.__ignore_whitespace()
  38. if not re.match('[=!]=', self.content):
  39. # no equality needed, short cut to our prime unary
  40. return rv[0]
  41. # append operator
  42. rv.append(Expression.__ASTLeaf('op', self.content[:2]))
  43. self.__strip(2)
  44. self.__ignore_whitespace()
  45. rv.append(self.__get_unary())
  46. self.__ignore_whitespace()
  47. return rv
  48. def __get_unary(self):
  49. """
  50. Production: '!'? value
  51. """
  52. # eat whitespace right away, too
  53. not_ws = re.match('!\s*', self.content)
  54. if not not_ws:
  55. return self.__get_value()
  56. rv = Expression.__AST('not')
  57. self.__strip(not_ws.end())
  58. rv.append(self.__get_value())
  59. self.__ignore_whitespace()
  60. return rv
  61. def __get_value(self):
  62. """
  63. Production: ( [0-9]+ | \w+)
  64. Note that the order is important, and the expression is kind-of
  65. ambiguous as \w includes 0-9. One could make it unambiguous by
  66. removing 0-9 from the first char of a string literal.
  67. """
  68. rv = None
  69. word_len = re.match('[0-9]*', self.content).end()
  70. if word_len:
  71. value = int(self.content[:word_len])
  72. rv = Expression.__ASTLeaf('int', value)
  73. else:
  74. word_len = re.match('\w*', self.content).end()
  75. if word_len:
  76. rv = Expression.__ASTLeaf('string', self.content[:word_len])
  77. else:
  78. raise Expression.ParseError, self
  79. self.__strip(word_len)
  80. self.__ignore_whitespace()
  81. return rv
  82. def __ignore_whitespace(self):
  83. ws_len = re.match('\s*', self.content).end()
  84. self.__strip(ws_len)
  85. return
  86. def __strip(self, length):
  87. """
  88. Remove a given amount of chars from the input and update
  89. the offset.
  90. """
  91. self.content = self.content[length:]
  92. self.offset += length
  93. def evaluate(self, context):
  94. """
  95. Evaluate the expression with the given context
  96. """
  97. # Helper function to evaluate __get_equality results
  98. def eval_equality(tok):
  99. left = opmap[tok[0].type](tok[0])
  100. right = opmap[tok[2].type](tok[2])
  101. rv = left == right
  102. if tok[1].value == '!=':
  103. rv = not rv
  104. return rv
  105. # Mapping from token types to evaluator functions
  106. # Apart from (non-)equality, all these can be simple lambda forms.
  107. opmap = {
  108. 'equality': eval_equality,
  109. 'not': lambda tok: not opmap[tok[0].type](tok[0]),
  110. 'string': lambda tok: context[tok.value],
  111. 'int': lambda tok: tok.value}
  112. return opmap[self.e.type](self.e);
  113. class __AST(list):
  114. """
  115. Internal class implementing Abstract Syntax Tree nodes
  116. """
  117. def __init__(self, type):
  118. self.type = type
  119. super(self.__class__, self).__init__(self)
  120. class __ASTLeaf:
  121. """
  122. Internal class implementing Abstract Syntax Tree leafs
  123. """
  124. def __init__(self, type, value):
  125. self.value = value
  126. self.type = type
  127. def __str__(self):
  128. return self.value.__str__()
  129. def __repr__(self):
  130. return self.value.__repr__()
  131. class ParseError(StandardError):
  132. """
  133. Error raised when parsing fails.
  134. It has two members, offset and content, which give the offset of the
  135. error and the offending content.
  136. """
  137. def __init__(self, expression):
  138. self.offset = expression.offset
  139. self.content = expression.content[:3]
  140. def __str__(self):
  141. return 'Unexpected content at offset %i, "%s"'%(self.offset, self.content)
  142. class Context(dict):
  143. """
  144. This class holds variable values by subclassing dict, and while it
  145. truthfully reports True and False on
  146. name in context
  147. it returns the variable name itself on
  148. context["name"]
  149. to reflect the ambiguity between string literals and preprocessor
  150. variables.
  151. """
  152. def __getitem__(self, key):
  153. if key in self:
  154. return super(self.__class__, self).__getitem__(key)
  155. return key