Repository navigation
feat(inference): inference engine via salsa - #10888
Conversation
|
No actionable comments were generated in the recent review. π βΉοΈ Recent review infoβοΈ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: β Files ignored due to path filters (2)
π Files selected for processing (6)
π§ Files skipped from review as they are similar to previous changes (5)
WalkthroughThis PR adds a Salsa-backed JavaScript type-inference engine with interned types, compound-type builders, module-graph queries, expression and member resolution, formatting, benchmarks, and extensive tests. Module collection now supports Possibly related issues
Possibly related PRs
Suggested labels: Suggested reviewers: π₯ Pre-merge checks | β 4β Passed checks (4 passed)
β¨ Finishing Touchesπ§ͺ Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
π§Ή Nitpick comments (4)
crates/biome_db/src/testing.rs (1)
112-140: π Maintainability & Code Quality | π΅ Trivial | β‘ Quick winDuplicated matching predicate.
The event-matching predicate here is identical to the one in
find_will_execute_event(lines 141-160). Consider extracting a shared helper (e.g. a small closure factory or a common iterator filter) so future tweaks to the matching logic don't need to be applied in two places.β»οΈ Possible consolidation
+fn matches_query_event<I>(db: &dyn salsa::Database, query_name: &str, input_id: salsa::Id, event: &Event) -> bool +where + I: salsa::plumbing::AsId, +{ + if let salsa::EventKind::WillExecute { database_key } = event.kind { + db.ingredient_debug_name(database_key.ingredient_index()) == query_name + && database_key.key_index() == input_id + } else { + false + } +}Then both
function_query_will_execute_positionandfind_will_execute_eventcould call this shared helper.π€ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/biome_db/src/testing.rs` around lines 112 - 140, The `function_query_will_execute_position` predicate duplicates the `WillExecute` matching logic already used by `find_will_execute_event`, so extract the shared event-matching check into a common helper and have both functions reuse it. Keep the helper focused on comparing `ingredient_debug_name`, `database_key.key_index()`, and `query_name(&query)` so any future changes to `salsa::EventKind::WillExecute` matching only need to be made in one place.crates/biome_service/src/workspace/db.rs (1)
101-113: π©Ί Stability & Availability | π΅ Trivial | β‘ Quick winDrop
DerefMutfromDbReadGuard
DbReadGuardis only used for reads here, and there are no call sites that need a mutable fork result. RemovingDerefMutkeeps the deadlock guard tighter; if a mutable escape is intentional, document that path explicitly.π€ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/biome_service/src/workspace/db.rs` around lines 101 - 113, DbReadGuard currently exposes mutable access via DerefMut even though it is only used for reads, so remove the DerefMut impl from DbReadGuard and keep only the Deref impl to WorkspaceDb. If any mutable access is truly needed later, route it through an explicit API on DbReadGuard or WorkspaceDb instead of implicit mutable deref.crates/biome_module_graph/src/db/mod.rs (1)
8-10: π Maintainability & Code Quality | π΅ Trivial | π€ Low valueStale doc comment. The trait now extends
TypeDb, but the comment still referencesDb.π Tiny wording fix
-/// Extends `Db` with module-graph-specific lookups. +/// Extends `TypeDb` with module-graph-specific lookups. #[salsa::db] pub trait ModuleDb: TypeDb {π€ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/biome_module_graph/src/db/mod.rs` around lines 8 - 10, Update the doc comment on ModuleDb so it no longer refers to Db and instead matches the actual supertrait TypeDb; keep the wording aligned with the trait definition in ModuleDb and preserve the module-graph-specific context.crates/biome_js_analyze/src/services/typed.rs (1)
43-56: π Performance & Scalability | π΅ Trivial | β‘ Quick win
resolver()re-runs full module inference on every call.
ModuleResolver::for_module(...)runsrun_inference()(imports + resolve_all + flatten_all) on construction. Sincetype_of_expression,type_of_named_value, andtype_of_functionall callresolver()afresh β andtype_of_memberfans out into two of them β a rule visiting many nodes will re-infer the entire module for each lookup. The previous storedArc<ModuleResolver>amortised this; consider memoising perTypedServiceinstance (e.g. aOnceCell<Option<Arc<ModuleResolver>>>).Not blocking given this isn't wired to production yet, but it'll bite once it is.
π€ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/biome_js_analyze/src/services/typed.rs` around lines 43 - 56, The TypedService::resolver() method is recreating a ModuleResolver on every lookup, which re-runs full module inference repeatedly. Memoize the resolver per TypedService instance so type_of_expression, type_of_named_value, type_of_function, and type_of_member can reuse the same Arc<ModuleResolver>; a OnceCell<Option<Arc<ModuleResolver>>> or equivalent cache in TypedService is a good fit.
π€ Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@crates/biome_js_type_info/src/format_inferred_type_info.rs`:
- Line 795: The `Self::New` formatter in `format_inferred_type_info.rs` is
omitting constructor arguments, so the debug/format output is incomplete
compared with `Self::Call`. Update the `write!` branch for `TypeofNewExpression`
to format both `expr.callee` and `expr.arguments`, mirroring the existing
call-expression handling so `new` expressions round-trip with their full
argument list.
In `@crates/biome_module_graph/src/db/type_inference/expressions.rs`:
- Around line 1432-1471: The string-coercion logic in expressions handling `+`
is missing `InferredTypeData::Tuple(_)`, so tuple/array operands can incorrectly
fall through to `None`. Update the match in `expressions.rs` so the same branch
that returns `Some(InferredTypeData::String)` for `Class`, `Object`, `String`,
etc. also covers `Tuple`, ensuring array-like values are treated as strings
during coercion.
- Around line 1705-1711: In the FilterAction::Retained branch inside the
expression type inference logic, non-flattenable InferredTypeData::InstanceOf
values are currently skipped instead of being preserved. Update the retained
handling in the expressions inference path so that when should_flatten_instance
returns false, the original ty is added to pending/types rather than being
dropped, matching the behavior used for other retained cases and keeping
InstanceOf in the inferred union.
In `@crates/biome_service/src/workspace/db.rs`:
- Around line 58-64: The doc comment for into_untracked_db is mangled and should
be rewritten for clarity. Update the wording in the comment on into_untracked_db
and DbState so the final sentence reads naturally, especially the guidance about
keeping the guard alive for normal reads and only using this escape hatch when a
lower-level read-only API needs a plain WorkspaceDb. Ensure the NOTE remains
intact and legible.
In `@crates/biome_service/src/workspace/server.rs`:
- Around line 3059-3064: The comment above new_root in server.rs has a typo and
is missing the key wording that explains the block scope; update the prose
around get_db and update_snippets so it clearly says the operations are
intentionally kept inside blocks to ensure the forks created by get_db are
dropped before setters run. Keep the fix limited to the nearby inline comment
and preserve the intent of the new_root / workspace_db flow.
---
Nitpick comments:
In `@crates/biome_db/src/testing.rs`:
- Around line 112-140: The `function_query_will_execute_position` predicate
duplicates the `WillExecute` matching logic already used by
`find_will_execute_event`, so extract the shared event-matching check into a
common helper and have both functions reuse it. Keep the helper focused on
comparing `ingredient_debug_name`, `database_key.key_index()`, and
`query_name(&query)` so any future changes to `salsa::EventKind::WillExecute`
matching only need to be made in one place.
In `@crates/biome_js_analyze/src/services/typed.rs`:
- Around line 43-56: The TypedService::resolver() method is recreating a
ModuleResolver on every lookup, which re-runs full module inference repeatedly.
Memoize the resolver per TypedService instance so type_of_expression,
type_of_named_value, type_of_function, and type_of_member can reuse the same
Arc<ModuleResolver>; a OnceCell<Option<Arc<ModuleResolver>>> or equivalent cache
in TypedService is a good fit.
In `@crates/biome_module_graph/src/db/mod.rs`:
- Around line 8-10: Update the doc comment on ModuleDb so it no longer refers to
Db and instead matches the actual supertrait TypeDb; keep the wording aligned
with the trait definition in ModuleDb and preserve the module-graph-specific
context.
In `@crates/biome_service/src/workspace/db.rs`:
- Around line 101-113: DbReadGuard currently exposes mutable access via DerefMut
even though it is only used for reads, so remove the DerefMut impl from
DbReadGuard and keep only the Deref impl to WorkspaceDb. If any mutable access
is truly needed later, route it through an explicit API on DbReadGuard or
WorkspaceDb instead of implicit mutable deref.
πͺ Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
βΉοΈ Review info
βοΈ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: a000ae35-18c7-4d35-8310-d1ae9dce9844
β Files ignored due to path filters (55)
Cargo.lockis excluded by!**/*.lockand included by**crates/biome_module_graph/tests/snapshots/test_infer_call_expression_type_deduplicates_substituted_union_return_type.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_call_expression_type_resolves_union_function_return_type.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_call_expression_type_selects_callable_interface_overload_by_arity.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_call_expression_type_selects_callable_interface_overload_with_optional_parameter_by_arity.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_call_expression_type_selects_callable_interface_overload_with_rest_parameter_by_arity.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_call_expression_type_selects_callable_object_overload_by_arity.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_call_expression_type_selects_function_declaration_overload_by_callback_return_type.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_call_expression_type_selects_imported_function_declaration_overload_by_callback_return_type.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_call_expression_type_substitutes_generic_from_callback_promise_return_type.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_call_expression_type_substitutes_generic_inside_intersection_return_type.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_call_expression_type_substitutes_generic_inside_promise_union_return_type.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_call_expression_type_substitutes_generic_inside_union_with_promise_return_type.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_call_expression_type_substitutes_multiple_generics_inside_union_return_type.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_call_expression_type_substitutes_nested_generic_return_type.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_arithmetic_unary_expressions_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_array_element_expressions_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_await_expressions_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_await_promise_like_expressions_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_await_union_expressions_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_call_expressions_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_conditional_logical_expressions_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_conditional_logical_fast_paths_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_destructuring_edge_expressions_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_destructuring_expressions_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_new_expressions_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_static_member_expressions_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_this_and_super_edge_expressions_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_this_and_super_expressions_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_evaluates_typeof_operator_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_filters_conditional_subsets_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_infers_new_expression_nested_generic_instances_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_merges_class_instance_intersections_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_merges_function_intersections_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_merges_inline_object_intersections_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_merges_mixed_intersections_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_normalizes_intersection_variants_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_normalizes_primitive_intersections_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_normalizes_union_variants_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_preserves_generic_interface_instantiation_parameters.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_preserves_new_expression_generic_instances_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_resolves_builtin_global_identities_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_resolves_generic_builtin_instances_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_resolves_namespace_import_members.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_resolves_namespace_reexport_members.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_resolves_record_index_signature_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_resolves_utility_type_members_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_selects_call_overloads_by_nominal_class_parameters_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_selects_call_overloads_by_parameter_types_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_selects_call_overloads_for_array_and_optional_tuple_spreads_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_infer_module_types_selects_call_overloads_for_subclass_arguments_on_build.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_normalize_type_collapses_equal_merged_reference_targets.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_normalize_type_preserves_recursive_array_local_edge.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_normalize_type_preserves_recursive_local_edge.snapis excluded by!**/*.snapand included by**crates/biome_module_graph/tests/snapshots/test_normalize_type_resolves_typeof_type.snapis excluded by!**/*.snapand included by**
π Files selected for processing (30)
crates/biome_db/src/testing.rscrates/biome_js_analyze/src/lib.rscrates/biome_js_analyze/src/services/typed.rscrates/biome_js_type_info/Cargo.tomlcrates/biome_js_type_info/src/builders.rscrates/biome_js_type_info/src/format_inferred_type_info.rscrates/biome_js_type_info/src/interned_types.rscrates/biome_js_type_info/src/lib.rscrates/biome_js_type_info/src/local_inference.rscrates/biome_module_graph/Cargo.tomlcrates/biome_module_graph/benches/type_inference.rscrates/biome_module_graph/src/db/mod.rscrates/biome_module_graph/src/db/queries.rscrates/biome_module_graph/src/db/type_inference/expressions.rscrates/biome_module_graph/src/db/type_inference/globals.rscrates/biome_module_graph/src/db/type_inference/imports.rscrates/biome_module_graph/src/db/type_inference/lookup.rscrates/biome_module_graph/src/db/type_inference/mod.rscrates/biome_module_graph/src/db/type_inference/qualifiers.rscrates/biome_module_graph/src/db/type_inference/resolver.rscrates/biome_module_graph/src/js_module_info.rscrates/biome_module_graph/src/js_module_info/collector.rscrates/biome_module_graph/src/js_module_info/visitor.rscrates/biome_module_graph/src/lib.rscrates/biome_module_graph/src/module_graph.rscrates/biome_module_graph/tests/snap/mod.rscrates/biome_module_graph/tests/spec_tests_v2.rscrates/biome_service/src/workspace/db.rscrates/biome_service/src/workspace/server.rscrates/biome_workspace_db/src/lib.rs
|
One important thing I forgot. Inside the inference code, I disabled the match wildcard on purpose, because it's very easy to make mistakes. So it's best let the compiler fail when adding a type, so that we're forced in fixing it |
|
Small update: the benchmarks can't be compared in the case of legacy VS new because the new engine works on a pull system. The old system is eager and flatten the types every time, the new system is lazy, and flattening (normalisation) is executed on demand by the rules. |
Summary
Important
This code isn't wired to production. Production still uses the current engine.
Part of #10883
This PR ports the existing engine to use the new salsa-backed engine. I implemented the PR mostly via coding agents. I crafted the plan with 5 iterations, and used two agents + and human review of the code emitted.
Below, an AI-generated summary of the change
How the new inference engine works
The big picture
The old engine did everything in one go, per file, every time. The new engine splits the work into collect once, infer once per change, look up many times.
Step 1 β Collect raw types
While walking the AST, the collector writes down every type it sees into a flat table: "slot 3 is a function returning slot 5", "slot 7 is
typeofof the expression in slot 6". Nothing is resolved yet β names are still names, imports are still paths. This table is cheap to build and is the input salsa watches for changes.Step 2 β Resolve (the salsa query)
infer_module_typeswalks the raw table and turns every entry into a real type:class Foo { next: Foo }stores a handle to itself instead of infinitely nesting. Whoever holds the handle resolves it later, one hop at a time.Flattening happens while building, not after
The old engine built messy types first and then ran a flatten pass up to ten times to clean them up. The new engine refuses to build messy types in the first place: every union and intersection goes through a builder that flattens nested unions, removes duplicates, collapses
true | falseintoboolean, and merges intersected object members β at the moment the type is created. There is no flatten pass anymore because there is nothing left to flatten.Expressions are evaluated during resolution
The raw table stores expressions like "the call of slot 4" or "await of slot 9". During resolution these are computed: a call looks up the function's return type (picking the right overload by checking each argument against each parameter),
awaitunwraps thePromise,a ?? bbecomes "the non-nullish part ofa, orb", member access finds the member β walking upextendschains if needed.Substitution makes generics concrete
When a generic shape meets concrete type arguments β
Box<string>, or a call likeidentity("hi")β the engine collects which type parameter maps to what (T β string) and then rebuilds the affected type with everyTreplaced. Types are immutable here, so substitution never edits anything: it produces a new type, and the union builder cleans up whatever the replacement produced (e.g.T | Tafter substitution becomes juststring). This runs for generic classes, function returns, callbacks, and inherited members (ClassBox<T> extends ClassBase<T>carries the substitution through the lookup).Everything is interned
Every type built this way is stored once, globally, and referred to by a tiny copyable id. Two identical types β even from different modules β are literally the same id, so comparing types is comparing two numbers, and duplicates cost nothing.
Why it's fast on re-analysis
Salsa remembers the result of
infer_module_typesper module. Edit one file and only that file (and the files whose results actually change) re-infer; everything else is a cache hit. Measured on the benchmark fixtures: a five-module graph costs ~142 ms to infer cold, ~80 Β΅s after editing one file, and 3β46 Β΅s to re-query unchanged.Safety rails
Every loop that follows references (handle chains, member lookups, promise unwrapping) carries a visited set and a step budget: a weird or cyclic type degrades to
unknowninstead of hanging. The engine prefers a vaguer answer over a wrong one β and always over no answer.'db, which is one of the reasons why it was best to create a new engine. The type isTypeDataTypeDbtrait. It only contains a function used to resolve the name of the locally resolved types.queries.rsis a big mess in terms of sorting and placement. I will tidy them up in the next PR.Test Plan
I added new tests inside the
spec_test_v2.rs, and many snapshot tests so that we can cover as much ground as possible before switching to the new engine, without breaking people's code.I also added new benchmarks that show how salsa is useful:
bench_index_d_ts_salsa_incrementalandbench_index_d_ts_salsa_incremental_first_run. The latter runs inference on cold cache, the former runs on cold cache, we apply a change to the source code e.g. a type and then it runs the inference again. Below, you can how it takes less because with salsa we compute only things that changedDocs
What's next
Two major things:
type Tree = string | Tree[]. For that, there's theTypeData::Divergenttype. We will use it for fixing cycles when importing modules e.g. module A imports B, and B imports A.