Skip to main content

orchidlang/parse/
parsed.rs

1//! Datastructures representing the units of macro execution
2//!
3//! These structures are produced by the pipeline, processed by the macro
4//! executor, and then converted to other usable formats.
5
6use std::fmt;
7use std::hash::Hash;
8use std::rc::Rc;
9
10use hashbrown::HashSet;
11use intern_all::Tok;
12use itertools::Itertools;
13use ordered_float::NotNan;
14
15use crate::foreign::atom::AtomGenerator;
16#[allow(unused)] // for doc
17use crate::interpreter::nort;
18use crate::location::SourceRange;
19use crate::name::{Sym, VName, VPath};
20use crate::parse::numeric::print_nat16;
21
22/// A [Clause] with associated metadata
23#[derive(Clone, Debug)]
24pub struct Expr {
25  /// The actual value
26  pub value: Clause,
27  /// Information about the code that produced this value
28  pub range: SourceRange,
29}
30
31impl Expr {
32  /// Process all names with the given mapper.
33  /// Return a new object if anything was processed
34  #[must_use]
35  pub fn map_names(&self, pred: &mut impl FnMut(Sym) -> Option<Sym>) -> Option<Self> {
36    (self.value.map_names(pred)).map(|value| Self { value, range: self.range.clone() })
37  }
38
39  /// Visit all expressions in the tree. The search can be exited early by
40  /// returning [Some]
41  ///
42  /// See also [crate::interpreter::nort::Expr::search_all]
43  pub fn search_all<T>(&self, f: &mut impl FnMut(&Self) -> Option<T>) -> Option<T> {
44    f(self).or_else(|| self.value.search_all(f))
45  }
46}
47
48/// Visit all expression sequences including this sequence itself.
49pub fn search_all_slcs<T>(this: &[Expr], f: &mut impl FnMut(&[Expr]) -> Option<T>) -> Option<T> {
50  f(this).or_else(|| this.iter().find_map(|expr| expr.value.search_all_slcs(f)))
51}
52
53impl Expr {
54  /// Add the specified prefix to every Name
55  #[must_use]
56  pub fn prefix(&self, prefix: &[Tok<String>], except: &impl Fn(Tok<String>) -> bool) -> Self {
57    Self { value: self.value.prefix(prefix, except), range: self.range.clone() }
58  }
59}
60
61impl fmt::Display for Expr {
62  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.value.fmt(f) }
63}
64
65/// Various types of placeholders
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
67pub enum PHClass {
68  /// Matches multiple tokens, lambdas or parenthesized groups
69  Vec {
70    /// If true, must match at least one clause
71    nonzero: bool,
72    /// Greediness in the allocation of tokens
73    prio: usize,
74  },
75  /// Matches exactly one token, lambda or parenthesized group
76  Scalar,
77  /// Matches exactly one name
78  Name,
79}
80
81/// Properties of a placeholder that matches unknown tokens in macros
82#[derive(Clone, Debug, PartialEq, Eq, Hash)]
83pub struct Placeholder {
84  /// Identifier to pair placeholders in the pattern and template
85  pub name: Tok<String>,
86  /// The nature of the token set matched by this placeholder
87  pub class: PHClass,
88}
89
90impl fmt::Display for Placeholder {
91  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92    let name = &self.name;
93    match self.class {
94      PHClass::Scalar => write!(f, "${name}"),
95      PHClass::Name => write!(f, "$_{name}"),
96      PHClass::Vec { nonzero, prio } => {
97        if nonzero { write!(f, "...") } else { write!(f, "..") }?;
98        write!(f, "${name}:{prio}")
99      },
100    }
101  }
102}
103
104/// Different types of brackets supported by Orchid
105#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
106pub enum PType {
107  /// ()
108  Par,
109  /// []
110  Sqr,
111  /// {}
112  Curl,
113}
114impl PType {
115  /// Left paren character for this paren type
116  pub fn l(self) -> char {
117    match self {
118      PType::Curl => '{',
119      PType::Par => '(',
120      PType::Sqr => '[',
121    }
122  }
123
124  /// Right paren character for this paren type
125  pub fn r(self) -> char {
126    match self {
127      PType::Curl => '}',
128      PType::Par => ')',
129      PType::Sqr => ']',
130    }
131  }
132}
133
134/// An S-expression as read from a source file
135#[derive(Debug, Clone)]
136pub enum Clause {
137  /// An opaque non-callable value, eg. a file handle
138  Atom(AtomGenerator),
139  /// A c-style name or an operator, eg. `+`, `i`, `foo::bar`
140  Name(Sym),
141  /// A parenthesized expression
142  /// eg. `(print out "hello")`, `[1, 2, 3]`, `{Some(t) => t}`
143  S(PType, Rc<Vec<Expr>>),
144  /// A function expression, eg. `\x. x + 1`
145  Lambda(Rc<Vec<Expr>>, Rc<Vec<Expr>>),
146  /// A placeholder for macros, eg. `$name`, `...$body`, `...$lhs:1`
147  Placeh(Placeholder),
148}
149
150impl Clause {
151  /// Extract the expressions from an auto, lambda or S
152  #[must_use]
153  pub fn body(&self) -> Option<Rc<Vec<Expr>>> {
154    match self {
155      Self::Lambda(_, body) | Self::S(_, body) => Some(body.clone()),
156      _ => None,
157    }
158  }
159
160  /// Convert with identical meaning
161  #[must_use]
162  pub fn into_expr(self, range: SourceRange) -> Expr {
163    if let Self::S(PType::Par, body) = &self {
164      if let [wrapped] = &body[..] {
165        return wrapped.clone();
166      }
167    }
168    Expr { value: self, range }
169  }
170
171  /// Convert with identical meaning
172  #[must_use]
173  pub fn from_exprs(exprs: &[Expr]) -> Option<Self> {
174    match exprs {
175      [] => None,
176      [only] => Some(only.value.clone()),
177      _ => Some(Self::S(PType::Par, Rc::new(exprs.to_vec()))),
178    }
179  }
180
181  /// Convert with identical meaning
182  #[must_use]
183  pub fn from_exprv(exprv: &Rc<Vec<Expr>>) -> Option<Clause> {
184    if exprv.len() < 2 { Self::from_exprs(exprv) } else { Some(Self::S(PType::Par, exprv.clone())) }
185  }
186
187  /// Collect all names that appear in this expression.
188  /// NOTICE: this isn't the total set of unbound names, it's mostly useful to
189  /// make weak statements for optimization.
190  #[must_use]
191  pub fn collect_names(&self) -> HashSet<Sym> {
192    if let Self::Name(n) = self {
193      return HashSet::from([n.clone()]);
194    }
195    let mut glossary = HashSet::new();
196    let result = self.search_all(&mut |e| {
197      if let Clause::Name(n) = &e.value {
198        glossary.insert(n.clone());
199      }
200      None::<()>
201    });
202    assert!(result.is_none(), "Callback never returns Some");
203    glossary
204  }
205
206  /// Process all names with the given mapper.
207  /// Return a new object if anything was processed
208  #[must_use]
209  pub fn map_names(&self, pred: &mut impl FnMut(Sym) -> Option<Sym>) -> Option<Self> {
210    match self {
211      Clause::Atom(_) | Clause::Placeh(_) => None,
212      Clause::Name(name) => pred(name.clone()).map(Clause::Name),
213      Clause::S(c, body) => {
214        let mut any_some = false;
215        let new_body = body
216          .iter()
217          .map(|e| {
218            let val = e.map_names(pred);
219            any_some |= val.is_some();
220            val.unwrap_or_else(|| e.clone())
221          })
222          .collect();
223        if any_some { Some(Clause::S(*c, Rc::new(new_body))) } else { None }
224      },
225      Clause::Lambda(arg, body) => {
226        let mut any_some = false;
227        let new_arg = (arg.iter())
228          .map(|e| {
229            let val = e.map_names(pred);
230            any_some |= val.is_some();
231            val.unwrap_or_else(|| e.clone())
232          })
233          .collect();
234        let new_body = (body.iter())
235          .map(|e| {
236            let val = e.map_names(pred);
237            any_some |= val.is_some();
238            val.unwrap_or_else(|| e.clone())
239          })
240          .collect();
241        if any_some { Some(Clause::Lambda(Rc::new(new_arg), Rc::new(new_body))) } else { None }
242      },
243    }
244  }
245
246  /// Pair of [Expr::search_all]
247  pub fn search_all<T>(&self, f: &mut impl FnMut(&Expr) -> Option<T>) -> Option<T> {
248    match self {
249      Clause::Lambda(arg, body) =>
250        arg.iter().chain(body.iter()).find_map(|expr| expr.search_all(f)),
251      Clause::Name(_) | Clause::Atom(_) | Clause::Placeh(_) => None,
252      Clause::S(_, body) => body.iter().find_map(|expr| expr.search_all(f)),
253    }
254  }
255
256  /// Visit all expression sequences. Most useful when looking for some pattern
257  pub fn search_all_slcs<T>(&self, f: &mut impl FnMut(&[Expr]) -> Option<T>) -> Option<T> {
258    match self {
259      Clause::Lambda(arg, body) => search_all_slcs(arg, f).or_else(|| search_all_slcs(body, f)),
260      Clause::Name(_) | Clause::Atom(_) | Clause::Placeh(_) => None,
261      Clause::S(_, body) => search_all_slcs(body, f),
262    }
263  }
264
265  /// Generate a parenthesized expression sequence
266  pub fn s(delimiter: char, body: impl IntoIterator<Item = Self>, range: SourceRange) -> Self {
267    let ptype = match delimiter {
268      '(' => PType::Par,
269      '[' => PType::Sqr,
270      '{' => PType::Curl,
271      _ => panic!("not an opening paren"),
272    };
273    let body = body.into_iter().map(|it| it.into_expr(range.clone())).collect();
274    Self::S(ptype, Rc::new(body))
275  }
276}
277
278impl Clause {
279  /// Add the specified prefix to every Name
280  #[must_use]
281  pub fn prefix(&self, prefix: &[Tok<String>], except: &impl Fn(Tok<String>) -> bool) -> Self {
282    self
283      .map_names(&mut |name| match except(name[0].clone()) {
284        true => None,
285        false => {
286          let prefixed = prefix.iter().cloned().chain(name.iter()).collect::<Vec<_>>();
287          Some(Sym::from_tok(name.tok().interner().i(&prefixed)).unwrap())
288        },
289      })
290      .unwrap_or_else(|| self.clone())
291  }
292}
293
294impl fmt::Display for Clause {
295  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296    match self {
297      Self::Atom(a) => write!(f, "{a:?}"),
298      Self::Name(name) => write!(f, "{}", name),
299      Self::S(t, items) => {
300        let body = items.iter().join(" ");
301        write!(f, "{}{body}{}", t.l(), t.r())
302      },
303      Self::Lambda(arg, body) => {
304        let args = arg.iter().join(" ");
305        let bodys = body.iter().join(" ");
306        write!(f, "\\{args}.{bodys}")
307      },
308      Self::Placeh(ph) => ph.fmt(f),
309    }
310  }
311}
312
313/// A substitution rule as loaded from source
314#[derive(Debug, Clone)]
315pub struct Rule {
316  /// Expressions on the left side of the arrow
317  pub pattern: Vec<Expr>,
318  /// Priority number written inside the arrow
319  pub prio: NotNan<f64>,
320  /// Expressions on the right side of the arrow
321  pub template: Vec<Expr>,
322}
323
324impl fmt::Display for Rule {
325  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326    write!(
327      f,
328      "rule {} ={}=> {}",
329      self.pattern.iter().join(" "),
330      print_nat16(self.prio),
331      self.template.iter().join(" ")
332    )
333  }
334}
335
336/// A named constant
337#[derive(Debug, Clone)]
338pub struct Constant {
339  /// Used to reference the constant
340  pub name: Tok<String>,
341  /// The constant value inserted where the name is found
342  pub value: Expr,
343}
344
345impl fmt::Display for Constant {
346  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347    write!(f, "const {} := {}", *self.name, self.value)
348  }
349}
350
351/// An import pointing at another module, either specifying the symbol to be
352/// imported or importing all available symbols with a globstar (*)
353#[derive(Debug, Clone, PartialEq, Eq, Hash)]
354pub struct Import {
355  /// Import path, a sequence of module names. Can either start with
356  ///
357  /// - `self` to reference the current module
358  /// - any number of `super` to reference the parent module of the implied
359  ///   `self`
360  /// - a root name
361  pub path: VPath,
362  /// If name is None, this is a wildcard import
363  pub name: Option<Tok<String>>,
364  /// Location of the final name segment, which uniquely identifies this name
365  pub range: SourceRange,
366}
367impl Import {
368  /// Constructor
369  pub fn new(
370    path: impl IntoIterator<Item = Tok<String>>,
371    name: Option<Tok<String>>,
372    range: SourceRange,
373  ) -> Self {
374    let path = VPath(path.into_iter().collect());
375    assert!(name.is_some() || !path.0.is_empty(), "import * not allowed");
376    Self { range, name, path }
377  }
378
379  /// Get the preload target space for this import - the prefix below
380  /// which all files should be included in the compilation
381  ///
382  /// Returns the path if this is a glob import, or the path plus the
383  /// name if this is a specific import
384  #[must_use]
385  pub fn nonglob_path(&self) -> VName {
386    VName::new(self.path.0.iter().chain(&self.name).cloned())
387      .expect("Everything import (`import *`) not allowed")
388  }
389}
390
391impl fmt::Display for Import {
392  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393    match &self.name {
394      None => write!(f, "{}::*", self.path),
395      Some(n) => write!(f, "{}::{}", self.path, n),
396    }
397  }
398}
399
400/// A namespace block
401#[derive(Debug, Clone)]
402pub struct ModuleBlock {
403  /// Name prefixed to all names in the block
404  pub name: Tok<String>,
405  /// Prefixed entries
406  pub body: Vec<SourceLine>,
407}
408
409impl fmt::Display for ModuleBlock {
410  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411    let bodys = self.body.iter().map(|e| e.to_string()).join("\n");
412    write!(f, "module {} {{\n{}\n}}", self.name, bodys)
413  }
414}
415
416/// see [Member]
417#[derive(Debug, Clone)]
418pub enum MemberKind {
419  /// A substitution rule. Rules apply even when they're not in scope, if the
420  /// absolute names are present eg. because they're produced by other rules
421  Rule(Rule),
422  /// A constant (or function) associated with a name
423  Constant(Constant),
424  /// A prefixed set of other entries
425  Module(ModuleBlock),
426}
427impl MemberKind {
428  /// Convert to [SourceLine]
429  pub fn into_line(self, exported: bool, range: SourceRange) -> SourceLine {
430    SourceLineKind::Member(Member { exported, kind: self }).wrap(range)
431  }
432}
433
434impl fmt::Display for MemberKind {
435  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
436    match self {
437      Self::Constant(c) => c.fmt(f),
438      Self::Module(m) => m.fmt(f),
439      Self::Rule(r) => r.fmt(f),
440    }
441  }
442}
443
444/// Things that may be prefixed with an export
445/// see [MemberKind]
446#[derive(Debug, Clone)]
447pub struct Member {
448  /// Various members
449  pub kind: MemberKind,
450  /// Whether this member is exported or not
451  pub exported: bool,
452}
453
454impl fmt::Display for Member {
455  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
456    match self {
457      Self { exported: true, kind } => write!(f, "export {kind}"),
458      Self { exported: false, kind } => write!(f, "{kind}"),
459    }
460  }
461}
462
463/// See [SourceLine]
464#[derive(Debug, Clone)]
465pub enum SourceLineKind {
466  /// Imports one or all names in a module
467  Import(Vec<Import>),
468  /// Comments are kept here in case dev tooling wants to parse documentation
469  Comment(String),
470  /// An element with visibility information
471  Member(Member),
472  /// A list of tokens exported explicitly. This can also create new exported
473  /// tokens that the local module doesn't actually define a role for
474  Export(Vec<(Tok<String>, SourceRange)>),
475}
476impl SourceLineKind {
477  /// Wrap with no location
478  pub fn wrap(self, range: SourceRange) -> SourceLine { SourceLine { kind: self, range } }
479}
480
481impl fmt::Display for SourceLineKind {
482  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
483    match self {
484      Self::Comment(s) => write!(f, "--[{s}]--"),
485      Self::Export(s) => {
486        write!(f, "export ::({})", s.iter().map(|t| &**t.0).join(", "))
487      },
488      Self::Member(member) => write!(f, "{member}"),
489      Self::Import(i) => {
490        write!(f, "import ({})", i.iter().map(|i| i.to_string()).join(", "))
491      },
492    }
493  }
494}
495
496/// Anything the parser might encounter in a file. See [SourceLineKind]
497#[derive(Debug, Clone)]
498pub struct SourceLine {
499  /// What we encountered
500  pub kind: SourceLineKind,
501  /// Where we encountered it.
502  pub range: SourceRange,
503}
504
505impl fmt::Display for SourceLine {
506  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.kind.fmt(f) }
507}