meta-language 1.0.0

A self-describing links-network core for lossless language representation
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
//! The surface AST the four frontends produce and the checker consumes.
//!
//! Its JSON form is the JavaScript runtime's (`{ "k": "binary", "op": "add", … }`),
//! so the frontends of both runtimes can be compared node for node.

use serde::{Deserialize, Deserializer, Serialize};

use super::types::Type;
use super::{Language, Span};

#[allow(clippy::trivially_copy_pass_by_ref)] // serde passes fields by reference
const fn is_false(value: &bool) -> bool {
    !*value
}

/// Numeral text: the JavaScript frontends store some pattern numerals as
/// numbers and others as decimal strings.
fn numeral<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Numeral {
        Text(String),
        Number(serde_json::Number),
    }
    Ok(match Numeral::deserialize(deserializer)? {
        Numeral::Text(text) => text,
        Numeral::Number(number) => number.to_string(),
    })
}

/// A surface expression.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SExpr {
    #[serde(flatten)]
    pub node: SNode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
    /// Set on a Rust block expression (`{ … }`) used as a value.
    #[serde(default, skip_serializing_if = "is_false")]
    pub block: bool,
    /// Set on the match a JavaScript `x.$ === 'tag'` test reads as, so an
    /// `if` on it can narrow `x`.
    #[serde(rename = "tagTest", default, skip_serializing_if = "Option::is_none")]
    pub tag_test: Option<Box<STagTest>>,
}

/// A JavaScript `x.$ === 'tag'` (or `!==`) test: the tested value, the tag
/// and the data type that has it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct STagTest {
    pub object: SExpr,
    pub tag: String,
    pub data: SData,
    pub negated: bool,
}

impl SExpr {
    #[must_use]
    pub const fn new(node: SNode, span: Option<Span>) -> Self {
        Self {
            node,
            span,
            block: false,
            tag_test: None,
        }
    }

    /// A name reference without a span, as the checker builds them.
    #[must_use]
    pub fn name(name: &str) -> Self {
        Self::new(
            SNode::Name {
                path: vec![name.to_owned()],
            },
            None,
        )
    }

    /// The single-segment name this expression refers to, if it is one.
    #[must_use]
    pub fn simple_name(&self) -> Option<&str> {
        match &self.node {
            SNode::Name { path } if path.len() == 1 => Some(&path[0]),
            _ => None,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum UnaryOp {
    Not,
    Neg,
}

/// Surface binary operators: `plus` is JavaScript's overloaded `+`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BinaryOp {
    Add,
    Sub,
    Mul,
    Div,
    Rem,
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
    And,
    Or,
    Concat,
    Plus,
}

impl BinaryOp {
    /// The operator's name in the checked program's JSON, such as `add`.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Add => "add",
            Self::Sub => "sub",
            Self::Mul => "mul",
            Self::Div => "div",
            Self::Rem => "rem",
            Self::Eq => "eq",
            Self::Ne => "ne",
            Self::Lt => "lt",
            Self::Le => "le",
            Self::Gt => "gt",
            Self::Ge => "ge",
            Self::And => "and",
            Self::Or => "or",
            Self::Concat => "concat",
            Self::Plus => "plus",
        }
    }
}

/// Division rounding a source operator asks for.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Rounding {
    Trunc,
    Euclid,
    Floor,
}

/// How a value is printed: each source language's own rendering.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ShowStyle {
    #[serde(rename = "lean")]
    Lean,
    #[serde(rename = "rocq")]
    Rocq,
    #[serde(rename = "rust")]
    Rust,
    #[serde(rename = "js-console")]
    JsConsole,
    #[serde(rename = "js-template")]
    JsTemplate,
    /// The first of several `console.log` arguments, when it is not a literal string.
    #[serde(rename = "js-format-first")]
    JsFormatFirst,
    /// The argument of a `%d` directive.
    #[serde(rename = "js-format-number")]
    JsFormatNumber,
    /// The argument of a `%i` directive.
    #[serde(rename = "js-format-integer")]
    JsFormatInteger,
}

impl ShowStyle {
    /// True for the values `console.log` shows: its argument, or those `util.format` reads.
    #[must_use]
    pub const fn is_console(self) -> bool {
        matches!(
            self,
            Self::JsConsole | Self::JsFormatFirst | Self::JsFormatNumber | Self::JsFormatInteger
        )
    }
}

/// Conversion semantics: exact, checked (aborts when out of range) or clamped.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Flavor {
    Exact,
    Checked,
    Clamp,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "k", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum SNode {
    Num {
        value: String,
        #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
        ty: Option<Type>,
        #[serde(default, skip_serializing_if = "is_false")]
        negative: bool,
        /// The 1 of `x++`, which takes the type of `x`.
        #[serde(default, skip_serializing_if = "is_false")]
        unit: bool,
    },
    Bool {
        value: bool,
    },
    Str {
        value: String,
    },
    Unit,
    Name {
        path: Vec<String>,
    },
    /// Lean's `.ctor`, resolved against the expected type.
    DotCtor {
        name: String,
    },
    App {
        #[serde(rename = "fn")]
        func: Box<SExpr>,
        args: Vec<SExpr>,
    },
    Field {
        object: Box<SExpr>,
        field: String,
    },
    Unary {
        op: UnaryOp,
        arg: Box<SExpr>,
    },
    Binary {
        op: BinaryOp,
        left: Box<SExpr>,
        right: Box<SExpr>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        rounding: Option<Rounding>,
    },
    If {
        cond: Box<SExpr>,
        then: Box<SExpr>,
        #[serde(rename = "else")]
        otherwise: Box<SExpr>,
    },
    Let {
        name: String,
        #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
        ty: Option<Type>,
        value: Box<SExpr>,
        body: Box<SExpr>,
    },
    Match {
        scrutinees: Vec<SExpr>,
        rows: Vec<SRow>,
    },
    /// A single-level match, as pattern compilation produces it.
    Match1 {
        scrutinee: Box<SExpr>,
        cases: Vec<SCase>,
    },
    ToString {
        arg: Box<SExpr>,
    },
    Show {
        arg: Box<SExpr>,
        style: ShowStyle,
    },
    Cast {
        arg: Box<SExpr>,
        to: Type,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        from: Option<Type>,
        flavor: Flavor,
    },
    Abort {
        message: String,
    },
    /// `console.log(expr)`, then `body`.
    Print {
        expr: Box<SExpr>,
        style: ShowStyle,
        body: Box<SExpr>,
    },
    /// A JavaScript `{ $: 'tag', field: value }` constructor object, fields in source order.
    CtorObject {
        tag: String,
        #[serde(with = "ordered_fields")]
        fields: Vec<(String, SExpr)>,
    },
    /// A JavaScript array literal `[a, ...xs, b]`.
    Array {
        items: Vec<SArrayItem>,
        /// The element type inference fixed for a literal with no element of its own.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        element: Option<Type>,
    },
    /// `xs[i]`, a read of an array element.
    Index {
        object: Box<SExpr>,
        index: Box<SExpr>,
    },
    /// The length of an array: a Number, or for the counter of a for…of loop a `BigInt`.
    Length {
        object: Box<SExpr>,
        integer: bool,
    },
    /// A call of a Math or Number function, `Math.max(a, ...xs)`: `op` is
    /// the function and `name` the path the program called it by.
    Math {
        op: String,
        name: String,
        args: Vec<SArrayItem>,
    },
    // Frontend-internal forms; the checker rejects them if they reach it.
    Cons {
        head: Box<SExpr>,
        tail: Box<SExpr>,
    },
    Nil,
    List {
        items: Vec<SExpr>,
    },
    Tag {
        tag: String,
    },
    Default,
}

impl SNode {
    /// The `k` discriminant.
    #[must_use]
    pub const fn kind(&self) -> &'static str {
        match self {
            Self::Num { .. } => "num",
            Self::Bool { .. } => "bool",
            Self::Str { .. } => "str",
            Self::Unit => "unit",
            Self::Name { .. } => "name",
            Self::DotCtor { .. } => "dotCtor",
            Self::App { .. } => "app",
            Self::Field { .. } => "field",
            Self::Unary { .. } => "unary",
            Self::Binary { .. } => "binary",
            Self::If { .. } => "if",
            Self::Let { .. } => "let",
            Self::Match { .. } => "match",
            Self::Match1 { .. } => "match1",
            Self::ToString { .. } => "toString",
            Self::Show { .. } => "show",
            Self::Cast { .. } => "cast",
            Self::Abort { .. } => "abort",
            Self::Print { .. } => "print",
            Self::CtorObject { .. } => "ctorObject",
            Self::Array { .. } => "array",
            Self::Index { .. } => "index",
            Self::Length { .. } => "length",
            Self::Math { .. } => "math",
            Self::Cons { .. } => "cons",
            Self::Nil => "nil",
            Self::List { .. } => "list",
            Self::Tag { .. } => "tag",
            Self::Default => "default",
        }
    }
}

