1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
use std::ops::Range;
use anyhow::{anyhow, Ok, Result};
use ariadne::{Color, Label, Report, ReportBuilder, ReportKind, Source};
use super::{Context, Declaration, Frame};
use crate::ast::ast_fold::*;
use crate::ast::*;
use crate::error::Span;
pub fn label_references(nodes: &[Node], context: &Context, source_id: String, source: String) {
let mut report = Report::build(ReportKind::Custom("Info", Color::Blue), &source_id, 0);
let source = Source::from(source);
let mut labeler = Labeler {
context,
source: &source,
source_id: &source_id,
report: &mut report,
};
labeler.fold_nodes(nodes.to_owned()).unwrap();
report.finish().print((source_id, source)).unwrap();
}
struct Labeler<'a> {
context: &'a Context,
source: &'a Source,
source_id: &'a str,
report: &'a mut ReportBuilder<(String, Range<usize>)>,
}
impl<'a> AstFold for Labeler<'a> {
fn fold_node(&mut self, node: Node) -> Result<Node> {
if let Some(declared_at) = node.declared_at {
let (declaration, span) = &self.context.declarations.0[declared_at];
let message = if let Some(span) = span {
let span = self.source.get_line_range(&Range::from(*span));
if span.len() <= 1 {
format!("[{declared_at}] {declaration} at line {}", span.start + 1)
} else {
format!(
"[{declared_at}] {declaration} at lines {}-{}",
span.start + 1,
span.end
)
}
} else {
declaration.to_string()
};
let color = match declaration {
Declaration::Expression(_) => Color::Blue,
Declaration::ExternRef { .. } => Color::Cyan,
Declaration::Table { .. } => Color::Magenta,
Declaration::Function(_) => Color::Yellow,
};
if let Some(span) = node.span {
self.report.add_label(
Label::new((self.source_id.to_string(), Range::from(span)))
.with_message(message)
.with_color(color),
);
}
}
Ok(self.fold_item(node.item)?.into())
}
}
pub fn collect_frames(nodes: Vec<Node>) -> Vec<(Span, Frame)> {
let mut collector = FrameCollector { frames: vec![] };
collector.fold_nodes(nodes).unwrap();
collector.frames
}
struct FrameCollector {
frames: Vec<(Span, Frame)>,
}
impl AstFold for FrameCollector {
fn fold_table(&mut self, table: Table) -> Result<Table> {
Ok(table)
}
fn fold_pipeline(&mut self, pipeline: Pipeline) -> Result<Pipeline> {
let mut frame = Frame::default();
for node in &pipeline.nodes {
let transform = (node.item)
.as_transform()
.ok_or_else(|| anyhow!("plain function in pipeline"))?;
frame.apply_transform(transform)?;
self.frames.push((node.span.unwrap(), frame.clone()));
}
Ok(pipeline)
}
fn fold_func_def(&mut self, function: FuncDef) -> Result<FuncDef> {
fold_func_def(self, function)
}
}