From cdc52c42f7229854b64f7b3894ecd08f0d091e7a Mon Sep 17 00:00:00 2001 From: Dominic Orchard Date: Fri, 23 Oct 2026 09:15:48 +0100 Subject: [PATCH 01/11] fix nat_of_integer bug --- Python_Setup.thy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python_Setup.thy b/Python_Setup.thy index 1a148cf..c023879 100644 --- a/Python_Setup.thy +++ b/Python_Setup.thy @@ -49,7 +49,7 @@ code_printing | constant "(<) :: nat \ nat \ bool" \ (Python) "(_ < _)" code_printing - constant Code_Numeral.nat_of_integer \ (Python) "_" + constant Code_Numeral.nat_of_integer \ (Python) "max(0, _)" | constant Code_Numeral.integer_of_nat \ (Python) "_" setup \ From 2ad257836b0c521446744b2fddc74c62110dd744 Mon Sep 17 00:00:00 2001 From: Dominic Orchard Date: Fri, 23 Oct 2026 09:26:38 +0100 Subject: [PATCH 02/11] make async a reserved keyword --- code_python.ML | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code_python.ML b/code_python.ML index a8aecba..0229de6 100644 --- a/code_python.ML +++ b/code_python.ML @@ -68,7 +68,7 @@ fun enable_native_encoding name = Native_Encoding_Data.map (Symtab.update (name, fun use_native_encoding thy name = Symtab.defined (Native_Encoding_Data.get thy) name; val python_reserved_words = - ["False", "None", "True", "and", "as", "assert", "await", "break", "class", + ["False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield", "match", "case"] From d17317f5bc7917f864649f65eba08c2b9e24c96a Mon Sep 17 00:00:00 2001 From: Dominic Orchard Date: Fri, 23 Oct 2026 09:51:23 +0100 Subject: [PATCH 03/11] bracket equality for strings, like integers --- Python.thy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python.thy b/Python.thy index 04931fa..3558e17 100644 --- a/Python.thy +++ b/Python.thy @@ -36,7 +36,7 @@ code_printing | constant "(+) :: String.literal \ String.literal \ String.literal" \ (Python) infixl 65 "+" | constant "HOL.equal :: String.literal \ String.literal \ bool" \ - (Python) infixl 40 "==" + (Python) "(_ == _)" | constant "(\) :: String.literal \ String.literal \ bool" \ (Python) infixl 35 "<=" | constant "(<) :: String.literal \ String.literal \ bool" \ From e477f0fdea9b2bd282f1f0357d4f65edc9d9d913 Mon Sep 17 00:00:00 2001 From: Dominic Orchard Date: Fri, 23 Oct 2026 09:55:18 +0100 Subject: [PATCH 04/11] bracket string inequalities too --- Python.thy | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python.thy b/Python.thy index 3558e17..2d33f73 100644 --- a/Python.thy +++ b/Python.thy @@ -38,9 +38,9 @@ code_printing | constant "HOL.equal :: String.literal \ String.literal \ bool" \ (Python) "(_ == _)" | constant "(\) :: String.literal \ String.literal \ bool" \ - (Python) infixl 35 "<=" + (Python) "(_ <= _)" | constant "(<) :: String.literal \ String.literal \ bool" \ - (Python) infixl 35 "<" + (Python) "(_ < _)" setup \ Literal.add_code "Python" From cc461c5c48080dc63bbde21b7a8c66c4342aa677 Mon Sep 17 00:00:00 2001 From: Dominic Orchard Date: Fri, 23 Oct 2026 10:45:55 +0100 Subject: [PATCH 05/11] remove min and max explicit which works out better overall --- Python_Setup.thy | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python_Setup.thy b/Python_Setup.thy index c023879..502d9c2 100644 --- a/Python_Setup.thy +++ b/Python_Setup.thy @@ -25,8 +25,8 @@ code_printing code_printing constant "abs :: int \ int" \ (Python) "abs'(_')" - | constant "min" \ (Python) "min(_, _)" - | constant "max" \ (Python) "max(_, _)" + (* min and max are derived automatically from Isabelle's own definition as `if a <= b then a else b` . + This is coherent with Python's semantics and scales up to data types like sets and lists *) (* Bridge between int and integer *) code_printing @@ -129,7 +129,7 @@ code_reserved (Python) len list map max min abs divmod code_printing type_constructor List.list \ (Python) "_ list" | constant List.list.Nil \ (Python) "[]" - + code_printing constant "length" \ (Python) "len'(_')" | constant List.nth \ (Python) "_[_]" @@ -140,7 +140,7 @@ setup \ let open Code_Thingol Code_Printer; - fun dest_list_literal (IConst { sym = Code_Symbol.Constant + fun dest_list_literal (IConst { sym = Code_Symbol.Constant \<^const_name>\List.list.Nil\, ...}) = SOME [] | dest_list_literal (IConst { sym = Code_Symbol.Constant \<^const_name>\List.list.Cons\, ...} `$ x `$ xs) = @@ -157,7 +157,7 @@ setup \ | NONE => Pretty.block [Pretty.str "[", print_term vars NOBR x, Pretty.str "] + ", print_term vars NOBR xs]; - + in (fn target => Code_Target.set_printings (Code_Symbol.Constant (\<^const_name>\List.list.Cons\, From 4ca4a4588950e62e2de9610392266ec520b23d0a Mon Sep 17 00:00:00 2001 From: Nikolaus Huber Date: Mon, 2 Nov 2026 14:38:44 +0000 Subject: [PATCH 06/11] revert to explicit list of reserved words --- code_python.ML | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/code_python.ML b/code_python.ML index 4b7fdbb..fce9a37 100644 --- a/code_python.ML +++ b/code_python.ML @@ -69,7 +69,7 @@ fun enable_native_encoding name = Native_Encoding_Data.map (Symtab.update (name, fun use_native_encoding thy name = Symtab.defined (Native_Encoding_Data.get thy) name; val python_reserved_words = - ["False", "None", "True", "and", "as", "assert", "async","await", "break", "class", + ["False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield", "match", "case"] @@ -1158,6 +1158,6 @@ val _ = Theory.setup "python3 -m py_compile " ^ Bash.string module_name ^ "/*.py")}, evaluation_args = []}) #> (fn thy => fold (Code_Target.add_reserved target) - (distinct (op =) (python_names thy @ prelude_names)) thy)); + (distinct (op =) python_reserved_words) thy)); end; (* struct *) From 487e59294d9274df0ff88eba17c4ed1bee13783b Mon Sep 17 00:00:00 2001 From: Nikolaus Huber Date: Mon, 2 Nov 2026 14:50:46 +0000 Subject: [PATCH 07/11] add code printing for List.upt --- Python_Setup.thy | 1 + 1 file changed, 1 insertion(+) diff --git a/Python_Setup.thy b/Python_Setup.thy index 5c01c85..a0cd816 100644 --- a/Python_Setup.thy +++ b/Python_Setup.thy @@ -156,6 +156,7 @@ code_printing | constant List.nth \ (Python) "_[_]" | constant List.map \ (Python) "list(map((_), (_)))" | constant List.append \ (Python) "(_ + _)" + | constant List.upt \ (Python) "list(range((_), (_)))" setup \ let From b911b8939bf244254cbb5dc9b508d357dbf6dadb Mon Sep 17 00:00:00 2001 From: Nikolaus Huber Date: Mon, 2 Nov 2026 15:01:44 +0000 Subject: [PATCH 08/11] change the way we handle reserved words --- Makefile | 5 +- Python.thy | 11 ++ README.md | 3 + code_python.ML | 14 +-- etc/python_reserved_words | 192 +++++++++++++++++++++++++++++++++++ etc/update_reserved_words.py | 37 +++++++ 6 files changed, 251 insertions(+), 11 deletions(-) create mode 100644 etc/python_reserved_words create mode 100644 etc/update_reserved_words.py diff --git a/Makefile b/Makefile index 590ae11..2142e5a 100644 --- a/Makefile +++ b/Makefile @@ -32,6 +32,9 @@ test-oracle: build-test-oracle reseed: build-examples $(PYTHON) test/diff/reseed_goldens.py +reserved-words: + $(PYTHON) etc/update_reserved_words.py + test-all: test-quick test-slow test-diff test-oracle test: test-quick @@ -39,7 +42,7 @@ test: test-quick build: $(ISABELLE) build -d . -e Python -.PHONY: default build-test-slow test-slow build-test-quick test-quick build-examples test-diff reseed test-all test build-test-oracle test-oracle build +.PHONY: default build-test-slow test-slow build-test-quick test-quick build-examples test-diff reseed test-all test build-test-oracle test-oracle build reserved-words diff --git a/Python.thy b/Python.thy index 3674fa1..a1fce3b 100644 --- a/Python.thy +++ b/Python.thy @@ -4,6 +4,17 @@ begin ML_file \code_python.ML\ +(* Keywords and builtins of the target Python, which generated names must not hide; + make reserved-words writes the file from the Python in .python-version *) +external_file \etc/python_reserved_words\ + +setup \fn thy => + File.read_lines (Resources.master_directory thy + \<^path>\etc/python_reserved_words\) + |> map trim_line + |> filter_out (fn line => line = "" orelse String.isPrefix "#" line) + |> (fn names => fold (Code_Target.add_reserved Code_Python.target) names thy) +\ + declare [[default_code_width = 2000]] code_identifier diff --git a/README.md b/README.md index 2bd0c34..f4e9e04 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,9 @@ Python 3. - [uv](https://docs.astral.sh/uv/), which runs Python at the version in `.python-version`, the target version of the generated code +Generated names never hide the keywords and builtins listed in `etc/python_reserved_words`. After changing +`.python-version`, regenerate that list with `make reserved-words`. + ## Installing as a component ```bash diff --git a/code_python.ML b/code_python.ML index fce9a37..7730612 100644 --- a/code_python.ML +++ b/code_python.ML @@ -68,14 +68,9 @@ fun enable_native_encoding name = Native_Encoding_Data.map (Symtab.update (name, fun use_native_encoding thy name = Symtab.defined (Native_Encoding_Data.get thy) name; -val python_reserved_words = - ["False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", - "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", - "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", - "raise", "return", "try", "while", "with", "yield", "match", "case"] - - (* these are symbols we use in addition to the standard reserved words *) - @ ["dataclass", "Any", "Callable", "_unimplemented", "_abort", "functools"];; +(* Names bound by the prelude of every generated module; the keywords and builtins of + Python are reserved by Python.thy, from etc/python_reserved_words *) +val prelude_names = ["dataclass", "Any", "Callable", "_unimplemented", "_abort", "functools"]; type eqtn = { patterns: iterm list, (* left hand side pattern list *) @@ -1157,7 +1152,6 @@ val _ = Theory.setup run_command = Code_Target.run_command_bash (fn module_name => "python3 -m py_compile " ^ Bash.string module_name ^ "/*.py")}, evaluation_args = []}) - #> (fn thy => fold (Code_Target.add_reserved target) - (distinct (op =) python_reserved_words) thy)); + #> fold (Code_Target.add_reserved target) prelude_names); end; (* struct *) diff --git a/etc/python_reserved_words b/etc/python_reserved_words new file mode 100644 index 0000000..c24cda0 --- /dev/null +++ b/etc/python_reserved_words @@ -0,0 +1,192 @@ +# Keywords and builtins of Python 3.12, written by etc/update_reserved_words.py +False +None +True +and +as +assert +async +await +break +class +continue +def +del +elif +else +except +finally +for +from +global +if +import +in +is +lambda +nonlocal +not +or +pass +raise +return +try +while +with +yield +case +match +type +ArithmeticError +AssertionError +AttributeError +BaseException +BaseExceptionGroup +BlockingIOError +BrokenPipeError +BufferError +BytesWarning +ChildProcessError +ConnectionAbortedError +ConnectionError +ConnectionRefusedError +ConnectionResetError +DeprecationWarning +EOFError +Ellipsis +EncodingWarning +EnvironmentError +Exception +ExceptionGroup +FileExistsError +FileNotFoundError +FloatingPointError +FutureWarning +GeneratorExit +IOError +ImportError +ImportWarning +IndentationError +IndexError +InterruptedError +IsADirectoryError +KeyError +KeyboardInterrupt +LookupError +MemoryError +ModuleNotFoundError +NameError +NotADirectoryError +NotImplemented +NotImplementedError +OSError +OverflowError +PendingDeprecationWarning +PermissionError +ProcessLookupError +RecursionError +ReferenceError +ResourceWarning +RuntimeError +RuntimeWarning +StopAsyncIteration +StopIteration +SyntaxError +SyntaxWarning +SystemError +SystemExit +TabError +TimeoutError +TypeError +UnboundLocalError +UnicodeDecodeError +UnicodeEncodeError +UnicodeError +UnicodeTranslateError +UnicodeWarning +UserWarning +ValueError +Warning +ZeroDivisionError +__build_class__ +__debug__ +__doc__ +__import__ +__loader__ +__name__ +__package__ +__spec__ +abs +aiter +all +anext +any +ascii +bin +bool +breakpoint +bytearray +bytes +callable +chr +classmethod +compile +complex +copyright +credits +delattr +dict +dir +divmod +enumerate +eval +exec +exit +filter +float +format +frozenset +getattr +globals +hasattr +hash +help +hex +id +input +int +isinstance +issubclass +iter +len +license +list +locals +map +max +memoryview +min +next +object +oct +open +ord +pow +print +property +quit +range +repr +reversed +round +set +setattr +slice +sorted +staticmethod +str +sum +super +tuple +vars +zip diff --git a/etc/update_reserved_words.py b/etc/update_reserved_words.py new file mode 100644 index 0000000..90f6558 --- /dev/null +++ b/etc/update_reserved_words.py @@ -0,0 +1,37 @@ +""" +Writes etc/python_reserved_words: the keywords, soft keywords and builtins of +the Python version in .python-version, which generated names must not hide. +Python.thy reserves every name in that file. + +Run it with that Python, as the make target does through uv: + + make reserved-words +""" + +import builtins +import keyword +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +OUT = ROOT / "etc" / "python_reserved_words" + + +def main(): + version = (ROOT / ".python-version").read_text().strip() + running = ".".join(map(str, sys.version_info[:len(version.split("."))])) + if running != version: + sys.exit(f"{Path(__file__).name}: running Python {running}, but " + f".python-version names {version}") + + # _ is the wildcard pattern the generator prints, so it stays usable + names = keyword.kwlist + [k for k in keyword.softkwlist if k != "_"] + dir(builtins) + lines = [f"# Keywords and builtins of Python {version}, written by " + f"etc/{Path(__file__).name}"] + lines += list(dict.fromkeys(names)) + OUT.write_text("\n".join(lines) + "\n") + print(f"wrote {len(lines) - 1} names to {OUT.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() From 0c2d985fd49327e7d4834d4298200293dbf9f6af Mon Sep 17 00:00:00 2001 From: Nikolaus Huber Date: Mon, 2 Nov 2026 15:02:45 +0000 Subject: [PATCH 09/11] reseed diff tests --- .../Example_class_dicts.py | 2 +- .../Example_iarray.py | 4 ++-- .../Arith.py | 4 ++-- .../Example_integer_bit_ops.py | 10 ++++---- .../Example_nat.py | 20 ++++++++-------- .../Example_nat_edge_cases.py | 8 +++---- .../Example_nat_pattern.py | 6 ++--- .../Example_nested_case.py | 20 ++++++++-------- .../Example_nested_if.py | 24 +++++++++---------- .../Example_polymorphic_const.py | 2 +- .../Example_short_circuit.py | 2 +- 11 files changed, 51 insertions(+), 51 deletions(-) diff --git a/test/diff/golden/Python_Examples.Example_class_dicts/Example_class_dicts.py b/test/diff/golden/Python_Examples.Example_class_dicts/Example_class_dicts.py index 7985deb..2b7cb46 100644 --- a/test/diff/golden/Python_Examples.Example_class_dicts/Example_class_dicts.py +++ b/test/diff/golden/Python_Examples.Example_class_dicts/Example_class_dicts.py @@ -17,7 +17,7 @@ def weight(a_dict, x, xa1): return (0) case (xa, [y, *ys]): if (a_dict[1].order_linorder.preorder_order.ord_preorder.less(y, xa)): - z = (2) + z = (max(0, 2)) else: if (HOL.eq(a_dict[0], y, xa)): z = (1) diff --git a/test/diff/golden/Python_Examples.Example_iarray/Example_iarray.py b/test/diff/golden/Python_Examples.Example_iarray/Example_iarray.py index a8cbea7..f74a5bb 100644 --- a/test/diff/golden/Python_Examples.Example_iarray/Example_iarray.py +++ b/test/diff/golden/Python_Examples.Example_iarray/Example_iarray.py @@ -12,9 +12,9 @@ def _abort(msg, thunk): def sum_ends(a): return (((a[0]) + (a[(max(0, (len(a)) - 1))]))) -squares = (tuple(map(lambda i: (i * i), range(4)))) +squares = (tuple(map(lambda i: (i * i), range((max(0, 4)))))) -example = (((list(squares)), ((sum_ends(squares), (((all(map(lambda x: (x < 10), squares))), IArray.equal_iarray(Nat.equal_nat(), (tuple((list(map(lambda a: (a + 1), [1, 2]))))), (tuple([2, 3]))))))))) +example = (((list(squares)), ((sum_ends(squares), (((all(map(lambda x: (x < (max(0, 10))), squares))), IArray.equal_iarray(Nat.equal_nat(), (tuple((list(map(lambda a: (a + 1), [1, max(0, 2)]))))), (tuple([max(0, 2), max(0, 3)]))))))))) def sub_pair(p): return ((lambda a, i: a[i])(*p)) diff --git a/test/diff/golden/Python_Examples.Example_integer_bit_ops/Arith.py b/test/diff/golden/Python_Examples.Example_integer_bit_ops/Arith.py index a69c90b..3eea699 100644 --- a/test/diff/golden/Python_Examples.Example_integer_bit_ops/Arith.py +++ b/test/diff/golden/Python_Examples.Example_integer_bit_ops/Arith.py @@ -23,10 +23,10 @@ def power_integer(): return Power.power(one_power = one_integer(), times_power = times_integer()) def drop_bit(i, k): - return ((lambda a, b: a // b if b else 0)(k, Power.power_(power_integer(), 2, (abs(i))))) + return ((lambda a, b: a // b if b else 0)(k, Power.power_(power_integer(), 2, (max(0, (abs(i))))))) def push_bit(i, k): - return ((k * Power.power_(power_integer(), 2, (abs(i))))) + return ((k * Power.power_(power_integer(), 2, (max(0, (abs(i))))))) def sgn_integer(k): if ((k == 0)): diff --git a/test/diff/golden/Python_Examples.Example_integer_bit_ops/Example_integer_bit_ops.py b/test/diff/golden/Python_Examples.Example_integer_bit_ops/Example_integer_bit_ops.py index 5714cb1..dcbc1b5 100644 --- a/test/diff/golden/Python_Examples.Example_integer_bit_ops/Example_integer_bit_ops.py +++ b/test/diff/golden/Python_Examples.Example_integer_bit_ops/Example_integer_bit_ops.py @@ -12,16 +12,16 @@ def _abort(msg, thunk): test_sgn = (Arith.sgn_integer(-42)) -test_mask = (Arith.mask_integer(5)) +test_mask = (Arith.mask_integer((max(0, 5)))) -test_set_bit = (Arith.set_bit_integer(2, 0)) +test_set_bit = (Arith.set_bit_integer((max(0, 2)), 0)) -test_drop_bit = (Arith.drop_bit_integer(2, 20)) +test_drop_bit = (Arith.drop_bit_integer((max(0, 2)), 20)) test_flip_bit = (Arith.flip_bit_integer(1, 5)) -test_push_bit = (Arith.push_bit_integer(3, 5)) +test_push_bit = (Arith.push_bit_integer((max(0, 3)), 5)) -test_take_bit = (Arith.take_bit_integer(4, 255)) +test_take_bit = (Arith.take_bit_integer((max(0, 4)), 255)) test_unset_bit = (Arith.unset_bit_integer(0, 7)) diff --git a/test/diff/golden/Python_Examples.Example_nat/Example_nat.py b/test/diff/golden/Python_Examples.Example_nat/Example_nat.py index 9ce8d1e..e124381 100644 --- a/test/diff/golden/Python_Examples.Example_nat/Example_nat.py +++ b/test/diff/golden/Python_Examples.Example_nat/Example_nat.py @@ -7,27 +7,27 @@ def _abort(msg, thunk): raise RuntimeError(msg) -nat_sum = ((6 + 7)) +nat_sum = (((max(0, 6)) + (max(0, 7)))) -nat_eq_test = ((4 == 4)) +nat_eq_test = (((max(0, 4)) == (max(0, 4)))) -nat_le_test = ((3 <= 5)) +nat_le_test = (((max(0, 3)) <= (max(0, 5)))) -nat_literal = (42) +nat_literal = (max(0, 42)) -nat_lt_test = ((5 < 3)) +nat_lt_test = (((max(0, 5)) < (max(0, 3)))) -nat_product = ((6 * 7)) +nat_product = (((max(0, 6)) * (max(0, 7)))) -nat_sub_pos = (max(0, 10 - 3)) +nat_sub_pos = (max(0, (max(0, 10)) - (max(0, 3)))) def nat_checksum(x, y): return ((((lambda a, b: a % b if b else a)(((x * y)), ((y + 1)))) + (max(0, x - y)))) -nat_quotient = ((lambda a, b: a // b if b else 0)(7, 2)) +nat_quotient = ((lambda a, b: a // b if b else 0)((max(0, 7)), (max(0, 2)))) -nat_remainder = ((lambda a, b: a % b if b else a)(7, 2)) +nat_remainder = ((lambda a, b: a % b if b else a)((max(0, 7)), (max(0, 2)))) -nat_sub_trunc = (max(0, 3 - 10)) +nat_sub_trunc = (max(0, (max(0, 3)) - (max(0, 10)))) nat_zero_test = (0) diff --git a/test/diff/golden/Python_Examples.Example_nat_edge_cases/Example_nat_edge_cases.py b/test/diff/golden/Python_Examples.Example_nat_edge_cases/Example_nat_edge_cases.py index 2e45c53..2084b17 100644 --- a/test/diff/golden/Python_Examples.Example_nat_edge_cases/Example_nat_edge_cases.py +++ b/test/diff/golden/Python_Examples.Example_nat_edge_cases/Example_nat_edge_cases.py @@ -19,7 +19,7 @@ def peel_positive_head(x0): case _: raise RuntimeError("match failed") -peel_test = (peel_positive_head([3, 4, 5])) +peel_test = (peel_positive_head([max(0, 3), max(0, 4), max(0, 5)])) def nat_minus2(v, n): if ((v == 0)): @@ -37,8 +37,8 @@ def classify_small(uu): if (((max(0, uu - 1)) == 0)): return (1) else: - return (2) + return (max(0, 2)) -classify_test = ((classify_small(0), ((classify_small(1), classify_small(7))))) +classify_test = ((classify_small(0), ((classify_small(1), classify_small((max(0, 7))))))) -nat_minus2_test = (nat_minus2(5, 3)) +nat_minus2_test = (nat_minus2((max(0, 5)), (max(0, 3)))) diff --git a/test/diff/golden/Python_Examples.Example_nat_pattern/Example_nat_pattern.py b/test/diff/golden/Python_Examples.Example_nat_pattern/Example_nat_pattern.py index adbca63..cf7f52b 100644 --- a/test/diff/golden/Python_Examples.Example_nat_pattern/Example_nat_pattern.py +++ b/test/diff/golden/Python_Examples.Example_nat_pattern/Example_nat_pattern.py @@ -13,7 +13,7 @@ def fact(n): else: return (((((max(0, n - 1)) + 1)) * fact((max(0, n - 1))))) -fact_5 = (fact(5)) +fact_5 = (fact((max(0, 5)))) def countdown(n): if ((n == 0)): @@ -27,6 +27,6 @@ def nat_is_even(n): else: return (not nat_is_even((max(0, n - 1)))) -is_even_7 = (nat_is_even(7)) +is_even_7 = (nat_is_even((max(0, 7)))) -countdown_4 = (countdown(4)) +countdown_4 = (countdown((max(0, 4)))) diff --git a/test/diff/golden/Python_Examples.Example_nested_case/Example_nested_case.py b/test/diff/golden/Python_Examples.Example_nested_case/Example_nested_case.py index ccce21a..a0e9035 100644 --- a/test/diff/golden/Python_Examples.Example_nested_case/Example_nested_case.py +++ b/test/diff/golden/Python_Examples.Example_nested_case/Example_nested_case.py @@ -12,23 +12,23 @@ def weird(n): return (1) else: if ((n == 0)): - x = (10) + x = (max(0, 10)) else: - x = ((20 + (max(0, n - 1)))) + x = (((max(0, 20)) + (max(0, n - 1)))) return ((1 + x)) def classify(n): if ((n == 0)): - x = (100) + x = (max(0, 100)) else: - x = (200) + x = (max(0, 200)) return ((1 + x)) def nat_label(n): if ((n == 0)): - x = (10) + x = (max(0, 10)) else: - x = ((20 + (max(0, n - 1)))) + x = (((max(0, 20)) + (max(0, n - 1)))) return ((1 + x)) def abs_manual(x): @@ -37,11 +37,11 @@ def abs_manual(x): else: return (x) -label_five = (nat_label(5)) +label_five = (nat_label((max(0, 5)))) label_zero = (nat_label(0)) -weird_five = (weird(5)) +weird_five = (weird((max(0, 5)))) weird_zero = (weird(0)) @@ -62,6 +62,6 @@ def describe_len(xs): abs_manual_pos = (abs_manual(7)) -classify_other = (classify(5)) +classify_other = (classify((max(0, 5)))) -describe_len_123 = (describe_len([1, 2, 3])) +describe_len_123 = (describe_len([1, max(0, 2), max(0, 3)])) diff --git a/test/diff/golden/Python_Examples.Example_nested_if/Example_nested_if.py b/test/diff/golden/Python_Examples.Example_nested_if/Example_nested_if.py index 31c486b..9e11078 100644 --- a/test/diff/golden/Python_Examples.Example_nested_if/Example_nested_if.py +++ b/test/diff/golden/Python_Examples.Example_nested_if/Example_nested_if.py @@ -8,29 +8,29 @@ def _abort(msg, thunk): raise RuntimeError(msg) def grade_code(score): - if ((score < 60)): + if ((score < (max(0, 60)))): return (0) else: - if ((score < 70)): + if ((score < (max(0, 70)))): return (1) else: - if ((score < 80)): - return (2) + if ((score < (max(0, 80)))): + return (max(0, 2)) else: - if ((score < 90)): - return (3) + if ((score < (max(0, 90)))): + return (max(0, 3)) else: - return (4) + return (max(0, 4)) -grade_a = (grade_code(95)) +grade_a = (grade_code((max(0, 95)))) -grade_b = (grade_code(85)) +grade_b = (grade_code((max(0, 85)))) -grade_c = (grade_code(75)) +grade_c = (grade_code((max(0, 75)))) -grade_d = (grade_code(65)) +grade_d = (grade_code((max(0, 65)))) -grade_f = (grade_code(40)) +grade_f = (grade_code((max(0, 40)))) def nested_then(x, y): if ((0 < x)): diff --git a/test/diff/golden/Python_Examples.Example_polymorphic_const/Example_polymorphic_const.py b/test/diff/golden/Python_Examples.Example_polymorphic_const/Example_polymorphic_const.py index 2e75fc1..9afa91e 100644 --- a/test/diff/golden/Python_Examples.Example_polymorphic_const/Example_polymorphic_const.py +++ b/test/diff/golden/Python_Examples.Example_polymorphic_const/Example_polymorphic_const.py @@ -9,7 +9,7 @@ def _abort(msg, thunk): empty_list = ([]) -magic_number = (42) +magic_number = (max(0, 42)) uses_empty_list = (empty_list) diff --git a/test/diff/golden/Python_Examples.Example_short_circuit/Example_short_circuit.py b/test/diff/golden/Python_Examples.Example_short_circuit/Example_short_circuit.py index 4770045..fd513e1 100644 --- a/test/diff/golden/Python_Examples.Example_short_circuit/Example_short_circuit.py +++ b/test/diff/golden/Python_Examples.Example_short_circuit/Example_short_circuit.py @@ -69,7 +69,7 @@ def conj_case_list(xss): disj_case_empty = (disj_case([])) -disj_case_three = (disj_case([3])) +disj_case_three = (disj_case([max(0, 3)])) impl_case_empty = (impl_case([])) From 6f1bddfc25a263bee123e95eabd55279a401283c Mon Sep 17 00:00:00 2001 From: Nikolaus Huber Date: Mon, 2 Nov 2026 15:12:15 +0000 Subject: [PATCH 10/11] push to trigger CI From 3d828d9d76e05f0e106169aeb62b63a970c37b1c Mon Sep 17 00:00:00 2001 From: Nikolaus Huber Date: Mon, 2 Nov 2026 15:19:16 +0000 Subject: [PATCH 11/11] documentation handling of reserved words --- README.md | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f4e9e04..ca80246 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,6 @@ Python 3. - [uv](https://docs.astral.sh/uv/), which runs Python at the version in `.python-version`, the target version of the generated code -Generated names never hide the keywords and builtins listed in `etc/python_reserved_words`. After changing -`.python-version`, regenerate that list with `make reserved-words`. - ## Installing as a component ```bash @@ -45,6 +42,35 @@ things. Python integers, lists as Python lists, pairs as tuples and `char` as one-character strings. +### Reserved names + +Generated code must not use Python's keywords as names, nor hide the builtins +it calls itself (`len`, `list`, `range`, ...). The names to avoid are listed one +per line in `etc/python_reserved_words`: the keywords, soft keywords and +builtins of the Python version in `.python-version`. Lines starting with `#` +are comments. `Python.thy` reserves every name in the file, together with the +names that the prelude of each generated module binds (`dataclass`, `Any`, +`Callable`, `functools`, `_abort`, `_unimplemented`; `prelude_names` in +`code_python.ML`). + +A definition, class or datatype with a reserved name gets a trailing +underscore (`tuple` becomes `tuple_`), and a variable gets a fresh variant +(`len` becomes `lena`). + +The list is generated rather than edited by hand. After changing +`.python-version`, regenerate it with + +```bash +make reserved-words +``` + +which runs `etc/update_reserved_words.py` with the project's Python through +`uv run`. The script refuses to run under any other Python version than the +one in `.python-version`. Commit the updated list with the version change. +`Python.thy` declares the file with `external_file`, so the next +`isabelle build` rebuilds the `Python` session, and every session built on it, +whenever the list changes. + ### Tail calls as loops Python does not eliminate tail calls, so a function that recurses once per