1use std::ops::Range;
6
7pub const MAX_IDENTIFIER_BYTES: usize = 64;
9
10#[derive(Debug, Clone, PartialEq)]
11pub struct Token {
12 pub kind: Kind,
13 pub span: Range<usize>,
14}
15
16#[derive(Debug, Clone, PartialEq)]
17pub enum Kind {
18 Ident(String),
19 Number(String),
21 Str(Literal),
22 LBrace,
23 RBrace,
24 LParen,
25 RParen,
26 LBracket,
27 RBracket,
28 Eq,
29 Comma,
30 Colon,
31 Amp,
32 Bang,
33 Dot,
34 Spread,
35 Arrow,
37}
38
39impl Kind {
40 pub fn describe(&self) -> String {
42 match self {
43 Self::Ident(name) => format!("`{name}`"),
44 Self::Number(number) => format!("number {number}"),
45 Self::Str(_) => "a string".into(),
46 Self::LBrace => "`{`".into(),
47 Self::RBrace => "`}`".into(),
48 Self::LParen => "`(`".into(),
49 Self::RParen => "`)`".into(),
50 Self::LBracket => "`[`".into(),
51 Self::RBracket => "`]`".into(),
52 Self::Eq => "`=`".into(),
53 Self::Comma => "`,`".into(),
54 Self::Colon => "`:`".into(),
55 Self::Amp => "`&`".into(),
56 Self::Bang => "`!`".into(),
57 Self::Dot => "`.`".into(),
58 Self::Spread => "`...`".into(),
59 Self::Arrow => "`=>`".into(),
60 }
61 }
62}
63
64#[derive(Debug, Clone, PartialEq, Default)]
66pub struct Literal {
67 pub parts: Vec<Part>,
68}
69
70impl Literal {
71 pub fn plain(&self) -> Option<String> {
73 self.parts
74 .iter()
75 .map(|part| match part {
76 Part::Text(text) => Some(text.as_str()),
77 Part::Slot(_) => None,
78 })
79 .collect()
80 }
81}
82
83#[derive(Debug, Clone, PartialEq)]
84pub enum Part {
85 Text(String),
86 Slot(Slot),
87}
88
89#[derive(Debug, Clone, PartialEq)]
91pub struct Slot {
92 pub kind: SlotKind,
93 pub words: Vec<(String, Range<usize>)>,
94 pub span: Range<usize>,
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum SlotKind {
99 Artf,
100 Path,
101 Param,
102}
103
104impl SlotKind {
105 pub fn name(self) -> &'static str {
106 match self {
107 Self::Artf => "artf",
108 Self::Path => "path",
109 Self::Param => "param",
110 }
111 }
112}
113
114#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
115#[error("{message}")]
116pub struct SyntaxError {
117 pub offset: usize,
118 pub message: String,
119}
120
121fn error(offset: usize, message: impl Into<String>) -> SyntaxError {
122 SyntaxError {
123 offset,
124 message: message.into(),
125 }
126}
127
128#[derive(Debug, Clone, PartialEq, Default)]
130pub struct Lexed {
131 pub tokens: Vec<Token>,
132 pub comments: Vec<Range<usize>>,
133}
134
135pub fn lex(source: &str) -> Result<Lexed, SyntaxError> {
136 let bytes = source.as_bytes();
137 let mut lexed = Lexed::default();
138 let mut index = 0;
139 while index < bytes.len() {
140 let start = index;
141 let byte = bytes[index];
142 let single = |kind| Some((kind, 1));
143 let punct = match byte {
144 b'{' => single(Kind::LBrace),
145 b'}' => single(Kind::RBrace),
146 b'(' => single(Kind::LParen),
147 b')' => single(Kind::RParen),
148 b'[' => single(Kind::LBracket),
149 b']' => single(Kind::RBracket),
150 b'=' if bytes.get(index + 1) == Some(&b'>') => Some((Kind::Arrow, 2)),
151 b'=' => single(Kind::Eq),
152 b',' => single(Kind::Comma),
153 b':' => single(Kind::Colon),
154 b'&' => single(Kind::Amp),
155 b'!' => single(Kind::Bang),
156 b'.' if source[index..].starts_with("...") => Some((Kind::Spread, 3)),
157 b'.' => single(Kind::Dot),
158 _ => None,
159 };
160 if let Some((kind, width)) = punct {
161 index += width;
162 lexed.tokens.push(Token {
163 kind,
164 span: start..index,
165 });
166 continue;
167 }
168 match byte {
169 b' ' | b'\t' | b'\r' | b'\n' => index += 1,
170 b'/' if bytes.get(index + 1) == Some(&b'/') => {
171 index = source[index..]
172 .find('\n')
173 .map_or(bytes.len(), |end| index + end);
174 lexed.comments.push(start..index);
175 }
176 b'"' | b'\'' => {
177 let (literal, end) = string(source, index)?;
178 index = end;
179 lexed.tokens.push(Token {
180 kind: Kind::Str(literal),
181 span: start..index,
182 });
183 }
184 b'-' | b'0'..=b'9' => {
185 index = number(source, index)?;
186 lexed.tokens.push(Token {
187 kind: Kind::Number(source[start..index].to_owned()),
188 span: start..index,
189 });
190 }
191 byte if byte.is_ascii_alphabetic() => {
192 while index < bytes.len()
193 && (bytes[index].is_ascii_alphanumeric() || matches!(bytes[index], b'_' | b'-'))
194 {
195 index += 1;
196 }
197 if index - start > MAX_IDENTIFIER_BYTES {
198 return Err(error(
199 start,
200 format!("An identifier is at most {MAX_IDENTIFIER_BYTES} bytes."),
201 ));
202 }
203 lexed.tokens.push(Token {
204 kind: Kind::Ident(source[start..index].to_owned()),
205 span: start..index,
206 });
207 }
208 _ => {
209 let character = source[index..].chars().next().expect("index on a char");
210 return Err(error(index, format!("Unexpected character {character:?}.")));
211 }
212 }
213 }
214 Ok(lexed)
215}
216
217fn number(source: &str, start: usize) -> Result<usize, SyntaxError> {
219 let bytes = source.as_bytes();
220 let digits = |mut index: usize| {
221 let from = index;
222 while index < bytes.len() && bytes[index].is_ascii_digit() {
223 index += 1;
224 }
225 (index, index - from)
226 };
227 let mut index = start + usize::from(bytes[start] == b'-');
228 let (after, count) = digits(index);
229 if count == 0 {
230 return Err(error(start, "A number needs a digit after `-`."));
231 }
232 if count > 1 && bytes[index] == b'0' {
233 return Err(error(start, "A number has no leading zero."));
234 }
235 index = after;
236 if bytes.get(index) == Some(&b'.') {
237 let (after, count) = digits(index + 1);
238 if count == 0 {
239 return Err(error(index, "A number needs a digit after `.`."));
240 }
241 index = after;
242 }
243 if matches!(bytes.get(index), Some(b'e' | b'E')) {
244 index += 1;
245 if matches!(bytes.get(index), Some(b'+' | b'-')) {
246 index += 1;
247 }
248 let (after, count) = digits(index);
249 if count == 0 {
250 return Err(error(index, "A number needs a digit in its exponent."));
251 }
252 index = after;
253 }
254 if bytes
255 .get(index)
256 .is_some_and(|byte| byte.is_ascii_alphabetic() || matches!(byte, b'_'))
257 {
258 return Err(error(start, "A number cannot run into a name."));
259 }
260 Ok(index)
261}
262
263fn string(source: &str, start: usize) -> Result<(Literal, usize), SyntaxError> {
265 let rest = &source[start..];
266 if let Some(body) = rest.strip_prefix("\"\"\"") {
267 let close = body
268 .find("\"\"\"")
269 .ok_or_else(|| error(start, "This `\"\"\"` string has no closing `\"\"\"`."))?;
270 let content = start + 3..start + 3 + close;
271 let (text, map) = dedent(source, content);
272 Ok((decode(&text, &map, false)?, start + 3 + close + 3))
273 } else if let Some(body) = rest.strip_prefix("'''") {
274 let close = body
275 .find("'''")
276 .ok_or_else(|| error(start, "This `'''` string has no closing `'''`."))?;
277 let content = start + 3..start + 3 + close;
278 let (text, map) = dedent(source, content);
279 Ok((decode(&text, &map, true)?, start + 3 + close + 3))
280 } else if rest.starts_with('"') {
281 let bytes = source.as_bytes();
282 let mut index = start + 1;
283 loop {
284 match bytes.get(index) {
285 None | Some(b'\n') => {
286 return Err(error(start, "This string has no closing `\"` on its line."));
287 }
288 Some(b'\\') => index += 2,
289 Some(b'"') => break,
290 Some(_) => index += 1,
291 }
292 }
293 let content = &source[start + 1..index];
294 let map: Vec<usize> = (start + 1..index).collect();
295 Ok((decode(content, &map, false)?, index + 1))
296 } else {
297 Err(error(
298 start,
299 "A single quote starts only a raw `'''` string; use `\"` for a string.",
300 ))
301 }
302}
303
304fn dedent(source: &str, content: Range<usize>) -> (String, Vec<usize>) {
308 let mut start = content.start;
309 let body = &source[content.clone()];
310 if body.starts_with("\r\n") {
311 start += 2;
312 } else if body.starts_with('\n') {
313 start += 1;
314 }
315 let mut lines: Vec<Range<usize>> = Vec::new();
316 let mut line_start = start;
317 for (offset, byte) in source[start..content.end].bytes().enumerate() {
318 if byte == b'\n' {
319 let end = start + offset;
320 let end = if end > line_start && source.as_bytes()[end - 1] == b'\r' {
321 end - 1
322 } else {
323 end
324 };
325 lines.push(line_start..end);
326 line_start = start + offset + 1;
327 }
328 }
329 lines.push(line_start..content.end);
330 if lines.len() > 1
331 && source[lines.last().expect("a line").clone()]
332 .bytes()
333 .all(|byte| matches!(byte, b' ' | b'\t'))
334 {
335 lines.pop();
336 }
337 let blank = |line: &Range<usize>| source[line.clone()].trim().is_empty();
338 let indent = lines
339 .iter()
340 .filter(|line| !blank(line))
341 .map(|line| {
342 source[line.clone()]
343 .bytes()
344 .take_while(|byte| matches!(byte, b' ' | b'\t'))
345 .count()
346 })
347 .min()
348 .unwrap_or(0);
349 let mut text = String::new();
350 let mut map = Vec::new();
351 for (number, line) in lines.iter().enumerate() {
352 if number > 0 {
353 text.push('\n');
354 map.push(line.start.saturating_sub(1));
355 }
356 if blank(line) {
357 continue;
358 }
359 let from = line.start + indent;
360 text.push_str(&source[from..line.end]);
361 map.extend(from..line.end);
362 }
363 (text, map)
364}
365
366fn decode(text: &str, map: &[usize], raw: bool) -> Result<Literal, SyntaxError> {
368 let at = |index: usize| {
369 map.get(index)
370 .copied()
371 .unwrap_or_else(|| map.last().map_or(0, |last| last + 1))
372 };
373 if raw {
374 return Ok(Literal {
375 parts: vec![Part::Text(text.to_owned())],
376 });
377 }
378 let mut parts = Vec::new();
379 let mut current = String::new();
380 let mut chars = text.char_indices().peekable();
381 while let Some((index, character)) = chars.next() {
382 let rest = &text[index..];
383 if rest.starts_with("@@{") {
384 current.push_str("@{");
385 chars.next();
386 chars.next();
387 continue;
388 }
389 if rest.starts_with("@{") {
390 let close = rest
391 .find('}')
392 .ok_or_else(|| error(at(index), "This `@{` slot has no closing `}`."))?;
393 let slot = slot(
394 &rest[2..close],
395 index + 2,
396 map,
397 at(index)..at(index + close) + 1,
398 )?;
399 if !current.is_empty() {
400 parts.push(Part::Text(std::mem::take(&mut current)));
401 }
402 parts.push(Part::Slot(slot));
403 while chars.peek().is_some_and(|(next, _)| *next <= index + close) {
404 chars.next();
405 }
406 continue;
407 }
408 if character != '\\' {
409 current.push(character);
410 continue;
411 }
412 let Some((_, escaped)) = chars.next() else {
413 return Err(error(at(index), "A string cannot end with `\\`."));
414 };
415 match escaped {
416 '"' => current.push('"'),
417 '\\' => current.push('\\'),
418 '/' => current.push('/'),
419 'b' => current.push('\u{8}'),
420 'f' => current.push('\u{c}'),
421 'n' => current.push('\n'),
422 'r' => current.push('\r'),
423 't' => current.push('\t'),
424 'u' => {
425 let hex: String = (0..4)
426 .filter_map(|_| chars.next().map(|(_, c)| c))
427 .collect();
428 let value = u32::from_str_radix(&hex, 16)
429 .ok()
430 .filter(|_| hex.len() == 4)
431 .and_then(char::from_u32)
432 .ok_or_else(|| {
433 error(at(index), "`\\u` takes four hex digits of a character.")
434 })?;
435 current.push(value);
436 }
437 '\n' => {
438 while chars
440 .peek()
441 .is_some_and(|(_, next)| matches!(next, ' ' | '\t' | '\n' | '\r'))
442 {
443 chars.next();
444 }
445 }
446 other => {
447 return Err(error(
448 at(index),
449 format!("Unknown escape `\\{other}`; write `\\\\` for a backslash."),
450 ));
451 }
452 }
453 }
454 if !current.is_empty() || parts.is_empty() {
455 parts.push(Part::Text(current));
456 }
457 Ok(Literal { parts })
458}
459
460fn slot(
462 inner: &str,
463 offset: usize,
464 map: &[usize],
465 span: Range<usize>,
466) -> Result<Slot, SyntaxError> {
467 let at = |index: usize| map.get(offset + index).copied().unwrap_or(span.start);
468 let mut words = Vec::new();
469 let mut starts = Vec::new();
470 let mut cursor = 0;
471 for word in inner.split([' ', '\t', '\n', '\r']) {
472 if !word.is_empty() {
473 words.push((word.to_owned(), at(cursor)..at(cursor) + word.len()));
474 starts.push(cursor);
475 }
476 cursor += word.len() + 1;
477 }
478 if words.first().is_some_and(|(kind, _)| kind == "path")
481 && words.len() > 2
482 && words[1].0.contains('/')
483 {
484 let start = starts[1];
485 let rest = inner[start..].trim_end();
486 words.truncate(1);
487 words.push((rest.to_owned(), at(start)..at(start) + rest.len()));
488 }
489 let Some((kind, kind_span)) = words.first().cloned() else {
490 return Err(error(
491 span.start,
492 "An empty `@{}` slot; write `@{artf NAME}`, `@{path NAME}` or `@{param NAME}`, or `@@{` for a literal `@{`.",
493 ));
494 };
495 let kind = match kind.as_str() {
496 "artf" => SlotKind::Artf,
497 "path" => SlotKind::Path,
498 "param" => SlotKind::Param,
499 "tool" => {
500 return Err(error(
501 kind_span.start,
502 "There is no tool slot: composing a toolset gives an eval its tools, and `@{artf NAME}` names an Artifact whose tools it reads.",
503 ));
504 }
505 other => {
506 return Err(error(
507 kind_span.start,
508 format!(
509 "Unknown slot kind `{other}`: a slot is `@{{artf …}}`, `@{{path …}}` or `@{{param …}}`; write `@@{{` for a literal `@{{`."
510 ),
511 ));
512 }
513 };
514 words.remove(0);
515 if words.len() != 1 {
516 return Err(error(
517 span.start,
518 format!(
519 "A `{}` slot names one thing: `@{{{} NAME}}`.",
520 kind.name(),
521 kind.name()
522 ),
523 ));
524 }
525 Ok(Slot { kind, words, span })
526}
527
528#[cfg(test)]
529mod tests;