Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Limit the number of symbol completion candidates and make it faster #41

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion lib/repl_type_completor/result.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def completion_candidates
in [:gvar, name, scope]
scope.global_variables
in [:symbol, name]
Symbol.all_symbols.map { _1.inspect[1..] }
filter_symbol_candidates(Symbol.all_symbols, name, limit: 100)
in [:call, name, type, self_call]
(self_call ? type.all_methods : type.methods).map(&:to_s) - HIDDEN_METHODS
in [:lvar_or_method, name, scope]
Expand Down Expand Up @@ -116,6 +116,25 @@ def doc_namespace(matched)

private

def filter_symbol_candidates(symbols, prefix, limit:)
sym_prefix = ":#{prefix}"
candidates = symbols.filter_map do |s|
next unless s.start_with?(prefix) # Fast and inaccurate check before calling inspect

inspect = s.inspect
inspect[1..] if inspect.start_with?(sym_prefix) # Reject `:"a b"` when completing `:a`
rescue EncodingError
# ignore
end

if candidates.size > limit
# min(n) + max(n) is faster than sort and slice
candidates.min(limit - limit / 2) + candidates.max(limit / 2).reverse
else
candidates.sort
end
end

def method_doc(type, name)
type = type.types.find { _1.all_methods.include? name.to_sym }
case type
Expand Down
10 changes: 10 additions & 0 deletions test/repl_type_completor/test_repl_type_completor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,16 @@ def test_symbol
assert_completion(prefix, include: sym.inspect.delete_prefix(prefix))
end

def test_symbol_limit
result = ReplTypeCompletor::Result.new([:symbol, 'sym'], binding, 'file')
symbols = [:ae, :ad, :ab1, :ab2, :ac, :aa, :b, :"a a", 75.chr('utf-7').to_sym]
assert_equal(%w[aa ab1 ab2 ac ad ae], result.send(:filter_symbol_candidates, symbols, 'a', limit: 100))
assert_equal(%w[aa ab1 ab2 ad ae], result.send(:filter_symbol_candidates, symbols, 'a', limit: 5))
assert_equal(%w[aa ab1 ad ae], result.send(:filter_symbol_candidates, symbols, 'a', limit: 4))
assert_equal(%w[ab1 ab2], result.send(:filter_symbol_candidates, symbols, 'ab', limit: 4))
assert_equal([], result.send(:filter_symbol_candidates, symbols, 'c', limit: 4))
end

def test_call
assert_completion('1.', include: 'abs')
assert_completion('1.a', include: 'bs')
Expand Down