1use 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
33pub const MAX_STACK_TRACE_BYTES: u64 = 1024 * 1024;
38
39const MAX_REPORTED_FRAMES: usize = 256;
43
44const MAX_FRAME_CANDIDATES: usize = 10;
48
49const BUILD_OUTPUT_SEGMENTS: &[&str] = &["dist", "build", "out", ".next"];
53
54const DEPENDENCY_SEGMENT: &str = "node_modules";
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct RawFrame {
60 pub raw: String,
62 pub function: Option<String>,
65 pub is_constructor: bool,
67 pub is_async: bool,
69 pub file: Option<String>,
71 pub line: Option<u32>,
73 pub column: Option<u32>,
75}
76
77#[derive(Debug, Clone, Default, PartialEq, Eq)]
79pub struct ParsedStackTrace {
80 pub header: Option<String>,
82 pub frames: Vec<RawFrame>,
84 pub unparsed_lines: usize,
86}
87
88#[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
114fn parse_frame(trimmed: &str) -> Option<RawFrame> {
116 parse_v8_frame(trimmed).or_else(|| parse_at_sign_frame(trimmed))
117}
118
119fn 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 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
168fn 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
188fn named_function(name: &str) -> Option<String> {
190 if name.is_empty() || name == "<anonymous>" {
191 return None;
192 }
193 Some(name.to_string())
194}
195
196fn 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 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
219fn 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
233fn 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
265fn 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
274fn has_path_segment(path: &str, segment: &str) -> bool {
276 path.split('/').any(|component| component == segment)
277}
278
279fn is_runtime_internal(path: &str) -> bool {
281 path.starts_with("node:") || path.starts_with("internal/")
282}
283
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286struct Identifier<'a> {
287 printed: &'a str,
289 owner: Option<&'a str>,
292 name: &'a str,
294}
295
296fn 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
330const 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
341struct 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
351struct TraceContext<'a> {
358 root: &'a Path,
360 canonical_root: Option<PathBuf>,
362 resolved_paths: FxHashMap<String, Option<String>>,
365 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 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#[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
476fn 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
529struct FrameOutcome {
531 resolution: FrameResolution,
532 candidates: Vec<ErrorTraceCandidate>,
533 candidates_omitted: usize,
534 line_mismatch: bool,
535 reason: String,
536}
537
538impl FrameOutcome {
539 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
551fn 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
587fn 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 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 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
661fn 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
680fn 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 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(¬e);
741 }
742
743 FrameOutcome {
744 resolution,
745 candidates,
746 candidates_omitted,
747 line_mismatch,
748 reason,
749 }
750}
751
752fn 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
790fn 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
798fn 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 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
842fn 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
860fn 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
921fn 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
941pub 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 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 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}