💬
【bugs.ruby Advent Calender 2025】よりシンプルなエラーメッセージを出力できるようにするチケット【16日目】
bugs.ruby Advent Calender 2025 16日目の記事です。
これはなに
今年1年間通してみてきた bugs.ruby のチケットの中から気になったものを1つずつ取り上げていく Advent Calender です。
取り上げるチケットは基本的にこのブログで取り上げたものになります。
記事のまとめは ここを参照 してください。
[Feature #21573] Simpler syntax errors
現状はシンタックスエラーが発生した場合に発生原因などを特定できるようにするためにエラーメッセージにコンテキスト情報がいろいろと追加されて出力されます。
1 +x 2 do
do
__END__
output:
test.rb: --> test.rb
Unmatched keyword, missing `end' ?
> 1 1 +x 2 do
> 2 do
test.rb:1: syntax errors found (SyntaxError)
> 1 | 1 +x 2 do
| ^ unexpected integer, expecting end-of-input
| ^~ unexpected 'do', ignoring it
| ^~ unexpected 'do', expecting end-of-input
> 2 | do
| ^~ unexpected 'do', ignoring it
これは人間が見る場合はわかりやすいのですが機械的にエラー内容を解析したい場合にはやや不向きです。
そこで 環境変数 SIMPLE_ERRORS=1 が有効な場合に以下のようなシンプルなエラーメッセージで出力できるようにしたいという提案になります。
1 +x 2 do
do
__END__
output:
./miniruby: -:1: syntax errors found (SyntaxError)
-:1: unexpected integer, expecting end-of-input
-:1: unexpected 'do', expecting end-of-input
-:1: unexpected 'do', ignoring it
-:2: unexpected 'do', ignoring it
モチベーションとしては外部ツールを利用してエラーメッセージから情報を抜き取りたい場合に現状だとパースするのが難しいのでよりシンプルに扱いたい、みたいなところですね。
実際にエディタとかでエラーメッセージをパースしてそこからエラー箇所をハイライトするとかはよくあるのでそういうことをしたい場合だと提案されている内容のほうが扱いやすいですねえ。
ちなみに Prism を利用すれば以下のように Ruby のコードからエラー内容を取得することができたりします。
source = <<~EOS
1 +x 2 do
do
EOS
require "prism"
pp Prism.parse(source).errors
# => [#<Prism::ParseError @type=:expect_eol_after_statement @message="unexpected integer, expecting end-of-input" @location=#<Prism::Location @start_offset=5 @length=1 start_line=1> @level=:syntax>,
# #<Prism::ParseError @type=:expect_eol_after_statement @message="unexpected 'do', expecting end-of-input" @location=#<Prism::Location @start_offset=7 @length=2 start_line=1> @level=:syntax>,
# #<Prism::ParseError @type=:unexpected_token_ignore @message="unexpected 'do', ignoring it" @location=#<Prism::Location @start_offset=7 @length=2 start_line=1> @level=:syntax>,
# #<Prism::ParseError @type=:unexpected_token_ignore @message="unexpected 'do', ignoring it" @location=#<Prism::Location @start_offset=10 @length=2 start_line=2> @level=:syntax>]
これはこれでいろいろと捗りそうですね。
Discussion