简体   繁体   English

Python语法结尾“返回外部函数”

[英]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? 我注意到Python语法允许return语句出现在函数外部,但我真的不明白,为什么? I believe that one can specify grammar so, that this wouldn't be allowed. 我相信可以这样指定语法,因此不允许这样做。

This is a piece of Python grammar which allows this: 这是一段Python语法,它允许这样做:

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. 首先,中断器构建AST树。 Then, When it generates code for basic blocks by visiting the AST tree, It verifies that the return statement is inside a function. 然后,当它通过访问AST树为基本块生成代码时,它会验证return语句在函数内部。

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. 如您所见,语言的语义不仅仅由语法定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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