python / python/cpython

Add to AST location info for compound exception headers or keywords

未關閉
#129,157 3 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

interpreter-core topic-parser type-feature
主要語言
Python
星號
77.2k
分支
35.9k
PR 合併指標
PR 指標待擷取

描述

The location information in the AST for a compound statement spans the whole body.

For example:

>>> src = """with A as cm:
...     1
...     2
...     3
...     """

Output:

"Module(body=[With(items=[withitem(context_expr=Name(id='A', ctx=Load(), lineno=1, col_offset=5, end_lineno=1, end_col_offset=6), optional_vars=Name(id='cm', ctx=Store(), lineno=1, col_offset=10, end_lineno=1, end_col_offset=12))], body=[Expr(value=Constant(value=1, lineno=2, col_offset=4, end_lineno=2, end_col_offset=5), lineno=2, col_offset=4, end_lineno=2, end_col_offset=5), Expr(value=Constant(value=2, lineno=3, col_offset=4, end_lineno=3, end_col_offset=5), lineno=3, col_offset=4, end_lineno=3, end_col_offset=5), Expr(value=Constant(value=3, lineno=4, col_offset=4, end_lineno=4, end_col_offset=5), lineno=4, col_offset=4, end_lineno=4, end_col_offset=5)], lineno=1, col_offset=0, end_lineno=4, end_col_offset=5)])"

If __enter__ or __exit__ of the context manager raises an exception, we don't want the location of the exception to span the entire body. Ideally it would be the location of the with keyword (my view) or the entire with x as y statement (@ericsnowcurrently's view). However, we don't have those locations in the AST so currently we hilight the location of the expression that creates the context manager:

>>> class C:
...     def __enter__(self): 1/0
...     def __exit__(*args): pass
...     
>>> with C() as c: pass
... 
Traceback (most recent call last):
  File "<python-input-11>", line 1, in <module>
    with C() as c: pass
         ~^^
  File "<python-input-10>", line 2, in __enter__
    def __enter__(self): 1/0
                         ~^~
ZeroDivisionError: division by zero

We have similar issue with except blocks and class definitions.

Can we add location information of the keywords, or of the header of a compound expression, to the AST?

@pablogsal @lysnikolaou

Linked PRs
  • gh-129162

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

未指定原始碼檔案或測試。先檢視此處及連結的 PR gh-129162 中所描述的 AST 位置行為,接著比較相關的 except 區塊與類別定義 issue。當複合陳述式的標頭或關鍵字具有可用的 AST 位置,且不會將內容管理器例外歸因於整個主體時,即表示完成。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
compilers
Issue 類型
功能
難度
5/5
預估耗時
一週以上
活躍度
停滯
描述清晰度
需要釐清
新手友好度
25/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。