Skip to main content

logicaffeine_lsp/
pipeline.rs

1use std::collections::HashMap;
2
3use logicaffeine_base::{Arena, Interner};
4use logicaffeine_compile::analysis::{EscapeChecker, OwnershipChecker, VarState};
5use logicaffeine_language::{
6    analysis::{DiscoveryPass, PolicyRegistry, TypeRegistry},
7    arena_ctx::AstContext,
8    ast::stmt::{Expr, Stmt, StmtId, TypeExpr},
9    drs::WorldState,
10    error::ParseError,
11    lexer::Lexer,
12    mwe,
13    parser::{NestedStmtSpans, Parser},
14    token::{BlockType, Span, Token, TokenType},
15};
16
17use logicaffeine_compile::vm::compiler::Refusal;
18use logicaffeine_language::lgx::check::Finding;
19use logicaffeine_language::lint::Finding as CopyFinding;
20
21use crate::index::SymbolIndex;
22
23/// A lightweight owned analysis error from escape/ownership checking.
24#[derive(Debug, Clone)]
25pub struct AnalysisError {
26    /// Socratic error message
27    pub message: String,
28    /// Variable name for span resolution
29    pub variable: String,
30    /// Stable diagnostic code for code actions
31    pub code: &'static str,
32    /// Optional cause context for related information
33    pub cause_context: Option<String>,
34    /// The erring statement's span — the innermost statement at fault, nested
35    /// ones included — when known.
36    pub use_span: Option<Span>,
37    /// The causing statement's span (the Give that moved it), when known.
38    pub cause_span: Option<Span>,
39}
40
41/// Result of running the full analysis pipeline on a document.
42pub struct AnalysisResult {
43    pub tokens: Vec<Token>,
44    pub interner: Interner,
45    pub type_registry: TypeRegistry,
46    pub policy_registry: PolicyRegistry,
47    pub errors: Vec<ParseError>,
48    pub escape_errors: Vec<AnalysisError>,
49    pub ownership_errors: Vec<AnalysisError>,
50    pub ownership_states: HashMap<String, VarState>,
51    pub symbol_index: SymbolIndex,
52    /// The LGX template checker's findings — accessibility and structure warnings on a `View:` —
53    /// at their spans in the file.
54    pub lgx_findings: Vec<Finding>,
55    /// The value-semantics copy lint's findings, at their spans in the file — see
56    /// `logicaffeine_language::lint`.
57    pub copy_findings: Vec<CopyFinding>,
58    /// Every refusal the browser build of this program meets, each at the construct it refuses.
59    /// Whole-program: computed from a full parse only, since whether a `## Route` or a mounted
60    /// component lowers depends on the declarations beside it.
61    pub refusals: Vec<Refusal>,
62}
63
64/// Run the full analysis pipeline: lex → MWE → discover → parse → index.
65///
66/// Uses block-level error recovery: if the full parse fails, splits source
67/// at `## BlockHeader` boundaries and parses each block independently.
68/// Blank the `private` header modifier — replace `private ` with spaces in a
69/// `## To … private …` / `## A[n] private …` header so the parser (which has no
70/// notion of privacy) names the definition by its REAL name instead of naming it
71/// `private`, and so a private definition raises no spurious diagnostic. Byte
72/// length is preserved, so every span the analysis reports still lines up with
73/// the original document.
74fn blank_privacy_markers(source: &str) -> String {
75    const BLANK: &str = "        "; // "private " is 8 bytes
76    let mut out = String::with_capacity(source.len());
77    for line in source.split_inclusive('\n') {
78        match privacy_marker_offset(line) {
79            Some(at) => {
80                out.push_str(&line[..at]);
81                out.push_str(BLANK);
82                out.push_str(&line[at + BLANK.len()..]);
83            }
84            None => out.push_str(line),
85        }
86    }
87    out
88}
89
90/// Byte offset of a `private ` modifier within a header line, when it sits in a
91/// real modifier position (`## To [native] private …`, `## A[n] private …`).
92/// `None` for prose, a `private` inside a name, or a string.
93fn privacy_marker_offset(line: &str) -> Option<usize> {
94    let indent = line.len() - line.trim_start().len();
95    let t = &line[indent..];
96    if let Some(rest) = t.strip_prefix("## To ") {
97        let mut pos = indent + "## To ".len();
98        let rest = match rest.strip_prefix("native ") {
99            Some(r) => {
100                pos += "native ".len();
101                r
102            }
103            None => rest,
104        };
105        return rest.starts_with("private ").then_some(pos);
106    }
107    for prefix in ["## A ", "## An "] {
108        if let Some(rest) = t.strip_prefix(prefix) {
109            if rest.starts_with("private ") {
110                return Some(indent + prefix.len());
111            }
112        }
113    }
114    None
115}
116
117pub fn analyze(source: &str) -> AnalysisResult {
118    let blanked = blank_privacy_markers(source);
119    let source = blanked.as_str();
120    let mut interner = Interner::new();
121    let mut lexer = Lexer::new(source, &mut interner);
122    let tokens = lexer.tokenize();
123
124    let mwe_trie = mwe::build_mwe_trie();
125    let tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
126
127    let (type_registry, policy_registry) = {
128        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
129        let result = discovery.run_full();
130        (result.types, result.policies)
131    };
132
133    let parse_tokens = tokens.clone();
134
135    // Try full parse first (optimistic fast path)
136    let (
137        errors,
138        symbol_index,
139        escape_errors,
140        ownership_errors,
141        ownership_states,
142        lgx_findings,
143        copy_findings,
144        refusals,
145    ) = match try_full_parse(parse_tokens.clone(), &type_registry, &mut interner) {
146        Ok(result) => {
147            let idx = SymbolIndex::build(
148                &result.owned_stmts,
149                &tokens,
150                &type_registry,
151                result.interner,
152                source,
153            );
154            (
155                result.type_errors,
156                idx,
157                result.escape_errors,
158                result.ownership_errors,
159                result.ownership_states,
160                result.lgx_findings,
161                result.copy_findings,
162                result.refusals,
163            )
164        }
165        Err(first_error) => {
166            // Fall through to block-level recovery
167            let mut recovery = parse_with_recovery(source, &tokens, &type_registry, &mut interner);
168
169            // Extract function definitions from block header tokens (the standard
170            // parser cannot handle `## To funcName with param: Type` blocks)
171            let func_defs = extract_function_defs_from_tokens(&tokens, &interner);
172            recovery.stmts.extend(func_defs);
173
174            // The full parse saw the whole program; its error is the truest
175            // diagnosis for the region it names. The per-sentence reparse
176            // only sees the excised sentence and can degrade a specific
177            // teaching (IsValueEquality) to a generic ExpectedStatement —
178            // swap the same-line generic back for the specific one (the two
179            // anchor differently within the sentence, so lines, not spans,
180            // are the join).
181            let line_of = |offset: usize| {
182                source[..offset.min(source.len())]
183                    .bytes()
184                    .filter(|&b| b == b'\n')
185                    .count()
186            };
187            let first_error_line = line_of(first_error.span.start);
188            let same_line = recovery
189                .parse_errors
190                .iter_mut()
191                .find(|e| line_of(e.span.start) == first_error_line);
192            if let Some(slot) = same_line {
193                *slot = first_error;
194            } else {
195                // The full parse read the whole program — function bodies
196                // included, which the per-block recovery does not reparse — so
197                // its error stands whatever the recovery found elsewhere.
198                let at = recovery
199                    .parse_errors
200                    .partition_point(|e| e.span.start <= first_error.span.start);
201                recovery.parse_errors.insert(at, first_error);
202            }
203            let idx =
204                SymbolIndex::build(&recovery.stmts, &tokens, &type_registry, &interner, source);
205            (
206                recovery.parse_errors,
207                idx,
208                recovery.escape_errors,
209                recovery.ownership_errors,
210                recovery.ownership_states,
211                recovery.lgx_findings,
212                recovery.copy_findings,
213                Vec::new(),
214            )
215        }
216    };
217
218    AnalysisResult {
219        tokens,
220        interner,
221        type_registry,
222        policy_registry,
223        errors,
224        escape_errors,
225        ownership_errors,
226        ownership_states,
227        symbol_index,
228        lgx_findings,
229        copy_findings,
230        refusals,
231    }
232}
233
234/// Result of a successful full parse, including analysis checker results.
235struct FullParseResult<'a> {
236    owned_stmts: Vec<OwnedStmt>,
237    interner: &'a Interner,
238    /// Typechecker findings mapped onto real statement spans.
239    type_errors: Vec<ParseError>,
240    escape_errors: Vec<AnalysisError>,
241    ownership_errors: Vec<AnalysisError>,
242    ownership_states: HashMap<String, VarState>,
243    lgx_findings: Vec<Finding>,
244    copy_findings: Vec<CopyFinding>,
245    refusals: Vec<Refusal>,
246}
247
248/// Attempt a full parse of the token stream.
249fn try_full_parse<'a>(
250    tokens: Vec<Token>,
251    type_registry: &TypeRegistry,
252    interner: &'a mut Interner,
253) -> Result<FullParseResult<'a>, ParseError> {
254    let expr_arena = Arena::new();
255    let term_arena = Arena::new();
256    let np_arena = Arena::new();
257    let sym_arena = Arena::new();
258    let role_arena = Arena::new();
259    let pp_arena = Arena::new();
260    let stmt_arena: Arena<Stmt> = Arena::new();
261    let imperative_expr_arena: Arena<Expr> = Arena::new();
262    let type_expr_arena: Arena<TypeExpr> = Arena::new();
263
264    let ctx = AstContext::with_types(
265        &expr_arena,
266        &term_arena,
267        &np_arena,
268        &sym_arena,
269        &role_arena,
270        &pp_arena,
271        &stmt_arena,
272        &imperative_expr_arena,
273        &type_expr_arena,
274    );
275
276    let mut world_state = WorldState::new();
277    let mut parser = Parser::new(
278        tokens,
279        &mut world_state,
280        interner,
281        ctx,
282        type_registry.clone(),
283    );
284    let stmts = parser.parse_program()?;
285    let stmt_spans = parser.stmt_spans().to_vec();
286    let nested_spans = parser.nested_stmt_spans().clone();
287    let lgx_findings = parser.lgx_findings().to_vec();
288    let copy_findings = parser.value_copy_findings().to_vec();
289    let type_registry = parser.into_type_registry();
290
291    // The browser build's own refusals — the same list the bytecode compiler stops at the first
292    // of — located in THIS file: the editor parses without the stdlib prelude, so a span here is
293    // already a file offset.
294    let refusals =
295        logicaffeine_compile::vm::compiler::lgx_refusals(&stmts, interner, Some(&type_registry));
296
297    // Typecheck while the arena AST is alive; every failing top-level
298    // statement reports, anchored on the innermost statement at fault — a
299    // nested one through its trail, else the top-level statement itself.
300    let type_errors = {
301        let (_env, indexed) =
302            logicaffeine_compile::analysis::check_program_collect(&stmts, interner, &type_registry);
303        indexed
304            .into_iter()
305            .map(|found| {
306                let mut kind = found.error.to_parse_error_kind(interner);
307                // The bridge cannot see the registry; fill in the fields that
308                // DO exist so the message and quickfix can name them.
309                if let logicaffeine_language::error::ParseErrorKind::FieldNotFound {
310                    type_name,
311                    available,
312                    ..
313                } = &mut kind
314                {
315                    *available = fields_of_type(&type_registry, type_name, interner);
316                }
317                ParseError {
318                    kind,
319                    span: statement_span(
320                        &found.trail,
321                        found.stmt_index,
322                        &stmt_spans,
323                        &nested_spans,
324                    )
325                    .unwrap_or_default(),
326                }
327            })
328            .collect()
329    };
330
331    // Escape and ownership analysis while the arena AST is still alive.
332    let escape_errors = escape_findings(&stmts, interner, &stmt_spans, &nested_spans);
333    let (ownership_errors, ownership_states) =
334        ownership_findings(&stmts, interner, &stmt_spans, &nested_spans);
335
336    // Convert arena-allocated stmts to owned summaries for the symbol index
337    let owned = stmts.iter().map(|s| summarize_stmt(s, interner)).collect();
338    Ok(FullParseResult {
339        owned_stmts: owned,
340        interner,
341        type_errors,
342        escape_errors,
343        ownership_errors,
344        ownership_states,
345        lgx_findings,
346        copy_findings,
347        refusals,
348    })
349}
350
351/// Where a finding lands: the innermost statement of its trail that the parser
352/// read (a nested one, through `Parser::nested_stmt_spans`), else its
353/// top-level statement (through `Parser::stmt_spans`).
354fn statement_span(
355    trail: &[StmtId],
356    stmt_index: Option<usize>,
357    stmt_spans: &[Span],
358    nested_spans: &NestedStmtSpans,
359) -> Option<Span> {
360    trail
361        .iter()
362        .find_map(|id| nested_spans.get(*id))
363        .or_else(|| stmt_index.and_then(|i| stmt_spans.get(i)).copied())
364}
365
366/// Every escape finding in `stmts`, anchored on the statement at fault.
367fn escape_findings(
368    stmts: &[Stmt<'_>],
369    interner: &Interner,
370    stmt_spans: &[Span],
371    nested_spans: &NestedStmtSpans,
372) -> Vec<AnalysisError> {
373    use logicaffeine_compile::analysis::EscapeErrorKind;
374    EscapeChecker::new(interner)
375        .check_program_collect(stmts)
376        .into_iter()
377        .map(|finding| {
378            let (code, variable, cause_context) = match &finding.error.kind {
379                EscapeErrorKind::ReturnEscape {
380                    variable,
381                    zone_name,
382                } => (
383                    "escape-return",
384                    variable.clone(),
385                    Some(format!("zone '{}'", zone_name)),
386                ),
387                EscapeErrorKind::AssignmentEscape {
388                    variable,
389                    target,
390                    zone_name,
391                } => (
392                    "escape-assignment",
393                    variable.clone(),
394                    Some(format!("zone '{}', target '{}'", zone_name, target)),
395                ),
396            };
397            AnalysisError {
398                message: finding.error.to_string(),
399                variable,
400                code,
401                cause_context,
402                use_span: statement_span(
403                    &finding.trail,
404                    Some(finding.stmt_index),
405                    stmt_spans,
406                    nested_spans,
407                ),
408                cause_span: None,
409            }
410        })
411        .collect()
412}
413
414/// Every ownership finding in `stmts`, anchored on the use at fault and linked
415/// to the statement that gave the value away, plus the variable states the
416/// checker ended with.
417fn ownership_findings(
418    stmts: &[Stmt<'_>],
419    interner: &Interner,
420    stmt_spans: &[Span],
421    nested_spans: &NestedStmtSpans,
422) -> (Vec<AnalysisError>, HashMap<String, VarState>) {
423    use logicaffeine_compile::analysis::OwnershipErrorKind;
424    let mut checker = OwnershipChecker::new(interner);
425    let errors = checker
426        .check_program_collect(stmts)
427        .into_iter()
428        .map(|finding| {
429            let (code, variable, cause_context) = match &finding.error.kind {
430                OwnershipErrorKind::UseAfterMove { variable } => (
431                    "use-after-move",
432                    variable.clone(),
433                    Some(format!("'{}' was given away here", variable)),
434                ),
435                OwnershipErrorKind::UseAfterMaybeMove { variable, given_in } => (
436                    "maybe-moved",
437                    variable.clone(),
438                    Some(format!(
439                        "'{}' might be given away in {}",
440                        variable, given_in
441                    )),
442                ),
443                OwnershipErrorKind::DoubleMoved { variable } => (
444                    "double-move",
445                    variable.clone(),
446                    Some(format!("'{}' was first given away here", variable)),
447                ),
448            };
449            let cause_trail: Vec<StmtId> = finding.cause.into_iter().collect();
450            AnalysisError {
451                message: finding.error.to_string(),
452                variable,
453                code,
454                cause_context,
455                use_span: statement_span(
456                    &finding.trail,
457                    Some(finding.stmt_index),
458                    stmt_spans,
459                    nested_spans,
460                ),
461                cause_span: statement_span(
462                    &cause_trail,
463                    finding.cause_stmt_index,
464                    stmt_spans,
465                    nested_spans,
466                ),
467            }
468        })
469        .collect();
470    let states = checker
471        .var_states()
472        .iter()
473        .map(|(sym, state)| (interner.resolve(*sym).to_string(), *state))
474        .collect();
475    (errors, states)
476}
477
478/// The field names a struct type declares, for did-you-mean and message text.
479fn fields_of_type(registry: &TypeRegistry, type_name: &str, interner: &Interner) -> Vec<String> {
480    for (sym, typedef) in registry.iter_types() {
481        if interner.resolve(*sym) == type_name {
482            if let logicaffeine_language::analysis::TypeDef::Struct { fields, .. } = typedef {
483                return fields
484                    .iter()
485                    .map(|f| interner.resolve(f.name).to_string())
486                    .collect();
487            }
488        }
489    }
490    Vec::new()
491}
492
493/// Lightweight summary of a statement for symbol indexing.
494/// This avoids lifetime issues with arena-allocated AST nodes.
495#[derive(Debug, Clone)]
496pub enum OwnedStmt {
497    FunctionDef {
498        name: String,
499        params: Vec<(String, String)>,
500        return_type: Option<String>,
501    },
502    StructDef {
503        name: String,
504        fields: Vec<(String, String)>,
505    },
506    Let {
507        name: String,
508        ty: Option<String>,
509        inferred_type: Option<String>,
510        mutable: bool,
511    },
512    Theorem {
513        name: String,
514    },
515    Block {
516        name: String,
517        kind: String,
518    },
519    /// `## Component App` — its heading, its state, its props and its actions.
520    ///
521    /// ★ IT CARRIES ITS OWN SPANS, unlike every variant above, which hands the indexer a NAME and
522    /// lets it hunt the token stream for a match. That works for a `To …` heading and stops working
523    /// here: a `View:` body is ONE `RawBlock` token, so a name used only in a template is not in
524    /// the token stream at all — and a name that appears both in `State:` and in the view would be
525    /// matched by position rather than by meaning. The parser already resolved all of this (a
526    /// `StateField`, an `ActionDef` and the `ComponentDef` each carry a `Span`, and template spans
527    /// are mapped back to FILE offsets by `RawMap`), so the answer is carried rather than re-guessed.
528    ComponentDef {
529        name: String,
530        /// What the heading says it is — "component", "page", "store", "error page".
531        kind: String,
532        name_span: Span,
533        /// `(name, type-or-inferred, derived?, span)`.
534        state: Vec<(String, Option<String>, bool, Span)>,
535        props: Vec<(String, String, Span)>,
536        actions: Vec<(String, Vec<(String, String)>, Span)>,
537        /// Every identifier the `View:` mentions, at its span in the FILE — the references a
538        /// token walk cannot see, because the whole template is one `RawBlock` token.
539        mentions: Vec<(String, Span)>,
540    },
541    Other,
542}
543
544fn summarize_stmt(stmt: &Stmt, interner: &Interner) -> OwnedStmt {
545    match stmt {
546        Stmt::ComponentDef(def) => {
547            use logicaffeine_language::ast::component::ComponentKind;
548            OwnedStmt::ComponentDef {
549                name: interner.resolve(def.name).to_string(),
550                kind: match &def.kind {
551                    ComponentKind::Component => "component",
552                    ComponentKind::Page { .. } => "page",
553                    _ => "component",
554                }
555                .to_string(),
556                name_span: def.span,
557                state: def
558                    .state
559                    .iter()
560                    .map(|f| {
561                        (
562                            interner.resolve(f.name).to_string(),
563                            f.ty.map(|t| format_type_expr(t, interner))
564                                .or_else(|| infer_type_from_expr(f.init, interner)),
565                            f.derived,
566                            f.span,
567                        )
568                    })
569                    .collect(),
570                props: def
571                    .props
572                    .iter()
573                    .map(|(n, t)| {
574                        (
575                            interner.resolve(*n).to_string(),
576                            format_type_expr(t, interner),
577                            def.span,
578                        )
579                    })
580                    .collect(),
581                mentions: def
582                    .view
583                    .as_ref()
584                    .map(|v| {
585                        v.mentions
586                            .iter()
587                            .map(|(n, sp)| (interner.resolve(*n).to_string(), *sp))
588                            .collect()
589                    })
590                    .unwrap_or_default(),
591                actions: def
592                    .actions
593                    .iter()
594                    .map(|a| {
595                        (
596                            interner.resolve(a.name).to_string(),
597                            a.params
598                                .iter()
599                                .map(|(n, t)| {
600                                    (
601                                        interner.resolve(*n).to_string(),
602                                        format_type_expr(t, interner),
603                                    )
604                                })
605                                .collect(),
606                            a.span,
607                        )
608                    })
609                    .collect(),
610            }
611        }
612        Stmt::FunctionDef {
613            name,
614            params,
615            return_type,
616            ..
617        } => OwnedStmt::FunctionDef {
618            name: interner.resolve(*name).to_string(),
619            params: params
620                .iter()
621                .map(|(n, ty)| {
622                    (
623                        interner.resolve(*n).to_string(),
624                        format_type_expr(ty, interner),
625                    )
626                })
627                .collect(),
628            return_type: return_type.map(|ty| format_type_expr(ty, interner)),
629        },
630        Stmt::StructDef { name, fields, .. } => OwnedStmt::StructDef {
631            name: interner.resolve(*name).to_string(),
632            fields: fields
633                .iter()
634                .map(|(n, ty, _is_public)| {
635                    (
636                        interner.resolve(*n).to_string(),
637                        interner.resolve(*ty).to_string(),
638                    )
639                })
640                .collect(),
641        },
642        Stmt::Let {
643            var,
644            ty,
645            mutable,
646            value,
647            ..
648        } => {
649            let explicit_ty = ty.map(|t| format_type_expr(t, interner));
650            let inferred_type = if explicit_ty.is_none() {
651                infer_type_from_expr(value, interner)
652            } else {
653                None
654            };
655            OwnedStmt::Let {
656                name: interner.resolve(*var).to_string(),
657                ty: explicit_ty,
658                inferred_type,
659                mutable: *mutable,
660            }
661        }
662        Stmt::Theorem(t) => OwnedStmt::Theorem {
663            name: t.name.clone(),
664        },
665        _ => OwnedStmt::Other,
666    }
667}
668
669fn infer_type_from_expr(expr: &Expr, interner: &Interner) -> Option<String> {
670    use logicaffeine_language::ast::stmt::Literal;
671    match expr {
672        Expr::Literal(lit) => match lit {
673            Literal::Number(_) => Some("Int".to_string()),
674            Literal::Float(_) => Some("Real".to_string()),
675            Literal::Text(_) => Some("Text".to_string()),
676            Literal::Boolean(_) => Some("Bool".to_string()),
677            Literal::Nothing => Some("Unit".to_string()),
678            Literal::Char(_) => Some("Char".to_string()),
679            Literal::Duration(_) => Some("Duration".to_string()),
680            Literal::Date(_) => Some("Date".to_string()),
681            Literal::Moment(_) => Some("Moment".to_string()),
682            _ => None,
683        },
684        Expr::New { type_name, .. } => Some(interner.resolve(*type_name).to_string()),
685        Expr::List(_) => Some("Seq".to_string()),
686        Expr::Call { function, .. } => Some(format!("{}(..)", interner.resolve(*function))),
687        Expr::Copy { .. } => Some("copy".to_string()),
688        Expr::Length { .. } => Some("Int".to_string()),
689        Expr::Contains { .. } => Some("Bool".to_string()),
690        _ => None,
691    }
692}
693
694fn format_type_expr(ty: &TypeExpr, interner: &Interner) -> String {
695    match ty {
696        TypeExpr::Primitive(sym) => interner.resolve(*sym).to_string(),
697        TypeExpr::Named(sym) => interner.resolve(*sym).to_string(),
698        TypeExpr::Generic { base, params } => {
699            let base_name = interner.resolve(*base);
700            let param_strs: Vec<String> = params
701                .iter()
702                .map(|p| format_type_expr(p, interner))
703                .collect();
704            format!("{} of {}", base_name, param_strs.join(", "))
705        }
706        TypeExpr::Function { inputs, output } => {
707            let input_strs: Vec<String> = inputs
708                .iter()
709                .map(|i| format_type_expr(i, interner))
710                .collect();
711            let out = format_type_expr(output, interner);
712            format!("({}) -> {}", input_strs.join(", "), out)
713        }
714        TypeExpr::Refinement { base, .. } => {
715            format!("{} where ...", format_type_expr(base, interner))
716        }
717        TypeExpr::Persistent { inner } => {
718            format!("Persistent {}", format_type_expr(inner, interner))
719        }
720        TypeExpr::Mutable { inner } => {
721            format!("mutable {}", format_type_expr(inner, interner))
722        }
723        TypeExpr::Tuple(elems) => {
724            let parts: Vec<String> = elems
725                .iter()
726                .map(|t| format_type_expr(t, interner))
727                .collect();
728            format!("({})", parts.join(", "))
729        }
730        TypeExpr::Record {
731            field_names,
732            field_types,
733        } => {
734            let parts: Vec<String> = field_names
735                .iter()
736                .zip(field_types.iter())
737                .map(|(n, t)| {
738                    format!(
739                        "{}: {}",
740                        interner.resolve(*n),
741                        format_type_expr(t, interner)
742                    )
743                })
744                .collect();
745            format!("({})", parts.join(", "))
746        }
747    }
748}
749
750/// Result of block-level recovery parsing, including analysis errors.
751struct RecoveryResult {
752    stmts: Vec<OwnedStmt>,
753    parse_errors: Vec<ParseError>,
754    escape_errors: Vec<AnalysisError>,
755    ownership_errors: Vec<AnalysisError>,
756    ownership_states: HashMap<String, VarState>,
757    lgx_findings: Vec<Finding>,
758    copy_findings: Vec<CopyFinding>,
759}
760
761/// Parse with block-level recovery.
762///
763/// Splits source at `## BlockHeader` boundaries and parses each block
764/// independently, collecting successful parses and errors separately.
765/// Function definition blocks (`## To`) are skipped — they are handled
766/// separately by `extract_function_defs_from_tokens`.
767fn parse_with_recovery(
768    _source: &str,
769    tokens: &[Token],
770    type_registry: &TypeRegistry,
771    interner: &mut Interner,
772) -> RecoveryResult {
773    let mut result = RecoveryResult {
774        stmts: vec![],
775        parse_errors: vec![],
776        escape_errors: vec![],
777        ownership_errors: vec![],
778        ownership_states: HashMap::new(),
779        lgx_findings: vec![],
780        copy_findings: vec![],
781    };
782
783    // Find block header positions in the token stream
784    let mut block_boundaries: Vec<usize> = vec![0]; // first token
785    for (i, tok) in tokens.iter().enumerate() {
786        if matches!(tok.kind, TokenType::BlockHeader { .. }) && i > 0 {
787            block_boundaries.push(i);
788        }
789    }
790
791    if block_boundaries.len() <= 1 {
792        // Single block — check if it's a function block (handled elsewhere)
793        let is_function_block = tokens.first().map_or(false, |t| {
794            matches!(
795                t.kind,
796                TokenType::BlockHeader {
797                    block_type: BlockType::Function
798                }
799            )
800        });
801        if is_function_block {
802            return result;
803        }
804        // Non-function single block: attempt to parse for partial recovery
805        let block_tokens: Vec<Token> = tokens.to_vec();
806        let (block, errors) =
807            parse_block_excising_bad_sentences(block_tokens, type_registry, interner);
808        result.parse_errors.extend(errors);
809        if let Some(block) = block {
810            result.stmts = block.owned_stmts;
811            result.escape_errors = block.escape_errors;
812            result.ownership_errors = block.ownership_errors;
813            result.ownership_states = block.ownership_states;
814            result.lgx_findings = block.lgx_findings;
815            result.copy_findings = block.copy_findings;
816        }
817        return result;
818    }
819
820    let mut try_block_fn = |start: usize, end_excl: usize, result: &mut RecoveryResult| {
821        // Skip function blocks — they can't be parsed by the standard parser
822        if matches!(
823            tokens[start].kind,
824            TokenType::BlockHeader {
825                block_type: BlockType::Function
826            }
827        ) {
828            return;
829        }
830        let block_tokens: Vec<Token> = tokens[start..end_excl].to_vec();
831        let (block, errors) =
832            parse_block_excising_bad_sentences(block_tokens, type_registry, interner);
833        result.parse_errors.extend(errors);
834        if let Some(block) = block {
835            result.stmts.extend(block.owned_stmts);
836            result.escape_errors.extend(block.escape_errors);
837            result.ownership_errors.extend(block.ownership_errors);
838            result.ownership_states.extend(block.ownership_states);
839            result.lgx_findings.extend(block.lgx_findings);
840            result.copy_findings.extend(block.copy_findings);
841        }
842    };
843
844    for window in block_boundaries.windows(2) {
845        let start = window[0];
846        let end = window[1];
847        try_block_fn(start, end, &mut result);
848    }
849
850    // Parse the last block
851    let last_start = *block_boundaries.last().unwrap();
852    try_block_fn(last_start, tokens.len(), &mut result);
853
854    result
855}
856
857/// Extract function definitions from `## To` block header tokens.
858///
859/// The standard parser cannot handle function definition blocks, so we extract
860/// function name and parameters directly from the token stream.
861fn extract_function_defs_from_tokens(tokens: &[Token], interner: &Interner) -> Vec<OwnedStmt> {
862    let mut results = Vec::new();
863    let mut i = 0;
864
865    while i < tokens.len() {
866        if let TokenType::BlockHeader {
867            block_type: BlockType::Function,
868        } = &tokens[i].kind
869        {
870            let mut j = i + 1;
871            let mut func_name: Option<String> = None;
872            let mut params: Vec<(String, String)> = Vec::new();
873            let mut after_with = false;
874            let mut current_param_name: Option<String> = None;
875            let mut return_type: Option<String> = None;
876
877            while j < tokens.len() {
878                match &tokens[j].kind {
879                    TokenType::Newline | TokenType::Indent | TokenType::BlockHeader { .. } => break,
880                    TokenType::Colon => {
881                        if let Some(param_name) = current_param_name.take() {
882                            // Next token after colon is the type
883                            j += 1;
884                            let type_name = if j < tokens.len()
885                                && !matches!(
886                                    tokens[j].kind,
887                                    TokenType::Newline
888                                        | TokenType::Indent
889                                        | TokenType::BlockHeader { .. }
890                                        | TokenType::Colon
891                                ) {
892                                interner.resolve(tokens[j].lexeme).to_string()
893                            } else {
894                                "auto".to_string()
895                            };
896                            params.push((param_name, type_name));
897                        }
898                    }
899                    TokenType::Arrow => {
900                        // Next token is the return type
901                        j += 1;
902                        if j < tokens.len()
903                            && !matches!(
904                                tokens[j].kind,
905                                TokenType::Newline
906                                    | TokenType::Indent
907                                    | TokenType::BlockHeader { .. }
908                            )
909                        {
910                            return_type = Some(interner.resolve(tokens[j].lexeme).to_string());
911                        }
912                    }
913                    TokenType::And | TokenType::Comma => {
914                        // Parameter separator
915                    }
916                    TokenType::LParen => {
917                        // `(n: Int)` groups open the parameter list exactly
918                        // like the prose `with` does.
919                        if func_name.is_some() {
920                            after_with = true;
921                        }
922                    }
923                    TokenType::RParen => {}
924                    _ => {
925                        let text = interner.resolve(tokens[j].lexeme);
926                        if text == "with" && func_name.is_some() {
927                            after_with = true;
928                        } else if func_name.is_none() {
929                            func_name = Some(text.to_string());
930                        } else if after_with && current_param_name.is_none() {
931                            current_param_name = Some(text.to_string());
932                        }
933                    }
934                }
935                j += 1;
936            }
937
938            if let Some(name) = func_name {
939                results.push(OwnedStmt::FunctionDef {
940                    name,
941                    params,
942                    return_type,
943                });
944            }
945        }
946        i += 1;
947    }
948
949    results
950}
951
952#[cfg(test)]
953#[path = "../../logicaffeine_tests/unit/logicaffeine_lsp/pipeline/tests.rs"]
954mod tests;
955
956/// Result of parsing a single recovered block, including analysis errors.
957/// Parse a block, excising broken SENTENCES one at a time so every
958/// independently bad statement reports and the good ones stay analyzed.
959///
960/// On failure the sentence containing the error span (a `Period`-delimited
961/// token run) is removed — spans on the surviving tokens are original, so
962/// later errors and the symbol index stay source-accurate — and the block is
963/// reparsed. Excision stops when a failing sentence carries block structure
964/// (`Indent`/`Dedent`, where cutting would unbalance the tree), when the
965/// error lies outside any sentence, or after a hard iteration cap.
966fn parse_block_excising_bad_sentences(
967    mut block_tokens: Vec<Token>,
968    type_registry: &TypeRegistry,
969    interner: &mut Interner,
970) -> (Option<BlockParseResult>, Vec<ParseError>) {
971    const MAX_EXCISIONS: usize = 32;
972    let mut errors = Vec::new();
973
974    // Mid-stream block slices carry no EOF; the parser walks off the end of
975    // an EOF-less stream, so terminate the slice before any parse attempt.
976    if !matches!(block_tokens.last().map(|t| &t.kind), Some(TokenType::EOF)) {
977        let end = block_tokens.last().map(|t| t.span.end).unwrap_or(0);
978        let empty = interner.intern("");
979        block_tokens.push(Token::new(
980            TokenType::EOF,
981            empty,
982            logicaffeine_language::token::Span::new(end, end),
983        ));
984    }
985
986    for _ in 0..=MAX_EXCISIONS {
987        match try_parse_block(block_tokens.clone(), type_registry, interner) {
988            Ok(block) => return (Some(block), errors),
989            Err(e) => {
990                let sentence = sentence_token_range(&block_tokens, e.span.start);
991                errors.push(e);
992                match sentence {
993                    Some((start, end)) => {
994                        let cuts_structure = block_tokens[start..=end]
995                            .iter()
996                            .any(|t| matches!(t.kind, TokenType::Indent | TokenType::Dedent));
997                        if cuts_structure {
998                            return (None, errors);
999                        }
1000                        block_tokens.drain(start..=end);
1001                    }
1002                    None => return (None, errors),
1003                }
1004            }
1005        }
1006    }
1007    (None, errors)
1008}
1009
1010/// The token range (inclusive) of the `Period`-delimited sentence containing
1011/// `offset`. Sentences start after the previous `Period` (or the block
1012/// header) and end at their own `Period`.
1013fn sentence_token_range(tokens: &[Token], offset: usize) -> Option<(usize, usize)> {
1014    let mut start = None;
1015    for (i, token) in tokens.iter().enumerate() {
1016        if matches!(
1017            token.kind,
1018            TokenType::Indent | TokenType::Dedent | TokenType::Newline | TokenType::EOF
1019        ) || matches!(token.kind, TokenType::BlockHeader { .. })
1020        {
1021            continue;
1022        }
1023        if start.is_none() {
1024            start = Some(i);
1025        }
1026        if matches!(token.kind, TokenType::Period) {
1027            let s = start.take().unwrap();
1028            if tokens[s].span.start <= offset && offset <= token.span.end {
1029                return Some((s, i));
1030            }
1031        }
1032    }
1033    // An error past the last period belongs to the trailing unterminated run.
1034    if let Some(s) = start {
1035        if tokens[s].span.start <= offset {
1036            return Some((s, tokens.len().saturating_sub(1)));
1037        }
1038    }
1039    None
1040}
1041
1042struct BlockParseResult {
1043    owned_stmts: Vec<OwnedStmt>,
1044    escape_errors: Vec<AnalysisError>,
1045    ownership_errors: Vec<AnalysisError>,
1046    ownership_states: HashMap<String, VarState>,
1047    lgx_findings: Vec<Finding>,
1048    copy_findings: Vec<CopyFinding>,
1049}
1050
1051fn try_parse_block(
1052    tokens: Vec<Token>,
1053    type_registry: &TypeRegistry,
1054    interner: &mut Interner,
1055) -> Result<BlockParseResult, ParseError> {
1056    let expr_arena = Arena::new();
1057    let term_arena = Arena::new();
1058    let np_arena = Arena::new();
1059    let sym_arena = Arena::new();
1060    let role_arena = Arena::new();
1061    let pp_arena = Arena::new();
1062    let stmt_arena: Arena<Stmt> = Arena::new();
1063    let imperative_expr_arena: Arena<Expr> = Arena::new();
1064    let type_expr_arena: Arena<TypeExpr> = Arena::new();
1065
1066    let ctx = AstContext::with_types(
1067        &expr_arena,
1068        &term_arena,
1069        &np_arena,
1070        &sym_arena,
1071        &role_arena,
1072        &pp_arena,
1073        &stmt_arena,
1074        &imperative_expr_arena,
1075        &type_expr_arena,
1076    );
1077
1078    let mut world_state = WorldState::new();
1079    let mut parser = Parser::new(
1080        tokens,
1081        &mut world_state,
1082        interner,
1083        ctx,
1084        type_registry.clone(),
1085    );
1086    // A per-block recovery reparse sees only this block's own statements — the whole-file checks
1087    // `parse_program` otherwise runs at its end (`Mount` names something real, a page mounts
1088    // itself, LGX resolution) would report false refusals for names the REST of the file declares.
1089    // `fragment_mode` skips exactly those four; see its own doc comment for what a fragment still
1090    // does NOT get (cross-block LGX checks stay absent, not wrong, until the next whole-file parse).
1091    parser.fragment_mode = true;
1092    let stmts = parser.parse_program()?;
1093    let stmt_spans = parser.stmt_spans().to_vec();
1094    let nested_spans = parser.nested_stmt_spans().clone();
1095    let lgx_findings = parser.lgx_findings().to_vec();
1096    let copy_findings = parser.value_copy_findings().to_vec();
1097    drop(parser);
1098
1099    let escape_errors = escape_findings(&stmts, interner, &stmt_spans, &nested_spans);
1100    let (ownership_errors, ownership_states) =
1101        ownership_findings(&stmts, interner, &stmt_spans, &nested_spans);
1102
1103    let owned: Vec<OwnedStmt> = stmts.iter().map(|s| summarize_stmt(s, interner)).collect();
1104    Ok(BlockParseResult {
1105        owned_stmts: owned,
1106        escape_errors,
1107        ownership_errors,
1108        ownership_states,
1109        lgx_findings,
1110        copy_findings,
1111    })
1112}