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
use std::{rc::Rc};
use std::{collections::VecDeque};
use fnv::{FnvBuildHasher};
use quickscope::ScopeMap;
use crate::{lang::{Sequence, Rst}, RantValue, Rant};
use crate::runtime::*;
use super::{output::OutputWriter};

type CallStackVector<I> = SmallVec<[StackFrame<I>; super::CALL_STACK_INLINE_COUNT]>;

/// Represents a call stack and its associated locals.
pub struct CallStack<I> {
  frames: CallStackVector<I>,
  locals: ScopeMap<InternalString, RantVar, FnvBuildHasher>,
}

impl<I> Default for CallStack<I> {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

impl<I> CallStack<I> {
  #[inline]
  pub(crate) fn new() -> Self {
    Self {
      frames: Default::default(),
      locals: Default::default(),
    }
  }

  /// Returns `true` if the stack is empty.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.frames.is_empty()
  }

  /// Gets the number of frames in the stack.
  #[inline]
  pub fn len(&self) -> usize {
    self.frames.len()
  }

  /// Removes the topmost frame from the stack and returns it.
  #[inline]
  pub fn pop_frame(&mut self) -> Option<StackFrame<I>> {
    if let Some(frame) = self.frames.pop() {
      self.locals.pop_layer();
      return Some(frame)
    }
    None
  }

  /// Adds a frame to the top of the stack.
  #[inline]
  pub fn push_frame(&mut self, frame: StackFrame<I>) {
    self.locals.push_layer();
    self.frames.push(frame);
  }

  /// Returns a mutable reference to the topmost frame in the stack.
  #[inline]
  pub fn top_mut(&mut self) -> Option<&mut StackFrame<I>> {
    self.frames.last_mut()
  }


  /// Returns a mutable reference to the frame `depth` frames below the top of the stack.
  #[inline]
  pub fn parent_mut(&mut self, depth: usize) -> Option<&mut StackFrame<I>> {
    self.frames.iter_mut().rev().nth(depth)
  }

  /// Returns a reference to the frame `depth` frames below the top of the stack.
  #[inline]
  pub fn parent(&self, depth: usize) -> Option<&StackFrame<I>> {
    self.frames.iter().rev().nth(depth)
  }

  /// Returna reference to the topmost frame in the stack.
  #[inline]
  pub fn top(&self) -> Option<&StackFrame<I>> {
    self.frames.last()
  }

  /// Generates a stack trace string from the current state of the stack.
  pub fn gen_stack_trace(&self) -> String {
    let mut trace = String::new();
    let mut last_frame_info: Option<(String, usize)> = None;
    for frame in self.frames.iter().rev() {
      let current_frame_string = frame.to_string();

      if let Some((last_frame_string, count)) = last_frame_info.take() {
        if current_frame_string == last_frame_string {
          last_frame_info = Some((last_frame_string, count + 1));
        } else {
          // spit out last repeated frame
          match count {
            1 => trace.push_str(&format!("-> {}\n", last_frame_string)),
            _ => trace.push_str(&format!("-> {} ({} frames)\n", last_frame_string, count)),
          }
          last_frame_info = Some((current_frame_string, 1));
        }
      } else {
        last_frame_info = Some((current_frame_string, 1));
      }
    }

    // emit bottom frame
    if let Some((last_frame_string, count)) = last_frame_info.take() {
      match count {
        1 => trace.push_str(&format!("-> {}", last_frame_string)),
        _ => trace.push_str(&format!("-> {} ({} frames)", last_frame_string, count)),
      }
    }

    trace
  }

  /// Sets a variable's value using the specified access type.
  #[inline]
  pub fn set_var_value(&mut self, context: &mut Rant, id: &str, access: AccessPathKind, val: RantValue) -> RuntimeResult<()> {
    match access {
      AccessPathKind::Local => {
        if let Some(var) = self.locals.get_mut(id) {
          if !var.write(val) {
            runtime_error!(RuntimeErrorType::InvalidAccess, "cannot reassign local constant '{}'", id);
          }
          return Ok(())
        }
      },
      AccessPathKind::Descope(n) => {
        if let Some(var) = self.locals.get_parent_mut(id, n) {
          if !var.write(val) {
            runtime_error!(RuntimeErrorType::InvalidAccess, "cannot reassign local constant '{}'", id);
          }
          return Ok(())
        }
      },
      // Skip locals completely if it's a global accessor
      AccessPathKind::ExplicitGlobal => {}
    }

    // Check globals
    if context.has_global(id) {
      if !context.set_global(id, val) {
        runtime_error!(RuntimeErrorType::InvalidAccess, "cannot reassign global constant '{}'", id);
      }
      return Ok(())
    }

    runtime_error!(RuntimeErrorType::InvalidAccess, "variable '{}' not found", id);
  }

  #[inline]
  pub fn get_var_depth(&self, context: &Rant, id: &str, access: AccessPathKind) -> RuntimeResult<usize> {
    match access {
      AccessPathKind::Local => {
        if let Some(d) = self.locals.depth_of(id) {
          return Ok(d)
        }
      },
      AccessPathKind::Descope(n) => {
        if let Some((_, d)) = self.locals.get_parent_depth(id, n) {
          return Ok(d)
        }
      },
      // Skip locals completely if it's a global accessor
      AccessPathKind::ExplicitGlobal => {}
    }

    // Check globals
    if context.has_global(id) {
      return Ok(self.locals.depth() - 1)
    }

    runtime_error!(RuntimeErrorType::InvalidAccess, "variable '{}' not found", id);
  }

  /// Gets a variable's value using the specified access type.
  #[inline]
  pub fn get_var_value(&self, context: &Rant, id: &str, access: AccessPathKind, prefer_function: bool) -> RuntimeResult<RantValue> {

    macro_rules! percolating_func_lookup {
      ($value_iter:expr) => {
        if let Some(mut vars) = $value_iter {
          if let Some(mut var) = vars.next() {
            // If the topmost value isn't callable, check the whole pile and then globals for something that is
            if !var.value_ref().is_callable() {
              if let Some(func_var) = vars
              .find(|v| v.value_ref().is_callable())
              .or_else(|| context.get_global_var(id).filter(|v| v.value_ref().is_callable())) 
              {
                var = func_var;
              }
            }
            return Ok(var.value_cloned())
          }
        }
      }
    }

    match access {
      AccessPathKind::Local => {
        // If the caller requested a function, perform function percolation
        if prefer_function {
          percolating_func_lookup!(self.locals.get_all(id));
        } else if let Some(var) = self.locals.get(id) {
          return Ok(var.value_cloned())
        }
      },
      AccessPathKind::Descope(n) => {
        if prefer_function {
          percolating_func_lookup!(self.locals.get_parents(id, n));
        } else if let Some(var) = self.locals.get_parent(id, n) {
          return Ok(var.value_cloned())
        }
      },
      AccessPathKind::ExplicitGlobal => {},
    }    

    // Check globals
    if let Some(val) = context.get_global(id) {
      return Ok(val)
    }

    Err(RuntimeError {
      error_type: RuntimeErrorType::InvalidAccess,
      description: Some(format!("{} '{}' not found", if prefer_function { "function" } else { "variable" }, id)),
      stack_trace: None,
    })
  }

  /// Gets a mutable reference to a variable.
  pub fn get_var_mut<'a>(&'a mut self, context: &'a mut Rant, id: &str, access: AccessPathKind) -> RuntimeResult<&'a mut RantVar> {
    match access {
      AccessPathKind::Local => {
        if let Some(var) = self.locals.get_mut(id) {
          return Ok(var)
        }
      },
      AccessPathKind::Descope(n) => {
        if let Some(var) = self.locals.get_parent_mut(id, n) {
          return Ok(var)
        }
      },
      AccessPathKind::ExplicitGlobal => {},
    }    

    // Check globals
    if let Some(var) = context.get_global_var_mut(id) {
      return Ok(var)
    }

    Err(RuntimeError {
      error_type: RuntimeErrorType::InvalidAccess,
      description: Some(format!("variable '{}' not found", id)),
      stack_trace: None,
    })
  }

  /// Defines a local variable of the specified name.
  ///
  /// ## Notes
  ///
  /// This function does not perform any identifier validation.
  pub fn def_local_var(&mut self, id: &str, var: RantVar) -> RuntimeResult<()> {
    self.locals.define(InternalString::from(id), var);
    Ok(())
  }

  /// Defines a variable of the specified name by-value.
  ///
  /// ## Notes
  ///
  /// This function does not perform any identifier validation.
  #[inline]
  pub fn def_var_value(&mut self, context: &mut Rant, id: &str, access: AccessPathKind, val: RantValue, is_const: bool) -> RuntimeResult<()> {
    match access {
      AccessPathKind::Local => {
        // Don't allow redefs of local constants
        if let Some(v) = self.locals.get(id) {
          if v.is_const() && self.locals.depth_of(id) == Some(0) {
            runtime_error!(RuntimeErrorType::InvalidAccess, "attempted to redefine local constant '{}'", id);
          }
        }

        let variable = if is_const { RantVar::ByValConst(val) } else { RantVar::ByVal(val) };
        self.locals.define(InternalString::from(id), variable);
        return Ok(())
      },
      AccessPathKind::Descope(descope_count) => {
        // Don't allow redefs of parent constants
        if let Some((v, vd)) = self.locals.get_parent_depth(id, descope_count) {
          if v.is_const() && vd == descope_count {
            runtime_error!(RuntimeErrorType::InvalidAccess, "attempted to redefine parent constant '{}'", id);
          }
        }

        let variable = if is_const { RantVar::ByValConst(val) } else { RantVar::ByVal(val) };
        self.locals.define_parent(InternalString::from(id), variable, descope_count);
        return Ok(())
      },
      AccessPathKind::ExplicitGlobal => {}
    }
    
    // Don't allow redefs of global constants
    if !(if is_const { context.set_global_const(id, val) } else { context.set_global(id, val) }) {
      runtime_error!(RuntimeErrorType::InvalidAccess, "attempted to redefine global constant '{}'", id);
    }

    Ok(())
  }

  /// Scans ("tastes") the stack from the top looking for the first occurrence of the specified frame flavor.
  /// Returns the top-relative index of the first occurrence, or `None` if no match was found or a stronger flavor was found first.
  #[inline]
  pub fn taste_for_first(&self, target_flavor: StackFrameFlavor) -> Option<usize> {
    for (frame_index, frame) in self.frames.iter().rev().enumerate() {
      if frame.flavor > target_flavor {
        return None
      } else if frame.flavor == target_flavor {
        return Some(frame_index)
      }
    }
    None
  }

  /// Scans ("tastes") the stack from the top looking for the first occurrence of the specified frame flavor.
  /// Returns the top-relative index of the first occurrence, or `None` if no match was found or another flavor was found first.
  #[inline]
  pub fn taste_for(&self, target_flavor: StackFrameFlavor) -> Option<usize> {
    for (frame_index, frame) in self.frames.iter().rev().enumerate() {
      if frame.flavor == target_flavor {
        return Some(frame_index)
      }
    }
    None
  }
}

/// Represents a call stack frame.
pub struct StackFrame<I> {
  /// Node sequence being executed by the frame
  sequence: Option<Rc<Sequence>>,
  /// Program Counter (as index in sequence) for the current frame
  pc: usize,
  /// Has frame sequence started running?
  started: bool,
  /// Output for the frame
  output: Option<OutputWriter>,
  /// Intent queue for the frame
  intents: VecDeque<I>,
  /// Line/col for debug info
  debug_pos: (usize, usize),
  /// Origin of sequence
  origin: Rc<RantProgramInfo>,
  /// A usage hint provided by the program element that created the frame.
  flavor: StackFrameFlavor,
}

impl<I> StackFrame<I> {
  #[inline]
  pub(crate) fn new(sequence: Rc<Sequence>, has_output: bool, prev_output: Option<&OutputWriter>) -> Self {
    Self {
      origin: Rc::clone(&sequence.origin),
      sequence: Some(sequence),
      output: if has_output { Some(OutputWriter::new(prev_output)) } else { None },
      started: false,
      pc: 0,
      intents: Default::default(),
      debug_pos: (0, 0),
      flavor: Default::default(),
    }
  }

  #[inline]
  pub(crate) fn with_extended_config(
    sequence: Option<Rc<Sequence>>,
    has_output: bool, 
    prev_output: Option<&OutputWriter>, 
    origin: Rc<RantProgramInfo>, 
    debug_pos: (usize, usize),
    flavor: StackFrameFlavor
  ) -> Self 
  {
    Self {
      origin,
      sequence,
      output: if has_output { Some(OutputWriter::new(prev_output)) } else { None },
      started: false,
      pc: 0,
      intents: Default::default(),
      debug_pos,
      flavor,
    }
  }

  #[inline(always)]
  pub(crate) fn with_flavor(self, flavor: StackFrameFlavor) -> Self {
    let mut frame = self;
    frame.flavor = flavor;
    frame
  }
}

impl<I> StackFrame<I> {
  #[inline]
  pub(crate) fn seq_next(&mut self) -> Option<Rc<Rst>> {
    if self.is_done() {
      return None
    }
    
    // Increment PC
    if self.started {
      self.pc += 1;
    } else {
      self.started = true;
    }
    
    self.sequence.as_ref().and_then(|seq| seq.get(self.pc).map(Rc::clone))
  }
  
  /// Gets the Program Counter (PC) for the frame.
  #[inline(always)]
  pub fn pc(&self) -> usize {
    self.pc
  }

  /// Gets the flavor of the frame.
  #[inline(always)]
  pub fn flavor(&self) -> StackFrameFlavor {
    self.flavor
  }

