DFASerializer.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. # A DFA walker that knows how to dump them to serialized strings.#/
  7. from io import StringIO
  8. from antlr4 import DFA
  9. from antlr4.Utils import str_list
  10. from antlr4.dfa.DFAState import DFAState
  11. class DFASerializer(object):
  12. __slots__ = ('dfa', 'literalNames', 'symbolicNames')
  13. def __init__(self, dfa:DFA, literalNames:list=None, symbolicNames:list=None):
  14. self.dfa = dfa
  15. self.literalNames = literalNames
  16. self.symbolicNames = symbolicNames
  17. def __str__(self):
  18. if self.dfa.s0 is None:
  19. return None
  20. with StringIO() as buf:
  21. for s in self.dfa.sortedStates():
  22. n = 0
  23. if s.edges is not None:
  24. n = len(s.edges)
  25. for i in range(0, n):
  26. t = s.edges[i]
  27. if t is not None and t.stateNumber != 0x7FFFFFFF:
  28. buf.write(self.getStateString(s))
  29. label = self.getEdgeLabel(i)
  30. buf.write("-")
  31. buf.write(label)
  32. buf.write("->")
  33. buf.write(self.getStateString(t))
  34. buf.write('\n')
  35. output = buf.getvalue()
  36. if len(output)==0:
  37. return None
  38. else:
  39. return output
  40. def getEdgeLabel(self, i:int):
  41. if i==0:
  42. return "EOF"
  43. if self.literalNames is not None and i<=len(self.literalNames):
  44. return self.literalNames[i-1]
  45. elif self.symbolicNames is not None and i<=len(self.symbolicNames):
  46. return self.symbolicNames[i-1]
  47. else:
  48. return str(i-1)
  49. def getStateString(self, s:DFAState):
  50. n = s.stateNumber
  51. baseStateStr = ( ":" if s.isAcceptState else "") + "s" + str(n) + ( "^" if s.requiresFullContext else "")
  52. if s.isAcceptState:
  53. if s.predicates is not None:
  54. return baseStateStr + "=>" + str_list(s.predicates)
  55. else:
  56. return baseStateStr + "=>" + str(s.prediction)
  57. else:
  58. return baseStateStr
  59. class LexerDFASerializer(DFASerializer):
  60. def __init__(self, dfa:DFA):
  61. super().__init__(dfa, None)
  62. def getEdgeLabel(self, i:int):
  63. return "'" + chr(i) + "'"