ã¯ããã«
ä¹
ç³å¥ããããèªçæ¥ããã§ã¨ããããã¾ãããããã®ã½ãªã¹ããè¸ãæã¤...ð
nikkieã§ãã
Rustã§Pythonã®ASTãæ±ããå°ããªå°ããªä¸æ©ã®ç´ æ¯ãããã¾ããã
ç®æ¬¡
- ã¯ããã«
- ç®æ¬¡
- Pythonã§ASTãdumpãã
- rustpython-parser crate
- Ruffã®ãªãã¸ããªã«è¦ã¤ããprint-ast
- ãRustã®ç·´ç¿å¸³ãã§è¦ãã¨ããã ï¼
- rustpython-parserã«ããASTãpretty-print
- çµããã«
Pythonã§ASTãdumpãã
æ¨æºã©ã¤ãã©ãªastã使ãã¾ãã
https://docs.python.org/ja/3/library/ast.html#command-line-usage
% python -m ast <<"EOF"
if True:
pass # comment
EOF
Module(
body=[
If(
test=Constant(value=True),
body=[
Pass()],
orelse=[])],
type_ignores=[])
rustpython-parser crate
https://crates.io/crates/rustpython-parser
å¶ç¶ç¥ãã¾ããã
ã½ã¼ã¹ã³ã¼ããããã®ã¯ãRustPython/Parserã¨ãããªãã¸ããª
The parser is one of the core part of RustPython and Ruff project.
Ruffã§ã使ããã¦ããï¼ä½¿ããã¦ããï¼1ï¼ããã§ã
Ruffã®ãªãã¸ããªã«è¦ã¤ããprint-ast
Contributingã®ãã¼ã¸ã®ãcargo devãã®é
ç®ã
https://docs.astral.sh/ruff/contributing/#cargo-dev
cargo dev print-ast <file>ãç´¹ä»ããã¦ãã¾ãã
ãããè¦ã¦ãrustpython-parserã使ã£ã¦ãprint-astç¸å½ã®ãã¨ãã§ããã®ã§ã¯ãªããã¨æãã¤ãã¾ããã
crates.ioã®ãHow to useãã®ã³ã¼ãã§Vecãè¿ã£ã¦ãã¾ãã
ãããprint-astã®ããã«è¡¨ç¤ºãã¦ã¿ãããªã£ãã®ã§ãã
ãã¯ãããã«ãprint-astã®å®è£
ã確èªãã¾ãã
https://github.com/astral-sh/ruff/blob/0.8.6/crates/ruff_dev/src/print_ast.rs
println!("{python_ast:#?}");
ãRustã®ç·´ç¿å¸³ãã§è¦ãã¨ããã ï¼
{:#?}ãè¦ã¦ãRustã®ç·´ç¿å¸³ããæãåºãã¾ãã2ã
{:?}ã使ããã¨ã§ãæ§é ä½ããããã°ç¨ã®å½¢å¼ï¼ãªã³ã¯çç¥ï¼ã§è¡¨ç¤ºã§ãã¾ããï¼2.2.1ï¼ä»åã¯
{:#?}ã使ã£ã¦ãæ¹è¡ã¨ã¤ã³ãã³ããå ¥ãã¦åºåãèªã¿ããããã¦ãã¾ããããã¯ãæ´å½¢è¡¨ç¤ºï¼pretty-printingï¼ã¨å¼ã°ãã¦ãã¾ããï¼2.2.3ï¼
Ruffã®print-astã§ãã£ã¦ããã®ã¯ãæ´å½¢è¡¨ç¤ºï¼pretty-printï¼ï¼
ãã®æ©ã«ããã¥ã¡ã³ãã確èª
?formatting.When used with the alternate format specifier
#?, the output is pretty-printed.
rustpython-parserã«ããASTãpretty-print
% cargo init hello-ast % cd hello-ast % cargo add rustpython-parser
ã¤ã³ã¹ãã¼ã«ãããrustpython-parserã¯0.4.0ã§ãã
% cargo run -q
[
If(
StmtIf {
range: 0..13,
test: Constant(
ExprConstant {
range: 3..7,
value: Bool(
true,
),
kind: None,
},
),
body: [
Pass(
StmtPass {
range: 9..13,
},
),
],
orelse: [],
},
),
]
ã§ããï¼ï¼
Ruffã®ããã¥ã¡ã³ãã®print-astã®åºåä¾ã¨ä¸è´ããããã«æããã¾ãã
ï¼ãªãããã¡ã¤ã«ããã®èªã¿è¾¼ã¿ã¯å¾åãã«ãã¦ãã¾ãï¼
çµããã«
ããããçãPythonã³ã¼ãçãrustpython-parserã§ASTã«å¤æãããããpretty-printãã¾ããã
Pythonã®astã¢ã¸ã¥ã¼ã«ã¨æ¯ã¹ãã¨ãã§ããããASTã¯å
¨ç¶éãã®ã§ããã
ä¾ãã°Ruffã¯ãããªASTãæ±ã£ã¦ããã®ãã
- https://github.com/astral-sh/ruff ãæ¤ç´¢ããã¨ãããç¾å¨ã¯Cargo.tomlã«ä¾åã®è¨è¼ã¯ãªãããã§ãããRuffã®ãªãã¸ããªå ã«ãparserã®crateãããã¾ã↩
- åãçµãã ãã¨ãããã¾ã ↩