Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/lark/lark.py: 51%
330 statements
« prev ^ index » next coverage.py v7.4.1, created at 2024-02-14 06:19 +0000
« prev ^ index » next coverage.py v7.4.1, created at 2024-02-14 06:19 +0000
1from abc import ABC, abstractmethod
2import getpass
3import sys, os, pickle
4import tempfile
5import types
6import re
7from typing import (
8 TypeVar, Type, List, Dict, Iterator, Callable, Union, Optional, Sequence,
9 Tuple, Iterable, IO, Any, TYPE_CHECKING, Collection
10)
11if TYPE_CHECKING:
12 from .parsers.lalr_interactive_parser import InteractiveParser
13 from .tree import ParseTree
14 from .visitors import Transformer
15 if sys.version_info >= (3, 8):
16 from typing import Literal
17 else:
18 from typing_extensions import Literal
19 from .parser_frontends import ParsingFrontend
21from .exceptions import ConfigurationError, assert_config, UnexpectedInput
22from .utils import Serialize, SerializeMemoizer, FS, isascii, logger
23from .load_grammar import load_grammar, FromPackageLoader, Grammar, verify_used_files, PackageResource, sha256_digest
24from .tree import Tree
25from .common import LexerConf, ParserConf, _ParserArgType, _LexerArgType
27from .lexer import Lexer, BasicLexer, TerminalDef, LexerThread, Token
28from .parse_tree_builder import ParseTreeBuilder
29from .parser_frontends import _validate_frontend_args, _get_lexer_callbacks, _deserialize_parsing_frontend, _construct_parsing_frontend
30from .grammar import Rule
33try:
34 import regex
35 _has_regex = True
36except ImportError:
37 _has_regex = False
40###{standalone
43class PostLex(ABC):
44 @abstractmethod
45 def process(self, stream: Iterator[Token]) -> Iterator[Token]:
46 return stream
48 always_accept: Iterable[str] = ()
50class LarkOptions(Serialize):
51 """Specifies the options for Lark
53 """
55 start: List[str]
56 debug: bool
57 strict: bool
58 transformer: 'Optional[Transformer]'
59 propagate_positions: Union[bool, str]
60 maybe_placeholders: bool
61 cache: Union[bool, str]
62 regex: bool
63 g_regex_flags: int
64 keep_all_tokens: bool
65 tree_class: Optional[Callable[[str, List], Any]]
66 parser: _ParserArgType
67 lexer: _LexerArgType
68 ambiguity: 'Literal["auto", "resolve", "explicit", "forest"]'
69 postlex: Optional[PostLex]
70 priority: 'Optional[Literal["auto", "normal", "invert"]]'
71 lexer_callbacks: Dict[str, Callable[[Token], Token]]
72 use_bytes: bool
73 ordered_sets: bool
74 edit_terminals: Optional[Callable[[TerminalDef], TerminalDef]]
75 import_paths: 'List[Union[str, Callable[[Union[None, str, PackageResource], str], Tuple[str, str]]]]'
76 source_path: Optional[str]
78 OPTIONS_DOC = r"""
79 **=== General Options ===**
81 start
82 The start symbol. Either a string, or a list of strings for multiple possible starts (Default: "start")
83 debug
84 Display debug information and extra warnings. Use only when debugging (Default: ``False``)
85 When used with Earley, it generates a forest graph as "sppf.png", if 'dot' is installed.
86 strict
87 Throw an exception on any potential ambiguity, including shift/reduce conflicts, and regex collisions.
88 transformer
89 Applies the transformer to every parse tree (equivalent to applying it after the parse, but faster)
90 propagate_positions
91 Propagates positional attributes into the 'meta' attribute of all tree branches.
92 Sets attributes: (line, column, end_line, end_column, start_pos, end_pos,
93 container_line, container_column, container_end_line, container_end_column)
94 Accepts ``False``, ``True``, or a callable, which will filter which nodes to ignore when propagating.
95 maybe_placeholders
96 When ``True``, the ``[]`` operator returns ``None`` when not matched.
97 When ``False``, ``[]`` behaves like the ``?`` operator, and returns no value at all.
98 (default= ``True``)
99 cache
100 Cache the results of the Lark grammar analysis, for x2 to x3 faster loading. LALR only for now.
102 - When ``False``, does nothing (default)
103 - When ``True``, caches to a temporary file in the local directory
104 - When given a string, caches to the path pointed by the string
105 regex
106 When True, uses the ``regex`` module instead of the stdlib ``re``.
107 g_regex_flags
108 Flags that are applied to all terminals (both regex and strings)
109 keep_all_tokens
110 Prevent the tree builder from automagically removing "punctuation" tokens (Default: ``False``)
111 tree_class
112 Lark will produce trees comprised of instances of this class instead of the default ``lark.Tree``.
114 **=== Algorithm Options ===**
116 parser
117 Decides which parser engine to use. Accepts "earley" or "lalr". (Default: "earley").
118 (there is also a "cyk" option for legacy)
119 lexer
120 Decides whether or not to use a lexer stage
122 - "auto" (default): Choose for me based on the parser
123 - "basic": Use a basic lexer
124 - "contextual": Stronger lexer (only works with parser="lalr")
125 - "dynamic": Flexible and powerful (only with parser="earley")
126 - "dynamic_complete": Same as dynamic, but tries *every* variation of tokenizing possible.
127 ambiguity
128 Decides how to handle ambiguity in the parse. Only relevant if parser="earley"
130 - "resolve": The parser will automatically choose the simplest derivation
131 (it chooses consistently: greedy for tokens, non-greedy for rules)
132 - "explicit": The parser will return all derivations wrapped in "_ambig" tree nodes (i.e. a forest).
133 - "forest": The parser will return the root of the shared packed parse forest.
135 **=== Misc. / Domain Specific Options ===**
137 postlex
138 Lexer post-processing (Default: ``None``) Only works with the basic and contextual lexers.
139 priority
140 How priorities should be evaluated - "auto", ``None``, "normal", "invert" (Default: "auto")
141 lexer_callbacks
142 Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution.
143 use_bytes
144 Accept an input of type ``bytes`` instead of ``str``.
145 ordered_sets
146 Should Earley use ordered-sets to achieve stable output (~10% slower than regular sets. Default: True)
147 edit_terminals
148 A callback for editing the terminals before parse.
149 import_paths
150 A List of either paths or loader functions to specify from where grammars are imported
151 source_path
152 Override the source of from where the grammar was loaded. Useful for relative imports and unconventional grammar loading
153 **=== End of Options ===**
154 """
155 if __doc__:
156 __doc__ += OPTIONS_DOC
159 # Adding a new option needs to be done in multiple places:
160 # - In the dictionary below. This is the primary truth of which options `Lark.__init__` accepts
161 # - In the docstring above. It is used both for the docstring of `LarkOptions` and `Lark`, and in readthedocs
162 # - As an attribute of `LarkOptions` above
163 # - Potentially in `_LOAD_ALLOWED_OPTIONS` below this class, when the option doesn't change how the grammar is loaded
164 # - Potentially in `lark.tools.__init__`, if it makes sense, and it can easily be passed as a cmd argument
165 _defaults: Dict[str, Any] = {
166 'debug': False,
167 'strict': False,
168 'keep_all_tokens': False,
169 'tree_class': None,
170 'cache': False,
171 'postlex': None,
172 'parser': 'earley',
173 'lexer': 'auto',
174 'transformer': None,
175 'start': 'start',
176 'priority': 'auto',
177 'ambiguity': 'auto',
178 'regex': False,
179 'propagate_positions': False,
180 'lexer_callbacks': {},
181 'maybe_placeholders': True,
182 'edit_terminals': None,
183 'g_regex_flags': 0,
184 'use_bytes': False,
185 'ordered_sets': True,
186 'import_paths': [],
187 'source_path': None,
188 '_plugins': {},
189 }
191 def __init__(self, options_dict: Dict[str, Any]) -> None:
192 o = dict(options_dict)
194 options = {}
195 for name, default in self._defaults.items():
196 if name in o:
197 value = o.pop(name)
198 if isinstance(default, bool) and name not in ('cache', 'use_bytes', 'propagate_positions'):
199 value = bool(value)
200 else:
201 value = default
203 options[name] = value
205 if isinstance(options['start'], str):
206 options['start'] = [options['start']]
208 self.__dict__['options'] = options
211 assert_config(self.parser, ('earley', 'lalr', 'cyk', None))
213 if self.parser == 'earley' and self.transformer:
214 raise ConfigurationError('Cannot specify an embedded transformer when using the Earley algorithm. '
215 'Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. LALR)')
217 if o:
218 raise ConfigurationError("Unknown options: %s" % o.keys())
220 def __getattr__(self, name: str) -> Any:
221 try:
222 return self.__dict__['options'][name]
223 except KeyError as e:
224 raise AttributeError(e)
226 def __setattr__(self, name: str, value: str) -> None:
227 assert_config(name, self.options.keys(), "%r isn't a valid option. Expected one of: %s")
228 self.options[name] = value
230 def serialize(self, memo = None) -> Dict[str, Any]:
231 return self.options
233 @classmethod
234 def deserialize(cls, data: Dict[str, Any], memo: Dict[int, Union[TerminalDef, Rule]]) -> "LarkOptions":
235 return cls(data)
238# Options that can be passed to the Lark parser, even when it was loaded from cache/standalone.
239# These options are only used outside of `load_grammar`.
240_LOAD_ALLOWED_OPTIONS = {'postlex', 'transformer', 'lexer_callbacks', 'use_bytes', 'debug', 'g_regex_flags', 'regex', 'propagate_positions', 'tree_class', '_plugins'}
242_VALID_PRIORITY_OPTIONS = ('auto', 'normal', 'invert', None)
243_VALID_AMBIGUITY_OPTIONS = ('auto', 'resolve', 'explicit', 'forest')
246_T = TypeVar('_T', bound="Lark")
248class Lark(Serialize):
249 """Main interface for the library.
251 It's mostly a thin wrapper for the many different parsers, and for the tree constructor.
253 Parameters:
254 grammar: a string or file-object containing the grammar spec (using Lark's ebnf syntax)
255 options: a dictionary controlling various aspects of Lark.
257 Example:
258 >>> Lark(r'''start: "foo" ''')
259 Lark(...)
260 """
262 source_path: str
263 source_grammar: str
264 grammar: 'Grammar'
265 options: LarkOptions
266 lexer: Lexer
267 parser: 'ParsingFrontend'
268 terminals: Collection[TerminalDef]
270 def __init__(self, grammar: 'Union[Grammar, str, IO[str]]', **options) -> None:
271 self.options = LarkOptions(options)
272 re_module: types.ModuleType
274 # Set regex or re module
275 use_regex = self.options.regex
276 if use_regex:
277 if _has_regex:
278 re_module = regex
279 else:
280 raise ImportError('`regex` module must be installed if calling `Lark(regex=True)`.')
281 else:
282 re_module = re
284 # Some, but not all file-like objects have a 'name' attribute
285 if self.options.source_path is None:
286 try:
287 self.source_path = grammar.name # type: ignore[union-attr]
288 except AttributeError:
289 self.source_path = '<string>'
290 else:
291 self.source_path = self.options.source_path
293 # Drain file-like objects to get their contents
294 try:
295 read = grammar.read # type: ignore[union-attr]
296 except AttributeError:
297 pass
298 else:
299 grammar = read()
301 cache_fn = None
302 cache_sha256 = None
303 if isinstance(grammar, str):
304 self.source_grammar = grammar
305 if self.options.use_bytes:
306 if not isascii(grammar):
307 raise ConfigurationError("Grammar must be ascii only, when use_bytes=True")
309 if self.options.cache:
310 if self.options.parser != 'lalr':
311 raise ConfigurationError("cache only works with parser='lalr' for now")
313 unhashable = ('transformer', 'postlex', 'lexer_callbacks', 'edit_terminals', '_plugins')
314 options_str = ''.join(k+str(v) for k, v in options.items() if k not in unhashable)
315 from . import __version__
316 s = grammar + options_str + __version__ + str(sys.version_info[:2])
317 cache_sha256 = sha256_digest(s)
319 if isinstance(self.options.cache, str):
320 cache_fn = self.options.cache
321 else:
322 if self.options.cache is not True:
323 raise ConfigurationError("cache argument must be bool or str")
325 try:
326 username = getpass.getuser()
327 except Exception:
328 # The exception raised may be ImportError or OSError in
329 # the future. For the cache, we don't care about the
330 # specific reason - we just want a username.
331 username = "unknown"
333 cache_fn = tempfile.gettempdir() + "/.lark_cache_%s_%s_%s_%s.tmp" % (username, cache_sha256, *sys.version_info[:2])
335 old_options = self.options
336 try:
337 with FS.open(cache_fn, 'rb') as f:
338 logger.debug('Loading grammar from cache: %s', cache_fn)
339 # Remove options that aren't relevant for loading from cache
340 for name in (set(options) - _LOAD_ALLOWED_OPTIONS):
341 del options[name]
342 file_sha256 = f.readline().rstrip(b'\n')
343 cached_used_files = pickle.load(f)
344 if file_sha256 == cache_sha256.encode('utf8') and verify_used_files(cached_used_files):
345 cached_parser_data = pickle.load(f)
346 self._load(cached_parser_data, **options)
347 return
348 except FileNotFoundError:
349 # The cache file doesn't exist; parse and compose the grammar as normal
350 pass
351 except Exception: # We should probably narrow done which errors we catch here.
352 logger.exception("Failed to load Lark from cache: %r. We will try to carry on.", cache_fn)
354 # In theory, the Lark instance might have been messed up by the call to `_load`.
355 # In practice the only relevant thing that might have been overwritten should be `options`
356 self.options = old_options
359 # Parse the grammar file and compose the grammars
360 self.grammar, used_files = load_grammar(grammar, self.source_path, self.options.import_paths, self.options.keep_all_tokens)
361 else:
362 assert isinstance(grammar, Grammar)
363 self.grammar = grammar
366 if self.options.lexer == 'auto':
367 if self.options.parser == 'lalr':
368 self.options.lexer = 'contextual'
369 elif self.options.parser == 'earley':
370 if self.options.postlex is not None:
371 logger.info("postlex can't be used with the dynamic lexer, so we use 'basic' instead. "
372 "Consider using lalr with contextual instead of earley")
373 self.options.lexer = 'basic'
374 else:
375 self.options.lexer = 'dynamic'
376 elif self.options.parser == 'cyk':
377 self.options.lexer = 'basic'
378 else:
379 assert False, self.options.parser
380 lexer = self.options.lexer
381 if isinstance(lexer, type):
382 assert issubclass(lexer, Lexer) # XXX Is this really important? Maybe just ensure interface compliance
383 else:
384 assert_config(lexer, ('basic', 'contextual', 'dynamic', 'dynamic_complete'))
385 if self.options.postlex is not None and 'dynamic' in lexer:
386 raise ConfigurationError("Can't use postlex with a dynamic lexer. Use basic or contextual instead")
388 if self.options.ambiguity == 'auto':
389 if self.options.parser == 'earley':
390 self.options.ambiguity = 'resolve'
391 else:
392 assert_config(self.options.parser, ('earley', 'cyk'), "%r doesn't support disambiguation. Use one of these parsers instead: %s")
394 if self.options.priority == 'auto':
395 self.options.priority = 'normal'
397 if self.options.priority not in _VALID_PRIORITY_OPTIONS:
398 raise ConfigurationError("invalid priority option: %r. Must be one of %r" % (self.options.priority, _VALID_PRIORITY_OPTIONS))
399 if self.options.ambiguity not in _VALID_AMBIGUITY_OPTIONS:
400 raise ConfigurationError("invalid ambiguity option: %r. Must be one of %r" % (self.options.ambiguity, _VALID_AMBIGUITY_OPTIONS))
402 if self.options.parser is None:
403 terminals_to_keep = '*'
404 elif self.options.postlex is not None:
405 terminals_to_keep = set(self.options.postlex.always_accept)
406 else:
407 terminals_to_keep = set()
409 # Compile the EBNF grammar into BNF
410 self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start, terminals_to_keep)
412 if self.options.edit_terminals:
413 for t in self.terminals:
414 self.options.edit_terminals(t)
416 self._terminals_dict = {t.name: t for t in self.terminals}
418 # If the user asked to invert the priorities, negate them all here.
419 if self.options.priority == 'invert':
420 for rule in self.rules:
421 if rule.options.priority is not None:
422 rule.options.priority = -rule.options.priority
423 for term in self.terminals:
424 term.priority = -term.priority
425 # Else, if the user asked to disable priorities, strip them from the
426 # rules and terminals. This allows the Earley parsers to skip an extra forest walk
427 # for improved performance, if you don't need them (or didn't specify any).
428 elif self.options.priority is None:
429 for rule in self.rules:
430 if rule.options.priority is not None:
431 rule.options.priority = None
432 for term in self.terminals:
433 term.priority = 0
435 # TODO Deprecate lexer_callbacks?
436 self.lexer_conf = LexerConf(
437 self.terminals, re_module, self.ignore_tokens, self.options.postlex,
438 self.options.lexer_callbacks, self.options.g_regex_flags, use_bytes=self.options.use_bytes, strict=self.options.strict
439 )
441 if self.options.parser:
442 self.parser = self._build_parser()
443 elif lexer:
444 self.lexer = self._build_lexer()
446 if cache_fn:
447 logger.debug('Saving grammar to cache: %s', cache_fn)
448 try:
449 with FS.open(cache_fn, 'wb') as f:
450 assert cache_sha256 is not None
451 f.write(cache_sha256.encode('utf8') + b'\n')
452 pickle.dump(used_files, f)
453 self.save(f, _LOAD_ALLOWED_OPTIONS)
454 except IOError as e:
455 logger.exception("Failed to save Lark to cache: %r.", cache_fn, e)
457 if __doc__:
458 __doc__ += "\n\n" + LarkOptions.OPTIONS_DOC
460 __serialize_fields__ = 'parser', 'rules', 'options'
462 def _build_lexer(self, dont_ignore: bool=False) -> BasicLexer:
463 lexer_conf = self.lexer_conf
464 if dont_ignore:
465 from copy import copy
466 lexer_conf = copy(lexer_conf)
467 lexer_conf.ignore = ()
468 return BasicLexer(lexer_conf)
470 def _prepare_callbacks(self) -> None:
471 self._callbacks = {}
472 # we don't need these callbacks if we aren't building a tree
473 if self.options.ambiguity != 'forest':
474 self._parse_tree_builder = ParseTreeBuilder(
475 self.rules,
476 self.options.tree_class or Tree,
477 self.options.propagate_positions,
478 self.options.parser != 'lalr' and self.options.ambiguity == 'explicit',
479 self.options.maybe_placeholders
480 )
481 self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
482 self._callbacks.update(_get_lexer_callbacks(self.options.transformer, self.terminals))
484 def _build_parser(self) -> "ParsingFrontend":
485 self._prepare_callbacks()
486 _validate_frontend_args(self.options.parser, self.options.lexer)
487 parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
488 return _construct_parsing_frontend(
489 self.options.parser,
490 self.options.lexer,
491 self.lexer_conf,
492 parser_conf,
493 options=self.options
494 )
496 def save(self, f, exclude_options: Collection[str] = ()) -> None:
497 """Saves the instance into the given file object
499 Useful for caching and multiprocessing.
500 """
501 if self.options.parser != 'lalr':
502 raise NotImplementedError("Lark.save() is only implemented for the LALR(1) parser.")
503 data, m = self.memo_serialize([TerminalDef, Rule])
504 if exclude_options:
505 data["options"] = {n: v for n, v in data["options"].items() if n not in exclude_options}
506 pickle.dump({'data': data, 'memo': m}, f, protocol=pickle.HIGHEST_PROTOCOL)
508 @classmethod
509 def load(cls: Type[_T], f) -> _T:
510 """Loads an instance from the given file object
512 Useful for caching and multiprocessing.
513 """
514 inst = cls.__new__(cls)
515 return inst._load(f)
517 def _deserialize_lexer_conf(self, data: Dict[str, Any], memo: Dict[int, Union[TerminalDef, Rule]], options: LarkOptions) -> LexerConf:
518 lexer_conf = LexerConf.deserialize(data['lexer_conf'], memo)
519 lexer_conf.callbacks = options.lexer_callbacks or {}
520 lexer_conf.re_module = regex if options.regex else re
521 lexer_conf.use_bytes = options.use_bytes
522 lexer_conf.g_regex_flags = options.g_regex_flags
523 lexer_conf.skip_validation = True
524 lexer_conf.postlex = options.postlex
525 return lexer_conf
527 def _load(self: _T, f: Any, **kwargs) -> _T:
528 if isinstance(f, dict):
529 d = f
530 else:
531 d = pickle.load(f)
532 memo_json = d['memo']
533 data = d['data']
535 assert memo_json
536 memo = SerializeMemoizer.deserialize(memo_json, {'Rule': Rule, 'TerminalDef': TerminalDef}, {})
537 options = dict(data['options'])
538 if (set(kwargs) - _LOAD_ALLOWED_OPTIONS) & set(LarkOptions._defaults):
539 raise ConfigurationError("Some options are not allowed when loading a Parser: {}"
540 .format(set(kwargs) - _LOAD_ALLOWED_OPTIONS))
541 options.update(kwargs)
542 self.options = LarkOptions.deserialize(options, memo)
543 self.rules = [Rule.deserialize(r, memo) for r in data['rules']]
544 self.source_path = '<deserialized>'
545 _validate_frontend_args(self.options.parser, self.options.lexer)
546 self.lexer_conf = self._deserialize_lexer_conf(data['parser'], memo, self.options)
547 self.terminals = self.lexer_conf.terminals
548 self._prepare_callbacks()
549 self._terminals_dict = {t.name: t for t in self.terminals}
550 self.parser = _deserialize_parsing_frontend(
551 data['parser'],
552 memo,
553 self.lexer_conf,
554 self._callbacks,
555 self.options, # Not all, but multiple attributes are used
556 )
557 return self
559 @classmethod
560 def _load_from_dict(cls, data, memo, **kwargs):
561 inst = cls.__new__(cls)
562 return inst._load({'data': data, 'memo': memo}, **kwargs)
564 @classmethod
565 def open(cls: Type[_T], grammar_filename: str, rel_to: Optional[str]=None, **options) -> _T:
566 """Create an instance of Lark with the grammar given by its filename
568 If ``rel_to`` is provided, the function will find the grammar filename in relation to it.
570 Example:
572 >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
573 Lark(...)
575 """
576 if rel_to:
577 basepath = os.path.dirname(rel_to)
578 grammar_filename = os.path.join(basepath, grammar_filename)
579 with open(grammar_filename, encoding='utf8') as f:
580 return cls(f, **options)
582 @classmethod
583 def open_from_package(cls: Type[_T], package: str, grammar_path: str, search_paths: 'Sequence[str]'=[""], **options) -> _T:
584 """Create an instance of Lark with the grammar loaded from within the package `package`.
585 This allows grammar loading from zipapps.
587 Imports in the grammar will use the `package` and `search_paths` provided, through `FromPackageLoader`
589 Example:
591 Lark.open_from_package(__name__, "example.lark", ("grammars",), parser=...)
592 """
593 package_loader = FromPackageLoader(package, search_paths)
594 full_path, text = package_loader(None, grammar_path)
595 options.setdefault('source_path', full_path)
596 options.setdefault('import_paths', [])
597 options['import_paths'].append(package_loader)
598 return cls(text, **options)
600 def __repr__(self):
601 return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source_path, self.options.parser, self.options.lexer)
604 def lex(self, text: str, dont_ignore: bool=False) -> Iterator[Token]:
605 """Only lex (and postlex) the text, without parsing it. Only relevant when lexer='basic'
607 When dont_ignore=True, the lexer will return all tokens, even those marked for %ignore.
609 :raises UnexpectedCharacters: In case the lexer cannot find a suitable match.
610 """
611 lexer: Lexer
612 if not hasattr(self, 'lexer') or dont_ignore:
613 lexer = self._build_lexer(dont_ignore)
614 else:
615 lexer = self.lexer
616 lexer_thread = LexerThread.from_text(lexer, text)
617 stream = lexer_thread.lex(None)
618 if self.options.postlex:
619 return self.options.postlex.process(stream)
620 return stream
622 def get_terminal(self, name: str) -> TerminalDef:
623 """Get information about a terminal"""
624 return self._terminals_dict[name]
626 def parse_interactive(self, text: Optional[str]=None, start: Optional[str]=None) -> 'InteractiveParser':
627 """Start an interactive parsing session.
629 Parameters:
630 text (str, optional): Text to be parsed. Required for ``resume_parse()``.
631 start (str, optional): Start symbol
633 Returns:
634 A new InteractiveParser instance.
636 See Also: ``Lark.parse()``
637 """
638 return self.parser.parse_interactive(text, start=start)
640 def parse(self, text: str, start: Optional[str]=None, on_error: 'Optional[Callable[[UnexpectedInput], bool]]'=None) -> 'ParseTree':
641 """Parse the given text, according to the options provided.
643 Parameters:
644 text (str): Text to be parsed.
645 start (str, optional): Required if Lark was given multiple possible start symbols (using the start option).
646 on_error (function, optional): if provided, will be called on UnexpectedToken error. Return true to resume parsing.
647 LALR only. See examples/advanced/error_handling.py for an example of how to use on_error.
649 Returns:
650 If a transformer is supplied to ``__init__``, returns whatever is the
651 result of the transformation. Otherwise, returns a Tree instance.
653 :raises UnexpectedInput: On a parse error, one of these sub-exceptions will rise:
654 ``UnexpectedCharacters``, ``UnexpectedToken``, or ``UnexpectedEOF``.
655 For convenience, these sub-exceptions also inherit from ``ParserError`` and ``LexerError``.
657 """
658 return self.parser.parse(text, start=start, on_error=on_error)
661###}