Class: Refax

Inherits:
Object
  • Object
show all
Defined in:
lib/fixloops.rb

Instance Method Summary collapse

Instance Method Details

#couldPossiblyRefactor?(p, ind) ⇒ Boolean

Returns:

  • (Boolean)


6
7
8
9
10
11
12
# File 'lib/fixloops.rb', line 6

def couldPossiblyRefactor?(p, ind)
  return false unless p[ind].is_a?(Array)
  return false unless p[ind].first == :while
  return false if p[ind][-1] == :post
  return true unless p[ind][2].is_a?(Array)
  p[ind][2].first == :block
end

#fixcode(p, ind) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/fixloops.rb', line 37

def fixcode(p, ind)
  loopsize = howManyInsn(p[ind])
  goodcode = p.clone
  goodcode[ind][-1] = ! goodcode[ind][-1] #true # false
  goodcode.slice!(ind-loopsize..ind-1)
  goodcode # todo : make correcter
end

#grabInsnArray(p) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/fixloops.rb', line 24

def grabInsnArray(p)
  fail "Must be a while, not a #{p}" unless p[0] == :while
    if p[2].is_a?(Array)
      p[2][1..-1]
    else
      [p[2]]
    end
end

#howManyInsn(p) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/fixloops.rb', line 14

def howManyInsn(p)
  fail "Must be a while, not a #{p}" unless p.first == :while
  if p[2].is_a?(Array)
    fail unless p[2].first == :block
    p[2].size - 1
  else
    1
  end
end

#isEquiv(a, b) ⇒ Object



33
34
35
# File 'lib/fixloops.rb', line 33

def isEquiv(a, b)
  a.to_s == b.to_s
end

#recurseOn(p) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/fixloops.rb', line 45

def recurseOn(p)
  if p.is_a?(Array)
    @lastclass = p[1] if p.first == :class
    @lastfunc = p[1] if p.first == :defn
    p.each { |i| recurseOn(i) }
    p.each_index do |ind|
      if couldPossiblyRefactor?(p,ind)
        loopsize = howManyInsn(p[ind])
        if loopsize < ind
          if isEquiv(p[ind-loopsize,loopsize], grabInsnArray(p[ind]))
            goodstuff = fixcode(p, ind)
            puts "Suggest refactoring #{@lastclass}##{@lastfunc} from:"
            puts 
            puts RubyToRuby.translate(eval(@lastclass.to_s), @lastfunc)
            print "\nto:\n\n"
            puts RubyToRuby.new.process(s(:defn, @lastfunc, s(:scope, goodstuff)))
          end
        end
      end
    end
  end
end

#refactor(c) ⇒ Object



68
69
70
71
72
# File 'lib/fixloops.rb', line 68

def refactor(c)
  fail "Must have class or module" unless c.is_a?(Module)
  p = ParseTree.new.parse_tree(c)
  recurseOn(p)
end