1use std::collections::{HashMap, HashSet};
51use std::path::Path;
52
53use anyhow::Context;
54use model_core::{
55 Descriptor, EntityId, EntityKind, KindId, LanguageId, ModelBuilder, Provenance, RelationKind,
56};
57use rayon::prelude::*;
58
59mod parse;
60mod rpc;
61
62use parse::{FileFacts, MethodDecl, Pos, Route, TypeDecl, join_paths, parse_source};
63use rpc::Receiver;
64
65#[cfg(test)]
66mod tests;
67
68pub const PROP_ENDPOINTS: &str = "http.endpoints";
70pub const HTTP_ENDPOINT: &str = "http.endpoint";
73
74pub fn declare_kinds(b: &mut ModelBuilder) -> KindId {
77 let id = b.define_kind(
78 HTTP_ENDPOINT,
79 EntityKind::Variable,
80 model_traits::mask(&["Named"]),
81 None,
82 );
83 b.set_kind_concept(id, Some("HttpEndpoint"), Some("httpEndpoints"));
84 id
85}
86pub const PROP_RPC_SERVICE: &str = "rpc.service";
88pub const PROP_RPC_CALLS: &str = "rpc.calls";
90pub const RPC_RELATION: &str = "gwt-rpc";
93
94pub fn rpc_relation() -> RelationKind {
96 RelationKind::Other(RPC_RELATION.to_string())
97}
98
99#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
101pub struct JavaStats {
102 pub files: usize,
104 pub generated_files: usize,
106 pub handlers: usize,
108 pub endpoints: usize,
110 pub rpc_calls: usize,
112 pub rpc_linked: usize,
114 pub rpc_maybe: usize,
117 pub unresolved_api: usize,
120}
121
122fn eligible(rel: &str) -> bool {
124 rel.ends_with(".java") && !rel.contains("src/test/")
125}
126
127fn in_generated(rel: &Path) -> bool {
129 let comps: Vec<_> = rel.components().map(|c| c.as_os_str()).collect();
130 comps.windows(2).any(|w| {
131 (w[0] == "target" && w[1] == "generated-sources")
132 || (w[0] == "build" && w[1] == "generated")
133 })
134}
135
136fn generated_files(root: &Path) -> Vec<String> {
139 let walk_root = root.to_path_buf();
140 let walker = ignore::WalkBuilder::new(root)
141 .standard_filters(false)
142 .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 in_generated(rel) || n != "src"
153 })
154 .build();
155 let mut files: Vec<String> = walker
156 .flatten()
157 .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
158 .filter_map(|e| {
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 .collect();
164 files.sort();
165 files
166}
167
168pub 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 };
176 let read = |rel: &String| -> anyhow::Result<(String, String)> {
177 let bytes = std::fs::read(root.join(rel)).with_context(|| format!("reading {rel}"))?;
178 Ok((rel.clone(), String::from_utf8_lossy(&bytes).into_owned()))
179 };
180 let main: Vec<String> = model_treesitter::source_files(root, &opts)?
181 .into_iter()
182 .filter(|f| eligible(f) && !in_generated(Path::new(f)))
185 .collect();
186 let main = main
187 .par_iter()
188 .map(read)
189 .collect::<anyhow::Result<Vec<_>>>()?;
190 let gen_paths = generated_files(root);
191 let generated: Vec<(String, String)> =
193 gen_paths.par_iter().filter_map(|p| read(p).ok()).collect();
194 let main: Vec<(&str, &str)> = main.iter().map(|(a, b)| (a.as_str(), b.as_str())).collect();
195 let generated: Vec<(&str, &str)> = generated
196 .iter()
197 .map(|(a, b)| (a.as_str(), b.as_str()))
198 .collect();
199 enrich_sources(b, &main, &generated)
200}
201
202pub fn enrich_sources(
206 b: &mut ModelBuilder,
207 sources: &[(&str, &str)],
208 generated: &[(&str, &str)],
209) -> anyhow::Result<JavaStats> {
210 let mut kept: Vec<&(&str, &str)> = sources.iter().filter(|(rel, _)| eligible(rel)).collect();
211 kept.sort_by(|a, b| a.0.split('/').cmp(b.0.split('/')));
212 let parsed: Vec<FileFacts> = kept
213 .par_iter()
214 .map(|(rel, src)| parse_source(rel, src))
215 .collect::<anyhow::Result<_>>()?;
216 let mut gen_sorted: Vec<&(&str, &str)> = generated
217 .iter()
218 .filter(|(rel, _)| rel.ends_with(".java"))
219 .collect();
220 gen_sorted.sort_by(|a, b| a.0.split('/').cmp(b.0.split('/')));
221 let generated: Vec<FileFacts> = gen_sorted
222 .par_iter()
223 .filter_map(|(rel, src)| parse_source(rel, src).ok())
224 .collect();
225 Ok(run(b, &parsed, &generated))
226}
227
228#[derive(Clone, Copy)]
232struct TypeRef<'a> {
233 file: &'a FileFacts,
234 decl: &'a TypeDecl,
235}
236
237struct TypeIndex<'a> {
239 dotted: HashMap<String, &'a str>,
241 simple: HashMap<&'a str, Vec<&'a str>>,
243 by_id: HashMap<&'a str, TypeRef<'a>>,
244}
245
246impl<'a> TypeIndex<'a> {
247 fn new(files: &'a [FileFacts]) -> Self {
248 let mut idx = TypeIndex {
249 dotted: HashMap::new(),
250 simple: HashMap::new(),
251 by_id: HashMap::new(),
252 };
253 for file in files {
254 for decl in &file.types {
255 idx.dotted.insert(decl.id.replace('$', "."), &decl.id);
256 idx.simple.entry(&decl.name).or_default().push(&decl.id);
257 idx.by_id.entry(&decl.id).or_insert(TypeRef { file, decl });
258 }
259 }
260 idx
261 }
262
263 fn resolve(&self, fs: &FileFacts, name: &str) -> Option<&'a str> {
264 let suffix = format!(".{name}");
265 let mut explicit = false;
266 for imp in fs.imports.iter().filter(|i| i.ends_with(&suffix)) {
267 explicit = true;
268 if let Some(id) = self.dotted.get(imp) {
269 return Some(id);
270 }
271 }
272 if explicit {
273 return None;
275 }
276 match &fs.package {
277 Some(p) => {
278 if let Some(id) = self.dotted.get(&format!("{p}{suffix}")) {
279 return Some(id);
280 }
281 }
282 None => {
283 if let Some(id) = self.dotted.get(name) {
284 return Some(id);
285 }
286 }
287 }
288 for imp in fs.imports.iter().filter_map(|i| i.strip_suffix(".*")) {
289 if let Some(id) = self.dotted.get(&format!("{imp}{suffix}")) {
290 return Some(id);
291 }
292 }
293 match self.simple.get(name).map(Vec::as_slice) {
294 Some([only]) => Some(only),
295 _ => None,
296 }
297 }
298}
299
300struct Entities {
304 by_file: HashMap<String, HashMap<Pos, Vec<EntityId>>>,
305}
306
307impl Entities {
308 fn new(b: &ModelBuilder) -> Self {
309 let mut by_file: HashMap<String, HashMap<Pos, Vec<EntityId>>> = HashMap::new();
310 for id in b.ids() {
311 if let (Some(file), Some(r)) = (b.file(id), b.name_range(id))
312 && file.ends_with(".java")
313 {
314 by_file
315 .entry(file.to_string())
316 .or_default()
317 .entry((r.start_line, r.start_col))
318 .or_default()
319 .push(id);
320 }
321 }
322 Entities { by_file }
323 }
324
325 fn find(
326 &self,
327 b: &ModelBuilder,
328 file: &str,
329 pos: Pos,
330 keep: fn(&ModelBuilder, EntityId) -> bool,
331 ) -> Option<EntityId> {
332 self.by_file
333 .get(file)?
334 .get(&pos)?
335 .iter()
336 .copied()
337 .find(|&id| keep(b, id))
338 }
339
340 fn method(&self, b: &ModelBuilder, file: &str, m: &MethodDecl) -> Option<EntityId> {
341 self.find(b, file, m.name_pos, |b, id| b.kind(id).is_callable())
342 }
343
344 fn type_of(&self, b: &ModelBuilder, file: &str, t: &TypeDecl) -> Option<EntityId> {
345 self.find(b, file, t.name_pos, |b, id| b.kind(id).is_type())
346 }
347}
348
349type Supers = HashMap<String, Vec<String>>;
352type RouteTable = HashMap<String, Vec<Route>>;
353
354fn inherited_routes<'a>(
356 supers: &Supers,
357 routes: &'a RouteTable,
358 tid: &str,
359 suffix: &str,
360 seen: &mut HashSet<String>,
361) -> Option<&'a Vec<Route>> {
362 for sup in supers.get(tid)? {
363 if !seen.insert(sup.clone()) {
364 continue;
365 }
366 if let Some(r) = routes.get(&format!("{sup}#{suffix}")) {
367 return Some(r);
368 }
369 if let Some(r) = inherited_routes(supers, routes, sup, suffix, seen) {
370 return Some(r);
371 }
372 }
373 None
374}
375
376fn effective_prefixes(
378 supers: &Supers,
379 prefixes: &HashMap<String, Vec<String>>,
380 tid: &str,
381 seen: &mut HashSet<String>,
382) -> Option<Vec<String>> {
383 if let Some(p) = prefixes.get(tid) {
384 return Some(p.clone());
385 }
386 for sup in supers.get(tid)? {
387 if seen.insert(sup.clone())
388 && let Some(p) = effective_prefixes(supers, prefixes, sup, seen)
389 {
390 return Some(p);
391 }
392 }
393 None
394}
395
396fn suffix_of(m: &MethodDecl) -> String {
397 format!("{}({})", m.name, m.arity)
398}
399
400fn http(
402 b: &mut ModelBuilder,
403 ents: &Entities,
404 parsed: &[FileFacts],
405 generated: &[FileFacts],
406 index: &TypeIndex,
407 stats: &mut JavaStats,
408) {
409 let kind = declare_kinds(b);
410 let gen_index = TypeIndex::new(generated);
411 let mut supers: Supers = HashMap::new();
412 let mut routes: RouteTable = HashMap::new();
413 let mut prefixes: HashMap<String, Vec<String>> = HashMap::new();
414 for (is_parsed, fs) in parsed
416 .iter()
417 .map(|f| (true, f))
418 .chain(generated.iter().map(|f| (false, f)))
419 {
420 for t in &fs.types {
421 if !t.supertypes.is_empty() {
422 let mut resolved = Vec::new();
423 let mut missing_api = false;
424 for sup in &t.supertypes {
425 match index
426 .resolve(fs, sup)
427 .or_else(|| gen_index.resolve(fs, sup))
428 {
429 Some(id) => resolved.push(id.to_string()),
430 None => missing_api |= sup.ends_with("Api"),
431 }
432 }
433 if is_parsed && !t.interface && missing_api {
434 stats.unresolved_api += 1;
435 }
436 supers.entry(t.id.clone()).or_insert(resolved);
437 }
438 if let Some(p) = &t.prefixes {
439 prefixes.entry(t.id.clone()).or_insert_with(|| p.clone());
440 }
441 for m in t.methods.iter().filter(|m| !m.routes.is_empty()) {
442 routes
443 .entry(format!("{}#{}", t.id, suffix_of(m)))
444 .or_insert_with(|| m.routes.clone());
445 }
446 }
447 }
448 for fs in parsed {
449 for t in &fs.types {
450 for m in t.methods.iter().filter(|m| !m.constructor) {
451 let own = routes.get(&format!("{}#{}", t.id, suffix_of(m)));
452 let raw = match own {
453 Some(r) => r,
454 None => {
455 match inherited_routes(
456 &supers,
457 &routes,
458 &t.id,
459 &suffix_of(m),
460 &mut HashSet::new(),
461 ) {
462 Some(r) => r,
463 None => continue,
464 }
465 }
466 };
467 let pres = effective_prefixes(&supers, &prefixes, &t.id, &mut HashSet::new())
468 .unwrap_or_else(|| vec![String::new()]);
469 let mut out: Vec<String> = Vec::new();
470 let mut served: Vec<(&str, String)> = Vec::new();
471 for r in raw {
472 for pre in &pres {
473 let path = join_paths(pre, &r.path);
474 let e = format!("{} {path}", r.verb.as_str());
475 if !out.contains(&e) {
476 out.push(e);
477 served.push((r.verb.as_str(), path));
478 }
479 }
480 }
481 if let Some(id) = ents.method(b, &fs.file, m)
482 && !out.is_empty()
483 {
484 stats.handlers += 1;
485 stats.endpoints += out.len();
486 b.set_prop(id, PROP_ENDPOINTS, out);
487 let at = b.name_range(id).unwrap_or_default();
488 for (verb, path) in served {
489 let key = format!(
490 "{}{}",
491 b.key(id),
492 Descriptor::Meta(format!("{verb} {path}"))
493 );
494 let e = b.entity_of_kind(&key, kind, &format!("{verb} {path}"));
495 b.set_parent(e, Some(id));
496 b.set_language(e, &LanguageId::new("java"));
497 b.set_source(e, &fs.file, at, None);
498 b.set_prop(e, "http.verb", verb);
499 b.set_prop(e, "http.path", path.as_str());
500 b.occurrence(
501 &RelationKind::Other(PROP_ENDPOINTS.to_string()),
502 id,
503 e,
504 Provenance::Frontend,
505 at,
506 );
507 }
508 }
509 }
510 }
511 }
512}
513
514fn remote_services(parsed: &[FileFacts], index: &TypeIndex) -> HashSet<String> {
518 let mut remote: HashSet<String> = HashSet::new();
519 let mut supers: Vec<(&str, Vec<&str>)> = Vec::new();
520 for fs in parsed {
521 for t in fs.types.iter().filter(|t| t.interface) {
522 if t.supertypes.iter().any(|s| s == "RemoteService") {
523 remote.insert(t.id.clone());
524 } else {
525 let resolved = t
526 .supertypes
527 .iter()
528 .filter_map(|s| index.resolve(fs, s))
529 .collect();
530 supers.push((&t.id, resolved));
531 }
532 }
533 }
534 loop {
535 let before = remote.len();
536 for (id, sups) in &supers {
537 if !remote.contains(*id) && sups.iter().any(|s| remote.contains(*s)) {
538 remote.insert((*id).to_string());
539 }
540 }
541 if remote.len() == before {
542 return remote;
543 }
544 }
545}
546
547struct Hierarchy<'a> {
549 index: &'a TypeIndex<'a>,
550 subs: HashMap<&'a str, Vec<&'a str>>,
552 supers: HashMap<&'a str, Vec<&'a str>>,
554}
555
556impl<'a> Hierarchy<'a> {
557 fn new(parsed: &'a [FileFacts], index: &'a TypeIndex<'a>) -> Self {
558 let mut subs: HashMap<&str, Vec<&str>> = HashMap::new();
559 let mut supers: HashMap<&str, Vec<&str>> = HashMap::new();
560 for fs in parsed {
561 for t in &fs.types {
562 for s in &t.supertypes {
563 if let Some(target) = index.resolve(fs, s)
564 && target != t.id
565 {
566 subs.entry(target).or_default().push(&t.id);
567 supers.entry(&t.id).or_default().push(target);
568 }
569 }
570 }
571 }
572 Hierarchy {
573 index,
574 subs,
575 supers,
576 }
577 }
578
579 fn implementations(&self, iface: &'a str) -> Vec<&'a str> {
581 let mut seen: HashSet<&str> = HashSet::new();
582 let mut todo: Vec<&str> = vec![iface];
583 let mut out = Vec::new();
584 while let Some(t) = todo.pop() {
585 if !seen.insert(t) {
586 continue;
587 }
588 if self.index.by_id.get(t).is_some_and(|r| !r.decl.interface) {
589 out.push(t);
590 }
591 todo.extend(self.subs.get(t).into_iter().flatten());
592 }
593 out
594 }
595
596 fn implementations_by_name(&self, parsed: &'a [FileFacts], simple: &str) -> Vec<&'a str> {
599 let mut out = Vec::new();
600 for fs in parsed {
601 for t in fs.types.iter().filter(|t| !t.interface) {
602 if !t.supertypes.iter().any(|s| s == simple) {
603 continue;
604 }
605 let resolved = self
606 .supers
607 .get(t.id.as_str())
608 .into_iter()
609 .flatten()
610 .any(|s| {
611 self.index
612 .by_id
613 .get(s)
614 .is_some_and(|r| r.decl.name == simple)
615 });
616 if !resolved {
617 out.push(t.id.as_str());
618 }
619 }
620 }
621 out
622 }
623
624 fn find_method(
627 &self,
628 b: &ModelBuilder,
629 ents: &Entities,
630 class: &'a str,
631 method: &str,
632 arity: usize,
633 ) -> Option<EntityId> {
634 let mut seen: HashSet<&str> = HashSet::new();
635 let mut todo: Vec<&str> = vec![class];
636 while let Some(c) = todo.pop() {
637 if !seen.insert(c) {
638 continue;
639 }
640 let Some(r) = self.index.by_id.get(c).filter(|r| !r.decl.interface) else {
641 continue;
642 };
643 if let Some(m) = r
644 .decl
645 .methods
646 .iter()
647 .find(|m| !m.constructor && m.name == method && m.arity == arity)
648 {
649 return ents.method(b, &r.file.file, m);
650 }
651 todo.extend(self.supers.get(c).into_iter().flatten());
652 }
653 None
654 }
655}
656
657struct Service {
660 id: String,
661 in_project: bool,
662 maybe: bool,
663}
664
665fn service_of(
666 recv: &Receiver,
667 fs: &FileFacts,
668 index: &TypeIndex,
669 remote: &HashSet<String>,
670) -> Option<Service> {
671 match recv {
672 Receiver::Async(n) => match index.resolve(fs, n) {
673 Some(id) => id
674 .strip_suffix("Async")
675 .filter(|sync| remote.contains(*sync))
676 .map(|sync| Service {
677 id: sync.to_string(),
678 in_project: true,
679 maybe: false,
680 }),
681 None => n.strip_suffix("Async").map(|x| Service {
683 id: x.to_string(),
684 in_project: false,
685 maybe: false,
686 }),
687 },
688 Receiver::Sync { name, strict } => match index.resolve(fs, name) {
689 Some(id) => remote.contains(id).then(|| Service {
690 id: id.to_string(),
691 in_project: true,
692 maybe: false,
693 }),
694 None => (!strict).then(|| Service {
696 id: name.clone(),
697 in_project: false,
698 maybe: !index.simple.contains_key(format!("{name}Async").as_str()),
699 }),
700 },
701 }
702}
703
704fn rpc(
705 b: &mut ModelBuilder,
706 ents: &Entities,
707 parsed: &[FileFacts],
708 index: &TypeIndex,
709 stats: &mut JavaStats,
710) {
711 if parsed.iter().all(|f| {
712 f.types
713 .iter()
714 .all(|t| t.methods.iter().all(|m| m.rpc.is_empty()))
715 }) {
716 return;
717 }
718 let remote = remote_services(parsed, index);
719 let hier = Hierarchy::new(parsed, index);
720 let relation = rpc_relation();
721 let mut services_marked: HashSet<&str> = HashSet::new();
722 for fs in parsed {
723 for t in &fs.types {
724 for m in t.methods.iter().filter(|m| !m.rpc.is_empty()) {
725 let Some(caller) = ents.method(b, &fs.file, m) else {
726 continue;
727 };
728 let mut calls: Vec<String> = Vec::new();
729 for call in &m.rpc {
730 let Some(svc) = service_of(&call.recv, fs, index, &remote) else {
731 continue;
732 };
733 let impls: Vec<&str> = match index.by_id.get(svc.id.as_str()) {
734 Some(r) if svc.in_project => {
735 if services_marked.insert(&r.decl.id)
736 && let Some(e) = ents.type_of(b, &r.file.file, r.decl)
737 {
738 b.set_prop(e, PROP_RPC_SERVICE, true);
739 }
740 hier.implementations(&r.decl.id)
741 }
742 _ if svc.maybe => {
743 stats.rpc_maybe += 1;
744 continue;
745 }
746 _ => {
747 let simple = svc.id.rsplit(['.', '$']).next().unwrap_or(&svc.id);
748 hier.implementations_by_name(parsed, simple)
749 }
750 };
751 stats.rpc_calls += 1;
752 let label = format!(
753 "{}#{}/{}",
754 svc.id.replace('$', "."),
755 call.method,
756 call.arity
757 );
758 if !calls.contains(&label) {
759 calls.push(label);
760 }
761 let arity = call.arity as usize;
762 let mut targets: Vec<EntityId> = Vec::new();
763 for c in impls {
764 let t = arity
765 .checked_sub(1)
766 .and_then(|a| hier.find_method(b, ents, c, &call.method, a))
767 .or_else(|| hier.find_method(b, ents, c, &call.method, arity));
768 targets.extend(t);
769 }
770 targets.sort_by_key(|e| e.index());
771 targets.dedup();
772 if !targets.is_empty() {
773 stats.rpc_linked += 1;
774 }
775 for to in targets {
776 b.occurrence(&relation, caller, to, Provenance::Frontend, call.site);
777 }
778 }
779 if !calls.is_empty() {
780 b.set_prop(caller, PROP_RPC_CALLS, calls);
781 }
782 }
783 }
784 }
785}
786
787fn run(b: &mut ModelBuilder, parsed: &[FileFacts], generated: &[FileFacts]) -> JavaStats {
788 let mut stats = JavaStats {
789 files: parsed.len(),
790 generated_files: generated.len(),
791 ..JavaStats::default()
792 };
793 let ents = Entities::new(b);
794 let index = TypeIndex::new(parsed);
795 http(b, &ents, parsed, generated, &index, &mut stats);
796 rpc(b, &ents, parsed, &index, &mut stats);
797 stats
798}