Skip to content
Merged
65 changes: 63 additions & 2 deletions crates/cg-extract/src/facts/js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) {
}
walk_children(cx, n, scope);
}
"nested_type_identifier" => {
namespace_type(cx, n);
walk_children(cx, n, scope);
}
_ => walk_children(cx, n, scope),
}
}
Expand Down Expand Up @@ -378,6 +382,7 @@ fn export_stmt(cx: &mut Cx, n: Node) {
});
}
let is_default = kids(n).any(|c| c.kind() == "default");
let stmt_type_only = kids(n).any(|c| c.kind() == "type");
let mut had_clause = false;
for ch in kids(n) {
match ch.kind() {
Expand All @@ -389,6 +394,20 @@ fn export_stmt(cx: &mut Cx, n: Node) {
}
let name = sp.child_by_field_name("name").map(|c| unquote(cx.text(c)).to_owned()).unwrap_or_default();
let alias = sp.child_by_field_name("alias").map(|c| unquote(cx.text(c)).to_owned());
if let Some(spec) = &source {
// `export { a as b } from 'x'` imports `a` without binding it here (no local)
let line = cx.line(n);
let type_only = stmt_type_only || kids(sp).any(|c| c.kind() == "type");
cx.add_import(ImportFact {
local: String::new(),
imported: name.clone(),
spec: spec.clone(),
kind: ImportKind::Named,
type_only,
scope: 0,
line,
});
}
cx.facts.exports.push(ExportFact {
name: alias.unwrap_or_else(|| name.clone()),
node_row: NONE,
Expand Down Expand Up @@ -639,6 +658,7 @@ fn function(cx: &mut Cx, n: Node, scope: u32) {
}
}
let sc = cx.push_scope(ScopeKind::Function, scope, n);
type_params(cx, n, sc);
return_annotation(cx, n, sc);
let line = cx.line(n);
if let Some(p) = n.child_by_field_name("parameter") {
Expand Down Expand Up @@ -673,6 +693,15 @@ fn function(cx: &mut Cx, n: Node, scope: u32) {
}
}

/// `class Schema<Output>`, `function f<T>()`: `Output` and `T` inside name no declaration.
fn type_params(cx: &mut Cx, n: Node, sc: u32) {
let Some(params) = n.child_by_field_name("type_parameters") else { return };
for name in kids(params).filter_map(|p| p.child_by_field_name("name")) {
let name = cx.text(name).to_owned();
cx.add_binding(sc, &name, BindKind::TypeParam, "", "", 0);
}
}

/// Record the narrow `merge-descriptors` factory pattern used by Express: a local
/// function/object is mixed with an imported module and then returned. We do not
/// infer anything from an arbitrary function called `mixin` or from nested calls.
Expand Down Expand Up @@ -768,6 +797,7 @@ fn factory_mixin(cx: &mut Cx, n: Node, scope: u32) {

fn class(cx: &mut Cx, n: Node, scope: u32) {
let sc = cx.push_scope(ScopeKind::Class, scope, n);
type_params(cx, n, sc);
let Some(body) = n.child_by_field_name("body") else {
walk_children(cx, n, scope);
return;
Expand All @@ -783,8 +813,10 @@ fn class(cx: &mut Cx, n: Node, scope: u32) {
let line = cx.line(m);
cx.add_binding(sc, &nm, BindKind::Field, if ty.is_empty() { &vt } else { &ty }, &init, line);
}
if let Some(v) = m.child_by_field_name("value") {
walk(cx, v, sc);
for c in ["type", "value"] {
if let Some(v) = m.child_by_field_name(c) {
walk(cx, v, sc);
}
}
}
"method_definition" => {
Expand Down Expand Up @@ -828,13 +860,36 @@ fn require_target(cx: &Cx, v: Node) -> Option<String> {
Some(unquote(cx.text(first)).to_owned())
}

/// `core.output<T>`: the kernel names the type by its last segment (`output`); the path as
/// written keeps the namespace's type apart from a same-named one beside the reference.
fn namespace_type(cx: &mut Cx, n: Node) {
let Some(name) = n.child_by_field_name("name") else { return };
let pos = cx.start(name);
let tail = cx.text(name).to_owned();
let path: String = cx.text(n).chars().filter(|c| !c.is_whitespace()).collect();
cx.facts.call_names.push(CallNameFact { line: (pos >> 32) as u32, col: pos as u32, kernel_name: tail.clone(), tail, name: path });
}

/// `require('./utils').compileETag`: the module and the member it reads.
fn require_member(cx: &Cx, v: Node) -> Option<(String, String)> {
if v.kind() != "member_expression" {
return None;
}
let spec = require_target(cx, v.child_by_field_name("object")?)?;
let prop = v.child_by_field_name("property").filter(|p| p.kind() == "property_identifier")?;
Some((spec, cx.text(prop).to_owned()))
}

fn var_decl(cx: &mut Cx, n: Node, scope: u32) {
for d in kids(n) {
if d.kind() != "variable_declarator" {
continue;
}
let Some(name) = d.child_by_field_name("name") else { continue };
let ty = d.child_by_field_name("type").map(|t| ts_type_name(cx, t)).unwrap_or_default();
if let Some(t) = d.child_by_field_name("type") {
walk(cx, t, scope); // `core.ParseContext` inside the annotation
}
let value = d.child_by_field_name("value");
if let Some(v) = value {
// `var app = exports = module.exports = {}` ties subsequent
Expand Down Expand Up @@ -877,6 +932,12 @@ fn var_decl(cx: &mut Cx, n: Node, scope: u32) {
}
continue;
}
// `var compileETag = require('./utils').compileETag`, like `const { compileETag } = require('./utils')`
if let Some((spec, imported)) = require_member(cx, v).filter(|_| name.kind() == "identifier") {
let local = cx.text(name).to_owned();
cx.add_import(ImportFact { local, imported, spec, kind: ImportKind::Require, type_only: false, scope, line: cx.line(d) });
continue;
}
let is_fn = matches!(v.kind(), "arrow_function" | "function_expression" | "function" | "generator_function");
let constant = kids(n).next().is_some_and(|k| k.kind() == "const");
if is_fn && name.kind() == "identifier" {
Expand Down
3 changes: 3 additions & 0 deletions crates/cg-extract/src/facts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,9 @@ pub enum BindKind {
/// C++ `#define BEGIN namespace fmt {`: `name` is a namespace opened only by a macro, which
/// no node of the index stands for. Metadata only; not a lexical binding.
MacroNamespace = 15,
/// A Rust type parameter of the fn, impl or trait whose scope holds it. Only a type
/// reference sees it: `T` in `fn new(value: T)` names no `struct T` elsewhere.
TypeParam = 16,
}

#[derive(Clone, Debug, PartialEq, Eq)]
Expand Down
41 changes: 41 additions & 0 deletions crates/cg-extract/src/facts/rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) {
let generics = generics_of(cx, n);
cx.generics.push(generics);
let sc = cx.push_scope(ScopeKind::Class, scope, n);
bind_type_params(cx, sc);
if n.kind() == "impl_item" {
deref_impl(cx, n, scope);
}
Expand Down Expand Up @@ -176,6 +177,10 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) {
}
walk_children(cx, n, scope);
}
"scoped_identifier" => {
scoped_receiver(cx, n);
walk_children(cx, n, scope);
}
"for_expression" => {
if let Some(p) = n.child_by_field_name("pattern") {
bind_pattern(cx, p, scope, BindKind::Local);
Expand All @@ -192,6 +197,20 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) {
}
}

/// `mio::Interest::AIO`: the kernel names the receiver of a path's member by its last segment
/// (`Interest`); the path as written keeps a dependency's type apart from a local one.
fn scoped_receiver(cx: &mut Cx, n: Node) {
let (Some(path), Some(member)) = (n.child_by_field_name("path"), n.child_by_field_name("name")) else { return };
if path.kind() != "scoped_identifier" || !cx.text(member).starts_with(|c: char| c.is_ascii_uppercase()) {
return;
}
let Some(recv) = path.child_by_field_name("name") else { return };
let pos = cx.start(recv);
let recv = cx.text(recv).to_owned();
let name = cx.text(path).to_owned();
cx.facts.call_names.push(CallNameFact { line: (pos >> 32) as u32, col: pos as u32, tail: recv.clone(), kernel_name: recv, name });
}

/// Bounds that add nothing a call goes through.
const MARKER_TRAITS: &[&str] =
&["Clone", "Copy", "Send", "Sync", "Sized", "Debug", "Default", "Eq", "PartialEq", "Hash", "Ord", "PartialOrd", "Display", "Unpin", "Any"];
Expand Down Expand Up @@ -391,6 +410,19 @@ fn let_decl(cx: &mut Cx, n: Node, scope: u32) {
if target.kind() == "identifier" {
let nm = cx.text(target).to_owned();
cx.add_binding(scope, &nm, BindKind::Local, &ty, &init, line);
} else if target.kind() == "tuple_pattern" && init.ends_with([')', '?']) && !kids(target).any(|c| c.kind() == "remaining_field_pattern") {
// `let (tx, rx) = mpsc::channel()`: element i holds the call's `.i`
let elems: Vec<Node> = kids(target).filter(|c| (c.is_named() || c.kind() == "_") && !c.kind().ends_with("comment")).collect();
for (i, e) in elems.into_iter().enumerate() {
// `mut rx`: `mutable_specifier` first, then the pattern
let id = if e.kind() == "mut_pattern" { e.named_child(1).unwrap_or(e) } else { e };
if id.kind() == "identifier" {
let nm = cx.text(id).to_owned();
cx.add_binding(scope, &nm, BindKind::Local, "", &format!("{init}.{i}"), line);
} else {
bind_pattern(cx, e, scope, BindKind::Local);
}
}
} else {
bind_pattern(cx, p, scope, BindKind::Local);
}
Expand Down Expand Up @@ -457,6 +489,7 @@ fn function_body(cx: &mut Cx, n: Node, scope: u32) {
}
}
let sc = cx.push_scope(ScopeKind::Function, scope, n);
bind_type_params(cx, sc);
if let Some(p) = n.child_by_field_name("parameters") {
params(cx, p, sc);
}
Expand All @@ -465,6 +498,14 @@ fn function_body(cx: &mut Cx, n: Node, scope: u32) {
}
}

/// The type parameters of the item whose scope `sc` is (the innermost `cx.generics`).
fn bind_type_params(cx: &mut Cx, sc: u32) {
let names: Vec<String> = cx.generics.last().map(|g| g.iter().map(|(n, _)| n.clone()).collect()).unwrap_or_default();
for n in names {
cx.add_binding(sc, &n, BindKind::TypeParam, "", "", 0);
}
}

fn closure(cx: &mut Cx, n: Node, scope: u32) {
let sc = cx.push_scope(ScopeKind::Function, scope, n);
if let Some(p) = n.child_by_field_name("parameters") {
Expand Down
21 changes: 19 additions & 2 deletions crates/cg-resolve/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -694,8 +694,8 @@ impl<'v> Engine<'v> {
cross.push(cand);
}
match self.view.file(tfile).lang().family() {
// Java/Kotlin nested types (pre-existing behaviour)
LangFamily::Jvm => best.filter(|_| tn.qname().contains("::")),
// Java/Kotlin nested types (pre-existing behaviour), then a Kotlin extension function
LangFamily::Jvm => best.filter(|_| tn.qname().contains("::")).or_else(|| self.kotlin_extension(t, name)),
// Swift extensions (emitted as class nodes) add members in other files and other
// modules (a test target extending the library's type). Pick deterministically:
// posting order (base before delta) must never decide.
Expand All @@ -716,6 +716,23 @@ impl<'v> Engine<'v> {
}
}

/// Kotlin `fun Lockable.awaitNanos()` outside any type body: the kernel names it
/// `Lockable::awaitNanos`, without the package. One in `t`'s package first, else the only one.
fn kotlin_extension(&self, t: NodeIdx, name: &str) -> Option<NodeIdx> {
let view = self.view;
let tn = view.node(t);
let mut cands: SmallVec<[NodeIdx; 4]> = view
.by_qname(&format!("{}::{}", tn.name(), name))
.filter(|&c| view.file(view.hot(c).file).lang() == Lang::Kotlin && view.node(c).parent().is_none_or(|p| !view.node(p).kind().is_type()))
.collect();
cands.sort_by_key(|&c| (view.file(view.hot(c).file).path(), view.node(c).start_line()));
let tpkg = self.modules.pkg_of(tn.file());
match cands.as_slice() {
[only] => Some(*only),
_ => cands.iter().copied().find(|&c| self.modules.pkg_of(view.hot(c).file) == tpkg),
}
}

/// Whether a member with type `t`'s qualified name found in another file belongs to `t`:
/// C# / Ruby when that file re-declares the type (partial class, reopened class or
/// module); C/C++ when the member's file includes the type's file or vice versa.
Expand Down
Loading
Loading