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 CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- ColdFusion files are read with a newer CFML parser, so code it used to stumble over is now indexed: `elseif` chains, brace-less `try`, `savecontent` and function-listener expressions, dotted struct keys and property names, `java:` and `cfml:` static calls, and word operators such as `EQV` in queries; text that ColdFusion itself prints as written, like a `#…#` in a function without `output="true"` or inside a CFML comment, is no longer mistaken for calls.
- ColdFusion (CFML) files are now read by the native engine by default, which indexes most CFML projects faster.
- Python files with syntax errors are now read by the native engine as well, with the same results as before.
- Rust files with syntax errors are now read by the native engine as well, with the same results as before.
- Nix files with syntax errors are now read by the native engine as well, with the same results as before.
- COBOL files with syntax errors are now read by the native engine as well, with the same results as before.
- Erlang files with syntax errors are now read by the native engine as well, with the same results as before.
Expand Down
50 changes: 50 additions & 0 deletions __tests__/fixtures/kernel-parity/broken-macros.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
//! Expression macros, declared macros and route macros in a file with
//! errors: an empty argument, a stray token, a statement that never ends,
//! and last a macro whose token tree never closes.

macro_rules! check {
($e:expr) => {
assert!($e)
};
}

macro_rules! passthrough {
($($t:tt)*) => { $($t)* };
}

fn pred(x: &u32) -> bool {
*x > 1
}

fn compute() -> u32 {
let broken = ;
2
}

fn macros(items: Vec<u32>, f: &mut Formatter) {
check!(items.iter().all(pred));
passthrough!(compute());
format!("{} {}", compute(), self.code.as_str(), , $);
println!("{}", Foo::new().bar(), x.y::<u8>());
assert_eq!(compute(), , 3);
write!(f, "{}", self.a.b());
let = 1;
matches!(mode, Mode::A | Mode::B if compute() > 1);
vec![pred; compute()];
json!({"k": compute(), "j": });
crate::check!(compute() == 2);
}

fn routes() {
rocket::build()
.mount("/", routes![api::index, api::users::list, ])
.register("/", catchers![not_found, crate::errors::internal]);
x = ;
}

fn not_found() {}

