pgen.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. # Pgen imports
  4. from . import grammar, token, tokenize
  5. class PgenGrammar(grammar.Grammar):
  6. pass
  7. class ParserGenerator(object):
  8. def __init__(self, filename, stream=None):
  9. close_stream = None
  10. if stream is None:
  11. stream = open(filename)
  12. close_stream = stream.close
  13. self.filename = filename
  14. self.stream = stream
  15. self.generator = tokenize.generate_tokens(stream.readline)
  16. self.gettoken() # Initialize lookahead
  17. self.dfas, self.startsymbol = self.parse()
  18. if close_stream is not None:
  19. close_stream()
  20. self.first = {} # map from symbol name to set of tokens
  21. self.addfirstsets()
  22. def make_grammar(self):
  23. c = PgenGrammar()
  24. names = list(self.dfas.keys())
  25. names.sort()
  26. names.remove(self.startsymbol)
  27. names.insert(0, self.startsymbol)
  28. for name in names:
  29. i = 256 + len(c.symbol2number)
  30. c.symbol2number[name] = i
  31. c.number2symbol[i] = name
  32. for name in names:
  33. dfa = self.dfas[name]
  34. states = []
  35. for state in dfa:
  36. arcs = []
  37. for label, next in sorted(state.arcs.items()):
  38. arcs.append((self.make_label(c, label), dfa.index(next)))
  39. if state.isfinal:
  40. arcs.append((0, dfa.index(state)))
  41. states.append(arcs)
  42. c.states.append(states)
  43. c.dfas[c.symbol2number[name]] = (states, self.make_first(c, name))
  44. c.start = c.symbol2number[self.startsymbol]
  45. return c
  46. def make_first(self, c, name):
  47. rawfirst = self.first[name]
  48. first = {}
  49. for label in sorted(rawfirst):
  50. ilabel = self.make_label(c, label)
  51. ##assert ilabel not in first # XXX failed on <> ... !=
  52. first[ilabel] = 1
  53. return first
  54. def make_label(self, c, label):
  55. # XXX Maybe this should be a method on a subclass of converter?
  56. ilabel = len(c.labels)
  57. if label[0].isalpha():
  58. # Either a symbol name or a named token
  59. if label in c.symbol2number:
  60. # A symbol name (a non-terminal)
  61. if label in c.symbol2label:
  62. return c.symbol2label[label]
  63. else:
  64. c.labels.append((c.symbol2number[label], None))
  65. c.symbol2label[label] = ilabel
  66. return ilabel
  67. else:
  68. # A named token (NAME, NUMBER, STRING)
  69. itoken = getattr(token, label, None)
  70. assert isinstance(itoken, int), label
  71. assert itoken in token.tok_name, label
  72. if itoken in c.tokens:
  73. return c.tokens[itoken]
  74. else:
  75. c.labels.append((itoken, None))
  76. c.tokens[itoken] = ilabel
  77. return ilabel
  78. else:
  79. # Either a keyword or an operator
  80. assert label[0] in ('"', "'"), label
  81. value = eval(label)
  82. if value[0].isalpha():
  83. # A keyword
  84. if value in c.keywords:
  85. return c.keywords[value]
  86. else:
  87. c.labels.append((token.NAME, value))
  88. c.keywords[value] = ilabel
  89. return ilabel
  90. else:
  91. # An operator (any non-numeric token)
  92. itoken = grammar.opmap[value] # Fails if unknown token
  93. if itoken in c.tokens:
  94. return c.tokens[itoken]
  95. else:
  96. c.labels.append((itoken, None))
  97. c.tokens[itoken] = ilabel
  98. return ilabel
  99. def addfirstsets(self):
  100. names = list(self.dfas.keys())
  101. names.sort()
  102. for name in names:
  103. if name not in self.first:
  104. self.calcfirst(name)
  105. #print name, self.first[name].keys()
  106. def calcfirst(self, name):
  107. dfa = self.dfas[name]
  108. self.first[name] = None # dummy to detect left recursion
  109. state = dfa[0]
  110. totalset = {}
  111. overlapcheck = {}
  112. for label, next in state.arcs.items():
  113. if label in self.dfas:
  114. if label in self.first:
  115. fset = self.first[label]
  116. if fset is None:
  117. raise ValueError("recursion for rule %r" % name)
  118. else:
  119. self.calcfirst(label)
  120. fset = self.first[label]
  121. totalset.update(fset)
  122. overlapcheck[label] = fset
  123. else:
  124. totalset[label] = 1
  125. overlapcheck[label] = {label: 1}
  126. inverse = {}
  127. for label, itsfirst in overlapcheck.items():
  128. for symbol in itsfirst:
  129. if symbol in inverse:
  130. raise ValueError("rule %s is ambiguous; %s is in the"
  131. " first sets of %s as well as %s" %
  132. (name, symbol, label, inverse[symbol]))
  133. inverse[symbol] = label
  134. self.first[name] = totalset
  135. def parse(self):
  136. dfas = {}
  137. startsymbol = None
  138. # MSTART: (NEWLINE | RULE)* ENDMARKER
  139. while self.type != token.ENDMARKER:
  140. while self.type == token.NEWLINE:
  141. self.gettoken()
  142. # RULE: NAME ':' RHS NEWLINE
  143. name = self.expect(token.NAME)
  144. self.expect(token.OP, ":")
  145. a, z = self.parse_rhs()
  146. self.expect(token.NEWLINE)
  147. #self.dump_nfa(name, a, z)
  148. dfa = self.make_dfa(a, z)
  149. #self.dump_dfa(name, dfa)
  150. oldlen = len(dfa)
  151. self.simplify_dfa(dfa)
  152. newlen = len(dfa)
  153. dfas[name] = dfa
  154. #print name, oldlen, newlen
  155. if startsymbol is None:
  156. startsymbol = name
  157. return dfas, startsymbol
  158. def make_dfa(self, start, finish):
  159. # To turn an NFA into a DFA, we define the states of the DFA
  160. # to correspond to *sets* of states of the NFA. Then do some
  161. # state reduction. Let's represent sets as dicts with 1 for
  162. # values.
  163. assert isinstance(start, NFAState)
  164. assert isinstance(finish, NFAState)
  165. def closure(state):
  166. base = {}
  167. addclosure(state, base)
  168. return base
  169. def addclosure(state, base):
  170. assert isinstance(state, NFAState)
  171. if state in base:
  172. return
  173. base[state] = 1
  174. for label, next in state.arcs:
  175. if label is None:
  176. addclosure(next, base)
  177. states = [DFAState(closure(start), finish)]
  178. for state in states: # NB states grows while we're iterating
  179. arcs = {}
  180. for nfastate in state.nfaset:
  181. for label, next in nfastate.arcs:
  182. if label is not None:
  183. addclosure(next, arcs.setdefault(label, {}))
  184. for label, nfaset in sorted(arcs.items()):
  185. for st in states:
  186. if st.nfaset == nfaset:
  187. break
  188. else:
  189. st = DFAState(nfaset, finish)
  190. states.append(st)
  191. state.addarc(st, label)
  192. return states # List of DFAState instances; first one is start
  193. def dump_nfa(self, name, start, finish):
  194. print("Dump of NFA for", name)
  195. todo = [start]
  196. for i, state in enumerate(todo):
  197. print(" State", i, state is finish and "(final)" or "")
  198. for label, next in state.arcs:
  199. if next in todo:
  200. j = todo.index(next)
  201. else:
  202. j = len(todo)
  203. todo.append(next)
  204. if label is None:
  205. print(" -> %d" % j)
  206. else:
  207. print(" %s -> %d" % (label, j))
  208. def dump_dfa(self, name, dfa):
  209. print("Dump of DFA for", name)
  210. for i, state in enumerate(dfa):
  211. print(" State", i, state.isfinal and "(final)" or "")
  212. for label, next in sorted(state.arcs.items()):
  213. print(" %s -> %d" % (label, dfa.index(next)))
  214. def simplify_dfa(self, dfa):
  215. # This is not theoretically optimal, but works well enough.
  216. # Algorithm: repeatedly look for two states that have the same
  217. # set of arcs (same labels pointing to the same nodes) and
  218. # unify them, until things stop changing.
  219. # dfa is a list of DFAState instances
  220. changes = True
  221. while changes:
  222. changes = False
  223. for i, state_i in enumerate(dfa):
  224. for j in range(i+1, len(dfa)):
  225. state_j = dfa[j]
  226. if state_i == state_j:
  227. #print " unify", i, j
  228. del dfa[j]
  229. for state in dfa:
  230. state.unifystate(state_j, state_i)
  231. changes = True
  232. break
  233. def parse_rhs(self):
  234. # RHS: ALT ('|' ALT)*
  235. a, z = self.parse_alt()
  236. if self.value != "|":
  237. return a, z
  238. else:
  239. aa = NFAState()
  240. zz = NFAState()
  241. aa.addarc(a)
  242. z.addarc(zz)
  243. while self.value == "|":
  244. self.gettoken()
  245. a, z = self.parse_alt()
  246. aa.addarc(a)
  247. z.addarc(zz)
  248. return aa, zz
  249. def parse_alt(self):
  250. # ALT: ITEM+
  251. a, b = self.parse_item()
  252. while (self.value in ("(", "[") or
  253. self.type in (token.NAME, token.STRING)):
  254. c, d = self.parse_item()
  255. b.addarc(c)
  256. b = d
  257. return a, b
  258. def parse_item(self):
  259. # ITEM: '[' RHS ']' | ATOM ['+' | '*']
  260. if self.value == "[":
  261. self.gettoken()
  262. a, z = self.parse_rhs()
  263. self.expect(token.OP, "]")
  264. a.addarc(z)
  265. return a, z
  266. else:
  267. a, z = self.parse_atom()
  268. value = self.value
  269. if value not in ("+", "*"):
  270. return a, z
  271. self.gettoken()
  272. z.addarc(a)
  273. if value == "+":
  274. return a, z
  275. else:
  276. return a, a
  277. def parse_atom(self):
  278. # ATOM: '(' RHS ')' | NAME | STRING
  279. if self.value == "(":
  280. self.gettoken()
  281. a, z = self.parse_rhs()
  282. self.expect(token.OP, ")")
  283. return a, z
  284. elif self.type in (token.NAME, token.STRING):
  285. a = NFAState()
  286. z = NFAState()
  287. a.addarc(z, self.value)
  288. self.gettoken()
  289. return a, z
  290. else:
  291. self.raise_error("expected (...) or NAME or STRING, got %s/%s",
  292. self.type, self.value)
  293. def expect(self, type, value=None):
  294. if self.type != type or (value is not None and self.value != value):
  295. self.raise_error("expected %s/%s, got %s/%s",
  296. type, value, self.type, self.value)
  297. value = self.value
  298. self.gettoken()
  299. return value
  300. def gettoken(self):
  301. tup = next(self.generator)
  302. while tup[0] in (tokenize.COMMENT, tokenize.NL):
  303. tup = next(self.generator)
  304. self.type, self.value, self.begin, self.end, self.line = tup
  305. #print token.tok_name[self.type], repr(self.value)
  306. def raise_error(self, msg, *args):
  307. if args:
  308. try:
  309. msg = msg % args
  310. except:
  311. msg = " ".join([msg] + list(map(str, args)))
  312. raise SyntaxError(msg, (self.filename, self.end[0],
  313. self.end[1], self.line))
  314. class NFAState(object):
  315. def __init__(self):
  316. self.arcs = [] # list of (label, NFAState) pairs
  317. def addarc(self, next, label=None):
  318. assert label is None or isinstance(label, str)
  319. assert isinstance(next, NFAState)
  320. self.arcs.append((label, next))
  321. class DFAState(object):
  322. def __init__(self, nfaset, final):
  323. assert isinstance(nfaset, dict)
  324. assert isinstance(next(iter(nfaset)), NFAState)
  325. assert isinstance(final, NFAState)
  326. self.nfaset = nfaset
  327. self.isfinal = final in nfaset
  328. self.arcs = {} # map from label to DFAState
  329. def addarc(self, next, label):
  330. assert isinstance(label, str)
  331. assert label not in self.arcs
  332. assert isinstance(next, DFAState)
  333. self.arcs[label] = next
  334. def unifystate(self, old, new):
  335. for label, next in self.arcs.items():
  336. if next is old:
  337. self.arcs[label] = new
  338. def __eq__(self, other):
  339. # Equality test -- ignore the nfaset instance variable
  340. assert isinstance(other, DFAState)
  341. if self.isfinal != other.isfinal:
  342. return False
  343. # Can't just return self.arcs == other.arcs, because that
  344. # would invoke this method recursively, with cycles...
  345. if len(self.arcs) != len(other.arcs):
  346. return False
  347. for label, next in self.arcs.items():
  348. if next is not other.arcs.get(label):
  349. return False
  350. return True
  351. __hash__ = None # For Py3 compatibility.
  352. def generate_grammar(filename="Grammar.txt"):
  353. p = ParserGenerator(filename)
  354. return p.make_grammar()