Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/lark/lark.py: 50%

329 statements  

« prev     ^ index     » next       coverage.py v7.3.1, created at 2023-09-25 06:30 +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 

20 

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 

26 

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 

31 

32 

33try: 

34 import regex 

35 _has_regex = True 

36except ImportError: 

37 _has_regex = False 

38 

39 

40###{standalone 

41 

42 

43class PostLex(ABC): 

44 @abstractmethod 

45 def process(self, stream: Iterator[Token]) -> Iterator[Token]: 

46 return stream 

47 

48 always_accept: Iterable[str] = () 

49 

50class LarkOptions(Serialize): 

51 """Specifies the options for Lark 

52 

53 """ 

54 

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: 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 edit_terminals: Optional[Callable[[TerminalDef], TerminalDef]] 

74 import_paths: 'List[Union[str, Callable[[Union[None, str, PackageResource], str], Tuple[str, str]]]]' 

75 source_path: Optional[str] 

76 

77 OPTIONS_DOC = """ 

78 **=== General Options ===** 

79 

80 start 

81 The start symbol. Either a string, or a list of strings for multiple possible starts (Default: "start") 

82 debug 

83 Display debug information and extra warnings. Use only when debugging (Default: ``False``) 

84 When used with Earley, it generates a forest graph as "sppf.png", if 'dot' is installed. 

85 strict 

86 Throw an exception on any potential ambiguity, including shift/reduce conflicts, and regex collisions. 

87 transformer 

88 Applies the transformer to every parse tree (equivalent to applying it after the parse, but faster) 

89 propagate_positions 

90 Propagates positional attributes into the 'meta' attribute of all tree branches. 

91 Sets attributes: (line, column, end_line, end_column, start_pos, end_pos, 

92 container_line, container_column, container_end_line, container_end_column) 

93 Accepts ``False``, ``True``, or a callable, which will filter which nodes to ignore when propagating. 

94 maybe_placeholders 

95 When ``True``, the ``[]`` operator returns ``None`` when not matched. 

96 When ``False``, ``[]`` behaves like the ``?`` operator, and returns no value at all. 

97 (default= ``True``) 

98 cache 

99 Cache the results of the Lark grammar analysis, for x2 to x3 faster loading. LALR only for now. 

100 

101 - When ``False``, does nothing (default) 

102 - When ``True``, caches to a temporary file in the local directory 

103 - When given a string, caches to the path pointed by the string 

104 regex 

105 When True, uses the ``regex`` module instead of the stdlib ``re``. 

106 g_regex_flags 

107 Flags that are applied to all terminals (both regex and strings) 

108 keep_all_tokens 

109 Prevent the tree builder from automagically removing "punctuation" tokens (Default: ``False``) 

110 tree_class 

111 Lark will produce trees comprised of instances of this class instead of the default ``lark.Tree``. 

112 

113 **=== Algorithm Options ===** 

114 

115 parser 

116 Decides which parser engine to use. Accepts "earley" or "lalr". (Default: "earley"). 

117 (there is also a "cyk" option for legacy) 

118 lexer 

119 Decides whether or not to use a lexer stage 

120 

121 - "auto" (default): Choose for me based on the parser 

122 - "basic": Use a basic lexer 

123 - "contextual": Stronger lexer (only works with parser="lalr") 

124 - "dynamic": Flexible and powerful (only with parser="earley") 

125 - "dynamic_complete": Same as dynamic, but tries *every* variation of tokenizing possible. 

126 ambiguity 

127 Decides how to handle ambiguity in the parse. Only relevant if parser="earley" 

128 

129 - "resolve": The parser will automatically choose the simplest derivation 

130 (it chooses consistently: greedy for tokens, non-greedy for rules) 

131 - "explicit": The parser will return all derivations wrapped in "_ambig" tree nodes (i.e. a forest). 

132 - "forest": The parser will return the root of the shared packed parse forest. 

133 

134 **=== Misc. / Domain Specific Options ===** 

135 

136 postlex 

137 Lexer post-processing (Default: ``None``) Only works with the basic and contextual lexers. 

138 priority 

139 How priorities should be evaluated - "auto", ``None``, "normal", "invert" (Default: "auto") 

140 lexer_callbacks 

141 Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution. 

142 use_bytes 

143 Accept an input of type ``bytes`` instead of ``str``. 

144 edit_terminals 

145 A callback for editing the terminals before parse. 

146 import_paths 

147 A List of either paths or loader functions to specify from where grammars are imported 

148 source_path 

149 Override the source of from where the grammar was loaded. Useful for relative imports and unconventional grammar loading 

150 **=== End of Options ===** 

151 """ 

