Class: Flog

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

Constant Summary collapse

VERSION =
'2.1.1'
THRESHOLD =
0.60
SCORES =
Hash.new 1
BRANCHING =
[ :and, :case, :else, :if, :or, :rescue, :until, :when, :while ]
OTHER_SCORES =

various non-call constructs

{
  :alias          => 2,
  :assignment     => 1,
  :block          => 1,
  :block_pass     => 1,
  :branch         => 1,
  :lit_fixnum     => 0.25,
  :sclass         => 5,
  :super          => 1,
  :to_proc_icky!  => 10,
  :to_proc_normal => 5,
  :yield          => 1,
}
@@no_class =
:main
@@no_method =
:none

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Flog

Returns a new instance of Flog.



219
220
221
222
223
224
225
226
227
228
229
# File 'lib/flog.rb', line 219

def initialize options = {}
  super()
  @options             = options
  @class_stack         = []
  @method_stack        = []
  @mass                = {}
  @parser              = RubyParser.new
  self.auto_shift_type = true
  self.require_empty   = false # HACK
  self.reset
end

Instance Attribute Details

#callsObject (readonly)

Returns the value of attribute calls.



79
80
81
# File 'lib/flog.rb', line 79

def calls
  @calls
end

#class_stackObject (readonly)

Returns the value of attribute class_stack.



79
80
81
# File 'lib/flog.rb', line 79

def class_stack
  @class_stack
end

#massObject (readonly)

Returns the value of attribute mass.



79
80
81
# File 'lib/flog.rb', line 79

def mass
  @mass
end

#method_stackObject (readonly)

Returns the value of attribute method_stack.



79
80
81
# File 'lib/flog.rb', line 79

def method_stack
  @method_stack
end

#multiplierObject

Returns the value of attribute multiplier.



78
79
80
# File 'lib/flog.rb', line 78

def multiplier
  @multiplier
end

#optionsObject (readonly)

Returns the value of attribute options.



79
80
81
# File 'lib/flog.rb', line 79

def options
  @options
end

Class Method Details

.default_optionsObject



81
82
83
84
85
86
# File 'lib/flog.rb', line 81

def self.default_options
  {
    :quiet    => true,
    :continue => false,
  }
end

.expand_dirs_to_files(*dirs) ⇒ Object

REFACTOR: from flay



89
90
91
92
93
94
95
96
97
98
99
# File 'lib/flog.rb', line 89

def self.expand_dirs_to_files *dirs
  extensions = ['rb']

  dirs.flatten.map { |p|
    if File.directory? p then
      Dir[File.join(p, '**', "*.{#{extensions.join(',')}}")]
    else
      p
    end
  }.flatten.sort
end

.parse_optionsObject



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/flog.rb', line 101

def self.parse_options
  options = self.default_options
  op = OptionParser.new do |opts|
    opts.on("-a", "--all", "Display all flog results, not top 60%.") do
      options[:all] = true
    end

    opts.on("-b", "--blame", "Include blame information for methods.") do
      options[:blame] = true
    end

    opts.on("-c", "--continue", "Continue despite syntax errors.") do
      options[:continue] = true
    end

    opts.on("-d", "--details", "Show method details.") do
      options[:details] = true
    end

    opts.on("-g", "--group", "Group and sort by class.") do
      options[:group] = true
    end

    opts.on("-h", "--help", "Show this message.") do
      puts opts
      exit
    end

    opts.on("-I dir1,dir2,dir3", Array, "Add to LOAD_PATH.") do |dirs|
      dirs.each do |dir|
        $: << dir
      end
    end

    opts.on("-m", "--methods-only", "Skip code outside of methods.") do |m|
      options[:methods] = m
    end

    opts.on("-q", "--quiet", "Don't show method details. [default]")  do |v|
      options[:quiet] = v
    end

    opts.on("-s", "--score", "Display total score only.")  do |s|
      options[:score] = s
    end

    opts.on("-v", "--verbose", "Display progress during processing.")  do |v|
      options[:verbose] = v
    end
  end.parse!

  options
end

Instance Method Details

#add_to_score(name, score = ) ⇒ Object

TODO: rename options to option, you only deal with them one at a time…



157
158
159
# File 'lib/flog.rb', line 157

def add_to_score name, score = OTHER_SCORES[name]
  @calls["#{klass_name}##{method_name}"][name] += score * @multiplier
end

#alias_methodObject

various “magic” usually used for “clever code”



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/flog.rb', line 49

