Class: LangScan::EasyScanner

Inherits:
Object
  • Object
show all
Defined in:
lib/langscan/_easyscanner.rb

Instance Method Summary collapse

Constructor Details

#initialize(pattern, types, keywords) ⇒ EasyScanner

Returns a new instance of EasyScanner.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/langscan/_easyscanner.rb', line 16

def initialize(pattern, types, keywords)
  @pattern = pattern

  # build regexp
  regexp = "(\n)|" + @pattern.map {|v| "(" + v[1] + ")"}.join("|")
  @regexp = Regexp.new(regexp)

  # build type hash
  @type = {}
  types.each {|k| @type[k] = true }

  # build keyword hash
  @keyword = {}
  keywords.each {|k| @keyword[k] = true }
end

Instance Method Details

#scan(input, &block) ⇒ Object



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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/langscan/_easyscanner.rb', line 32

def scan(input, &block)
  lineno = 0
  offset = 0
  while match = @regexp.match(input[offset..-1])
    if match[1]
      # newline
      lineno += 1
      offset += match.end(0)
    else
      for i in 2..match.size-1
        if match[i]
          type = @pattern[i-2][0]
          byteno = offset + match.begin(0)
          if @pattern[i-2][2]
            # pattern with terminator
            start = offset + match.end(0)
            end_match = input[start..-1].match(@pattern[i-2][2])
            if end_match
              offset = start + end_match.end(0)
            else
              # not terminated! what should we do?
              offset = start
            end
          else
            # simple pattern
            offset += match.end(0)
          end
          text = input[byteno..offset-1]
          if type == :ident
            case true
            when @type[text]
              type = :type
            when @keyword[text]
              type = :keyword
            end
          end
          yield(Fragment.new(type, text, lineno, byteno))
          lineno += text.count("\n")
          break
        end
      end
    end
  end
end