shiftreduce.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. # Natural Language Toolkit: Shift-Reduce Parser
  2. #
  3. # Copyright (C) 2001-2020 NLTK Project
  4. # Author: Edward Loper <edloper@gmail.com>
  5. # Steven Bird <stevenbird1@gmail.com>
  6. # URL: <http://nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. from nltk.grammar import Nonterminal
  9. from nltk.tree import Tree
  10. from nltk.parse.api import ParserI
  11. ##//////////////////////////////////////////////////////
  12. ## Shift/Reduce Parser
  13. ##//////////////////////////////////////////////////////
  14. class ShiftReduceParser(ParserI):
  15. """
  16. A simple bottom-up CFG parser that uses two operations, "shift"
  17. and "reduce", to find a single parse for a text.
  18. ``ShiftReduceParser`` maintains a stack, which records the
  19. structure of a portion of the text. This stack is a list of
  20. strings and Trees that collectively cover a portion of
  21. the text. For example, while parsing the sentence "the dog saw
  22. the man" with a typical grammar, ``ShiftReduceParser`` will produce
  23. the following stack, which covers "the dog saw"::
  24. [(NP: (Det: 'the') (N: 'dog')), (V: 'saw')]
  25. ``ShiftReduceParser`` attempts to extend the stack to cover the
  26. entire text, and to combine the stack elements into a single tree,
  27. producing a complete parse for the sentence.
  28. Initially, the stack is empty. It is extended to cover the text,
  29. from left to right, by repeatedly applying two operations:
  30. - "shift" moves a token from the beginning of the text to the
  31. end of the stack.
  32. - "reduce" uses a CFG production to combine the rightmost stack
  33. elements into a single Tree.
  34. Often, more than one operation can be performed on a given stack.
  35. In this case, ``ShiftReduceParser`` uses the following heuristics
  36. to decide which operation to perform:
  37. - Only shift if no reductions are available.
  38. - If multiple reductions are available, then apply the reduction
  39. whose CFG production is listed earliest in the grammar.
  40. Note that these heuristics are not guaranteed to choose an
  41. operation that leads to a parse of the text. Also, if multiple
  42. parses exists, ``ShiftReduceParser`` will return at most one of
  43. them.
  44. :see: ``nltk.grammar``
  45. """
  46. def __init__(self, grammar, trace=0):
  47. """
  48. Create a new ``ShiftReduceParser``, that uses ``grammar`` to
  49. parse texts.
  50. :type grammar: Grammar
  51. :param grammar: The grammar used to parse texts.
  52. :type trace: int
  53. :param trace: The level of tracing that should be used when
  54. parsing a text. ``0`` will generate no tracing output;
  55. and higher numbers will produce more verbose tracing
  56. output.
  57. """
  58. self._grammar = grammar
  59. self._trace = trace
  60. self._check_grammar()
  61. def grammar(self):
  62. return self._grammar
  63. def parse(self, tokens):
  64. tokens = list(tokens)
  65. self._grammar.check_coverage(tokens)
  66. # initialize the stack.
  67. stack = []
  68. remaining_text = tokens
  69. # Trace output.
  70. if self._trace:
  71. print("Parsing %r" % " ".join(tokens))
  72. self._trace_stack(stack, remaining_text)
  73. # iterate through the text, pushing the token onto
  74. # the stack, then reducing the stack.
  75. while len(remaining_text) > 0:
  76. self._shift(stack, remaining_text)
  77. while self._reduce(stack, remaining_text):
  78. pass
  79. # Did we reduce everything?
  80. if len(stack) == 1:
  81. # Did we end up with the right category?
  82. if stack[0].label() == self._grammar.start().symbol():
  83. yield stack[0]
  84. def _shift(self, stack, remaining_text):
  85. """
  86. Move a token from the beginning of ``remaining_text`` to the
  87. end of ``stack``.
  88. :type stack: list(str and Tree)
  89. :param stack: A list of strings and Trees, encoding
  90. the structure of the text that has been parsed so far.
  91. :type remaining_text: list(str)
  92. :param remaining_text: The portion of the text that is not yet
  93. covered by ``stack``.
  94. :rtype: None
  95. """
  96. stack.append(remaining_text[0])
  97. remaining_text.remove(remaining_text[0])
  98. if self._trace:
  99. self._trace_shift(stack, remaining_text)
  100. def _match_rhs(self, rhs, rightmost_stack):
  101. """
  102. :rtype: bool
  103. :return: true if the right hand side of a CFG production
  104. matches the rightmost elements of the stack. ``rhs``
  105. matches ``rightmost_stack`` if they are the same length,
  106. and each element of ``rhs`` matches the corresponding
  107. element of ``rightmost_stack``. A nonterminal element of
  108. ``rhs`` matches any Tree whose node value is equal
  109. to the nonterminal's symbol. A terminal element of ``rhs``
  110. matches any string whose type is equal to the terminal.
  111. :type rhs: list(terminal and Nonterminal)
  112. :param rhs: The right hand side of a CFG production.
  113. :type rightmost_stack: list(string and Tree)
  114. :param rightmost_stack: The rightmost elements of the parser's
  115. stack.
  116. """
  117. if len(rightmost_stack) != len(rhs):
  118. return False
  119. for i in range(len(rightmost_stack)):
  120. if isinstance(rightmost_stack[i], Tree):
  121. if not isinstance(rhs[i], Nonterminal):
  122. return False
  123. if rightmost_stack[i].label() != rhs[i].symbol():
  124. return False
  125. else:
  126. if isinstance(rhs[i], Nonterminal):
  127. return False
  128. if rightmost_stack[i] != rhs[i]:
  129. return False
  130. return True
  131. def _reduce(self, stack, remaining_text, production=None):
  132. """
  133. Find a CFG production whose right hand side matches the
  134. rightmost stack elements; and combine those stack elements
  135. into a single Tree, with the node specified by the
  136. production's left-hand side. If more than one CFG production
  137. matches the stack, then use the production that is listed
  138. earliest in the grammar. The new Tree replaces the
  139. elements in the stack.
  140. :rtype: Production or None
  141. :return: If a reduction is performed, then return the CFG
  142. production that the reduction is based on; otherwise,
  143. return false.
  144. :type stack: list(string and Tree)
  145. :param stack: A list of strings and Trees, encoding
  146. the structure of the text that has been parsed so far.
  147. :type remaining_text: list(str)
  148. :param remaining_text: The portion of the text that is not yet
  149. covered by ``stack``.
  150. """
  151. if production is None:
  152. productions = self._grammar.productions()
  153. else:
  154. productions = [production]
  155. # Try each production, in order.
  156. for production in productions:
  157. rhslen = len(production.rhs())
  158. # check if the RHS of a production matches the top of the stack
  159. if self._match_rhs(production.rhs(), stack[-rhslen:]):
  160. # combine the tree to reflect the reduction
  161. tree = Tree(production.lhs().symbol(), stack[-rhslen:])
  162. stack[-rhslen:] = [tree]
  163. # We reduced something
  164. if self._trace:
  165. self._trace_reduce(stack, production, remaining_text)
  166. return production
  167. # We didn't reduce anything
  168. return None
  169. def trace(self, trace=2):
  170. """
  171. Set the level of tracing output that should be generated when
  172. parsing a text.
  173. :type trace: int
  174. :param trace: The trace level. A trace level of ``0`` will
  175. generate no tracing output; and higher trace levels will
  176. produce more verbose tracing output.
  177. :rtype: None
  178. """
  179. # 1: just show shifts.
  180. # 2: show shifts & reduces
  181. # 3: display which tokens & productions are shifed/reduced
  182. self._trace = trace
  183. def _trace_stack(self, stack, remaining_text, marker=" "):
  184. """
  185. Print trace output displaying the given stack and text.
  186. :rtype: None
  187. :param marker: A character that is printed to the left of the
  188. stack. This is used with trace level 2 to print 'S'
  189. before shifted stacks and 'R' before reduced stacks.
  190. """
  191. s = " " + marker + " [ "
  192. for elt in stack:
  193. if isinstance(elt, Tree):
  194. s += repr(Nonterminal(elt.label())) + " "
  195. else:
  196. s += repr(elt) + " "
  197. s += "* " + " ".join(remaining_text) + "]"
  198. print(s)
  199. def _trace_shift(self, stack, remaining_text):
  200. """
  201. Print trace output displaying that a token has been shifted.
  202. :rtype: None
  203. """
  204. if self._trace > 2:
  205. print("Shift %r:" % stack[-1])
  206. if self._trace == 2:
  207. self._trace_stack(stack, remaining_text, "S")
  208. elif self._trace > 0:
  209. self._trace_stack(stack, remaining_text)
  210. def _trace_reduce(self, stack, production, remaining_text):
  211. """
  212. Print trace output displaying that ``production`` was used to
  213. reduce ``stack``.
  214. :rtype: None
  215. """
  216. if self._trace > 2:
  217. rhs = " ".join(production.rhs())
  218. print("Reduce %r <- %s" % (production.lhs(), rhs))
  219. if self._trace == 2:
  220. self._trace_stack(stack, remaining_text, "R")
  221. elif self._trace > 1:
  222. self._trace_stack(stack, remaining_text)
  223. def _check_grammar(self):
  224. """
  225. Check to make sure that all of the CFG productions are
  226. potentially useful. If any productions can never be used,
  227. then print a warning.
  228. :rtype: None
  229. """
  230. productions = self._grammar.productions()
  231. # Any production whose RHS is an extension of another production's RHS
  232. # will never be used.
  233. for i in range(len(productions)):
  234. for j in range(i + 1, len(productions)):
  235. rhs1 = productions[i].rhs()
  236. rhs2 = productions[j].rhs()
  237. if rhs1[: len(rhs2)] == rhs2:
  238. print("Warning: %r will never be used" % productions[i])
  239. ##//////////////////////////////////////////////////////
  240. ## Stepping Shift/Reduce Parser
  241. ##//////////////////////////////////////////////////////
  242. class SteppingShiftReduceParser(ShiftReduceParser):
  243. """
  244. A ``ShiftReduceParser`` that allows you to setp through the parsing
  245. process, performing a single operation at a time. It also allows
  246. you to change the parser's grammar midway through parsing a text.
  247. The ``initialize`` method is used to start parsing a text.
  248. ``shift`` performs a single shift operation, and ``reduce`` performs
  249. a single reduce operation. ``step`` will perform a single reduce
  250. operation if possible; otherwise, it will perform a single shift
  251. operation. ``parses`` returns the set of parses that have been
  252. found by the parser.
  253. :ivar _history: A list of ``(stack, remaining_text)`` pairs,
  254. containing all of the previous states of the parser. This
  255. history is used to implement the ``undo`` operation.
  256. :see: ``nltk.grammar``
  257. """
  258. def __init__(self, grammar, trace=0):
  259. super(SteppingShiftReduceParser, self).__init__(grammar, trace)
  260. self._stack = None
  261. self._remaining_text = None
  262. self._history = []
  263. def parse(self, tokens):
  264. tokens = list(tokens)
  265. self.initialize(tokens)
  266. while self.step():
  267. pass
  268. return self.parses()
  269. def stack(self):
  270. """
  271. :return: The parser's stack.
  272. :rtype: list(str and Tree)
  273. """
  274. return self._stack
  275. def remaining_text(self):
  276. """
  277. :return: The portion of the text that is not yet covered by the
  278. stack.
  279. :rtype: list(str)
  280. """
  281. return self._remaining_text
  282. def initialize(self, tokens):
  283. """
  284. Start parsing a given text. This sets the parser's stack to
  285. ``[]`` and sets its remaining text to ``tokens``.
  286. """
  287. self._stack = []
  288. self._remaining_text = tokens
  289. self._history = []
  290. def step(self):
  291. """
  292. Perform a single parsing operation. If a reduction is
  293. possible, then perform that reduction, and return the
  294. production that it is based on. Otherwise, if a shift is
  295. possible, then perform it, and return True. Otherwise,
  296. return False.
  297. :return: False if no operation was performed; True if a shift was
  298. performed; and the CFG production used to reduce if a
  299. reduction was performed.
  300. :rtype: Production or bool
  301. """
  302. return self.reduce() or self.shift()
  303. def shift(self):
  304. """
  305. Move a token from the beginning of the remaining text to the
  306. end of the stack. If there are no more tokens in the
  307. remaining text, then do nothing.
  308. :return: True if the shift operation was successful.
  309. :rtype: bool
  310. """
  311. if len(self._remaining_text) == 0:
  312. return False
  313. self._history.append((self._stack[:], self._remaining_text[:]))
  314. self._shift(self._stack, self._remaining_text)
  315. return True
  316. def reduce(self, production=None):
  317. """
  318. Use ``production`` to combine the rightmost stack elements into
  319. a single Tree. If ``production`` does not match the
  320. rightmost stack elements, then do nothing.
  321. :return: The production used to reduce the stack, if a
  322. reduction was performed. If no reduction was performed,
  323. return None.
  324. :rtype: Production or None
  325. """
  326. self._history.append((self._stack[:], self._remaining_text[:]))
  327. return_val = self._reduce(self._stack, self._remaining_text, production)
  328. if not return_val:
  329. self._history.pop()
  330. return return_val
  331. def undo(self):
  332. """
  333. Return the parser to its state before the most recent
  334. shift or reduce operation. Calling ``undo`` repeatedly return
  335. the parser to successively earlier states. If no shift or
  336. reduce operations have been performed, ``undo`` will make no
  337. changes.
  338. :return: true if an operation was successfully undone.
  339. :rtype: bool
  340. """
  341. if len(self._history) == 0:
  342. return False
  343. (self._stack, self._remaining_text) = self._history.pop()
  344. return True
  345. def reducible_productions(self):
  346. """
  347. :return: A list of the productions for which reductions are
  348. available for the current parser state.
  349. :rtype: list(Production)
  350. """
  351. productions = []
  352. for production in self._grammar.productions():
  353. rhslen = len(production.rhs())
  354. if self._match_rhs(production.rhs(), self._stack[-rhslen:]):
  355. productions.append(production)
  356. return productions
  357. def parses(self):
  358. """
  359. :return: An iterator of the parses that have been found by this
  360. parser so far.
  361. :rtype: iter(Tree)
  362. """
  363. if (
  364. len(self._remaining_text) == 0
  365. and len(self._stack) == 1
  366. and self._stack[0].label() == self._grammar.start().symbol()
  367. ):
  368. yield self._stack[0]
  369. # copied from nltk.parser
  370. def set_grammar(self, grammar):
  371. """
  372. Change the grammar used to parse texts.
  373. :param grammar: The new grammar.
  374. :type grammar: CFG
  375. """
  376. self._grammar = grammar
  377. ##//////////////////////////////////////////////////////
  378. ## Demonstration Code
  379. ##//////////////////////////////////////////////////////
  380. def demo():
  381. """
  382. A demonstration of the shift-reduce parser.
  383. """
  384. from nltk import parse, CFG
  385. grammar = CFG.fromstring(
  386. """
  387. S -> NP VP
  388. NP -> Det N | Det N PP
  389. VP -> V NP | V NP PP
  390. PP -> P NP
  391. NP -> 'I'
  392. N -> 'man' | 'park' | 'telescope' | 'dog'
  393. Det -> 'the' | 'a'
  394. P -> 'in' | 'with'
  395. V -> 'saw'
  396. """
  397. )
  398. sent = "I saw a man in the park".split()
  399. parser = parse.ShiftReduceParser(grammar, trace=2)
  400. for p in parser.parse(sent):
  401. print(p)
  402. if __name__ == "__main__":
  403. demo()