33# Copyright (C) 2001-2023 NLTK Project
44# Author: Steven Bird <[email protected] > 55# Peter Ljunglöf <[email protected] > 6+ 67# URL: <https://www.nltk.org/>
78# For license information, see LICENSE.TXT
89#
1314from nltk .grammar import Nonterminal
1415
1516
17+ def is_recursive (grammar ):
18+ for prod in grammar .productions ():
19+ if prod .lhs () in prod .rhs ():
20+ return True
21+ return False
22+
23+
1624def generate (grammar , start = None , depth = None , n = None ):
1725 """
1826 Generates an iterator of all sentences from a CFG.
@@ -26,7 +34,11 @@ def generate(grammar, start=None, depth=None, n=None):
2634 if not start :
2735 start = grammar .start ()
2836 if depth is None :
29- depth = sys .maxsize
37+ if is_recursive (grammar ):
38+ # This seems to be an almost maximal safe default with Python 3:
39+ depth = (sys .getrecursionlimit () // 3 ) - 3
40+ else :
41+ depth = sys .maxsize
3042
3143 iter = _generate_all (grammar , [start ], depth )
3244
@@ -45,7 +57,8 @@ def _generate_all(grammar, items, depth):
4557 except RecursionError as error :
4658 # Helpful error message while still showing the recursion stack.
4759 raise RuntimeError (
48- "The grammar has rule(s) that yield infinite recursion!"
60+ "The grammar has rule(s) that yield infinite recursion!\n \
61+ Eventually use a lower 'depth', or a higher 'sys.setrecursionlimit()'."
4962 ) from error
5063 else :
5164 yield []
0 commit comments