mod expr;
mod function;
mod module;
mod pattern;
mod stmt;
use std::borrow::Cow;
use std::cell::Cell;
use std::collections::HashMap;
use parsec_base::{Budget, Diagnostic, Limits, Severity, Span};
use crate::ast::{Ast, Comment, CommentKind, List, Node, NodeId};
use crate::lexer::{Goal, Lexer, SourceType};
use crate::text;
use crate::token::{Flags, Keyword, Kind, Punct, Token};
pub const DEFAULT_MAX_DEPTH: u32 = 256;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Options {
pub source_type: SourceType,
pub limits: Limits,
}
pub fn parse(src: &str, options: &Options) -> Result<Ast, Diagnostic> {
Parser::new(src, options).parse()
}
pub fn parse_script(src: &str) -> Result<Ast, Diagnostic> {
parse(src, &Options::default())
}
pub fn parse_recovering(src: &str, options: &Options) -> Result<Ast, Vec<Diagnostic>> {
let mut p = Parser::new(src, options);
p.recover = true;
p.parse_all()
}
pub(crate) struct Resume {
pub start: u32,
pub body: bool,
pub ctx: Ctx,
pub labels: Vec<(String, Span, bool)>,
pub classes: usize,
pub depth: u32,
pub max_depth: u32,
}
pub(crate) struct Piece {
pub ast: Ast,
pub end: u32,
pub private_names: Vec<String>,
}
pub(crate) fn parse_piece(src: &str, options: &Options, r: Resume) -> Option<Piece> {
let mut p = Parser::with_room(src, options, 64);
p.ast.lists.push(NodeId::new(1));
p.lexer = p.lexer.starting_at(r.start, false);
p.ctx = r.ctx;
p.labels = r
.labels
.into_iter()
.map(|(name, span, is_loop)| Label {
name,
span,
is_loop,
})
.collect();
p.classes = (0..r.classes).map(|_| ClassScope::default()).collect();
p.depth = r.depth;
p.max_depth = r.max_depth;
let root = p.piece(r.body).ok()?;
if root.index() + 1 != p.ast.nodes.len() {
return None;
}
let end = p.prev_end;
let mut private_names = Vec::new();
for scope in p.classes.drain(..) {
private_names.extend(scope.used.into_iter().map(|(name, _)| name));
}
let mut ast = p.ast;
ast.comments.retain(|c| c.span.start < end);
ast.warnings = p
.lexer
.take_diagnostics()
.into_iter()
.filter(|d| d.severity == Severity::Warning && d.span.start < end)
.collect();
ast.root = Some(root);
Some(Piece {
ast,
end,
private_names,
})
}
#[derive(Debug)]
pub(crate) struct Stop;
pub(crate) type R<T> = Result<T, Stop>;
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Ctx {
pub strict: bool,
pub yield_: bool,
pub await_: bool,
pub ret: bool,
pub new_target: bool,
pub super_prop: bool,
pub super_call: bool,
pub no_arguments: bool,
pub static_block: bool,
pub loops: u32,
pub breakable: u32,
pub labels: usize,
}
struct Label {
name: String,
span: Span,
is_loop: bool,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Private {
Field,
Method,
Get,
Set,
GetSet,
}
#[derive(Default)]
struct ClassScope {
declared: HashMap<String, (Private, bool, Span)>,
used: Vec<(String, Span)>,
}
thread_local! {
static SPARE_SCRATCH: Cell<Vec<NodeId>> = const { Cell::new(Vec::new()) };
}
struct Scratch(Vec<NodeId>);
impl Scratch {
fn take() -> Scratch {
let mut v = SPARE_SCRATCH.try_with(Cell::take).unwrap_or_default();
if v.capacity() == 0 {
v.reserve(64);
}
Scratch(v)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let mut v = std::mem::take(&mut self.0);
if v.capacity() <= 4096 {
v.clear();
let _ = SPARE_SCRATCH.try_with(|spare| spare.set(v));
}
}
}
impl std::ops::Deref for Scratch {
type Target = Vec<NodeId>;
fn deref(&self) -> &Vec<NodeId> {
&self.0
}
}
impl std::ops::DerefMut for Scratch {
fn deref_mut(&mut self) -> &mut Vec<NodeId> {
&mut self.0
}
}
pub(crate) struct Parser<'a> {
src: &'a str,
lexer: Lexer<'a>,
tok: Token,
prev_end: u32,
ast: Ast,
scratch: Scratch,
names: Vec<Span>,
sorted_names: Vec<(Cow<'a, str>, Span)>,
if_chain: Vec<(u32, NodeId, NodeId)>,
error: Option<Diagnostic>,
recover: bool,
errors: Vec<Diagnostic>,
seen: usize,
module: bool,
ctx: Ctx,
depth: u32,
max_depth: u32,
budget: Budget,
labels: Vec<Label>,
label_chain: Option<usize>,
label_candidate: Option<u32>,
in_body: bool,
pending: Vec<(NodeId, Span, &'static str)>,
classes: Vec<ClassScope>,
exports: HashMap<String, Span>,
last_yield: Option<u32>,
last_await: Option<u32>,
last_await_ident: Option<u32>,
}
impl<'a> Parser<'a> {
pub(crate) fn new(src: &'a str, options: &Options) -> Parser<'a> {
let len = match options.limits.check_input(src.len()) {
Ok(()) => src.len(),
Err(_) => 0,
};
Parser::with_room(
src,
options,
16 + len.min(1 << 16) / 4 + len.saturating_sub(1 << 16) / 8,
)
}
fn with_room(src: &'a str, options: &Options, nodes: usize) -> Parser<'a> {
let lexer = Lexer::with_limits(src, options.source_type, &options.limits);
let ast = Ast::new(nodes);
let module = options.source_type == SourceType::Module;
Parser {
src: lexer.source(),
lexer,
tok: Token {
kind: Kind::Eof,
flags: Flags::empty(),
span: Span::at(0),
},
prev_end: 0,
ast,
scratch: Scratch::take(),
names: Vec::new(),
sorted_names: Vec::new(),
if_chain: Vec::new(),
error: None,
recover: false,
errors: Vec::new(),
seen: 0,
module,
ctx: Ctx {
strict: module,
await_: module,
..Ctx::default()
},
depth: 0,
max_depth: options.limits.max_depth.unwrap_or(DEFAULT_MAX_DEPTH),
budget: options.limits.budget(),
labels: Vec::new(),
label_chain: None,
label_candidate: None,
in_body: false,
pending: Vec::new(),
classes: Vec::new(),
exports: HashMap::new(),
last_yield: None,
last_await: None,
last_await_ident: None,
}
}
pub(crate) fn parse(mut self) -> Result<Ast, Diagnostic> {
let result = self.program();
if let Err(Stop) = result {
return Err(self.error.take().expect("a stop has a diagnostic"));
}
let mut ast = self.ast;
ast.warnings = self
.lexer
.take_diagnostics()
.into_iter()
.filter(|d| d.severity == Severity::Warning)
.collect();
Ok(ast)
}
fn piece(&mut self, body: bool) -> R<NodeId> {
if let Some(d) = self.lexer.diagnostics().first() {
return self.fail(d.clone());
}
self.advance()?;
if body {
self.function_body(List::default(), true, false, None)
} else {
self.statement_list_item()
}
}
fn parse_all(mut self) -> Result<Ast, Vec<Diagnostic>> {
let result = self.program();
let mut errors = std::mem::take(&mut self.errors);
if let Err(Stop) = result {
errors.extend(self.error.take());
}
if !errors.is_empty() {
return Err(errors);
}
let mut ast = self.ast;
ast.warnings = self
.lexer
.take_diagnostics()
.into_iter()
.filter(|d| d.severity == Severity::Warning)
.collect();
Ok(ast)
}
fn program(&mut self) -> R<()> {
if let Some(d) = self.lexer.diagnostics().first() {
return self.fail(d.clone());
}
self.advance()?;
let mark = self.scratch.len();
self.statement_list(true)?;
while self.recover && self.at(Punct::RBrace) {
let d = self.unexpected_diagnostic();
self.errors.push(d);
self.skip_token()?;
self.statement_list(false)?;
}
if self.tok.kind != Kind::Eof {
return self.unexpected();
}
let body = self.take_list(mark);
let source_type = if self.module {
SourceType::Module
} else {
SourceType::Script
};
let root = self.ast.push(
Span::new(0, self.src.len() as u32),
Node::Program { body, source_type },
);
self.ast.root = Some(root);
Ok(())
}
fn fail<T>(&mut self, d: Diagnostic) -> R<T> {
if self.error.is_none() {
self.error = Some(d);
}
Err(Stop)
}
fn err<T>(
&mut self,
code: &'static str,
span: Span,
message: impl Into<Cow<'static, str>>,
) -> R<T> {
self.fail(Diagnostic::error(code, span, message))
}
fn unexpected<T>(&mut self) -> R<T> {
let d = self.unexpected_diagnostic();
self.fail(d)
}
fn unexpected_diagnostic(&self) -> Diagnostic {
let t = self.tok;
if t.kind == Kind::Eof {
return Diagnostic::error(
"unexpected-end",
t.span,
"the input ends in the middle of something",
);
}
let text = t.text(self.src);
let shown: String = text.chars().take(40).collect();
Diagnostic::error(
"unexpected-token",
t.span,
format!("`{shown}` can't go here"),
)
}
fn expect_in(&mut self, p: Punct, open: Token) -> R<Token> {
if self.at(p) {
return self.bump();
}
self.unclosed(open)
}
#[cold]
#[inline(never)]
fn unclosed<T>(&mut self, open: Token) -> R<T> {
let what = match open.kind {
Kind::Punct(Punct::LParen) => "this `(` is still open",
Kind::Punct(Punct::LBracket) => "this `[` is still open",
_ => "this `{` is still open",
};
let d = self.unexpected_diagnostic().with_label(open.span, what);
self.fail(d)
}
fn advance(&mut self) -> R<()> {
self.tok = self.lexer.next_token(Goal::Div);
self.check_lexer()?;
if self.tok.is_trivia() {
return self.after_comments();
}
Ok(())
}
#[inline(never)]
fn after_comments(&mut self) -> R<()> {
loop {
let t = self.tok;
let kind = match t.kind {
Kind::LineComment => CommentKind::Line,
Kind::BlockComment => CommentKind::Block,
Kind::Hashbang => CommentKind::Hashbang,
Kind::HtmlOpenComment => CommentKind::HtmlOpen,
Kind::HtmlCloseComment => CommentKind::HtmlClose,
_ => return Ok(()),
};
self.ast.comments.push(Comment { kind, span: t.span });
self.tok = self.lexer.next_token(Goal::Div);
self.check_lexer()?;
}
}
#[inline(always)]
fn check_lexer(&mut self) -> R<()> {
if self.lexer.diagnostics().len() > self.seen {
return self.lexer_reported();
}
Ok(())
}
#[cold]
#[inline(never)]
fn lexer_reported(&mut self) -> R<()> {
let diagnostics = self.lexer.diagnostics();
if diagnostics.len() > self.seen {
let new = &diagnostics[self.seen..];
self.seen = diagnostics.len();
if let Some(d) = new.iter().find(|d| d.is_error()) {
let d = d.clone();
return self.fail(d);
}
}
Ok(())
}
#[inline(always)]
fn bump(&mut self) -> R<Token> {
let t = self.tok;
self.skip()?;
Ok(t)
}
#[inline(never)]
fn skip(&mut self) -> R<()> {
let spent = self.budget.spend(1).is_ok();
if !spent || (self.tok.flags.contains(Flags::LEGACY_OCTAL) && self.ctx.strict) {
return self.refuse_token(spent);
}
self.prev_end = self.tok.span.end;
self.advance()
}
#[cold]
#[inline(never)]
fn refuse_token(&mut self, spent: bool) -> R<()> {
let span = self.tok.span;
if !spent {
return self.err(
"step-budget",
span,
"the parse used up its step budget here",
);
}
self.err(
"legacy-octal-in-strict",
span,
"legacy octal literals and escapes aren't allowed in strict code",
)
}
fn rescan(&mut self, goal: Goal) -> R<()> {
self.tok = self.lexer.rescan(self.tok, goal);
self.check_lexer()
}
fn peek(&self) -> Token {
let mut lexer = self.lexer.fork();
loop {
let t = lexer.next_token(Goal::Div);
if !t.is_trivia() {
return t;
}
}
}
fn at(&self, p: Punct) -> bool {
self.tok.kind == Kind::Punct(p)
}
fn at_kw(&self, k: Keyword) -> bool {
self.tok.kind == Kind::Keyword(k)
}
fn eat(&mut self, p: Punct) -> R<bool> {
if self.at(p) {
self.bump()?;
return Ok(true);
}
Ok(false)
}
fn expect(&mut self, p: Punct) -> R<Token> {
if self.at(p) {
return self.bump();
}
self.unexpected()
}
fn expect_kw(&mut self, k: Keyword) -> R<Token> {
if self.at_kw(k) {
return self.bump();
}
self.unexpected()
}
fn semicolon(&mut self) -> R<()> {
if self.eat(Punct::Semicolon)? {
return Ok(());
}
if self.can_insert_semicolon() {
return Ok(());
}
self.unexpected()
}
fn can_insert_semicolon(&self) -> bool {
self.tok.newline_before() || self.at(Punct::RBrace) || self.tok.kind == Kind::Eof
}
fn finish(&mut self, start: u32, node: Node) -> NodeId {
self.ast
.push(Span::new(start, self.prev_end.max(start)), node)
}
fn take_list(&mut self, mark: usize) -> List {
self.ast.list(self.scratch.drain(mark..))
}
fn node(&self, id: NodeId) -> Node {
*self.ast.node(id)
}
fn span(&self, id: NodeId) -> Span {
self.ast.span(id)
}
fn enter(&mut self) -> R<()> {
self.depth += 1;
if self.depth > self.max_depth {
let span = self.tok.span;
return self.err(
"too-deep",
span,
format!("this nests deeper than the limit of {}", self.max_depth),
);
}
Ok(())
}
fn leave(&mut self) {
self.depth -= 1;
}
fn name(&self, span: Span) -> Cow<'a, str> {
let raw = span.text(self.src);
if !self.lexer.escaped_ident() {
return Cow::Borrowed(raw);
}
text::ident_name(raw)
}
fn name_is(&self, span: Span, name: &str) -> bool {
let raw = span.text(self.src);
match raw.len().cmp(&name.len()) {
std::cmp::Ordering::Less => false,
std::cmp::Ordering::Equal => raw == name,
std::cmp::Ordering::Greater => {
self.lexer.escaped_ident() && raw.contains('\\') && text::ident_name(raw) == name
}
}
}
fn at_ident_name(&self) -> bool {
matches!(self.tok.kind, Kind::Ident | Kind::Keyword(_))
}
fn at_identifier(&self) -> bool {
match self.tok.kind {
Kind::Ident => true,
Kind::Keyword(k) => !k.is_reserved() || matches!(k, Keyword::Yield | Keyword::Await),
_ => false,
}
}
fn word(&self, t: Token) -> Option<Keyword> {
match t.kind {
Kind::Keyword(k) => Some(k),
Kind::Ident if t.flags.contains(Flags::ESCAPED) => {
Keyword::from_str(&self.name(t.span))
}
_ => None,
}
}
#[inline(always)]
fn check_identifier(&mut self, t: Token, binding: bool) -> R<()> {
if t.kind == Kind::Ident
&& !t.flags.contains(Flags::ESCAPED)
&& !(binding && self.ctx.strict)
{
return Ok(());
}
self.check_word(t, binding)
}
#[inline(never)]
fn check_word(&mut self, t: Token, binding: bool) -> R<()> {
let word = self.word(t);
let reserved = match word {
None => false,
Some(Keyword::Await) => {
self.last_await_ident = Some(t.span.start);
self.ctx.await_ || self.module || self.ctx.static_block
}
Some(Keyword::Yield) => self.ctx.yield_ || self.ctx.strict,
Some(k) if k.is_strict_reserved() => self.ctx.strict,
Some(k) => k.is_reserved(),
};
if reserved {
let name = self.name(t.span).into_owned();
return self.err(
"reserved-word",
t.span,
format!("`{name}` is reserved here, so it can't be an identifier"),
);
}
if word.is_none() && binding && self.ctx.strict {
let name = self.name(t.span);
if name == "eval" || name == "arguments" {
return self.err(
"strict-binding",
t.span,
format!("strict code can't bind or assign `{name}`"),
);
}
}
Ok(())
}
fn check_arguments(&mut self, span: Span) -> R<()> {
if self.ctx.no_arguments && self.name_is(span, "arguments") {
return self.err(
"arguments-in-class-init",
span,
"`arguments` isn't allowed in a class field or static block",
);
}
Ok(())
}
fn identifier(&mut self, binding: bool) -> R<NodeId> {
if !self.at_identifier() {
return self.unexpected();
}
let t = self.tok;
self.check_identifier(t, binding)?;
self.bump()?;
Ok(self.ast.push(t.span, Node::Identifier))
}
fn identifier_name(&mut self) -> R<NodeId> {
if !self.at_ident_name() {
return self.unexpected();
}
let t = self.bump()?;
Ok(self.ast.push(t.span, Node::Identifier))
}
fn declare_private(&mut self, span: Span, kind: Private, is_static: bool) -> R<()> {
let name = self.name(Span::new(span.start + 1, span.end)).into_owned();
if name == "constructor" {
return self.err(
"private-constructor",
span,
"a private name can't be #constructor",
);
}
let Some(scope) = self.classes.last_mut() else {
return self.err(
"private-outside-class",
span,
"private names are only declared in classes",
);
};
let first = match scope.declared.get_mut(&name) {
None => {
scope.declared.insert(name, (kind, is_static, span));
return Ok(());
}
Some((had, was_static, first)) if *was_static == is_static => match (*had, kind) {
(Private::Get, Private::Set) | (Private::Set, Private::Get) => {
*had = Private::GetSet;
return Ok(());
}
_ => *first,
},
Some((.., first)) => *first,
};
self.fail(
Diagnostic::error(
"duplicate-private-name",
span,
format!("#{name} is declared twice"),
)
.with_label(first, "declared here first"),
)
}
fn use_private(&mut self, span: Span) -> R<()> {
let name = self.name(Span::new(span.start + 1, span.end)).into_owned();
match self.classes.last_mut() {
Some(scope) => {
scope.used.push((name, span));
Ok(())
}
None => self.err(
"undeclared-private-name",
span,
format!("#{name} isn't declared in a class around it"),
),
}
}
fn end_class_scope(&mut self) -> R<()> {
let scope = self.classes.pop().unwrap_or_default();
for (name, span) in scope.used {
if scope.declared.contains_key(&name) {
continue;
}
match self.classes.last_mut() {
Some(outer) => outer.used.push((name, span)),
None => {
return self.err(
"undeclared-private-name",
span,
format!("#{name} isn't declared in a class around it"),
);
}
}
}
Ok(())
}
fn check_pending(&mut self, mark: usize) -> R<()> {
if self.pending.len() <= mark {
return Ok(());
}
let found = self.pending[mark..]
.iter()
.find(|(id, ..)| matches!(self.ast.node(*id), Node::Object { .. }))
.copied();
self.pending.truncate(mark);
match found {
Some((_, span, "shorthand-init")) => self.err(
"shorthand-init",
span,
"`{a = 1}` is only allowed as a pattern, like `({a = 1} = b)`",
),
Some((_, span, _)) => self.err(
"duplicate-proto",
span,
"an object literal can set __proto__ only once",
),
None => Ok(()),
}
}
}
fn starts_expression(kind: Kind) -> bool {
match kind {
Kind::Eof => false,
Kind::Keyword(Keyword::In | Keyword::Instanceof) => false,
Kind::Punct(p) => matches!(
p,
Punct::LParen
| Punct::LBracket
| Punct::LBrace
| Punct::Plus
| Punct::Minus
| Punct::Bang
| Punct::Tilde
| Punct::PlusPlus
| Punct::MinusMinus
| Punct::Slash
| Punct::SlashEq
),
_ => true,
}
}