Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/lark/lark.py: 53%
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, Generic, overload,
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, LarkInput
20from .load_grammar import load_grammar, FromPackageLoader, Grammar, verify_used_files, PackageResource, sha256_digest
22from .tree import Tree
23from .common import LexerConf, ParserConf, _ParserArgType, _LexerArgType
25from .lexer import Lexer, BasicLexer, TerminalDef, LexerThread, Token
26from .visitors import _Return_T
27from .parse_tree_builder import ParseTreeBuilder
28from .parser_frontends import _validate_frontend_args, _get_lexer_callbacks, _deserialize_parsing_frontend, _construct_parsing_frontend
29from .grammar import Rule
32try:
33 import regex
34 _has_regex = True
35except ImportError:
36 _has_regex = False
39###{standalone
42class PostLex(ABC):
43 @abstractmethod
44 def process(self, stream: Iterator[Token]) -> Iterator[Token]:
45 return stream
47 always_accept: Iterable[str] = ()
49class LarkOptions(Serialize):
50 """Specifies the options for Lark
52 """
54 start: List[str]
55 debug: bool
56 strict: bool
57 transformer: 'Optional[Transformer]'
58 propagate_positions: Union[bool, str]
59 maybe_placeholders: bool
60 cache: Union[bool, str]
61 cache_grammar: bool
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 cache_grammar
106 For use with ``cache`` option. When ``True``, the unanalyzed grammar is also included in the cache.
107 Useful for classes that require the ``Lark.grammar`` to be present (e.g. Reconstructor).
108 (default= ``False``)
109 regex
110 When True, uses the ``regex`` module instead of the stdlib ``re``.
111 g_regex_flags
112 Flags that are applied to all terminals (both regex and strings)
113 keep_all_tokens
114 Prevent the tree builder from automagically removing "punctuation" tokens (Default: ``False``)
115 tree_class
116 Lark will produce trees comprised of instances of this class instead of the default ``lark.Tree``.
118 **=== Algorithm Options ===**
120 parser
121 Decides which parser engine to use. Accepts "earley" or "lalr". (Default: "earley").
122 (there is also a "cyk" option for legacy)
123 lexer
124 Decides whether or not to use a lexer stage
126 - "auto" (default): Choose for me based on the parser
127 - "basic": Use a basic lexer
128 - "contextual": Stronger lexer (only works with parser="lalr")
129 - "dynamic": Flexible and powerful (only with parser="earley")
130 - "dynamic_complete": Same as dynamic, but tries *every* variation of tokenizing possible.
131 ambiguity
132 Decides how to handle ambiguity in the parse. Only relevant if parser="earley"
134 - "resolve": The parser will automatically choose the simplest derivation
135 (it chooses consistently: greedy for tokens, non-greedy for rules)
136 - "explicit": The parser will return all derivations wrapped in "_ambig" tree nodes (i.e. a forest).
137 - "forest": The parser will return the root of the shared packed parse forest.
139 **=== Misc. / Domain Specific Options ===**
141 postlex
142 Lexer post-processing (Default: ``None``) Only works with the basic and contextual lexers.
143 priority
144 How priorities should be evaluated - "auto", ``None``, "normal", "invert" (Default: "auto")
145 lexer_callbacks
146 Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution.
147 use_bytes
148 Accept an input of type ``bytes`` instead of ``str``.
149 ordered_sets
150 Should Earley use ordered-sets to achieve stable output (~10% slower than regular sets. Default: True)
151 edit_terminals
152 A callback for editing the terminals before parse.
153 import_paths
154 A List of either paths or loader functions to specify from where grammars are imported
155 source_path
156 Override the source of from where the grammar was loaded. Useful for relative imports and unconventional grammar loading
157 **=== End of Options ===**
158 """
159 if __doc__:
160 __doc__ += OPTIONS_DOC
163 # Adding a new option needs to be done in multiple places:
164 # - In the dictionary below. This is the primary truth of which options `Lark.__init__` accepts
165 # - In the docstring above. It is used both for the docstring of `LarkOptions` and `Lark`, and in readthedocs
166 # - As an attribute of `LarkOptions` above
167 # - Potentially in `_LOAD_ALLOWED_OPTIONS` below this class, when the option doesn't change how the grammar is loaded
168 # - Potentially in `lark.tools.__init__`, if it makes sense, and it can easily be passed as a cmd argument
169 _defaults: Dict[str, Any] = {
170 'debug': False,
171 'strict': False,
172 'keep_all_tokens': False,
173 'tree_class': None,
174 'cache': False,
175 'cache_grammar': False,
176 'postlex': None,
177 'parser': 'earley',
178 'lexer': 'auto',
179 'transformer': None,
180 'start': 'start',
181 'priority': 'auto',
182 'ambiguity': 'auto',
183 'regex': False,
184 'propagate_positions': False,
185 'lexer_callbacks': {},
186 'maybe_placeholders': True,
187 'edit_terminals': None,
188 'g_regex_flags': 0,
189 'use_bytes': False,
190 'ordered_sets': True,
191 'import_paths': [],
192 'source_path': None,
193 '_plugins': {},
194 }
196 def __init__(self, options_dict: Dict[str, Any]) -> None:
197 o = dict(options_dict)
199 options = {}
200 for name, default in self._defaults.items():
201 if name in o:
202 value = o.pop(name)
203 if isinstance(default, bool) and name not in ('cache', 'use_bytes', 'propagate_positions'):
204 value = bool(value)
205 else:
206 value = default
208 options[name] = value
210 if isinstance(options['start'], str):
211 options['start'] = [options['start']]
213 self.__dict__['options'] = options
216 assert_config(self.parser, ('earley', 'lalr', 'cyk', None))
218 if self.parser == 'earley' and self.transformer:
219 raise ConfigurationError('Cannot specify an embedded transformer when using the Earley algorithm. '
220 'Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. LALR)')
222 if self.cache_grammar and not self.cache:
223 raise ConfigurationError('cache_grammar cannot be set when cache is disabled')
225 if o:
226 raise ConfigurationError("Unknown options: %s" % o.keys())
228 def __getattr__(self, name: str) -> Any:
229 try:
230 return self.__dict__['options'][name]
231 except KeyError as e:
232 raise AttributeError(e)
234 def __setattr__(self, name: str, value: str) -> None:
235 assert_config(name, self.options.keys(), "%r isn't a valid option. Expected one of: %s")
236 self.options[name] = value
238 def serialize(self, memo = None) -> Dict[str, Any]:
239 return self.options
241 @classmethod
242 def deserialize(cls, data: Dict[str, Any], memo: Dict[int, Union[TerminalDef, Rule]]) -> "LarkOptions":
243 return cls(data)
246# Options that can be passed to the Lark parser, even when it was loaded from cache/standalone.
247# These options are only used outside of `load_grammar`.
248_LOAD_ALLOWED_OPTIONS = {'postlex', 'transformer', 'lexer_callbacks', 'use_bytes', 'debug', 'g_regex_flags', 'regex', 'propagate_positions', 'tree_class', '_plugins'}
250_VALID_PRIORITY_OPTIONS = ('auto', 'normal', 'invert', None)
251_VALID_AMBIGUITY_OPTIONS = ('auto', 'resolve', 'explicit', 'forest')
254_T = TypeVar('_T', bound="Lark")
255_InitReturn_T = TypeVar('_InitReturn_T') # __init__ self annotations must use a new type-var
257class Lark(Serialize, Generic[_Return_T]):
258 """Main interface for the library.
260 It's mostly a thin wrapper for the many different parsers, and for the tree constructor.
262 Parameters:
263 grammar: a string or file-object containing the grammar spec (using Lark's ebnf syntax)
264 options: a dictionary controlling various aspects of Lark.
266 Example:
267 >>> Lark(r'''start: "foo" ''')
268 Lark(...)
269 """
271 source_path: str
272 source_grammar: str
273 grammar: 'Grammar'
274 options: LarkOptions
275 lexer: Lexer
276 parser: 'ParsingFrontend'
277 terminals: Collection[TerminalDef]
279 __serialize_fields__ = ['parser', 'rules', 'options']
281 @overload
282 def __init__(
283 self: 'Lark[_InitReturn_T]',
284 grammar: 'Union[Grammar, str, IO[str]]',
285 *,
286 transformer: 'Transformer[Token, _InitReturn_T]',
287 **options: Any,
288 ) -> None: ...
290 @overload
291 def __init__(
292 self: 'Lark[ParseTree]',
293 grammar: 'Union[Grammar, str, IO[str]]',
294 **options: Any,
295 ) -> None: ...
297 def __init__(self, grammar: 'Union[Grammar, str, IO[str]]', **options) -> None:
298 self.options = LarkOptions(options)
299 re_module: types.ModuleType
301 # Update which fields are serialized
302 if self.options.cache_grammar:
303 self.__serialize_fields__ = self.__serialize_fields__ + ['grammar']
305 # Set regex or re module
306 use_regex = self.options.regex
307 if use_regex:
308 if _has_regex:
309 re_module = regex
310 else:
311 raise ImportError('`regex` module must be installed if calling `Lark(regex=True)`.')
312 else:
313 re_module = re
315 # Some, but not all file-like objects have a 'name' attribute
316 if self.options.source_path is None:
317 try:
318 self.source_path = grammar.name # type: ignore[union-attr]
319 except AttributeError:
320 self.source_path = '<string>'
321 else:
322 self.source_path = self.options.source_path
324 # Drain file-like objects to get their contents
325 try:
326 read = grammar.read # type: ignore[union-attr]
327 except AttributeError:
328 pass
329 else:
330 grammar = read()
332 cache_fn = None
333 cache_sha256 = None
334 if isinstance(grammar, str):
335 self.source_grammar = grammar
336 if self.options.use_bytes:
337 if not grammar.isascii():
338 raise ConfigurationError("Grammar must be ascii only, when use_bytes=True")
340 if self.options.cache:
341 if self.options.parser != 'lalr':
342 raise ConfigurationError("cache only works with parser='lalr' for now")
344 unhashable = ('transformer', 'postlex', 'lexer_callbacks', 'edit_terminals', '_plugins')
345 options_str = ''.join(k+str(v) for k, v in options.items() if k not in unhashable)
346 from . import __version__
347 s = grammar + options_str + __version__ + str(sys.version_info[:2])
348 cache_sha256 = sha256_digest(s)
350 if isinstance(self.options.cache, str):
351 cache_fn = self.options.cache
352 else:
353 if self.options.cache is not True:
354 raise ConfigurationError("cache argument must be bool or str")
356 try:
357 username = getpass.getuser()
358 except Exception:
359 # The exception raised may be ImportError or OSError in
360 # the future. For the cache, we don't care about the
361 # specific reason - we just want a username.
362 username = "unknown"
365 cache_fn = tempfile.gettempdir() + "/.lark_%s_%s_%s_%s_%s.tmp" % (
366 "cache_grammar" if self.options.cache_grammar else "cache", username, cache_sha256, *sys.version_info[:2])
368 old_options = self.options
369 try:
370 with FS.open(cache_fn, 'rb') as f:
371 logger.debug('Loading grammar from cache: %s', cache_fn)
372 # Remove options that aren't relevant for loading from cache
373 for name in (set(options) - _LOAD_ALLOWED_OPTIONS):
374 del options[name]
375 file_sha256 = f.readline().rstrip(b'\n')
376 cached_used_files = pickle.load(f)
377 if file_sha256 == cache_sha256.encode('utf8') and verify_used_files(cached_used_files):
378 cached_parser_data = pickle.load(f)
379 self._load(cached_parser_data, **options)
380 return
381 except FileNotFoundError:
382 # The cache file doesn't exist; parse and compose the grammar as normal
383 pass
384 except Exception: # We should probably narrow done which errors we catch here.
385 logger.exception("Failed to load Lark from cache: %r. We will try to carry on.", cache_fn)
387 # In theory, the Lark instance might have been messed up by the call to `_load`.
388 # In practice the only relevant thing that might have been overwritten should be `options`
389 self.options = old_options
392 # Parse the grammar file and compose the grammars
393 self.grammar, used_files = load_grammar(grammar, self.source_path, self.options.import_paths, self.options.keep_all_tokens)
394 else:
395 assert isinstance(grammar, Grammar)
396 self.grammar = grammar
399 if self.options.lexer == 'auto':
400 if self.options.parser == 'lalr':
401 self.options.lexer = 'contextual'
402 elif self.options.parser == 'earley':
403 if self.options.postlex is not None:
404 logger.info("postlex can't be used with the dynamic lexer, so we use 'basic' instead. "
405 "Consider using lalr with contextual instead of earley")
406 self.options.lexer = 'basic'
407 else:
408 self.options.lexer = 'dynamic'
409 elif self.options.parser == 'cyk':
410 self.options.lexer = 'basic'
411 else:
412 assert False, self.options.parser
413 lexer = self.options.lexer
414 if isinstance(lexer, type):
415 assert issubclass(lexer, Lexer) # XXX Is this really important? Maybe just ensure interface compliance
416 else:
417 assert_config(lexer, ('basic', 'contextual', 'dynamic', 'dynamic_complete'))
418 if self.options.postlex is not None and 'dynamic' in lexer:
419 raise ConfigurationError("Can't use postlex with a dynamic lexer. Use basic or contextual instead")
421 if self.options.ambiguity == 'auto':
422 if self.options.parser == 'earley':
423 self.options.ambiguity = 'resolve'
424 else:
425 assert_config(self.options.parser, ('earley', 'cyk'), "%r doesn't support disambiguation. Use one of these parsers instead: %s")
427 if self.options.priority == 'auto':
428 self.options.priority = 'normal'
430 if self.options.priority not in _VALID_PRIORITY_OPTIONS:
431 raise ConfigurationError("invalid priority option: %r. Must be one of %r" % (self.options.priority, _VALID_PRIORITY_OPTIONS))
432 if self.options.ambiguity not in _VALID_AMBIGUITY_OPTIONS:
433 raise ConfigurationError("invalid ambiguity option: %r. Must be one of %r" % (self.options.ambiguity, _VALID_AMBIGUITY_OPTIONS))
435 if self.options.parser is None:
436 terminals_to_keep = '*' # For lexer-only mode, keep all terminals
437 elif self.options.postlex is not None:
438 terminals_to_keep = set(self.options.postlex.always_accept)
439 else:
440 terminals_to_keep = set()
442 # Compile the EBNF grammar into BNF
443 self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start, terminals_to_keep)
445 if self.options.edit_terminals:
446 for t in self.terminals:
447 self.options.edit_terminals(t)
449 self._terminals_dict = {t.name: t for t in self.terminals}
451 # If the user asked to invert the priorities, negate them all here.
452 if self.options.priority == 'invert':
453 for rule in self.rules:
454 if rule.options.priority is not None:
455 rule.options.priority = -rule.options.priority
456 for term in self.terminals:
457 term.priority = -term.priority
458 # Else, if the user asked to disable priorities, strip them from the
459 # rules and terminals. This allows the Earley parsers to skip an extra forest walk
460 # for improved performance, if you don't need them (or didn't specify any).
461 elif self.options.priority is None:
462 for rule in self.rules:
463 if rule.options.priority is not None:
464 rule.options.priority = None
465 for term in self.terminals:
466 term.priority = 0
468 # TODO Deprecate lexer_callbacks?
469 self.lexer_conf = LexerConf(
470 self.terminals, re_module, self.ignore_tokens, self.options.postlex,
471 self.options.lexer_callbacks, self.options.g_regex_flags, use_bytes=self.options.use_bytes, strict=self.options.strict
472 )
474 if self.options.parser:
475 self.parser = self._build_parser()
476 elif lexer:
477 self.lexer = self._build_lexer()
479 if cache_fn:
480 logger.debug('Saving grammar to cache: %s', cache_fn)
481 try:
482 with FS.open(cache_fn, 'wb') as f:
483 assert cache_sha256 is not None
484 f.write(cache_sha256.encode('utf8') + b'\n')
485 pickle.dump(used_files, f)
486 self.save(f, _LOAD_ALLOWED_OPTIONS)
487 except IOError as e:
488 logger.exception("Failed to save Lark to cache: %r.", cache_fn, e)
490 if __doc__:
491 __doc__ += "\n\n" + LarkOptions.OPTIONS_DOC
493 def _build_lexer(self, dont_ignore: bool=False) -> BasicLexer:
494 lexer_conf = self.lexer_conf
495 if dont_ignore:
496 from copy import copy
497 lexer_conf = copy(lexer_conf)
498 lexer_conf.ignore = ()
499 return BasicLexer(lexer_conf)
501 def _prepare_callbacks(self) -> None:
502 self._callbacks = {}
503 # we don't need these callbacks if we aren't building a tree
504 if self.options.ambiguity != 'forest':
505 self._parse_tree_builder = ParseTreeBuilder(
506 self.rules,
507 self.options.tree_class or Tree,
508 self.options.propagate_positions,
509 self.options.parser != 'lalr' and self.options.ambiguity == 'explicit',
510 self.options.maybe_placeholders
511 )
512 self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
513 self._callbacks.update(_get_lexer_callbacks(self.options.transformer, self.terminals))
515 def _build_parser(self) -> "ParsingFrontend":
516 self._prepare_callbacks()
517 _validate_frontend_args(self.options.parser, self.options.lexer)
518 parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
519 return _construct_parsing_frontend(
520 self.options.parser,
521 self.options.lexer,
522 self.lexer_conf,
523 parser_conf,
524 options=self.options
525 )
527 def save(self, f, exclude_options: Collection[str] = ()) -> None:
528 """Saves the instance into the given file object
530 Useful for caching and multiprocessing.
531 """
532 if self.options.parser != 'lalr':
533 raise NotImplementedError("Lark.save() is only implemented for the LALR(1) parser.")
534 data, m = self.memo_serialize([TerminalDef, Rule])
535 if exclude_options:
536 data["options"] = {n: v for n, v in data["options"].items() if n not in exclude_options}
537 pickle.dump({'data': data, 'memo': m}, f, protocol=pickle.HIGHEST_PROTOCOL)
539 @classmethod
540 def load(cls: Type[_T], f) -> _T:
541 """Loads an instance from the given file object
543 Useful for caching and multiprocessing.
544 """
545 inst = cls.__new__(cls)
546 return inst._load(f)
548 def _deserialize_lexer_conf(self, data: Dict[str, Any], memo: Dict[int, Union[TerminalDef, Rule]], options: LarkOptions) -> LexerConf:
549 lexer_conf = LexerConf.deserialize(data['lexer_conf'], memo)
550 lexer_conf.callbacks = options.lexer_callbacks or {}
551 lexer_conf.re_module = regex if options.regex else re
552 lexer_conf.use_bytes = options.use_bytes
553 lexer_conf.g_regex_flags = options.g_regex_flags
554 lexer_conf.skip_validation = True
555 lexer_conf.postlex = options.postlex
556 return lexer_conf
558 def _load(self: _T, f: Any, **kwargs) -> _T:
559 if isinstance(f, dict):
560 d = f
561 else:
562 d = pickle.load(f)
563 memo_json = d['memo']
564 data = d['data']
566 assert memo_json
567 memo = SerializeMemoizer.deserialize(memo_json, {'Rule': Rule, 'TerminalDef': TerminalDef}, {})
568 if 'grammar' in data:
569 self.grammar = Grammar.deserialize(data['grammar'], memo)
570 options = dict(data['options'])
571 if (set(kwargs) - _LOAD_ALLOWED_OPTIONS) & set(LarkOptions._defaults):
572 raise ConfigurationError("Some options are not allowed when loading a Parser: {}"
573 .format(set(kwargs) - _LOAD_ALLOWED_OPTIONS))
574 options.update(kwargs)
575 self.options = LarkOptions.deserialize(options, memo)
576 self.rules = [Rule.deserialize(r, memo) for r in data['rules']]
577 self.source_path = '<deserialized>'
578 _validate_frontend_args(self.options.parser, self.options.lexer)
579 self.lexer_conf = self._deserialize_lexer_conf(data['parser'], memo, self.options)
580 self.terminals = self.lexer_conf.terminals
581 self._prepare_callbacks()
582 self._terminals_dict = {t.name: t for t in self.terminals}
583 self.parser = _deserialize_parsing_frontend(
584 data['parser'],
585 memo,
586 self.lexer_conf,
587 self._callbacks,
588 self.options, # Not all, but multiple attributes are used
589 )
590 return self
592 @classmethod
593 def _load_from_dict(cls, data, memo, **kwargs):
594 inst = cls.__new__(cls)
595 return inst._load({'data': data, 'memo': memo}, **kwargs)
597 @overload
598 @classmethod
599 def open(
600 cls,
601 grammar_filename: str,
602 rel_to: Optional[str] = None,
603 *,
604 transformer: 'Transformer[Token, _Return_T]',
605 **options: Any,
606 ) -> 'Lark[_Return_T]': ...
608 @overload
609 @classmethod
610 def open(
611 cls,
612 grammar_filename: str,
613 rel_to: Optional[str] = None,
614 **options: Any,
615 ) -> 'Lark[ParseTree]': ...
617 @classmethod
618 def open(cls, grammar_filename: str, rel_to: Optional[str]=None, **options) -> 'Lark':
619 """Create an instance of Lark with the grammar given by its filename
621 If ``rel_to`` is provided, the function will find the grammar filename in relation to it.
623 Example:
625 >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
626 Lark(...)
627 """
628 if rel_to:
629 basepath = os.path.dirname(rel_to)
630 grammar_filename = os.path.join(basepath, grammar_filename)
631 with open(grammar_filename, encoding='utf8') as f:
632 return cls(f, **options)
634 @overload
635 @classmethod
636 def open_from_package(
637 cls,
638 package: str,
639 grammar_path: str,
640 search_paths: 'Sequence[str]' = ...,
641 *,
642 transformer: 'Transformer[Token, _Return_T]',
643 **options: Any,
644 ) -> 'Lark[_Return_T]': ...
646 @overload
647 @classmethod
648 def open_from_package(
649 cls,
650 package: str,
651 grammar_path: str,
652 search_paths: 'Sequence[str]' = ...,
653 **options: Any,
654 ) -> 'Lark[ParseTree]': ...
656 @classmethod
657 def open_from_package(cls, package: str, grammar_path: str, search_paths: 'Sequence[str]'=[""], **options) -> 'Lark':
658 """Create an instance of Lark with the grammar loaded from within the package ``package``.
659 This allows grammar loading from zipapps.
661 Imports in the grammar will use the ``package`` and ``search_paths`` provided, through ``FromPackageLoader``
663 Example:
665 Lark.open_from_package(__name__, "example.lark", ("grammars",), parser=...)
666 """
667 package_loader = FromPackageLoader(package, search_paths)
668 full_path, text = package_loader(None, grammar_path)
669 options.setdefault('source_path', full_path)
670 options.setdefault('import_paths', [])
671 options['import_paths'].append(package_loader)
672 return cls(text, **options)
674 def __repr__(self):
675 return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source_path, self.options.parser, self.options.lexer)
678 def lex(self, text: TextOrSlice, dont_ignore: bool=False) -> Iterator[Token]:
679 """Only lex (and postlex) the text, without parsing it. Only relevant when lexer='basic'
681 When dont_ignore=True, the lexer will return all tokens, even those marked for %ignore.
683 :raises UnexpectedCharacters: In case the lexer cannot find a suitable match.
684 """
685 lexer: Lexer
686 if not hasattr(self, 'lexer') or dont_ignore:
687 lexer = self._build_lexer(dont_ignore)
688 else:
689 lexer = self.lexer
690 lexer_thread = LexerThread.from_text(lexer, text)
691 stream = lexer_thread.lex(None)
692 if self.options.postlex:
693 return self.options.postlex.process(stream)
694 return stream
696 def get_terminal(self, name: str) -> TerminalDef:
697 """Get information about a terminal"""
698 return self._terminals_dict[name]
700 def parse_interactive(self, text: Optional[LarkInput]=None, start: Optional[str]=None) -> 'InteractiveParser':
701 """Start an interactive parsing session. Only works when parser='lalr'.
703 Parameters:
704 text (LarkInput, optional): Text to be parsed. Required for ``resume_parse()``.
705 start (str, optional): Start symbol
707 Returns:
708 A new InteractiveParser instance.
710 See Also: ``Lark.parse()``
711 """
712 return self.parser.parse_interactive(text, start=start)
714 def parse(self, text: LarkInput, start: Optional[str]=None, on_error: 'Optional[Callable[[UnexpectedInput], bool]]'=None) -> _Return_T:
715 """Parse the given text, according to the options provided.
717 Parameters:
718 text (LarkInput): Text to be parsed, as `str` or `bytes`.
719 TextSlice may also be used, but only when lexer='basic' or 'contextual'.
720 If Lark was created with a custom lexer, this may be an object of any type.
721 start (str, optional): Required if Lark was given multiple possible start symbols (using the start option).
722 on_error (function, optional): if provided, will be called on UnexpectedInput error,
723 with the exception as its argument. Return true to resume parsing, or false to raise the exception.
724 LALR only. See examples/advanced/error_handling.py for an example of how to use on_error.
726 Returns:
727 If a transformer is supplied to ``__init__``, returns whatever is the
728 result of the transformation. Otherwise, returns a Tree instance.
730 :raises UnexpectedInput: On a parse error, one of these sub-exceptions will rise:
731 ``UnexpectedCharacters``, ``UnexpectedToken``, or ``UnexpectedEOF``.
732 For convenience, these sub-exceptions also inherit from ``ParserError`` and ``LexerError``.
734 """
735 if on_error is not None and self.options.parser != 'lalr':
736 raise NotImplementedError("The on_error option is only implemented for the LALR(1) parser.")
737 return self.parser.parse(text, start=start, on_error=on_error)
740###}