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
#![deny(unused_must_use)]
#![allow(dead_code, clippy::needless_update)]

use beef::lean::Cow;
use span::{Span, Spanned};

use self::indent::IndentStack;
use crate::lexer::TokenKind::*;
use crate::lexer::{Lexer, Token, TokenKind};
use crate::{ast, Error, ErrorContext, Result};

// TODO: `is` and `in`
// TODO: `async`/`await` - maybe post-MVP

pub fn parse(src: &str) -> Result<ast::Module, Vec<Error>> {
  let lexer = Lexer::new(src);
  let parser = Parser::new(lexer);
  parser.module()
}

#[derive(Clone)]
struct Context {
  ignore_indent: bool,
  current_loop: Option<()>,
  current_func: Option<Func>,
  current_class: Option<Class>,
}

impl Context {
  pub fn with_ignore_indent(&self) -> Self {
    Self {
      ignore_indent: true,
      current_loop: self.current_loop,
      current_func: self.current_func,
      current_class: self.current_class,
    }
  }

  pub fn with_class(has_super: bool) -> Self {
    Self {
      ignore_indent: false,
      current_loop: None,
      current_func: None,
      current_class: Some(Class { has_super }),
    }
  }

  pub fn with_func(&self, has_self: bool) -> Self {
    Self {
      ignore_indent: false,
      current_loop: None,
      current_func: Some(Func {
        has_yield: false,
        has_self,
      }),
      current_class: self.current_class,
    }
  }

  pub fn with_loop(&self) -> Self {
    Self {
      ignore_indent: false,
      current_loop: Some(()),
      current_func: self.current_func,
      current_class: self.current_class,
    }
  }
}

#[derive(Clone, Copy)]
struct Class {
  has_super: bool,
}

#[derive(Clone, Copy)]
struct Func {
  has_yield: bool,
  has_self: bool,
}

#[allow(clippy::derivable_impls)]
impl Default for Context {
  fn default() -> Self {
    Self {
      ignore_indent: false,
      current_loop: None,
      current_func: None,
      current_class: None,
    }
  }
}

#[allow(clippy::derivable_impls)]
impl Default for Func {
  fn default() -> Self {
    Self {
      has_yield: false,
      has_self: false,
    }
  }
}

struct Parser<'src> {
  module: ast::Module<'src>,
  lex: Lexer<'src>,
  errors: Vec<Error>,
  indent: IndentStack,
  ctx: Context,
}

impl<'src> Parser<'src> {
  fn new(lex: Lexer<'src>) -> Self {
    Self {
      module: ast::Module::new(),
      lex,
      errors: Vec::new(),
      indent: IndentStack::new(),
      ctx: Context::default(),
    }
  }

  fn no_indent(&self) -> Result<()> {
    let token = self.current();
    if self.ctx.ignore_indent || token.is(Tok_Eof) || token.ws.is_none() {
      Ok(())
    } else {
      Err(Error::new("invalid indentation", token.span))
    }
  }

  fn indent_eq(&self) -> Result<()> {
    let token = self.current();
    if self.ctx.ignore_indent
      || token.is(Tok_Eof)
      || matches!(token.ws, Some(n) if self.indent.is_eq(n))
    {
      Ok(())
    } else {
      Err(Error::new("invalid indentation", token.span))
    }
  }

  fn indent_gt(&mut self) -> Result<()> {
    let token = self.current();
    if self.ctx.ignore_indent
      || token.is(Tok_Eof)
      || matches!(token.ws, Some(n) if self.indent.is_gt(n))
    {
      self.indent.push(token.ws.unwrap());
      Ok(())
    } else {
      Err(Error::new("invalid indentation", token.span))
    }
  }

  fn dedent(&mut self) -> Result<()> {
    let token = self.current();
    if self.ctx.ignore_indent
      || token.is(Tok_Eof)
      || matches!(token.ws, Some(n) if self.indent.is_lt(n))
    {
      self.indent.pop();
      Ok(())
    } else {
      Err(Error::new("invalid indentation", token.span))
    }
  }

  #[inline]
  fn previous(&self) -> &Token {
    self.lex.previous()
  }