SCORES.merge!(:alias_method               => 2,
:extend                     => 2,
:include                    => 2,
:instance_method            => 2,
:instance_methods           => 2,
:method_added               => 2,
:method_defined?            => 2,
:method_removed             => 2,
:method_undefined           => 2,
:private_class_method       => 2,
:private_instance_methods   => 2,
:private_method_defined?    => 2,
:protected_instance_methods => 2,
:protected_method_defined?  => 2,
:public_class_method        => 2,
:public_instance_methods    => 2,
:public_method_defined?     => 2,
:remove_method              => 2,
:send                       => 3,
:undef_method               => 2)

#analyze_list(exp) ⇒ Object

Process each element of #exp in turn. TODO: rename, bleed wasn’t good, but this is actually worse



165
166
167
# File 'lib/flog.rb', line 165

def analyze_list exp
  process exp.shift until exp.empty?
end

#averageObject



169
170
171
172
# File 'lib/flog.rb', line 169

def average
  return 0 if calls.size == 0
  total / calls.size
end

#define_methodObject

eval forms



40
41
42
43
44
# File 'lib/flog.rb', line 40

SCORES.merge!(:define_method => 5,
:eval          => 5,
:module_eval   => 5,
:class_eval    => 5,
:instance_eval => 5)

#flog(*files_or_dirs) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/flog.rb', line 174

def flog(*files_or_dirs)
  files = Flog.expand_dirs_to_files(*files_or_dirs)

  files.each do |file|
    begin
      # TODO: replace File.open to deal with "-"
      ruby = file == '-' ? $stdin.read : File.read(file)
      warn "** flogging #{file}" if options[:verbose]

      ast = @parser.process(ruby, file)
      mass[file] = ast.mass
      process ast
    rescue SyntaxError, Racc::ParseError => e
      if e.inspect =~ /<%|%>/ then
        warn "#{e.inspect} at #{e.backtrace.first(5).join(', ')}"
        warn "\n...stupid lemmings and their bad erb templates... skipping"
      else
        raise e unless options[:continue]
        warn file
        warn "#{e.inspect} at #{e.backtrace.first(5).join(', ')}"
      end
    end
  end
end

#in_klass(name) ⇒ Object



199
200
201
202
203
# File 'lib/flog.rb', line 199

def in_klass name
  @class_stack.unshift name
  yield
  @class_stack.shift
end

#in_method(name) ⇒ Object

Adds name to the list of methods, for the duration of the block



208
209
210
211
212
# File 'lib/flog.rb', line 208

def in_method name
  @method_stack.unshift name
  yield
  @method_stack.shift
end

#increment_total_score_by(amount) ⇒ Object



214
215
216
217
# File 'lib/flog.rb', line 214

def increment_total_score_by amount
  raise "@total_score isn't even set yet... dumbass" unless @total_score
  @total_score += amount
end

#injectObject

calls I don’t like and usually see being abused



73
# File 'lib/flog.rb', line 73

SCORES.merge!(:inject => 2)

#klass_nameObject

returns the first class in the list, or @@no_class if there are none.



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/flog.rb', line 235

def klass_name
  name = @class_stack.first || @@no_class
  if Sexp === name then
    name = case name.first
           when :colon2 then
             name = name.flatten
             name.delete :const
             name.delete :colon2
             name.join("::")
           when :colon3 then
             name.last
           else
             name
           end
  end
  name
end

#method_nameObject

returns the first method in the list, or @@no_method if there are none.



257
258
259
# File 'lib/flog.rb', line 257

def method_name
  @method_stack.first || @@no_method
end

#output_details(io, max = nil) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/flog.rb', line 261

