Count Zero
Count Zero

Reputation: 545

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?

Upvotes: 2

Views: 240

Answers (1)

napuzba
napuzba

Reputation: 6298

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.

Upvotes: 4

Related Questions