Skip to content

Instantly share code, notes, and snippets.

@JacobNinja
Created July 9, 2014 21:45
Show Gist options
  • Save JacobNinja/b90fde12da3ba759d304 to your computer and use it in GitHub Desktop.
Save JacobNinja/b90fde12da3ba759d304 to your computer and use it in GitHub Desktop.
Source tree substitution examples
# Example 1: Swap the consequence and else statements in an if expression
if_node = CodeMiner.parse(<<-RUBY).each.first
if foo
begin
do_something
end
else
do_something_else
end
RUBY
swap_consequence_with_else = CodeMiner::Substitution::Value.new(if_node.consequence, if_node.else_statement.body.src)
swap_else_with_consequence = CodeMiner::Substitution::Value.new(if_node.else_statement.body, if_node.consequence.src)
puts CodeMiner::Substitution.new(if_node).substitute(swap_consequence_with_else, swap_else_with_consequence)
=begin output
if foo
do_something_else
else
begin
do_something
end
end
=end
# Example 2: Convert a transformation that mutates an external array into a call to map
iter_node = CodeMiner.parse(<<-RUBY).each.first
foo.each do |i|
array << process(i)
end
RUBY
array_mutation = iter_node.block.body.each.first
each_to_map = CodeMiner::Substitution::Value.new(iter_node.token, 'map')
unwrap_transformation = CodeMiner::Substitution::Value.new(array_mutation, array_mutation.body.src)
puts CodeMiner::Substitution.new(iter_node).substitute(each_to_map, unwrap_transformation)
=begin output
foo.map do |i|
process(i)
end
=end
# Example 3: Convert a filter that mutates an external array into a call to select
iter_node = CodeMiner.parse(<<-RUBY).each.first
foo.each do |i|
if i % 2 == 0
array << i
end
end
RUBY
if_node = iter_node.block.body.each.first
array_mutation = if_node.consequence.body.each.first
each_to_select = CodeMiner::Substitution::Value.new(iter_node.token, 'select')
unwrap_conditional_test = CodeMiner::Substitution::Value.new(if_node, if_node.test.src)
puts CodeMiner::Substitution.new(iter_node).substitute(each_to_select, unwrap_conditional_test)
=begin output
foo.select do |i|
i % 2 == 0
end
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment