Skip to main content

artifactize_core/config/
lang.rs

1//! The `.artf` language: `artf` bindings with their `eval`s, `tool` sets composed with `&`,
2//! `artf!` macros and typed `@{…}` slots; and `.artfprofiles` files, whose profiles say how
3//! Agent evals run, each branch chosen by the environment. Every file of a project shares one
4//! scope; reading resolves names in two passes, so declaration order is free, and expands
5//! macros into plain Artifacts without running anything.
6
7pub(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/// Where a definition file comes from: the project's `.artifactize/`, or a plugin, whose
22/// files may declare only its toolset and macros.
23#[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    /// Workspace-relative for project files; `plugins/<namespace>/…` for plugin files.
38    pub path: PathBuf,
39    pub text: String,
40    pub origin: Origin,
41}
42
43/// The extension of a file of profiles.
44pub(crate) const PROFILES_EXTENSION: &str = "artfprofiles";
45
46impl SourceFile {
47    /// Whether it holds profiles rather than declarations.
48    pub(crate) fn holds_profiles(&self) -> bool {
49        self.path
50            .extension()
51            .is_some_and(|extension| extension == PROFILES_EXTENSION)
52    }
53}
54
55/// Every file read together, so spans can be shown as `file: line, column`.
56#[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    /// `line L, column C` of a span's start.
80    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    /// The whole lines a span covers, for showing a declaration as written.
93    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/// A diagnostic at one span, with notes at others: a macro's call site, or the other side of
122/// a duplicate.
123#[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/// What reading a project produces: its Artifacts, expanded, and its profiles, each in the
146/// branch the environment selects.
147#[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    /// The environment variables the profiles read, each with its value.
153    pub environment: BTreeMap<String, Option<String>>,
154    pub symbols: Vec<Symbol>,
155    /// Every span that names an Artifact: its bindings, the names it is listed by and the
156    /// slots that name it, each once.
157    pub names: Vec<(Span, String)>,
158}
159
160/// A global binding, for `config symbols`.
161#[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
183/// Parse and expand every file, choosing each profile's branch by `environment`. A file that
184/// fails to parse names its own position.
185pub(crate) fn read(
186    files: Vec<SourceFile>,
187    environment: Environment<'_>,
188) -> Result<Program, (Arc<Sources>, LangError)> {
189    let sources = Arc::new(Sources::new(files));
190    let mut parsed = Vec::new();
191    let mut profiles = Vec::new();
192    for (id, file) in sources.ids() {
193        let failed =
194            |error: parse::ParseError| (sources.clone(), LangError::new(error.span, error.message));
195        if file.holds_profiles() {
196            profiles.push((id, parse::parse_profiles(id, &file.text).map_err(failed)?));
197        } else {
198            parsed.push((id, parse::parse(id, &file.text).map_err(failed)?));
199        }
200    }
201    let expanded = expand::expand(&sources, &parsed, &profiles, environment)
202        .map_err(|error| (sources.clone(), error))?;
203    Ok(Program {
204        sources,
205        artifacts: expanded.artifacts,
206        profiles: expanded.profiles,
207        environment: expanded.environment,
208        symbols: expanded.symbols,
209        names: expanded.names,
210    })
211}
212
213/// The process environment, as a project's profiles read it.
214pub(crate) fn process_environment(name: &str) -> Option<String> {
215    crate::platform::environment::var_text(name)
216}
217
218/// Whether a project file is written in the language at all, or is an older TOML definition
219/// that `config migrate` converts.
220pub(crate) fn looks_like_toml(text: &str) -> bool {
221    text.lines()
222        .map(str::trim)
223        .find(|line| !line.is_empty() && !line.starts_with('#') && !line.starts_with("//"))
224        .is_some_and(|line| {
225            line.starts_with('[')
226                || line
227                    .split_once('=')
228                    .is_some_and(|(key, _)| !key.trim().contains(' ') && !key.trim().is_empty())
229                    && !["artf", "tool", "profile"]
230                        .iter()
231                        .any(|keyword| line.starts_with(keyword))
232        })
233}
234
235/// The span of the part of an Artifact's declaration that `keys` names, or its binding.
236pub(crate) fn span_of(artifact: &LoweredArtifact, keys: &[&str]) -> Span {
237    let eval = |id: &str| artifact.evals.iter().find(|eval| eval.id == id);
238    match keys {
239        ["path", ..] => artifact.path.1,
240        ["name", ..] => artifact.name_span,
241        ["parts", ..] => artifact
242            .parts
243            .first()
244            .map_or(artifact.binding, |part| part.1),
245        ["select", ..] => artifact
246            .select
247            .as_ref()
248            .map_or(artifact.binding, |select| select.1),
249        ["fingerprint", ..] => artifact.fingerprint.1.unwrap_or(artifact.binding),
250        ["tools"] | ["views"] => artifact
251            .tools
252            .as_ref()
253            .map_or(artifact.binding, |tools| tools.1),
254        ["views", table, tool, ..] => {
255            let audience = match *table {
256                "human_tools" => "human",
257                "agent_sessions" => "session",
258                _ => "agent",
259            };
260            artifact
261                .tool_spans
262                .get(&format!("{audience}.{tool}"))
263                .copied()
264                .or(artifact.tools.as_ref().map(|tools| tools.1))
265                .unwrap_or(artifact.binding)
266        }
267        ["evals", id, rest @ ..] => eval(id).map_or(artifact.binding, |eval| match rest {
268            ["instruction" | "payload", ..] => eval
269                .instruction
270                .as_ref()
271                .map_or(eval.id_span, |instruction| instruction.1),
272            ["profile", ..] => eval.profile_span,
273            ["inputs" | "deps", ..] => eval.deps.first().map_or(eval.id_span, |dep| dep.1),
274            _ => eval.id_span,
275        }),
276        _ => artifact.name_span,
277    }
278}