nitmetrics: dont crash if nclassdef.mclassdef is null
[nit.git] / src / metrics / static_types_metrics.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 Jean Privat <jean@pryen.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Metrics on the usage of explicit static types.
18 module static_types_metrics
19
20 import metrics_base
21 import modelize
22
23 redef class ToolContext
24 var static_types_metrics_phase: Phase = new StaticTypesMetricsPhase(self, null)
25 end
26
27 private class StaticTypesMetricsPhase
28 super Phase
29 redef fun process_mainmodule(mainmodule, given_mmodules)
30 do
31 if not toolcontext.opt_static_types.value and not toolcontext.opt_all.value then return
32 compute_static_types_metrics(toolcontext.modelbuilder)
33 end
34 end
35
36 # The job of this visitor is to resolve all types found
37 private class ATypeCounterVisitor
38 super Visitor
39 var modelbuilder: ModelBuilder
40 var nclassdef: AClassdef
41
42 var typecount: Counter[MType]
43
44 # Get a new visitor on a classef to add type count in `typecount`.
45 init(modelbuilder: ModelBuilder, nclassdef: AClassdef, typecount: Counter[MType])
46 do
47 self.modelbuilder = modelbuilder
48 self.nclassdef = nclassdef
49 self.typecount = typecount
50 end
51
52 redef fun visit(n)
53 do
54 if n isa AAnnotation then return
55
56 if n isa AType then do
57 var mclassdef = self.nclassdef.mclassdef
58 if mclassdef == null then break
59 var mtype = modelbuilder.resolve_mtype(mclassdef, n)
60 if mtype != null then
61 self.typecount.inc(mtype)
62 end
63 end
64 n.visit_all(self)
65 end
66 end
67
68 # Visit the AST and print metrics on the usage of explicit static types.
69 fun compute_static_types_metrics(modelbuilder: ModelBuilder)
70 do
71 # Count each occurence of a specific static type
72 var typecount = new Counter[MType]
73
74 # Visit all the source code to collect data
75 for nmodule in modelbuilder.nmodules do
76 for nclassdef in nmodule.n_classdefs do
77 var visitor = new ATypeCounterVisitor(modelbuilder, nclassdef, typecount)
78 visitor.enter_visit(nclassdef)
79 end
80 end
81
82 # Display data
83 print "--- Metrics of the explitic static types ---"
84 print "Total number of explicit static types: {typecount.sum}"
85 if typecount.sum == 0 then return
86
87 print "Statistics of type usage:"
88 typecount.print_summary
89 typecount.print_elements(10)
90 end