forked from rouge-ruby/rouge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
guesser.rb
57 lines (45 loc) · 1.31 KB
/
guesser.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# frozen_string_literal: true
module Rouge
class Guesser
class Ambiguous < StandardError
attr_reader :alternatives
def initialize(alternatives); @alternatives = alternatives; end
def message
"Ambiguous guess: can't decide between #{alternatives.map(&:tag).inspect}"
end
end
def self.guess(guessers, lexers)
original_size = lexers.size
guessers.each do |g|
new_lexers = case g
when Guesser then g.filter(lexers)
when proc { |x| x.respond_to? :call } then g.call(lexers)
else raise "bad guesser: #{g}"
end
lexers = new_lexers && new_lexers.any? ? new_lexers : lexers
end
# if we haven't filtered the input at *all*,
# then we have no idea what language it is,
# so we bail and return [].
lexers.size < original_size ? lexers : []
end
def collect_best(lexers, opts={}, &scorer)
best = []
best_score = opts[:threshold]
lexers.each do |lexer|
score = scorer.call(lexer)
next if score.nil?
if best_score.nil? || score > best_score
best_score = score
best = [lexer]
elsif score == best_score
best << lexer
end
end
best
end
def filter(lexers)
raise 'abstract'
end
end
end