examples: annotate examples
[nit.git] / src / examples / get_mclasses.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Sample program that search classes in a model
16 #
17 # eg.
18 #
19 # ~~~raw
20 # get_mclasses ../../lib core::Array Array care::Arrow Fail
21 # ~~~
22 module get_mclasses is example
23
24 import parser_util
25 import modelbuilder
26 import modelize
27 import more_collections
28
29 # Manage the logistic of the tool
30 var tc = new ToolContext
31 tc.tooldescription = "Usage: get_mclasses file qualified_class_name..."
32 tc.process_options(args)
33
34 # Parse the first argument to fill a model
35 var model = new Model
36 var mb = new ModelBuilder(model, tc)
37 mb.parse_full([args.shift])
38 mb.run_phases
39
40 # Query remaining arguments
41 for arg in args do
42 # Ask the parser to parse the argument. It's its job!
43 var n = tc.parse_something(arg)
44 if n isa AType then
45 # Only the class qualified identifier is useful
46 # We just ignore `nullable` or generic arguments.
47 var qid = n.n_qid
48 var full_name = qid.full_name
49 print "search: {full_name}"
50
51 # Iterate on all classes of the model to find one that matches the qualified name.
52 # Because we are efficient, we iterate only on the classes with the same short name.
53 var short_name = qid.n_id.text
54 var classes = model.get_mclasses_by_name(short_name)
55 var found = false
56 if classes != null then for c in classes do
57 if qid.accept(c) then
58 print " * {c.full_name}"
59 found = true
60 end
61 end
62
63 if not found then
64 # We are unlucky, maybe a misspell?
65 # Look for all classes with a similar name
66 var bests = new BestDistance[MClass](full_name.length)
67 for c in model.mclasses do
68 # Check with both the full_name and the short_name
69 var lev = full_name.levenshtein_distance(c.full_name)
70 bests.update(lev, c)
71 lev = full_name.levenshtein_distance(c.name)
72 bests.update(lev, c)
73 end
74 if bests.best_items.is_empty then
75 print " Found nothing :("
76 else
77 print " Did you mean?"
78 for c in bests.best_items do
79 print " * {c.full_name}"
80 end
81 end
82 end
83 else
84 print "`{arg}` is {n}, wanted a class name :("
85 end
86 end