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
//! 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 an accessor path.

#[derive(Debug)]
pub enum AccessPathComponent {
  /// Name of variable or map item

  Name(Identifier),
  /// List index

  Index(i64),
  /// Dynamic key

  Expression(Rc<Sequence>),
}

impl Display for AccessPathComponent {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    match self {
      AccessPathComponent::Name(name) => write!(f, "{}", name),
      AccessPathComponent::Index(i) => write!(f, "{}", i),
      AccessPathComponent::Expression(expr) => write!(f, "{{{}...}}", expr.name().map(|name| name.as_str()).unwrap_or("")),
    }
  }
}

/// Types of access paths.

#[derive(Debug, Copy, Clone)]
pub enum AccessPathKind {
  /// Path points to a variable in the current scope.

  Local,
  /// Path points explicitly to a global variable.

  ExplicitGlobal,
  /// Path points explicitly to a variable that is at most _n_ scopes above the current scope.

  Descope(usize),
}

impl AccessPathKind {
  /// Gets the number of explicit descopes required by this path. If the path is explicitly global, returns 0.

  pub fn descope_count(&self) -> usize {
    match self {
      AccessPathKind::Local | AccessPathKind::ExplicitGlobal => 0,
      AccessPathKind::Descope(n) => *n
    }
  }
}

/// Describes the location of a value.

#[derive(Debug)]
pub struct AccessPath {
  path: Vec<AccessPathComponent>,
  kind: AccessPathKind,
}

impl AccessPath {
  #[inline]
  pub fn new(path: Vec<AccessPathComponent>, kind: AccessPathKind) -> Self {
    Self {
      path,
      kind
    }
  }

  #[inline]
  pub fn is_explicit_global(&self) -> bool {
    matches!(self.kind, AccessPathKind::ExplicitGlobal)
  }

  #[inline]
  pub fn kind(&self) -> AccessPathKind {
    self.kind
  }

  /// Returns a list of dynamic keys used by the path in order.

  #[inline]
  pub fn dynamic_keys(&self) -> Vec<Rc<Sequence>> {
    self.iter().filter_map(|c| {
      match c {
        AccessPathComponent::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`.

  #[inline]
  pub fn capture_var_name(&self) -> Option<Identifier> {
    if let Some(AccessPathComponent::Name(id)) = self.first() {
      Some(id.clone())
    } else {
      None
    }
  }
}

impl Deref for AccessPath {
  type Target = Vec<AccessPathComponent>;
  fn deref(&self) -> &Self::Target {
    &self.path
  }
}

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

impl Display for AccessPath {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "{}", self.iter().map(|part| part.to_string()).collect::<Vec<String>>().join("/"))
  }
}

/// A series of Rant program elements.

#[derive(Debug)]
pub struct Sequence {
  elements: Vec<Rc<RST>>,
  name: Option<RantString>,
}

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

  #[inline(always)]
  pub fn with_name(mut self, name: RantString) -> Self {
    self.name = Some(name);
    self
  }

  #[inline(always)]
  pub fn with_name_str(mut self, name: &str) -> Self {
    self.name = Some(RantString::from(name));
    self
  }

  pub fn name(&self) -> Option<&RantString> {
    self.name.as_ref()
  }
}

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

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

/// A block is a set of zero or more distinct Rant code snippets.

#[derive(Debug)]
pub struct Block {
  pub flag: PrintFlag,
  pub elements: Rc<Vec<Rc<Sequence>>>
}

impl Block {
  pub fn new(flag: PrintFlag, elements: Vec<Rc<Sequence>>) -> Self {
    Block {
      flag,
      elements: Rc::new(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<AccessPath>,
  pub arguments: Rc<Vec<Rc<Sequence>>>,
}

/// Describes a function definition.

#[derive(Debug)]
pub struct FunctionDef {
  pub id: Rc<AccessPath>,
  pub params: Rc<Vec<Parameter>>,
  pub capture_vars: Rc<Vec<Identifier>>,
  pub body: Rc<Sequence>,
}

/// Describes a boxing (closure) operation to turn a block into a function.

#[derive(Debug)]
pub struct ClosureExpr {
  pub expr: Rc<Sequence>,
  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(Rc<Sequence>),
  /// 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),
  /// Block as value

  BlockValue(Rc<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, AccessPathKind, Option<Rc<Sequence>>),
  /// Value getter

  VarGet(Rc<AccessPath>),
  /// Value setter

  VarSet(Rc<AccessPath>, 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),
}