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
//! Contains Rant's syntax tree implementation and supporting data structures.

use std::{ops::{DerefMut, Deref}, fmt::Display, rc::Rc};
use crate::RantString;

/// Printflags indicate to the compiler whether a given program element is likely to print something or not.
#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum PrintFlag {
  /// Use default printing behavior.
  None,
  /// Treat the marked element as printing.
  Hint,
  /// Treat the marked element as non-printing.
  Sink
}

impl PrintFlag {
  #[inline]
  pub fn prioritize(prev: PrintFlag, next: PrintFlag) -> PrintFlag {
    match next {
      PrintFlag::None => prev,
      _ => next,
    }
  }

  #[inline]
  pub fn is_sink(&self) -> bool {
    matches!(self, PrintFlag::Sink)
  }
}

/// Identifiers are special strings used to name variables and static (non-procedural) map keys.
/// This is just a wrapper around a SmartString that enforces identifier formatting requirements.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Identifier(RantString);

impl Identifier {
  pub fn new(idstr: RantString) -> Self {
    Self(idstr)
  }
}

impl Deref for Identifier {
  type Target = RantString;
  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

impl Display for Identifier {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "{}", self.0)
  }
}

/// Component in a variable accessor chain
#[derive(Debug)]
pub enum VarAccessComponent {
  /// Name of variable or map item
  Name(Identifier),
  /// List index
  Index(i64),
  /// Dynamic key
  Expression(Rc<Block>),
}

/// An accessor consisting of a chain of variable names and indices
#[derive(Debug)]
pub struct VarAccessPath(Vec<VarAccessComponent>);

impl VarAccessPath {
  pub fn new(parts: Vec<VarAccessComponent>) -> Self {
    Self(parts)
  }

  /// Returns a list of dynamic keys used by the path in order.
  pub fn dynamic_keys(&self) -> Vec<Rc<Block>> {
    self.iter().filter_map(|c| {
      match c {
        VarAccessComponent::Expression(expr) => Some(Rc::clone(expr)),
        _ => None
      }
    }).collect()
  }

  /// If the path statically accesses a variable, returns the name of the variable accessed; otherwise, returns `None`.
  pub fn capture_var_name(&self) -> Option<Identifier> {
    if self.len() > 0 {
      match &self[0] {
        VarAccessComponent::Name(id) => Some(id.clone()),
        _ => None,
      }
    } else {
      None
    }
  }
}

impl Deref for VarAccessPath {
  type Target = Vec<VarAccessComponent>;
  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

impl DerefMut for VarAccessPath {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.0   
  }
}

/// A series of Rant program elements.
#[derive(Debug)]
pub struct Sequence(Vec<Rc<RST>>);

impl Sequence {
  pub fn new(seq: Vec<Rc<RST>>) -> Self {
    Self(seq)
  }
  
  pub fn one(rst: RST) -> Self {
    Self(vec![Rc::new(rst)])
  }
  
  pub fn empty() -> Self {
    Self::new(vec![])
  }
}

impl Deref for Sequence {
  type Target = Vec<Rc<RST>>;
  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

impl DerefMut for Sequence {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.0
  }
}

/// A block is a set of zero or more distinct Rant code snippets.
#[derive(Debug)]
pub struct Block {
  pub flag: PrintFlag,
  pub elements: Vec<Rc<Sequence>>
}

impl Block {
  pub fn new(flag: PrintFlag, elements: Vec<Rc<Sequence>>) -> Self {
    Block {
      flag,
      elements
    }
  }
  
  #[inline]
  pub fn len(&self) -> usize {
    self.elements.len()
  }
}

/// Describes the arity requirements of a function parameter.
#[derive(Debug, Copy, Clone)]
pub enum Varity {
  /// Single-value, always required
  Required,
  /// Single-value, may be omitted in favor of a default value
  Optional,
  /// Optional series of zero or more values; defaults to empty list
  VariadicStar,
  /// Required series of one or more values
  VariadicPlus,
}

impl Varity {
  /// Returns true if the supplied varity pair is in a valid order.
  pub fn is_valid_order(first: Varity, second: Varity) -> bool {
    use Varity::*;
    matches!((first, second), 
      (Required, Required) |
      (Required, Optional) |
      (Required, VariadicStar) |
      (Required, VariadicPlus) |
      (Optional, Optional) |
      (Optional, VariadicStar)
    )
  }

  /// Returns true if the varity is variadic.
  pub fn is_variadic(&self) -> bool {
    use Varity::*;
    matches!(self, VariadicStar | VariadicPlus)
  }
}

impl Display for Varity {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    use Varity::*;
    match self {
      Required => write!(f, "required parameter"),
      Optional => write!(f, "optional parameter"),
      VariadicStar => write!(f, "optional variadic parameter"),
      VariadicPlus => write!(f, "required variadic parameter"),
    }
  }
}

/// Describes a function parameter.
#[derive(Debug)]
pub struct Parameter {
  /// The name of the parameter
  pub name: Identifier,
  /// The varity of the parameter
  pub varity: Varity,
}

