42 lines
1.5 KiB
Markdown
42 lines
1.5 KiB
Markdown
---
|
|
date: 2025-07-22 17:00
|
|
---
|
|
#programming-language
|
|
|
|
一般的なコードフォーマッターの実装について。
|
|
|
|
[How to write a code formatter](https://yorickpeterse.com/articles/how-to-write-a-code-formatter/)
|
|
|
|
1行当たり最大文字数がこのくらい、としたときに、どういう戦略で折り返すかは結構難しい問題。
|
|
|
|
文字列→トークン→ASTという順番で変換されるので、この逆順が良いのかとも思ったが、
|
|
|
|
AST→フォーマッタ用の専用の木構造みたいな中間表現を一度挟んだほうが賢いのかもしれない
|
|
|
|
[[Rust]]の[pretty](https://docs.rs/pretty/latest/pretty/)クレートがコンビネーターとして定義してあるやつ
|
|
|
|
[[Tree-sitter]]を使った汎用フォーマッター[Topiary](https://topiary.tweag.io/)とかいうのもある
|
|
|
|
---
|
|
|
|
Exprの途中に差し込まれたトリビア(主にコメント)をどうやって抽出するか
|
|
|
|
ExprNodeIdに対するSecondary MapがSpanに対して作れているのだから、Trailng Triviaとしてコメントを保持するのは一応できるか?
|
|
|
|
パーサコンビネータでどうにか処理できるもんか?
|
|
|
|
```rust
|
|
fn parse_expr_top<Output>()->impl Parser<Token,Output,Error>{
|
|
not(comment()).padded_by(comment().repeated())
|
|
}
|
|
|
|
```
|
|
|
|
[Parser in chumsky - Rust](https://docs.rs/chumsky/latest/chumsky/trait.Parser.html#method.map_with)
|
|
|
|
`map_with`使えばいけるかしら
|
|
|
|
Stateにトリビアを書き込んでおけばいいのか
|
|
|
|
|