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
mod into_value;
mod literal;
mod range;

pub use crate::ast::range::TextRange;
use crate::{
    value::{parse_number, Decimal, Integer, Text, TextDelimiter},
    Value,
};
use num::{BigInt, Num};
use std::fmt::{self, Debug, Formatter};

#[derive(Clone, Eq, PartialEq)]
pub struct AST {
    /// AST data
    pub kind: ASTKind,
    /// 1-indexed start to end position
    pub range: Option<TextRange>,
    /// Whitespace, Newline, Comment
    pub additional: Option<String>,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ASTKind {
    /// Placeholder
    /// Unreachable structure
    None,
    /// Root of all nodes
    Program(Vec<AST>),
    /// Flattened structure
    Sequence(Vec<AST>),
    /// Plain Text, NewLines
    Span(String),
    /// `[list.scope]`
    ListScope(usize, Box<AST>),
    /// `{dict.scope}`
    DictScope(usize, Box<AST>),
    ///
    Pair(Box<AST>, Box<AST>),
    /// `null`
    Null,
    /// `true` | `false`
    Boolean(bool),
    ///
    String(Box<Text>),
    ///
    Namespace(Vec<AST>),
    ///
    Integer(Box<Integer>),
    ///
    Decimal(Box<Decimal>),
    ///
    Cite(Box<AST>),
    ///
    Dict(Vec<AST>),
    ///
    List(Vec<AST>),
}

impl Debug for AST {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            AST { kind, range, additional } => {
                let mut builder = f.debug_struct("AST");
                builder.field("kind", kind);
                if let Some(s) = range {
                    builder.field("range", s);
                }
                if let Some(s) = additional {
                    builder.field("additional", s);
                }
                builder.finish()
            }
        }
    }
}

impl Default for AST {
    fn default() -> Self {
        Self { kind: ASTKind::None, range: Default::default(), additional: None }
    }
}

impl From<ASTKind> for AST {
    fn from(kind: ASTKind) -> Self {
        Self { kind, range: None, additional: None }
    }
}

// impl AST {
//     pub fn as_vec(&self) -> Vec<AST> {
//         match &self.kind {
//             ASTKind::Program(v) | ASTKind::Block(v) => v.to_owned(),
//             _ => vec![],
//         }
//     }
// }

impl AST {
    pub fn set_additional(&mut self, info: impl Into<String>) {
        self.additional = Some(info.into())
    }
    pub fn set_range(&mut self, range: TextRange) {
        self.range = Some(range)
    }
}

