Skip to content

Commit

Permalink
Now ignorable. Needs refactor to extract the logic out to an applicative
Browse files Browse the repository at this point in the history
TODO: #2
  • Loading branch information
pawandubey committed Nov 9, 2017
1 parent 00b4555 commit 8b731e2
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 1 deletion.
17 changes: 17 additions & 0 deletions spec/ast_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,21 @@ describe Pegasus::ParseTree do
res = parser.parse("abcdef")
res.parse_tree.dump.should eq(expected_parse_tree.dump)
end

it "ignores ignored nodes while still matching" do
parser = Pegasus::Parser.define do |p|
p.rule(:def) { |p| p.str("def") }
p.rule(:abcdef) { |p| p.rule(:abc).aka(:a2c) >> p.rule(:def).ignore }
p.rule(:abc) { |p| p.str("abc") }

p.root(:abcdef)
end

expected_parse_tree = Pegasus::Branch(String).new(:seq).tap do |tree|
tree << Pegasus::Leaf.new(:a2c, "abc")
end

res = parser.parse("abcdef")
res.parse_tree.dump.should eq(expected_parse_tree.dump)
end
end
12 changes: 12 additions & 0 deletions src/pegasus/ast.cr
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ module Pegasus
to_json
end

def prune
self
end

JSON.mapping(
label: Symbol,
item: T
Expand Down Expand Up @@ -46,6 +50,14 @@ module Pegasus
to_json
end

def prune
Branch(T).new(@label).tap do |branch|
@children.each do |child|
branch << child if child.label != :ignore
end
end
end

JSON.mapping(
label: Symbol,
children: Array(Branch(T) | Leaf(T))
Expand Down
6 changes: 5 additions & 1 deletion src/pegasus/extensions/ignored.cr
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ module Pegasus
old_context = context.dup
match, _ = @rule.match?(context)

{match, old_context}
if match.success?
{MatchResult.success(Leaf.new(@label, match.parse_tree.value)), old_context}
else
{MatchResult.failure(Leaf.new(@label, match.parse_tree.value)), old_context}
end
end

def flatten
Expand Down
1 change: 1 addition & 0 deletions src/pegasus/match_result.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module Pegasus
getter :parse_tree

def initialize(@result : Bool, @parse_tree : Pegasus::ParseTree)
@parse_tree = parse_tree.prune
end

def self.success(tree : Pegasus::ParseTree)
Expand Down

0 comments on commit 8b731e2

Please sign in to comment.