def output_details(io, max = nil)
  my_totals = totals
  current = 0

  if options[:group] then
    scores = Hash.new 0
    methods = Hash.new { |h,k| h[k] = [] }

    calls.sort_by { |k,v| -my_totals[k] }.each do |class_method, call_list|
      klass = class_method.split(/#|::/).first
      score = totals[class_method]
      methods[klass] << [class_method, score]
      scores[klass] += score
      current += score
      break if max and current >= max
    end

    scores.sort_by { |_, n| -n }.each do |klass, total|
      io.puts
      io.puts "%8.1f: %s" % [total, "#{klass} total"]
      methods[klass].each do |name, score|
        io.puts "%8.1f: %s" % [score, name]
      end
    end
  else
    io.puts
    calls.sort_by { |k,v| -my_totals[k] }.each do |class_method, call_list|
      current += output_method_details(io, class_method, call_list)
      break if max and current >= max
    end
  end
end

#output_method_details(io, class_method, call_list) ⇒ Object



294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/flog.rb', line 294

def output_method_details(io, class_method, call_list)
  return 0 if options[:methods] and class_method =~ /##{@@no_method}/

  total = totals[class_method]
  io.puts "%8.1f: %s" % [total, class_method]

  call_list.sort_by { |k,v| -v }.each do |call, count|
    io.puts "  %6.1f: %s" % [count, call]
  end if options[:details]

  total
end

#output_summary(io) ⇒ Object



307
308
309
310
# File 'lib/flog.rb', line 307

def output_summary(io)
  io.puts "%8.1f: %s" % [total, "flog total"]
  io.puts "%8.1f: %s" % [average, "flog/method average"]
end

#penalize_by(bonus) ⇒ Object

For the duration of the block the complexity factor is increased by #bonus This allows the complexity of sub-expressions to be influenced by the expressions in which they are found. Yields 42 to the supplied block.



318
319
320
321
322
# File 'lib/flog.rb', line 318

def penalize_by bonus
  @multiplier += bonus
  yield
  @multiplier -= bonus
end

#process_alias(exp) ⇒ Object

Process Methods:



393
394
395
396
397
398
# File 'lib/flog.rb', line 393

def process_alias(exp)
  process exp.shift
  process exp.shift
  add_to_score :alias
  s()
end

#process_and(exp) ⇒ Object Also known as: process_or



400
401
402
403
404
405
406
407
# File 'lib/flog.rb', line 400

def process_and(exp)
  add_to_score :branch
  penalize_by 0.1 do
    process exp.shift # lhs
    process exp.shift # rhs
  end
  s()
end

#process_attrasgn(exp) ⇒ Object



410
411
412
413
414
415
416
# File 'lib/flog.rb', line 410

def process_attrasgn(exp)
  add_to_score :assignment
  process exp.shift # lhs
  exp.shift # name
  process exp.shift # rhs
  s()
end

#process_attrset(exp) ⇒ Object



418
419
420
421
422
# File 'lib/flog.rb', line 418

def process_attrset(exp)
  add_to_score :assignment
  raise exp.inspect
  s()
end

#process_block(exp) ⇒ Object



424
425
426
427
428
429
# File 'lib/flog.rb', line 424

def process_block(exp)
  penalize_by 0.1 do
    analyze_list exp
  end
  s()
end

#process_block_pass(exp) ⇒ Object



431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# File 'lib/flog.rb', line 431

def process_block_pass(exp)
  arg = exp.shift

  add_to_score :block_pass

  case arg.first
  when :lvar, :dvar, :ivar, :cvar, :self, :const, :nil then
    # do nothing
  when :lit, :call then
    add_to_score :to_proc_normal
  when :iter, :dsym, :dstr, *BRANCHING then
    add_to_score :to_proc_icky!
  else
    raise({:block_pass_even_ickier! => [arg, call]}.inspect)
  end

  process arg

  s()
end

#process_call(exp) ⇒ Object



452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/flog.rb', line 452

def process_call(exp)
  penalize_by 0.2 do
    recv = process exp.shift
  end
  name = exp.shift
  penalize_by 0.2 do
    args = process exp.shift
  end

  add_to_score name, SCORES[name]

  s()
end

#process_case(exp) ⇒ Object



466
467
468
469
470
471
472
473
# File 'lib/flog.rb', line 466

def process_case(exp)
  add_to_score :branch
  process exp.shift # recv
  penalize_by 0.1 do
    analyze_list exp
  end
  s()
end

#process_class(exp) ⇒ Object



475
476
477
478
479
480
481
482
483
# File 'lib/flog.rb', line 475

def process_class(exp)
  in_klass exp.shift do
    penalize_by 1.0 do
      supr = process exp.shift
    end
    analyze_list exp
  end
  s()
end

#process_dasgn_curr(exp) ⇒ Object Also known as: process_iasgn, process_lasgn



485
486
487
488
489
490
# File 'lib/flog.rb', line 485

def process_dasgn_curr(exp)
  add_to_score :assignment
  exp.shift # name
  process exp.shift # assigment, if any
  s()
end

#process_defn(exp) ⇒ Object



494
495
496
497
498
499
# File 'lib/flog.rb', line 494

def process_defn(exp)
  in_method exp.shift do
    analyze_list exp
  end
  s()
end

#process_defs(exp) ⇒ Object



501
502
503
504
505
506
507
# File 'lib/flog.rb', line 501

def process_defs(exp)
  process exp.shift
  in_method exp.shift do
    analyze_list exp
  end
  s()
end

#process_else(exp) ⇒ Object Also known as: process_rescue, process_when

TODO: it’s not clear to me whether this can be generated at all.



510
511
512
513
514
515
516
# File 'lib/flog.rb', line 510

def process_else(exp)
  add_to_score :branch
  penalize_by 0.1 do
    analyze_list exp
  end
  s()
end

#process_if(exp) ⇒ Object



520
521
522
523
524
525
526
527
528
# File 'lib/flog.rb', line 520

def process_if(exp)
  add_to_score :branch
  process exp.shift # cond
  penalize_by 0.1 do
    process exp.shift # true
    process exp.shift # false
  end
  s()
end

#process_iter(exp) ⇒ Object



530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
# File 'lib/flog.rb', line 530

def process_iter(exp)
  context = (self.context - [:class, :module, :scope])
  if context.uniq.sort_by {|s|s.to_s} == [:block, :iter] then
    recv = exp.first
    if (recv[0] == :call and recv[1] == nil and recv.arglist[1] and
        [:lit, :str].include? recv.arglist[1][0]) then
      msg = recv[2]
      submsg = recv.arglist[1][1]
      in_method submsg do
        in_klass msg do
          analyze_list exp
        end
      end
      return s()
    end
  end

  add_to_score :branch

  exp.pop if exp.last == 0
  process exp.shift # no penalty for LHS

  penalize_by 0.1 do
    analyze_list exp
  end

  s()
end

#process_lit(exp) ⇒ Object



559
560
561
562
563
564
565
566
567
568
569
570
571
572
# File 'lib/flog.rb', line 559

def process_lit(exp)
  value = exp.shift
  case value
  when 0, -1 then
    # ignore those because they're used as array indicies instead of first/last
  when Integer then
    add_to_score :lit_fixnum
  when Float, Symbol, Regexp, Range then
    # do nothing
  else
    raise value.inspect
  end
  s()
end

#process_masgn(exp) ⇒ Object



574
575
576
577
578
# File 'lib/flog.rb', line 574

def process_masgn(exp)
  add_to_score :assignment
  analyze_list exp
  s()
end

#process_module(exp) ⇒ Object



580
581
582
583
584
585
# File 'lib/flog.rb', line 580

def process_module(exp)
  in_klass exp.shift do
    analyze_list exp
  end
  s()
end

#process_sclass(exp) ⇒ Object



587
588
589
590
591
592
593
594
595
# File 'lib/flog.rb', line 587

def process_sclass(exp)
  penalize_by 0.5 do
    recv = process exp.shift
    analyze_list exp
  end

  add_to_score :sclass
  s()
end

#process_super(exp) ⇒ Object



597
598
599
600
601
# File 'lib/flog.rb', line 597

def process_super(exp)
  add_to_score :super
  analyze_list exp
  s()
end

#process_while(exp) ⇒ Object Also known as: process_until



603
604
605
606
607
608
609
610
611
# File 'lib/flog.rb', line 603

def process_while(exp)
  add_to_score :branch
  penalize_by 0.1 do
    process exp.shift # cond
    process exp.shift # body
  end
  exp.shift # pre/post
  s()
end

#process_yield(exp) ⇒ Object



614
615
616
617
618
# File 'lib/flog.rb', line 614

def process_yield(exp)
  add_to_score :yield
  analyze_list exp
  s()
end

#record_method_score(method, score) ⇒ Object



324
325
326
327
# File 'lib/flog.rb', line 324

def record_method_score(method, score)
  @totals ||= Hash.new(0)
  @totals[method] = score
end

#report(io = $stdout) ⇒ Object

Report results to #io, STDOUT by default.



332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/flog.rb', line 332

def report(io = $stdout)
  output_summary(io)
  return if options[:score]

  if options[:all] then # TODO: fix - use option[:all] and THRESHOLD directly
    output_details(io)
  else
    output_details(io, total * THRESHOLD)
  end
ensure
  self.reset
end

#resetObject



345
346
347
348
349
# File 'lib/flog.rb', line 345

def reset
  @totals     = @total_score = nil
  @multiplier = 1.0
  @calls      = Hash.new { |h,k| h[k] = Hash.new 0 }
end

#score_method(tally) ⇒ Object



351
352
353
354
355
356
357
358
359
360
361
# File 'lib/flog.rb', line 351

def score_method(tally)
  a, b, c = 0, 0, 0
  tally.each do |cat, score|
    case cat
    when :assignment then a += score
    when :branch     then b += score
    else                  c += score
    end
  end
  Math.sqrt(a*a + b*b + c*c)
end

#summarize_method(meth, tally) ⇒ Object



363
364
365
366
367
368
# File 'lib/flog.rb', line 363

def summarize_method(meth, tally)
  return if options[:methods] and meth =~ /##{@@no_method}$/
  score = score_method(tally)
  record_method_score(meth, score)
  increment_total_score_by score
end

#totalObject



370
371
372
373
374
# File 'lib/flog.rb', line 370

def total
  totals unless @total_score # calculates total_score as well

  @total_score
end

#totalsObject

Return the total score and populates @totals.



379
380
381
382
383
384
385
386
387
388
# File 'lib/flog.rb', line 379

def totals
  unless @totals then
    @total_score = 0
    @totals = Hash.new(0)
    calls.each do |meth, tally|
      summarize_method(meth, tally)
    end
  end
  @totals
end