CommonTokenFactory.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #
  2. # Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  3. # Use of this file is governed by the BSD 3-clause license that
  4. # can be found in the LICENSE.txt file in the project root.
  5. #
  6. #
  7. # This default implementation of {@link TokenFactory} creates
  8. # {@link CommonToken} objects.
  9. #
  10. from antlr4.Token import CommonToken
  11. class TokenFactory(object):
  12. pass
  13. class CommonTokenFactory(TokenFactory):
  14. __slots__ = 'copyText'
  15. #
  16. # The default {@link CommonTokenFactory} instance.
  17. #
  18. # <p>
  19. # This token factory does not explicitly copy token text when constructing
  20. # tokens.</p>
  21. #
  22. DEFAULT = None
  23. def __init__(self, copyText:bool=False):
  24. # Indicates whether {@link CommonToken#setText} should be called after
  25. # constructing tokens to explicitly set the text. This is useful for cases
  26. # where the input stream might not be able to provide arbitrary substrings
  27. # of text from the input after the lexer creates a token (e.g. the
  28. # implementation of {@link CharStream#getText} in
  29. # {@link UnbufferedCharStream} throws an
  30. # {@link UnsupportedOperationException}). Explicitly setting the token text
  31. # allows {@link Token#getText} to be called at any time regardless of the
  32. # input stream implementation.
  33. #
  34. # <p>
  35. # The default value is {@code false} to avoid the performance and memory
  36. # overhead of copying text for every token unless explicitly requested.</p>
  37. #
  38. self.copyText = copyText
  39. def create(self, source, type:int, text:str, channel:int, start:int, stop:int, line:int, column:int):
  40. t = CommonToken(source, type, channel, start, stop)
  41. t.line = line
  42. t.column = column
  43. if text is not None:
  44. t.text = text
  45. elif self.copyText and source[1] is not None:
  46. t.text = source[1].getText(start,stop)
  47. return t
  48. def createThin(self, type:int, text:str):
  49. t = CommonToken(type=type)
  50. t.text = text
  51. return t
  52. CommonTokenFactory.DEFAULT = CommonTokenFactory()