1use std::path::{Path, PathBuf};
8use std::time::{Duration, Instant};
9
10use bitloom_builder::{ElaborateSession, GroundType, HwCaptureRef, Span};
11use bitloom_hir::{Diagnostic, FrozenHir};
12
13mod discover;
14pub use discover::{DiscoveredDesignRoot, discover_design_roots, discover_design_roots_under};
15
16pub const MVP_MAX_MODULES: usize = 8;
18
19pub const MVP_INTERACTIVE_BUDGET: Duration = Duration::from_secs(2);
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum AnalysisMode {
25 FullElaborate,
27 Shallow,
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum DesignFixture {
34 OkCounter,
36 FailHwCapture,
38 Oversized,
40 SlowForTimeout,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct HwSymbol {
46 pub name: String,
47 pub kind: String,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct MappedDiagnostic {
52 pub code: String,
53 pub message: String,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct AnalyzeResult {
58 pub diagnostics: Vec<MappedDiagnostic>,
59 pub symbols: Vec<HwSymbol>,
60 pub called_finish: bool,
62 pub timed_out: bool,
63 pub oversized: bool,
64 pub mode: AnalysisMode,
65}
66
67fn map_diag(d: &Diagnostic) -> MappedDiagnostic {
68 MappedDiagnostic {
69 code: d.code.clone(),
70 message: format!("{}: {} ({})", d.code, d.en, d.zh),
71 }
72}
73
74fn symbols_from_hir(hir: &FrozenHir) -> Vec<HwSymbol> {
75 let mut out = Vec::new();
76 for m in &hir.circuit().modules {
77 out.push(HwSymbol {
78 name: m.name.clone(),
79 kind: "module".into(),
80 });
81 for p in &m.ports {
82 out.push(HwSymbol {
83 name: format!("{}.{}", m.name, p.name),
84 kind: "port".into(),
85 });
86 }
87 }
88 out
89}
90
91fn build_ok_counter() -> ElaborateSession {
92 let mut s = ElaborateSession::new("Fr99OkCounter");
93 s.begin_module("Fr99OkCounter", Span::default());
94 s.add_input("clk", GroundType::Clock, Span::default());
95 s.add_input("rst", GroundType::Reset, Span::default());
96 s.add_output("q", GroundType::UInt { width: 8 }, Span::default());
97 s.declare_reg("count", GroundType::UInt { width: 8 }, Span::default());
98 s.begin_combinational(Span::default());
99 s.assign_net("q", "count", Span::default());
100 s.end_process();
101 s.begin_sequential(Span::default());
102 s.assign_reg_d_inc("count", Span::default());
103 s.end_process();
104 s.end_module();
105 s
106}
107
108fn build_fail_hw_capture() -> ElaborateSession {
109 let mut s = ElaborateSession::new("Fr99FailCapture");
110 s.begin_module("Fr99FailCapture", Span::default());
111 s.add_input("clk", GroundType::Clock, Span::default());
112 s.add_input("rst", GroundType::Reset, Span::default());
113 s.add_output("y", GroundType::UInt { width: 8 }, Span::default());
114 s.declare_wire("w", GroundType::UInt { width: 8 }, Span::default());
115 s.assert_no_hw_capture(&[HwCaptureRef::wire("w")], Span::default());
116 s.declare_mem_with_init_fn("rom", 4, 8, |i| i as u64, Span::default());
117 s.begin_combinational(Span::default());
118 s.assign_net("y", "rom", Span::default());
119 s.end_process();
120 s.end_module();
121 s
122}
123
124fn build_oversized() -> ElaborateSession {
125 let mut s = ElaborateSession::new("Fr99Oversized");
126 for i in 0..=MVP_MAX_MODULES {
127 let name = format!("Mod{i}");
128 s.begin_module(&name, Span::default());
129 s.add_input("clk", GroundType::Clock, Span::default());
130 s.add_output("y", GroundType::Bool, Span::default());
131 s.begin_combinational(Span::default());
132 s.assign_lit("y", 0, Span::default());
133 s.end_process();
134 s.end_module();
135 }
136 s
137}
138
139pub fn analyze(mode: AnalysisMode, fixture: DesignFixture, timeout: Duration) -> AnalyzeResult {
144 let started = Instant::now();
145
146 if matches!(fixture, DesignFixture::SlowForTimeout) {
147 if mode == AnalysisMode::Shallow {
148 return AnalyzeResult {
149 diagnostics: vec![],
150 symbols: vec![],
151 called_finish: false,
152 timed_out: false,
153 oversized: false,
154 mode,
155 };
156 }
157 std::thread::sleep(timeout.saturating_add(Duration::from_millis(50)));
159 if started.elapsed() > timeout {
160 return AnalyzeResult {
161 diagnostics: vec![MappedDiagnostic {
162 code: "bitloom-lsp.timeout".into(),
163 message: format!(
164 "bitloom-lsp.timeout: full-design elaborate exceeded interactive budget ({timeout:?}); cold start may be excluded per NFR14 P3"
165 ),
166 }],
167 symbols: vec![],
168 called_finish: false,
169 timed_out: true,
170 oversized: false,
171 mode,
172 };
173 }
174 }
175
176 let session = match fixture {
177 DesignFixture::OkCounter => build_ok_counter(),
178 DesignFixture::FailHwCapture => build_fail_hw_capture(),
179 DesignFixture::Oversized => build_oversized(),
180 DesignFixture::SlowForTimeout => build_ok_counter(),
181 };
182
183 let mods = match fixture {
185 DesignFixture::Oversized => MVP_MAX_MODULES + 1,
186 DesignFixture::OkCounter | DesignFixture::FailHwCapture | DesignFixture::SlowForTimeout => {
187 1
188 }
189 };
190 if mods > MVP_MAX_MODULES {
191 return AnalyzeResult {
192 diagnostics: vec![MappedDiagnostic {
193 code: "bitloom-lsp.oversized".into(),
194 message: format!(
195 "bitloom-lsp.oversized: design has {mods} modules; MVP ceiling is {MVP_MAX_MODULES} (NFR14 P4) — refusing to pretend full elaborate succeeded"
196 ),
197 }],
198 symbols: vec![],
199 called_finish: false,
200 timed_out: false,
201 oversized: true,
202 mode,
203 };
204 }
205
206 match mode {
207 AnalysisMode::Shallow => AnalyzeResult {
208 diagnostics: vec![],
209 symbols: vec![],
210 called_finish: false,
211 timed_out: false,
212 oversized: false,
213 mode,
214 },
215 AnalysisMode::FullElaborate => {
216 if started.elapsed() > timeout {
217 return AnalyzeResult {
218 diagnostics: vec![MappedDiagnostic {
219 code: "bitloom-lsp.timeout".into(),
220 message: format!(
221 "bitloom-lsp.timeout: full-design elaborate exceeded interactive budget ({timeout:?})"
222 ),
223 }],
224 symbols: vec![],
225 called_finish: false,
226 timed_out: true,
227 oversized: false,
228 mode,
229 };
230 }
231 match session.finish() {
232 Ok(hir) => AnalyzeResult {
233 diagnostics: vec![],
234 symbols: symbols_from_hir(&hir),
235 called_finish: true,
236 timed_out: false,
237 oversized: false,
238 mode,
239 },
240 Err(diags) => AnalyzeResult {
241 diagnostics: diags.0.iter().map(map_diag).collect(),
242 symbols: vec![],
243 called_finish: true,
244 timed_out: false,
245 oversized: false,
246 mode,
247 },
248 }
249 }
250 }
251}
252
253pub fn analyze_on_did_save() -> AnalyzeResult {
256 analyze(
257 AnalysisMode::FullElaborate,
258 DesignFixture::OkCounter,
259 MVP_INTERACTIVE_BUDGET,
260 )
261}
262
263fn session_for_discovered_root_id(root_id: &str) -> Option<(ElaborateSession, usize)> {
268 match root_id {
269 "Fr113OkCounter" => Some((build_fr113_ok_counter(), 1)),
270 "Fr113FailHwCapture" => Some((build_fr113_fail_hw_capture(), 1)),
271 "Fr113Oversized" => Some((build_oversized(), MVP_MAX_MODULES + 1)),
272 "Fr118OkCounter" => Some((build_fr118_ok_counter(), 1)),
273 "Fr118FailHwCapture" => Some((build_fr118_fail_hw_capture(), 1)),
274 _ => None,
275 }
276}
277
278fn build_fr113_ok_counter() -> ElaborateSession {
279 let mut s = ElaborateSession::new("Fr113OkCounter");
280 s.begin_module("Fr113OkCounter", Span::default());
281 s.add_input("clk", GroundType::Clock, Span::default());
282 s.add_input("rst", GroundType::Reset, Span::default());
283 s.add_output("q", GroundType::UInt { width: 8 }, Span::default());
284 s.declare_reg("count", GroundType::UInt { width: 8 }, Span::default());
285 s.begin_combinational(Span::default());
286 s.assign_net("q", "count", Span::default());
287 s.end_process();
288 s.begin_sequential(Span::default());
289 s.assign_reg_d_inc("count", Span::default());
290 s.end_process();
291 s.end_module();
292 s
293}
294
295fn build_fr113_fail_hw_capture() -> ElaborateSession {
296 let mut s = ElaborateSession::new("Fr113FailCapture");
297 s.begin_module("Fr113FailCapture", Span::default());
298 s.add_input("clk", GroundType::Clock, Span::default());
299 s.add_input("rst", GroundType::Reset, Span::default());
300 s.add_output("y", GroundType::UInt { width: 8 }, Span::default());
301 s.declare_wire("w", GroundType::UInt { width: 8 }, Span::default());
302 s.assert_no_hw_capture(&[HwCaptureRef::wire("w")], Span::default());
303 s.declare_mem_with_init_fn("rom", 4, 8, |i| i as u64, Span::default());
304 s.begin_combinational(Span::default());
305 s.assign_net("y", "rom", Span::default());
306 s.end_process();
307 s.end_module();
308 s
309}
310
311fn build_fr118_ok_counter() -> ElaborateSession {
312 let mut s = ElaborateSession::new("Fr118OkCounter");
313 s.begin_module("Fr118OkCounter", Span::default());
314 s.add_input("clk", GroundType::Clock, Span::default());
315 s.add_input("rst", GroundType::Reset, Span::default());
316 s.add_output("q", GroundType::UInt { width: 8 }, Span::default());
317 s.declare_reg("count", GroundType::UInt { width: 8 }, Span::default());
318 s.begin_combinational(Span::default());
319 s.assign_net("q", "count", Span::default());
320 s.end_process();
321 s.begin_sequential(Span::default());
322 s.assign_reg_d_inc("count", Span::default());
323 s.end_process();
324 s.end_module();
325 s
326}
327
328fn build_fr118_fail_hw_capture() -> ElaborateSession {
329 let mut s = ElaborateSession::new("Fr118FailCapture");
330 s.begin_module("Fr118FailCapture", Span::default());
331 s.add_input("clk", GroundType::Clock, Span::default());
332 s.add_input("rst", GroundType::Reset, Span::default());
333 s.add_output("y", GroundType::UInt { width: 8 }, Span::default());
334 s.declare_wire("w", GroundType::UInt { width: 8 }, Span::default());
335 s.assert_no_hw_capture(&[HwCaptureRef::wire("w")], Span::default());
336 s.declare_mem_with_init_fn("rom", 4, 8, |i| i as u64, Span::default());
337 s.begin_combinational(Span::default());
338 s.assign_net("y", "rom", Span::default());
339 s.end_process();
340 s.end_module();
341 s
342}
343
344pub fn analyze_discovered_root(
349 mode: AnalysisMode,
350 root: &DiscoveredDesignRoot,
351 timeout: Duration,
352) -> AnalyzeResult {
353 let started = Instant::now();
354 let Some((session, mods)) = session_for_discovered_root_id(&root.root_id) else {
355 return AnalyzeResult {
356 diagnostics: vec![MappedDiagnostic {
357 code: "bitloom-lsp.unknown-design-root".into(),
358 message: format!(
359 "bitloom-lsp.unknown-design-root: package `{}` root_id `{}` is not a registered FR113/FR118 elaborate entry",
360 root.package_name, root.root_id
361 ),
362 }],
363 symbols: vec![],
364 called_finish: false,
365 timed_out: false,
366 oversized: false,
367 mode,
368 };
369 };
370
371 if mods > MVP_MAX_MODULES {
372 return AnalyzeResult {
373 diagnostics: vec![MappedDiagnostic {
374 code: "bitloom-lsp.oversized".into(),
375 message: format!(
376 "bitloom-lsp.oversized: discovered root `{}` has {mods} modules; MVP ceiling is {MVP_MAX_MODULES} (NFR14 P4)",
377 root.root_id
378 ),
379 }],
380 symbols: vec![],
381 called_finish: false,
382 timed_out: false,
383 oversized: true,
384 mode,
385 };
386 }
387
388 match mode {
389 AnalysisMode::Shallow => AnalyzeResult {
390 diagnostics: vec![],
391 symbols: vec![],
392 called_finish: false,
393 timed_out: false,
394 oversized: false,
395 mode,
396 },
397 AnalysisMode::FullElaborate => {
398 if started.elapsed() > timeout {
399 return AnalyzeResult {
400 diagnostics: vec![MappedDiagnostic {
401 code: "bitloom-lsp.timeout".into(),
402 message: format!(
403 "bitloom-lsp.timeout: discovered-root elaborate exceeded interactive budget ({timeout:?})"
404 ),
405 }],
406 symbols: vec![],
407 called_finish: false,
408 timed_out: true,
409 oversized: false,
410 mode,
411 };
412 }
413 match session.finish() {
414 Ok(hir) => AnalyzeResult {
415 diagnostics: vec![],
416 symbols: symbols_from_hir(&hir),
417 called_finish: true,
418 timed_out: false,
419 oversized: false,
420 mode,
421 },
422 Err(diags) => AnalyzeResult {
423 diagnostics: diags.0.iter().map(map_diag).collect(),
424 symbols: vec![],
425 called_finish: true,
426 timed_out: false,
427 oversized: false,
428 mode,
429 },
430 }
431 }
432 }
433}
434
435pub fn analyze_workspace_design_roots(
439 mode: AnalysisMode,
440 workspace: impl AsRef<Path>,
441 timeout: Duration,
442) -> AnalyzeResult {
443 let workspace = workspace.as_ref();
444 match discover_design_roots(workspace) {
445 Ok(roots) if roots.is_empty() => AnalyzeResult {
446 diagnostics: vec![MappedDiagnostic {
447 code: "bitloom-lsp.no-design-roots".into(),
448 message: format!(
449 "bitloom-lsp.no-design-roots: no metadata `design_roots` and no `#[bitloom::top]` syn-scan hits under {} (FR113/FR118); DesignFixture-only ≠ deepen",
450 workspace.display()
451 ),
452 }],
453 symbols: vec![],
454 called_finish: false,
455 timed_out: false,
456 oversized: false,
457 mode,
458 },
459 Ok(roots) => analyze_discovered_root(mode, &roots[0], timeout),
460 Err(e) => AnalyzeResult {
461 diagnostics: vec![MappedDiagnostic {
462 code: "bitloom-lsp.discover-failed".into(),
463 message: format!(
464 "bitloom-lsp.discover-failed: Cargo-graph discovery under {}: {e}",
465 workspace.display()
466 ),
467 }],
468 symbols: vec![],
469 called_finish: false,
470 timed_out: false,
471 oversized: false,
472 mode,
473 },
474 }
475}
476
477pub fn analyze_on_did_save_at(path_hint: Option<&Path>) -> AnalyzeResult {
481 if let Some(hint) = path_hint {
482 if let Some(cargo_root) = find_cargo_root(hint) {
483 if let Ok(roots) = discover_design_roots(&cargo_root) {
484 if !roots.is_empty() {
485 return analyze_discovered_root(
486 AnalysisMode::FullElaborate,
487 &roots[0],
488 MVP_INTERACTIVE_BUDGET,
489 );
490 }
491 }
492 }
493 }
494 analyze_on_did_save()
495}
496
497fn find_cargo_root(start: &Path) -> Option<PathBuf> {
498 let mut cur = if start.is_file() {
499 start.parent()?.to_path_buf()
500 } else {
501 start.to_path_buf()
502 };
503 loop {
504 if cur.join("Cargo.toml").is_file() {
505 return Some(cur);
506 }
507 if !cur.pop() {
508 return None;
509 }
510 }
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516
517 #[test]
518 fn full_ok_calls_finish_and_symbols() {
519 let r = analyze(
520 AnalysisMode::FullElaborate,
521 DesignFixture::OkCounter,
522 MVP_INTERACTIVE_BUDGET,
523 );
524 assert!(r.called_finish);
525 assert!(r.diagnostics.is_empty());
526 assert!(r.symbols.iter().any(|s| s.name == "Fr99OkCounter"));
527 assert!(r.symbols.iter().any(|s| s.kind == "port"));
528 }
529
530 #[test]
531 fn shallow_does_not_call_finish() {
532 let r = analyze(
533 AnalysisMode::Shallow,
534 DesignFixture::FailHwCapture,
535 MVP_INTERACTIVE_BUDGET,
536 );
537 assert!(!r.called_finish);
538 assert!(r.diagnostics.is_empty());
539 }
540
541 #[test]
542 fn discovered_ok_counter_calls_finish() {
543 let root = DiscoveredDesignRoot {
544 package_name: "fixture".into(),
545 package_dir: PathBuf::from("."),
546 root_id: "Fr113OkCounter".into(),
547 };
548 let r = analyze_discovered_root(AnalysisMode::FullElaborate, &root, MVP_INTERACTIVE_BUDGET);
549 assert!(r.called_finish);
550 assert!(r.symbols.iter().any(|s| s.name == "Fr113OkCounter"));
551 }
552}