Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ecma/parser): throw error when function body has use strict and paramaters is not simple #3278

Merged
merged 6 commits into from
Jan 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/swc_ecma_parser/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ pub enum SyntaxError {
InvalidIdentInStrict,
/// 'eval' and 'arguments' are invalid identifier in strict mode.
EvalAndArgumentsInStrict,
IllegalLanguageModeDirective,
UnaryInExp {
left: String,
left_span: Span,
Expand Down Expand Up @@ -300,6 +301,9 @@ impl SyntaxError {
SyntaxError::EvalAndArgumentsInStrict => "'eval' and 'arguments' cannot be used as a \
binding identifier in strict mode"
.into(),
SyntaxError::IllegalLanguageModeDirective => {
"Illegal 'use strict' directive in function with non-simple parameter list.".into()
}
SyntaxError::UnaryInExp { .. } => "** cannot be applied to unary expression".into(),
SyntaxError::Hash => "Unexpected token '#'".into(),
SyntaxError::LineBreakInThrow => "LineBreak cannot follow 'throw'".into(),
Expand Down
82 changes: 71 additions & 11 deletions crates/swc_ecma_parser/src/parser/class_and_fn.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::{ident::MaybeOptionalIdentParser, *};
use crate::{error::SyntaxError, lexer::TokenContext, Tokens};
use crate::{error::SyntaxError, lexer::TokenContext, parser::stmt::IsDirective, Tokens};
use either::Either;
use swc_atoms::js_word;
use swc_common::{Spanned, SyntaxContext};
Expand Down Expand Up @@ -667,7 +667,8 @@ impl<'a, I: Tokens> Parser<I> {
self.emit_err(type_ann.type_ann.span(), SyntaxError::TS1093);
}

let body: Option<_> = self.parse_fn_body(false, false)?;
let body: Option<_> =
self.parse_fn_body(false, false, params.is_simple_parameter_list())?;

if self.syntax().typescript() && body.is_none() {
// Declare constructors cannot have assignment pattern in parameters
Expand Down Expand Up @@ -1110,7 +1111,8 @@ impl<'a, I: Tokens> Parser<I> {
None
};

let body: Option<_> = p.parse_fn_body(is_async, is_generator)?;
let body: Option<_> =
p.parse_fn_body(is_async, is_generator, params.is_simple_parameter_list())?;

if p.syntax().typescript() && body.is_none() {
// Declare functions cannot have assignment pattern in parameters
Expand Down Expand Up @@ -1149,7 +1151,12 @@ impl<'a, I: Tokens> Parser<I> {
}
}

pub(super) fn parse_fn_body<T>(&mut self, is_async: bool, is_generator: bool) -> PResult<T>
pub(super) fn parse_fn_body<T>(
&mut self,
is_async: bool,
is_generator: bool,
is_simple_parameter_list: bool,
) -> PResult<T>
where
Self: FnBodyParser<T>,
{
Expand All @@ -1173,7 +1180,9 @@ impl<'a, I: Tokens> Parser<I> {
labels: vec![],
..Default::default()
};
self.with_ctx(ctx).with_state(state).parse_fn_body_inner()
self.with_ctx(ctx)
.with_state(state)
.parse_fn_body_inner(is_simple_parameter_list)
}
}

Expand Down Expand Up @@ -1373,26 +1382,77 @@ impl OutputType for Decl {
}

pub(super) trait FnBodyParser<Body> {
fn parse_fn_body_inner(&mut self) -> PResult<Body>;
fn parse_fn_body_inner(&mut self, is_simple_parameter_list: bool) -> PResult<Body>;
}
fn has_use_strict(block: &BlockStmt) -> Option<Span> {
match block.stmts.iter().find(|stmt| stmt.is_use_strict()) {
Some(Stmt::Expr(ExprStmt { span, expr: _ })) => Some(*span),
_ => None,
}
}

impl<I: Tokens> FnBodyParser<BlockStmtOrExpr> for Parser<I> {
fn parse_fn_body_inner(&mut self) -> PResult<BlockStmtOrExpr> {
fn parse_fn_body_inner(&mut self, is_simple_parameter_list: bool) -> PResult<BlockStmtOrExpr> {
if is!(self, '{') {
self.parse_block(false).map(BlockStmtOrExpr::BlockStmt)
self.parse_block(false).map(|block_stmt| {
if !self.input.syntax().typescript() && !is_simple_parameter_list {
if let Some(span) = has_use_strict(&block_stmt) {
self.emit_err(span, SyntaxError::IllegalLanguageModeDirective);
}
}
BlockStmtOrExpr::BlockStmt(block_stmt)
})
} else {
self.parse_assignment_expr().map(BlockStmtOrExpr::Expr)
}
}
}

impl<I: Tokens> FnBodyParser<Option<BlockStmt>> for Parser<I> {
fn parse_fn_body_inner(&mut self) -> PResult<Option<BlockStmt>> {
fn parse_fn_body_inner(
&mut self,
is_simple_parameter_list: bool,
) -> PResult<Option<BlockStmt>> {
// allow omitting body and allow placing `{` on next line
if self.input.syntax().typescript() && !is!(self, '{') && eat!(self, ';') {
return Ok(None);
}
self.include_in_expr(true).parse_block(true).map(Some)
let block = self.include_in_expr(true).parse_block(true);
block.map(|block_stmt| {
if !self.input.syntax().typescript() && !is_simple_parameter_list {
if let Some(span) = has_use_strict(&block_stmt) {
self.emit_err(span, SyntaxError::IllegalLanguageModeDirective);
}
}
Some(block_stmt)
})
}
}

pub(super) trait IsSimpleParameterList {
fn is_simple_parameter_list(&self) -> bool;
}
impl IsSimpleParameterList for Vec<Param> {
fn is_simple_parameter_list(&self) -> bool {
self.iter().all(|param| matches!(param.pat, Pat::Ident(_)))
}
}
impl IsSimpleParameterList for Vec<Pat> {
fn is_simple_parameter_list(&self) -> bool {
self.iter().all(|pat| matches!(pat, Pat::Ident(_)))
}
}
impl IsSimpleParameterList for Vec<ParamOrTsParamProp> {
fn is_simple_parameter_list(&self) -> bool {
self.iter().all(|param| {
matches!(
param,
ParamOrTsParamProp::TsParamProp(..)
| ParamOrTsParamProp::Param(Param {
pat: Pat::Ident(_),
..
})
)
})
Comment on lines +1444 to +1455
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure about ts params, so I ignored them

}
}

Expand Down
29 changes: 20 additions & 9 deletions crates/swc_ecma_parser/src/parser/expr.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use super::{pat::PatType, util::ExprExt, *};
use crate::{lexer::TokenContext, token::AssignOpToken};
use crate::{
lexer::TokenContext, parser::class_and_fn::IsSimpleParameterList, token::AssignOpToken,
};
use either::Either;
use swc_atoms::js_word;
use swc_common::{ast_node, util::take::Take, Spanned};
Expand Down Expand Up @@ -394,7 +396,7 @@ impl<'a, I: Tokens> Parser<I> {
let arg = Pat::from(ident);
let params = vec![arg];
expect!(self, "=>");
let body = self.parse_fn_body(true, false)?;
let body = self.parse_fn_body(true, false, params.is_simple_parameter_list())?;

return Ok(Box::new(Expr::Arrow(ArrowExpr {
span: span!(self, start),
Expand All @@ -407,7 +409,7 @@ impl<'a, I: Tokens> Parser<I> {
})));
} else if can_be_arrow && !self.input.had_line_break_before_cur() && eat!(self, "=>") {
let params = vec![id.into()];
let body = self.parse_fn_body(false, false)?;
let body = self.parse_fn_body(false, false, params.is_simple_parameter_list())?;

return Ok(Box::new(Expr::Arrow(ArrowExpr {
span: span!(self, start),
Expand Down Expand Up @@ -681,12 +683,16 @@ impl<'a, I: Tokens> Parser<I> {

expect!(p, "=>");

let params = p
let params: Vec<Pat> = p
.parse_paren_items_as_params(items_ref.clone())?
.into_iter()
.collect();

let body: BlockStmtOrExpr = p.parse_fn_body(async_span.is_some(), false)?;
let body: BlockStmtOrExpr = p.parse_fn_body(
async_span.is_some(),
false,
params.is_simple_parameter_list(),
)?;

if is_direct_child_of_cond {
if !is_one_of!(p, ':', ';') {
Expand Down Expand Up @@ -733,12 +739,16 @@ impl<'a, I: Tokens> Parser<I> {
}
expect!(self, "=>");

let params = self
let params: Vec<Pat> = self
.parse_paren_items_as_params(paren_items)?
.into_iter()
.collect();

let body: BlockStmtOrExpr = self.parse_fn_body(async_span.is_some(), false)?;
let body: BlockStmtOrExpr = self.parse_fn_body(
async_span.is_some(),
false,
params.is_simple_parameter_list(),
)?;
let arrow_expr = ArrowExpr {
span: span!(self, expr_start),
is_async: async_span.is_some(),
Expand Down Expand Up @@ -1633,12 +1643,13 @@ impl<'a, I: Tokens> Parser<I> {
_ => false,
}
} {
let params = self
let params: Vec<Pat> = self
.parse_paren_items_as_params(items.clone())?
.into_iter()
.collect();

let body: BlockStmtOrExpr = self.parse_fn_body(false, false)?;
let body: BlockStmtOrExpr =
self.parse_fn_body(false, false, params.is_simple_parameter_list())?;
let span = span!(self, start);

items.push(PatOrExprOrSpread::ExprOrSpread(ExprOrSpread {
Expand Down
55 changes: 55 additions & 0 deletions crates/swc_ecma_parser/src/parser/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,3 +301,58 @@ fn issue_2853_2() {
Ok(program)
});
}

#[test]
fn illegal_language_mode_directive1() {
test_parser(
r#"function f(a = 0) { "use strict"; }"#,
Default::default(),
|p| {
let program = p.parse_program()?;

let errors = p.take_errors();
assert_eq!(
errors,
vec![Error {
error: Box::new((
Span {
lo: BytePos(20),
hi: BytePos(33),
ctxt: swc_common::SyntaxContext::empty()
},
crate::parser::SyntaxError::IllegalLanguageModeDirective
))
}]
);

Ok(program)
},
);
}
#[test]
fn illegal_language_mode_directive2() {
test_parser(
r#"let f = (a = 0) => { "use strict"; }"#,
Default::default(),
|p| {
let program = p.parse_program()?;

let errors = p.take_errors();
assert_eq!(
errors,
vec![Error {
error: Box::new((
Span {
lo: BytePos(21),
hi: BytePos(34),
ctxt: swc_common::SyntaxContext::empty()
},
crate::parser::SyntaxError::IllegalLanguageModeDirective
))
}]
);

Ok(program)
},
);
}
6 changes: 3 additions & 3 deletions crates/swc_ecma_parser/src/parser/typescript.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::*;
use crate::lexer::TokenContexts;
use crate::{lexer::TokenContexts, parser::class_and_fn::IsSimpleParameterList};
use either::Either;
use swc_atoms::js_word;
use swc_common::{Spanned, SyntaxContext};
Expand Down Expand Up @@ -2474,7 +2474,7 @@ impl<I: Tokens> Parser<I> {
let type_params = p.parse_ts_type_params()?;
// Don't use overloaded parseFunctionParams which would look for "<" again.
expect!(p, '(');
let params = p
let params: Vec<Pat> = p
.parse_formal_params()?
.into_iter()
.map(|p| p.pat)
Expand Down Expand Up @@ -2502,7 +2502,7 @@ impl<I: Tokens> Parser<I> {
self.with_ctx(ctx).parse_with(|p| {
let is_generator = false;
let is_async = true;
let body = p.parse_fn_body(true, false)?;
let body = p.parse_fn_body(true, false, params.is_simple_parameter_list())?;
Ok(Some(ArrowExpr {
span: span!(p, start),
body,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
let f = (a = 0) => {
"use strict";
}
Loading