python / python/cpython

Specialized syntax error messages are not produced in all positions where the invalid construct can occur

未关闭
#153,171 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

interpreter-core type-feature
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Feature or enhancement

Several rules for generating specialized syntax error messages are attached to a grammar rule in which the invalid construct can only occur at some of its possible positions. When the same construct occurs at a deeper position, the parser falls back to a generic SyntaxError: invalid syntax.

invalid_factor catches a unary operator followed by not. It is an alternative of term, so it is only tried where a term starts. But its construct occurs wherever a factor is expected -- also as the right operand of *, /, %, //, @ and **:

>>> + not x
SyntaxError: 'not' after an operator must be parenthesized
>>> 1 * + not x
SyntaxError: invalid syntax
>>> 2 ** + not x
SyntaxError: invalid syntax

invalid_arithmetic catches a binary arithmetic operator followed by not. It is an alternative of shift_expr, so it misses the construct in the right operand of << and >> (a sum position):

>>> 1 + not x
SyntaxError: 'not' after an operator must be parenthesized
>>> 1 << 2 + not x
SyntaxError: invalid syntax

The fix is to attach each error rule to the rule matched at all positions where its construct can occur:

  • move invalid_factor from term to factor;
  • move invalid_arithmetic from shift_expr to sum.

After this change all the examples above produce the specialized error messages, and all previously produced messages are unchanged.

The placement of invalid_factor and invalid_arithmetic dates from their introduction in bpo-24612 (GH-28170), which attached both symmetrically to the rule containing the binary operators, one level above the operand rule where the construct can actually occur.

There are a few related gaps which require modifying the error rules themselves rather than moving them (1 << not x, lambda x=: 0, def f[T=]: pass, x = 1 + *y); they are left for separate issues.

Linked PRs
  • gh-153175
  • gh-153193

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 issue 中指定的语法规则开始:invalid_factor、invalid_arithmetic、term、factor、shift_expr 和 sum。将每条错误规则移动到指定的操作数规则中,然后检查列出的交互式示例,以确认专用消息会出现,并且现有消息保持不变。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
compilers
Issue 类型
缺陷
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
描述清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。