1use 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)] use crate::interpreter::nort;
18use crate::location::SourceRange;
19use crate::name::{Sym, VName, VPath};
20use crate::parse::numeric::print_nat16;
21
22#[derive(Clone, Debug)]
24pub struct Expr {
25 pub value: Clause,
27 pub range: SourceRange,
29}
30
31impl Expr {
32 #[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 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
48pub 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 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
67pub enum PHClass {
68 Vec {
70 nonzero: bool,
72 prio: usize,
74 },
75 Scalar,
77 Name,
79}
80
81#[derive(Clone, Debug, PartialEq, Eq, Hash)]
83pub struct Placeholder {
84 pub name: Tok<String>,
86 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#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
106pub enum PType {
107 Par,
109 Sqr,
111 Curl,
113}
114impl PType {
115 pub fn l(self) -> char {
117 match self {
118 PType::Curl => '{',
119 PType::Par => '(',
120 PType::Sqr => '[',
121 }
122 }
123
124 pub fn r(self) -> char {
126 match self {
127 PType::Curl => '}',
128 PType::Par => ')',
129 PType::Sqr => ']',
130 }
131 }
132}
133
134#[derive(Debug, Clone)]
136pub enum Clause {
137 Atom(AtomGenerator),
139 Name(Sym),
141 S(PType, Rc<Vec<Expr>>),
144 Lambda(Rc<Vec<Expr>>, Rc<Vec<Expr>>),
146 Placeh(Placeholder),
148}
149
150impl Clause {
151 #[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 #[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 #[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 #[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 #[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 #[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 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 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 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 #[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#[derive(Debug, Clone)]
315pub struct Rule {
316 pub pattern: Vec<Expr>,
318 pub prio: NotNan<f64>,
320 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#[derive(Debug, Clone)]
338pub struct Constant {
339 pub name: Tok<String>,
341 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
354pub struct Import {
355 pub path: VPath,
362 pub name: Option<Tok<String>>,
364 pub range: SourceRange,
366}
367impl Import {
368 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 #[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#[derive(Debug, Clone)]
402pub struct ModuleBlock {
403 pub name: Tok<String>,
405 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#[derive(Debug, Clone)]
418pub enum MemberKind {
419 Rule(Rule),
422 Constant(Constant),
424 Module(ModuleBlock),
426}
427impl MemberKind {
428 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#[derive(Debug, Clone)]
447pub struct Member {
448 pub kind: MemberKind,
450 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#[derive(Debug, Clone)]
465pub enum SourceLineKind {
466 Import(Vec<Import>),
468 Comment(String),
470 Member(Member),
472 Export(Vec<(Tok<String>, SourceRange)>),
475}
476impl SourceLineKind {
477 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#[derive(Debug, Clone)]
498pub struct SourceLine {
499 pub kind: SourceLineKind,
501 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}