/// An element of an array literal, or with `spread` the elements of an array.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SArrayItem {
    pub spread: bool,
    pub value: SExpr,
}

/// An object whose keys keep their insertion order, as JavaScript objects do.
mod ordered_fields {
    use std::fmt;

    use serde::de::{MapAccess, Visitor};
    use serde::ser::SerializeMap;
    use serde::{Deserializer, Serializer};

    use super::SExpr;

    #[allow(clippy::ptr_arg)]
    pub fn serialize<S: Serializer>(
        fields: &Vec<(String, SExpr)>,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        let mut map = serializer.serialize_map(Some(fields.len()))?;
        for (name, value) in fields {
            map.serialize_entry(name, value)?;
        }
        map.end()
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Vec<(String, SExpr)>, D::Error> {
        struct Fields;
        impl<'de> Visitor<'de> for Fields {
            type Value = Vec<(String, SExpr)>;
            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("an object of fields")
            }
            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
                let mut fields = Vec::new();
                while let Some(entry) = map.next_entry()? {
                    fields.push(entry);
                }
                Ok(fields)
            }
        }
        deserializer.deserialize_map(Fields)
    }
}

/// One row of a multi-scrutinee surface match.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SRow {
    pub patterns: Vec<SPattern>,
    pub body: SExpr,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
}

/// One case of a single-level match.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SCase {
    pub pattern: SCasePattern,
    pub body: SExpr,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
}

/// Patterns of a single-level match: one constructor, fields bound to names.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "k", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum SCasePattern {
    Wild,
    Bind {
        name: String,
    },
    NatZero,
    NatSucc {
        name: String,
    },
    Ctor {
        path: Vec<String>,
        binds: Vec<Option<String>>,
    },
}