impl AST {
    pub fn program(children: Vec<AST>) -> Self {
        Self { kind: ASTKind::Program(children), range: None, additional: None }
    }
    pub fn block(children: Vec<AST>) -> Self {
        Self { kind: ASTKind::Sequence(children), range: None, additional: None }
    }
    // pub fn statement(children: Vec<AST>, r: TextRange) -> Self {
    //     Self { kind: ASTKind::Statement(children), range: box_range(r) }
    // }
    //
    // pub fn if_else_chain(cds: Vec<AST>, acts: Vec<AST>, r: TextRange) -> Self {
    //     let kind = ASTKind::IfElseChain(Box::new(IfElseChain::build(cds, acts)));
    //     Self { kind, range: box_range(r) }
    // }
    //
    // pub fn for_in_loop(pattern: AST, terms: AST, block: AST, guard: Option<AST>, for_else: Option<AST>, r: TextRange) -> Self {
    //     let kind = ASTKind::ForInLoop(Box::new(ForInLoop { pattern, terms, guard, block, for_else }));
    //     Self { kind, range: box_range(r) }
    // }
    //
    // pub fn expression(children: AST, eos: bool, r: TextRange) -> Self {
    //     let kind = ASTKind::Expression(Box::new(children), eos);
    //     Self { kind, range: box_range(r) }
    // }
    //
    // pub fn operation(op: &str, kind: &str, r: TextRange) -> Self {
    //     let o = match kind {
    //         "<" => Operator::prefix(op),
    //         ">" => Operator::suffix(op),
    //         _ => Operator::infix(op),
    //     };
    //     let kind = ASTKind::Operator(Box::new(o));
    //     Self { kind, range: box_range(r) }
    // }
    //
    // pub fn string_expression(value: Vec<AST>, handler: Option<AST>, r: TextRange) -> Self {
    //     let kind = ASTKind::StringExpression(Box::new(StringExpression { handler, inner: value }));
    //     Self { kind, range: box_range(r) }
    // }
    //
    // pub fn infix_expression(op: AST, lhs: AST, rhs: AST, r: TextRange) -> Self {
    //     let kind = ASTKind::InfixExpression(Box::new(InfixExpression { op, lhs, rhs }));
    //     Self { kind, range: box_range(r) }
    // }
    //
    // pub fn prefix_expression(op: AST, rhs: AST, r: TextRange) -> Self {
    //     let kind = ASTKind::PrefixExpression(Box::new(UnaryExpression { op, base: rhs }));
    //     Self { kind, range: box_range(r) }
    // }
    //
    // pub fn suffix_expression(op: AST, lhs: AST, r: TextRange) -> Self {
    //     let kind = ASTKind::PrefixExpression(Box::new(UnaryExpression { op, base: lhs }));
    //     Self { kind, range: box_range(r) }
    // }
    //
    // pub fn call_chain(chain: CallChain, r: TextRange) -> Self {
    //     Self { kind: ASTKind::CallChain(Box::new(chain)), range: box_range(r) }
    // }
    //
    // pub fn call_index(index: &str, r: TextRange) -> Self {
    //     let n = BigInt::parse_bytes(index.as_bytes(), 10).unwrap_or_default();
    //     Self { kind: ASTKind::CallIndex(Box::new(n)), range: box_range(r) }
    // }
    //
    // pub fn template(value: Template, r: TextRange) -> Self {
    //     Self { kind: ASTKind::Template(Box::new(value)), range: box_range(r) }
    // }
    //
    pub fn null() -> Self {
        Self { kind: ASTKind::Null, range: None, additional: None }
    }

    pub fn boolean(value: bool) -> Self {
        Self { kind: ASTKind::Boolean(value), range: None, additional: None }
    }
    pub fn string(value: Text) -> Self {
        Self { kind: ASTKind::String(Box::new(value)), range: None, additional: None }
    }
    // pub fn string_escaped(value: String, r: TextRange) -> Self {
    //     Self { kind: ASTKind::EscapedText(value), range: box_range(r) }
    // }
    pub fn integer(value: &str) -> Self {
        let n = BigInt::from_str_radix(value, 10).unwrap_or_default();
        Self { kind: ASTKind::Integer(Box::new(Integer::from(n))), range: None, additional: None }
    }
    pub fn number(value: &str) -> Self {
        let kind = match parse_number(value) {
            Some(Value::Integer(n)) => ASTKind::Integer(n),
            Some(Value::Decimal(n)) => ASTKind::Decimal(n),
            _ => ASTKind::Null,
        };
        Self { kind, range: None, additional: None }
    }
    pub fn namespace(value: Vec<AST>) -> Self {
        Self { kind: ASTKind::Namespace(value), range: None, additional: None }
    }
    pub fn list(value: Vec<AST>) -> Self {
        Self { kind: ASTKind::List(value), range: None, additional: None }
    }
    pub fn dict(pairs: Vec<AST>) -> Self {
        Self { kind: ASTKind::Dict(pairs), range: None, additional: None }
    }
    pub fn pair(lhs: AST, rhs: AST) -> Self {
        Self { kind: ASTKind::Pair(Box::new(lhs), Box::new(rhs)), range: None, additional: None }
    }
}

impl Text {
    pub fn string_escaped(value: impl Into<String>, handler: impl Into<String>, delimiter: usize) -> Self {
        let handler = handler.into();
        let handler = match handler.len() {
            0 => None,
            _ => Some(handler),
        };
        Text { handler, delimiter: TextDelimiter::Quotation(delimiter), value: value.into() }
    }
    pub fn string_literal(value: impl Into<String>, handler: impl Into<String>, delimiter: usize) -> Self {
        let handler = handler.into();
        let handler = match handler.len() {
            0 => None,
            _ => Some(handler),
        };
        Text { handler, delimiter: TextDelimiter::Apostrophe(delimiter), value: value.into() }
    }
    pub fn string_bare(value: impl Into<String>) -> Self {
        Text { handler: None, delimiter: TextDelimiter::Bare, value: value.into() }
    }
}