Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions eval/HOW-TO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
97 changes: 76 additions & 21 deletions eval/oracles/python/oracle.py
Original file line number Diff line number Diff line change
@@ -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 = (
Expand Down Expand Up @@ -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():
Expand Down
17 changes: 17 additions & 0 deletions eval/tests/fixtures/python/grouped_from_imports.py
Original file line number Diff line number Diff line change
@@ -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
4 changes: 4 additions & 0 deletions eval/tests/fixtures/python/late_coding_cookie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# First physical line
# Second physical line
# coding: latin1
from names import K
2 changes: 2 additions & 0 deletions eval/tests/fixtures/python/latin1_import.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# coding: latin1 # café
from names import café
37 changes: 36 additions & 1 deletion eval/tests/integration/python_oracle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand Down Expand Up @@ -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<u8> = 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(
Expand Down