-
-
Save franckverrot/4291939 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| require "./tinyparse" | |
| parser = Tinyparse.build do | |
| paren "(", :main, ")", :main | |
| main [:paren, ""] | |
| end | |
| ["((()))", "(((", "()()((()()))", "))(("].each do |str| | |
| puts str | |
| if parser =~ str | |
| puts " \e[32;1mis valid\e[0m" | |
| else | |
| puts " \e[31;1mis invalid\e[0m" | |
| end | |
| end |
This file contains hidden or 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
| class Tinyparse | |
| def self.build(&bk) | |
| new.tap { |t| t.instance_eval(&bk) }.to_regexp | |
| end | |
| attr_reader :rules | |
| def initialize | |
| @rules = {} | |
| end | |
| def to_regexp | |
| Regexp.new("\\A" << @rules.map { |name,re| "(?<#{name}>#{re}){0}" }.join << "\\g<main>\\z") | |
| end | |
| def method_missing(rule, *args) | |
| compile = ->x { | |
| case x | |
| when Regexp | |
| Regexp.union(//, x).source["(?-mix:)|".length..-1] | |
| when String | |
| Regexp.escape(x) | |
| when Symbol | |
| "\\g<#{x}>" | |
| when Array | |
| "(#{x.map(&compile).join("|")})" | |
| end | |
| } | |
| @rules[rule] = args.map(&compile).join | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment