model_collect: fix MClass ancestors and descendants access
[nit.git] / src / model / model_index.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 # Search things from the Model
16 #
17 # ModelIndex allows you to index mentities then retrieve them by their `name`
18 # or `full_name`.
19 # It offers a set of `find_*` methods that can be used to match queries
20 # against entities name.
21 #
22 # Because each use is different, ModelIndex only provide base raw search services.
23 # All of them return IndexMatches that can be ordered and filtered by the client.
24 #
25 # ## Indexing mentities
26 #
27 # Before searching something from the ModelIndex, you have to index it.
28 # Use the `ModelIndex::index` method to do that:
29 #
30 # ~~~nitish
31 # var index = new ModelIndex
32 # for mentity in model.collect_mentities do
33 # index.index(mentity)
34 # end
35 # ~~~
36 #
37 # ## Search mentities
38 #
39 # You can then run queries on the ModelIndex:
40 #
41 # ~~~nitish
42 # for res in index.find("Array").limit(10) do
43 # print res
44 # end
45 # ~~~
46 #
47 # ## Examples
48 #
49 # Here some examples of how you can use the ModelIndex.
50 #
51 # ### Smart type prediction
52 #
53 # Use ModelIndex to implement a smart prediction system based on the typed prefix:
54 #
55 # ~~~nitish
56 # var index = new ModelIndex
57 # for mentity in model.collect_mentities do
58 # # We don't really care about definitions
59 # if mentity isa MClassDef or mentity isa MPropDef then continue
60 # index.index(mentity)
61 # end
62 #
63 # var typed_prefix = "Arr"
64 # for res in index.find_by_name_prefix(typed_prefix).
65 # uniq. # keep only the best ranked mentity
66 # limit(5). # limit to ten results
67 # sort(new VisibilityComparator, new NameComparator) do # order by visibility then name
68 # print res
69 # end
70 # ~~~
71 #
72 # Will output something like:
73 #
74 # ~~~raw
75 # Array (1)
76 # ArraySet (2)
77 # ArrayMap (3)
78 # ArrayCmp (4)
79 # ArrayMapKeys (5)
80 # ~~~
81 #
82 # ### Method autocompletion
83 #
84 # Find methods from a class full_name:
85 #
86 # ~~~nitish
87 # var class_full_name = "core::Array"
88 # for res in index.find_by_full_name_prefix("{class_full_name}::").
89 # uniq. # keep only the best ranked mentity
90 # sort(new VisibilityComparator). # put private in the bottom of the list
91 # limit(5). # limit to ten results
92 # sort(new FullNameComparator) do # order by lexicographic order
93 # print res
94 # end
95 # ~~~
96 #
97 # Will output something like:
98 #
99 # ~~~raw
100 # * (2)
101 # + (1)
102 # filled_with (5)
103 # from (3)
104 # with_items (4)
105 # ~~~
106 #
107 # ### Name typo detection and suggestion
108 #
109 # Detect unknown names and suggest corrections:
110 #
111 # ~~~nitish
112 # var name = "Zrray"
113 #
114 # if index.find_by_name_prefix(name).is_empty then
115 # printn "`{name}` not found, did you mean: "
116 # printn index.find_by_name_similarity(name).sort(new ScoreComparator).limit(2).join(" or ")
117 # print "?"
118 # end
119 # ~~~
120 #
121 # Will output something like:
122 #
123 # ~~~raw
124 # `Zrray` not found, did you mean: Array (1) or array (1)?
125 # ~~~
126 module model_index
127
128 import model::model_collect
129 import trees::trie
130
131 redef class Model
132
133 # Keep a direct link to mentities by full name to speed up `mentity_from_uri`
134 var mentities_by_full_name: HashMap[String, MEntity] is lazy do
135 var mentities_by_full_name = new HashMap[String, MEntity]
136 for mentity in collect_mentities do
137 mentities_by_full_name[mentity.full_name] = mentity
138 end
139 return mentities_by_full_name
140 end
141
142 # ModelIndex used to perform searches
143 var index: ModelIndex is lazy do
144 var index = new ModelIndex
145 for mentity in collect_mentities do
146 if mentity isa MClassDef or mentity isa MPropDef then continue
147 index.index mentity
148 end
149 return index
150 end
151
152 redef fun mentities_by_name(name, filter) do
153 var res = new Array[MEntity]
154 if index.name_prefixes.has_key(name) then
155 for mentity in index.name_prefixes[name] do
156 if filter == null or filter.accept_mentity(mentity) then
157 res.add mentity
158 end
159 end
160 end
161 return res
162 end
163
164 redef fun mentity_by_full_name(full_name, filter) do
165 if mentities_by_full_name.has_key(full_name) then
166 var mentity = mentities_by_full_name[full_name]
167 if filter == null or filter.accept_mentity(mentity) then return mentity
168 end
169 return null
170 end
171
172 private var score_sorter = new ScoreComparator
173 private var vis_sorter = new VisibilityComparator
174 private var kind_sorter = new MEntityComparator
175 private var name_sorter = new NameComparator
176 private var lname_sorter = new NameLengthComparator
177 private var fname_sorter = new FullNameComparator
178 private var lfname_sorter = new FullNameLengthComparator
179
180 # Search mentities based on a `query` string
181 #
182 # Lookup the index for anything matching `query` and return `limit` results.
183 #
184 # The algorithm used is the following:
185 # 1- lookup by name prefix
186 # 2- lookup by full_name prefix
187 # 3- loopup by levenshtein distance
188 #
189 # At each step if the `limit` is reached, the algorithm stops and returns the results.
190 fun find(query: String, limit: nullable Int): Array[MEntity] do
191 # Find, lookup by name prefix
192 var matches = index.find_by_name_prefix(query).uniq.
193 sort(lname_sorter, name_sorter, kind_sorter)
194 if limit != null and matches.length >= limit then
195 return matches.limit(limit).rerank.sort(vis_sorter, score_sorter).mentities
196 end
197 matches = matches.rerank.sort(vis_sorter, score_sorter)
198
199 # If limit not reached, lookup by full_name prefix
200 var malus = matches.length
201 var full_matches = new IndexMatches
202 for match in index.find_by_full_name_prefix(query).
203 sort(kind_sorter, lfname_sorter, fname_sorter) do
204 match.score += malus
205 full_matches.add match
206 end
207 matches = matches.uniq
208 if limit != null and matches.length + full_matches.length >= limit then
209 matches.add_all full_matches
210 matches = matches.uniq.limit(limit).rerank.sort(vis_sorter, score_sorter)
211 return matches.mentities
212 end
213
214 # If limit not reached, lookup by similarity
215 malus = matches.length
216 var sim_matches = new IndexMatches
217 for match in index.find_by_similarity(query).sort(score_sorter, kind_sorter, lname_sorter, name_sorter) do
218 match.score += malus
219 sim_matches.add match
220 end
221 matches.add_all sim_matches
222 matches = matches.uniq
223 if limit != null then matches = matches.limit(limit)
224 return matches.rerank.sort(vis_sorter, score_sorter).mentities
225 end
226 end
227
228 # ModelIndex indexes mentities by their name and full name
229 #
230 # It provides methods to find mentities based on a prefix or string similarity.
231 #
232 # ~~~nitish
233 # # Build index
234 # var index = new ModelIndex
235 # for mentity in model.collect_mentities do
236 # if mentity isa MClassDef or mentity isa MPropDef then continue
237 # index.index(mentity)
238 # end
239 #
240 # for e in index.find("Foo").uniq.sort(new ScoreComparator).limit(10) do
241 # print " * {e.score}: {e.mentity.name} ({e.mentity.full_name})"
242 # end
243 # ~~~
244 class ModelIndex
245
246 # List of all indexed mentities.
247 #
248 # Faster than traversing the tries.
249 var mentities = new Array[MEntity]
250
251 # Prefix tree for mentities `name`
252 #
253 # Because multiple mentities can share the same `name`, we use a Trie of
254 # arrays of mentities.
255 #
256 # As for now, we do not index class and property definitions.
257 # TODO add an option.
258 var name_prefixes = new Trie[Array[MEntity]]
259
260 # Prefix tree for mentities `full_name`
261 #
262 # Even if two mentities cannot share the same `full_name`, we use a Trie of
263 # arrays of mentities to be consistent with `name_prefixes`.
264 var full_name_prefixes = new Trie[Array[MEntity]]
265
266 # Index `mentity` by it's `MEntity::name`
267 #
268 # See `name_prefixes`.
269 private fun index_by_name(mentity: MEntity) do
270 var name = mentity.name
271 if not name_prefixes.has_key(name) then
272 name_prefixes[name] = new Array[MEntity]
273 end
274 name_prefixes[name].add mentity
275 end
276
277 # Index `mentity` by its `MEntity::full_name`
278 private fun index_by_full_name(mentity: MEntity) do
279 var name = mentity.full_name
280 if not full_name_prefixes.has_key(name) then
281 full_name_prefixes[name] = new Array[MEntity]
282 end
283 full_name_prefixes[name].add mentity
284 end
285
286 # Index `mentity` so it can be retrieved by a find query
287 #
288 # MEntities are indexed by both name and full_name.
289 fun index(mentity: MEntity) do
290 mentities.add mentity
291 index_by_name mentity
292 index_by_full_name mentity
293 end
294
295 # Translate Trie results to `SearchResult`
296 #
297 # This method is used internally to translate each mentity returned by a prefix
298 # match in a Trie into a SearchResult that can be ranked by score.
299 #
300 # Results from the Trie are returned in a breadth first manner so we get the
301 # matches ordered by prefix.
302 # We preserve that order by giving an incremental score to the `array` items.
303 private fun score_results_incremental(array: Array[Array[MEntity]]): IndexMatches do
304 var results = new IndexMatches
305 var score = 1
306 for mentities in array do
307 for mentity in mentities do
308 results.add new IndexMatch(mentity, score)
309 end
310 score += 1
311 end
312 return results
313 end
314
315 # Find all mentities where `MEntity::name` matches the `prefix`
316 fun find_by_name_prefix(prefix: String): IndexMatches do
317 return score_results_incremental(name_prefixes.find_by_prefix(prefix))
318 end
319
320 # Find all mentities where `MEntity::full_name` matches the `prefix`
321 fun find_by_full_name_prefix(prefix: String): IndexMatches do
322 return score_results_incremental(full_name_prefixes.find_by_prefix(prefix))
323 end
324
325 # Rank all mentities by the distance between `MEntity::name` and `name`
326 #
327 # Use the Levenshtein algorithm on all the indexed mentities `name`.
328 # Warning: may not scale to large indexes.
329 fun find_by_name_similarity(name: String): IndexMatches do
330 var results = new IndexMatches
331 for mentity in mentities do
332 if mentity isa MClassDef or mentity isa MPropDef then continue
333 results.add new IndexMatch(mentity, name.levenshtein_distance(mentity.name))
334 end
335 return results
336 end
337
338 # Rank all mentities by the distance between `MEntity::full_name` and `full_name`
339 #
340 # Use the Levenshtein algorithm on all the indexed mentities `full_name`.
341 # Warning: may not scale to large indexes.
342 fun find_by_full_name_similarity(name: String): IndexMatches do
343 var results = new IndexMatches
344 for mentity in mentities do
345 if mentity isa MClassDef or mentity isa MPropDef then continue
346 results.add new IndexMatch(mentity, name.levenshtein_distance(mentity.full_name))
347 end
348 return results
349 end
350
351 # Rank all mentities by the distance between `name` and both the mentity name and full name
352 fun find_by_similarity(name: String): IndexMatches do
353 var results = new IndexMatches
354 for mentity in mentities do
355 if mentity isa MClassDef or mentity isa MPropDef then continue
356 results.add new IndexMatch(mentity, name.levenshtein_distance(mentity.name))
357 results.add new IndexMatch(mentity, name.levenshtein_distance(mentity.full_name))
358 end
359 return results
360 end
361
362 # Find mentities by name trying first by prefix then by similarity
363 fun find_by_name(name: String): IndexMatches do
364 var results = find_by_name_prefix(name)
365 for mentity in mentities do
366 if mentity isa MClassDef or mentity isa MPropDef then continue
367 results.add new IndexMatch(mentity, name.levenshtein_distance(mentity.name))
368 end
369 return results
370 end
371
372 # Find mentities by full name trying firt by prefix then by similarity
373 fun find_by_full_name(name: String): IndexMatches do
374 var results = find_by_full_name_prefix(name)
375 for mentity in mentities do
376 if mentity isa MClassDef or mentity isa MPropDef then continue
377 results.add new IndexMatch(mentity, name.levenshtein_distance(mentity.full_name))
378 end
379 return results
380 end
381
382 # Find all mentities that matches `name`
383 #
384 # 1. try by name prefix
385 # 2. add full name prefix matches
386 # 3. try similarity by name
387 # 4. try similarity by full_name
388 fun find(name: String): IndexMatches do
389 var results = find_by_name_prefix(name)
390
391 for result in find_by_full_name_prefix(name) do
392 results.add result
393 end
394
395 for mentity in mentities do
396 if mentity isa MClassDef or mentity isa MPropDef then continue
397 results.add new IndexMatch(mentity, name.levenshtein_distance(mentity.name))
398 results.add new IndexMatch(mentity, name.levenshtein_distance(mentity.full_name))
399 end
400 return results
401 end
402 end
403
404 # An array of IndexMatch instances returned by the ModelIndex
405 #
406 # Index matches can be sorted, filtered and truncated.
407 #
408 # Thanks to the fluent interface, the index matches can be manipulated in chain
409 # from a model index query:
410 #
411 # ~~~nitish
412 # var res = index.find("Foo").
413 # uniq.
414 # sort(new ScoreComparator, new MEntityComparator).
415 # limit(10).
416 # sort(new VisibilityComparator)
417 # ~~~
418 class IndexMatches
419 super Array[IndexMatch]
420
421 # Create a new ModelMatches from an array of matches
422 #
423 # Elements are copied.
424 init from_matches(matches: Array[IndexMatch]) do self.add_all matches
425
426 # Sort the matches with `comparator` (or a list of comparators)
427 #
428 # Return a new IndexMatches instance with the sorted results.
429 #
430 # When more than one comparator is given, the comparators are applied in a
431 # pipeline where the `n`th comparator is applied only if the `n-1`th comparator
432 # returned 0.
433 fun sort(comparator: ScoreComparator...): IndexMatches do
434 var res = to_a
435 if comparator.length == 1 then
436 comparator.first.sort res
437 else
438 var comparators = new MatchComparators(comparator)
439 comparators.sort res
440 end
441 return new IndexMatches.from_matches(res)
442 end
443
444 # Limit the matches with `limit`
445 #
446 # Return a new IndexMatches instance with only the `limit` first matches.
447 fun limit(limit: Int): IndexMatches do
448 var res = new Array[IndexMatch]
449 for match in self do
450 if res.length >= limit then break
451 res.add match
452 end
453 return new IndexMatches.from_matches(res)
454 end
455
456 # Remove doublons from the matches
457 #
458 # Preverse the lowest score of all the matches for a MEntity.
459 fun uniq: IndexMatches do
460 var scores = new HashMap[MEntity, IndexMatch]
461 var res = new Array[IndexMatch]
462 for match in self do
463 var mentity = match.mentity
464 if scores.has_key(mentity) then
465 var older = scores[mentity]
466 if match.score < older.score then older.score = match.score
467 else
468 scores[mentity] = match
469 res.add match
470 end
471 end
472 return new IndexMatches.from_matches(res)
473 end
474
475 # Reset score of each matches to follow `self` order
476 #
477 # Usefull when you need to apply one sorter over another.
478 fun rerank: IndexMatches do
479 var res = new IndexMatches
480 for match in self do
481 res.add match
482 match.score = res.length
483 end
484 return res
485 end
486
487 # Aggregate the mentities for all the matches
488 #
489 # Preserve the match order.
490 fun mentities: Array[MEntity] do
491 var res = new Array[MEntity]
492 for match in self do res.add match.mentity
493 return res
494 end
495 end
496
497 # An MEntity matched from a ModelIndex
498 #
499 # Each match has a `score`. The score should be seen as the distance of
500 # the match from the query. In other words, the lowest is the score, the more
501 # relevant is the match.
502 class IndexMatch
503 super Comparable
504
505 redef type OTHER: IndexMatch
506
507 # MEntity matches
508 var mentity: MEntity
509
510 # Score allocated by the search method
511 #
512 # A lowest score means a more relevant match.
513 #
514 # Scores values are arbitrary, the meaning of `10` vs `2000` really depends
515 # on the search method producing the match and the comparators used to sort
516 # the matches.
517 # The only universal rule is: low score = relevance.
518 var score: Int is writable
519
520 # By default matches are compared only on their score
521 redef fun <=>(o) do return score <=> o.score
522
523 redef fun to_s do return "{mentity} ({score})"
524 end
525
526 # Compare two matches by their score
527 #
528 # Since the score can be seen as a distance, we want the lowest score first.
529 class ScoreComparator
530 super Comparator
531
532 redef type COMPARED: IndexMatch
533
534 redef fun compare(o1, o2) do return o1.score <=> o2.score
535 end
536
537 # A pipeline of comparators executed in inclusion order
538 #
539 # This class is used internally to agregate the behaviors of multiple comparators.
540 # Use `IndexMatches::sort(comparator...)` instead.
541 private class MatchComparators
542 super ScoreComparator
543
544 # Comparator to use in the array order
545 var comparators: Array[ScoreComparator]
546
547 # Compare with each comparator
548 #
549 # Return the compare value of the first one to return anything else than 0.
550 redef fun compare(o1, o2) do
551 for comparator in comparators do
552 var c = comparator.compare(o1, o2)
553 if c != 0 then return c
554 end
555 return 0
556 end
557 end
558
559 # Compare two matches by their MEntity kind
560 #
561 # Usefull to order the mentities by kind in this order:
562 # packages, groups, modules and classes, properties.
563 class MEntityComparator
564 super ScoreComparator
565
566 # See `MEntity::compare_mentity`
567 redef fun compare(o1, o2) do
568 return o1.mentity.mentity_kind_rank <=> o2.mentity.mentity_kind_rank
569 end
570 end
571
572 # Compare two matches by their MEntity visibility
573 #
574 # We reverse the original order so private is at the end of the list.
575 class VisibilityComparator
576 super ScoreComparator
577
578 redef fun compare(o1, o2) do return o2.mentity.visibility <=> o1.mentity.visibility
579 end
580
581 # Compare two matches by their name in lexicographic order
582 #
583 # Generally, for a same score, we want to put A before Z.
584 class NameComparator
585 super ScoreComparator
586
587 redef fun compare(o1, o2) do return o1.mentity.name <=> o2.mentity.name
588 end
589
590 # Compare two matches by their name length
591 class NameLengthComparator
592 super ScoreComparator
593
594 redef fun compare(o1, o2) do return o1.mentity.name.length <=> o2.mentity.name.length
595 end
596
597 # Compare two matches by their full_name in lexicographic order
598 #
599 # Generally, for a same score, we want to put A before Z.
600 class FullNameComparator
601 super ScoreComparator
602
603 redef fun compare(o1, o2) do return o1.mentity.full_name <=> o2.mentity.full_name
604 end
605
606 # Compare two matches by their full name length
607 class FullNameLengthComparator
608 super ScoreComparator
609
610 redef fun compare(o1, o2) do return o1.mentity.full_name.length <=> o2.mentity.full_name.length
611 end
612
613 redef class MEntity
614
615 # Compare MEntity class kind
616 #
617 # Unknown kind have a virtually high score.
618 private fun mentity_kind_rank: Int do return 10
619 end
620
621 redef class MPackage
622 redef fun mentity_kind_rank do return 1
623 end
624
625 redef class MGroup
626 redef fun mentity_kind_rank do return 2
627 end
628
629 redef class MModule
630 redef fun mentity_kind_rank do return 3
631 end
632
633 redef class MClass
634 redef fun mentity_kind_rank do return 4
635 end
636
637 redef class MClassDef
638 redef fun mentity_kind_rank do return 5
639 end
640
641 redef class MProperty
642 redef fun mentity_kind_rank do return 6
643 end
644
645 redef class MPropDef
646 redef fun mentity_kind_rank do return 7
647 end