1use crate::{
2 expr::print::{PrettyBuf, PrettyDisplay},
3 typ::{TVar, Type},
4 PrintFlag, PRINT_FLAGS,
5};
6use anyhow::Result;
7use arcstr::{literal, ArcStr};
8use combine::stream::position::SourcePosition;
9pub use modpath::ModPath;
10use netidx::{path::Path, subscriber::Value, utils::Either};
11pub use pattern::{Pattern, StructurePattern};
12use regex::Regex;
13pub use resolver::ModuleResolver;
14use serde::{
15 de::{self, Visitor},
16 Deserialize, Deserializer, Serialize, Serializer,
17};
18use std::{
19 cell::RefCell,
20 cmp::{Ordering, PartialEq, PartialOrd},
21 fmt,
22 ops::Deref,
23 path::PathBuf,
24 result,
25 str::FromStr,
26 sync::LazyLock,
27};
28use triomphe::Arc;
29
30mod modpath;
31pub mod parser;
32mod pattern;
33pub mod print;
34mod resolver;
35#[cfg(test)]
36mod test;
37
38pub const VNAME: LazyLock<Regex> =
39 LazyLock::new(|| Regex::new("^[a-z][a-z0-9_]*$").unwrap());
40
41atomic_id!(ExprId);
42
43const DEFAULT_ORIGIN: LazyLock<Arc<Origin>> =
44 LazyLock::new(|| Arc::new(Origin::default()));
45
46thread_local! {
47 static ORIGIN: RefCell<Option<Arc<Origin>>> = RefCell::new(None);
48}
49
50pub(crate) fn set_origin(ori: Arc<Origin>) {
51 ORIGIN.with_borrow_mut(|global| *global = Some(ori))
52}
53
54pub(crate) fn get_origin() -> Arc<Origin> {
55 ORIGIN.with_borrow(|ori| {
56 ori.as_ref().cloned().unwrap_or_else(|| DEFAULT_ORIGIN.clone())
57 })
58}
59
60#[derive(Debug)]
61pub struct CouldNotResolve(ArcStr);
62
63impl fmt::Display for CouldNotResolve {
64 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65 write!(f, "could not resolve module {}", self.0)
66 }
67}
68
69#[derive(Debug, Clone, PartialEq, PartialOrd)]
70pub struct Arg {
71 pub labeled: Option<Option<Expr>>,
72 pub pattern: StructurePattern,
73 pub constraint: Option<Type>,
74}
75
76#[derive(Debug, Clone, PartialEq, PartialOrd)]
77pub struct Doc(pub Option<ArcStr>);
78
79#[derive(Debug, Clone, PartialEq, PartialOrd)]
80pub struct TypeDefExpr {
81 pub name: ArcStr,
82 pub params: Arc<[(TVar, Option<Type>)]>,
83 pub typ: Type,
84}
85
86#[derive(Debug, Clone, PartialEq, PartialOrd)]
87pub struct BindSig {
88 pub name: ArcStr,
89 pub typ: Type,
90}
91
92#[derive(Debug, Clone, PartialEq, PartialOrd)]
93pub enum SigKind {
94 TypeDef(TypeDefExpr),
95 Bind(BindSig),
96 Module(ArcStr),
97 Use(ModPath),
98}
99
100#[derive(Debug, Clone, PartialEq, PartialOrd)]
101pub struct SigItem {
102 pub doc: Doc,
103 pub kind: SigKind,
104}
105
106#[derive(Debug, Clone, PartialEq, PartialOrd)]
107pub struct Sig {
108 pub items: Arc<[SigItem]>,
109 pub toplevel: bool,
110}
111
112impl Deref for Sig {
113 type Target = [SigItem];
114
115 fn deref(&self) -> &Self::Target {
116 &*self.items
117 }
118}
119
120#[derive(Debug, Clone, PartialEq, PartialOrd)]
121pub enum Sandbox {
122 Unrestricted,
123 Blacklist(Arc<[ModPath]>),
124 Whitelist(Arc<[ModPath]>),
125}
126
127#[derive(Debug, Clone, PartialEq, PartialOrd)]
128pub enum ModuleKind {
129 Dynamic { sandbox: Sandbox, sig: Sig, source: Arc<Expr> },
130 Resolved { exprs: Arc<[Expr]>, sig: Option<Sig>, from_interface: bool },
131 Unresolved { from_interface: bool },
132}
133
134#[derive(Debug, Clone, PartialEq, PartialOrd)]
135pub struct BindExpr {
136 pub rec: bool,
137 pub pattern: StructurePattern,
138 pub typ: Option<Type>,
139 pub value: Expr,
140}
141
142#[derive(Debug, Clone, PartialEq, PartialOrd)]
143pub struct LambdaExpr {
144 pub args: Arc<[Arg]>,
145 pub vargs: Option<Option<Type>>,
146 pub rtype: Option<Type>,
147 pub constraints: Arc<[(TVar, Type)]>,
148 pub throws: Option<Type>,
149 pub body: Either<Expr, ArcStr>,
150}
151
152#[derive(Debug, Clone, PartialEq, PartialOrd)]
153pub struct TryCatchExpr {
154 pub bind: ArcStr,
155 pub constraint: Option<Type>,
156 pub handler: Arc<Expr>,
157 pub exprs: Arc<[Expr]>,
158}
159
160#[derive(Debug, Clone, PartialEq, PartialOrd)]
161pub struct StructWithExpr {
162 pub source: Arc<Expr>,
163 pub replace: Arc<[(ArcStr, Expr)]>,
164}
165
166#[derive(Debug, Clone, PartialEq, PartialOrd)]
167pub struct StructExpr {
168 pub args: Arc<[(ArcStr, Expr)]>,
169}
170
171#[derive(Debug, Clone, PartialEq, PartialOrd)]
172pub struct ApplyExpr {
173 pub args: Arc<[(Option<ArcStr>, Expr)]>,
174 pub function: Arc<Expr>,
175}
176
177#[derive(Debug, Clone, PartialEq, PartialOrd)]
178pub struct SelectExpr {
179 pub arg: Arc<Expr>,
180 pub arms: Arc<[(Pattern, Expr)]>,
181}
182
183#[derive(Debug, Clone, PartialEq, PartialOrd)]
184pub enum ExprKind {
185 NoOp,
186 Constant(Value),
187 Module { name: ArcStr, value: ModuleKind },
188 ExplicitParens(Arc<Expr>),
189 Do { exprs: Arc<[Expr]> },
190 Use { name: ModPath },
191 Bind(Arc<BindExpr>),
192 Ref { name: ModPath },
193 Connect { name: ModPath, value: Arc<Expr>, deref: bool },
194 StringInterpolate { args: Arc<[Expr]> },
195 StructRef { source: Arc<Expr>, field: ArcStr },
196 TupleRef { source: Arc<Expr>, field: usize },
197 ArrayRef { source: Arc<Expr>, i: Arc<Expr> },
198 ArraySlice { source: Arc<Expr>, start: Option<Arc<Expr>>, end: Option<Arc<Expr>> },
199 MapRef { source: Arc<Expr>, key: Arc<Expr> },
200 StructWith(StructWithExpr),
201 Lambda(Arc<LambdaExpr>),
202 TypeDef(TypeDefExpr),
203 TypeCast { expr: Arc<Expr>, typ: Type },
204 Apply(ApplyExpr),
205 Any { args: Arc<[Expr]> },
206 Array { args: Arc<[Expr]> },
207 Map { args: Arc<[(Expr, Expr)]> },
208 Tuple { args: Arc<[Expr]> },
209 Variant { tag: ArcStr, args: Arc<[Expr]> },
210 Struct(StructExpr),
211 Select(SelectExpr),
212 Qop(Arc<Expr>),
213 OrNever(Arc<Expr>),
214 TryCatch(Arc<TryCatchExpr>),
215 ByRef(Arc<Expr>),
216 Deref(Arc<Expr>),
217 Eq { lhs: Arc<Expr>, rhs: Arc<Expr> },
218 Ne { lhs: Arc<Expr>, rhs: Arc<Expr> },
219 Lt { lhs: Arc<Expr>, rhs: Arc<Expr> },
220 Gt { lhs: Arc<Expr>, rhs: Arc<Expr> },
221 Lte { lhs: Arc<Expr>, rhs: Arc<Expr> },
222 Gte { lhs: Arc<Expr>, rhs: Arc<Expr> },
223 And { lhs: Arc<Expr>, rhs: Arc<Expr> },
224 Or { lhs: Arc<Expr>, rhs: Arc<Expr> },
225 Not { expr: Arc<Expr> },
226 Add { lhs: Arc<Expr>, rhs: Arc<Expr> },
227 Sub { lhs: Arc<Expr>, rhs: Arc<Expr> },
228 Mul { lhs: Arc<Expr>, rhs: Arc<Expr> },
229 Div { lhs: Arc<Expr>, rhs: Arc<Expr> },
230 Mod { lhs: Arc<Expr>, rhs: Arc<Expr> },
231 Sample { lhs: Arc<Expr>, rhs: Arc<Expr> },
232}
233
234impl ExprKind {
235 pub fn to_expr(self, pos: SourcePosition) -> Expr {
236 Expr { id: ExprId::new(), ori: get_origin(), pos, kind: self }
237 }
238
239 pub fn to_expr_nopos(self) -> Expr {
241 Expr { id: ExprId::new(), ori: get_origin(), pos: Default::default(), kind: self }
242 }
243}
244
245#[derive(Debug, Clone, PartialEq, PartialOrd)]
246pub enum Source {
247 File(PathBuf),
248 Netidx(Path),
249 Internal(ArcStr),
250 Unspecified,
251}
252
253impl Default for Source {
254 fn default() -> Self {
255 Self::Unspecified
256 }
257}
258
259impl Source {
260 pub fn has_filename(&self, name: &str) -> bool {
261 match self {
262 Self::File(buf) => match buf.file_name() {
263 None => false,
264 Some(os) => match os.to_str() {
265 None => false,
266 Some(s) => s == name,
267 },
268 },
269 Self::Netidx(_) | Self::Internal(_) | Self::Unspecified => false,
270 }
271 }
272
273 pub fn is_file(&self) -> bool {
274 match self {
275 Self::File(_) => true,
276 Self::Netidx(_) | Self::Internal(_) | Self::Unspecified => false,
277 }
278 }
279
280 pub fn to_value(&self) -> Value {
281 match self {
282 Self::File(pb) => {
283 let s = pb.as_os_str().to_string_lossy();
284 (literal!("File"), ArcStr::from(s)).into()
285 }
286 Self::Netidx(p) => (literal!("Netidx"), p.clone()).into(),
287 Self::Internal(s) => (literal!("Internal"), s.clone()).into(),
288 Self::Unspecified => literal!("Unspecified").into(),
289 }
290 }
291}
292
293#[derive(Debug, Clone, PartialEq, PartialOrd, Default)]
295pub struct Origin {
296 pub parent: Option<Arc<Origin>>,
297 pub source: Source,
298 pub text: ArcStr,
299}
300
301impl fmt::Display for Origin {
302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 let flags = PRINT_FLAGS.with(|f| f.get());
304 match &self.source {
305 Source::Unspecified => {
306 if flags.contains(PrintFlag::NoSource) {
307 write!(f, "in expr")?
308 } else {
309 write!(f, "in expr {}", self.text)?
310 }
311 }
312 Source::File(n) => write!(f, "in file {n:?}")?,
313 Source::Netidx(n) => write!(f, "in netidx {n}")?,
314 Source::Internal(n) => write!(f, "in module {n}")?,
315 }
316 let mut p = &self.parent;
317 if flags.contains(PrintFlag::NoParents) {
318 Ok(())
319 } else {
320 loop {
321 match p {
322 None => break Ok(()),
323 Some(parent) => {
324 writeln!(f, "")?;
325 write!(f, " ")?;
326 match &parent.source {
327 Source::Unspecified => {
328 if flags.contains(PrintFlag::NoSource) {
329 write!(f, "included from expr")?
330 } else {
331 write!(f, "included from expr {}", parent.text)?
332 }
333 }
334 Source::File(n) => write!(f, "included from file {n:?}")?,
335 Source::Netidx(n) => write!(f, "included from netidx {n}")?,
336 Source::Internal(n) => write!(f, "included from module {n}")?,
337 }
338 p = &parent.parent;
339 }
340 }
341 }
342 }
343 }
344}
345
346impl Origin {
347 pub fn to_value(&self) -> Value {
348 let p = Value::from(self.parent.as_ref().map(|p| p.to_value()));
349 [
350 (literal!("parent"), p),
351 (literal!("source"), self.source.to_value()),
352 (literal!("text"), Value::from(self.text.clone())),
353 ]
354 .into()
355 }
356}
357
358#[derive(Debug, Clone)]
359pub struct Expr {
360 pub id: ExprId,
361 pub ori: Arc<Origin>,
362 pub pos: SourcePosition,
363 pub kind: ExprKind,
364}
365
366impl fmt::Display for Expr {
367 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
368 write!(f, "{}", self.kind)
369 }
370}
371
372impl PrettyDisplay for Expr {
373 fn fmt_pretty_inner(&self, buf: &mut PrettyBuf) -> fmt::Result {
374 self.kind.fmt_pretty(buf)
375 }
376}
377
378impl PartialOrd for Expr {
379 fn partial_cmp(&self, rhs: &Expr) -> Option<Ordering> {
380 self.kind.partial_cmp(&rhs.kind)
381 }
382}
383
384impl PartialEq for Expr {
385 fn eq(&self, rhs: &Expr) -> bool {
386 self.kind.eq(&rhs.kind)
387 }
388}
389
390impl Eq for Expr {}
391
392impl Serialize for Expr {
393 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
394 where
395 S: Serializer,
396 {
397 serializer.serialize_str(&self.to_string())
398 }
399}
400
401impl Default for Expr {
402 fn default() -> Self {
403 ExprKind::Constant(Value::Null).to_expr(Default::default())
404 }
405}
406
407impl FromStr for Expr {
408 type Err = anyhow::Error;
409
410 fn from_str(s: &str) -> result::Result<Self, Self::Err> {
411 parser::parse_one(s)
412 }
413}
414
415#[derive(Clone, Copy)]
416struct ExprVisitor;
417
418impl<'de> Visitor<'de> for ExprVisitor {
419 type Value = Expr;
420
421 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
422 write!(formatter, "expected expression")
423 }
424
425 fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
426 where
427 E: de::Error,
428 {
429 Expr::from_str(s).map_err(de::Error::custom)
430 }
431
432 fn visit_borrowed_str<E>(self, s: &'de str) -> Result<Self::Value, E>
433 where
434 E: de::Error,
435 {
436 Expr::from_str(s).map_err(de::Error::custom)
437 }
438
439 fn visit_string<E>(self, s: String) -> Result<Self::Value, E>
440 where
441 E: de::Error,
442 {
443 Expr::from_str(&s).map_err(de::Error::custom)
444 }
445}
446
447impl<'de> Deserialize<'de> for Expr {
448 fn deserialize<D>(de: D) -> Result<Self, D::Error>
449 where
450 D: Deserializer<'de>,
451 {
452 de.deserialize_str(ExprVisitor)
453 }
454}
455
456impl Expr {
457 pub fn new(kind: ExprKind, pos: SourcePosition) -> Self {
458 Expr { id: ExprId::new(), ori: get_origin(), pos, kind }
459 }
460
461 pub fn fold<T, F: FnMut(T, &Self) -> T>(&self, init: T, f: &mut F) -> T {
463 let init = f(init, self);
464 match &self.kind {
465 ExprKind::Constant(_)
466 | ExprKind::NoOp
467 | ExprKind::Use { .. }
468 | ExprKind::Ref { .. }
469 | ExprKind::TypeDef { .. } => init,
470 ExprKind::ExplicitParens(e) => e.fold(init, f),
471 ExprKind::StructRef { source, .. } | ExprKind::TupleRef { source, .. } => {
472 source.fold(init, f)
473 }
474
475 ExprKind::Map { args } => args.iter().fold(init, |init, (k, v)| {
476 let init = k.fold(init, f);
477 v.fold(init, f)
478 }),
479 ExprKind::MapRef { source, key } => {
480 let init = source.fold(init, f);
481 key.fold(init, f)
482 }
483 ExprKind::Module { value: ModuleKind::Resolved { exprs, .. }, .. } => {
484 exprs.iter().fold(init, |init, e| e.fold(init, f))
485 }
486 ExprKind::Module {
487 value: ModuleKind::Dynamic { sandbox: _, sig: _, source },
488 ..
489 } => source.fold(init, f),
490 ExprKind::Module { value: ModuleKind::Unresolved { .. }, .. } => init,
491 ExprKind::Do { exprs } => exprs.iter().fold(init, |init, e| e.fold(init, f)),
492 ExprKind::Bind(b) => b.value.fold(init, f),
493 ExprKind::StructWith(StructWithExpr { replace, .. }) => {
494 replace.iter().fold(init, |init, (_, e)| e.fold(init, f))
495 }
496 ExprKind::Connect { value, .. } => value.fold(init, f),
497 ExprKind::Lambda(l) => match &l.body {
498 Either::Left(e) => e.fold(init, f),
499 Either::Right(_) => init,
500 },
501 ExprKind::TypeCast { expr, .. } => expr.fold(init, f),
502 ExprKind::Apply(ApplyExpr { args, function: _ }) => {
503 args.iter().fold(init, |init, (_, e)| e.fold(init, f))
504 }
505 ExprKind::Any { args }
506 | ExprKind::Array { args }
507 | ExprKind::Tuple { args }
508 | ExprKind::Variant { args, .. }
509 | ExprKind::StringInterpolate { args } => {
510 args.iter().fold(init, |init, e| e.fold(init, f))
511 }
512 ExprKind::ArrayRef { source, i } => {
513 let init = source.fold(init, f);
514 i.fold(init, f)
515 }
516 ExprKind::ArraySlice { source, start, end } => {
517 let init = source.fold(init, f);
518 let init = match start {
519 None => init,
520 Some(e) => e.fold(init, f),
521 };
522 match end {
523 None => init,
524 Some(e) => e.fold(init, f),
525 }
526 }
527 ExprKind::Struct(StructExpr { args }) => {
528 args.iter().fold(init, |init, (_, e)| e.fold(init, f))
529 }
530 ExprKind::Select(SelectExpr { arg, arms }) => {
531 let init = arg.fold(init, f);
532 arms.iter().fold(init, |init, (p, e)| {
533 let init = match p.guard.as_ref() {
534 None => init,
535 Some(g) => g.fold(init, f),
536 };
537 e.fold(init, f)
538 })
539 }
540 ExprKind::TryCatch(tc) => {
541 let init = tc.exprs.iter().fold(init, |init, e| e.fold(init, f));
542 tc.handler.fold(init, f)
543 }
544 ExprKind::Qop(e)
545 | ExprKind::OrNever(e)
546 | ExprKind::ByRef(e)
547 | ExprKind::Deref(e)
548 | ExprKind::Not { expr: e } => e.fold(init, f),
549 ExprKind::Add { lhs, rhs }
550 | ExprKind::Sub { lhs, rhs }
551 | ExprKind::Mul { lhs, rhs }
552 | ExprKind::Div { lhs, rhs }
553 | ExprKind::Mod { lhs, rhs }
554 | ExprKind::And { lhs, rhs }
555 | ExprKind::Or { lhs, rhs }
556 | ExprKind::Eq { lhs, rhs }
557 | ExprKind::Ne { lhs, rhs }
558 | ExprKind::Gt { lhs, rhs }
559 | ExprKind::Lt { lhs, rhs }
560 | ExprKind::Gte { lhs, rhs }
561 | ExprKind::Lte { lhs, rhs }
562 | ExprKind::Sample { lhs, rhs } => {
563 let init = lhs.fold(init, f);
564 rhs.fold(init, f)
565 }
566 }
567 }
568}
569
570pub struct ErrorContext(pub Expr);
571
572impl fmt::Display for ErrorContext {
573 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
574 use std::fmt::Write;
575 const MAX: usize = 38;
576 thread_local! {
577 static BUF: RefCell<String> = RefCell::new(String::new());
578 }
579 BUF.with_borrow_mut(|buf| {
580 buf.clear();
581 write!(buf, "{}", self.0).unwrap();
582 if buf.len() <= MAX {
583 write!(f, "at: {}, in: {buf}", self.0.pos)
584 } else {
585 let mut end = MAX;
586 while !buf.is_char_boundary(end) {
587 end += 1
588 }
589 let buf = &buf[0..end];
590 write!(f, "at: {}, in: {buf}..", self.0.pos)
591 }
592 })
593 }
594}