From 4dbafd3e7e70f5523c6b7dc84655ac433705f1a4 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Thu, 3 Dec 2026 05:33:29 +0800 Subject: [PATCH 1/5] fix(lang-python): preserve grouped imports in the oracle --- eval/HOW-TO.md | 1 + eval/oracles/python/oracle.py | 33 ++++++++++++++----------- eval/tests/integration/python_oracle.rs | 22 ++++++++++++++++- 3 files changed, 41 insertions(+), 15 deletions(-) diff --git a/eval/HOW-TO.md b/eval/HOW-TO.md index e8ccd905..61e008ab 100644 --- a/eval/HOW-TO.md +++ b/eval/HOW-TO.md @@ -93,6 +93,7 @@ The newest `analyzer` that admits Dart 3.0 is 6.4.1; it fails with "Expected an - When a runtime is missing or too old, or an oracle does not build, the language's recall status is `skipped` with the reason. - Oracle comparison compares each file that the oracle parses with the codeint Language plugin's model of the same file: functions match by first and last line, decision points count up to the oracle's count per matched function, and static imports match by specifier. + The Python oracle groups named from-imports by module and sorts original names, including names imported with an alias. Actual counts are tracked alongside expected and matched counts so both recall (`matched / expected`) and precision (`matched / actual`) are measured; precision is `1.0` when both expected and actual are zero, and `0.0` when expected is zero and actual is positive. Functions that share a first and last line pair by decision points, highest first, so the order of the two lists never changes the score. The report shows each percentage cut off, not rounded, at two decimals, so a value below the bar never shows as the bar. diff --git a/eval/oracles/python/oracle.py b/eval/oracles/python/oracle.py index 07e5f1f3..a0e1c868 100644 --- a/eval/oracles/python/oracle.py +++ b/eval/oracles/python/oracle.py @@ -65,33 +65,38 @@ def is_type_checking_guard(node): return named or attribute -def from_import_names(node): +def record_from_import(node, found, grouped): dots = "." * node.level if node.level == 0 and node.module == "__future__": - return [] - if node.module: - return [dots + node.module] - return [dots if alias.name == "*" else dots + alias.name for alias in node.names] - - -def import_names(node): - if isinstance(node, ast.Import): - return [alias.name for alias in node.names] - if isinstance(node, ast.ImportFrom): - return from_import_names(node) - return [] + return + if node.module is None: + found.update(dots if alias.name == "*" else dots + alias.name for alias in node.names) + return + module = dots + node.module + if node.names[0].name == "*": + found.add(module) + else: + grouped.setdefault(module, set()).update(alias.name for alias in node.names) def imports(tree): found = set() + grouped = {} pending = [tree] while pending: node = pending.pop() if isinstance(node, ast.If) and is_type_checking_guard(node): pending.extend(node.orelse) continue - found.update(import_names(node)) + if isinstance(node, ast.Import): + found.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + record_from_import(node, found, grouped) pending.extend(ast.iter_child_nodes(node)) + found.difference_update(grouped) + found.update( + f"from {module} import {','.join(sorted(names))}" for module, names in grouped.items() + ) return sorted(found) diff --git a/eval/tests/integration/python_oracle.rs b/eval/tests/integration/python_oracle.rs index 76046470..eb3101cd 100644 --- a/eval/tests/integration/python_oracle.rs +++ b/eval/tests/integration/python_oracle.rs @@ -49,7 +49,7 @@ fn the_python_oracle_reports_functions_decision_points_imports_and_syntax_errors assert_eq!(records.len(), 2, "{records:?}"); assert_eq!( records[0], - json!({"path": "calc.py", "functions": [[5, 8, 2]], "imports": ["a", "os"]}) + json!({"path": "calc.py", "functions": [[5, 8, 2]], "imports": ["from a import b", "os"]}) ); assert_eq!(records[1]["path"], "broken.py"); assert!( @@ -92,6 +92,26 @@ fn assert_oracle_record(file_name: &str, bytes: &[u8], expected: Value) { assert_eq!(records, vec![expected]); } +#[test] +fn the_python_oracle_preserves_names_in_a_from_import() { + assert_oracle_record( + "counts.py", + concat!( + "from collections import Counter\n", + "\ndef count(values):\n if values:\n return Counter(values)\n return Counter()\n", + "\nimport collections\n", + "from collections import defaultdict as default, Counter\n", + "from .pkg import Zeta as last, Alpha\n", + "from . import sibling as local\n", + "from another import *\n", + ) + .as_bytes(), + json!({"path": "counts.py", "functions": [[3, 6, 1]], "imports": [ + ".sibling", "another", "from .pkg import Alpha,Zeta", "from collections import Counter,defaultdict" + ]}), + ); +} + #[test] fn the_python_oracle_honors_a_coding_declaration_on_a_non_utf8_file() { assert_oracle_record( From c91ac32e0d4bc77c002a64a64061d945a7135a2f Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Thu, 3 Dec 2026 05:36:55 +0800 Subject: [PATCH 2/5] fix(lang-python): retain source spelling in oracle imports --- eval/oracles/python/oracle.py | 36 +++++++++++++++---- .../fixtures/python/grouped_from_imports.py | 14 ++++++++ eval/tests/integration/python_oracle.rs | 13 ++----- 3 files changed, 45 insertions(+), 18 deletions(-) create mode 100644 eval/tests/fixtures/python/grouped_from_imports.py diff --git a/eval/oracles/python/oracle.py b/eval/oracles/python/oracle.py index a0e1c868..e4c7f1a1 100644 --- a/eval/oracles/python/oracle.py +++ b/eval/oracles/python/oracle.py @@ -1,7 +1,9 @@ import ast +import io import json import os import sys +import tokenize FUNCTION_NODES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda) SINGLE_DECISIONS = ( @@ -65,21 +67,40 @@ def is_type_checking_guard(node): return named or attribute -def record_from_import(node, found, grouped): +def import_source_lines(source): + if source.isascii(): + return None + try: + encoding, _ = tokenize.detect_encoding(io.BytesIO(source).readline) + return source.decode(encoding).encode().splitlines() + except (SyntaxError, UnicodeError): + return None + + +def imported_name(alias, lines): + if lines is None: + return alias.name + end = alias.end_col_offset if alias.end_lineno == alias.lineno else None + segment = lines[alias.lineno - 1][alias.col_offset:end] + return segment.split(b"\\", 1)[0].split()[0].decode() + + +def record_from_import(node, lines, found, grouped): dots = "." * node.level if node.level == 0 and node.module == "__future__": return if node.module is None: - found.update(dots if alias.name == "*" else dots + alias.name for alias in node.names) + found.update(dots if alias.name == "*" else dots + imported_name(alias, lines) + for alias in node.names) return module = dots + node.module if node.names[0].name == "*": found.add(module) else: - grouped.setdefault(module, set()).update(alias.name for alias in node.names) + grouped.setdefault(module, set()).update(imported_name(alias, lines) for alias in node.names) -def imports(tree): +def imports(tree, lines): found = set() grouped = {} pending = [tree] @@ -91,7 +112,7 @@ def imports(tree): if isinstance(node, ast.Import): found.update(alias.name for alias in node.names) elif isinstance(node, ast.ImportFrom): - record_from_import(node, found, grouped) + record_from_import(node, lines, found, grouped) pending.extend(ast.iter_child_nodes(node)) found.difference_update(grouped) found.update( @@ -103,10 +124,11 @@ def imports(tree): def describe(path): try: with open(path, "rb") as handle: - tree = ast.parse(handle.read(), filename=path) + source = handle.read() + tree = ast.parse(source, filename=path) except (SyntaxError, ValueError) as error: return {"path": path, "error": str(error)} - return {"path": path, "functions": functions(tree), "imports": imports(tree)} + return {"path": path, "functions": functions(tree), "imports": imports(tree, import_source_lines(source))} def main(): diff --git a/eval/tests/fixtures/python/grouped_from_imports.py b/eval/tests/fixtures/python/grouped_from_imports.py new file mode 100644 index 00000000..8bc31880 --- /dev/null +++ b/eval/tests/fixtures/python/grouped_from_imports.py @@ -0,0 +1,14 @@ +from collections import Counter + +def count(values): + if values: + return Counter(values) + return Counter() + +import collections +from collections import defaultdict as default +from collections import defaultdict +from .pkg import Zeta as last, Alpha +from . import sibling as local +from another import * +from names import K as kelvin diff --git a/eval/tests/integration/python_oracle.rs b/eval/tests/integration/python_oracle.rs index eb3101cd..a3873eca 100644 --- a/eval/tests/integration/python_oracle.rs +++ b/eval/tests/integration/python_oracle.rs @@ -96,18 +96,9 @@ fn assert_oracle_record(file_name: &str, bytes: &[u8], expected: Value) { fn the_python_oracle_preserves_names_in_a_from_import() { assert_oracle_record( "counts.py", - concat!( - "from collections import Counter\n", - "\ndef count(values):\n if values:\n return Counter(values)\n return Counter()\n", - "\nimport collections\n", - "from collections import defaultdict as default, Counter\n", - "from .pkg import Zeta as last, Alpha\n", - "from . import sibling as local\n", - "from another import *\n", - ) - .as_bytes(), + include_bytes!("../fixtures/python/grouped_from_imports.py"), json!({"path": "counts.py", "functions": [[3, 6, 1]], "imports": [ - ".sibling", "another", "from .pkg import Alpha,Zeta", "from collections import Counter,defaultdict" + ".sibling", "another", "from .pkg import Alpha,Zeta", "from collections import Counter,defaultdict", "from names import K" ]}), ); } From 12c91f973932cdc03aac750e3fcce230a4f8ed3a Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Thu, 3 Dec 2026 05:41:24 +0800 Subject: [PATCH 3/5] fix(lang-python): align source module names and encoding --- eval/oracles/python/oracle.py | 54 ++++++++++++------- .../fixtures/python/grouped_from_imports.py | 3 ++ .../fixtures/python/late_coding_cookie.py | 4 ++ eval/tests/integration/python_oracle.rs | 13 ++++- 4 files changed, 55 insertions(+), 19 deletions(-) create mode 100644 eval/tests/fixtures/python/late_coding_cookie.py diff --git a/eval/oracles/python/oracle.py b/eval/oracles/python/oracle.py index e4c7f1a1..e155afaa 100644 --- a/eval/oracles/python/oracle.py +++ b/eval/oracles/python/oracle.py @@ -4,6 +4,7 @@ import os import sys import tokenize +from itertools import islice, takewhile FUNCTION_NODES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda) SINGLE_DECISIONS = ( @@ -68,32 +69,48 @@ def is_type_checking_guard(node): def import_source_lines(source): - if source.isascii(): + physical_lines = source.replace(b"\r\n", b"\n").replace(b"\r", b"\n") + encoding, _ = tokenize.detect_encoding(io.BytesIO(physical_lines).readline) + decoded = source.decode(encoding) + if decoded.isascii(): return None - try: - encoding, _ = tokenize.detect_encoding(io.BytesIO(source).readline) - return source.decode(encoding).encode().splitlines() - except (SyntaxError, UnicodeError): + return decoded.encode().splitlines() + + +def source_spelling(node, lines, *, stop, skip=0): + if lines is None: return None + segment = lines[node.lineno - 1 : node.end_lineno] + segment[-1] = segment[-1][:node.end_col_offset] + segment[0] = segment[0][node.col_offset:] + source = b"\n".join(segment) + if source.isascii(): + return None + tokens = tokenize.generate_tokens(io.StringIO(source.decode()).readline) + parts = ( + token.string + for token in tokens + if token.type in (tokenize.NAME, tokenize.OP) + or (token.type == tokenize.ERRORTOKEN and not token.string.isspace()) + ) + return "".join(takewhile(lambda part: part != stop, islice(parts, skip, None))) def imported_name(alias, lines): - if lines is None: - return alias.name - end = alias.end_col_offset if alias.end_lineno == alias.lineno else None - segment = lines[alias.lineno - 1][alias.col_offset:end] - return segment.split(b"\\", 1)[0].split()[0].decode() + return source_spelling(alias, lines, stop="as") or alias.name def record_from_import(node, lines, found, grouped): dots = "." * node.level - if node.level == 0 and node.module == "__future__": - return if node.module is None: - found.update(dots if alias.name == "*" else dots + imported_name(alias, lines) - for alias in node.names) + found.update( + dots if alias.name == "*" else dots + imported_name(alias, lines) + for alias in node.names + ) + return + module = source_spelling(node, lines, stop="import", skip=1) or dots + node.module + if module == "__future__": return - module = dots + node.module if node.names[0].name == "*": found.add(module) else: @@ -110,7 +127,7 @@ def imports(tree, lines): pending.extend(node.orelse) continue if isinstance(node, ast.Import): - found.update(alias.name for alias in node.names) + found.update(imported_name(alias, lines) for alias in node.names) elif isinstance(node, ast.ImportFrom): record_from_import(node, lines, found, grouped) pending.extend(ast.iter_child_nodes(node)) @@ -126,9 +143,10 @@ def describe(path): with open(path, "rb") as handle: source = handle.read() tree = ast.parse(source, filename=path) - except (SyntaxError, ValueError) as error: + import_specifiers = imports(tree, import_source_lines(source)) + except (SyntaxError, ValueError, tokenize.TokenError) as error: return {"path": path, "error": str(error)} - return {"path": path, "functions": functions(tree), "imports": imports(tree, import_source_lines(source))} + return {"path": path, "functions": functions(tree), "imports": import_specifiers} def main(): diff --git a/eval/tests/fixtures/python/grouped_from_imports.py b/eval/tests/fixtures/python/grouped_from_imports.py index 8bc31880..a7170b0b 100644 --- a/eval/tests/fixtures/python/grouped_from_imports.py +++ b/eval/tests/fixtures/python/grouped_from_imports.py @@ -12,3 +12,6 @@ def count(values): from . import sibling as local from another import * from names import K as kelvin +import K.sub as compatibility_module +from K import A +from K import B diff --git a/eval/tests/fixtures/python/late_coding_cookie.py b/eval/tests/fixtures/python/late_coding_cookie.py new file mode 100644 index 00000000..e4e73bf7 --- /dev/null +++ b/eval/tests/fixtures/python/late_coding_cookie.py @@ -0,0 +1,4 @@ +# First physical line +# Second physical line +# coding: latin1 +from names import K diff --git a/eval/tests/integration/python_oracle.rs b/eval/tests/integration/python_oracle.rs index a3873eca..42685076 100644 --- a/eval/tests/integration/python_oracle.rs +++ b/eval/tests/integration/python_oracle.rs @@ -98,11 +98,22 @@ fn the_python_oracle_preserves_names_in_a_from_import() { "counts.py", include_bytes!("../fixtures/python/grouped_from_imports.py"), json!({"path": "counts.py", "functions": [[3, 6, 1]], "imports": [ - ".sibling", "another", "from .pkg import Alpha,Zeta", "from collections import Counter,defaultdict", "from names import K" + ".sibling", "another", "from .pkg import Alpha,Zeta", "from K import B", + "from collections import Counter,defaultdict", "from names import K", "from K import A", "K.sub" ]}), ); } +#[test] +fn the_python_oracle_only_reads_encoding_declarations_on_the_first_two_physical_lines() { + let source = include_str!("../fixtures/python/late_coding_cookie.py").replace('\n', "\r"); + assert_oracle_record( + "cr.py", + source.as_bytes(), + json!({"path": "cr.py", "functions": [], "imports": ["from names import K"]}), + ); +} + #[test] fn the_python_oracle_honors_a_coding_declaration_on_a_non_utf8_file() { assert_oracle_record( From 316d3577b1b3974e7a939d3f6daa1c621a6bf4d7 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Thu, 3 Dec 2026 05:42:07 +0800 Subject: [PATCH 4/5] fix(lang-python): recover modules after the from keyword --- eval/oracles/python/oracle.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/eval/oracles/python/oracle.py b/eval/oracles/python/oracle.py index e155afaa..513560cb 100644 --- a/eval/oracles/python/oracle.py +++ b/eval/oracles/python/oracle.py @@ -4,7 +4,7 @@ import os import sys import tokenize -from itertools import islice, takewhile +from itertools import dropwhile, takewhile FUNCTION_NODES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda) SINGLE_DECISIONS = ( @@ -77,7 +77,7 @@ def import_source_lines(source): return decoded.encode().splitlines() -def source_spelling(node, lines, *, stop, skip=0): +def source_spelling(node, lines, *, stop, after=None): if lines is None: return None segment = lines[node.lineno - 1 : node.end_lineno] @@ -93,7 +93,10 @@ def source_spelling(node, lines, *, stop, skip=0): if token.type in (tokenize.NAME, tokenize.OP) or (token.type == tokenize.ERRORTOKEN and not token.string.isspace()) ) - return "".join(takewhile(lambda part: part != stop, islice(parts, skip, None))) + if after is not None: + parts = dropwhile(lambda part: part != after, parts) + next(parts, None) + return "".join(takewhile(lambda part: part != stop, parts)) def imported_name(alias, lines): @@ -108,7 +111,7 @@ def record_from_import(node, lines, found, grouped): for alias in node.names ) return - module = source_spelling(node, lines, stop="import", skip=1) or dots + node.module + module = source_spelling(node, lines, stop="import", after="from") or dots + node.module if module == "__future__": return if node.names[0].name == "*": From de599cd72a61560464666c544b5e41c5fd242a03 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Thu, 3 Dec 2026 05:45:44 +0800 Subject: [PATCH 5/5] fix(lang-python): read encoding cookies on Python 3.12 --- eval/oracles/python/oracle.py | 9 ++++++++- eval/tests/fixtures/python/latin1_import.py | 2 ++ eval/tests/integration/python_oracle.rs | 13 +++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 eval/tests/fixtures/python/latin1_import.py diff --git a/eval/oracles/python/oracle.py b/eval/oracles/python/oracle.py index 513560cb..35ca8cd1 100644 --- a/eval/oracles/python/oracle.py +++ b/eval/oracles/python/oracle.py @@ -6,6 +6,8 @@ import tokenize from itertools import dropwhile, takewhile +NON_ASCII_TO_PLACEHOLDER = bytes(range(128)) + b"?" * 128 + FUNCTION_NODES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda) SINGLE_DECISIONS = ( ast.If, @@ -70,7 +72,12 @@ def is_type_checking_guard(node): def import_source_lines(source): physical_lines = source.replace(b"\r\n", b"\n").replace(b"\r", b"\n") - encoding, _ = tokenize.detect_encoding(io.BytesIO(physical_lines).readline) + lines = io.BytesIO(physical_lines) + first = lines.readline() + bom = b"\xef\xbb\xbf" if first.startswith(b"\xef\xbb\xbf") else b"" + header = first[len(bom):] + lines.readline() + encoding_header = bom + header.translate(NON_ASCII_TO_PLACEHOLDER) + encoding, _ = tokenize.detect_encoding(io.BytesIO(encoding_header).readline) decoded = source.decode(encoding) if decoded.isascii(): return None diff --git a/eval/tests/fixtures/python/latin1_import.py b/eval/tests/fixtures/python/latin1_import.py new file mode 100644 index 00000000..67c02046 --- /dev/null +++ b/eval/tests/fixtures/python/latin1_import.py @@ -0,0 +1,2 @@ +# coding: latin1 # café +from names import café diff --git a/eval/tests/integration/python_oracle.rs b/eval/tests/integration/python_oracle.rs index 42685076..d8c7c8e4 100644 --- a/eval/tests/integration/python_oracle.rs +++ b/eval/tests/integration/python_oracle.rs @@ -114,6 +114,19 @@ fn the_python_oracle_only_reads_encoding_declarations_on_the_first_two_physical_ ); } +#[test] +fn the_python_oracle_reads_a_non_utf8_comment_on_the_encoding_declaration() { + let source: Vec = include_str!("../fixtures/python/latin1_import.py") + .chars() + .map(|character| u8::try_from(character).expect("Latin-1 character")) + .collect(); + assert_oracle_record( + "latin_import.py", + &source, + json!({"path": "latin_import.py", "functions": [], "imports": ["from names import café"]}), + ); +} + #[test] fn the_python_oracle_honors_a_coding_declaration_on_a_non_utf8_file() { assert_oracle_record(