Last active
May 15, 2016 07:57
-
-
Save yshl/7c17bc3a20d15ba14b743770810398b0 to your computer and use it in GitHub Desktop.
パーサーの練習
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
require 'parslet' | |
class AAAParser < Parslet::Parser | |
root :all | |
rule(:all){ | |
# 全体は line の 0 回以上の繰り返しの後に | |
line.repeat >> | |
# statement があるかもしれない | |
statement.maybe | |
} | |
rule(:line){ | |
# line は statement の後に newline を付けたもの | |
statement >> newline | |
} | |
rule(:statement){ | |
# statement は文字 a の 0 回以上の繰り返し | |
str('a').repeat | |
} | |
rule(:newline){ | |
# newline は文字 "\n" | |
str("\n") | |
} | |
end | |
ap=AAAParser.new | |
p ap.parse("aaaaa\naaa\n") # OK | |
begin | |
ap.parse("aabaa\n") # エラー | |
rescue Parslet::ParseFailed => e | |
puts e.message | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment