forked from seattlerb/flog
-
Notifications
You must be signed in to change notification settings - Fork 1
/
flog.rb
616 lines (515 loc) · 13.8 KB
/
flog.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
94
95
96
97
98
99
100
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
require 'rubygems'
require 'sexp_processor'
require 'ruby_parser'
require 'optparse'
class Flog < SexpProcessor
VERSION = '2.2.0'
THRESHOLD = 0.60
SCORES = Hash.new 1
BRANCHING = [ :and, :case, :else, :if, :or, :rescue, :until, :when, :while ]
##
# various non-call constructs
OTHER_SCORES = {
: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,
}
##
# eval forms
SCORES.merge!(:define_method => 5,
:eval => 5,
:module_eval => 5,
:class_eval => 5,
:instance_eval => 5)
##
# various "magic" usually used for "clever code"
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)
##
# calls I don't like and usually see being abused
SCORES.merge!(:inject => 2)
@@no_class = :main
@@no_method = :none
attr_accessor :multiplier
attr_reader :calls, :options, :class_stack, :method_stack, :mass, :method_locations
def self.default_options
{
:quiet => true,
:continue => false,
}
end
# REFACTOR: from flay
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
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
# TODO: rename options to option, you only deal with them one at a time...
def add_to_score name, score = OTHER_SCORES[name]
@calls["#{klass_name}##{method_name}"][name] += score * @multiplier
end
##
# Process each element of #exp in turn.
# TODO: rename, bleed wasn't good, but this is actually worse
def analyze_list exp
process exp.shift until exp.empty?
end
def average
return 0 if calls.size == 0
total / calls.size
end
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)
next unless ast
mass[file] = ast.mass
process ast
rescue SyntaxError, Racc::ParseError => e
if e.inspect =~ /<%|%>/ or ruby =~ /<%|%>/ 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
def in_klass name
@class_stack.unshift name
yield
@class_stack.shift
end
##
# Adds name to the list of methods, for the duration of the block
def in_method(name, line)
@method_stack.unshift name
@method_locations["#{klass_name}##{name}"] = line
yield
@method_stack.shift
end
def increment_total_score_by amount
raise "@total_score isn't even set yet... dumbass" unless @total_score
@total_score += amount
end
def initialize options = {}
super()
@options = options
@class_stack = []
@method_stack = []
@method_locations = {}
@mass = {}
@parser = RubyParser.new
self.auto_shift_type = true
self.require_empty = false # HACK
self.reset
end
##
# returns the first class in the list, or @@no_class if there are
# none.
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
##
# returns the first method in the list, or @@no_method if there are
# none.
def method_name
@method_stack.first || @@no_method
end
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
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
def output_summary(io)
io.puts "%8.1f: %s" % [total, "flog total"]
io.puts "%8.1f: %s" % [average, "flog/method average"]
end
##
# 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.
def penalize_by bonus
@multiplier += bonus
yield
@multiplier -= bonus
end
def record_method_score(method, score)
@totals ||= Hash.new(0)
@totals[method] = score
end
##
# Report results to #io, STDOUT by default.
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
def reset
@totals = @total_score = nil
@multiplier = 1.0
@calls = Hash.new { |h,k| h[k] = Hash.new 0 }
end
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
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
def total
totals unless @total_score # calculates total_score as well
@total_score
end
##
# Return the total score and populates @totals.
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
############################################################
# Process Methods:
def process_alias(exp)
process exp.shift
process exp.shift
add_to_score :alias
s()
end
def process_and(exp)
add_to_score :branch
penalize_by 0.1 do
process exp.shift # lhs
process exp.shift # rhs
end
s()
end
alias :process_or :process_and
def process_attrasgn(exp)
add_to_score :assignment
process exp.shift # lhs
exp.shift # name
process exp.shift # rhs
s()
end
def process_attrset(exp)
add_to_score :assignment
raise exp.inspect
s()
end
def process_block(exp)
penalize_by 0.1 do
analyze_list exp
end
s()
end
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
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
def process_case(exp)
add_to_score :branch
process exp.shift # recv
penalize_by 0.1 do
analyze_list exp
end
s()
end
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
def process_dasgn_curr(exp)
add_to_score :assignment
exp.shift # name
process exp.shift # assigment, if any
s()
end
alias :process_iasgn :process_dasgn_curr
alias :process_lasgn :process_dasgn_curr
def process_defn(exp)
in_method(exp.shift, exp.line) do
analyze_list exp
end
s()
end
def process_defs(exp)
process exp.shift
in_method(exp.shift, exp.line) do
analyze_list exp
end
s()
end
# TODO: it's not clear to me whether this can be generated at all.
def process_else(exp)
add_to_score :branch
penalize_by 0.1 do
analyze_list exp
end
s()
end
alias :process_rescue :process_else
alias :process_when :process_else
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
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_klass msg do
in_method(submsg, exp.line) do
analyze_list exp
end
end
return s()
end
end
add_to_score :branch
exp.delete 0
process exp.shift # no penalty for LHS
penalize_by 0.1 do
analyze_list exp
end
s()
end
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
def process_masgn(exp)
add_to_score :assignment
analyze_list exp
s()
end
def process_module(exp)
in_klass exp.shift do
analyze_list exp
end
s()
end
def process_sclass(exp)
penalize_by 0.5 do
recv = process exp.shift
analyze_list exp
end
add_to_score :sclass
s()
end
def process_super(exp)
add_to_score :super
analyze_list exp
s()
end
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
alias :process_until :process_while
def process_yield(exp)
add_to_score :yield
analyze_list exp
s()
end
end