parsing - Python grammar end "return outside function" -


i've noticed python grammar allows return statement appear outside function, don't understand, why? believe 1 can specify grammar so, wouldn't allowed.

this piece of python grammar 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 interpreter reports syntax error ('return' outside function), how can parser detect it, if isn't specified in grammar?

first, interrupter builds ast tree. then, when generates code basic blocks visiting ast tree, verifies return statement inside 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 can see, semantics of language not defined grammar.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -