Skip to content

正規表現エンジンが入れ子のStarでスタックオーバーフローする問題を回避#4

Merged
ytakano merged 1 commit into
ytakano:masterfrom
y-yu:avoid-stack-overflow-star
Dec 25, 2022
Merged

正規表現エンジンが入れ子のStarでスタックオーバーフローする問題を回避#4
ytakano merged 1 commit into
ytakano:masterfrom
y-yu:avoid-stack-overflow-star

Conversation

@y-yu
Copy link
Copy Markdown
Contributor

@y-yu y-yu commented Dec 24, 2022

「ゼロから学ぶRust」を楽しく読ませていただいています。
Rustの問題なのか(本の本質と関係あるか)どうか微妙なところですが、以前、Russ CoxのVM正規表現を自分も実装したことがあり、そのままだと入れ子になったスターを持つ(a*)*のような正規表現でスタックオーバーフローが生じてしまいます。
元の正規表現と等しいことをパッと証明はできませんし、これでどうして治るのかもよく分かってませんが、とりあえず(r*)*となっているところを再帰的にr*へ変換すれば大丈夫だと思いこのような修正を提案します。

これまで

$ cargo run "(a*)*" Cargo.toml
expr: (a*)*
AST: Seq([Star(Seq([Star(Char('a'))]))])

code:
0000: split 0001, 0005
0001: split 0002, 0004
0002: char a
0003: jump 0001
0004: jump 0000
0005: match


thread 'main' has overflowed its stack
fatal runtime error: stack overflow
zsh: abort      cargo run "(a*)*" Cargo.toml

修正後

$ cargo run "(a*)*" Cargo.toml
expr: (a*)*
AST: Seq([Star(Seq([Star(Char('a'))]))])

code:
0000: char a
0001: match

[package]
name = "regex"
authors = ["Yuuki Takano <ytakanoster@gmail.com>"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
name = "benchmark"
harness = false

@ytakano ytakano merged commit 8ec8794 into ytakano:master Dec 25, 2022
@ytakano
Copy link
Copy Markdown
Owner

ytakano commented Dec 25, 2022

ありがとうございます!
このような問題があるのは初めて知りました。助かります。

@y-yu y-yu deleted the avoid-stack-overflow-star branch December 25, 2022 07:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants