1 # This file is part of NIT ( http://www.nitlanguage.org ).
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # Search things from the Model
17 # ModelIndex allows you to index mentities then retrieve them by their `name`
19 # It offers a set of `find_*` methods that can be used to match queries
20 # against entities name.
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.
25 # ## Indexing mentities
27 # Before searching something from the ModelIndex, you have to index it.
28 # Use the `ModelIndex::index` method to do that:
31 # var index = new ModelIndex
32 # for mentity in model.collect_mentities do
33 # index.index(mentity)
39 # You can then run queries on the ModelIndex:
42 # for res in index.find("Array").limit(10) do
49 # Here some examples of how you can use the ModelIndex.
51 # ### Smart type prediction
53 # Use ModelIndex to implement a smart prediction system based on the typed prefix:
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)
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
72 # Will output something like:
82 # ### Method autocompletion
84 # Find methods from a class full_name:
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
97 # Will output something like:
107 # ### Name typo detection and suggestion
109 # Detect unknown names and suggest corrections:
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 ")
121 # Will output something like:
124 # `Zrray` not found, did you mean: Array (1) or array (1)?
128 import model
::model_collect
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
139 return mentities_by_full_name
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
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
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
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
180 # Search mentities based on a `query` string
182 # Lookup the index for anything matching `query` and return `limit` results.
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
189 # At each step if the `limit` is reached, the algorithm stops and returns the results.
190 fun find
(query
: String, limit
: nullable Int, filter
: nullable ModelFilter): Array[MEntity] do
191 # Find, lookup by name prefix
192 var matches
= index
.find_by_name_prefix
(query
, filter
).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
197 matches
= matches
.rerank
.sort
(vis_sorter
, score_sorter
)
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
, filter
).
203 sort
(kind_sorter
, lfname_sorter
, fname_sorter
) do
205 full_matches
.add match
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
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
, filter
).sort
(score_sorter
, kind_sorter
, lname_sorter
, name_sorter
) do
219 sim_matches
.add match
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
228 # ModelIndex indexes mentities by their name and full name
230 # It provides methods to find mentities based on a prefix or string similarity.
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)
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})"
246 # List of all indexed mentities.
248 # Faster than traversing the tries.
249 var mentities
= new Array[MEntity]
251 # Prefix tree for mentities `name`
253 # Because multiple mentities can share the same `name`, we use a Trie of
254 # arrays of mentities.
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]]
260 # Prefix tree for mentities `full_name`
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]]
266 # Index `mentity` by it's `MEntity::name`
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]
274 name_prefixes
[name
].add mentity
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]
283 full_name_prefixes
[name
].add mentity
286 # Index `mentity` so it can be retrieved by a find query
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
295 # Translate Trie results to `SearchResult`
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.
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]], filter
: nullable ModelFilter): IndexMatches do
304 var results
= new IndexMatches
306 for mentities
in array
do
307 for mentity
in mentities
do
308 if filter
!= null and not filter
.accept_mentity
(mentity
) then continue
309 results
.add
new IndexMatch(mentity
, score
)
316 # Find all mentities where `MEntity::name` matches the `prefix`
317 fun find_by_name_prefix
(prefix
: String, filter
: nullable ModelFilter): IndexMatches do
318 return score_results_incremental
(name_prefixes
.find_by_prefix
(prefix
), filter
)
321 # Find all mentities where `MEntity::full_name` matches the `prefix`
322 fun find_by_full_name_prefix
(prefix
: String, filter
: nullable ModelFilter): IndexMatches do
323 return score_results_incremental
(full_name_prefixes
.find_by_prefix
(prefix
), filter
)
326 # Rank all mentities by the distance between `MEntity::name` and `name`
328 # Use the Levenshtein algorithm on all the indexed mentities `name`.
329 # Warning: may not scale to large indexes.
330 fun find_by_name_similarity
(name
: String, filter
: nullable ModelFilter): IndexMatches do
331 var results
= new IndexMatches
332 for mentity
in mentities
do
333 if filter
!= null and not filter
.accept_mentity
(mentity
) then continue
334 if mentity
isa MClassDef or mentity
isa MPropDef then continue
335 results
.add
new IndexMatch(mentity
, name
.levenshtein_distance
(mentity
.name
))
340 # Rank all mentities by the distance between `MEntity::full_name` and `full_name`
342 # Use the Levenshtein algorithm on all the indexed mentities `full_name`.
343 # Warning: may not scale to large indexes.
344 fun find_by_full_name_similarity
(name
: String, filter
: nullable ModelFilter): IndexMatches do
345 var results
= new IndexMatches
346 for mentity
in mentities
do
347 if filter
!= null and not filter
.accept_mentity
(mentity
) then continue
348 if mentity
isa MClassDef or mentity
isa MPropDef then continue
349 results
.add
new IndexMatch(mentity
, name
.levenshtein_distance
(mentity
.full_name
))
354 # Rank all mentities by the distance between `name` and both the mentity name and full name
355 fun find_by_similarity
(name
: String, filter
: nullable ModelFilter): IndexMatches do
356 var results
= new IndexMatches
357 for mentity
in mentities
do
358 if filter
!= null and not filter
.accept_mentity
(mentity
) then continue
359 if mentity
isa MClassDef or mentity
isa MPropDef then continue
360 results
.add
new IndexMatch(mentity
, name
.levenshtein_distance
(mentity
.name
))
361 results
.add
new IndexMatch(mentity
, name
.levenshtein_distance
(mentity
.full_name
))
366 # Find mentities by name trying first by prefix then by similarity
367 fun find_by_name
(name
: String, filter
: nullable ModelFilter): IndexMatches do
368 var results
= find_by_name_prefix
(name
)
369 for mentity
in mentities
do
370 if filter
!= null and not filter
.accept_mentity
(mentity
) then continue
371 if mentity
isa MClassDef or mentity
isa MPropDef then continue
372 results
.add
new IndexMatch(mentity
, name
.levenshtein_distance
(mentity
.name
))
377 # Find mentities by full name trying firt by prefix then by similarity
378 fun find_by_full_name
(name
: String, filter
: nullable ModelFilter): IndexMatches do
379 var results
= find_by_full_name_prefix
(name
)
380 for mentity
in mentities
do
381 if filter
!= null and not filter
.accept_mentity
(mentity
) then continue
382 if mentity
isa MClassDef or mentity
isa MPropDef then continue
383 results
.add
new IndexMatch(mentity
, name
.levenshtein_distance
(mentity
.full_name
))
388 # Find all mentities that matches `name`
390 # 1. try by name prefix
391 # 2. add full name prefix matches
392 # 3. try similarity by name
393 # 4. try similarity by full_name
394 fun find
(name
: String, filter
: nullable ModelFilter): IndexMatches do
395 var results
= find_by_name_prefix
(name
, filter
)
397 for result
in find_by_full_name_prefix
(name
, filter
) do
401 for mentity
in mentities
do
402 if filter
!= null and not filter
.accept_mentity
(mentity
) then continue
403 if mentity
isa MClassDef or mentity
isa MPropDef then continue
404 results
.add
new IndexMatch(mentity
, name
.levenshtein_distance
(mentity
.name
))
405 results
.add
new IndexMatch(mentity
, name
.levenshtein_distance
(mentity
.full_name
))
411 # An array of IndexMatch instances returned by the ModelIndex
413 # Index matches can be sorted, filtered and truncated.
415 # Thanks to the fluent interface, the index matches can be manipulated in chain
416 # from a model index query:
419 # var res = index.find("Foo").
421 # sort(new ScoreComparator, new MEntityComparator).
423 # sort(new VisibilityComparator)
426 super Array[IndexMatch]
428 # Create a new ModelMatches from an array of matches
430 # Elements are copied.
431 init from_matches
(matches
: Array[IndexMatch]) do self.add_all matches
433 # Sort the matches with `comparator` (or a list of comparators)
435 # Return a new IndexMatches instance with the sorted results.
437 # When more than one comparator is given, the comparators are applied in a
438 # pipeline where the `n`th comparator is applied only if the `n-1`th comparator
440 fun sort
(comparator
: ScoreComparator...): IndexMatches do
442 if comparator
.length
== 1 then
443 comparator
.first
.sort res
445 var comparators
= new MatchComparators(comparator
)
448 return new IndexMatches.from_matches
(res
)
451 # Limit the matches with `limit`
453 # Return a new IndexMatches instance with only the `limit` first matches.
454 fun limit
(limit
: Int): IndexMatches do
455 var res
= new Array[IndexMatch]
457 if res
.length
>= limit
then break
460 return new IndexMatches.from_matches
(res
)
463 # Remove doublons from the matches
465 # Preverse the lowest score of all the matches for a MEntity.
466 fun uniq
: IndexMatches do
467 var scores
= new HashMap[MEntity, IndexMatch]
468 var res
= new Array[IndexMatch]
470 var mentity
= match
.mentity
471 if scores
.has_key
(mentity
) then
472 var older
= scores
[mentity
]
473 if match
.score
< older
.score
then older
.score
= match
.score
475 scores
[mentity
] = match
479 return new IndexMatches.from_matches
(res
)
482 # Reset score of each matches to follow `self` order
484 # Usefull when you need to apply one sorter over another.
485 fun rerank
: IndexMatches do
486 var res
= new IndexMatches
489 match
.score
= res
.length
494 # Aggregate the mentities for all the matches
496 # Preserve the match order.
497 fun mentities
: Array[MEntity] do
498 var res
= new Array[MEntity]
499 for match
in self do res
.add match
.mentity
504 # An MEntity matched from a ModelIndex
506 # Each match has a `score`. The score should be seen as the distance of
507 # the match from the query. In other words, the lowest is the score, the more
508 # relevant is the match.
512 redef type OTHER: IndexMatch
517 # Score allocated by the search method
519 # A lowest score means a more relevant match.
521 # Scores values are arbitrary, the meaning of `10` vs `2000` really depends
522 # on the search method producing the match and the comparators used to sort
524 # The only universal rule is: low score = relevance.
525 var score
: Int is writable
527 # By default matches are compared only on their score
528 redef fun <=>(o
) do return score
<=> o
.score
530 redef fun to_s
do return "{mentity} ({score})"
533 # Compare two matches by their score
535 # Since the score can be seen as a distance, we want the lowest score first.
536 class ScoreComparator
539 redef type COMPARED: IndexMatch
541 redef fun compare
(o1
, o2
) do return o1
.score
<=> o2
.score
544 # A pipeline of comparators executed in inclusion order
546 # This class is used internally to agregate the behaviors of multiple comparators.
547 # Use `IndexMatches::sort(comparator...)` instead.
548 private class MatchComparators
549 super ScoreComparator
551 # Comparator to use in the array order
552 var comparators
: Array[ScoreComparator]
554 # Compare with each comparator
556 # Return the compare value of the first one to return anything else than 0.
557 redef fun compare
(o1
, o2
) do
558 for comparator
in comparators
do
559 var c
= comparator
.compare
(o1
, o2
)
560 if c
!= 0 then return c
566 # Compare two matches by their MEntity kind
568 # Usefull to order the mentities by kind in this order:
569 # packages, groups, modules and classes, properties.
570 class MEntityComparator
571 super ScoreComparator
573 # See `MEntity::compare_mentity`
574 redef fun compare
(o1
, o2
) do
575 return o1
.mentity
.mentity_kind_rank
<=> o2
.mentity
.mentity_kind_rank
579 # Compare two matches by their MEntity visibility
581 # We reverse the original order so private is at the end of the list.
582 class VisibilityComparator
583 super ScoreComparator
585 redef fun compare
(o1
, o2
) do return o2
.mentity
.visibility
<=> o1
.mentity
.visibility
588 # Compare two matches by their name in lexicographic order
590 # Generally, for a same score, we want to put A before Z.
592 super ScoreComparator
594 redef fun compare
(o1
, o2
) do return o1
.mentity
.name
<=> o2
.mentity
.name
597 # Compare two matches by their name length
598 class NameLengthComparator
599 super ScoreComparator
601 redef fun compare
(o1
, o2
) do return o1
.mentity
.name
.length
<=> o2
.mentity
.name
.length
604 # Compare two matches by their full_name in lexicographic order
606 # Generally, for a same score, we want to put A before Z.
607 class FullNameComparator
608 super ScoreComparator
610 redef fun compare
(o1
, o2
) do return o1
.mentity
.full_name
<=> o2
.mentity
.full_name
613 # Compare two matches by their full name length
614 class FullNameLengthComparator
615 super ScoreComparator
617 redef fun compare
(o1
, o2
) do return o1
.mentity
.full_name
.length
<=> o2
.mentity
.full_name
.length
622 # Compare MEntity class kind
624 # Unknown kind have a virtually high score.
625 private fun mentity_kind_rank
: Int do return 10
629 redef fun mentity_kind_rank
do return 1
633 redef fun mentity_kind_rank
do return 2
637 redef fun mentity_kind_rank
do return 3
641 redef fun mentity_kind_rank
do return 4
644 redef class MClassDef
645 redef fun mentity_kind_rank
do return 5
648 redef class MProperty
649 redef fun mentity_kind_rank
do return 6
653 redef fun mentity_kind_rank
do return 7