  #[inline]
  fn current(&self) -> &Token {
    self.lex.current()
  }

  #[inline]
  fn expect(&mut self, kind: TokenKind) -> Result<()> {
    if self.bump_if(kind) {
      Ok(())
    } else {
      Err(Error::new(
        format!("expected `{}`", kind.name()),
        self.current().span,
      ))
    }
  }

  #[inline]
  fn bump_if(&mut self, kind: TokenKind) -> bool {
    if self.current().is(kind) {
      self.bump();
      true
    } else {
      false
    }
  }

  /// Move forward by one token, returning the previous one.
  #[inline]
  fn bump(&mut self) -> &Token {
    self.lex.bump();
    while self.current().is(Tok_Error) {
      self.errors.push(Error::new(
        format!("invalid token `{}`", self.lex.lexeme(self.current())),
        self.current().span,
      ));
      self.lex.bump();
    }
    self.previous()
  }

  /// Calls `f` in the context `ctx`.
  /// `ctx` is used only for the duration of the call to `f`.
  #[inline]
  fn with_ctx<T>(&mut self, mut ctx: Context, f: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
    std::mem::swap(&mut self.ctx, &mut ctx);
    let res = f(self);
    std::mem::swap(&mut self.ctx, &mut ctx);
    res
  }

  #[inline]
  fn with_ctx2<T>(
    &mut self,
    mut ctx: Context,
    f: impl FnOnce(&mut Self) -> Result<T>,
  ) -> Result<(Context, T)> {
    std::mem::swap(&mut self.ctx, &mut ctx);
    let res = f(self);
    std::mem::swap(&mut self.ctx, &mut ctx);
    Ok((ctx, res?))
  }

  /// Calls `f` and wraps the returned value in a span that encompasses the
  /// entire sequence of tokens parsed within `f`.
  #[inline]
  fn span<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T>) -> Result<Spanned<T>> {
    let start = self.current().span;
    f(self).map(|value| {
      let end = self.previous().span;
      Spanned::new(start.join(end), value)
    })
  }

  fn sync(&mut self) {
    self.bump();
    while !self.current().is(Tok_Eof) {
      // break when exiting a block (dedent)
      // but not in an if statement, because it is composed of multiple blocks
      if self.dedent().is_ok() && ![Kw_Else, Kw_Elif].contains(&self.current().kind) {
        break;
      }

      match self.current().kind {
        // break on keywords that begin statements
        Kw_Import | Kw_From | Kw_Fn | Kw_Class | Kw_For | Kw_While | Kw_Loop | Kw_If => break,
        // handle any errors
        Tok_Error => self.errors.push(Error::new(
          format!("invalid token `{}`", self.lex.lexeme(self.current())),
          self.current().span,
        )),
        _ => {}
      }

      self.bump();
    }
  }
}

mod common;
mod expr;
mod indent;
mod module;
mod stmt;

// On average, a single parse_XXX() method consumes between 10 and 700 bytes of
// stack space. Assuming ~50 recursive calls per dive and 700 bytes of stack
// space per call, we'll require 50 * 700 = 35k bytes of stack space in order
// to dive. For future proofing, we round this value up to 64k bytes.
const MINIMUM_STACK_REQUIRED: usize = 64_000;

// On WASM, remaining_stack() will always return None. Stack overflow panics
// are converted to exceptions and handled by the host, which means a
// `try { ... } catch { ... }` around a call to one of the Hebi compiler
// functions would be enough to properly handle this case.
#[cfg(any(target_family = "wasm", not(feature = "check_recursion_limit")))]
fn check_recursion_limit(_span: Span) -> Result<(), Error> {
  Ok(())
}

#[cfg(all(not(target_family = "wasm"), feature = "check_recursion_limit"))]
fn check_recursion_limit(span: Span) -> Result<()> {
  if stacker::remaining_stack()
    .map(|available| available > MINIMUM_STACK_REQUIRED)
    .unwrap_or(true)
  {
    Ok(())
  } else {
    Err(Error::new("nesting limit reached", span))
  }
}

#[cfg(test)]
mod tests;