calcit_runner 0.5.25

Interpreter and js codegen for Calcit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
use crate::{
  builtins::{is_js_syntax_procs, is_proc_name},
  call_stack::{extend_call_stack, CalcitStack, CallStackList, StackKind},
  primes,
  primes::{Calcit, CalcitErr, CalcitItems, CalcitSyntax, ImportRule, SymbolResolved::*},
  program, runner,
};

use std::cell::RefCell;
use std::collections::HashSet;
use std::sync::Arc;

use im_ternary_tree::TernaryTreeList;

/// only macro and func are cared about during preprocessing
/// only used in preprocess defs
fn pick_macro_fn(x: Calcit) -> Option<Calcit> {
  match &x {
    Calcit::Fn { .. } | Calcit::Macro { .. } => Some(x),
    _ => None,
  }
}

/// returns the resolved symbol,
/// if code related is not preprocessed, do it internally
pub fn preprocess_ns_def(
  raw_ns: Arc<str>,
  raw_def: Arc<str>,
  // pass original string representation, TODO codegen currently relies on this
  raw_sym: Arc<str>,
  import_rule: Option<Arc<ImportRule>>, // returns form and possible value
  check_warnings: &RefCell<Vec<String>>,
  call_stack: &rpds::ListSync<CalcitStack>,
) -> Result<(Calcit, Option<Calcit>), CalcitErr> {
  let ns = &raw_ns;
  let def = &raw_def;
  let original_sym = &raw_sym;
  // println!("preprocessing def: {}/{}", ns, def);
  match program::lookup_evaled_def(ns, def) {
    Some(v) => {
      // println!("{}/{} has inited", ns, def);
      Ok((
        Calcit::Symbol {
          sym: original_sym.to_owned(),
          ns: ns.to_owned(),
          at_def: def.to_owned(),
          resolved: Some(Arc::new(ResolvedDef {
            ns: ns.to_owned(),
            def: def.to_owned(),
            rule: import_rule,
          })),
        },
        pick_macro_fn(v),
      ))
    }
    None => {
      // println!("init for... {}/{}", ns, def);
      match program::lookup_def_code(ns, def) {
        Some(code) => {
          // write a nil value first to prevent dead loop
          program::write_evaled_def(ns, def, Calcit::Nil).map_err(|e| CalcitErr::use_msg_stack(e, call_stack))?;

          let next_stack = extend_call_stack(
            call_stack,
            ns.to_owned(),
            def.to_owned(),
            StackKind::Fn,
            code.to_owned(),
            &TernaryTreeList::Empty,
          );

          let (resolved_code, _resolve_value) = preprocess_expr(&code, &HashSet::new(), ns.to_owned(), check_warnings, &next_stack)?;
          // println!("\n resolve code to run: {:?}", resolved_code);
          let v = if is_fn_or_macro(&resolved_code) {
            match runner::evaluate_expr(&resolved_code, &rpds::HashTrieMap::new_sync(), ns.to_owned(), &next_stack) {
              Ok(ret) => ret,
              Err(e) => return Err(e),
            }
          } else {
            Calcit::Thunk(Arc::new(resolved_code), None)
          };
          // println!("\nwriting value to: {}/{} {:?}", ns, def, v);
          program::write_evaled_def(ns, def, v.to_owned()).map_err(|e| CalcitErr::use_msg_stack(e, call_stack))?;

          Ok((
            Calcit::Symbol {
              sym: original_sym.to_owned(),
              ns: ns.to_owned(),
              at_def: def.to_owned(),
              resolved: Some(Arc::new(ResolvedDef {
                ns: ns.to_owned(),
                def: def.to_owned(),
                rule: Some(Arc::new(ImportRule::NsReferDef(ns.to_owned(), def.to_owned()))),
              })),
            },
            pick_macro_fn(v),
          ))
        }
        None if ns.starts_with('|') || ns.starts_with('"') => Ok((
          Calcit::Symbol {
            sym: original_sym.to_owned(),
            ns: ns.to_owned(),
            at_def: def.to_owned(),
            resolved: Some(Arc::new(ResolvedDef {
              ns: ns.to_owned(),
              def: def.to_owned(),
              rule: import_rule,
            })),
          },
          None,
        )),
        None => Err(CalcitErr::use_msg_stack(
          format!("unknown ns/def in program: {}/{}", ns, def),
          call_stack,
        )),
      }
    }
  }
}

