Debian Codegraph @

pypy/interpreter/pycompiler.py

raw symbols SCIP
1 """
2 General classes for bytecode compilers.
3 Compiler instances are stored into 'space.getexecutioncontext().compiler'.
4 """
5
6 from pypy.interpreter import pycode
7 from pypy.interpreter.pyparser import future, pyparse, error as parseerror
8 from pypy.interpreter.astcompiler import (codegen, consts, misc,
9 optimize, ast, validate)
10 from pypy.interpreter.error import OperationError, oefmt
11
12
13 class AbstractCompiler(object):
14 """Abstract base class for a bytecode compiler."""
15
16 # The idea is to grow more methods here over the time,
17 # e.g. to handle .pyc files in various ways if we have multiple compilers.
18
19 def __init__(self, space):
20 self.space = space
21 self.w_compile_hook = space.w_None
22
23 def compile(self, source, filename, mode, flags=0):
24 """Compile and return an pypy.interpreter.eval.Code instance."""
25 raise NotImplementedError
26
27 def getcodeflags(self, code):
28 """Return the __future__ compiler flags that were used to compile
29 the given code object."""
30 return 0
31
32 def compile_command(self, source, filename, mode, flags):
33 """Same as compile(), but tries to compile a possibly partial
34 interactive input. If more input is needed, it returns None.
35 """
36 # Hackish default implementation based on the stdlib 'codeop' module.
37 # See comments over there.
38 space = self.space
39 flags |= consts.PyCF_DONT_IMPLY_DEDENT
40 # Check for source consisting of only blank lines and comments
41 if mode != "eval":
42 in_comment = False
43 for c in source:
44 if c in ' \t\f\v': # spaces
45 pass
46 elif c == '#':
47 in_comment = True
48 elif c in '\n\r':
49 in_comment = False
50 elif not in_comment:
51 break # non-whitespace, non-comment character
52 else:
53 source = "pass" # Replace it with a 'pass' statement
54
55 try:
56 code = self.compile(source, filename, mode, flags)
57 return code # success
58 except OperationError as err:
59 if not err.match(space, space.w_SyntaxError):
60 raise
61
62 try:
63 self.compile(source + "\n", filename, mode, flags)
64 return None # expect more
65 except OperationError as err1:
66 if not err1.match(space, space.w_SyntaxError):
67 raise
68
69 try:
70 self.compile(source + "\n\n", filename, mode, flags)
71 raise # uh? no error with \n\n. re-raise the previous error
72 except OperationError as err2:
73 if not err2.match(space, space.w_SyntaxError):
74 raise
75
76 if space.eq_w(err1.get_w_value(space), err2.get_w_value(space)):
77 raise # twice the same error, re-raise
78
79 return None # two different errors, expect more
80
81
82 class PyCodeCompiler(AbstractCompiler):
83 """Base class for compilers producing PyCode objects."""
84
85 def getcodeflags(self, code):
86 """Return the __future__ compiler flags that were used to compile
87 the given code object."""
88 if isinstance(code, pycode.PyCode):
89 return code.co_flags & self.compiler_flags
90 else:
91 return 0
92
93
94 class PythonAstCompiler(PyCodeCompiler):
95 """Uses the stdlib's python implementation of compiler
96
97 XXX: This class should override the baseclass implementation of
98 compile_command() in order to optimize it, especially in case
99 of incomplete inputs (e.g. we shouldn't re-compile from scratch
100 the whole source after having only added a new '\n')
101 """
102 def __init__(self, space, override_version=None):
103 PyCodeCompiler.__init__(self, space)
104 self.future_flags = future.futureFlags_3_11
105 self.parser = pyparse.PegParser(space, self.future_flags)
106 self.additional_rules = {}
107 self.compiler_flags = self.future_flags.allowed_flags
108
109 def compile_ast(self, node, filename, mode, flags=0, optimize=-1):
110 if mode == 'eval':
111 check = isinstance(node, ast.Expression)
112 elif mode == 'exec':
113 check = isinstance(node, ast.Module)
114 elif mode == 'input':
115 check = isinstance(node, ast.Interactive)
116 elif mode == 'func_type':
117 raise oefmt(self.space.w_ValueError, "can't compile func_type input")
118 else:
119 check = True
120 if not check:
121 raise oefmt(self.space.w_TypeError, "invalid node type")
122 if optimize == -1:
123 optimize = self.space.sys.get_optimize()
124
125 fut = misc.parse_future(self.space, node, self.future_flags.compiler_features)
126 f_flags, f_lineno, f_col = fut
127 future_pos = f_lineno, f_col
128 flags |= f_flags
129 info = pyparse.CompileInfo(filename, mode, flags, future_pos,
130 optimize=optimize)
131 return self._compile_ast(node, info)
132
133 def _compile_ast(self, node, info, source=None):
134 from pypy.interpreter.astcompiler.unparse import unparse_annotations
135 space = self.space
136 try:
137 if info.flags & consts.CO_FUTURE_ANNOTATIONS:
138 node = unparse_annotations(space, node)
139 mod = optimize.optimize_ast(space, node, info)
140 code = codegen.compile_ast(space, mod, info)
141 except parseerror.SyntaxError as e:
142 raise OperationError(space.w_SyntaxError, e.find_sourceline_and_wrap_info(space, source, info.filename))
143 return code
144
145 def validate_ast(self, node):
146 try:
147 validate.validate_ast(self.space, node)
148 except validate.ValidationTypeError as e:
149 raise OperationError(self.space.w_TypeError,
150 self.space.newtext(e.message))
151 except validate.ValidationError as e:
152 raise OperationError(self.space.w_ValueError,
153 self.space.newtext(e.message))
154
155 def compile_to_ast(self, source, filename, mode, flags=0, feature_version=-1):
156 info = pyparse.CompileInfo(filename, mode, flags, feature_version=feature_version)
157 return self._compile_to_ast(source, info)
158
159 def _compile_to_ast(self, source, info):
160 space = self.space
161 self.parser.reset()
162 try:
163 mod = self.parser.parse_source(source, info)
164 except parseerror.TabError as e:
165 raise OperationError(space.w_TabError,
166 e.find_sourceline_and_wrap_info(space, source, info.filename))
167 except parseerror.IndentationError as e:
168 raise OperationError(space.w_IndentationError, e.find_sourceline_and_wrap_info(space, source, info.filename))
169 except parseerror.SyntaxError as e:
170 raise OperationError(space.w_SyntaxError, e.find_sourceline_and_wrap_info(space, source, info.filename))
171 return mod
172
173 def compile(self, source, filename, mode, flags=0, hidden_applevel=False,
174 optimize=-1):
175 if optimize == -1:
176 optimize = self.space.sys.get_optimize()
177 assert optimize >= 0
178 info = pyparse.CompileInfo(filename, mode, flags,
179 hidden_applevel=hidden_applevel, optimize=optimize)
180 mod = self._compile_to_ast(source, info)
181 return self._compile_ast(mod, info, source)