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..35ca8cd1 100644 --- a/eval/oracles/python/oracle.py +++ b/eval/oracles/python/oracle.py @@ -1,7 +1,12 @@ import ast +import io import json import os import sys +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 = ( @@ -65,43 +70,93 @@ def is_type_checking_guard(node): return named or attribute -def from_import_names(node): +def import_source_lines(source): + physical_lines = source.replace(b"\r\n", b"\n").replace(b"\r", b"\n") + 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 + return decoded.encode().splitlines() + + +def source_spelling(node, lines, *, stop, after=None): + 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()) + ) + 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): + 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: - 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 [] - - -def imports(tree): + if node.module is None: + 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", after="from") or dots + node.module + if module == "__future__": + return + if node.names[0].name == "*": + found.add(module) + else: + grouped.setdefault(module, set()).update(imported_name(alias, lines) for alias in node.names) + + +def imports(tree, lines): 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(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)) + found.difference_update(grouped) + found.update( + f"from {module} import {','.join(sorted(names))}" for module, names in grouped.items() + ) return sorted(found) def describe(path): try: with open(path, "rb") as handle: - tree = ast.parse(handle.read(), filename=path) - except (SyntaxError, ValueError) as error: + source = handle.read() + tree = ast.parse(source, filename=path) + 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)} + 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 new file mode 100644 index 00000000..a7170b0b --- /dev/null +++ b/eval/tests/fixtures/python/grouped_from_imports.py @@ -0,0 +1,17 @@ +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 +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/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 76046470..d8c7c8e4 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,41 @@ 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", + 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 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_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(