fn is_fn_or_macro(code: &Calcit) -> bool {
  match code {
    Calcit::List(xs) => match xs.get(0) {
      Some(Calcit::Symbol { sym, .. }) => &**sym == "defn" || &**sym == "defmacro",
      Some(Calcit::Syntax(s, ..)) => s == &CalcitSyntax::Defn || s == &CalcitSyntax::Defmacro,
      _ => false,
    },
    _ => false,
  }
}

pub fn preprocess_expr(
  expr: &Calcit,
  scope_defs: &HashSet<Arc<str>>,
  file_ns: Arc<str>,
  check_warnings: &RefCell<Vec<String>>,
  call_stack: &CallStackList,
) -> Result<(Calcit, Option<Calcit>), CalcitErr> {
  // println!("preprocessing @{} {}", file_ns, expr);
  match expr {
    Calcit::Symbol {
      sym: def,
      ns: def_ns,
      at_def,
      ..
    } => match runner::parse_ns_def(def) {
      Some((ns_alias, def_part)) => {
        if &*ns_alias == "js" {
          Ok((
            Calcit::Symbol {
              sym: def.to_owned(),
              ns: def_ns.to_owned(),
              at_def: at_def.to_owned(),
              resolved: Some(Arc::new(ResolvedDef {
                ns: String::from("js").into(),
                def: (*def_part).into(),
                rule: None,
              })),
            },
            None,
          ))
        } else if let Some(target_ns) = program::lookup_ns_target_in_import(def_ns.to_owned(), &ns_alias) {
          // TODO js syntax to handle in future
          preprocess_ns_def(target_ns, def_part, def.to_owned(), None, check_warnings, call_stack)
        } else if program::has_def_code(&ns_alias, &def_part) {
          // refer to namespace/def directly for some usages
          preprocess_ns_def(ns_alias.to_owned(), def_part, def.to_owned(), None, check_warnings, call_stack)
        } else {
          Err(CalcitErr::use_msg_stack(format!("unknown ns target: {}", def), call_stack))
        }
      }
      None => {
        let def_ref = &**def;
        if def_ref == "~" || def_ref == "~@" || def_ref == "&" || def_ref == "?" {
          Ok((
            Calcit::Symbol {
              sym: def.to_owned(),
              ns: def_ns.to_owned(),
              at_def: at_def.to_owned(),
              resolved: Some(Arc::new(ResolvedRaw)),
            },
            None,
          ))
        } else if scope_defs.contains(def) {
          Ok((
            Calcit::Symbol {
              sym: def.to_owned(),
              ns: def_ns.to_owned(),
              at_def: at_def.to_owned(),
              resolved: Some(Arc::new(ResolvedLocal)),
            },
            None,
          ))
        } else if CalcitSyntax::is_core_syntax(def) {
          Ok((
            Calcit::Syntax(
              CalcitSyntax::from(def).map_err(|e| CalcitErr::use_msg_stack(e, call_stack))?,
              def_ns.to_owned(),
            ),
            None,
          ))
        } else if is_proc_name(def) {
          Ok((Calcit::Proc(def.to_owned()), None))
        } else if program::has_def_code(primes::CORE_NS, def) {
          preprocess_ns_def(
            primes::CORE_NS.into(),
            def.to_owned(),
            def.to_owned(),
            None,
            check_warnings,
            call_stack,
          )
        } else if program::has_def_code(def_ns, def) {
          preprocess_ns_def(def_ns.to_owned(), def.to_owned(), def.to_owned(), None, check_warnings, call_stack)
        } else {
          match program::lookup_def_target_in_import(def_ns, def) {
            Some(target_ns) => {
              // effect
              // TODO js syntax to handle in future
              preprocess_ns_def(target_ns, def.to_owned(), def.to_owned(), None, check_warnings, call_stack)
            }
            // TODO check js_mode
            None if is_js_syntax_procs(def) => Ok((expr.to_owned(), None)),
            None if def.starts_with('.') => Ok((expr.to_owned(), None)),
            None => {
              let from_default = program::lookup_default_target_in_import(def_ns, def);
              if let Some(target_ns) = from_default {
                let target = Some(Arc::new(ResolvedDef {
                  ns: target_ns.to_owned(),
                  def: def.to_owned(),
                  rule: Some(Arc::new(ImportRule::NsDefault(target_ns))),
                }));
                Ok((
                  Calcit::Symbol {
                    sym: def.to_owned(),
                    ns: def_ns.to_owned(),
                    at_def: at_def.to_owned(),
                    resolved: target,
                  },
                  None,
                ))
              } else {
                let mut names: Vec<Arc<str>> = Vec::with_capacity(scope_defs.len());
                for def in scope_defs {
                  names.push(def.to_owned());
                }
                let mut warnings = check_warnings.borrow_mut();
                warnings.push(format!(
                  "[Warn] unknown `{}` in {}/{}, locals {{{}}}",
                  def,
                  def_ns,
                  at_def,
                  names.join(" ")
                ));
                Ok((expr.to_owned(), None))
              }
            }
          }
        }
      }
    },
    Calcit::List(xs) => {
      if xs.is_empty() {
        Ok((expr.to_owned(), None))
      } else {
        // TODO whether function bothers this...
        // println!("start calling: {}", expr);
        process_list_call(xs, scope_defs, file_ns, check_warnings, call_stack)
      }
    }
    Calcit::Number(..) | Calcit::Str(..) | Calcit::Nil | Calcit::Bool(..) | Calcit::Keyword(..) => Ok((expr.to_owned(), None)),
    Calcit::Proc(..) => {
      // maybe detect method in future
      Ok((expr.to_owned(), None))
    }

    _ => {
      let mut warnings = check_warnings.borrow_mut();
      warnings.push(format!("[Warn] unexpected data during preprocess: {:?}", expr));
      Ok((expr.to_owned(), None))
    }
  }
}

fn process_list_call(
  xs: &CalcitItems,
  scope_defs: &HashSet<Arc<str>>,
  file_ns: Arc<str>,
  check_warnings: &RefCell<Vec<String>>,
  call_stack: &CallStackList,
) -> Result<(Calcit, Option<Calcit>), CalcitErr> {
  let head = &xs[0];
  let (head_form, head_evaled) = preprocess_expr(head, scope_defs, file_ns.to_owned(), check_warnings, call_stack)?;
  let args = xs.drop_left();
  let def_name = grab_def_name(head);

  // println!(
  //   "handling list call: {} {:?}, {}",
  //   primes::CrListWrap(xs.to_owned()),
  //   head_form,
  //   if head_evaled.is_some() {
  //     head_evaled.to_owned().unwrap()
  //   } else {
  //     Calcit::Nil
  //   }
  // );

  // == Tips ==
  // Macro from value: will be called during processing
  // Func from value: for checking arity
  // Keyword: transforming into keyword expression
  // Syntax: handled directly during preprocessing
  // Thunk: invalid here
  match (&head_form, &head_evaled) {
    (Calcit::Keyword(..), _) => {
      if args.len() == 1 {
        let code = Calcit::List(TernaryTreeList::from(&[
          Calcit::Symbol {
            sym: String::from("get").into(),
            ns: String::from(primes::CORE_NS).into(),
            at_def: String::from(primes::GENERATED_DEF).into(),
            resolved: Some(Arc::new(ResolvedDef {
              ns: String::from(primes::CORE_NS).into(),
              def: String::from("get").into(),
              rule: None,
            })),
          },
          args[0].to_owned(),
          head.to_owned(),
        ]));
        preprocess_expr(&code, scope_defs, file_ns, check_warnings, call_stack)
      } else {
        Err(CalcitErr::use_msg_stack(format!("{} expected single argument", head), call_stack))
      }
    }
    (
      _,
      Some(Calcit::Macro {
        name,
        def_ns,
        args: def_args,
        body,
        ..
      }),
    ) => {
      let mut current_values = Box::new(args.to_owned());

      // println!("eval macro: {}", primes::CrListWrap(xs.to_owned()));
      // println!("macro... {} {}", x, CrListWrap(current_values.to_owned()));

      let code = Calcit::List(xs.to_owned());
      let next_stack = extend_call_stack(call_stack, def_ns.to_owned(), name.to_owned(), StackKind::Macro, code, &args);

      loop {
        // need to handle recursion
        // println!("evaling line: {:?}", body);
        let body_scope = runner::bind_args(def_args, &current_values, &rpds::HashTrieMap::new_sync(), &next_stack)?;
        let code = runner::evaluate_lines(body, &body_scope, def_ns.to_owned(), &next_stack)?;
        match code {
          Calcit::Recur(ys) => {
            current_values = Box::new(ys.to_owned());
          }
          _ => {
            // println!("gen code: {} {}", code, &code.lisp_str());
            return preprocess_expr(&code, scope_defs, file_ns, check_warnings, &next_stack);
          }
        }
      }
    }
    (Calcit::Syntax(name, name_ns), _) => match name {
      CalcitSyntax::Quasiquote => Ok((
        preprocess_quasiquote(name, name_ns.to_owned(), &args, scope_defs, file_ns, check_warnings, call_stack)?,
        None,
      )),
      CalcitSyntax::Defn | CalcitSyntax::Defmacro => Ok((
        preprocess_defn(name, name_ns.to_owned(), &args, scope_defs, file_ns, check_warnings, call_stack)?,
        None,
      )),
      CalcitSyntax::CoreLet => Ok((
        preprocess_call_let(name, name_ns.to_owned(), &args, scope_defs, file_ns, check_warnings, call_stack)?,
        None,
      )),
      CalcitSyntax::If
      | CalcitSyntax::Try
      | CalcitSyntax::Macroexpand
      | CalcitSyntax::MacroexpandAll
      | CalcitSyntax::Macroexpand1
      | CalcitSyntax::Reset => Ok((
        preprocess_each_items(name, name_ns.to_owned(), &args, scope_defs, file_ns, check_warnings, call_stack)?,
        None,
      )),
      CalcitSyntax::Quote | CalcitSyntax::Eval | CalcitSyntax::HintFn => {
        Ok((preprocess_quote(name, name_ns.to_owned(), &args, scope_defs, file_ns)?, None))
      }
      CalcitSyntax::Defatom => Ok((
        preprocess_defatom(name, name_ns.to_owned(), &args, scope_defs, file_ns, check_warnings, call_stack)?,
        None,
      )),
    },
    (Calcit::Thunk(..), _) => Err(CalcitErr::use_msg_stack(
      format!("does not know how to preprocess a thunk: {}", head),
      call_stack,
    )),

    (
      _,
      Some(Calcit::Fn {
        name: f_name,
        args: f_args,
        ..
      }),
    ) => {
      check_fn_args(f_args, &args, file_ns.to_owned(), f_name.to_owned(), def_name, check_warnings);
      let mut ys = Vec::with_capacity(args.len() + 1);
      ys.push(head_form);
      for a in &args {
        let (form, _v) = preprocess_expr(a, scope_defs, file_ns.to_owned(), check_warnings, call_stack)?;
        ys.push(form);
      }
      Ok((Calcit::List(TernaryTreeList::from(&ys)), None))
    }
    (_, _) => {
      let mut ys = Vec::with_capacity(args.len() + 1);
      ys.push(head_form);
      for a in &args {
        let (form, _v) = preprocess_expr(a, scope_defs, file_ns.to_owned(), check_warnings, call_stack)?;
        ys.push(form);
      }
      Ok((Calcit::List(TernaryTreeList::from(&ys)), None))
    }
  }
}

