def _compile(node, source=None, mode='eval', filename=None, lineno=-1, xform=None): if not filename: filename = '<string>' if IS_PYTHON2: # Python 2 requires non-unicode filenames if isinstance(filename, str): filename = filename.encode('utf-8', 'replace') else: # Python 3 requires unicode filenames if not isinstance(filename, str): filename = filename.decode('utf-8', 'replace') if lineno <= 0: lineno = 1 if xform is None: xform = { 'eval': ExpressionASTTransformer }.get(mode, TemplateASTTransformer) tree = xform().visit(node) if mode == 'eval': name = '<Expression %r>' % (source or '?') else: lines = source.splitlines() if not lines: extract = '' else: extract = lines[0] if len(lines) > 1: extract += ' ...' name = '<Suite %r>' % (extract) new_source = ASTCodeGenerator(tree).code code = compile(new_source, filename, mode) try: # We'd like to just set co_firstlineno, but it's readonly. So we need # to clone the code object while adjusting the line number return build_code_chunk(code, filename, name, lineno) except RuntimeError: return code
def _compile(node, source=None, mode='eval', filename=None, lineno=-1, xform=None): if not filename: filename = '<string>' if IS_PYTHON2: # Python 2 requires non-unicode filenames if isinstance(filename, unicode): filename = filename.encode('utf-8', 'replace') else: # Python 3 requires unicode filenames if not isinstance(filename, unicode): filename = filename.decode('utf-8', 'replace') if lineno <= 0: lineno = 1 if xform is None: xform = { 'eval': ExpressionASTTransformer }.get(mode, TemplateASTTransformer) tree = xform().visit(node) if mode == 'eval': name = '<Expression %r>' % (source or '?') else: lines = source.splitlines() if not lines: extract = '' else: extract = lines[0] if len(lines) > 1: extract += ' ...' name = '<Suite %r>' % (extract) new_source = ASTCodeGenerator(tree).code code = compile(new_source, filename, mode) try: # We'd like to just set co_firstlineno, but it's readonly. So we need # to clone the code object while adjusting the line number return build_code_chunk(code, filename, name, lineno) except RuntimeError: return code