/// A surface pattern.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SPattern {
    #[serde(flatten)]
    pub node: SPatternNode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "k", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum SPatternNode {
    Wild,
    /// A lone name: a nullary constructor when the scrutinee type has one, else a binder.
    BindOrCtor {
        name: String,
    },
    /// A binder, which the JavaScript frontend's generated matches use.
    Bind {
        name: String,
    },
    Ctor {
        path: Vec<String>,
        args: Vec<SPattern>,
    },
    NumLit {
        #[serde(deserialize_with = "numeral")]
        value: String,
        #[serde(default, skip_serializing_if = "is_false")]
        negative: bool,
    },
    BoolLit {
        value: bool,
        #[serde(default, skip_serializing_if = "is_false")]
        negative: bool,
    },
    StrLit {
        value: String,
    },
    /// Lean's `n + 2`; `add` holds the numeral's decimal digits.
    NatAdd {
        inner: Box<SPattern>,
        add: String,
    },
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SBinder {
    pub name: String,
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub ty: Option<Type>,
    /// The Rocq type as written (`N`, `nat`, `Z`), which proof steps consult.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rocq_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
}

/// A surface proposition.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SProp {
    #[serde(flatten)]
    pub node: SPropNode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SComparison {
    pub left: SExpr,
    pub right: SExpr,
    /// JavaScript's `assert.equal`, which compares objects by identity.
    #[serde(default, skip_serializing_if = "is_false")]
    pub reference: bool,
    /// `assert.strictEqual` and its kin compare with `SameValue`
    /// (`Object.is`): `NaN` equals `NaN`, and `0` differs from `-0`.
    #[serde(default, rename = "sameValue", skip_serializing_if = "is_false")]
    pub same_value: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "p", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum SPropNode {
    Forall {
        binders: Vec<SBinder>,
        body: Box<SProp>,
    },
    And {
        left: Box<SProp>,
        right: Box<SProp>,
    },
    Or {
        left: Box<SProp>,
        right: Box<SProp>,
    },
    Implies {
        left: Box<SProp>,
        right: Box<SProp>,
    },
    Not {
        arg: Box<SProp>,
    },
    Bool {
        expr: SExpr,
    },
    Eq(SComparison),
    Ne(SComparison),
    Lt(SComparison),
    Le(SComparison),
    Gt(SComparison),
    Ge(SComparison),
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SRule {
    pub name: String,
    pub reverse: bool,
}

/// A proof step: `t` names the tactic family.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "t", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum SStep {
    Compute {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tactic: Option<String>,
    },
    Arith {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tactic: Option<String>,
    },
    Intro {
        names: Vec<String>,
    },
    Unfold {
        names: Vec<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tactic: Option<String>,
    },
    Simp {
        rules: Vec<SRule>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        only: Option<bool>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tactic: Option<String>,
    },
    Rewrite {
        rules: Vec<SRule>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        only: Option<bool>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tactic: Option<String>,
    },
    Induction(SSplit),
    Cases(SSplit),
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SSplit {
    pub variable: String,
    pub cases: Vec<SSplitCase>,
    /// Rocq names cases by position; Lean by constructor.
    #[serde(default, skip_serializing_if = "is_false")]
    pub positional: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub blocks: Option<usize>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SSplitCase {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ctor: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub index: Option<usize>,
    pub binds: Vec<Option<String>>,
    pub steps: Vec<SStep>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SProof {
    pub steps: Vec<SStep>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    pub source_language: Language,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SField {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(rename = "type")]
    pub ty: Type,
    /// The type as written, on a Rocq constructor field declared as a binder `(x : N)`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rocq_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SCtor {
    pub name: String,
    pub fields: Vec<SField>,
}

/// The leading `if (n < 0n) throw …` of a JavaScript parameter: a negative
/// argument aborts with its message, the guards in their order.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Guard {
    pub message: String,
    pub order: usize,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SParam {
    pub name: String,
    #[serde(default, rename = "default", skip_serializing_if = "Option::is_none")]
    pub default_value: Option<SExpr>,
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub ty: Option<Type>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
    /// A JavaScript parameter restricted to the naturals by a leading guard.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub guard: Option<Guard>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rocq_type: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SData {
    pub name: String,
    pub ctors: Vec<SCtor>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
    /// A data type the translator made up, whose name may use the reserved `ml_` prefix.
    #[serde(default, skip_serializing_if = "is_false")]
    pub generated: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SFn {
    pub name: String,
    pub params: Vec<SParam>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ret: Option<Type>,
    pub body: SExpr,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
    /// A function the translator made up, such as a lifted loop.
    #[serde(default, skip_serializing_if = "is_false")]
    pub generated: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct STheorem {
    pub name: String,
    pub binders: Vec<SBinder>,
    pub prop: SProp,
    pub proof: SProof,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SModule {
    pub name: String,
    pub items: Vec<SItem>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "k", rename_all = "camelCase")]
pub enum SItem {
    Data(SData),
    Fn(SFn),
    Theorem(STheorem),
    Module(SModule),
}

impl SItem {
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Self::Data(item) => &item.name,
            Self::Fn(item) => &item.name,
            Self::Theorem(item) => &item.name,
            Self::Module(item) => &item.name,
        }
    }

    #[must_use]
    pub const fn span(&self) -> Option<Span> {
        match self {
            Self::Data(item) => item.span,
            Self::Fn(item) => item.span,
            Self::Theorem(item) => item.span,
            Self::Module(item) => item.span,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "k", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum SEffect {
    Print {
        expr: SExpr,
        style: ShowStyle,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        span: Option<Span>,
    },
    Let {
        name: String,
        #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
        ty: Option<Type>,
        value: SExpr,
        #[serde(default, skip_serializing_if = "is_false")]
        constant: bool,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        span: Option<Span>,
    },
    Assert {
        prop: SProp,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        span: Option<Span>,
    },
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SMain {
    pub effects: Vec<SEffect>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
    /// Every call of an async function is awaited where it is made.
    #[serde(rename = "sequentialAsync", default, skip_serializing_if = "is_false")]
    pub sequential_async: bool,
}

/// A parsed source program.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SProgram {
    pub language: Language,
    pub items: Vec<SItem>,
    #[serde(default)]
    pub main: Option<SMain>,
}