// detects arguments of top-level functions when possible
fn check_fn_args(
  defined_args: &[Arc<str>],
  params: &CalcitItems,
  file_ns: Arc<str>,
  f_name: Arc<str>,
  def_name: Arc<str>,
  check_warnings: &RefCell<Vec<String>>,
) {
  let mut i = 0;
  let mut j = 0;
  let mut optional = false;

  loop {
    let d = defined_args.get(i);
    let r = params.get(j);

    match (d, r) {
      (None, None) => return,
      (_, Some(Calcit::Symbol { sym, .. })) if &**sym == "&" => {
        // dynamic values, can't tell yet
        return;
      }
      (Some(sym), _) if &**sym == "&" => {
        // dynamic args rule, all okay
        return;
      }
      (Some(sym), _) if &**sym == "?" => {
        // dynamic args rule, all okay
        optional = true;
        i += 1;
        continue;
      }
      (Some(_), None) => {
        if optional {
          i += 1;
          j += 1;
          continue;
        } else {
          let mut warnings = check_warnings.borrow_mut();
          warnings.push(format!(
            "[Warn] lack of args in {} `{:?}` with `{}`, at {}/{}",
            f_name,
            defined_args,
            primes::CrListWrap(params.to_owned()),
            file_ns,
            def_name
          ));
          return;
        }
      }
      (None, Some(_)) => {
        let mut warnings = check_warnings.borrow_mut();
        warnings.push(format!(
          "[Warn] too many args for {} `{:?}` with `{}`, at {}/{}",
          f_name,
          defined_args,
          primes::CrListWrap(params.to_owned()),
          file_ns,
          def_name
        ));
        return;
      }
      (Some(_), Some(_)) => {
        i += 1;
        j += 1;
        continue;
      }
    }
  }
}

// TODO this native implementation only handles symbols
fn grab_def_name(x: &Calcit) -> Arc<str> {
  match x {
    Calcit::Symbol { at_def: def_name, .. } => def_name.to_owned(),
    _ => String::from("??").into(),
  }
}

// tradition rule for processing exprs
pub fn preprocess_each_items(
  head: &CalcitSyntax,
  head_ns: Arc<str>,
  args: &CalcitItems,
  scope_defs: &HashSet<Arc<str>>,
  file_ns: Arc<str>,
  check_warnings: &RefCell<Vec<String>>,
  call_stack: &CallStackList,
) -> Result<Calcit, CalcitErr> {
  let mut xs: CalcitItems = TernaryTreeList::from(&[Calcit::Syntax(head.to_owned(), head_ns)]);
  for a in args {
    let (form, _v) = preprocess_expr(a, scope_defs, file_ns.to_owned(), check_warnings, call_stack)?;
    xs = xs.push_right(form);
  }
  Ok(Calcit::List(xs))
}

pub fn preprocess_defn(
  head: &CalcitSyntax,
  head_ns: Arc<str>,
  args: &CalcitItems,
  scope_defs: &HashSet<Arc<str>>,
  file_ns: Arc<str>,
  check_warnings: &RefCell<Vec<String>>,
  call_stack: &CallStackList,
) -> Result<Calcit, CalcitErr> {
  // println!("defn args: {}", primes::CrListWrap(args.to_owned()));
  let mut xs: CalcitItems = TernaryTreeList::from(&[Calcit::Syntax(head.to_owned(), head_ns)]);
  match (args.get(0), args.get(1)) {
    (
      Some(Calcit::Symbol {
        sym: def_name,
        ns: def_name_ns,
        at_def,
        ..
      }),
      Some(Calcit::List(ys)),
    ) => {
      let mut body_defs: HashSet<Arc<str>> = scope_defs.to_owned();

      xs = xs.push_right(Calcit::Symbol {
        sym: def_name.to_owned(),
        ns: def_name_ns.to_owned(),
        at_def: at_def.to_owned(),
        resolved: Some(Arc::new(ResolvedRaw)),
      });
      let mut zs: CalcitItems = TernaryTreeList::Empty;
      for y in ys {
        match y {
          Calcit::Symbol {
            sym, ns: def_ns, at_def, ..
          } => {
            check_symbol(sym, args, check_warnings);
            zs = zs.push_right(Calcit::Symbol {
              sym: sym.to_owned(),
              ns: def_ns.to_owned(),
              at_def: at_def.to_owned(),
              resolved: Some(Arc::new(ResolvedRaw)),
            });
            // skip argument syntax marks
            if &**sym != "&" && &**sym != "?" {
              body_defs.insert(sym.to_owned());
            }
          }
          _ => {
            return Err(CalcitErr::use_msg_stack(
              format!("expected defn args to be symbols, got: {}", y),
              call_stack,
            ))
          }
        }
      }
      xs = xs.push_right(Calcit::List(zs));

      for (idx, a) in args.into_iter().enumerate() {
        if idx >= 2 {
          let (form, _v) = preprocess_expr(a, &body_defs, file_ns.to_owned(), check_warnings, call_stack)?;
          xs = xs.push_right(form);
        }
      }
      Ok(Calcit::List(xs))
    }
    (Some(a), Some(b)) => Err(CalcitErr::use_msg_stack(
      format!("defn/defmacro expected name and args: {} {}", a, b),
      call_stack,
    )),
    (a, b) => Err(CalcitErr::use_msg_stack(
      format!("defn or defmacro expected name and args, got {:?} {:?}", a, b,),
      call_stack,
    )),
  }
}

