Debian Codegraph @

pypy/module/__builtin__/compiling.py

raw symbols SCIP
1 """
2 Implementation of the interpreter-level compile/eval builtins.
3 """
4
5 from pypy.interpreter.pycode import PyCode
6 from pypy.interpreter.error import OperationError, oefmt
7 from pypy.interpreter.astcompiler import consts, ast
8 from pypy.interpreter.gateway import unwrap_spec
9 from pypy.interpreter.argument import Arguments
10 from pypy.interpreter.nestedscope import Cell
11 from pypy.interpreter.function import Function
12
13 @unwrap_spec(filename='fsencode', mode='text', flags=int, dont_inherit=int,
14 optimize=int, _feature_version=int)
15 def compile(space, w_source, filename, mode, flags=0, dont_inherit=0,
16 optimize=-1, _feature_version=-1):
17 """Compile the source string (a Python module, statement or expression)
18 into a code object that can be executed by the exec statement or eval().
19 The filename will be used for run-time error messages.
20 The mode must be 'exec' to compile a module, 'single' to compile a
21 single (interactive) statement, or 'eval' to compile an expression.
22 The flags argument, if present, controls which future statements influence
23 the compilation of the code.
24 The dont_inherit argument, if non-zero, stops the compilation inheriting
25 the effects of any future statements in effect in the code calling
26 compile; if absent or zero these statements do influence the compilation,
27 in addition to any features explicitly specified.
28 """
29 from pypy.interpreter.pyopcode import source_as_str
30 # only allow default value of _feature_version for now
31 # we need to support the keyword argument, the ast module passes it (set to
32 # -1, usually)
33 if _feature_version >= 0 and (flags & consts.PyCF_ONLY_AST):
34 feature_version = _feature_version
35 else:
36 feature_version = -1
37
38 ec = space.getexecutioncontext()
39 if flags & ~(ec.compiler.compiler_flags | consts.PyCF_ONLY_AST |
40 consts.PyCF_DONT_IMPLY_DEDENT | consts.PyCF_SOURCE_IS_UTF8 |
41 consts.PyCF_ACCEPT_NULL_BYTES | consts.PyCF_TYPE_COMMENTS |
42 consts.PyCF_ALLOW_TOP_LEVEL_AWAIT | consts.PyCF_ALLOW_INCOMPLETE_INPUT |
43 consts.PyCF_IGNORE_COOKIE):
44 raise oefmt(space.w_ValueError, "compile() unrecognized flags")
45
46 only_ast = flags & consts.PyCF_ONLY_AST
47
48 if not dont_inherit:
49 caller = ec.gettopframe_nohidden()
50 if caller:
51 flags |= ec.compiler.getcodeflags(caller.getcode())
52
53 if mode not in ('exec', 'eval', 'single', 'func_type'):
54 if only_ast:
55 raise oefmt(space.w_ValueError,
56 "compile() mode must be 'exec', 'eval', 'single' or 'func_type'")
57 else:
58 raise oefmt(space.w_ValueError,
59 "compile() arg 3 must be 'exec', 'eval' or 'single'")
60
61 if mode == "func_type" and not only_ast:
62 raise oefmt(space.w_ValueError,
63 "compile() mode 'func_type' requires flag PyCF_ONLY_AST")
64
65 if optimize < -1 or optimize > 2:
66 raise oefmt(space.w_ValueError,
67 "compile(): invalid optimize value")
68
69 if space.isinstance_w(w_source, space.gettypeobject(ast.W_AST.typedef)):
70 if only_ast:
71 return w_source
72 ast_node = ast.mod.from_object(space, w_source)
73 ec.compiler.validate_ast(ast_node)
74 return ec.compiler.compile_ast(ast_node, filename, mode, flags,
75 optimize=optimize)
76
77 flags |= consts.PyCF_SOURCE_IS_UTF8
78 source, flags = source_as_str(space, w_source, 'compile',
79 "string, bytes or AST", flags)
80
81 if only_ast:
82 node = ec.compiler.compile_to_ast(source, filename, mode, flags, feature_version)
83 return node.to_object(space)
84 else:
85 return ec.compiler.compile(source, filename, mode, flags,
86 optimize=optimize)
87
88
89 def eval(space, w_prog, w_globals=None, w_locals=None):
90 """Evaluate the source in the context of globals and locals.
91 The source may be a string representing a Python expression
92 or a code object as returned by compile(). The globals and locals
93 are dictionaries, defaulting to the current current globals and locals.
94 If only globals is given, locals defaults to it.
95 """
96 from pypy.interpreter.pyopcode import ensure_ns, source_as_str
97 w_globals, w_locals = ensure_ns(space, w_globals, w_locals, 'eval')
98
99 if space.isinstance_w(w_prog, space.gettypeobject(PyCode.typedef)):
100 code = space.interp_w(PyCode, w_prog)
101 space.audit("exec", [w_prog])
102 else:
103 source, flags = source_as_str(space, w_prog, 'eval',
104 "string, bytes or code",
105 consts.PyCF_SOURCE_IS_UTF8)
106 ec = space.getexecutioncontext()
107 code = ec.compiler.compile(source.lstrip(' \t'), "<string>", 'eval',
108 flags)
109 if not space.contains_w(w_globals, space.newtext("__builtins__")):
110 space.setitem_str(w_globals, "__builtins__", space.builtin)
111
112 return code.exec_code(space, w_globals, w_locals)
113
114 def exec_(space, w_prog, w_globals=None, w_locals=None, __posonly__=None, w_closure=None):
115 """
116 exec(source, globals=None, locals=None, *, closure=None)
117
118 Execute the given source in the context of globals and locals.
119
120 The source may be a string representing one or more Python statements
121 or a code object as returned by compile().
122 The globals must be a dictionary and locals can be any mapping,
123 defaulting to the current globals and locals.
124 If only globals is given, locals defaults to it.
125
126 The closure must be a tuple of cellvars, and can only be used when source
127 is a code object requiring exactly that many cellvars.
128 """
129
130 frame = space.getexecutioncontext().gettopframe()
131 frame.exec_(w_prog, w_globals, w_locals, w_closure)
132
133 def _update_bases(space, w_bases, bases_w):
134 new_bases_w = None
135 for i, w_base in enumerate(bases_w):
136 if space.isinstance_w(w_base, space.w_type):
137 if new_bases_w is not None:
138 new_bases_w.append(w_base)
139 continue
140 w_meth = None
141 try:
142 # one of the few places where cpython uses getattr not lookup
143 w_meth = space.getattr(w_base, space.newtext('__mro_entries__'))
144 except OperationError as e:
145 if not e.match(space, space.w_AttributeError):
146 raise
147 if new_bases_w is not None:
148 new_bases_w.append(w_base)
149 else:
150 w_new_base = space.call_function(w_meth, w_bases)
151 if not space.isinstance_w(w_new_base, space.w_tuple):
152 raise oefmt(space.w_TypeError, "__mro_entries__ must return a tuple")
153 if new_bases_w is None:
154 new_bases_w = bases_w[:i]
155 new_bases_w.extend(space.fixedview(w_new_base))
156 if new_bases_w is None:
157 return bases_w
158 return new_bases_w[:]
159
160 def build_class(space, w_func, w_name, __args__):
161 from pypy.objspace.std.typeobject import _calculate_metaclass, W_TypeObject
162 from pypy.interpreter.nestedscope import Cell
163 if not isinstance(w_func, Function):
164 raise oefmt(space.w_TypeError, "__build_class__: func must be a function")
165 orig_bases_w, kwds_w = __args__.unpack()
166 w_orig_bases = space.newtuple(orig_bases_w)
167 bases_w = _update_bases(space, w_orig_bases, orig_bases_w)
168 w_bases = space.newtuple(bases_w)
169 w_meta = kwds_w.pop('metaclass', None)
170 if w_meta is not None:
171 isclass = space.isinstance_w(w_meta, space.w_type)
172 else:
173 if bases_w:
174 w_meta = space.type(bases_w[0])
175 else:
176 w_meta = space.w_type
177 isclass = True
178 if isclass:
179 # w_meta is really a class, so check for a more derived
180 # metaclass, or possible metaclass conflicts
181 w_meta = _calculate_metaclass(space, w_meta, bases_w)
182
183 try:
184 w_prep = space.getattr(w_meta, space.newtext("__prepare__"))
185 except OperationError as e:
186 if not e.match(space, space.w_AttributeError):
187 raise
188 w_namespace = space.newdict(module=True)
189 else:
190 # XXX mess
191 keyword_names_w = [space.newtext(kwd) for kwd in kwds_w.keys()]
192 args = Arguments(space,
193 args_w=[w_name, w_bases],
194 keyword_names_w=keyword_names_w,
195 keywords_w=kwds_w.values())
196 w_namespace = space.call_args(w_prep, args)
197 if not space.ismapping_w(w_namespace):
198 if isclass:
199 raise oefmt(space.w_TypeError,
200 "%N.__prepare__() must return a mapping, not %T",
201 w_meta, w_namespace)
202 else:
203 raise oefmt(space.w_TypeError,
204 "<metaclass>.__prepare__() must return a mapping, not %T",
205 w_namespace)
206
207 code = w_func.getcode()
208 frame = space.createframe(code, w_func.w_func_globals, w_func)
209 frame.setdictscope(w_namespace)
210 w_cell = frame.run()
211 if bases_w is not orig_bases_w:
212 space.setitem(w_namespace, space.newtext("__orig_bases__"), w_orig_bases)
213 keyword_names_w = [space.newtext(kwd) for kwd in kwds_w.keys()]
214 args = Arguments(space,
215 args_w=[w_name, w_bases, w_namespace],
216 keyword_names_w=keyword_names_w,
217 keywords_w=kwds_w.values())
218 try:
219 w_class = space.call_args(w_meta, args)
220 except OperationError as e:
221 # give a more comprehensible error message for TypeErrors
222 if e.got_any_traceback():
223 raise
224 if (not e.match(space, space.w_TypeError) or
225 space.is_w(w_meta, space.w_type)):
226 raise
227 raise oefmt(space.w_TypeError,
228 "metaclass found to be '%N', but calling %R "
229 "with args (%R, %R, ...) raised %R",
230 w_meta, w_meta, w_name, w_bases,
231 e.get_w_value(space))
232 if isinstance(w_cell, Cell) and isinstance(w_class, W_TypeObject):
233 if w_cell.empty():
234 raise oefmt(space.w_RuntimeError,
235 "__class__ not set defining %S as %S. "
236 "Was __classcell__ propagated to type.__new__?",
237 w_name,
238 w_class)
239
240 else:
241 w_class_from_cell = w_cell.get()
242 if not space.is_w(w_class, w_class_from_cell):
243 raise oefmt(
244 space.w_TypeError,
245 "__class__ set to %S defining %S as %S",
246 w_class_from_cell, w_name, w_class)
247 return w_class