impl Parameter {
  /// Returns true if the parameter is required.
  #[inline]
  pub fn is_required(&self) -> bool {
    use Varity::*;
    matches!(self.varity, Required | VariadicPlus)
  }
}

/// Describes a function call.
#[derive(Debug)]
pub struct FunctionCall {
  pub flag: PrintFlag,
  pub id: Rc<VarAccessPath>,
  pub arguments: Rc<Vec<Rc<Sequence>>>,
}

/// Describes a function definition.
#[derive(Debug)]
pub struct FunctionDef {
  pub id: Rc<VarAccessPath>,
  pub params: Rc<Vec<Parameter>>,
  pub capture_vars: Rc<Vec<Identifier>>,
  pub body: Rc<Block>,
}

/// Describes a boxing (closure) operation to turn a block into a function.
#[derive(Debug)]
pub struct ClosureExpr {
  pub expr: Rc<Block>,
  pub params: Rc<Vec<Parameter>>,
  pub capture_vars: Rc<Vec<Identifier>>,
}

/// Describes an anonymous (nameless) function call.
#[derive(Debug)]
pub struct AnonFunctionCall {
  pub flag: PrintFlag,
  pub expr: Rc<Sequence>,
  pub args: Rc<Vec<Rc<Sequence>>>,
}

/// Key creation methods for map initializer entries.
#[derive(Debug)]
pub enum MapKeyExpr {
  /// Map key is evaluated from an expression at runtime.
  Dynamic(Block),
  /// Map key is evaluated at compile time from an identifier.
  Static(RantString),
}

/// Rant Syntax Tree
#[derive(Debug)]
pub enum RST {
  /// No Operation
  Nop,
  /// Program sequence
  Sequence(Rc<Sequence>),
  /// Rant block containing zero or more sequences
  Block(Block),
  /// List initializer
  ListInit(Rc<Vec<Rc<Sequence>>>),
  /// Map initializer
  MapInit(Rc<Vec<(MapKeyExpr, Rc<Sequence>)>>),
  /// Closure expression
  Closure(ClosureExpr),
  /// Anonymous function call
  AnonFuncCall(AnonFunctionCall),
  /// Named function call
  FuncCall(FunctionCall),
  /// Function definition
  FuncDef(FunctionDef),
  /// Variable definition
  VarDef(Identifier, Option<Rc<Sequence>>),
  /// Value getter
  VarGet(Rc<VarAccessPath>),
  /// Value setter
  VarSet(Rc<VarAccessPath>, Rc<Sequence>),
  /// Fragment
  Fragment(RantString),
  /// Whitespace
  Whitespace(RantString),
  /// Integer value
  Integer(i64),
  /// Floating-point value
  Float(f64),
  /// Boolean value
  Boolean(bool),
  /// Empty value
  EmptyVal,
  /// Provides debug information about the next sequence element
  DebugInfoUpdateOuter(DebugInfo),
  /// Provides debug information about the containing element
  DebugInfoUpdateInner(DebugInfo),
}

impl RST {
  pub fn display_name(&self) -> &'static str {
    match self {
      RST::Sequence(_) =>                     "sequence",
      RST::Block(..) =>                       "block",
      RST::ListInit(_) =>                     "list",
      RST::MapInit(_) =>                      "map",
      RST::Closure(_) =>                      "closure",
      RST::AnonFuncCall(_) =>                 "anonymous function call",
      RST::FuncCall(_) =>                     "function call",
      RST::FuncDef(_) =>                      "function definition",
      RST::Fragment(_) =>                     "fragment",
      RST::Whitespace(_) =>                   "whitespace",
      RST::Integer(_) =>                      "integer",
      RST::Float(_) =>                        "float",
      RST::Boolean(_) =>                      "boolean",
      RST::EmptyVal =>                        "empty",
      RST::Nop =>                             "nothing",
      RST::VarDef(..) =>                      "variable definition",
      RST::VarGet(_) =>                       "variable",
      RST::VarSet(..) =>                      "variable assignment",
      _ =>                                    "???"
    }
  }
  
  pub fn is_printing(&self) -> bool {
    matches!(self, 
      RST::Block(Block { flag: PrintFlag::Hint, .. }) |
      RST::AnonFuncCall(AnonFunctionCall { flag: PrintFlag::Hint, .. }) |
      RST::FuncCall(FunctionCall { flag: PrintFlag::Hint, .. }) |
      RST::Integer(_) |
      RST::Float(_) |
      RST::Boolean(_) |
      RST::Fragment(_) |
      RST::Whitespace(_) |
      RST::VarGet(_)
    )
  }
}

impl Display for RST {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "{}", self.display_name())
  }
}

/// Provides debug information about a program element.
#[derive(Debug)]
pub enum DebugInfo {
  Location { line: usize, col: usize },
  SourceName(RantString),
  ScopeName(RantString),
}