Class: ASTNormalizer

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeASTNormalizer

Returns a new instance of ASTNormalizer.



34
35
36
37
# File 'lib/normalize_ast.rb', line 34

def initialize
  @track = NameTracker.new
  @complexity = Hash.new { |h,k| h[k] = [] }
end

Instance Attribute Details

#complexityObject

Returns the value of attribute complexity.



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

def complexity
  @complexity
end

Instance Method Details

#pretty_complexityObject



41
42
43
44
45
# File 'lib/normalize_ast.rb', line 41

def pretty_complexity
  measures, out = [:int, :str, :send, :var, :float, :sym], {}
  @complexity.select { |k,v| measures.include?(k) }.each { |k,v| out[k] = v.size }
  out
end

#rewrite_ast(ast) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/normalize_ast.rb', line 46

def rewrite_ast(ast)
  if ast.is_a? AST::Node
    type = ast.type
    case type
    # Variables
    when :lvar, :ivar, :gvar
      update_complexity(:var, ast.children.first)
      ast.updated(nil, ast.children.map { |child| @track.rename(:var, child) })
    # Assignment
    when :lvasgn, :gvasgn, :ivasgn, :cvasgn
      update_complexity(:assignment, ast.children.first)
      ast.updated(nil, ast.children.map.with_index { |child,i| 
        i == 0 ? @track.rename(:var,child) : rewrite_ast(child)
      }) 
    # Primatives
    when :int, :float, :str, :sym, :arg, :restarg, :blockarg
      update_complexity(type, ast.children.first)
      ast.updated(nil, ast.children.map { |child| @track.rename(type, child) })
    when :optarg
      update_complexity(:arg, ast.children.first)
      ast.updated(nil, ast.children.map.with_index { |child,i| 
        if i == 0 
          @track.rename(:var, child)
        else
          rewrite_ast(child)
        end 
      })
    # Method definitions
    when :def
      update_complexity(:def, ast.children.first)
      ast.updated(nil, ast.children.map.with_index { |child,i|
        i == 0 ? :method : rewrite_ast(child)
      }) 
    when :defs
      update_complexity(:def, ast.children.first)
      ast.updated(nil, ast.children.map.with_index { |child,i|
        i == 1 ? :method : rewrite_ast(child)
      })
    when :send
      update_complexity(:send, ast.children[1])
      ast.updated(nil, ast.children.map { |child| rewrite_ast(child) })
    else
      ast.updated(nil, ast.children.map { |child| rewrite_ast(child) })
    end
  else
    ast
  end
end

#update_complexity(type, val) ⇒ Object



38
39
40
# File 'lib/normalize_ast.rb', line 38

def update_complexity(type,val)
  @complexity[type].push(val)
end