lib/parslet/transform.rb in parslet-0.11.0 vs lib/parslet/transform.rb in parslet-1.0.0
- old
+ new
@@ -44,14 +44,17 @@
#
# If you now apply this to a string like '(())', you get a intermediate parse
# tree that looks like this:
#
# {
-# :l => "(",
-# :m => {
-# :l=>"(", :m=>nil, :r=>")" },
-# :r => ")"
+# l: '(',
+# m: {
+# l: '(',
+# m: nil,
+# r: ')'
+# },
+# r: ')'
# }
#
# This parse tree is good for debugging, but what we would really like to have
# is just the nesting depth. This transformation rule will produce that:
#
@@ -98,30 +101,40 @@
@__transform_rules << [Parslet::Pattern.new(expression), block]
end
# Allows accessing the class' rules
#
- def rules
+ def rules # :nodoc:
@__transform_rules || []
end
end
- def initialize(&block)
+ def initialize(&block) # :nodoc:
@rules = []
if block
instance_eval(&block)
end
end
+ # Defines a rule to be applied whenever apply is called on a tree. A rule
+ # is composed of two parts:
+ #
+ # * an *expression pattern*
+ # * a *transformation block*
+ #
def rule(expression, &block)
@rules << [
Parslet::Pattern.new(expression),
block
]
end
+ # Applies the transformation to a tree that is generated by Parslet::Parser
+ # or a simple parslet. Transformation will proceed down the tree, replacing
+ # parts/all of it with new objects. The resulting object will be returned.
+ #
def apply(obj)
transform_elt(
case obj
when Hash
recurse_hash(obj)
@@ -134,30 +147,30 @@
end
# Allow easy access to all rules, the ones defined in the instance and the
# ones predefined in a subclass definition.
#
- def rules
+ def rules # :nodoc:
self.class.rules + @rules
end
- def transform_elt(elt)
+ def transform_elt(elt) # :nodoc:
rules.each do |pattern, block|
if bindings=pattern.match(elt)
# Produces transformed value
- return pattern.call_on_match(elt, bindings, block)
+ return pattern.call_on_match(bindings, block)
end
end
# No rule matched - element is not transformed
return elt
end
- def recurse_hash(hsh)
+ def recurse_hash(hsh) # :nodoc:
hsh.inject({}) do |new_hsh, (k,v)|
new_hsh[k] = apply(v)
new_hsh
end
end
- def recurse_array(ary)
+ def recurse_array(ary) # :nodoc:
ary.map { |elt| apply(elt) }
end
end
\ No newline at end of file