Skip to main content

fallow_engine/
trace_error.rs

1//! `fallow trace-error`: resolve a runtime stack trace's frames against the
2//! project graph.
3//!
4//! Two independent halves, kept apart so each is testable on its own:
5//!
6//! 1. [`parse_stack_trace`] turns text into frames. Pure, no graph, no I/O.
7//! 2. [`resolve_stack_trace`] asks the module graph which definitions each
8//!    frame's identifier names.
9//!
10//! The graph is asked ONLY about frames whose file resolved to project source.
11//! Everything else keeps its place in the reported array with its origin
12//! recorded, so the reported frame numbering matches the trace as pasted and
13//! the counts close.
14//!
15//! No source-map layer. A frame pointing into a build artifact reports that
16//! fact rather than being rebound through a map that may be stale, because a
17//! confidently wrong line is worse than a named refusal.
18
19use std::path::{Path, PathBuf};
20
21use fallow_types::discover::FileId;
22use fallow_types::extract::MemberKind;
23use fallow_types::trace_error::{
24    ErrorTrace, ErrorTraceCandidate, ErrorTraceCounts, ErrorTraceFrame, ErrorTraceSchemaVersion,
25    FrameOrigin, FrameResolution,
26};
27use rustc_hash::FxHashMap;
28
29use crate::graph::ModuleGraph;
30use crate::module_graph::RetainedModuleGraph;
31use crate::trace::trace_impl::{matching_module_indexes, relativize};
32
33/// Largest stack trace this verb will read, from a file or from stdin.
34///
35/// A stack trace is a handful of kilobytes. The cap exists so a redirected log
36/// file cannot turn a bounded question into an unbounded one.
37pub const MAX_STACK_TRACE_BYTES: u64 = 1024 * 1024;
38
39/// Largest number of frames reported. Runtimes cap their own traces well below
40/// this (V8's default is 10), so reaching it means the input is a log rather
41/// than a trace. Frames past the cap are counted in `frames_omitted`.
42const MAX_REPORTED_FRAMES: usize = 256;
43
44/// Largest number of definitions listed for one ambiguous frame. The true match
45/// count stays visible through `candidates_omitted`, so capping the list never
46/// makes a frame look less ambiguous than it is.
47const MAX_FRAME_CANDIDATES: usize = 10;
48
49/// Path segments whose presence means the frame points at generated bundle
50/// output rather than at source. Resolving those needs a source map, which this
51/// verb deliberately does not do.
52const BUILD_OUTPUT_SEGMENTS: &[&str] = &["dist", "build", "out", ".next"];
53
54/// The installed dependency tree's directory name.
55const DEPENDENCY_SEGMENT: &str = "node_modules";
56
57/// One frame as read from the input, before the graph is consulted.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct RawFrame {
60    /// The input line, trimmed and otherwise verbatim.
61    pub raw: String,
62    /// The function identifier the runtime printed, with the `async` and `new`
63    /// markers removed.
64    pub function: Option<String>,
65    /// Whether the runtime marked the frame as a constructor call.
66    pub is_constructor: bool,
67    /// Whether the runtime marked the frame as an async call.
68    pub is_async: bool,
69    /// The frame's file, unwrapped from any URL scheme and forward-slashed.
70    pub file: Option<String>,
71    /// 1-based line, when the runtime supplied one.
72    pub line: Option<u32>,
73    /// 1-based column, when the runtime supplied one.
74    pub column: Option<u32>,
75}
76
77/// A stack trace after parsing and before resolution.
78#[derive(Debug, Clone, Default, PartialEq, Eq)]
79pub struct ParsedStackTrace {
80    /// The first non-blank line preceding any frame, verbatim.
81    pub header: Option<String>,
82    /// Recognised frames, in input order.
83    pub frames: Vec<RawFrame>,
84    /// Non-blank lines that were neither a frame nor the header.
85    pub unparsed_lines: usize,
86}
87
88/// Parse a runtime stack trace into frames.
89///
90/// Recognises the V8 / Node form (`    at name (file:line:col)`) and the
91/// SpiderMonkey / JavaScriptCore form (`name@file:line:col`). A line matching
92/// neither is counted, never silently dropped.
93#[must_use]
94pub fn parse_stack_trace(input: &str) -> ParsedStackTrace {
95    let mut parsed = ParsedStackTrace::default();
96    for line in input.lines() {
97        let trimmed = line.trim();
98        if trimmed.is_empty() {
99            continue;
100        }
101        if let Some(frame) = parse_frame(trimmed) {
102            parsed.frames.push(frame);
103            continue;
104        }
105        if parsed.header.is_none() && parsed.frames.is_empty() {
106            parsed.header = Some(trimmed.to_string());
107            continue;
108        }
109        parsed.unparsed_lines += 1;
110    }
111    parsed
112}
113
114/// Recognise one line as a frame in either supported runtime form.
115fn parse_frame(trimmed: &str) -> Option<RawFrame> {
116    parse_v8_frame(trimmed).or_else(|| parse_at_sign_frame(trimmed))
117}
118
119/// V8 / Node: `at name (file:line:col)`, `at file:line:col`, `at name (native)`.
120fn parse_v8_frame(trimmed: &str) -> Option<RawFrame> {
121    let (name_part, location_part) = v8_frame_parts(trimmed)?;
122    let mut name = name_part.trim();
123    let mut is_async = false;
124    let mut is_constructor = false;
125    if let Some(stripped) = name.strip_prefix("async ") {
126        is_async = true;
127        name = stripped.trim_start();
128    }
129    if let Some(stripped) = name.strip_prefix("new ") {
130        is_constructor = true;
131        name = stripped.trim_start();
132    }
133
134    let (file, line, column) = parse_location(location_part);
135    Some(RawFrame {
136        raw: trimmed.to_string(),
137        function: named_function(name),
138        is_constructor,
139        is_async,
140        file,
141        line,
142        column,
143    })
144}
145
146fn v8_frame_parts(trimmed: &str) -> Option<(&str, &str)> {
147    let rest = trimmed.strip_prefix("at ")?.trim_start();
148    Some(
149        rest.strip_suffix(')')
150            .and_then(|head| head.rsplit_once(" ("))
151            .unwrap_or(("", rest)),
152    )
153}
154
155fn at_sign_frame_parts(trimmed: &str) -> Option<(&str, &str)> {
156    // At-signs can occur in the function name and in subsequent path segments.
157    let first = trimmed.find('@')?;
158    let tail = &trimmed[first + 1..];
159    let head = tail.split(['/', '\\']).next()?;
160    let separator = head.rfind('@').map_or(first, |i| first + 1 + i);
161    Some((&trimmed[..separator], &trimmed[separator + 1..]))
162}
163
164fn is_web_location(location: &str) -> bool {
165    location.starts_with("http://") || location.starts_with("https://")
166}
167
168/// SpiderMonkey / JavaScriptCore: `name@file:line:col`, `@file:line:col`.
169///
170/// A location without a line number is rejected rather than accepted, so an
171/// ordinary line that happens to contain an `@` does not become a frame.
172fn parse_at_sign_frame(trimmed: &str) -> Option<RawFrame> {
173    let (name_part, location_part) = at_sign_frame_parts(trimmed)?;
174    let (file, line, column) = parse_location(location_part);
175    let file = file?;
176    line?;
177    Some(RawFrame {
178        raw: trimmed.to_string(),
179        function: named_function(name_part.trim()),
180        is_constructor: false,
181        is_async: false,
182        file: Some(file),
183        line,
184        column,
185    })
186}
187
188/// A frame's printed name, or `None` when the runtime printed a placeholder.
189fn named_function(name: &str) -> Option<String> {
190    if name.is_empty() || name == "<anonymous>" {
191        return None;
192    }
193    Some(name.to_string())
194}
195
196/// Split a `file:line:col` location, peeling the numeric tail from the right so
197/// a Windows drive letter and a URL scheme keep their own colons.
198fn parse_location(location: &str) -> (Option<String>, Option<u32>, Option<u32>) {
199    let location = location.trim();
200    if location.is_empty() || location == "native" || location == "<anonymous>" {
201        return (None, None, None);
202    }
203    let (head, column) = peel_number(location);
204    let (head, line) = if column.is_some() {
205        peel_number(head)
206    } else {
207        (head, None)
208    };
209    // Only a `file:line:col` tail yields both numbers. A `file:line` tail
210    // leaves the single number in `column`, where it belongs on `line`.
211    let (line, column) = match (line, column) {
212        (Some(line), column) => (Some(line), column),
213        (None, Some(single)) => (Some(single), None),
214        (None, None) => (None, None),
215    };
216    (normalize_frame_path(head), line, column)
217}
218
219/// Split a trailing `:<digits>` off a location, when there is one.
220fn peel_number(text: &str) -> (&str, Option<u32>) {
221    let Some((head, tail)) = text.rsplit_once(':') else {
222        return (text, None);
223    };
224    if tail.is_empty() || !tail.bytes().all(|byte| byte.is_ascii_digit()) {
225        return (text, None);
226    }
227    match tail.parse::<u32>() {
228        Ok(value) => (head, Some(value)),
229        Err(_) => (text, None),
230    }
231}
232
233/// Unwrap a frame path from its URL scheme and forward-slash it.
234///
235/// `file://` and `http(s)://` are unwrapped because the remainder is a real
236/// path that can match a module. Every other scheme (`node:`, `webpack://`,
237/// extension schemes) is left intact, because rewriting it would invent a path
238/// the runtime never named.
239fn normalize_frame_path(path: &str) -> Option<String> {
240    let path = path.trim().replace('\\', "/");
241    if path.is_empty() {
242        return None;
243    }
244    if !is_web_location(&path) && !path.starts_with("file://") {
245        return Some(path);
246    }
247    let Ok(url) = url::Url::parse(&path) else {
248        return Some(path);
249    };
250    let decoded = crate::url_path::decode_path(url.path()).unwrap_or_else(|| url.path().to_owned());
251    if url.scheme() == "file" {
252        if let Some(host) = url.host_str() {
253            return Some(format!("//{host}{decoded}"));
254        }
255        if let Some(drive_path) = decoded
256            .strip_prefix('/')
257            .filter(|p| is_windows_drive_prefixed(p))
258        {
259            return Some(drive_path.to_owned());
260        }
261    }
262    Some(decoded)
263}
264
265/// Whether a path begins with a `C:/`-style Windows drive prefix.
266fn is_windows_drive_prefixed(path: &str) -> bool {
267    let mut bytes = path.bytes();
268    matches!(
269        (bytes.next(), bytes.next(), bytes.next()),
270        (Some(drive), Some(b':'), Some(b'/')) if drive.is_ascii_alphabetic()
271    )
272}
273
274/// Whether a normalized path contains `segment` as a whole path component.
275fn has_path_segment(path: &str, segment: &str) -> bool {
276    path.split('/').any(|component| component == segment)
277}
278
279/// Whether a frame path names a runtime internal rather than a project file.
280fn is_runtime_internal(path: &str) -> bool {
281    path.starts_with("node:") || path.starts_with("internal/")
282}
283
284/// A frame's printed name, split into the parts a graph lookup addresses.
285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286struct Identifier<'a> {
287    /// The name exactly as the runtime printed it, for diagnostics.
288    printed: &'a str,
289    /// The segment before the last dot, when there is one. V8 prints a
290    /// receiver here (`Task` in `Task.run`, or the synthetic `Object`).
291    owner: Option<&'a str>,
292    /// The last segment: the function or member the frame is executing.
293    name: &'a str,
294}
295
296/// Split a printed frame name into an optional owner and the member or function
297/// name it addresses.
298///
299/// Returns `None` for a name that is not an addressable identifier, such as
300/// `Object.<anonymous>` or a SpiderMonkey `outer/<` closure marker. Those are
301/// reported as frames and are simply never looked up.
302fn identifier_parts(function: &str) -> Option<Identifier<'_>> {
303    if function.is_empty()
304        || function
305            .chars()
306            .any(|c| c.is_whitespace() || c == '<' || c == '>' || c == '/' || c == '\\')
307    {
308        return None;
309    }
310    let mut segments = function.split('.');
311    let mut owner = None;
312    let mut name = segments.next()?;
313    if name.is_empty() {
314        return None;
315    }
316    for segment in segments {
317        if segment.is_empty() {
318            return None;
319        }
320        owner = Some(name);
321        name = segment;
322    }
323    Some(Identifier {
324        printed: function,
325        owner,
326        name,
327    })
328}
329
330/// Stable wire token for a member kind, matching `--trace FILE:MEMBER`.
331const fn member_kind_label(kind: MemberKind) -> &'static str {
332    match kind {
333        MemberKind::ClassMethod => "class-method",
334        MemberKind::ClassProperty => "class-property",
335        MemberKind::EnumMember => "enum-member",
336        MemberKind::StoreMember => "store-member",
337        MemberKind::NamespaceMember => "namespace-member",
338    }
339}
340
341/// A candidate before its declaration line has been resolved.
342struct LocatedCandidate {
343    file_id: FileId,
344    file: String,
345    symbol: String,
346    member: Option<String>,
347    kind: &'static str,
348    span_start: u32,
349}
350
351/// Per-run state every frame's resolution shares.
352///
353/// The two caches exist because a stack trace repeats itself: a recursive or
354/// deeply nested trace names the same file in frame after frame, and resolving
355/// or reading that file once per frame would turn a bounded question into a
356/// syscall per frame.
357struct TraceContext<'a> {
358    /// The project root as the caller spelled it.
359    root: &'a Path,
360    /// The project root with symlinks resolved, when it could be read.
361    canonical_root: Option<PathBuf>,
362    /// An absolute frame path mapped to its project-root-relative spelling,
363    /// or to `None` when it resolves to nothing inside the project.
364    resolved_paths: FxHashMap<String, Option<String>>,
365    /// A module's line offsets, or `None` when the file could not be read.
366    line_offsets: FxHashMap<FileId, Option<Vec<u32>>>,
367}
368
369impl<'a> TraceContext<'a> {
370    fn new(root: &'a Path) -> Self {
371        Self {
372            root,
373            canonical_root: dunce::canonicalize(root).ok(),
374            resolved_paths: FxHashMap::default(),
375            line_offsets: FxHashMap::default(),
376        }
377    }
378
379    /// The project-root-relative spelling of a frame's file, or `None` when
380    /// the frame path is relative, unreadable, or outside the project root.
381    ///
382    /// This verb is the one command whose input is written by a machine rather
383    /// than typed by a human: the runtime prints the absolute path ITS process
384    /// saw. A project reached through a symlink (macOS `/tmp`, a checkout
385    /// linked into place) therefore prints a prefix no module path carries,
386    /// and comparing that spelling against the canonicalized paths discovery
387    /// stored reports a real project file as out of corpus. Resolving both
388    /// sides once turns it back into the ordinary root-relative comparison.
389    ///
390    /// A path that does not exist is NOT rewritten: it resolves to `None` and
391    /// the frame is compared as the runtime spelled it, so a missing file can
392    /// never be turned into a match on something else.
393    fn root_relative(&mut self, path: &str) -> Option<String> {
394        if !Path::new(path).is_absolute() {
395            return None;
396        }
397        if let Some(cached) = self.resolved_paths.get(path) {
398            return cached.clone();
399        }
400        let resolved = dunce::canonicalize(path).ok().and_then(|canonical| {
401            let root = self.canonical_root.as_deref().unwrap_or(self.root);
402            let relative = canonical.strip_prefix(root).ok()?;
403            Some(relative.to_string_lossy().replace('\\', "/"))
404        });
405        self.resolved_paths
406            .insert(path.to_string(), resolved.clone());
407        resolved
408    }
409}
410
411/// Resolve a parsed stack trace against the module graph.
412#[must_use]
413pub fn resolve_stack_trace(
414    graph: &RetainedModuleGraph,
415    root: &Path,
416    parsed: ParsedStackTrace,
417    source: String,
418) -> ErrorTrace {
419    resolve_with_graph(graph.as_graph(), root, parsed, source)
420}
421
422fn resolve_with_graph(
423    graph: &ModuleGraph,
424    root: &Path,
425    parsed: ParsedStackTrace,
426    source: String,
427) -> ErrorTrace {
428    let ParsedStackTrace {
429        header,
430        frames,
431        unparsed_lines,
432    } = parsed;
433
434    let frames_omitted = frames.len().saturating_sub(MAX_REPORTED_FRAMES);
435    let mut context = TraceContext::new(root);
436    let mut counts = ErrorTraceCounts {
437        frames_omitted,
438        unparsed_lines,
439        ..ErrorTraceCounts::default()
440    };
441
442    let resolved_frames: Vec<ErrorTraceFrame> = frames
443        .into_iter()
444        .take(MAX_REPORTED_FRAMES)
445        .enumerate()
446        .map(|(index, frame)| resolve_frame(graph, &mut context, index, frame))
447        .collect();
448
449    counts.frames = resolved_frames.len();
450    for frame in &resolved_frames {
451        match frame.origin {
452            FrameOrigin::InProject => counts.in_project += 1,
453            FrameOrigin::NodeModules => counts.node_modules += 1,
454            FrameOrigin::OutOfCorpus => counts.out_of_corpus += 1,
455        }
456        match frame.resolution {
457            FrameResolution::Resolved => counts.resolved += 1,
458            FrameResolution::Ambiguous => counts.ambiguous += 1,
459            FrameResolution::NotFound => counts.not_found += 1,
460            FrameResolution::NotAttempted => counts.not_attempted += 1,
461        }
462    }
463
464    let reason = summary_reason(&counts, header.is_some());
465
466    ErrorTrace {
467        schema_version: ErrorTraceSchemaVersion::V1,
468        source,
469        header,
470        reason,
471        frames: resolved_frames,
472        counts,
473    }
474}
475
476/// One sentence stating what the run answered and what it did not.
477///
478/// `has_header` is the count `counts` cannot carry: the first non-blank line of
479/// a frameless input is taken as the error header and reported under `header`,
480/// so it is deliberately absent from `unparsed_lines`. A sentence that claims to
481/// describe the INPUT has to count it back in, or its number contradicts the
482/// lines the caller pasted. The frames branch instead says `further`, because
483/// there the header and the frames are both already reported above it.
484fn summary_reason(counts: &ErrorTraceCounts, has_header: bool) -> String {
485    use std::fmt::Write as _;
486
487    if counts.frames == 0 {
488        let input_lines = counts.unparsed_lines + usize::from(has_header);
489        return if input_lines == 0 {
490            "no stack frames in the input".to_string()
491        } else {
492            format!(
493                "no stack frames recognised in {input_lines} non-blank input {}",
494                plural(input_lines, "line", "lines")
495            )
496        };
497    }
498    let mut reason = format!(
499        "{} {}: {} resolved, {} ambiguous, {} not found, {} not attempted",
500        counts.frames,
501        plural(counts.frames, "frame", "frames"),
502        counts.resolved,
503        counts.ambiguous,
504        counts.not_found,
505        counts.not_attempted
506    );
507    if counts.frames_omitted > 0 {
508        let _ = write!(
509            reason,
510            " ({} further frames omitted)",
511            counts.frames_omitted
512        );
513    }
514    if counts.unparsed_lines > 0 {
515        let _ = write!(
516            reason,
517            "; {} further input {} not recognised as a frame",
518            counts.unparsed_lines,
519            plural(counts.unparsed_lines, "line", "lines")
520        );
521    }
522    reason
523}
524
525fn plural(count: usize, one: &'static str, many: &'static str) -> &'static str {
526    if count == 1 { one } else { many }
527}
528
529/// What asking (or declining to ask) the graph produced for one frame.
530struct FrameOutcome {
531    resolution: FrameResolution,
532    candidates: Vec<ErrorTraceCandidate>,
533    candidates_omitted: usize,
534    line_mismatch: bool,
535    reason: String,
536}
537
538impl FrameOutcome {
539    /// The graph was not consulted, and `reason` says why.
540    fn not_attempted(reason: String) -> Self {
541        Self {
542            resolution: FrameResolution::NotAttempted,
543            candidates: Vec::new(),
544            candidates_omitted: 0,
545            line_mismatch: false,
546            reason,
547        }
548    }
549}
550
551/// Classify one frame and, when it points at project source with an
552/// addressable identifier, ask the graph what that identifier names.
553fn resolve_frame(
554    graph: &ModuleGraph,
555    context: &mut TraceContext<'_>,
556    index: usize,
557    frame: RawFrame,
558) -> ErrorTraceFrame {
559    let (origin, outcome) = classify_and_look_up(graph, context, &frame);
560    let RawFrame {
561        raw,
562        function,
563        is_constructor,
564        is_async,
565        file,
566        line,
567        column,
568    } = frame;
569    ErrorTraceFrame {
570        index,
571        raw,
572        function,
573        is_constructor,
574        is_async,
575        file,
576        line,
577        column,
578        origin,
579        resolution: outcome.resolution,
580        candidates: outcome.candidates,
581        candidates_omitted: outcome.candidates_omitted,
582        line_mismatch: outcome.line_mismatch,
583        reason: outcome.reason,
584    }
585}
586
587/// The four gates a frame passes before the graph is asked anything, in order:
588/// it must carry a location, that location must not be a dependency, it must
589/// match a module, and it must carry an addressable identifier. Failing any one
590/// of them is `not_attempted` with the gate named, never `not_found`.
591fn classify_and_look_up(
592    graph: &ModuleGraph,
593    context: &mut TraceContext<'_>,
594    frame: &RawFrame,
595) -> (FrameOrigin, FrameOutcome) {
596    let Some(path) = frame.file.as_deref() else {
597        return (
598            FrameOrigin::OutOfCorpus,
599            FrameOutcome::not_attempted("frame carries no source location".to_string()),
600        );
601    };
602
603    if has_path_segment(path, DEPENDENCY_SEGMENT) {
604        return (
605            FrameOrigin::NodeModules,
606            FrameOutcome::not_attempted(
607                "frame is in an installed dependency, not in project source".to_string(),
608            ),
609        );
610    }
611
612    // An absolute frame path is resolved to its root-relative spelling FIRST,
613    // and only once, so a symlinked project root does not make every frame
614    // look out of corpus and so the resolution costs one stat rather than one
615    // per module.
616    let resolved = context.root_relative(path).or_else(|| {
617        let (_, location) =
618            v8_frame_parts(&frame.raw).or_else(|| at_sign_frame_parts(&frame.raw))?;
619        if !is_web_location(location) {
620            return None;
621        }
622        // A dev server serves /src/... from the project root.
623        let local = context
624            .canonical_root
625            .as_ref()?
626            .join(path.trim_start_matches('/'));
627        context.root_relative(local.to_str()?)
628    });
629    let match_path = resolved.as_deref().unwrap_or(path);
630    let root = context.root;
631    let module_indexes = matching_module_indexes(graph, root, match_path);
632    if module_indexes.is_empty() {
633        return (
634            FrameOrigin::OutOfCorpus,
635            FrameOutcome::not_attempted(out_of_corpus_reason(path)),
636        );
637    }
638
639    let Some(name) = frame.function.as_deref() else {
640        return (
641            FrameOrigin::InProject,
642            FrameOutcome::not_attempted(
643                "frame carries no function identifier to look up".to_string(),
644            ),
645        );
646    };
647
648    let Some(identifier) = identifier_parts(name) else {
649        return (
650            FrameOrigin::InProject,
651            FrameOutcome::not_attempted(format!("'{name}' is not an addressable identifier")),
652        );
653    };
654
655    (
656        FrameOrigin::InProject,
657        look_up(graph, context, &module_indexes, identifier, frame.line),
658    )
659}
660
661/// Why a frame that matched no module is out of corpus. The generated-output
662/// case is named specifically, because "not in the project" would read as a
663/// missing file when the real answer is "this is the compiled form of a file
664/// that IS in the project, and reading it back needs a source map".
665fn out_of_corpus_reason(path: &str) -> String {
666    if is_runtime_internal(path) {
667        return format!("'{path}' is a runtime internal, not project source");
668    }
669    if BUILD_OUTPUT_SEGMENTS
670        .iter()
671        .any(|segment| has_path_segment(path, segment))
672    {
673        return format!(
674            "'{path}' is generated build output; resolving it back to source needs a source map, which this command does not read"
675        );
676    }
677    format!("'{path}' is not a module in the analysed project")
678}
679
680/// Ask the graph which definitions an identifier names, and turn the answer
681/// into a frame outcome without preferring any one match.
682fn look_up(
683    graph: &ModuleGraph,
684    context: &mut TraceContext<'_>,
685    module_indexes: &[usize],
686    identifier: Identifier<'_>,
687    frame_line: Option<u32>,
688) -> FrameOutcome {
689    let name = identifier.printed;
690    let located = collect_candidates(
691        graph,
692        context.root,
693        module_indexes,
694        identifier.owner,
695        identifier.name,
696    );
697    let total = located.len();
698    let candidates_omitted = total.saturating_sub(MAX_FRAME_CANDIDATES);
699    let single_file_id = located.first().map(|candidate| candidate.file_id);
700    let candidates: Vec<ErrorTraceCandidate> = located
701        .into_iter()
702        .take(MAX_FRAME_CANDIDATES)
703        .map(|candidate| resolve_candidate_line(graph, candidate, &mut context.line_offsets))
704        .collect();
705
706    let mut line_mismatch = false;
707    let (resolution, mut reason) = match total {
708        0 => (
709            FrameResolution::NotFound,
710            format!(
711                "no definition named '{name}' is exported from the module this frame points at; a module-local function is not in the graph's definition set"
712            ),
713        ),
714        1 => {
715            let hit = &candidates[0];
716            let target = hit.member.as_ref().map_or_else(
717                || format!("{}:{}", hit.file, hit.symbol),
718                |member| format!("{}:{}.{member}", hit.file, hit.symbol),
719            );
720            (
721                FrameResolution::Resolved,
722                format!("'{name}' names {target} ({})", hit.kind),
723            )
724        }
725        _ => (
726            FrameResolution::Ambiguous,
727            format!("'{name}' names {total} definitions; none is preferred"),
728        ),
729    };
730
731    // The look-up matches on the identifier alone, so a single match is
732    // reported as `resolved` however far the frame's line sits from it. The
733    // frame's line is checked against the definitions of the file it points
734    // at, and a disagreement is stated rather than silently carried.
735    if resolution == FrameResolution::Resolved
736        && let Some(file_id) = single_file_id
737        && let Some(note) = line_mismatch_note(graph, context, file_id, &candidates[0], frame_line)
738    {
739        line_mismatch = true;
740        reason.push_str(&note);
741    }
742
743    FrameOutcome {
744        resolution,
745        candidates,
746        candidates_omitted,
747        line_mismatch,
748        reason,
749    }
750}
751
752/// Why the frame's own line disagrees with the definition its identifier
753/// matched, or `None` when the two agree or the comparison cannot be made.
754///
755/// The check is the cheapest one that answers the question a reader would ask
756/// next: which definition in this file is declared closest above the line the
757/// runtime reported? When that is the matched definition, the frame's line and
758/// the match tell the same story. When it is a DIFFERENT definition, the
759/// runtime was executing past a declaration the match does not cover, so the
760/// match is more likely a same-named definition elsewhere in the file. The
761/// frame stays `resolved`, because the graph's answer to the question asked is
762/// still correct; only the caller can decide what to do with the disagreement.
763fn line_mismatch_note(
764    graph: &ModuleGraph,
765    context: &mut TraceContext<'_>,
766    file_id: FileId,
767    candidate: &ErrorTraceCandidate,
768    frame_line: Option<u32>,
769) -> Option<String> {
770    let frame_line = frame_line?;
771    let candidate_line = candidate.line?;
772    let nearest = nearest_declaration_at_or_above(graph, context, file_id, frame_line);
773    if nearest
774        .as_ref()
775        .is_some_and(|(name, line)| *line == candidate_line && name == &candidate_label(candidate))
776    {
777        return None;
778    }
779    let matched = candidate_label(candidate);
780    Some(match nearest {
781        Some((name, line)) => format!(
782            "; the frame's line {frame_line} sits after the declaration of '{name}' at line {line}, not after '{matched}' at line {candidate_line}, so verify this is the definition that ran"
783        ),
784        None => format!(
785            "; the frame's line {frame_line} is above every definition this file declares, including '{matched}' at line {candidate_line}, so verify this is the definition that ran"
786        ),
787    })
788}
789
790/// The printed name of a candidate, matching how the frame's identifier reads.
791fn candidate_label(candidate: &ErrorTraceCandidate) -> String {
792    candidate.member.as_ref().map_or_else(
793        || candidate.symbol.clone(),
794        |member| format!("{}.{member}", candidate.symbol),
795    )
796}
797
798/// The definition declared closest at or above `line` in a module, as its
799/// printed name and 1-based declaration line.
800///
801/// Exports and their members are the graph's whole definition set, so this
802/// answers from what the look-up already consulted, using the line offsets the
803/// candidate resolution cached.
804fn nearest_declaration_at_or_above(
805    graph: &ModuleGraph,
806    context: &mut TraceContext<'_>,
807    file_id: FileId,
808    line: u32,
809) -> Option<(String, u32)> {
810    let module = graph.module(file_id)?;
811    let offsets = read_line_offsets(graph, file_id, &mut context.line_offsets)?;
812    let declaration_line =
813        |start: u32| fallow_types::extract::byte_offset_to_line_col(offsets, start).0;
814    // The winner is tracked by position so a losing declaration never pays for
815    // a formatted name.
816    let mut nearest: Option<(usize, Option<usize>, u32)> = None;
817    let mut consider = |export_index: usize, member_index: Option<usize>, declared: u32| {
818        if declared <= line && nearest.is_none_or(|(_, _, best)| declared > best) {
819            nearest = Some((export_index, member_index, declared));
820        }
821    };
822    for (export_index, export) in module.exports.iter().enumerate() {
823        consider(export_index, None, declaration_line(export.span.start));
824        for (member_index, member) in export.members.iter().enumerate() {
825            consider(
826                export_index,
827                Some(member_index),
828                declaration_line(member.span.start),
829            );
830        }
831    }
832
833    let (export_index, member_index, declared) = nearest?;
834    let export = module.exports.get(export_index)?;
835    let name = match member_index.and_then(|index| export.members.get(index)) {
836        Some(member) => format!("{}.{}", export.name, member.name),
837        None => export.name.to_string(),
838    };
839    Some((name, declared))
840}
841
842/// A module's line offsets, computed at most once per trace.
843fn read_line_offsets<'a>(
844    graph: &ModuleGraph,
845    file_id: FileId,
846    line_offsets: &'a mut FxHashMap<FileId, Option<Vec<u32>>>,
847) -> Option<&'a Vec<u32>> {
848    line_offsets
849        .entry(file_id)
850        .or_insert_with(|| {
851            graph
852                .modules()
853                .get(file_id.0 as usize)
854                .and_then(|module| std::fs::read_to_string(&module.path).ok())
855                .map(|source| fallow_types::extract::compute_line_offsets(&source))
856        })
857        .as_ref()
858}
859
860/// Every definition the frame's identifier could name, deterministically
861/// ordered and deduplicated.
862///
863/// Two rules run, and both are reported when both hit. An export whose name
864/// equals the frame's last segment is a candidate because V8 prints a synthetic
865/// receiver (`Object.run`) for a plain function; a member of an export named by
866/// the second-to-last segment is a candidate because that is what `Task.run`
867/// literally reads as. Choosing between them is the caller's judgment, not this
868/// command's.
869fn collect_candidates(
870    graph: &ModuleGraph,
871    root: &Path,
872    module_indexes: &[usize],
873    owner: Option<&str>,
874    name: &str,
875) -> Vec<LocatedCandidate> {
876    let mut candidates: Vec<LocatedCandidate> = Vec::new();
877    for &index in module_indexes {
878        let Some(module) = graph.modules().get(index) else {
879            continue;
880        };
881        let file = relativize(&module.path, root);
882        for export in &module.exports {
883            if export.name.matches_str(name) {
884                candidates.push(LocatedCandidate {
885                    file_id: module.file_id,
886                    file: file.clone(),
887                    symbol: export.name.to_string(),
888                    member: None,
889                    kind: "export",
890                    span_start: export.span.start,
891                });
892            }
893            if owner.is_some_and(|owner| export.name.matches_str(owner)) {
894                for member in &export.members {
895                    if member.name == name {
896                        candidates.push(LocatedCandidate {
897                            file_id: module.file_id,
898                            file: file.clone(),
899                            symbol: export.name.to_string(),
900                            member: Some(member.name.clone()),
901                            kind: member_kind_label(member.kind),
902                            span_start: member.span.start,
903                        });
904                    }
905                }
906            }
907        }
908    }
909    candidates.sort_by(|left, right| {
910        left.file
911            .cmp(&right.file)
912            .then_with(|| left.symbol.cmp(&right.symbol))
913            .then_with(|| left.member.cmp(&right.member))
914    });
915    candidates.dedup_by(|left, right| {
916        left.file == right.file && left.symbol == right.symbol && left.member == right.member
917    });
918    candidates
919}
920
921/// Turn a candidate's declaration span into a 1-based line, reading each source
922/// file at most once per trace. A file that cannot be read yields no line
923/// rather than a guessed one.
924fn resolve_candidate_line(
925    graph: &ModuleGraph,
926    candidate: LocatedCandidate,
927    line_offsets: &mut FxHashMap<FileId, Option<Vec<u32>>>,
928) -> ErrorTraceCandidate {
929    let line = read_line_offsets(graph, candidate.file_id, line_offsets).map(|offsets| {
930        fallow_types::extract::byte_offset_to_line_col(offsets, candidate.span_start).0
931    });
932    ErrorTraceCandidate {
933        file: candidate.file,
934        symbol: candidate.symbol,
935        member: candidate.member,
936        kind: candidate.kind.to_string(),
937        line,
938    }
939}
940
941/// Resolve a stack trace through an existing analysis session.
942///
943/// # Errors
944///
945/// Returns an error if parsing or graph construction fails.
946pub fn trace_error_with_session(
947    session: &crate::session::AnalysisSession,
948    input: &str,
949    source: String,
950) -> crate::EngineResult<ErrorTrace> {
951    let output = session.analyze_dead_code_with_shared_artifacts(false, true)?;
952    let graph = output
953        .graph
954        .as_ref()
955        .ok_or_else(|| crate::EngineError::new("trace-error requires a retained module graph"))?;
956    Ok(resolve_stack_trace(
957        graph,
958        session.root(),
959        parse_stack_trace(input),
960        source,
961    ))
962}
963
964#[cfg(test)]
965mod tests {
966    use super::*;
967
968    fn frames(input: &str) -> Vec<RawFrame> {
969        parse_stack_trace(input).frames
970    }
971
972    #[test]
973    fn reads_the_v8_frame_forms() {
974        let parsed = parse_stack_trace(
975            "TypeError: user.load is not a function\n\
976             \x20   at loadUser (/proj/src/services/user.ts:42:11)\n\
977             \x20   at async UserService.load (/proj/src/user.ts:10:3)\n\
978             \x20   at new Widget (/proj/src/widget.tsx:5:9)\n\
979             \x20   at /proj/src/bare.ts:7:2\n",
980        );
981
982        assert_eq!(
983            parsed.header.as_deref(),
984            Some("TypeError: user.load is not a function")
985        );
986        assert_eq!(parsed.unparsed_lines, 0);
987        assert_eq!(parsed.frames.len(), 4);
988
989        assert_eq!(parsed.frames[0].function.as_deref(), Some("loadUser"));
990        assert_eq!(
991            parsed.frames[0].file.as_deref(),
992            Some("/proj/src/services/user.ts")
993        );
994        assert_eq!(parsed.frames[0].line, Some(42));
995        assert_eq!(parsed.frames[0].column, Some(11));
996
997        assert_eq!(
998            parsed.frames[1].function.as_deref(),
999            Some("UserService.load")
1000        );
1001        assert!(parsed.frames[1].is_async);
1002        assert!(!parsed.frames[1].is_constructor);
1003
1004        assert_eq!(parsed.frames[2].function.as_deref(), Some("Widget"));
1005        assert!(parsed.frames[2].is_constructor);
1006
1007        assert_eq!(parsed.frames[3].function, None);
1008        assert_eq!(parsed.frames[3].file.as_deref(), Some("/proj/src/bare.ts"));
1009        assert_eq!(parsed.frames[3].line, Some(7));
1010    }
1011
1012    #[test]
1013    fn reads_the_at_sign_frame_form() {
1014        let parsed = parse_stack_trace(
1015            "loadUser@/proj/src/user.ts:42:11\n@/proj/src/index.ts:3:1\nboot@https://app.test/assets/main.js:1:20\n",
1016        );
1017
1018        assert_eq!(parsed.frames.len(), 3);
1019        assert_eq!(parsed.frames[0].function.as_deref(), Some("loadUser"));
1020        assert_eq!(parsed.frames[0].file.as_deref(), Some("/proj/src/user.ts"));
1021        assert_eq!(parsed.frames[0].line, Some(42));
1022        assert_eq!(parsed.frames[1].function, None);
1023        assert_eq!(
1024            parsed.frames[2].file.as_deref(),
1025            Some("/assets/main.js"),
1026            "an http location keeps its path component and drops the authority"
1027        );
1028    }
1029
1030    #[test]
1031    fn a_line_with_a_stray_at_sign_is_not_a_frame() {
1032        let parsed = parse_stack_trace("reported by dev@example.com\n");
1033
1034        assert!(parsed.frames.is_empty());
1035        assert_eq!(
1036            parsed.header.as_deref(),
1037            Some("reported by dev@example.com")
1038        );
1039        assert_eq!(parsed.unparsed_lines, 0);
1040    }
1041
1042    #[test]
1043    fn unrecognised_lines_are_counted_never_dropped() {
1044        let parsed = parse_stack_trace("Error: boom\nnot a frame\nalso not a frame\n");
1045
1046        assert!(parsed.frames.is_empty());
1047        assert_eq!(parsed.header.as_deref(), Some("Error: boom"));
1048        assert_eq!(parsed.unparsed_lines, 2);
1049    }
1050
1051    #[test]
1052    fn an_empty_input_parses_to_nothing() {
1053        let parsed = parse_stack_trace("");
1054
1055        assert_eq!(parsed, ParsedStackTrace::default());
1056    }
1057
1058    #[test]
1059    fn the_frameless_reason_counts_the_header_line_it_describes() {
1060        // Three non-blank lines in, none of them a frame: the first is taken as
1061        // the header and reported separately, so `unparsed_lines` is 2. A
1062        // sentence about the INPUT must still say three, or its number
1063        // contradicts what the caller pasted.
1064        let parsed = parse_stack_trace("something went wrong\nsee the logs\nand the dashboard\n");
1065        assert_eq!(parsed.unparsed_lines, 2);
1066        let counts = ErrorTraceCounts {
1067            unparsed_lines: parsed.unparsed_lines,
1068            ..ErrorTraceCounts::default()
1069        };
1070
1071        assert_eq!(
1072            summary_reason(&counts, parsed.header.is_some()),
1073            "no stack frames recognised in 3 non-blank input lines"
1074        );
1075    }
1076
1077    #[test]
1078    fn a_single_unrecognised_line_is_reported_as_one_input_line() {
1079        let parsed = parse_stack_trace("something went wrong\n");
1080        assert_eq!(parsed.unparsed_lines, 0);
1081        let counts = ErrorTraceCounts {
1082            unparsed_lines: parsed.unparsed_lines,
1083            ..ErrorTraceCounts::default()
1084        };
1085
1086        assert_eq!(
1087            summary_reason(&counts, parsed.header.is_some()),
1088            "no stack frames recognised in 1 non-blank input line"
1089        );
1090    }
1091
1092    #[test]
1093    fn an_input_with_no_lines_at_all_still_reads_as_empty() {
1094        let counts = ErrorTraceCounts::default();
1095
1096        assert_eq!(
1097            summary_reason(&counts, false),
1098            "no stack frames in the input"
1099        );
1100    }
1101
1102    #[test]
1103    fn the_frame_reason_marks_unparsed_lines_as_further_than_what_it_listed() {
1104        // With frames present the header and the frames are already reported
1105        // above the sentence, so the trailing count is explicitly the remainder
1106        // rather than a second claim about the whole input.
1107        let counts = ErrorTraceCounts {
1108            frames: 1,
1109            resolved: 1,
1110            unparsed_lines: 2,
1111            ..ErrorTraceCounts::default()
1112        };
1113
1114        assert_eq!(
1115            summary_reason(&counts, true),
1116            "1 frame: 1 resolved, 0 ambiguous, 0 not found, 0 not attempted; \
1117             2 further input lines not recognised as a frame"
1118        );
1119    }
1120
1121    #[test]
1122    fn a_native_or_anonymous_location_carries_no_path() {
1123        let parsed = frames("    at doThing (native)\n    at Array.forEach (<anonymous>)\n");
1124
1125        assert_eq!(parsed.len(), 2);
1126        assert_eq!(parsed[0].file, None);
1127        assert_eq!(parsed[0].line, None);
1128        assert_eq!(parsed[1].file, None);
1129    }
1130
1131    #[test]
1132    fn a_file_url_keeps_a_windows_drive_letter() {
1133        let parsed = frames(
1134            "    at run (file:///C:/proj/src/a.ts:3:4)\n    at run (file:///proj/src/b.ts:5:6)\n",
1135        );
1136
1137        assert_eq!(parsed[0].file.as_deref(), Some("C:/proj/src/a.ts"));
1138        assert_eq!(parsed[0].line, Some(3));
1139        assert_eq!(parsed[1].file.as_deref(), Some("/proj/src/b.ts"));
1140    }
1141
1142    #[test]
1143    fn a_backslash_windows_path_is_forward_slashed_and_keeps_its_numbers() {
1144        let parsed = frames("    at run (C:\\proj\\src\\a.ts:12:4)\n");
1145
1146        assert_eq!(parsed[0].file.as_deref(), Some("C:/proj/src/a.ts"));
1147        assert_eq!(parsed[0].line, Some(12));
1148        assert_eq!(parsed[0].column, Some(4));
1149    }
1150
1151    #[test]
1152    fn a_node_internal_frame_keeps_its_scheme() {
1153        let parsed = frames(
1154            "    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n",
1155        );
1156
1157        assert_eq!(
1158            parsed[0].file.as_deref(),
1159            Some("node:internal/process/task_queues")
1160        );
1161        assert!(is_runtime_internal("node:internal/process/task_queues"));
1162    }
1163
1164    #[test]
1165    fn a_location_without_a_column_puts_its_number_on_the_line() {
1166        let parsed = frames("    at run (/proj/src/a.ts:12)\n");
1167
1168        assert_eq!(parsed[0].file.as_deref(), Some("/proj/src/a.ts"));
1169        assert_eq!(parsed[0].line, Some(12));
1170        assert_eq!(parsed[0].column, None);
1171    }
1172
1173    #[test]
1174    fn identifier_parts_split_on_the_last_dot() {
1175        let parts = |name| identifier_parts(name).map(|id| (id.owner, id.name));
1176        assert_eq!(parts("run"), Some((None, "run")));
1177        assert_eq!(parts("Task.run"), Some((Some("Task"), "run")));
1178        assert_eq!(parts("ns.Task.run"), Some((Some("Task"), "run")));
1179    }
1180
1181    #[test]
1182    fn identifier_parts_reject_non_addressable_names() {
1183        for name in [
1184            "Object.<anonymous>",
1185            "outer/<",
1186            "global code",
1187            "Task..run",
1188            "",
1189        ] {
1190            assert_eq!(identifier_parts(name), None, "name was {name:?}");
1191        }
1192    }
1193
1194    #[test]
1195    fn an_absolute_frame_path_resolves_through_a_symlinked_root() {
1196        let dir = tempfile::tempdir().expect("tempdir");
1197        let real = dir.path().join("real/src");
1198        std::fs::create_dir_all(&real).expect("project dirs");
1199        std::fs::write(real.join("index.ts"), "export const run = () => 0;\n").expect("source");
1200        let linked = dir.path().join("linked");
1201        #[cfg(unix)]
1202        std::os::unix::fs::symlink(dir.path().join("real"), &linked).expect("symlink");
1203        #[cfg(windows)]
1204        std::os::windows::fs::symlink_dir(dir.path().join("real"), &linked).expect("symlink");
1205
1206        let root = dir.path().join("real");
1207        let mut context = TraceContext::new(&root);
1208        let frame = linked
1209            .join("src/index.ts")
1210            .to_string_lossy()
1211            .replace('\\', "/");
1212
1213        assert_eq!(
1214            context.root_relative(&frame).as_deref(),
1215            Some("src/index.ts"),
1216            "a frame spelled through a symlink must resolve to the module's own \
1217             root-relative path"
1218        );
1219    }
1220
1221    #[test]
1222    fn a_relative_or_missing_frame_path_is_never_rewritten() {
1223        let dir = tempfile::tempdir().expect("tempdir");
1224        let mut context = TraceContext::new(dir.path());
1225
1226        assert_eq!(context.root_relative("src/index.ts"), None);
1227        assert_eq!(
1228            context
1229                .root_relative(&dir.path().join("gone.ts").to_string_lossy())
1230                .as_deref(),
1231            None,
1232            "a path that does not exist resolves to nothing rather than to \
1233             something else"
1234        );
1235    }
1236
1237    #[test]
1238    fn path_segment_matching_is_component_wise() {
1239        assert!(has_path_segment(
1240            "/proj/node_modules/x/index.js",
1241            "node_modules"
1242        ));
1243        assert!(!has_path_segment(
1244            "/proj/my_node_modules_shim/a.js",
1245            "node_modules"
1246        ));
1247        assert!(has_path_segment("/proj/dist/main.js", "dist"));
1248        assert!(!has_path_segment("/proj/src/distance.ts", "dist"));
1249    }
1250}