  #[inline(always)]
  pub fn output(&self) -> Option<&OutputWriter> {
    self.output.as_ref()
  }

  #[inline(always)]
  pub fn origin(&self) -> &Rc<RantProgramInfo> {
    &self.origin
  }

  #[inline(always)]
  pub fn debug_pos(&self) -> (usize, usize) {
    self.debug_pos
  }

  #[inline]
  pub fn origin_name(&self) -> &str {
    self.origin.path
      .as_deref()
      .unwrap_or_else(|| 
        self.origin.name
          .as_deref()
          .unwrap_or(DEFAULT_PROGRAM_NAME)
      )
  }

  /// Takes the next intent to be handled.
  #[inline(always)]
  pub(crate) fn take_intent(&mut self) -> Option<I> {
    self.intents.pop_front()
  }

  /// Pushes an intent to the front of the queue so that it is handled next.
  #[inline(always)]
  pub fn push_intent_front(&mut self, intent: I) {
    self.intents.push_front(intent);
  }

  /// Pushes an intent to the back of the queue so that it is handled last.
  #[inline(always)]
  pub fn push_intent_back(&mut self, intent: I) {
    self.intents.push_back(intent);
  }

  /// If the frame has output, runs `func` on a mutable reference to the output; otherwise, does nothing.
  #[inline]
  pub fn use_output_mut<F: FnOnce(&mut OutputWriter)>(&mut self, func: F) {
    if let Some(output) = self.output.as_mut() {
      func(output);
    }
  }

  /// If the frame has output, runs `func` on a reference to the output; otherwise, does nothing.
  #[inline]
  pub fn use_output<'a, F: FnOnce(&'a OutputWriter) -> R, R>(&'a self, func: F) -> Option<R> {
    self.output.as_ref().map(|output| func(output))
  }

  /// Writes debug information to the current frame to be used in stack trace generation.
  #[inline]
  pub fn set_debug_info(&mut self, info: &DebugInfo) {
    match info {
      DebugInfo::Location { line, col } => self.debug_pos = (*line, *col),
    }
  }
}

impl<I> StackFrame<I> {
  #[inline(always)]
  fn is_done(&self) -> bool {
    self.sequence.is_none() || self.pc >= self.sequence.as_ref().unwrap().len()
  }
  
  /// Writes a fragment to the frame's output.
  #[inline]
  pub fn write_frag(&mut self, frag: &str) {
    if let Some(output) = self.output.as_mut() {
      output.write_frag(frag);
    }
  }
  
  /// Writes a whitespace string to the frame's output.
  #[inline]
  pub fn write_ws(&mut self, ws: &str) {
    if let Some(output) = self.output.as_mut() {
      output.write_ws(ws);
    }
  }

  /// Writes a value to the frame's output.
  #[inline]
  pub fn write_value(&mut self, val: RantValue) {
    if let Some(output) = self.output.as_mut() {
      output.write_value(val);
    }
  }

  /// Consumes the frame's output and returns the final value generated by it.
  #[inline]
  pub fn into_output(mut self) -> Option<RantValue> {
    self.output.take().map(|o| o.render_value())
  }
}

impl<I> Display for StackFrame<I> {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "[{}:{}:{}] in {}", 
      self.origin_name(), 
      self.debug_pos.0, 
      self.debug_pos.1,
      self.sequence.as_ref()
        .and_then(|seq| seq.name().map(|name| name.as_str()))
        .unwrap_or_else(|| self.flavor.name()), 
    )
  }
}

/// Hints at what kind of program element a specific stack frame represents.
///
/// The runtime can use this information to find where to unwind the call stack to on specific operations like breaking, returning, etc.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
pub enum StackFrameFlavor {
  /// Nothing special.
  Original,
  /// Native function call.
  NativeCall,
  /// Frame is used for a block element.
  BlockElement,
  /// Frame is used for a repeater element.
  RepeaterElement,
  /// Frame is used for the body of a function.
  FunctionBody,
  /// Frame is used to evaluate a dynamic key.
  DynamicKeyExpression,
  /// Frame is used to evaluate a function argument.
  ArgumentExpression,
}

impl Default for StackFrameFlavor {
  fn default() -> Self {
    Self::Original
  }
}

impl StackFrameFlavor {
  fn name(&self) -> &'static str {
    match self {
      Self::Original => "sequence",
      Self::NativeCall => "native call",
      Self::BlockElement => "block element",
      Self::RepeaterElement => "repeater element",
      Self::FunctionBody => "function body",
      Self::DynamicKeyExpression => "dynamic key",
      Self::ArgumentExpression => "argument",
    }
  }
}