summaryrefslogtreecommitdiff
path: root/lib/coderay/encoders/lint.rb
blob: 88c8bd1d590502d44c7c3e2b3bfbad59ead31473 (plain)
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
58
59
module CodeRay
module Encoders
  
  # = Lint Encoder
  #
  # Checks for:
  # 
  # - empty tokens
  # - incorrect nesting
  # 
  # It will raise an InvalidTokenStream exception when any of the above occurs.
  # 
  # See also: Encoders::DebugLint
  class Lint < Debug
    
    register_for :lint
    
    InvalidTokenStream         = Class.new StandardError
    EmptyToken                 = Class.new InvalidTokenStream
    UnknownTokenKind           = Class.new InvalidTokenStream
    IncorrectTokenGroupNesting = Class.new InvalidTokenStream
    
    def text_token text, kind
      raise EmptyToken,       'empty token for %p' % [kind] if text.empty?
      raise UnknownTokenKind, 'unknown token kind %p (text was %p)' % [kind, text] unless TokenKinds.has_key? kind
    end
    
    def begin_group kind
      @opened << kind
    end
    
    def end_group kind
      raise IncorrectTokenGroupNesting, 'We are inside %s, not %p (end_group)' % [@opened.reverse.map(&:inspect).join(' < '), kind] if @opened.last != kind
      @opened.pop
    end
    
    def begin_line kind
      @opened << kind
    end
    
    def end_line kind
      raise IncorrectTokenGroupNesting, 'We are inside %s, not %p (end_line)' % [@opened.reverse.map(&:inspect).join(' < '), kind] if @opened.last != kind
      @opened.pop
    end
    
    protected
    
    def setup options
      @opened = []
    end
    
    def finish options
      raise 'Some tokens still open at end of token stream: %p' % [@opened] unless @opened.empty?
    end
    
  end
  
end
end