[njs] Restricted function declaration to top level or inside a block.

Dmitry Volyntsev xeioex at nginx.com
Mon Apr 22 13:28:07 UTC 2019


details:   https://hg.nginx.org/njs/rev/3869b6e1f296
branches:  
changeset: 915:3869b6e1f296
user:      hongzhidao <hongzhidao at gmail.com>
date:      Sun Apr 21 17:36:25 2019 +0800
description:
Restricted function declaration to top level or inside a block.

diffstat:

 njs/njs_parser.c         |   6 ++++++
 njs/test/njs_unit_test.c |  21 +++++++++++++++++++++
 2 files changed, 27 insertions(+), 0 deletions(-)

diffs (47 lines):

diff -r 4883fe429836 -r 3869b6e1f296 njs/njs_parser.c
--- a/njs/njs_parser.c	Sun Apr 21 17:33:31 2019 +0800
+++ b/njs/njs_parser.c	Sun Apr 21 17:36:25 2019 +0800
@@ -492,6 +492,12 @@ njs_parser_block(njs_vm_t *vm, njs_parse
 {
     njs_parser_node_t  *node;
 
+    if (token == NJS_TOKEN_FUNCTION) {
+        njs_parser_syntax_error(vm, parser,
+              "Functions can only be declared at top level or inside a block");
+        return NJS_TOKEN_ILLEGAL;
+    }
+
     token = njs_parser_statement(vm, parser, token);
     if (nxt_slow_path(token <= NJS_TOKEN_ILLEGAL)) {
         return token;
diff -r 4883fe429836 -r 3869b6e1f296 njs/test/njs_unit_test.c
--- a/njs/test/njs_unit_test.c	Sun Apr 21 17:33:31 2019 +0800
+++ b/njs/test/njs_unit_test.c	Sun Apr 21 17:36:25 2019 +0800
@@ -5725,6 +5725,27 @@ static njs_unit_test_t  njs_test[] =
     { nxt_string("\n{\nreturn;\n}"),
       nxt_string("SyntaxError: Illegal return statement in 3") },
 
+    { nxt_string("if (1) function f(){}"),
+      nxt_string("SyntaxError: Functions can only be declared at top level or inside a block in 1") },
+
+    { nxt_string("if (1) { function f(){}}"),
+      nxt_string("undefined") },
+
+    { nxt_string("while (1) function f() { }"),
+      nxt_string("SyntaxError: Functions can only be declared at top level or inside a block in 1") },
+
+    { nxt_string("while (1) { break; function f(){}}"),
+      nxt_string("undefined") },
+
+    { nxt_string("for (;;) function f() { }"),
+      nxt_string("SyntaxError: Functions can only be declared at top level or inside a block in 1") },
+
+    { nxt_string("for (;;) { break; function f(){}}"),
+      nxt_string("undefined") },
+
+    { nxt_string("do function f() { } while (0)"),
+      nxt_string("SyntaxError: Functions can only be declared at top level or inside a block in 1") },
+
     { nxt_string("function f() { return f() } f()"),
       nxt_string("RangeError: Maximum call stack size exceeded") },
 


More information about the nginx-devel mailing list