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
分支
36k
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 摘要。