152 if __doc__: 

153 __doc__ += OPTIONS_DOC 

154 

155 

156 # Adding a new option needs to be done in multiple places: 

157 # - In the dictionary below. This is the primary truth of which options `Lark.__init__` accepts 

158 # - In the docstring above. It is used both for the docstring of `LarkOptions` and `Lark`, and in readthedocs 

159 # - As an attribute of `LarkOptions` above 

160 # - Potentially in `_LOAD_ALLOWED_OPTIONS` below this class, when the option doesn't change how the grammar is loaded 

161 # - Potentially in `lark.tools.__init__`, if it makes sense, and it can easily be passed as a cmd argument 

162 _defaults: Dict[str, Any] = { 

163 'debug': False, 

164 'strict': False, 

165 'keep_all_tokens': False, 

166 'tree_class': None, 

167 'cache': False, 

168 'postlex': None, 

169 'parser': 'earley', 

170 'lexer': 'auto', 

171 'transformer': None, 

172 'start': 'start', 

173 'priority': 'auto', 

174 'ambiguity': 'auto', 

175 'regex': False, 

176 'propagate_positions': False, 

177 'lexer_callbacks': {}, 

178 'maybe_placeholders': True, 

179 'edit_terminals': None, 

180 'g_regex_flags': 0, 

181 'use_bytes': False, 

182 'import_paths': [], 

183 'source_path': None, 

184 '_plugins': {}, 

185 } 

186 

187 def __init__(self, options_dict: Dict[str, Any]) -> None: 

188 o = dict(options_dict) 

189 

190 options = {} 

191 for name, default in self._defaults.items(): 

192 if name in o: 

193 value = o.pop(name) 

194 if isinstance(default, bool) and name not in ('cache', 'use_bytes', 'propagate_positions'): 

195 value = bool(value) 

196 else: 

197 value = default 

198 

199 options[name] = value 

200 

201 if isinstance(options['start'], str): 

202 options['start'] = [options['start']] 

203 

204 self.__dict__['options'] = options 

205 

206 

207 assert_config(self.parser, ('earley', 'lalr', 'cyk', None)) 

208 

209 if self.parser == 'earley' and self.transformer: 

210 raise ConfigurationError('Cannot specify an embedded transformer when using the Earley algorithm. ' 

211 'Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. LALR)') 

212 

213 if o: 

214 raise ConfigurationError("Unknown options: %s" % o.keys()) 

215 

216 def __getattr__(self, name: str) -> Any: 

217 try: 

218 return self.__dict__['options'][name] 

219 except KeyError as e: 

220 raise AttributeError(e) 

221 

222 def __setattr__(self, name: str, value: str) -> None: 

223 assert_config(name, self.options.keys(), "%r isn't a valid option. Expected one of: %s") 

224 self.options[name] = value 

225 

226 def serialize(self, memo = None) -> Dict[str, Any]: 

227 return self.options 

228 

229 @classmethod 

230 def deserialize(cls, data: Dict[str, Any], memo: Dict[int, Union[TerminalDef, Rule]]) -> "LarkOptions": 

231 return cls(data) 

232 

233 

234# Options that can be passed to the Lark parser, even when it was loaded from cache/standalone. 

235# These options are only used outside of `load_grammar`. 

236_LOAD_ALLOWED_OPTIONS = {'postlex', 'transformer', 'lexer_callbacks', 'use_bytes', 'debug', 'g_regex_flags', 'regex', 'propagate_positions', 'tree_class', '_plugins'} 

237 

238_VALID_PRIORITY_OPTIONS = ('auto', 'normal', 'invert', None) 

239_VALID_AMBIGUITY_OPTIONS = ('auto', 'resolve', 'explicit', 'forest') 

240 

241 

242_T = TypeVar('_T', bound="Lark") 

243 

244class Lark(Serialize): 

245 """Main interface for the library. 

246 

247 It's mostly a thin wrapper for the many different parsers, and for the tree constructor. 

248 

249 Parameters: 

250 grammar: a string or file-object containing the grammar spec (using Lark's ebnf syntax) 

251 options: a dictionary controlling various aspects of Lark. 

252 

253 Example: 

254 >>> Lark(r'''start: "foo" ''') 

255 Lark(...) 

256 """ 

257 

258 source_path: str 

259 source_grammar: str 

260 grammar: 'Grammar' 

261 options: LarkOptions 

262 lexer: Lexer 

263 parser: 'ParsingFrontend' 

264 terminals: Collection[TerminalDef] 

265 

266 def __init__(self, grammar: 'Union[Grammar, str, IO[str]]', **options) -> None: 

267 self.options = LarkOptions(options) 

268 re_module: types.ModuleType 

269 

270 # Set regex or re module 

271 use_regex = self.options.regex 

272 if use_regex: 

273 if _has_regex: 

274 re_module = regex 

275 else: 

276 raise ImportError('`regex` module must be installed if calling `Lark(regex=True)`.') 

277 else: 

278 re_module = re 

279 

280 # Some, but not all file-like objects have a 'name' attribute 

281 if self.options.source_path is None: 

282 try: 

283 self.source_path = grammar.name # type: ignore[union-attr] 

284 except AttributeError: 

285 self.source_path = '<string>' 

286 else: 

287 self.source_path = self.options.source_path 

288 

289 # Drain file-like objects to get their contents 

290 try: 

291 read = grammar.read # type: ignore[union-attr] 

292 except AttributeError: 

293 pass 

294 else: 

295 grammar = read() 

296 

297 cache_fn = None 

298 cache_sha256 = None 

299 if isinstance(grammar, str): 

300 self.source_grammar = grammar 

301 if self.options.use_bytes: 

302 if not isascii(grammar): 

303 raise ConfigurationError("Grammar must be ascii only, when use_bytes=True") 

304 

305 if self.options.cache: 

306 if self.options.parser != 'lalr': 

307 raise ConfigurationError("cache only works with parser='lalr' for now") 

308 

309 unhashable = ('transformer', 'postlex', 'lexer_callbacks', 'edit_terminals', '_plugins') 

310 options_str = ''.join(k+str(v) for k, v in options.items() if k not in unhashable) 

311 from . import __version__ 

312 s = grammar + options_str + __version__ + str(sys.version_info[:2]) 

313 cache_sha256 = sha256_digest(s) 

314 

315 if isinstance(self.options.cache, str): 

316 cache_fn = self.options.cache 

317 else: 

318 if self.options.cache is not True: 

319 raise ConfigurationError("cache argument must be bool or str") 

320 

321 try: 

322 username = getpass.getuser() 

323 except Exception: 

324 # The exception raised may be ImportError or OSError in 

325 # the future. For the cache, we don't care about the 

326 # specific reason - we just want a username. 

327 username = "unknown" 

328 

329 cache_fn = tempfile.gettempdir() + "/.lark_cache_%s_%s_%s_%s.tmp" % (username, cache_sha256, *sys.version_info[:2]) 

330 

331 old_options = self.options 

332 try: 

333 with FS.open(cache_fn, 'rb') as f: 

334 logger.debug('Loading grammar from cache: %s', cache_fn) 

335 # Remove options that aren't relevant for loading from cache 

336 for name in (set(options) - _LOAD_ALLOWED_OPTIONS): 

337 del options[name] 

338 file_sha256 = f.readline().rstrip(b'\n') 

339 cached_used_files = pickle.load(f) 

340 if file_sha256 == cache_sha256.encode('utf8') and verify_used_files(cached_used_files): 

341 cached_parser_data = pickle.load(f) 

342 self._load(cached_parser_data, **options) 

343 return 

344 except FileNotFoundError: 

345 # The cache file doesn't exist; parse and compose the grammar as normal 

346 pass 

347 except Exception: # We should probably narrow done which errors we catch here. 

348 logger.exception("Failed to load Lark from cache: %r. We will try to carry on.", cache_fn) 

349 

350 # In theory, the Lark instance might have been messed up by the call to `_load`. 

351 # In practice the only relevant thing that might have been overwritten should be `options` 

352 self.options = old_options 

353 

354 

355 # Parse the grammar file and compose the grammars 

356 self.grammar, used_files = load_grammar(grammar, self.source_path, self.options.import_paths, self.options.keep_all_tokens) 

357 else: 

358 assert isinstance(grammar, Grammar) 

359 self.grammar = grammar 

360 

361 

362 if self.options.lexer == 'auto': 

363 if self.options.parser == 'lalr': 

364 self.options.lexer = 'contextual' 

365 elif self.options.parser == 'earley': 

366 if self.options.postlex is not None: 

367 logger.info("postlex can't be used with the dynamic lexer, so we use 'basic' instead. " 

368 "Consider using lalr with contextual instead of earley") 

369 self.options.lexer = 'basic' 

370 else: 

371 self.options.lexer = 'dynamic' 

372 elif self.options.parser == 'cyk': 

373 self.options.lexer = 'basic' 

374 else: 

375 assert False, self.options.parser 

376 lexer = self.options.lexer 

377 if isinstance(lexer, type): 

378 assert issubclass(lexer, Lexer) # XXX Is this really important? Maybe just ensure interface compliance 

379 else: 

380 assert_config(lexer, ('basic', 'contextual', 'dynamic', 'dynamic_complete')) 

381 if self.options.postlex is not None and 'dynamic' in lexer: 

382 raise ConfigurationError("Can't use postlex with a dynamic lexer. Use basic or contextual instead") 

383 

384 if self.options.ambiguity == 'auto': 

385 if self.options.parser == 'earley': 

386 self.options.ambiguity = 'resolve' 

387 else: 

388 assert_config(self.options.parser, ('earley', 'cyk'), "%r doesn't support disambiguation. Use one of these parsers instead: %s") 

389 

390 if self.options.priority == 'auto': 

391 self.options.priority = 'normal' 

392 

393 if self.options.priority not in _VALID_PRIORITY_OPTIONS: 

394 raise ConfigurationError("invalid priority option: %r. Must be one of %r" % (self.options.priority, _VALID_PRIORITY_OPTIONS)) 

395 if self.options.ambiguity not in _VALID_AMBIGUITY_OPTIONS: 

396 raise ConfigurationError("invalid ambiguity option: %r. Must be one of %r" % (self.options.ambiguity, _VALID_AMBIGUITY_OPTIONS)) 

397 

398 if self.options.parser is None: 

399 terminals_to_keep = '*' 

400 elif self.options.postlex is not None: 

401 terminals_to_keep = set(self.options.postlex.always_accept) 

402 else: 

403 terminals_to_keep = set() 

404 

405 # Compile the EBNF grammar into BNF 

406 self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start, terminals_to_keep) 

407 

408 if self.options.edit_terminals: 

409 for t in self.terminals: 

410 self.options.edit_terminals(t) 

411 

412 self._terminals_dict = {t.name: t for t in self.terminals} 

413 

414 # If the user asked to invert the priorities, negate them all here. 

415 if self.options.priority == 'invert': 

416 for rule in self.rules: 

417 if rule.options.priority is not None: 

418 rule.options.priority = -rule.options.priority 

419 for term in self.terminals: 

420 term.priority = -term.priority 

421 # Else, if the user asked to disable priorities, strip them from the 

422 # rules and terminals. This allows the Earley parsers to skip an extra forest walk 

423 # for improved performance, if you don't need them (or didn't specify any). 

424 elif self.options.priority is None: 

425 for rule in self.rules: 

426 if rule.options.priority is not None: 

427 rule.options.priority = None 

428 for term in self.terminals: 

429 term.priority = 0 

430 

431 # TODO Deprecate lexer_callbacks? 

432 self.lexer_conf = LexerConf( 

433 self.terminals, re_module, self.ignore_tokens, self.options.postlex, 

434 self.options.lexer_callbacks, self.options.g_regex_flags, use_bytes=self.options.use_bytes, strict=self.options.strict 

435 ) 

436 

437 if self.options.parser: 

438 self.parser = self._build_parser() 

439 elif lexer: 

440 self.lexer = self._build_lexer() 

441 

442 if cache_fn: 

443 logger.debug('Saving grammar to cache: %s', cache_fn) 

444 try: 

445 with FS.open(cache_fn, 'wb') as f: 

446 assert cache_sha256 is not None 

447 f.write(cache_sha256.encode('utf8') + b'\n') 

448 pickle.dump(used_files, f) 

449 self.save(f, _LOAD_ALLOWED_OPTIONS) 

450 except IOError as e: 

451 logger.exception("Failed to save Lark to cache: %r.", cache_fn, e) 

452 

453 if __doc__: 

454 __doc__ += "\n\n" + LarkOptions.OPTIONS_DOC 

455 

456 __serialize_fields__ = 'parser', 'rules', 'options' 

457 

458 def _build_lexer(self, dont_ignore: bool=False) -> BasicLexer: 

459 lexer_conf = self.lexer_conf 

460 if dont_ignore: 

461 from copy import copy 

462 lexer_conf = copy(lexer_conf) 

463 lexer_conf.ignore = () 

464 return BasicLexer(lexer_conf) 

465 

466 def _prepare_callbacks(self) -> None: 

467 self._callbacks = {} 

468 # we don't need these callbacks if we aren't building a tree 

469 if self.options.ambiguity != 'forest': 

470 self._parse_tree_builder = ParseTreeBuilder( 

471 self.rules, 

472 self.options.tree_class or Tree, 

473 self.options.propagate_positions, 

474 self.options.parser != 'lalr' and self.options.ambiguity == 'explicit', 

475 self.options.maybe_placeholders 

476 ) 

477 self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer) 

478 self._callbacks.update(_get_lexer_callbacks(self.options.transformer, self.terminals)) 

479 

480 def _build_parser(self) -> "ParsingFrontend": 

481 self._prepare_callbacks() 

482 _validate_frontend_args(self.options.parser, self.options.lexer) 

483 parser_conf = ParserConf(self.rules, self._callbacks, self.options.start) 

484 return _construct_parsing_frontend( 

485 self.options.parser, 

486 self.options.lexer, 

487 self.lexer_conf, 

488 parser_conf, 

489 options=self.options 

490 ) 

491 

492 def save(self, f, exclude_options: Collection[str] = ()) -> None: 

493 """Saves the instance into the given file object 

494 

495 Useful for caching and multiprocessing. 

496 """ 

497 if self.options.parser != 'lalr': 

498 raise NotImplementedError("Lark.save() is only implemented for the LALR(1) parser.") 

499 data, m = self.memo_serialize([TerminalDef, Rule]) 

500 if exclude_options: 

501 data["options"] = {n: v for n, v in data["options"].items() if n not in exclude_options} 

502 pickle.dump({'data': data, 'memo': m}, f, protocol=pickle.HIGHEST_PROTOCOL) 

503 

504 @classmethod 

505 def load(cls: Type[_T], f) -> _T: 

506 """Loads an instance from the given file object 

507 

508 Useful for caching and multiprocessing. 

509 """ 

510 inst = cls.__new__(cls) 

511 return inst._load(f) 

512 

513 def _deserialize_lexer_conf(self, data: Dict[str, Any], memo: Dict[int, Union[TerminalDef, Rule]], options: LarkOptions) -> LexerConf: 

514 lexer_conf = LexerConf.deserialize(data['lexer_conf'], memo) 

515 lexer_conf.callbacks = options.lexer_callbacks or {} 

516 lexer_conf.re_module = regex if options.regex else re 

517 lexer_conf.use_bytes = options.use_bytes 

518 lexer_conf.g_regex_flags = options.g_regex_flags 

519 lexer_conf.skip_validation = True 

520 lexer_conf.postlex = options.postlex 

521 return lexer_conf 

522 

523 def _load(self: _T, f: Any, **kwargs) -> _T: 

524 if isinstance(f, dict): 

525 d = f 

526 else: 

527 d = pickle.load(f) 

528 memo_json = d['memo'] 

529 data = d['data'] 

530 

531 assert memo_json 

532 memo = SerializeMemoizer.deserialize(memo_json, {'Rule': Rule, 'TerminalDef': TerminalDef}, {}) 

533 options = dict(data['options']) 

534 if (set(kwargs) - _LOAD_ALLOWED_OPTIONS) & set(LarkOptions._defaults): 

535 raise ConfigurationError("Some options are not allowed when loading a Parser: {}" 

536 .format(set(kwargs) - _LOAD_ALLOWED_OPTIONS)) 

537 options.update(kwargs) 

538 self.options = LarkOptions.deserialize(options, memo) 

539 self.rules = [Rule.deserialize(r, memo) for r in data['rules']] 

540 self.source_path = '<deserialized>' 

541 _validate_frontend_args(self.options.parser, self.options.lexer) 

542 self.lexer_conf = self._deserialize_lexer_conf(data['parser'], memo, self.options) 

543 self.terminals = self.lexer_conf.terminals 

544 self._prepare_callbacks() 

545 self._terminals_dict = {t.name: t for t in self.terminals} 

546 self.parser = _deserialize_parsing_frontend( 

547 data['parser'], 

548 memo, 

549 self.lexer_conf, 

550 self._callbacks, 

551 self.options, # Not all, but multiple attributes are used 

552 ) 

553 return self 

554 

555 @classmethod 

556 def _load_from_dict(cls, data, memo, **kwargs): 

557 inst = cls.__new__(cls) 

558 return inst._load({'data': data, 'memo': memo}, **kwargs) 

559 

560 @classmethod 

561 def open(cls: Type[_T], grammar_filename: str, rel_to: Optional[str]=None, **options) -> _T: 

562 """Create an instance of Lark with the grammar given by its filename 

563 

564 If ``rel_to`` is provided, the function will find the grammar filename in relation to it. 

565 

566 Example: 

567 

568 >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr") 

569 Lark(...) 

570 

571 """ 

572 if rel_to: 

573 basepath = os.path.dirname(rel_to) 

574 grammar_filename = os.path.join(basepath, grammar_filename) 

575 with open(grammar_filename, encoding='utf8') as f: 

576 return cls(f, **options) 

577 

578 @classmethod 

579 def open_from_package(cls: Type[_T], package: str, grammar_path: str, search_paths: 'Sequence[str]'=[""], **options) -> _T: 

580 """Create an instance of Lark with the grammar loaded from within the package `package`. 

581 This allows grammar loading from zipapps. 

582 

583 Imports in the grammar will use the `package` and `search_paths` provided, through `FromPackageLoader` 

584 

585 Example: 

586 

587 Lark.open_from_package(__name__, "example.lark", ("grammars",), parser=...) 

588 """ 

589 package_loader = FromPackageLoader(package, search_paths) 

590 full_path, text = package_loader(None, grammar_path) 

591 options.setdefault('source_path', full_path) 

592 options.setdefault('import_paths', []) 

593 options['import_paths'].append(package_loader) 

594 return cls(text, **options) 

595 

596 def __repr__(self): 

597 return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source_path, self.options.parser, self.options.lexer) 

598 

599 

600 def lex(self, text: str, dont_ignore: bool=False) -> Iterator[Token]: 

601 """Only lex (and postlex) the text, without parsing it. Only relevant when lexer='basic' 

602 

603 When dont_ignore=True, the lexer will return all tokens, even those marked for %ignore. 

604 

605 :raises UnexpectedCharacters: In case the lexer cannot find a suitable match. 

606 """ 

607 lexer: Lexer 

608 if not hasattr(self, 'lexer') or dont_ignore: 

609 lexer = self._build_lexer(dont_ignore) 

610 else: 

611 lexer = self.lexer 

612 lexer_thread = LexerThread.from_text(lexer, text) 

613 stream = lexer_thread.lex(None) 

614 if self.options.postlex: 

615 return self.options.postlex.process(stream) 

616 return stream 

617 

618 def get_terminal(self, name: str) -> TerminalDef: 

619 """Get information about a terminal""" 

620 return self._terminals_dict[name] 

621 

622 def parse_interactive(self, text: Optional[str]=None, start: Optional[str]=None) -> 'InteractiveParser': 

623 """Start an interactive parsing session. 

624 

625 Parameters: 

626 text (str, optional): Text to be parsed. Required for ``resume_parse()``. 

627 start (str, optional): Start symbol 

628 

629 Returns: 

630 A new InteractiveParser instance. 

631 

632 See Also: ``Lark.parse()`` 

633 """ 

634 return self.parser.parse_interactive(text, start=start) 

635 

636 def parse(self, text: str, start: Optional[str]=None, on_error: 'Optional[Callable[[UnexpectedInput], bool]]'=None) -> 'ParseTree': 

637 """Parse the given text, according to the options provided. 

638 

639 Parameters: 

640 text (str): Text to be parsed. 

641 start (str, optional): Required if Lark was given multiple possible start symbols (using the start option). 

642 on_error (function, optional): if provided, will be called on UnexpectedToken error. Return true to resume parsing. 

643 LALR only. See examples/advanced/error_handling.py for an example of how to use on_error. 

644 

645 Returns: 

646 If a transformer is supplied to ``__init__``, returns whatever is the 

647 result of the transformation. Otherwise, returns a Tree instance. 

648 

649 :raises UnexpectedInput: On a parse error, one of these sub-exceptions will rise: 

650 ``UnexpectedCharacters``, ``UnexpectedToken``, or ``UnexpectedEOF``. 

651 For convenience, these sub-exceptions also inherit from ``ParserError`` and ``LexerError``. 

652 

653 """ 

654 return self.parser.parse(text, start=start, on_error=on_error) 

655 

656 

657###}