tokenizer.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. """
  2. This module contains a tokenizer for Excel formulae.
  3. The tokenizer is based on the Javascript tokenizer found at
  4. http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html written by Eric
  5. Bachtal
  6. """
  7. import re
  8. class TokenizerError(Exception):
  9. """Base class for all Tokenizer errors."""
  10. class Tokenizer:
  11. """
  12. A tokenizer for Excel worksheet formulae.
  13. Converts a str string representing an Excel formula (in A1 notation)
  14. into a sequence of `Token` objects.
  15. `formula`: The str string to tokenize
  16. Tokenizer defines a method `._parse()` to parse the formula into tokens,
  17. which can then be accessed through the `.items` attribute.
  18. """
  19. SN_RE = re.compile("^[1-9](\\.[0-9]+)?[Ee]$") # Scientific notation
  20. WSPACE_RE = re.compile(r"[ \n]+")
  21. STRING_REGEXES = {
  22. # Inside a string, all characters are treated as literals, except for
  23. # the quote character used to start the string. That character, when
  24. # doubled is treated as a single character in the string. If an
  25. # unmatched quote appears, the string is terminated.
  26. '"': re.compile('"(?:[^"]*"")*[^"]*"(?!")'),
  27. "'": re.compile("'(?:[^']*'')*[^']*'(?!')"),
  28. }
  29. ERROR_CODES = ("#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?",
  30. "#NUM!", "#N/A", "#GETTING_DATA")
  31. TOKEN_ENDERS = ',;}) +-*/^&=><%' # Each of these characters, marks the
  32. # end of an operand token
  33. def __init__(self, formula):
  34. self.formula = formula
  35. self.items = []
  36. self.token_stack = [] # Used to keep track of arrays, functions, and
  37. # parentheses
  38. self.offset = 0 # How many chars have we read
  39. self.token = [] # Used to build up token values char by char
  40. self._parse()
  41. def _parse(self):
  42. """Populate self.items with the tokens from the formula."""
  43. if self.offset:
  44. return # Already parsed!
  45. if not self.formula:
  46. return
  47. elif self.formula[0] == '=':
  48. self.offset += 1
  49. else:
  50. self.items.append(Token(self.formula, Token.LITERAL))
  51. return
  52. consumers = (
  53. ('"\'', self._parse_string),
  54. ('[', self._parse_brackets),
  55. ('#', self._parse_error),
  56. (' ', self._parse_whitespace),
  57. ('\n', self._parse_whitespace),
  58. ('+-*/^&=><%', self._parse_operator),
  59. ('{(', self._parse_opener),
  60. (')}', self._parse_closer),
  61. (';,', self._parse_separator),
  62. )
  63. dispatcher = {} # maps chars to the specific parsing function
  64. for chars, consumer in consumers:
  65. dispatcher.update(dict.fromkeys(chars, consumer))
  66. while self.offset < len(self.formula):
  67. if self.check_scientific_notation(): # May consume one character
  68. continue
  69. curr_char = self.formula[self.offset]
  70. if curr_char in self.TOKEN_ENDERS:
  71. self.save_token()
  72. if curr_char in dispatcher:
  73. self.offset += dispatcher[curr_char]()
  74. else:
  75. # TODO: this can probably be sped up using a regex to get to
  76. # the next interesting character
  77. self.token.append(curr_char)
  78. self.offset += 1
  79. self.save_token()
  80. def _parse_string(self):
  81. """
  82. Parse a "-delimited string or '-delimited link.
  83. The offset must be pointing to either a single quote ("'") or double
  84. quote ('"') character. The strings are parsed according to Excel
  85. rules where to escape the delimiter you just double it up. E.g.,
  86. "abc""def" in Excel is parsed as 'abc"def' in Python.
  87. Returns the number of characters matched. (Does not update
  88. self.offset)
  89. """
  90. self.assert_empty_token(can_follow=':')
  91. delim = self.formula[self.offset]
  92. assert delim in ('"', "'")
  93. regex = self.STRING_REGEXES[delim]
  94. match = regex.match(self.formula[self.offset:])
  95. if match is None:
  96. subtype = "string" if delim == '"' else 'link'
  97. raise TokenizerError(f"Reached end of formula while parsing {subtype} in {self.formula}")
  98. match = match.group(0)
  99. if delim == '"':
  100. self.items.append(Token.make_operand(match))
  101. else:
  102. self.token.append(match)
  103. return len(match)
  104. def _parse_brackets(self):
  105. """
  106. Consume all the text between square brackets [].
  107. Returns the number of characters matched. (Does not update
  108. self.offset)
  109. """
  110. assert self.formula[self.offset] == '['
  111. lefts = [(t.start(), 1) for t in
  112. re.finditer(r"\[", self.formula[self.offset:])]
  113. rights = [(t.start(), -1) for t in
  114. re.finditer(r"\]", self.formula[self.offset:])]
  115. open_count = 0
  116. for idx, open_close in sorted(lefts + rights):
  117. open_count += open_close
  118. if open_count == 0:
  119. outer_right = idx + 1
  120. self.token.append(
  121. self.formula[self.offset:self.offset + outer_right])
  122. return outer_right
  123. raise TokenizerError(f"Encountered unmatched '[' in {self.formula}")
  124. def _parse_error(self):
  125. """
  126. Consume the text following a '#' as an error.
  127. Looks for a match in self.ERROR_CODES and returns the number of
  128. characters matched. (Does not update self.offset)
  129. """
  130. self.assert_empty_token(can_follow='!')
  131. assert self.formula[self.offset] == '#'
  132. subformula = self.formula[self.offset:]
  133. for err in self.ERROR_CODES:
  134. if subformula.startswith(err):
  135. self.items.append(Token.make_operand(''.join(self.token) + err))
  136. del self.token[:]
  137. return len(err)
  138. raise TokenizerError(f"Invalid error code at position {self.offset} in '{self.formula}'")
  139. def _parse_whitespace(self):
  140. """
  141. Consume a string of consecutive spaces.
  142. Returns the number of spaces found. (Does not update self.offset).
  143. """
  144. assert self.formula[self.offset] in (' ', '\n')
  145. self.items.append(Token(self.formula[self.offset], Token.WSPACE))
  146. return self.WSPACE_RE.match(self.formula[self.offset:]).end()
  147. def _parse_operator(self):
  148. """
  149. Consume the characters constituting an operator.
  150. Returns the number of characters consumed. (Does not update
  151. self.offset)
  152. """
  153. if self.formula[self.offset:self.offset + 2] in ('>=', '<=', '<>'):
  154. self.items.append(Token(
  155. self.formula[self.offset:self.offset + 2],
  156. Token.OP_IN
  157. ))
  158. return 2
  159. curr_char = self.formula[self.offset] # guaranteed to be 1 char
  160. assert curr_char in '%*/^&=><+-'
  161. if curr_char == '%':
  162. token = Token('%', Token.OP_POST)
  163. elif curr_char in "*/^&=><":
  164. token = Token(curr_char, Token.OP_IN)
  165. # From here on, curr_char is guaranteed to be in '+-'
  166. elif not self.items:
  167. token = Token(curr_char, Token.OP_PRE)
  168. else:
  169. prev = next((i for i in reversed(self.items)
  170. if i.type != Token.WSPACE), None)
  171. is_infix = prev and (
  172. prev.subtype == Token.CLOSE
  173. or prev.type == Token.OP_POST
  174. or prev.type == Token.OPERAND
  175. )
  176. if is_infix:
  177. token = Token(curr_char, Token.OP_IN)
  178. else:
  179. token = Token(curr_char, Token.OP_PRE)
  180. self.items.append(token)
  181. return 1
  182. def _parse_opener(self):
  183. """
  184. Consumes a ( or { character.
  185. Returns the number of characters consumed. (Does not update
  186. self.offset)
  187. """
  188. assert self.formula[self.offset] in ('(', '{')
  189. if self.formula[self.offset] == '{':
  190. self.assert_empty_token()
  191. token = Token.make_subexp("{")
  192. elif self.token:
  193. token_value = "".join(self.token) + '('
  194. del self.token[:]
  195. token = Token.make_subexp(token_value)
  196. else:
  197. token = Token.make_subexp("(")
  198. self.items.append(token)
  199. self.token_stack.append(token)
  200. return 1
  201. def _parse_closer(self):
  202. """
  203. Consumes a } or ) character.
  204. Returns the number of characters consumed. (Does not update
  205. self.offset)
  206. """
  207. assert self.formula[self.offset] in (')', '}')
  208. token = self.token_stack.pop().get_closer()
  209. if token.value != self.formula[self.offset]:
  210. raise TokenizerError(
  211. "Mismatched ( and { pair in '%s'" % self.formula)
  212. self.items.append(token)
  213. return 1
  214. def _parse_separator(self):
  215. """
  216. Consumes a ; or , character.
  217. Returns the number of characters consumed. (Does not update
  218. self.offset)
  219. """
  220. curr_char = self.formula[self.offset]
  221. assert curr_char in (';', ',')
  222. if curr_char == ';':
  223. token = Token.make_separator(";")
  224. else:
  225. try:
  226. top_type = self.token_stack[-1].type
  227. except IndexError:
  228. token = Token(",", Token.OP_IN) # Range Union operator
  229. else:
  230. if top_type == Token.PAREN:
  231. token = Token(",", Token.OP_IN) # Range Union operator
  232. else:
  233. token = Token.make_separator(",")
  234. self.items.append(token)
  235. return 1
  236. def check_scientific_notation(self):
  237. """
  238. Consumes a + or - character if part of a number in sci. notation.
  239. Returns True if the character was consumed and self.offset was
  240. updated, False otherwise.
  241. """
  242. curr_char = self.formula[self.offset]
  243. if (curr_char in '+-'
  244. and len(self.token) >= 1
  245. and self.SN_RE.match("".join(self.token))):
  246. self.token.append(curr_char)
  247. self.offset += 1
  248. return True
  249. return False
  250. def assert_empty_token(self, can_follow=()):
  251. """
  252. Ensure that there's no token currently being parsed.
  253. Or if there is a token being parsed, it must end with a character in
  254. can_follow.
  255. If there are unconsumed token contents, it means we hit an unexpected
  256. token transition. In this case, we raise a TokenizerError
  257. """
  258. if self.token and self.token[-1] not in can_follow:
  259. raise TokenizerError(f"Unexpected character at position {self.offset} in '{self.formula}'")
  260. def save_token(self):
  261. """If there's a token being parsed, add it to the item list."""
  262. if self.token:
  263. self.items.append(Token.make_operand("".join(self.token)))
  264. del self.token[:]
  265. def render(self):
  266. """Convert the parsed tokens back to a string."""
  267. if not self.items:
  268. return ""
  269. elif self.items[0].type == Token.LITERAL:
  270. return self.items[0].value
  271. return "=" + "".join(token.value for token in self.items)
  272. class Token:
  273. """
  274. A token in an Excel formula.
  275. Tokens have three attributes:
  276. * `value`: The string value parsed that led to this token
  277. * `type`: A string identifying the type of token
  278. * `subtype`: A string identifying subtype of the token (optional, and
  279. defaults to "")
  280. """
  281. __slots__ = ['value', 'type', 'subtype']
  282. LITERAL = "LITERAL"
  283. OPERAND = "OPERAND"
  284. FUNC = "FUNC"
  285. ARRAY = "ARRAY"
  286. PAREN = "PAREN"
  287. SEP = "SEP"
  288. OP_PRE = "OPERATOR-PREFIX"
  289. OP_IN = "OPERATOR-INFIX"
  290. OP_POST = "OPERATOR-POSTFIX"
  291. WSPACE = "WHITE-SPACE"
  292. def __init__(self, value, type_, subtype=""):
  293. self.value = value
  294. self.type = type_
  295. self.subtype = subtype
  296. # Literal operands:
  297. #
  298. # Literal operands are always of type 'OPERAND' and can be of subtype
  299. # 'TEXT' (for text strings), 'NUMBER' (for all numeric types), 'LOGICAL'
  300. # (for TRUE and FALSE), 'ERROR' (for literal error values), or 'RANGE'
  301. # (for all range references).
  302. TEXT = 'TEXT'
  303. NUMBER = 'NUMBER'
  304. LOGICAL = 'LOGICAL'
  305. ERROR = 'ERROR'
  306. RANGE = 'RANGE'
  307. def __repr__(self):
  308. return u"{0} {1} {2}:".format(self.type, self.subtype, self.value)
  309. @classmethod
  310. def make_operand(cls, value):
  311. """Create an operand token."""
  312. if value.startswith('"'):
  313. subtype = cls.TEXT
  314. elif value.startswith('#'):
  315. subtype = cls.ERROR
  316. elif value in ('TRUE', 'FALSE'):
  317. subtype = cls.LOGICAL
  318. else:
  319. try:
  320. float(value)
  321. subtype = cls.NUMBER
  322. except ValueError:
  323. subtype = cls.RANGE
  324. return cls(value, cls.OPERAND, subtype)
  325. # Subexpresssions
  326. #
  327. # There are 3 types of `Subexpressions`: functions, array literals, and
  328. # parentheticals. Subexpressions have 'OPEN' and 'CLOSE' tokens. 'OPEN'
  329. # is used when parsing the initial expression token (i.e., '(' or '{')
  330. # and 'CLOSE' is used when parsing the closing expression token ('}' or
  331. # ')').
  332. OPEN = "OPEN"
  333. CLOSE = "CLOSE"
  334. @classmethod
  335. def make_subexp(cls, value, func=False):
  336. """
  337. Create a subexpression token.
  338. `value`: The value of the token
  339. `func`: If True, force the token to be of type FUNC
  340. """
  341. assert value[-1] in ('{', '}', '(', ')')
  342. if func:
  343. assert re.match('.+\\(|\\)', value)
  344. type_ = Token.FUNC
  345. elif value in '{}':
  346. type_ = Token.ARRAY
  347. elif value in '()':
  348. type_ = Token.PAREN
  349. else:
  350. type_ = Token.FUNC
  351. subtype = cls.CLOSE if value in ')}' else cls.OPEN
  352. return cls(value, type_, subtype)
  353. def get_closer(self):
  354. """Return a closing token that matches this token's type."""
  355. assert self.type in (self.FUNC, self.ARRAY, self.PAREN)
  356. assert self.subtype == self.OPEN
  357. value = "}" if self.type == self.ARRAY else ")"
  358. return self.make_subexp(value, func=self.type == self.FUNC)
  359. # Separator tokens
  360. #
  361. # Argument separators always have type 'SEP' and can have one of two
  362. # subtypes: 'ARG', 'ROW'. 'ARG' is used for the ',' token, when used to
  363. # delimit either function arguments or array elements. 'ROW' is used for
  364. # the ';' token, which is always used to delimit rows in an array
  365. # literal.
  366. ARG = "ARG"
  367. ROW = "ROW"
  368. @classmethod
  369. def make_separator(cls, value):
  370. """Create a separator token"""
  371. assert value in (',', ';')
  372. subtype = cls.ARG if value == ',' else cls.ROW
  373. return cls(value, cls.SEP, subtype)