fn tail() {
let x = compute();
debug_assert!(items.is_empty() || pred(&x);
}
92 changes: 92 additions & 0 deletions __tests__/fixtures/kernel-parity/broken-shapes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
//! A Rust file with errors, one shape at a time, each kept local
//! (kernel-error-trees.md, Rust's table).

use std::collections::HashMap;
use crate::util::{take, ;
use a::b as ;
use self::{x as , y};

const MAXV: u32 = 3;
const EMPTY: u32 = ;
static REGISTRY: Lazy<Table> = Lazy::new(|| build_table());

/// A trait whose second method never closes its call.
pub trait Store: Clone + fmt::Debug {
fn get(&self, key: &str) -> Option<u32>;
fn put(&mut self, key: &str) {
self.get(key;
}
}

#[derive(Debug)]
pub struct Config {
pub retries: u32,
timeout: ,
name: String,
}

pub enum Mode {
A,
B(u32, ),
C { x: u32 },
}

impl Config {
pub fn new() -> Self {
Config { retries: MAXV, timeout: , name: String::new() }
}

fn apply(&self, mode: Mode) -> &Self {
match mode {
Mode::A => self.reset(),
Mode::B(n) => helper(n,
Mode::C { x } => self.inner.run(x),
}
self
}

fn reset(&self) {}
}

impl Store for Config {
fn get(&self, key: &str) -> Option<u32> {
let map: HashMap<String, u32> = HashMap::new();
map.get(key).copied()
}
}

fn helper(n: u32) -> u32 {
fn nested(x: u32) -> u32 { x + MAXV }
nested(n) + $
}

fn build_table() -> Table {
let t = Table::with_capacity::<u8>(4);
t.register(on_event, crate::events::on_close, Self::k);
format!("{} {}", label(), t.len(), , $);
let = t;
vec![on_event; 3];
t
}

fn on_event() {}

fn label() -> String {
String::from("x")
}

#[tauri::command]
fn command(a: u32) -> u32 {
helper(a
}

fn chains(s: &Config) {
s.inner.store().put("k");
Config::new().apply(Mode::A);
s.a.();
x = ;
}

fn tail() -> u32 {
MAXV
}
22 changes: 22 additions & 0 deletions __tests__/fixtures/kernel-parity/broken-wide.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//! Une crate « café » : a Rust file with an error and characters outside ASCII.
//! Policy `Ascii` reads it with the reference until tree-sitter-rust's scanner
//! answers from one character table: it defers.

/// Grüße 😀.
pub fn grüße(名前: &str) -> String {
helper(名前).run()
}

pub struct Café {
ñ: u32,
}

impl Café {
pub fn méthode(&self) -> String {
grüße("ü😀"
}
}

fn helper(s: &str) -> Runner {
Runner::new(s)
}
129 changes: 127 additions & 2 deletions __tests__/kernel-error-tree-parity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@
* equal the reference in full objects, in order, errors included; LF,
* CRLF and a text outside ASCII. Each reference extraction has a path of
* its own (languages/erlang.ts keeps per-path facts in module state).
* 2k. Rust (policy Ascii): all-ASCII broken files extract through the kernel
* without deferring and equal the reference in full objects, in order,
* errors included; LF and CRLF; the differences its walker had on clean
* trees before. A broken Rust file outside ASCII still defers; a clean one
* does not.
* 3. A language on policy Defer still defers a broken file.
* 4. Policy Ascii, set per thread through the test-support export, on
* languages that ship on All.
Expand Down Expand Up @@ -1283,6 +1288,126 @@ describe.skipIf(!kernelBuilt)('kernel reads trees with errors', () => {
});
});

describe('2k. Rust reads its all-ASCII trees with errors natively', () => {
/** Kernel against reference, full objects in emission order, errors included. */
function assertRustParity(filePath: string, source: string, tree: 'E' | 'C' = 'E', minNodes = 1): ExtractionResult {
process.env.CODEGRAPH_KERNEL_LANGS = 'rust';
delete process.env.CODEGRAPH_KERNEL;
expect(kernel.debugTree('rust', source, 'utf8', BUDGET_MS)[0], `${filePath}: the tree's state`).toBe(tree);
const viaKernel = tryKernelExtract(filePath, source, 'rust');
expect(viaKernel, `${filePath}: the kernel extracts it, no deferral`).not.toBeNull();

process.env.CODEGRAPH_KERNEL = '0';
const viaWasm = extractFromSource(filePath, source, 'rust');
delete process.env.CODEGRAPH_KERNEL;

const k = canon(viaKernel!);
const w = canon(viaWasm);
expect(k.nodes, `${filePath}: nodes`).toEqual(w.nodes);
expect(k.edges, `${filePath}: edges`).toEqual(w.edges);
expect(k.refs, `${filePath}: refs`).toEqual(w.refs);
expect(k.errors, `${filePath}: errors`).toEqual(w.errors);
expect(viaWasm.nodes.length).toBeGreaterThanOrEqual(minNodes);
return viaKernel!;
}
const read = (name: string): string => fs.readFileSync(path.join(FIXTURE_DIR, name), 'utf8');
const crlf = (s: string): string => s.replace(/(?<!\r)\n/g, '\r\n');

for (const [name, minNodes] of [['broken-shapes.rs', 25], ['broken-macros.rs', 6]] as const) {
it(`${name}, LF and CRLF`, () => {
assertRustParity(`src/${name}`, read(name), 'E', minNodes);
assertRustParity(`src/crlf-${name}`, crlf(read(name)), 'E', minNodes);
});
}

// One shape per text (kernel-error-trees.md, Rust's table).
const SHAPES: Record<string, string> = {
'an ERROR child of the file, of a block and of an impl body': 'fn f() {\n $\n g(1);\n}\n$ ;\nstruct S;\nimpl S {\n $ fn m(&self) { self.n(); }\n fn n(&self) {}\n}\n',
'a parameter list that never closes, then a good function': 'fn f(a: u32 {\n g(a)\n}\n\nfn h() { f(1); }\n',
'a function named by a zero-width MISSING identifier': 'fn (x: u32) { g(x); }\nfn k() {}\n',
'a function written in a body without a name: walked as any node': 'fn outer() {\n fn () { inner_call(); }\n fn named() { k(); }\n after();\n}\n',
'an impl of a zero-width MISSING type: no receiver': 'impl { fn m(&self) { self.x(); } }\nfn g() {}\n',
'a trait impl for a missing type, and a trait with a broken method': 'impl Tr for { fn m() { n(); } }\ntrait T { fn a(&self); fn b(&self) { self.a(; } }\nstruct S;\n',
'struct, enum and union bodies with broken members': 'struct S { a: u32, b: , c: Vec<u32 }\nenum E { A, B(u32, , C { x: u32 } }\nunion U { a: u32, b: }\nfn f() -> S { S { a: f, b: } }\n',
'use declarations with nothing to import': 'use a::;\nuse a::{b, ;\nuse ::;\nuse a:::b;\nuse self::{x as , y};\nfn f() {}\n',
'a call whose arguments never close; a method call without a name': 'fn f() {\n g(1\n a.b().c(\n}\nfn h() {\n a.();\n self.;\n}\n',
'a turbofish that never closes; chains on a path and on self': 'fn f() {\n s.get::<u8(1);\n Vec::<u8>::with_capacity(1).len();\n self.store().put(\n}\n',
'assignments with a missing side; function values beside an error': 'fn on_a() {}\nfn f() {\n x = ;\n = g;\n a.cb = cb;\n run(on_a, m::cb, Self::k, r#Foo, m::r#Bar;\n}\n',
'expression macros whose token trees never close': 'fn f() {\n format!("{}", g(;\n vec![h; ];\n assert_eq!(a(), \n}\nfn h() {}\n',
'route macros with an empty path': 'fn main() {\n rocket::build().mount("/", routes![a::b, c::, d]).register(catchers![not_found;\n}\n',
'a declared macro whose rule never closes': 'macro_rules! wrap { ($e:expr) => { $e } \nfn f() { wrap!(items.iter().all(pred)); }\nfn pred() {}\n',
'constants and statics without a value': 'const X: u32 = ;\nstatic Y = 1;\nconst MAXV: u32 = 3;\nfn f() -> u32 { MAXV + }\n',
'a return type with an extra colon (`split(\'::\')` from the left)': 'fn f() -> a:::B { g() }\nfn k() -> Self {}\n',
'a Tauri command beside an error': '/// doc\n#[tauri::command]\nfn cmd() { g(; }\n#[tauri :: command]\nfn cmd2() {}\n',
// `if (typeName && posNode)`: a supertrait bound whose type is a zero-width MISSING node
// (found by the review) is no reference.
'a supertrait bound that is a zero-width MISSING type': 'trait T: +< asfor<\'a> + {}\nstruct S;\n',
'a higher-ranked supertrait bound without a type': 'trait T: for<\'a> {}\nstruct S;\n',
'a higher-ranked supertrait bound without a type after a generic one': 'trait X: for<\'a> m::Y<\'a> + for<\'b> {}\nstruct S;\n',
'nothing but an error (no symbol: the parse warning)': '$$$ ( ( (\n',
};
for (const [shape, text] of Object.entries(SHAPES)) {
it(`shape: ${shape}`, () => {
assertRustParity('src/shape.rs', text);
assertRustParity('src/shape-crlf.rs', crlf(text));
});
}

// Differences the walker had on CLEAN trees before it read trees with errors.
const CLEAN: Record<string, string> = {
// normalizeSpecial's `/^(?:r#)?[a-z_]/` holds for `r#Foo`: `r` is a lowercase letter.
'a path value whose last segment is a raw identifier with a capital': 'fn f() {\n run(m::r#Foo, m::r#bar);\n format!("{}", g(m::r#Baz));\n}\n',
// flushValueRefs takes in a `block` that follows the scope's node: a variable's scope node
// is its identifier, and the grammar takes a `let` at file level.
'the value block of a file-level `let`': 'const MAXV: u32 = 1;\nlet X = { MAXV };\nfn f() {}\n',
// The inner callee of `Foo::new().bar()` loses JavaScript's `\s` (U+FEFF yes, U+0085 no),
// here inside a comment.
'a NEXT LINE in a comment inside a chained call\'s inner callee': 'fn f() { Foo/*\u0085*/::new().bar(); }\n',
'a BOM in a comment inside a chained call\'s inner callee': 'fn f() { Foo/**/::new().bar(); }\n',
};
for (const [shape, text] of Object.entries(CLEAN)) {
it(`clean tree: ${shape}, and the same text broken`, () => {
assertRustParity('src/clean.rs', text, 'C');
assertRustParity('src/clean-crlf.rs', crlf(text), 'C');
const broken = `${text}fn z( {\n}\n`;
// eslint-disable-next-line no-control-regex
if (/^[\x00-\x7f]*$/.test(text)) assertRustParity('src/broken.rs', broken);
else expect(() => kernel.extractFile('src/broken.rs', broken, 'rust', BUDGET_MS)).toThrow(/^defer: parse tree contains errors/);
});
}

it('the parse warning of a file with no symbol is the reference\'s; an import is a symbol', () => {
const result = assertRustParity('src/only_errors.rs', '$$$ ( ( (\n');
expect(result.errors).toEqual([
{
message: 'src/only_errors.rs: parse produced no symbols (tree has errors) — the file is indexed but contributes nothing to the graph',
severity: 'warning',
code: 'parse_error',
},
]);
expect(assertRustParity('src/import_only.rs', 'use a::b;\n$$$ ( ( (\n').errors).toEqual([]);
});

it('Rust is on policy Ascii: a broken file outside ASCII defers, a clean one does not', () => {
expect(kernel.debugErrorTreePolicy('rust')).toBe('ascii');
const wide = read('broken-wide.rs');
for (const source of [wide, crlf(wide)]) {
expect(kernel.debugTree('rust', source, 'utf8', BUDGET_MS).startsWith('E')).toBe(true);
expect(() => kernel.extractFile('src/broken-wide.rs', source, 'rust', BUDGET_MS)).toThrow(
/^defer: parse tree contains errors/
);
}
// The same text repaired: clean, outside ASCII, read by the kernel, at parity. The pattern
// holds no line end, so a CRLF checkout (Windows) is repaired too, and a pattern that
// matches nothing fails here by name.
const clean = wide.replace('grüße("ü😀"', 'grüße("ü😀")');
expect(clean).not.toBe(wide);
expect(kernel.debugTree('rust', clean, 'utf8', BUDGET_MS).startsWith('C')).toBe(true);
expect(() => kernel.extractFile('src/clean-wide.rs', clean, 'rust', BUDGET_MS)).not.toThrow();
assertRustParity('src/clean-wide.rs', clean, 'C', 5);
});
});

describe('3. a language on policy Defer still defers a broken file', () => {
for (const language of Object.keys(SNIPPETS)) {
it(language, () => {
Expand All @@ -1297,8 +1422,8 @@ describe.skipIf(!kernelBuilt)('kernel reads trees with errors', () => {
});
}

it('every language but python, java, go, c, cpp, objc, pascal, solidity, nix, cobol and erlang is on Defer', () => {
const shipped: Record<string, string> = { python: 'all', java: 'all', go: 'all', c: 'all', cpp: 'ascii', objc: 'all', pascal: 'all', solidity: 'all', nix: 'all', cobol: 'all', erlang: 'all' };
it('every language but python, java, go, c, cpp, objc, pascal, solidity, nix, cobol, erlang and rust is on Defer', () => {
const shipped: Record<string, string> = { python: 'all', java: 'all', go: 'all', c: 'all', cpp: 'ascii', objc: 'all', pascal: 'all', solidity: 'all', nix: 'all', cobol: 'all', erlang: 'all', rust: 'ascii' };
const policies = Object.fromEntries(Object.keys(SNIPPETS).map((l) => [l, kernel.debugErrorTreePolicy(l)]));
for (const [language, policy] of Object.entries(policies)) {
expect(policy, language).toBe(shipped[language] ?? 'defer');
Expand Down
21 changes: 19 additions & 2 deletions __tests__/kernel-rustlang-parity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,14 +339,31 @@ fn shapes(items: Vec<u64>, opt: Option<u64>) -> bool {
assertParity('fixtures/torture.rs (crlf)', crlf, 20);
});

it('files with parse errors defer to the wasm extractor (recovery is encoding-dependent)', () => {
// A file with parse errors: the kernel reads an all-ASCII one itself
// (policy Ascii, docs/design/kernel-error-trees.md), at parity with the
// wasm extractor; one with a character outside ASCII still defers to it.
it('files with parse errors: an all-ASCII one at parity, one outside ASCII defers to the wasm extractor', () => {
const broken = 'fn f( {\n return }} 12 (\n';
process.env.CODEGRAPH_KERNEL_LANGS = 'all';
delete process.env.CODEGRAPH_KERNEL;
expect(tryKernelExtract('src/broken.rs', broken, 'rust')).toBeNull();
const viaKernel = tryKernelExtract('src/broken.rs', broken, 'rust');
expect(viaKernel).not.toBeNull();
process.env.CODEGRAPH_KERNEL = '0';
const viaWasm = extractFromSource('src/broken.rs', broken, 'rust');
delete process.env.CODEGRAPH_KERNEL;
expect(viaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
const k = canon(viaKernel!);
const w = canon(viaWasm);
expect(k.nodes).toEqual(w.nodes);
expect(k.edges).toEqual(w.edges);
expect(k.refs).toEqual(w.refs);
expect(viaKernel!.errors).toEqual(viaWasm.errors);

const wide = 'fn f( {\n return }} "é" 12 (\n';
expect(tryKernelExtract('src/broken-wide.rs', wide, 'rust')).toBeNull();
process.env.CODEGRAPH_KERNEL = '0';
const wideViaWasm = extractFromSource('src/broken-wide.rs', wide, 'rust');
delete process.env.CODEGRAPH_KERNEL;
expect(wideViaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
});
});
Loading