Permalink
Browse files

+ alternatives

  • Loading branch information...
1 parent 5f275ec commit f9c698d5ee28d770eb62873c60a23bed2bf20f3c @kschiess committed Nov 25, 2010
Showing with 12 additions and 25 deletions.
  1. +1 −1 lib/parslet/expression.rb
  2. +7 −9 lib/parslet/expression/treetop.rb
  3. +4 −15 spec/unit/parslet/expression_spec.rb
@@ -22,7 +22,7 @@ def initialize(str, opts={})
def transform(tree)
transform = Treetop::Transform.new
- pp tree
+ # pp tree
transform.apply(tree)
end
@@ -2,18 +2,15 @@ class Parslet::Expression::Treetop
class Parser < Parslet::Parser
root(:expression)
- rule(:expression) {
- alternatives
- }
+ rule(:expression) { alternatives }
+ # alternative 'a' / 'b'
rule(:alternatives) {
- simple >> (spaced('/') >> alternatives) |
- simple
+ (simple >> (spaced('/') >> simple).repeat).as(:alt)
}
- rule(:simple) {
- perhaps.repeat
- }
+ # sequence by simple concatenation 'a' 'b'
+ rule(:simple) { perhaps.repeat(1).as(:seq) }
rule(:perhaps) {
atom.as(:maybe) >> spaced('?') |
@@ -43,8 +40,9 @@ def spaced(str)
end
class Transform < Parser::Transform
+ rule(:alt => subtree(:alt)) { Parslet::Atoms::Alternative.new(*alt) }
+ rule(:seq => sequence(:s)) { Parslet::Atoms::Sequence.new(*s) }
rule(:unwrap => simple(:u)) { u }
- rule(sequence(:s)) { |d| Parslet::Atoms::Sequence.new(*d[:s]) }
rule(:maybe => simple(:m)) { |d| d[:m].maybe }
rule(:string => simple(:s)) { |d| str(d[:s]) }
end
@@ -5,19 +5,6 @@
describe Parslet::Expression do
include Parslet
- examples = <<-EXPRESSION_EXAMPLES
- 'a'
- EXPRESSION_EXAMPLES
-
- examples.lines.each do |example|
- example = example.strip.chomp
- context "[#{example}]" do
- it "should parse without exception" do
- exp = Parslet::Expression.new(example)
- end
- end
- end
-
RSpec::Matchers.define :accept do |string|
match do |parslet|
begin
@@ -41,8 +28,8 @@
"'a' 'b'", 'ab',
"'a' ('b')", 'ab',
- # "'a' / 'b'", 'a',
- # "'a' / 'b'", 'b',
+ "'a' / 'b'", 'a',
+ "'a' / 'b'", 'b',
].each_slice(2) do |pattern, input|
context "exp(#{pattern.inspect})" do
subject { exp(pattern) }
@@ -52,6 +39,8 @@
[ # pattern # input
"'abc'", 'cba',
+
+ "'a' / 'b'", 'c',
].each_slice(2) do |pattern, input|
context "exp(#{pattern.inspect})" do
subject { exp(pattern) }

0 comments on commit f9c698d

Please sign in to comment.