|
| 1 | +from __future__ import absolute_import, division, print_function, unicode_literals |
| 2 | +import sys, pyparser.source, pyparser.lexer, pyparser.parser |
| 3 | + |
| 4 | +def parse(source, filename='<unknown>', mode='exec', |
| 5 | + flags=[], version=sys.version_info[0:2]): |
| 6 | + """ |
| 7 | + Parse a string into an abstract syntax tree. |
| 8 | + This is the replacement for the built-in :meth:`..ast.parse`. |
| 9 | +
|
| 10 | + :param str source: Source code in the correct encoding |
| 11 | + :param filename: Filename of the source (used in diagnostics) |
| 12 | + :param mode: Execution mode. Pass ``"exec"`` to parse a module, |
| 13 | + ``"single"`` to parse a single (interactive) statement, |
| 14 | + and ``"eval"`` to parse an expression. In the last two cases, |
| 15 | + ``source`` must be terminated with an empty line |
| 16 | + (i.e. end with ``"\\n\\n"``). |
| 17 | + :param flags: Future flags. Equivalent to ``from __future__ import <flags>``. |
| 18 | + :param int,int version: A tuple of the major and minor version |
| 19 | + of Python syntax to recognize. |
| 20 | + :return ast.AST: abstract syntax tree |
| 21 | + :raise diagnostic.DiagnosticException: |
| 22 | + if the source code is not well-formed |
| 23 | + """ |
| 24 | + buffer = pyparser.source.Buffer(source, filename) |
| 25 | + lexer = pyparser.lexer.Lexer(buffer, version) |
| 26 | + parser = pyparser.parser.Parser(lexer) |
| 27 | + |
| 28 | + parser.add_flags(flags) |
| 29 | + |
| 30 | + if mode == 'exec': |
| 31 | + return parser.file_input() |
| 32 | + elif mode == 'single': |
| 33 | + return parser.single_input() |
| 34 | + elif mode == 'eval': |
| 35 | + return parser.eval_input() |
0 commit comments