1pub(crate) mod ast;
8mod expand;
9mod parse;
10pub(crate) mod render;
11mod scope;
12mod values;
13
14use std::{collections::BTreeMap, path::PathBuf, sync::Arc};
15
16pub(crate) use ast::{FileId, Span};
17pub(crate) use expand::{
18 Environment, LoweredArtifact, LoweredEval, LoweredFingerprint, Piece, SlotRef, SlotTarget,
19};
20
21#[derive(Debug, Clone, PartialEq, Eq)]
24pub(crate) enum Origin {
25 Project,
26 Plugin(PluginSource),
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub(crate) struct PluginSource {
31 pub namespace: String,
32 pub viewer: bool,
33}
34
35#[derive(Debug, Clone)]
36pub(crate) struct SourceFile {
37 pub path: PathBuf,
39 pub text: String,
40 pub origin: Origin,
41}
42
43pub(crate) const PROFILES_EXTENSION: &str = "artfprofiles";
45
46impl SourceFile {
47 pub(crate) fn holds_profiles(&self) -> bool {
49 self.path
50 .extension()
51 .is_some_and(|extension| extension == PROFILES_EXTENSION)
52 }
53}
54
55#[derive(Debug, Clone, Default)]
57pub struct Sources {
58 files: Vec<SourceFile>,
59}
60
61impl Sources {
62 pub(crate) fn new(files: Vec<SourceFile>) -> Self {
63 Self { files }
64 }
65
66 pub(crate) fn file(&self, id: FileId) -> &SourceFile {
67 &self.files[id.0 as usize]
68 }
69
70 pub(crate) fn ids(&self) -> impl Iterator<Item = (FileId, &SourceFile)> {
71 self.files.iter().enumerate().map(|(index, file)| {
72 (
73 FileId(u32::try_from(index).expect("fewer than 2^32 files")),
74 file,
75 )
76 })
77 }
78
79 pub(crate) fn line_column(&self, span: Span) -> (usize, usize) {
81 let text = &self.file(span.file).text;
82 let prefix = &text[..(span.start as usize).min(text.len())];
83 let line = prefix.bytes().filter(|byte| *byte == b'\n').count() + 1;
84 let column = prefix.rsplit('\n').next().unwrap_or("").chars().count() + 1;
85 (line, column)
86 }
87
88 pub(crate) fn text(&self, span: Span) -> &str {
89 &self.file(span.file).text[span.range()]
90 }
91
92 pub(crate) fn lines(&self, span: Span) -> (usize, &str) {
94 let text = &self.file(span.file).text;
95 let start = text[..span.start as usize]
96 .rfind('\n')
97 .map_or(0, |index| index + 1);
98 let end = text[span.end as usize..]
99 .find('\n')
100 .map_or(text.len(), |index| span.end as usize + index);
101 (self.line_column(span).0, &text[start..end])
102 }
103
104 pub(crate) fn error(&self, error: LangError) -> super::ConfigError {
105 let mut message = self.positioned(error.span, &error.message);
106 for (span, note) in &error.notes {
107 message.push_str("\n note: ");
108 message.push_str(&crate::platform::path_text(&self.file(span.file).path));
109 message.push_str(": ");
110 message.push_str(&self.positioned(*span, note));
111 }
112 super::ConfigError::new(self.file(error.span.file).path.clone(), message)
113 }
114
115 fn positioned(&self, span: Span, message: &str) -> String {
116 let (line, column) = self.line_column(span);
117 format!("line {line}, column {column}: {message}")
118 }
119}
120
121#[derive(Debug, Clone, PartialEq, Eq)]
124pub(crate) struct LangError {
125 pub span: Span,
126 pub message: String,
127 pub notes: Vec<(Span, String)>,
128}
129
130impl LangError {
131 pub fn new(span: Span, message: impl Into<String>) -> Self {
132 Self {
133 span,
134 message: message.into(),
135 notes: Vec::new(),
136 }
137 }
138
139 pub fn note(mut self, span: Span, note: impl Into<String>) -> Self {
140 self.notes.push((span, note.into()));
141 self
142 }
143}
144
145#[derive(Debug, Clone)]
148pub(crate) struct Program {
149 pub sources: Arc<Sources>,
150 pub artifacts: Vec<LoweredArtifact>,
151 pub profiles: BTreeMap<String, (super::Profile, Span)>,
152 pub environment: BTreeMap<String, Option<String>>,
154 pub symbols: Vec<Symbol>,
155 pub names: Vec<(Span, String)>,
158}
159
160#[derive(Debug, Clone, serde::Serialize)]
162#[serde(rename_all = "camelCase")]
163pub struct Symbol {
164 pub kind: &'static str,
165 pub name: String,
166 #[serde(rename = "macro")]
167 pub is_macro: bool,
168 #[serde(skip_serializing_if = "Option::is_none")]
169 pub params: Option<Vec<SymbolParam>>,
170 #[serde(serialize_with = "crate::platform::path_serde::serialize")]
171 pub file: PathBuf,
172 pub line: usize,
173 #[serde(skip_serializing_if = "Option::is_none")]
174 pub plugin: Option<String>,
175}
176
177#[derive(Debug, Clone, serde::Serialize)]
178pub struct SymbolParam {
179 pub name: String,
180 pub default: Option<String>,
181}
182
183pub(crate) fn read(
186 files: Vec<SourceFile>,
187 environment: Environment<'_>,
188) -> Result<Program, (Arc<Sources>, LangError)> {
189 read_selected(files, environment, None)
190}
191
192pub(crate) fn read_selected(
194 files: Vec<SourceFile>,
195 environment: Environment<'_>,
196 names: Option<&std::collections::BTreeSet<super::ArtifactName>>,
197) -> Result<Program, (Arc<Sources>, LangError)> {
198 let sources = Arc::new(Sources::new(files));
199 let mut parsed = Vec::new();
200 let mut profiles = Vec::new();
201 for (id, file) in sources.ids() {
202 let failed =
203 |error: parse::ParseError| (sources.clone(), LangError::new(error.span, error.message));
204 if file.holds_profiles() {
205 profiles.push((id, parse::parse_profiles(id, &file.text).map_err(failed)?));
206 } else {
207 parsed.push((id, parse::parse(id, &file.text).map_err(failed)?));
208 }
209 }
210 let expanded = expand::expand(&sources, &parsed, &profiles, environment, names)
211 .map_err(|error| (sources.clone(), error))?;
212 Ok(Program {
213 sources,
214 artifacts: expanded.artifacts,
215 profiles: expanded.profiles,
216 environment: expanded.environment,
217 symbols: expanded.symbols,
218 names: expanded.names,
219 })
220}
221
222pub(crate) fn process_environment(name: &str) -> Option<String> {
224 crate::platform::environment::var_text(name)
225}
226
227pub(crate) fn looks_like_toml(text: &str) -> bool {
230 text.lines()
231 .map(str::trim)
232 .find(|line| !line.is_empty() && !line.starts_with('#') && !line.starts_with("//"))
233 .is_some_and(|line| {
234 line.starts_with('[')
235 || line
236 .split_once('=')
237 .is_some_and(|(key, _)| !key.trim().contains(' ') && !key.trim().is_empty())
238 && !["artf", "tool", "profile"]
239 .iter()
240 .any(|keyword| line.starts_with(keyword))
241 })
242}
243
244pub(crate) fn span_of(artifact: &LoweredArtifact, keys: &[&str]) -> Span {
246 let eval = |id: &str| artifact.evals.iter().find(|eval| eval.id == id);
247 match keys {
248 ["path", ..] => artifact.path.1,
249 ["name", ..] => artifact.name_span,
250 ["parts", ..] => artifact
251 .parts
252 .first()
253 .map_or(artifact.binding, |part| part.1),
254 ["select", ..] => artifact
255 .select
256 .as_ref()
257 .map_or(artifact.binding, |select| select.1),
258 ["fingerprint", ..] => artifact.fingerprint.1.unwrap_or(artifact.binding),
259 ["tools"] | ["views"] => artifact
260 .tools
261 .as_ref()
262 .map_or(artifact.binding, |tools| tools.1),
263 ["views", table, tool, ..] => {
264 let audience = match *table {
265 "human_tools" => "human",
266 "agent_sessions" => "session",
267 _ => "agent",
268 };
269 artifact
270 .tool_spans
271 .get(&format!("{audience}.{tool}"))
272 .copied()
273 .or(artifact.tools.as_ref().map(|tools| tools.1))
274 .unwrap_or(artifact.binding)
275 }
276 ["evals", id, rest @ ..] => eval(id).map_or(artifact.binding, |eval| match rest {
277 ["instruction" | "payload", ..] => eval
278 .instruction
279 .as_ref()
280 .map_or(eval.id_span, |instruction| instruction.1),
281 ["profile", ..] => eval.profile_span,
282 ["inputs" | "deps", ..] => eval.deps.first().map_or(eval.id_span, |dep| dep.1),
283 _ => eval.id_span,
284 }),
285 _ => artifact.name_span,
286 }
287}