Skip to content

Truly independent web browser

LibJS: Parse the parameters of a dynamic function on their own

Shannon Booth36db02793909
diff --git a/Libraries/LibJS/Parser/Rust/src/expr.rs b/Libraries/LibJS/Parser/Rust/src/expr.rs
index b706549bf55..5cd62557ce1 100644
--- a/Libraries/LibJS/Parser/Rust/src/expr.rs
+++ b/Libraries/LibJS/Parser/Rust/src/expr.rs
@@ -9,6 +9,7 @@
use super::base::*;
use super::columns::*;
+use super::stmt::ParameterList;
use super::token::*;
use super::unit::Unit;
@@ -1397,7 +1398,13 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
let own_flags = function_flag::ARROW | if is_async { function_flag::ASYNC } else { 0 };
let mut state = self.begin_function(start, new_ctx, own_flags);
self.scopes.last_mut().unwrap().flags |= scope_flag::ARROW;
- let (list, count, length, simple, _) = self.parse_parameter_list(&mut state);
+ let ParameterList {
+ list,
+ count,
+ length,
+ simple,
+ ..
+ } = self.parse_parameter_list(&mut state);
self.parse_arrow_body(&mut state, list, count, length, simple, params_start, no_in, start)
}
diff --git a/Libraries/LibJS/Parser/Rust/src/stmt.rs b/Libraries/LibJS/Parser/Rust/src/stmt.rs
index fb30aee6995..cb68593235a 100644
--- a/Libraries/LibJS/Parser/Rust/src/stmt.rs
+++ b/Libraries/LibJS/Parser/Rust/src/stmt.rs
@@ -26,6 +26,16 @@ pub(crate) enum Context {
Single,
}
+/// The parameters of a function.
+pub(crate) struct ParameterList {
+ pub list: u32,
+ pub count: u32,
+ /// ExpectedArgumentCount of the list.
+ pub length: u32,
+ pub simple: bool,
+ pub has_rest: bool,
+}
+
#[derive(Clone, Copy, PartialEq, Eq)]
enum VarKind {
Var,
@@ -1131,15 +1141,39 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
}
/// The parameter list, from the `(`.
- pub(crate) fn parse_parameter_list(&mut self, state: &mut FunctionState) -> (u32, u32, u32, bool, bool) {
+ pub(crate) fn parse_parameter_list(&mut self, state: &mut FunctionState) -> ParameterList {
let params_start = self.tok_start;
self.expect(T::LParen);
+ let parameters = self.parse_parameters_until(T::RParen, params_start, state);
+ self.expect(T::RParen);
+ parameters
+ }
+
+ /// Parses the whole source as the parameter list of a function of the given kind.
+ pub fn parse_parameters_of_dynamic_function(&mut self, is_generator: bool, is_async: bool) {
+ self.open_scope_with(scope_flag::TOP, 0);
+ self.lex();
+ let new_ctx = Self::function_ctx(is_generator, is_async);
+ let flags = Self::function_flags(is_generator, is_async);
+ let mut state = self.begin_function(0, new_ctx, flags);
+ let parameters = self.parse_parameters_until(T::Eof, 0, &mut state);
+
+ // 15.1.1 Static Semantics: Early Errors, https://tc39.es/ecma262/#sec-parameter-lists-static-semantics-early-errors
+ // FormalParameters : FormalParameterList
+ // It is a Syntax Error if IsSimpleParameterList of FormalParameterList is false and the BoundNames of FormalParameterList contains any duplicate elements.
+ if !parameters.simple && self.duplicate_parameter != NONE {
+ self.fail(self.duplicate_parameter, "Duplicate parameter names not allowed");
+ }
+ }
+
+ /// Parses parameters up to `close`.
+ fn parse_parameters_until(&mut self, close: T, params_start: u32, state: &mut FunctionState) -> ParameterList {
let mark = self.scratch.len();
let mut simple = true;
let mut has_rest = false;
let mut length = 0;
let mut counting = true;
- while self.tok != T::RParen && self.tok != T::Eof {
+ while self.tok != close && self.tok != T::Eof {
let item_start = self.tok_start;
let item = if self.tok == T::Ellipsis {
self.next();
@@ -1147,7 +1181,7 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
has_rest = true;
simple = false;
counting = false;
- if self.tok != T::RParen {
+ if self.tok != close {
self.fail(self.tok_start, "Rest parameter must be last");
}
self.ast.push(tag::REST, item_start, target, 0)
@@ -1162,11 +1196,10 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
item
};
self.scratch.push(item);
- if self.tok != T::RParen {
- self.expect_comma_or(T::RParen);
+ if self.tok != close {
+ self.expect_comma_or(close);
}
}
- self.expect(T::RParen);
let count = (self.scratch.len() - mark) as u32;
let list = self.finish_list(mark);
if self.yield_pos != 0 || self.await_pos != 0 {
@@ -1175,7 +1208,13 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
if simple {
state.flags |= function_flag::SIMPLE_PARAMETERS;
}
- (list, count, length, simple, has_rest)
+ ParameterList {
+ list,
+ count,
+ length,
+ simple,
+ has_rest,
+ }
}
pub(crate) fn parse_function_tail(
@@ -1201,7 +1240,13 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
let node = self.skip_function(moved_state, row);
return (node, 0, false);
}
- let (list, count, length, simple, has_rest) = self.parse_parameter_list(state);
+ let ParameterList {
+ list,
+ count,
+ length,
+ simple,
+ has_rest,
+ } = self.parse_parameter_list(state);
if self.tok != T::LBrace {
self.unexpected();
}
diff --git a/Libraries/LibJS/Parser/Rust/src/token.rs b/Libraries/LibJS/Parser/Rust/src/token.rs
index 76bf7c14528..b14f3655dd9 100644
--- a/Libraries/LibJS/Parser/Rust/src/token.rs
+++ b/Libraries/LibJS/Parser/Rust/src/token.rs
@@ -49,6 +49,7 @@ impl T {
/// How error messages spell a token that the grammar wants.
pub fn spelling(self) -> &'static str {
match self {
+ T::Eof => "end of input",
T::LBrace => "'{'",
T::RBrace => "'}'",
T::LParen => "'('",
diff --git a/Libraries/LibJS/Rust/src/compile.rs b/Libraries/LibJS/Rust/src/compile.rs
index f94cf66cfe2..3bcc2a8f4bb 100644
--- a/Libraries/LibJS/Rust/src/compile.rs
+++ b/Libraries/LibJS/Rust/src/compile.rs
@@ -35,6 +35,7 @@ use crate::parser::ParseError;
use crate::parser::ParseOptions;
use crate::parser::ScriptData;
use crate::parser::TopLevelRows;
+use crate::parser::check_function_parameters;
use crate::parser::check_syntax;
use crate::parser::with_parsed_tree;
use crate::utf16::Utf16View;
@@ -1024,48 +1025,21 @@ pub fn parse_dynamic_function(
body_source: &[u16],
kind: ast::FunctionKind,
) -> Result<ParsedDynamicFunction, Vec<ParseError>> {
- // Lex the parameters on their own first, so that lexer errors such as an unterminated comment have positions in
- // the parameter string.
- let mut lexer = crate::lexer::Lexer::new(Utf16View::Utf16(parameters_source), 1, 0);
- loop {
- let token = lexer.next();
- if token.token_type == crate::token::TokenType::Eof {
- break;
- }
- if token.token_type == crate::token::TokenType::Invalid {
- let message = token
- .message
- .unwrap_or_else(|| format!("Unexpected token {}", token.token_type.name()));
- return Err(vec![ParseError {
- message,
- line: token.line_number,
- column: token.line_column,
- }]);
- }
- }
+ // 17. Let parameters be ParseText(P, parameterSym).
+ // 18. If parameters is a List of errors, throw a SyntaxError exception.
+ check_function_parameters(&ak::Utf16String::from_utf16(parameters_source), kind)?;
- // Then check them as the parameters of a function of the same kind.
- let mut parameters_check: Vec<u16> = Vec::new();
- parameters_check.extend_from_slice(match kind {
- ast::FunctionKind::Generator => utf16!("function* test("),
- ast::FunctionKind::Async => utf16!("async function test("),
- ast::FunctionKind::AsyncGenerator => utf16!("async function* test("),
- ast::FunctionKind::Normal => utf16!("function test("),
- });
- parameters_check.extend_from_slice(parameters_source);
- parameters_check.extend_from_slice(utf16!("\n) {}"));
- check_syntax(
- &ak::Utf16String::from_utf16(&parameters_check),
- &ParseOptions::new(ProgramType::Script),
- )?;
-
- // Check the body on its own as a script with the flags of a function body of the kind.
+ // 19. Let body be ParseText(bodyParseString, bodySym).
+ // 20. If body is a List of errors, throw a SyntaxError exception.
let mut options = ParseOptions::new(ProgramType::Script);
options.function_body = Some(kind);
check_syntax(&ak::Utf16String::from_utf16(body_source), &options)?;
- // The function is parsed as a function expression, so it has no Program scope whose globals its identifiers
- // could bind to.
+ // 21. NOTE: The parameters and body are parsed separately to ensure that each is valid alone. For example, new Function("/*", "*/ ) {") does not evaluate to a function.
+ // 22. NOTE: If this step is reached, sourceText must have the syntax of exprSym (although the reverse implication does not hold). The purpose of the next two steps is to enforce any Early Error rules which apply to exprSym directly.
+ // 23. Let expr be ParseText(sourceText, exprSym).
+ // 24. If expr is a List of errors, throw a SyntaxError exception.
+ // NB: As a function expression, the function has no Program scope whose globals its identifiers could bind to.
let mut options = ParseOptions::new(ProgramType::Script);
options.suppress_globals = true;
Ok(ParsedDynamicFunction {
diff --git a/Libraries/LibJS/Rust/src/parser/mod.rs b/Libraries/LibJS/Rust/src/parser/mod.rs
index ba7cf4f970d..ee8bdf15675 100644
--- a/Libraries/LibJS/Rust/src/parser/mod.rs
+++ b/Libraries/LibJS/Rust/src/parser/mod.rs
@@ -541,6 +541,24 @@ pub(crate) type TopLevelRows<'z> = Result<(AstColumns<'z>, u32), OutOfStack>;
enum ParsePurpose {
Compile,
CheckSyntax,
+ /// A check of the syntax of the code as the parameters of a function of this kind.
+ CheckFunctionParameters(crate::ast::FunctionKind),
+}
+
+/// The errors of a parse of `units` that failed with `error`.
+fn parse_errors<U: Unit>(
+ zone: &Zone,
+ units: &[U],
+ options: &ParseOptions,
+ error: base::PendingError<'_>,
+) -> Vec<ParseError> {
+ let lines = LineTable::new(zone, units, options.initial_line_number);
+ let position = lines.position(error.pos.min(u32_from_usize(units.len())));
+ vec![ParseError {
+ message: error.message.to_owned(),
+ line: position.line,
+ column: position.column,
+ }]
}
/// Parses `units`, the code units of `source`, from a copy of them in `zone` that is followed by the padding the lexer
@@ -576,15 +594,21 @@ fn parse_code_units<'z, U: Unit + Default, R>(
parser.strict |= options.starts_in_strict_mode;
parser.initiated_by_eval = options.initiated_by_eval;
parser.add_context(options.program_context().context);
- let root = parser.parse_program();
+ let root = match purpose {
+ ParsePurpose::Compile | ParsePurpose::CheckSyntax => parser.parse_program(),
+ ParsePurpose::CheckFunctionParameters(kind) => {
+ use crate::ast::FunctionKind;
+ let is_generator = matches!(kind, FunctionKind::Generator | FunctionKind::AsyncGenerator);
+ let is_async = matches!(kind, FunctionKind::Async | FunctionKind::AsyncGenerator);
+ parser.parse_parameters_of_dynamic_function(is_generator, is_async);
+ return match parser.err.take() {
+ Some(error) => Err(parse_errors(zone, units, options, error)),
+ None => Ok(None),
+ };
+ }
+ };
if let Some(error) = parser.err.take() {
- let lines = LineTable::new(zone, units, options.initial_line_number);
- let position = lines.position(error.pos.min(u32_from_usize(units.len())));
- return Err(vec![ParseError {
- message: error.message.to_owned(),
- line: position.line,
- column: position.column,
- }]);
+ return Err(parse_errors(zone, units, options, error));
}
if purpose == ParsePurpose::CheckSyntax {
return Ok(None);
@@ -704,3 +728,12 @@ pub fn with_parsed_tree<R>(
pub fn check_syntax(source: &ak::Utf16String, options: &ParseOptions) -> Result<(), Vec<ParseError>> {
parse_source(source, options, ParsePurpose::CheckSyntax, |_, _| ()).map(|_| ())
}
+
+/// Parses `source` as the parameters of a function of the kind, for their syntax errors alone.
+pub fn check_function_parameters(
+ source: &ak::Utf16String,
+ kind: crate::ast::FunctionKind,
+) -> Result<(), Vec<ParseError>> {
+ let options = ParseOptions::new(ProgramType::Script);
+ parse_source(source, &options, ParsePurpose::CheckFunctionParameters(kind), |_, _| ()).map(|_| ())
+}
diff --git a/Tests/LibJS/Runtime/builtins/Function/Function.js b/Tests/LibJS/Runtime/builtins/Function/Function.js
index bd459e9d54c..c06fdded6f6 100644
--- a/Tests/LibJS/Runtime/builtins/Function/Function.js
+++ b/Tests/LibJS/Runtime/builtins/Function/Function.js
@@ -63,4 +63,23 @@ describe("errors", () => {
new Function("/*", "*/ ) {");
}).toThrowWithMessage(SyntaxError, "Unterminated multi-line comment (line: 1, column: 3)");
});
+
+ test("parameters must not end the parameter list", () => {
+ const GeneratorFunction = function* () {}.constructor;
+ const AsyncFunction = async function () {}.constructor;
+ const AsyncGeneratorFunction = async function* () {}.constructor;
+ for (const constructor of [Function, GeneratorFunction, AsyncFunction, AsyncGeneratorFunction]) {
+ expect(() => constructor("a) { return 1; } function g(b", "return 2;")).toThrow(SyntaxError);
+ expect(() => constructor(") {} function g(", "return 2;")).toThrow(SyntaxError);
+ expect(() => constructor("a) {}; (0", "")).toThrow(SyntaxError);
+ expect(() => constructor("a b", "")).toThrowWithMessage(SyntaxError, "Expected ',' or end of input");
+ expect(() => constructor("a, a = 1", "return @")).toThrowWithMessage(
+ SyntaxError,
+ "Duplicate parameter names not allowed"
+ );
+ expect(() => constructor("a = function (b) {}, c", "")).not.toThrow();
+ expect(() => constructor("a, b // comment", "")).not.toThrow();
+ expect(() => constructor("{ a }, [b] = [], ...c", "")).not.toThrow();
+ }
+ });
});