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