| 1 |
from pypy.interpreter.error import OperationError |
| 2 |
from pypy.interpreter.pyparser import future, parser, pytokenizer, pygram, error, pytoken |
| 3 |
from pypy.interpreter.astcompiler import consts |
| 4 |
from pypy.module.sys.version import CPYTHON_VERSION |
| 5 |
from rpython.rlib import rstring |
| 6 |
|
| 7 |
CPYTHON_MINOR_VERSION = CPYTHON_VERSION[1] |
| 8 |
|
| 9 |
def recode_to_utf8(space, bytes, encoding): |
| 10 |
if encoding == 'utf-8': |
| 11 |
return bytes |
| 12 |
w_text = space.call_method(space.newbytes(bytes), "decode", |
| 13 |
space.newtext(encoding)) |
| 14 |
w_recoded = space.call_method(w_text, "encode", space.newtext("utf-8")) |
| 15 |
return space.bytes_w(w_recoded) |
| 16 |
|
| 17 |
def _normalize_encoding(encoding): |
| 18 |
"""returns normalized name for <encoding> |
| 19 |
|
| 20 |
see dist/src/Parser/tokenizer.c 'get_normal_name()' |
| 21 |
for implementation details / reference |
| 22 |
|
| 23 |
NOTE: for now, parser.suite() raises a MemoryError when |
| 24 |
a bad encoding is used. (SF bug #979739) |
| 25 |
""" |
| 26 |
if encoding is None: |
| 27 |
return None |
| 28 |
|
| 29 |
encoding = encoding.replace('_', '-').lower() |
| 30 |
if encoding == 'utf-8' or encoding.startswith('utf-8-'): |
| 31 |
return 'utf-8' |
| 32 |
for variant in ['latin-1', 'iso-latin-1', 'iso-8859-1']: |
| 33 |
if (encoding == variant or |
| 34 |
encoding.startswith(variant + '-')): |
| 35 |
return 'iso-8859-1' |
| 36 |
return encoding |
| 37 |
|
| 38 |
def _check_for_encoding(s): |
| 39 |
eol = s.find('\n') |
| 40 |
if eol < 0: |
| 41 |
return _check_line_for_encoding(s)[0] |
| 42 |
enc, again = _check_line_for_encoding(s[:eol]) |
| 43 |
if enc or not again: |
| 44 |
return enc |
| 45 |
eol2 = s.find('\n', eol + 1) |
| 46 |
if eol2 < 0: |
| 47 |
return _check_line_for_encoding(s[eol + 1:])[0] |
| 48 |
return _check_line_for_encoding(s[eol + 1:eol2])[0] |
| 49 |
|
| 50 |
|
| 51 |
def _check_line_for_encoding(line): |
| 52 |
"""returns the declared encoding or None""" |
| 53 |
i = 0 |
| 54 |
for i in range(len(line)): |
| 55 |
if line[i] == '#': |
| 56 |
break |
| 57 |
if line[i] not in ' \t\014': |
| 58 |
return None, False |
| 59 |
return pytokenizer.match_encoding_declaration(line[i:]), True |
| 60 |
|
| 61 |
|
| 62 |
class CompileInfo(object): |
| 63 |
"""Stores information about the source being compiled. |
| 64 |
|
| 65 |
* filename: The filename of the source. |
| 66 |
* mode: The parse mode to use. ('exec', 'eval', 'single' or 'func_type') |
| 67 |
* flags: Parser and compiler flags. |
| 68 |
* encoding: The source encoding. |
| 69 |
* last_future_import: The line number and offset of the last __future__ |
| 70 |
import. |
| 71 |
* hidden_applevel: Will this code unit and sub units be hidden at the |
| 72 |
applevel? |
| 73 |
* optimize: optimization level: |
| 74 |
0 = no optmiziation, |
| 75 |
1 = remove asserts, |
| 76 |
2 = remove docstrings. |
| 77 |
""" |
| 78 |
|
| 79 |
def __init__(self, filename, mode="exec", flags=0, future_pos=(0, 0), |
| 80 |
hidden_applevel=False, optimize=0, feature_version=-1): |
| 81 |
assert optimize >= 0 |
| 82 |
if feature_version == -1: |
| 83 |
feature_version = CPYTHON_MINOR_VERSION |
| 84 |
if feature_version < 7: |
| 85 |
flags |= consts.PyCF_ASYNC_HACKS |
| 86 |
rstring.check_str0(filename) |
| 87 |
self.filename = filename |
| 88 |
self.mode = mode |
| 89 |
self.encoding = None |
| 90 |
self.flags = flags |
| 91 |
self.optimize = optimize |
| 92 |
self.last_future_import = future_pos |
| 93 |
self.hidden_applevel = hidden_applevel |
| 94 |
self.feature_version = feature_version |
| 95 |
self.source_ends_with_newline = False |
| 96 |
|
| 97 |
|
| 98 |
class PythonParser(object): |
| 99 |
|
| 100 |
@staticmethod |
| 101 |
def _handle_encoding(bytessrc, compile_info, space): |
| 102 |
|
| 103 |
explicit_encoding = False |
| 104 |
enc = None |
| 105 |
if compile_info.flags & consts.PyCF_SOURCE_IS_UTF8: |
| 106 |
enc = 'utf-8' |
| 107 |
|
| 108 |
if compile_info.flags & consts.PyCF_IGNORE_COOKIE: |
| 109 |
textsrc = bytessrc |
| 110 |
elif bytessrc.startswith("\xEF\xBB\xBF"): |
| 111 |
bytessrc = bytessrc[3:] |
| 112 |
enc = 'utf-8' |
| 113 |
|
| 114 |
decl_enc = _check_for_encoding(bytessrc) |
| 115 |
explicit_encoding = (decl_enc is not None) |
| 116 |
if decl_enc and _normalize_encoding(decl_enc) != "utf-8": |
| 117 |
raise error.SyntaxError("UTF-8 BOM with %s coding cookie" % decl_enc, |
| 118 |
offset=-1, |
| 119 |
filename=compile_info.filename) |
| 120 |
textsrc = bytessrc |
| 121 |
else: |
| 122 |
enc = _normalize_encoding(_check_for_encoding(bytessrc)) |
| 123 |
explicit_encoding = (enc is not None) |
| 124 |
if enc is None: |
| 125 |
enc = 'utf-8' |
| 126 |
try: |
| 127 |
textsrc = recode_to_utf8(space, bytessrc, enc) |
| 128 |
except OperationError as e: |
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
if e.match(space, space.w_LookupError): |
| 133 |
raise error.SyntaxError("Unknown encoding: %s" % enc, |
| 134 |
filename=compile_info.filename) |
| 135 |
|
| 136 |
if e.match(space, space.w_UnicodeDecodeError): |
| 137 |
w_value = e.normalize_exception(space) |
| 138 |
w_message = space.str(w_value) |
| 139 |
raise error.SyntaxError(space.text_w(w_message)) |
| 140 |
raise |
| 141 |
if enc is not None: |
| 142 |
compile_info.encoding = enc |
| 143 |
if explicit_encoding: |
| 144 |
compile_info.flags |= consts.PyCF_FOUND_ENCODING |
| 145 |
return textsrc |
| 146 |
|
| 147 |
@staticmethod |
| 148 |
def _check_token_stream_single(compile_info, tokens_stream): |
| 149 |
for token in tokens_stream: |
| 150 |
if token.token_type == pygram.tokens.ENDMARKER: |
| 151 |
break |
| 152 |
if token.token_type == pygram.tokens.NEWLINE: |
| 153 |
continue |
| 154 |
|
| 155 |
if token.token_type == pygram.tokens.COMMENT: |
| 156 |
for token in tokens_stream: |
| 157 |
if token.token_type == pygram.tokens.NEWLINE: |
| 158 |
break |
| 159 |
else: |
| 160 |
new_err = error.SyntaxError |
| 161 |
msg = ("multiple statements found while " |
| 162 |
"compiling a single statement") |
| 163 |
raise new_err(msg, token.lineno, token.column, |
| 164 |
token.line, compile_info.filename) |
| 165 |
|
| 166 |
class PegParser(object): |
| 167 |
def __init__(self, space, future_flags=future.futureFlags_3_11): |
| 168 |
self.space = space |
| 169 |
self.future_flags = future_flags |
| 170 |
self.type_ignores = [] |
| 171 |
|
| 172 |
def reset(self): |
| 173 |
pass |
| 174 |
|
| 175 |
def parse_source(self, bytessrc, compile_info): |
| 176 |
"""Main entry point for parsing Python source. |
| 177 |
|
| 178 |
Everything from decoding the source to tokenizing to building the parse |
| 179 |
tree is handled here. |
| 180 |
""" |
| 181 |
if '\x00' in bytessrc: |
| 182 |
null_pos = bytessrc.find('\x00') |
| 183 |
assert null_pos >= 0 |
| 184 |
text_before = bytessrc[:null_pos] |
| 185 |
lineno = text_before.count('\n') + 1 |
| 186 |
line_start = text_before.rfind('\n') + 1 |
| 187 |
assert line_start >= 0 |
| 188 |
line_text = text_before[line_start:] + '\n' |
| 189 |
raise error.SyntaxError("source code cannot contain null bytes", |
| 190 |
lineno=lineno, |
| 191 |
text=line_text, |
| 192 |
filename=compile_info.filename) |
| 193 |
textsrc = PythonParser._handle_encoding(bytessrc, compile_info, self.space) |
| 194 |
return self._parse(textsrc, compile_info) |
| 195 |
|
| 196 |
def _parse(self, textsrc, compile_info): |
| 197 |
from pypy.interpreter.pyparser.rpypegparse import PythonParser |
| 198 |
|
| 199 |
flags = compile_info.flags |
| 200 |
|
| 201 |
|
| 202 |
source_lines = textsrc.splitlines(True) |
| 203 |
compile_info.source_ends_with_newline = textsrc.endswith("\n") |
| 204 |
if source_lines and not compile_info.source_ends_with_newline: |
| 205 |
source_lines[-1] += '\n' |
| 206 |
if compile_info.source_ends_with_newline or compile_info.mode != "single": |
| 207 |
flags &= ~consts.PyCF_DONT_IMPLY_DEDENT |
| 208 |
compile_info.flags &= ~consts.PyCF_DONT_IMPLY_DEDENT |
| 209 |
else: |
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
compile_info.flags |= consts.PyCF_DONT_IMPLY_DEDENT |
| 215 |
|
| 216 |
try: |
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
tokens = pytokenizer.generate_tokens(source_lines, flags, |
| 221 |
compile_info.filename) |
| 222 |
except error.TokenError as e: |
| 223 |
if compile_info.flags & consts.PyCF_ALLOW_INCOMPLETE_INPUT: |
| 224 |
single_quote_finalized = ( |
| 225 |
pytokenizer.SINGLE_QUOTE_UNTERMINATED_ERROR in e.msg and |
| 226 |
not textsrc.endswith('\\') and |
| 227 |
not textsrc.endswith('\\\n') and |
| 228 |
not textsrc.endswith('\\\r') and |
| 229 |
not textsrc.endswith('\\\r\n')) |
| 230 |
if not single_quote_finalized and ( |
| 231 |
pytokenizer.TRIPLE_QUOTE_UNTERMINATED_ERROR in e.msg or |
| 232 |
pytokenizer.SINGLE_QUOTE_UNTERMINATED_ERROR in e.msg or |
| 233 |
'was never closed' in e.msg or |
| 234 |
pytokenizer.EOF_MULTI_LINE_STATEMENT_ERROR in e.msg): |
| 235 |
e.msg = "incomplete input" |
| 236 |
e.filename = compile_info.filename |
| 237 |
raise |
| 238 |
except error.TokenIndentationError as e: |
| 239 |
e.filename = compile_info.filename |
| 240 |
raise |
| 241 |
|
| 242 |
|
| 243 |
newflags, last_future_import = ( |
| 244 |
future.add_future_flags(self.future_flags, tokens)) |
| 245 |
compile_info.last_future_import = last_future_import |
| 246 |
compile_info.flags |= newflags |
| 247 |
|
| 248 |
mode = compile_info.mode |
| 249 |
if mode != "single": |
| 250 |
assert tokens[-2].token_type == pytoken.python_tokens['NEWLINE'] |
| 251 |
del tokens[-2] |
| 252 |
pp = PythonParser(self.space, tokens, compile_info) |
| 253 |
try: |
| 254 |
for token in tokens: |
| 255 |
|
| 256 |
if token.token_type == pygram.tokens.TYPE_IGNORE: |
| 257 |
self.type_ignores.append(token) |
| 258 |
if mode == "exec": |
| 259 |
meth = PythonParser.file |
| 260 |
elif mode == "single": |
| 261 |
meth = PythonParser.interactive |
| 262 |
elif mode == "eval": |
| 263 |
meth = PythonParser.eval |
| 264 |
elif mode == "func_type": |
| 265 |
meth = PythonParser.func_type |
| 266 |
else: |
| 267 |
assert 0, "unknown mode" |
| 268 |
return pp.parse_meth_or_raise(meth) |
| 269 |
except error.TokenError as e: |
| 270 |
e.filename = compile_info.filename |
| 271 |
raise |
| 272 |
except error.TokenIndentationError as e: |
| 273 |
e.filename = compile_info.filename |
| 274 |
raise |
| 275 |
|
| 276 |
|