From 1a8c4f96df0aa4669e8b019b8d78dd4c6342e4cb Mon Sep 17 00:00:00 2001 From: Evan Hubinger Date: Sat, 12 Oct 2024 20:55:56 -0700 Subject: [PATCH] Prepare for snapshotting --- coconut/compiler/compiler.py | 21 +++++++++++++-------- coconut/util.py | 13 +++++++++---- 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/coconut/compiler/compiler.py b/coconut/compiler/compiler.py index cae7f6d8..54a92092 100644 --- a/coconut/compiler/compiler.py +++ b/coconut/compiler/compiler.py @@ -37,11 +37,11 @@ from functools import partial, wraps from collections import defaultdict from threading import Lock +from copy import copy from coconut._pyparsing import ( USE_COMPUTATION_GRAPH, USE_CACHE, - USE_LINE_BY_LINE, ParseBaseException, ParseResults, col as getcol, @@ -108,6 +108,7 @@ assert_remove_suffix, dictset, noop_ctx, + create_method, ) from coconut.exceptions import ( CoconutException, @@ -484,12 +485,16 @@ def get_cli_args(self): args.append("--no-wrap-types") return args - def __copy__(self): - """Create a new, blank copy of the compiler.""" - cls, args = self.__reduce__() - return cls(*args) - - copy = __copy__ + def copy(self, snapshot=False): + """Create a blank copy of the compiler, or a non-blank copy if snapshot=True.""" + if snapshot: + old_reduce, self.__reduce__ = self.__reduce__, create_method(object.__reduce__, self, self.__class__) + try: + return copy(self) + finally: + self.__reduce__ = old_reduce + else: + return copy(self) def genhash(self, code, package_level=-1): """Generate a hash from code.""" @@ -1357,7 +1362,7 @@ def run_final_checks(self, original, keep_state=False): def parse_line_by_line(self, init_parser, line_parser, original): """Apply init_parser then line_parser repeatedly.""" - if not USE_LINE_BY_LINE: + if not USE_COMPUTATION_GRAPH: raise CoconutException("line-by-line parsing not supported", extra="run 'pip install --upgrade cPyparsing' to fix") with ComputationNode.using_overrides(): ComputationNode.override_original = original diff --git a/coconut/util.py b/coconut/util.py index 51b8abc3..89f96e58 100644 --- a/coconut/util.py +++ b/coconut/util.py @@ -107,6 +107,14 @@ def __call__(self, *args, **kwargs): return self.value +def create_method(func, obj, objtype): + """Universally create a new method object.""" + if PY2: + return MethodType(func, obj, objtype) + else: + return MethodType(func, obj) + + class override(pickleable_obj): """Implementation of Coconut's @override for use within Coconut.""" __slots__ = ("func",) @@ -129,10 +137,7 @@ def __get__(self, obj, objtype=None): return self.func.__get__(obj, objtype) if obj is None: return self.func - if PY2: - return MethodType(self.func, obj, objtype) - else: - return MethodType(self.func, obj) + return create_method(self.func, obj, objtype) def __set_name__(self, obj, name): if not hasattr(super(obj, obj), name):