Truly independent web browser
LibJS: Parse the directive prologue as statements
Shannon Boothe70a147098ea
diff --git a/Libraries/LibJS/Parser/Rust/src/base.rs b/Libraries/LibJS/Parser/Rust/src/base.rsindex 631d1828eb9..eb6d958d254 100644--- a/Libraries/LibJS/Parser/Rust/src/base.rs+++ b/Libraries/LibJS/Parser/Rust/src/base.rs@@ -37,6 +37,22 @@ pub const USE_IN_WITH: u32 = 1 << 31;/// How many zero code units the lexer needs after the source.pub const SOURCE_PADDING: usize = 64;+/// How far the directive prologue of a statement list has got.+pub(crate) struct Prologue {+ pub has_ended: bool,+ /// Where the first directive with a legacy escape is, or `NONE`.+ pub legacy_escape: u32,+}++impl Default for Prologue {+ fn default() -> Self {+ Self {+ has_ended: false,+ legacy_escape: NONE,+ }+ }+}+#[derive(Clone, Copy, PartialEq, Eq, Debug)]pub enum Mode {/// Only keep the tree of top-level code and of functions that are likely called right away.@@ -668,14 +684,12 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {pub fn parse_program(&mut self) -> u32 {self.open_scope_with(scope_flag::TOP, 0);- if !self.strict {- self.strict = self.has_use_strict_directive(self.pos as usize);- }self.lex();self.first_token_start = self.tok_start;let mark = self.scratch.len();+ let mut prologue = Prologue::default();while self.tok != T::Eof {- let statement = self.parse_statement_list_item(true);+ let (statement, _) = self.parse_statement_of_prologue(&mut prologue, true);self.scratch.push(statement);}let list = self.finish_list(mark);diff --git a/Libraries/LibJS/Parser/Rust/src/lexer.rs b/Libraries/LibJS/Parser/Rust/src/lexer.rsindex fba04d819d9..c7d79286213 100644--- a/Libraries/LibJS/Parser/Rust/src/lexer.rs+++ b/Libraries/LibJS/Parser/Rust/src/lexer.rs@@ -923,75 +923,4 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {}self.token(T::Regex, p);}-- /// Whether the directive prologue at `start` contains "use strict". This looks ahead in the source so that the- /// rest of the prologue is parsed knowing it.- pub(crate) fn has_use_strict_directive(&mut self, start: usize) -> bool {- if self.err.is_some() {- return false;- }- let mut p = start;- loop {- p = self.skip_trivia_raw(p).0;- let quote = self.at(p);- if quote != 0x22 && quote != 0x27 {- return false;- }- let content = p + 1;- let mut q = content;- loop {- let c = self.at(q);- if c == quote {- break;- }- if q >= self.len as usize || c == 0x0A || c == 0x0D {- return false;- }- q += if c == 0x5C { 2 } else { 1 };- }- let is_use_strict = q - content == 10 && (0..10).all(|i| self.at(content + i) == b"use strict"[i] as u32);- let (after, newline) = self.skip_trivia_raw(q + 1);- let next = self.at(after);- if is_use_strict {- if next == 0x3B || next == 0x7D || after >= self.len as usize {- return true;- }- let continues = matches!(- next as u8 as char,- '(' | '`' | '.' | '[' | '+' | '-' | '/' | '*' | '%' | '<' | '>' | '=' | ',' | '?' | '^' | '&' | '|'- ) && next < 0x80- || (next == 0x21 && self.at(after + 1) == 0x3D);- return newline && !continues;- }- p = after;- if next == 0x3B {- p += 1;- }- }- }-- fn skip_trivia_raw(&mut self, start: usize) -> (usize, bool) {- let mut p = start;- let mut newline = false;- loop {- let c = self.at(p);- match c {- 0x20 | 0x09 | 0x0B | 0x0C => p += 1,- 0x0A | 0x0D | 0x2028 | 0x2029 => {- newline = true;- p += 1;- }- 0x2F if self.at(p + 1) == 0x2F => p = self.skip_line_comment(p + 2),- 0x2F if self.at(p + 1) == 0x2A => match self.skip_block_comment(p + 2) {- Some((end, had_newline)) => {- p = end;- newline |= had_newline;- }- None => return (p, newline),- },- _ if c >= 0x80 && is_unicode_whitespace(c) => p += 1,- _ => return (p, newline),- }- }- }}diff --git a/Libraries/LibJS/Parser/Rust/src/stmt.rs b/Libraries/LibJS/Parser/Rust/src/stmt.rsindex 9da24c92308..fb30aee6995 100644--- a/Libraries/LibJS/Parser/Rust/src/stmt.rs+++ b/Libraries/LibJS/Parser/Rust/src/stmt.rs@@ -56,10 +56,6 @@ impl VarKind {}impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {- pub(crate) fn parse_statement_list_item(&mut self, top_level: bool) -> u32 {- self.parse_statement(Context::List, top_level)- }-fn is_let(&mut self, context: Context) -> bool {if !self.is_contextual(N_LET) {return false;@@ -1228,38 +1224,22 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {is_arrow: bool,is_method: bool,) -> u32 {- let old_strict = self.strict;- let mut use_strict = false;- if !old_strict || !simple {- use_strict = self.has_use_strict_directive(self.tok_end as usize);- if use_strict && !simple {- self.fail(- self.tok_start,- "Illegal 'use strict' directive in function with non-simple parameter list",- );- }- }- if use_strict {- self.strict = true;- self.arguments_of_sloppy_function |= is_arrow && !old_strict;- }+ // 15.1.1 Static Semantics: Early Errors, https://tc39.es/ecma262/#sec-parameter-lists-static-semantics-early-errors+ // UniqueFormalParameters : FormalParameters+ // It is a Syntax Error if the BoundNames of FormalParameters contains any duplicate elements.+ // FormalParameters : FormalParameterList+ // It is a Syntax Error if IsSimpleParameterList of FormalParameterList is false and the BoundNames of FormalParameterList contains any duplicate elements.+ // NB: Strict functions, arrow functions and methods have UniqueFormalParameters.if self.duplicate_parameter != NONE && (self.strict || !simple || is_arrow || is_method) {self.fail(self.duplicate_parameter, "Duplicate parameter names not allowed");}- if self.strict {- if let Some((name, pos)) = name {- self.check_strict_binding_name(name, pos);- }- if !old_strict {- let count = self.ast.extra[parameters as usize];- for i in 0..count {- let parameter = self.ast.extra[(parameters + 1 + i) as usize];- if self.ast.tag[parameter as usize] == tag::IDENT {- let (name, pos) = (self.ast.a[parameter as usize], self.ast.pos[parameter as usize]);- self.check_strict_binding_name(name, pos);- }- }- }++ // 15.2.1 Static Semantics: Early Errors, https://tc39.es/ecma262/#sec-function-definitions-static-semantics-early-errors+ // If BindingIdentifier is present and IsStrict(BindingIdentifier) is true, it is a Syntax Error if the StringValue of BindingIdentifier is either "eval" or "arguments".+ if self.strict+ && let Some((name, pos)) = name+ {+ self.check_strict_binding_name(name, pos);}if !simple {self.open_function_body_scope(state);@@ -1268,14 +1248,107 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {state.body_start = self.tok_start;state.first_body_row = self.ast.tag.len() as u32;let mark = self.scratch.len();+ let mut prologue = Prologue::default();while self.tok != T::RBrace && self.tok != T::Eof {- let statement = self.parse_statement(Context::List, false);+ let was_strict = self.strict;+ let (statement, use_strict) = self.parse_statement_of_prologue(&mut prologue, false);self.scratch.push(statement);+ if !use_strict {+ continue;+ }++ // It is a Syntax Error if FunctionBodyContainsUseStrict of FunctionBody is true and IsSimpleParameterList of FormalParameters is false.+ // NB: Arrow functions and methods have the same rule.+ if !simple {+ self.fail(+ self.ast.pos[statement as usize],+ "Illegal 'use strict' directive in function with non-simple parameter list",+ );+ }+ if !was_strict {+ self.arguments_of_sloppy_function |= is_arrow;+ self.check_parameters_of_strict_function(name, parameters);+ }}self.expect(T::RBrace);self.finish_list(mark)}+ // 15.2.1 Static Semantics: Early Errors, https://tc39.es/ecma262/#sec-function-definitions-static-semantics-early-errors+ /// Checks the name and the parameters of a function that a directive makes strict.+ fn check_parameters_of_strict_function(&mut self, name: Option<(u32, u32)>, parameters: u32) {+ // If IsStrict(FormalParameters) is true, the Early Error rules for UniqueFormalParameters : FormalParameters are applied.+ if self.duplicate_parameter != NONE {+ self.fail(self.duplicate_parameter, "Duplicate parameter names not allowed");+ }++ // If BindingIdentifier is present and IsStrict(BindingIdentifier) is true, it is a Syntax Error if the StringValue of BindingIdentifier is either "eval" or "arguments".+ if let Some((name, pos)) = name {+ self.check_strict_binding_name(name, pos);+ }++ // 13.1.1 Static Semantics: Early Errors, https://tc39.es/ecma262/#sec-identifiers-static-semantics-early-errors+ // BindingIdentifier : Identifier+ // It is a Syntax Error if IsStrict(this production) is true and the StringValue of Identifier is either "arguments" or "eval".+ // NB: The parameters were parsed before the directive made them strict code.+ let count = self.ast.extra[parameters as usize];+ for i in 0..count {+ let parameter = self.ast.extra[(parameters + 1 + i) as usize];+ if self.ast.tag[parameter as usize] == tag::IDENT {+ let (name, pos) = (self.ast.a[parameter as usize], self.ast.pos[parameter as usize]);+ self.check_strict_binding_name(name, pos);+ }+ }+ }++ // 11.2.1 Directive Prologues and the Use Strict Directive, https://tc39.es/ecma262/#sec-directive-prologues-and-the-use-strict-directive+ /// Parses a statement of a list that starts with a directive prologue. Returns the statement, and whether it is a+ /// use strict directive, which makes the code strict from there on.+ pub(crate) fn parse_statement_of_prologue(&mut self, prologue: &mut Prologue, top_level: bool) -> (u32, bool) {+ // A Directive Prologue is the longest sequence of ExpressionStatements occurring as the initial StatementListItems or ModuleItems of a FunctionBody, a ScriptBody, or a ModuleBody and where each ExpressionStatement in the sequence consists entirely of a StringLiteral token followed by a semicolon.+ if prologue.has_ended || self.tok != T::Str {+ prologue.has_ended = true;+ return (self.parse_statement(Context::List, top_level), false);+ }+ let (start, has_legacy_escape) = (self.tok_start, self.tok_legacy);+ let statement = self.parse_statement(Context::List, top_level);+ let expression = self.ast.a[statement as usize];+ let is_directive = statement != 0+ && self.ast.tag[statement as usize] == tag::EXPR_STMT+ && self.ast.tag[expression as usize] == tag::STR+ && self.ast.pos[expression as usize] == start;+ if !is_directive {+ prologue.has_ended = true;+ return (statement, false);+ }+ if has_legacy_escape && prologue.legacy_escape == NONE {+ prologue.legacy_escape = start;+ }++ // A Use Strict Directive is an ExpressionStatement in a Directive Prologue whose StringLiteral is either of the exact code point sequences "use strict" or 'use strict'. A Use Strict Directive may not contain an EscapeSequence or LineContinuation.+ let use_strict = b"use strict";+ let content = start as usize + 1;+ let closing_quote = self.ast.a[expression as usize] as usize - 1;+ let is_use_strict = closing_quote - content == use_strict.len()+ && (0..use_strict.len()).all(|i| self.at(content + i) == u32::from(use_strict[i]));+ if is_use_strict && !self.strict {+ self.strict = true;++ // 12.9.4.1 Static Semantics: Early Errors, https://tc39.es/ecma262/#sec-string-literals-early-errors+ // EscapeSequence :: LegacyOctalEscapeSequence+ // EscapeSequence :: NonOctalDecimalEscapeSequence+ // It is a Syntax Error if IsStrict(this production) is true.+ // NOTE: It is possible for string literals to precede a Use Strict Directive that places the enclosing code in strict mode, and implementations must take care to enforce the above rules for such literals.+ if prologue.legacy_escape != NONE {+ self.fail(+ prologue.legacy_escape,+ "Octal escape sequence in string literal not allowed in strict mode",+ );+ }+ }+ (statement, is_use_strict)+ }+/// A method's function, from the `(`. Returns its node, its parameter count and whether it has a rest parameter.pub(crate) fn parse_method(&mut self,diff --git a/Tests/LibJS/Runtime/use-strict-directive.js b/Tests/LibJS/Runtime/use-strict-directive.jsnew file mode 100644index 00000000000..12f3f7a3824--- /dev/null+++ b/Tests/LibJS/Runtime/use-strict-directive.js@@ -0,0 +1,68 @@+function isStrictFunction(body) {+ return new Function("info", "instanceofs", `${body}\n;return this === undefined;`)();+}++function isStrictScript(source) {+ return (0, eval)(`${source}\n;(function () { return this === undefined; })();`);+}++test("a use strict directive that ends where a statement starts on the next line", () => {+ expect(isStrictFunction('"use strict"\n++globalThis.n')).toBeTrue();+ expect(isStrictFunction('"use strict"\n--globalThis.n')).toBeTrue();+ expect(isStrictFunction('"use strict"\n.5.toFixed()')).toBeTrue();+ expect(isStrictFunction('"use strict"\ninfo')).toBeTrue();+ expect(isStrictFunction('"use strict"\ninstanceofs')).toBeTrue();+ expect(isStrictScript('"use strict"\n++globalThis.n')).toBeTrue();+});++test("a string that an operator on the next line continues is no directive", () => {+ expect(isStrictFunction('"use strict"\nin {}')).toBeFalse();+ expect(isStrictFunction('"use strict"\ninstanceof Object')).toBeFalse();+ expect(isStrictFunction('"use strict"\n+ 1')).toBeFalse();+ expect(isStrictFunction('"use strict"\n- 1')).toBeFalse();+ expect(isStrictFunction('"use strict"\n.length')).toBeFalse();+ expect(isStrictFunction('"use strict"\n!= 1')).toBeFalse();+ expect(isStrictScript('"use strict"\nin {}')).toBeFalse();+ expect(isStrictFunction('"use strict"\nin {}; with ({}) {}')).toBeFalse();+});++test("HTML-like comments around a use strict directive", () => {+ expect(isStrictFunction('"use strict"\n<!-- comment')).toBeTrue();+ expect(isStrictFunction('"use strict"\n--> comment')).toBeTrue();+ expect(isStrictFunction('"use strict" <!-- comment')).toBeTrue();+ expect(isStrictFunction('\n<!-- comment\n"use strict";')).toBeTrue();+ expect(isStrictFunction('\n--> comment\n"use strict";')).toBeTrue();+ expect(isStrictScript('<!-- comment\n"use strict";')).toBeTrue();+ expect(isStrictScript('--> comment\n"use strict";')).toBeTrue();+});++test("a use strict directive after a directive with a line continuation", () => {+ expect(isStrictFunction('"a\\\r\nb"; "use strict";')).toBeTrue();+ expect(isStrictFunction('"a\\\nb"; "use strict";')).toBeTrue();+ expect(isStrictFunction('"a\\\rb"; "use strict";')).toBeTrue();+});++test("a use strict directive applies to what the function has before it", () => {+ expect('function f(eval) { "use strict"; }').not.toEval();+ expect('function f(arguments) { "use strict"; }').not.toEval();+ expect('function f(a, a) { "use strict"; }').not.toEval();+ expect('function f(yield) { "use strict"; }').not.toEval();+ expect('function eval() { "use strict"; }').not.toEval();+ expect('(function arguments() { "use strict"; })').not.toEval();+ expect('(eval) => { "use strict"; }').not.toEval();+ expect('function f(a = 1) { "use strict"; }').not.toEval();+ expect('function f(eval) { "a"; "use strict"; }').not.toEval();+ expect('function f(eval) { "use\\x20strict"; }').toEval();+ expect('function f(eval) { "a".length; "use strict"; }').toEval();+});++test("a use strict directive applies to the directives before it", () => {+ expect('function f() { "\\01"; "use strict"; }').not.toEval();+ expect('function f() { "\\8"; "use strict"; }').not.toEval();+ expect('function f() { "a"; "\\01"; "b"; "use strict"; }').not.toEval();+ expect('"\\01"; "use strict";').not.toEval();+ expect('function f() { "use strict"; "\\01"; }').not.toEval();+ expect('function f() { "\\01"; }').toEval();+ expect('function f() { "\\0"; "use strict"; }').toEval();+ expect('"\\01"; "use\\x20strict";').toEval();+});