// warn if this symbol is used
fn check_symbol(sym: &str, args: &CalcitItems, check_warnings: &RefCell<Vec<String>>) {
  if is_proc_name(sym) || CalcitSyntax::is_core_syntax(sym) || program::has_def_code(primes::CORE_NS, sym) {
    let mut warnings = check_warnings.borrow_mut();
    warnings.push(format!(
      "[Warn] local binding `{}` shadowed `calcit.core/{}`, with {}",
      sym,
      sym,
      primes::CrListWrap(args.to_owned())
    ));
  }
}

pub fn preprocess_call_let(
  head: &CalcitSyntax,
  head_ns: Arc<str>,
  args: &CalcitItems,
  scope_defs: &HashSet<Arc<str>>,
  file_ns: Arc<str>,
  check_warnings: &RefCell<Vec<String>>,
  call_stack: &CallStackList,
) -> Result<Calcit, CalcitErr> {
  let mut xs: CalcitItems = TernaryTreeList::from(&[Calcit::Syntax(head.to_owned(), head_ns)]);
  let mut body_defs: HashSet<Arc<str>> = scope_defs.to_owned();
  let binding = match args.get(0) {
    Some(Calcit::Nil) => Calcit::Nil,
    Some(Calcit::List(ys)) if ys.len() == 2 => match (&ys[0], &ys[1]) {
      (Calcit::Symbol { sym, .. }, a) => {
        check_symbol(sym, args, check_warnings);
        body_defs.insert(sym.to_owned());
        let (form, _v) = preprocess_expr(a, &body_defs, file_ns.to_owned(), check_warnings, call_stack)?;
        Calcit::List(TernaryTreeList::from(&[ys[0].to_owned(), form]))
      }
      (a, b) => {
        return Err(CalcitErr::use_msg_stack(
          format!("invalid pair for &let binding: {} {}", a, b),
          call_stack,
        ))
      }
    },
    Some(Calcit::List(ys)) => {
      return Err(CalcitErr::use_msg_stack(
        format!("expected binding of a pair, got {:?}", ys),
        call_stack,
      ))
    }
    Some(a) => {
      return Err(CalcitErr::use_msg_stack(
        format!("expected binding of a pair, got {}", a),
        call_stack,
      ))
    }
    None => {
      return Err(CalcitErr::use_msg_stack(
        "expected binding of a pair, got nothing".to_owned(),
        call_stack,
      ))
    }
  };
  xs = xs.push_right(binding);
  for (idx, a) in args.into_iter().enumerate() {
    if idx > 0 {
      let (form, _v) = preprocess_expr(a, &body_defs, file_ns.to_owned(), check_warnings, call_stack)?;
      xs = xs.push_right(form);
    }
  }
  Ok(Calcit::List(xs))
}

pub fn preprocess_quote(
  head: &CalcitSyntax,
  head_ns: Arc<str>,
  args: &CalcitItems,
  _scope_defs: &HashSet<Arc<str>>,
  _file_ns: Arc<str>,
) -> Result<Calcit, CalcitErr> {
  let mut xs: CalcitItems = TernaryTreeList::from(&[Calcit::Syntax(head.to_owned(), head_ns)]);
  for a in args {
    xs = xs.push_right(a.to_owned());
  }
  Ok(Calcit::List(xs))
}

pub fn preprocess_defatom(
  head: &CalcitSyntax,
  head_ns: Arc<str>,
  args: &CalcitItems,
  scope_defs: &HashSet<Arc<str>>,
  file_ns: Arc<str>,
  check_warnings: &RefCell<Vec<String>>,
  call_stack: &CallStackList,
) -> Result<Calcit, CalcitErr> {
  let mut xs: CalcitItems = TernaryTreeList::from(&[Calcit::Syntax(head.to_owned(), head_ns)]);
  for a in args {
    // TODO
    let (form, _v) = preprocess_expr(a, scope_defs, file_ns.to_owned(), check_warnings, call_stack)?;
    xs = xs.push_right(form.to_owned());
  }
  Ok(Calcit::List(xs))
}

/// need to handle experssions inside unquote snippets
pub fn preprocess_quasiquote(
  head: &CalcitSyntax,
  head_ns: Arc<str>,
  args: &CalcitItems,
  scope_defs: &HashSet<Arc<str>>,
  file_ns: Arc<str>,
  check_warnings: &RefCell<Vec<String>>,
  call_stack: &CallStackList,
) -> Result<Calcit, CalcitErr> {
  let mut xs: CalcitItems = TernaryTreeList::from(&[Calcit::Syntax(head.to_owned(), head_ns)]);
  for a in args {
    xs = xs.push_right(preprocess_quasiquote_internal(
      a,
      scope_defs,
      file_ns.to_owned(),
      check_warnings,
      call_stack,
    )?);
  }
  Ok(Calcit::List(xs))
}

pub fn preprocess_quasiquote_internal(
  x: &Calcit,
  scope_defs: &HashSet<Arc<str>>,
  file_ns: Arc<str>,
  check_warnings: &RefCell<Vec<String>>,
  call_stack: &CallStackList,
) -> Result<Calcit, CalcitErr> {
  match x {
    Calcit::List(ys) if ys.is_empty() => Ok(x.to_owned()),
    Calcit::List(ys) => match &ys[0] {
      Calcit::Symbol { sym, .. } if &**sym == "~" || &**sym == "~@" => {
        let mut xs: CalcitItems = TernaryTreeList::Empty;
        for y in ys {
          let (form, _) = preprocess_expr(y, scope_defs, file_ns.to_owned(), check_warnings, call_stack)?;
          xs = xs.push_right(form.to_owned());
        }
        Ok(Calcit::List(xs))
      }
      _ => {
        let mut xs: CalcitItems = TernaryTreeList::Empty;
        for y in ys {
          xs = xs.push_right(preprocess_quasiquote_internal(y, scope_defs, file_ns.to_owned(), check_warnings, call_stack)?.to_owned());
        }
        Ok(Calcit::List(xs))
      }
    },
    _ => Ok(x.to_owned()),
  }
}