Skip to main content

model_lang_java/
lib.rs

1//! Java enricher for Model: HTTP endpoints and GWT RPC calls.
2//!
3//! Run it on a [`ModelBuilder`] after `model-treesitter` (and the SCIP link)
4//! extracted the Java files: it re-reads the sources, finds the entities the
5//! extraction made by the position of their name, and adds facts a query
6//! cannot express. The only kind added is `http.endpoint`, shared with the
7//! Python and TypeScript enrichers; no language name enters `model-core`.
8//!
9//! # What it adds
10//!
11//! | Fact | Where | Shape |
12//! |---|---|---|
13//! | [`HTTP_ENDPOINT`] entity (`http.endpoint`, props `http.verb`, `http.path`) | child of the handler method, named `VERB /path`, relation `http.endpoints` from the method | `ANY` for any verb, `?` for a path that is not a literal |
14//! | [`PROP_ENDPOINTS`] (`http.endpoints`) | handler method | list of `"VERB /path"`, as TypeScript's |
15//! | [`PROP_RPC_SERVICE`] (`rpc.service`) | `RemoteService` interface | `true` |
16//! | [`PROP_RPC_CALLS`] (`rpc.calls`) | method or constructor calling a service | list of `"a.b.Service#method/arity"` (call arity, callback included) |
17//! | [`RPC_RELATION`] (`gwt-rpc`, `RelationKind::Other`) | caller → implementing method | `Provenance::Frontend`, one site per call |
18//!
19//! Endpoints: Spring `@RequestMapping` and `@Get/Post/Put/Delete/PatchMapping`
20//! (verbs, path arrays, `path =`/`value =`), JAX-RS `@Path` with `@GET`...;
21//! the class-level prefix comes from the type, else from the nearest
22//! supertype that has one. A method without a mapping inherits the one of the
23//! method it overrides (same name and arity) on a supertype, also one of the
24//! build-generated sources (`target/generated-sources`, `build/generated`,
25//! read for that purpose only, never given entities). Feign and
26//! `@HttpExchange` clients serve nothing.
27//!
28//! GWT RPC: a call is RPC-shaped when its receiver is an `XAsync` field,
29//! local or parameter, `X.Util.getInstance()` or `GWT.create(X.class)`, and
30//! `X` is a project `RemoteService` (or an unresolved `XAsync`, resolved by
31//! the name of the implementing classes' supertypes). The relation goes to
32//! the method of each implementing class (transitively), matched by name and
33//! arity with the callback dropped, then kept.
34//!
35//! # Moose / Famix
36//!
37//! Famix has no class for these facts. The `http.endpoint` entities have no
38//! FM3 class (the exporter skips them), the other facts are extension
39//! properties of existing entities, kept by the JSON model and ignored by
40//! `model-moose`'s export: an `http.endpoints` prop is not written, and the `gwt-rpc` relation is reported by the exporter as
41//! `gwt-rpc (no Famix association)`; the entities themselves export as
42//! before (`tests/moose.rs` checks it).
43//!
44//! # Scope
45//!
46//! Files under `src/test/` are not read. Entities are found by file and
47//! name position, so the model must come from the same sources
48//! (tree-sitter, with or without SCIP: lifted entities keep their ranges).
49
50use std::collections::{HashMap, HashSet};
51use std::path::Path;
52use std::sync::Arc;
53
54use anyhow::Context;
55use model_core::{
56    Descriptor, EntityId, EntityKind, KindId, LanguageId, ModelBuilder, Provenance, RelationKind,
57};
58use rayon::prelude::*;
59
60mod parse;
61mod rpc;
62
63use parse::{FileFacts, MethodDecl, Pos, Route, TypeDecl, join_paths, parse_source};
64use rpc::Receiver;
65
66#[cfg(test)]
67mod tests;
68
69/// Property of a handler method: its endpoints, `"GET /articles/{slug}"`.
70pub const PROP_ENDPOINTS: &str = "http.endpoints";
71/// Fine kind of the entity made for each endpoint: shared with the Python and
72/// TypeScript enrichers.
73pub const HTTP_ENDPOINT: &str = "http.endpoint";
74
75/// Defines the kinds this enricher adds (normally defined when first met),
76/// see `model_treesitter::declare_kinds`.
77pub fn declare_kinds(b: &mut ModelBuilder) -> KindId {
78    let id = b.define_kind(
79        HTTP_ENDPOINT,
80        EntityKind::Variable,
81        model_traits::mask(&["Named"]),
82        None,
83    );
84    b.set_kind_concept(id, Some("HttpEndpoint"), Some("httpEndpoints"));
85    id
86}
87/// Property of a `RemoteService` interface: `true`.
88pub const PROP_RPC_SERVICE: &str = "rpc.service";
89/// Property of a caller: the RPC calls it makes, `"a.b.Service#method/arity"`.
90pub const PROP_RPC_CALLS: &str = "rpc.calls";
91/// Name of the relation (`RelationKind::Other`) from a GWT RPC caller to the
92/// implementing method.
93pub const RPC_RELATION: &str = "gwt-rpc";
94
95/// The GWT RPC relation kind.
96pub fn rpc_relation() -> RelationKind {
97    RelationKind::Other(RPC_RELATION.to_string())
98}
99
100/// What an enrichment found.
101#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
102pub struct JavaStats {
103    /// Java files read (build-generated ones apart).
104    pub files: usize,
105    /// Build-generated files read for endpoint inheritance.
106    pub generated_files: usize,
107    /// Methods given an `http.endpoints` prop.
108    pub handlers: usize,
109    /// Endpoints written (a method may serve several).
110    pub endpoints: usize,
111    /// RPC calls whose service is known (project service, or a name).
112    pub rpc_calls: usize,
113    /// ... of which reached at least one implementing method.
114    pub rpc_linked: usize,
115    /// Calls on a possible but unconfirmed service (`X.Util.getInstance()`
116    /// with no `RemoteService` `X` nor `XAsync` in the project): dropped.
117    pub rpc_maybe: usize,
118    /// Classes implementing an unresolved `*Api` interface: their endpoints
119    /// are unknown (generated sources missing).
120    pub unresolved_api: usize,
121}
122
123/// Whether `rel` (`/`-separated) is read: a Java file outside `src/test/`.
124fn eligible(rel: &str) -> bool {
125    rel.ends_with(".java") && !rel.contains("src/test/")
126}
127
128/// Whether `rel` is under a build-generated source tree.
129fn in_generated(rel: &Path) -> bool {
130    let comps: Vec<_> = rel.components().map(|c| c.as_os_str()).collect();
131    comps.windows(2).any(|w| {
132        (w[0] == "target" && w[1] == "generated-sources")
133            || (w[0] == "build" && w[1] == "generated")
134    })
135}
136
137/// `.java` files under `target/generated-sources/**` and `build/generated/**`,
138/// as sorted `/`-separated paths relative to `root`.
139pub fn generated_files(root: &Path) -> Vec<String> {
140    let walk_root = root.to_path_buf();
141    let mut walker = ignore::WalkBuilder::new(root);
142    walker.standard_filters(false).filter_entry(move |e| {
143        if e.depth() == 0 || !e.file_type().is_some_and(|t| t.is_dir()) {
144            return true;
145        }
146        let n = e.file_name().to_string_lossy();
147        if matches!(n.as_ref(), "node_modules" | ".git" | ".gradle") {
148            return false;
149        }
150        let rel = e.path().strip_prefix(&walk_root).unwrap_or(e.path());
151        // Main sources are read elsewhere; only generated trees matter here.
152        in_generated(rel) || n != "src"
153    });
154    // Unreadable entries are skipped: these files only feed inheritance.
155    let mut files = model_detect::par_walk(&walker, false, |e| {
156        if !e.file_type().is_some_and(|t| t.is_file()) {
157            return None;
158        }
159        let rel = e.path().strip_prefix(root).ok()?;
160        (rel.extension().is_some_and(|x| x == "java") && in_generated(rel))
161            .then(|| rel.to_string_lossy().replace('\\', "/"))
162    })
163    .unwrap_or_default();
164    files.sort();
165    files
166}
167
168/// Enriches `b` from the Java files under `root` (the root the model was
169/// extracted from). Reads the same files `model-treesitter` does, minus
170/// `src/test/`, plus the build-generated sources for endpoint inheritance.
171pub fn enrich(b: &mut ModelBuilder, root: &Path) -> anyhow::Result<JavaStats> {
172    let opts = model_treesitter::ExtractOptions {
173        relations: false,
174        languages: Some(vec!["java".to_string()]),
175        ..Default::default()
176    };
177    enrich_files(b, root, &model_treesitter::source_files(root, &opts)?)
178}
179
180/// [`enrich`] over `files`, the source files under `root` as
181/// `model_treesitter::source_files` lists them (paths relative to `root`;
182/// those that are not Java are skipped): a caller that has the list saves
183/// walking the tree again.
184pub fn enrich_files(
185    b: &mut ModelBuilder,
186    root: &Path,
187    files: &[String],
188) -> anyhow::Result<JavaStats> {
189    Ok(prepare_files(root, files)?.apply(b))
190}
191
192/// [`enrich`] over in-memory sources `(relative path, text)`. `generated`
193/// are build-generated sources, read for endpoint inheritance only. Files
194/// that are not Java or under `src/test/` are skipped.
195pub fn enrich_sources(
196    b: &mut ModelBuilder,
197    sources: &[(&str, &str)],
198    generated: &[(&str, &str)],
199) -> anyhow::Result<JavaStats> {
200    Ok(prepare_sources(sources, generated)?.apply(b))
201}
202
203/// The Java sources of a project, read and parsed, ready to enrich a model.
204/// Parsing needs no builder: a caller can prepare while the model is being
205/// built (extraction, SCIP linking), then [`apply`](Prepared::apply).
206#[derive(Debug)]
207pub struct Prepared {
208    parsed: Vec<Arc<FileFacts>>,
209    generated: Vec<Arc<FileFacts>>,
210}
211
212impl Prepared {
213    /// Combines per-file preparations without parsing sources again.
214    pub fn combine<'a>(parts: impl IntoIterator<Item = &'a Prepared>) -> Prepared {
215        let mut prepared = Prepared {
216            parsed: Vec::new(),
217            generated: Vec::new(),
218        };
219        for part in parts {
220            prepared.parsed.extend(part.parsed.iter().cloned());
221            prepared.generated.extend(part.generated.iter().cloned());
222        }
223        prepared
224            .parsed
225            .sort_by(|a, b| a.file.split('/').cmp(b.file.split('/')));
226        prepared
227            .generated
228            .sort_by(|a, b| a.file.split('/').cmp(b.file.split('/')));
229        prepared
230    }
231
232    /// Adds the facts to `b`, which must hold the entities extracted from
233    /// the same sources: [`enrich_files`] in two steps.
234    pub fn apply(&self, b: &mut ModelBuilder) -> JavaStats {
235        run(b, &self.parsed, &self.generated)
236    }
237}
238
239/// Reads and parses what [`enrich_files`] does, without a builder.
240pub fn prepare_files(root: &Path, files: &[String]) -> anyhow::Result<Prepared> {
241    let read = |rel: &String| -> anyhow::Result<(String, String)> {
242        let bytes = std::fs::read(root.join(rel)).with_context(|| format!("reading {rel}"))?;
243        Ok((rel.clone(), String::from_utf8_lossy(&bytes).into_owned()))
244    };
245    let main = files
246        .par_iter()
247        // A build-generated tree is read below, for inheritance only: whether
248        // an ignore rule hides it from the walk must not change the result.
249        .filter(|f| eligible(f) && !in_generated(Path::new(f)))
250        .map(read)
251        .collect::<anyhow::Result<Vec<_>>>()?;
252    let gen_paths = generated_files(root);
253    // A generated file that cannot be read is skipped: it only feeds inheritance.
254    let generated: Vec<(String, String)> =
255        gen_paths.par_iter().filter_map(|p| read(p).ok()).collect();
256    let main: Vec<(&str, &str)> = main.iter().map(|(a, b)| (a.as_str(), b.as_str())).collect();
257    let generated: Vec<(&str, &str)> = generated
258        .iter()
259        .map(|(a, b)| (a.as_str(), b.as_str()))
260        .collect();
261    prepare_sources(&main, &generated)
262}
263
264/// Parses what [`enrich_sources`] does, without a builder.
265pub fn prepare_sources(
266    sources: &[(&str, &str)],
267    generated: &[(&str, &str)],
268) -> anyhow::Result<Prepared> {
269    let mut kept: Vec<&(&str, &str)> = sources.iter().filter(|(rel, _)| eligible(rel)).collect();
270    kept.sort_by(|a, b| a.0.split('/').cmp(b.0.split('/')));
271    let parsed: Vec<Arc<FileFacts>> = kept
272        .par_iter()
273        .map(|(rel, src)| parse_source(rel, src).map(Arc::new))
274        .collect::<anyhow::Result<_>>()?;
275    let mut gen_sorted: Vec<&(&str, &str)> = generated
276        .iter()
277        .filter(|(rel, _)| rel.ends_with(".java"))
278        .collect();
279    gen_sorted.sort_by(|a, b| a.0.split('/').cmp(b.0.split('/')));
280    let generated: Vec<Arc<FileFacts>> = gen_sorted
281        .par_iter()
282        .filter_map(|(rel, src)| parse_source(rel, src).ok().map(Arc::new))
283        .collect();
284    Ok(Prepared { parsed, generated })
285}
286
287// ---- type resolution ----
288
289/// Where a type was declared.
290#[derive(Clone, Copy)]
291struct TypeRef<'a> {
292    file: &'a FileFacts,
293    decl: &'a TypeDecl,
294}
295
296/// Type lookup tables used to resolve simple names to type ids.
297struct TypeIndex<'a> {
298    /// dotted name (`a.b.Outer.Inner`) -> id
299    dotted: HashMap<String, &'a str>,
300    /// simple name -> ids
301    simple: HashMap<&'a str, Vec<&'a str>>,
302    by_id: HashMap<&'a str, TypeRef<'a>>,
303}
304
305impl<'a> TypeIndex<'a> {
306    fn new(files: &'a [Arc<FileFacts>]) -> Self {
307        let mut idx = TypeIndex {
308            dotted: HashMap::new(),
309            simple: HashMap::new(),
310            by_id: HashMap::new(),
311        };
312        for file in files {
313            for decl in &file.types {
314                idx.dotted.insert(decl.id.replace('$', "."), &decl.id);
315                idx.simple.entry(&decl.name).or_default().push(&decl.id);
316                idx.by_id.entry(&decl.id).or_insert(TypeRef { file, decl });
317            }
318        }
319        idx
320    }
321
322    fn resolve(&self, fs: &FileFacts, name: &str) -> Option<&'a str> {
323        let suffix = format!(".{name}");
324        let mut explicit = false;
325        for imp in fs.imports.iter().filter(|i| i.ends_with(&suffix)) {
326            explicit = true;
327            if let Some(id) = self.dotted.get(imp) {
328                return Some(id);
329            }
330        }
331        if explicit {
332            // Explicitly imported non-project class: external, never guess.
333            return None;
334        }
335        match &fs.package {
336            Some(p) => {
337                if let Some(id) = self.dotted.get(&format!("{p}{suffix}")) {
338                    return Some(id);
339                }
340            }
341            None => {
342                if let Some(id) = self.dotted.get(name) {
343                    return Some(id);
344                }
345            }
346        }
347        for imp in fs.imports.iter().filter_map(|i| i.strip_suffix(".*")) {
348            if let Some(id) = self.dotted.get(&format!("{imp}{suffix}")) {
349                return Some(id);
350            }
351        }
352        match self.simple.get(name).map(Vec::as_slice) {
353            Some([only]) => Some(only),
354            _ => None,
355        }
356    }
357}
358
359// ---- entities ----
360
361/// Entities of the model by file and name position.
362struct Entities {
363    by_file: HashMap<String, HashMap<Pos, Vec<EntityId>>>,
364}
365
366impl Entities {
367    fn new(b: &ModelBuilder) -> Self {
368        let mut by_file: HashMap<String, HashMap<Pos, Vec<EntityId>>> = HashMap::new();
369        for id in b.ids() {
370            if let (Some(file), Some(r)) = (b.file(id), b.name_range(id))
371                && file.ends_with(".java")
372            {
373                by_file
374                    .entry(file.to_string())
375                    .or_default()
376                    .entry((r.start_line, r.start_col))
377                    .or_default()
378                    .push(id);
379            }
380        }
381        Entities { by_file }
382    }
383
384    fn find(
385        &self,
386        b: &ModelBuilder,
387        file: &str,
388        pos: Pos,
389        keep: fn(&ModelBuilder, EntityId) -> bool,
390    ) -> Option<EntityId> {
391        self.by_file
392            .get(file)?
393            .get(&pos)?
394            .iter()
395            .copied()
396            .find(|&id| keep(b, id))
397    }
398
399    fn method(&self, b: &ModelBuilder, file: &str, m: &MethodDecl) -> Option<EntityId> {
400        self.find(b, file, m.name_pos, |b, id| b.kind(id).is_callable())
401    }
402
403    fn type_of(&self, b: &ModelBuilder, file: &str, t: &TypeDecl) -> Option<EntityId> {
404        self.find(b, file, t.name_pos, |b, id| b.kind(id).is_type())
405    }
406}
407
408// ---- HTTP ----
409
410type Supers = HashMap<String, Vec<String>>;
411type RouteTable = HashMap<String, Vec<Route>>;
412
413/// Endpoints (no class prefix) of `tid#suffix` found on a supertype, transitively.
414fn inherited_routes<'a>(
415    supers: &Supers,
416    routes: &'a RouteTable,
417    tid: &str,
418    suffix: &str,
419    seen: &mut HashSet<String>,
420) -> Option<&'a Vec<Route>> {
421    for sup in supers.get(tid)? {
422        if !seen.insert(sup.clone()) {
423            continue;
424        }
425        if let Some(r) = routes.get(&format!("{sup}#{suffix}")) {
426            return Some(r);
427        }
428        if let Some(r) = inherited_routes(supers, routes, sup, suffix, seen) {
429            return Some(r);
430        }
431    }
432    None
433}
434
435/// Prefixes in force for `tid`: its own mapping, else the nearest supertype's.
436fn effective_prefixes(
437    supers: &Supers,
438    prefixes: &HashMap<String, Vec<String>>,
439    tid: &str,
440    seen: &mut HashSet<String>,
441) -> Option<Vec<String>> {
442    if let Some(p) = prefixes.get(tid) {
443        return Some(p.clone());
444    }
445    for sup in supers.get(tid)? {
446        if seen.insert(sup.clone())
447            && let Some(p) = effective_prefixes(supers, prefixes, sup, seen)
448        {
449            return Some(p);
450        }
451    }
452    None
453}
454
455fn suffix_of(m: &MethodDecl) -> String {
456    format!("{}({})", m.name, m.arity)
457}
458
459/// Writes `http.endpoints` on the handler methods.
460fn http(
461    b: &mut ModelBuilder,
462    ents: &Entities,
463    parsed: &[Arc<FileFacts>],
464    generated: &[Arc<FileFacts>],
465    index: &TypeIndex,
466    stats: &mut JavaStats,
467) {
468    let kind = declare_kinds(b);
469    let gen_index = TypeIndex::new(generated);
470    let mut supers: Supers = HashMap::new();
471    let mut routes: RouteTable = HashMap::new();
472    let mut prefixes: HashMap<String, Vec<String>> = HashMap::new();
473    // Parsed code first: it wins over a generated twin with the same id.
474    for (is_parsed, fs) in parsed
475        .iter()
476        .map(|f| (true, f))
477        .chain(generated.iter().map(|f| (false, f)))
478    {
479        for t in &fs.types {
480            if !t.supertypes.is_empty() {
481                let mut resolved = Vec::new();
482                let mut missing_api = false;
483                for sup in &t.supertypes {
484                    match index
485                        .resolve(fs, sup)
486                        .or_else(|| gen_index.resolve(fs, sup))
487                    {
488                        Some(id) => resolved.push(id.to_string()),
489                        None => missing_api |= sup.ends_with("Api"),
490                    }
491                }
492                if is_parsed && !t.interface && missing_api {
493                    stats.unresolved_api += 1;
494                }
495                supers.entry(t.id.clone()).or_insert(resolved);
496            }
497            if let Some(p) = &t.prefixes {
498                prefixes.entry(t.id.clone()).or_insert_with(|| p.clone());
499            }
500            for m in t.methods.iter().filter(|m| !m.routes.is_empty()) {
501                routes
502                    .entry(format!("{}#{}", t.id, suffix_of(m)))
503                    .or_insert_with(|| m.routes.clone());
504            }
505        }
506    }
507    for fs in parsed {
508        for t in &fs.types {
509            for m in t.methods.iter().filter(|m| !m.constructor) {
510                let own = routes.get(&format!("{}#{}", t.id, suffix_of(m)));
511                let raw = match own {
512                    Some(r) => r,
513                    None => {
514                        match inherited_routes(
515                            &supers,
516                            &routes,
517                            &t.id,
518                            &suffix_of(m),
519                            &mut HashSet::new(),
520                        ) {
521                            Some(r) => r,
522                            None => continue,
523                        }
524                    }
525                };
526                let pres = effective_prefixes(&supers, &prefixes, &t.id, &mut HashSet::new())
527                    .unwrap_or_else(|| vec![String::new()]);
528                let mut out: Vec<String> = Vec::new();
529                let mut served: Vec<(&str, String)> = Vec::new();
530                for r in raw {
531                    for pre in &pres {
532                        let path = join_paths(pre, &r.path);
533                        let e = format!("{} {path}", r.verb.as_str());
534                        if !out.contains(&e) {
535                            out.push(e);
536                            served.push((r.verb.as_str(), path));
537                        }
538                    }
539                }
540                if let Some(id) = ents.method(b, &fs.file, m)
541                    && !out.is_empty()
542                {
543                    stats.handlers += 1;
544                    stats.endpoints += out.len();
545                    b.set_prop(id, PROP_ENDPOINTS, out);
546                    let at = b.name_range(id).unwrap_or_default();
547                    for (verb, path) in served {
548                        let key = format!(
549                            "{}{}",
550                            b.key(id),
551                            Descriptor::Meta(format!("{verb} {path}"))
552                        );
553                        let e = b.entity_of_kind(&key, kind, &format!("{verb} {path}"));
554                        b.set_parent(e, Some(id));
555                        b.set_language(e, &LanguageId::new("java"));
556                        b.set_source(e, &fs.file, at, None);
557                        b.set_prop(e, "http.verb", verb);
558                        b.set_prop(e, "http.path", path.as_str());
559                        b.occurrence(
560                            &RelationKind::Other(PROP_ENDPOINTS.to_string()),
561                            id,
562                            e,
563                            Provenance::Frontend,
564                            at,
565                        );
566                    }
567                }
568            }
569        }
570    }
571}
572
573// ---- GWT RPC ----
574
575/// Interfaces that extend `RemoteService`, directly or through parsed interfaces.
576fn remote_services(parsed: &[Arc<FileFacts>], index: &TypeIndex) -> HashSet<String> {
577    let mut remote: HashSet<String> = HashSet::new();
578    let mut supers: Vec<(&str, Vec<&str>)> = Vec::new();
579    for fs in parsed {
580        for t in fs.types.iter().filter(|t| t.interface) {
581            if t.supertypes.iter().any(|s| s == "RemoteService") {
582                remote.insert(t.id.clone());
583            } else {
584                let resolved = t
585                    .supertypes
586                    .iter()
587                    .filter_map(|s| index.resolve(fs, s))
588                    .collect();
589                supers.push((&t.id, resolved));
590            }
591        }
592    }
593    loop {
594        let before = remote.len();
595        for (id, sups) in &supers {
596            if !remote.contains(*id) && sups.iter().any(|s| remote.contains(*s)) {
597                remote.insert((*id).to_string());
598            }
599        }
600        if remote.len() == before {
601            return remote;
602        }
603    }
604}
605
606/// The type hierarchy RPC resolution walks, over the parsed types.
607struct Hierarchy<'a> {
608    index: &'a TypeIndex<'a>,
609    /// type -> its direct subtypes
610    subs: HashMap<&'a str, Vec<&'a str>>,
611    /// type -> its direct supertypes
612    supers: HashMap<&'a str, Vec<&'a str>>,
613}
614
615impl<'a> Hierarchy<'a> {
616    fn new(parsed: &'a [Arc<FileFacts>], index: &'a TypeIndex<'a>) -> Self {
617        let mut subs: HashMap<&str, Vec<&str>> = HashMap::new();
618        let mut supers: HashMap<&str, Vec<&str>> = HashMap::new();
619        for fs in parsed {
620            for t in &fs.types {
621                for s in &t.supertypes {
622                    if let Some(target) = index.resolve(fs, s)
623                        && target != t.id
624                    {
625                        subs.entry(target).or_default().push(&t.id);
626                        supers.entry(&t.id).or_default().push(target);
627                    }
628                }
629            }
630        }
631        Hierarchy {
632            index,
633            subs,
634            supers,
635        }
636    }
637
638    /// Classes implementing `iface`, transitively.
639    fn implementations(&self, iface: &'a str) -> Vec<&'a str> {
640        let mut seen: HashSet<&str> = HashSet::new();
641        let mut todo: Vec<&str> = vec![iface];
642        let mut out = Vec::new();
643        while let Some(t) = todo.pop() {
644            if !seen.insert(t) {
645                continue;
646            }
647            if self.index.by_id.get(t).is_some_and(|r| !r.decl.interface) {
648                out.push(t);
649            }
650            todo.extend(self.subs.get(t).into_iter().flatten());
651        }
652        out
653    }
654
655    /// Classes with an unresolved supertype named like an interface that is
656    /// not in the project (another root, a library).
657    fn implementations_by_name(&self, parsed: &'a [Arc<FileFacts>], simple: &str) -> Vec<&'a str> {
658        let mut out = Vec::new();
659        for fs in parsed {
660            for t in fs.types.iter().filter(|t| !t.interface) {
661                if !t.supertypes.iter().any(|s| s == simple) {
662                    continue;
663                }
664                let resolved = self
665                    .supers
666                    .get(t.id.as_str())
667                    .into_iter()
668                    .flatten()
669                    .any(|s| {
670                        self.index
671                            .by_id
672                            .get(s)
673                            .is_some_and(|r| r.decl.name == simple)
674                    });
675                if !resolved {
676                    out.push(t.id.as_str());
677                }
678            }
679        }
680        out
681    }
682
683    /// The method `method(arity)` declared by the class or inherited from a
684    /// superclass (interface declarations do not count).
685    fn find_method(
686        &self,
687        b: &ModelBuilder,
688        ents: &Entities,
689        class: &'a str,
690        method: &str,
691        arity: usize,
692    ) -> Option<EntityId> {
693        let mut seen: HashSet<&str> = HashSet::new();
694        let mut todo: Vec<&str> = vec![class];
695        while let Some(c) = todo.pop() {
696            if !seen.insert(c) {
697                continue;
698            }
699            let Some(r) = self.index.by_id.get(c).filter(|r| !r.decl.interface) else {
700                continue;
701            };
702            if let Some(m) = r
703                .decl
704                .methods
705                .iter()
706                .find(|m| !m.constructor && m.name == method && m.arity == arity)
707            {
708                return ents.method(b, &r.file.file, m);
709            }
710            todo.extend(self.supers.get(c).into_iter().flatten());
711        }
712        None
713    }
714}
715
716/// The service a call talks to: its id when it is a project service, else the
717/// simple name; `maybe` when nothing says it exists.
718struct Service {
719    id: String,
720    in_project: bool,
721    maybe: bool,
722}
723
724fn service_of(
725    recv: &Receiver,
726    fs: &FileFacts,
727    index: &TypeIndex,
728    remote: &HashSet<String>,
729) -> Option<Service> {
730    match recv {
731        Receiver::Async(n) => match index.resolve(fs, n) {
732            Some(id) => id
733                .strip_suffix("Async")
734                .filter(|sync| remote.contains(*sync))
735                .map(|sync| Service {
736                    id: sync.to_string(),
737                    in_project: true,
738                    maybe: false,
739                }),
740            // `XAsync` from another root: keep `X`.
741            None => n.strip_suffix("Async").map(|x| Service {
742                id: x.to_string(),
743                in_project: false,
744                maybe: false,
745            }),
746        },
747        Receiver::Sync { name, strict } => match index.resolve(fs, name) {
748            Some(id) => remote.contains(id).then(|| Service {
749                id: id.to_string(),
750                in_project: true,
751                maybe: false,
752            }),
753            // Unknown `X`: plausible only if an `XAsync` type is parsed.
754            None => (!strict).then(|| Service {
755                id: name.clone(),
756                in_project: false,
757                maybe: !index.simple.contains_key(format!("{name}Async").as_str()),
758            }),
759        },
760    }
761}
762
763fn rpc(
764    b: &mut ModelBuilder,
765    ents: &Entities,
766    parsed: &[Arc<FileFacts>],
767    index: &TypeIndex,
768    stats: &mut JavaStats,
769) {
770    if parsed.iter().all(|f| {
771        f.types
772            .iter()
773            .all(|t| t.methods.iter().all(|m| m.rpc.is_empty()))
774    }) {
775        return;
776    }
777    let remote = remote_services(parsed, index);
778    let hier = Hierarchy::new(parsed, index);
779    let relation = rpc_relation();
780    let mut services_marked: HashSet<&str> = HashSet::new();
781    for fs in parsed {
782        for t in &fs.types {
783            for m in t.methods.iter().filter(|m| !m.rpc.is_empty()) {
784                let Some(caller) = ents.method(b, &fs.file, m) else {
785                    continue;
786                };
787                let mut calls: Vec<String> = Vec::new();
788                for call in &m.rpc {
789                    let Some(svc) = service_of(&call.recv, fs, index, &remote) else {
790                        continue;
791                    };
792                    let impls: Vec<&str> = match index.by_id.get(svc.id.as_str()) {
793                        Some(r) if svc.in_project => {
794                            if services_marked.insert(&r.decl.id)
795                                && let Some(e) = ents.type_of(b, &r.file.file, r.decl)
796                            {
797                                b.set_prop(e, PROP_RPC_SERVICE, true);
798                            }
799                            hier.implementations(&r.decl.id)
800                        }
801                        _ if svc.maybe => {
802                            stats.rpc_maybe += 1;
803                            continue;
804                        }
805                        _ => {
806                            let simple = svc.id.rsplit(['.', '$']).next().unwrap_or(&svc.id);
807                            hier.implementations_by_name(parsed, simple)
808                        }
809                    };
810                    stats.rpc_calls += 1;
811                    let label = format!(
812                        "{}#{}/{}",
813                        svc.id.replace('$', "."),
814                        call.method,
815                        call.arity
816                    );
817                    if !calls.contains(&label) {
818                        calls.push(label);
819                    }
820                    let arity = call.arity as usize;
821                    let mut targets: Vec<EntityId> = Vec::new();
822                    for c in impls {
823                        let t = arity
824                            .checked_sub(1)
825                            .and_then(|a| hier.find_method(b, ents, c, &call.method, a))
826                            .or_else(|| hier.find_method(b, ents, c, &call.method, arity));
827                        targets.extend(t);
828                    }
829                    targets.sort_by_key(|e| e.index());
830                    targets.dedup();
831                    if !targets.is_empty() {
832                        stats.rpc_linked += 1;
833                    }
834                    for to in targets {
835                        b.occurrence(&relation, caller, to, Provenance::Frontend, call.site);
836                    }
837                }
838                if !calls.is_empty() {
839                    b.set_prop(caller, PROP_RPC_CALLS, calls);
840                }
841            }
842        }
843    }
844}
845
846fn run(b: &mut ModelBuilder, parsed: &[Arc<FileFacts>], generated: &[Arc<FileFacts>]) -> JavaStats {
847    let mut stats = JavaStats {
848        files: parsed.len(),
849        generated_files: generated.len(),
850        ..JavaStats::default()
851    };
852    let ents = Entities::new(b);
853    let index = TypeIndex::new(parsed);
854    http(b, &ents, parsed, generated, &index, &mut stats);
855    rpc(b, &ents, parsed, &index, &mut stats);
856    stats
857}