简体   繁体   中英

Python grammar end “return outside function”

I've noticed that Python grammar allows return statement appear outside function, but I really don't understand, why? I believe that one can specify grammar so, that this wouldn't be allowed.

This is a piece of Python grammar which allows this:

single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
             import_stmt | global_stmt | nonlocal_stmt | assert_stmt)
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
return_stmt: 'return' [testlist]

Also the interpreter reports this as syntax error ('return' outside function), but how can parser detect it, if this isn't specified in the grammar?

First, the interrupter builds the AST tree. Then, When it generates code for basic blocks by visiting the AST tree, It verifies that the return statement is inside a function.

compiler_visit_stmt(struct compiler *c, stmt_ty s)
    ...
    switch (s->kind) {
        ...
        case Return_kind:
            if (c->u->u_ste->ste_type != FunctionBlock)
                return compiler_error(c, "'return' outside function");

As you can see, the semantics of the language is not defined only by its grammar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM