Skip to content

Instantly share code, notes, and snippets.

@maliqq
Created March 5, 2010 11:55
Show Gist options
  • Save maliqq/322662 to your computer and use it in GitHub Desktop.
Save maliqq/322662 to your computer and use it in GitHub Desktop.
module LineNumber
class Tag < Struct.new(:name, :close, :line, :in_script)
end
class LineNumber
attr_reader :tags
def self.parse(str)
parser = self.new(str)
return parser.parse
end
def initialize(str)
@str = str
@tags = []
end
def parse
@pos = 0
@len = @str.length
tokens = {
'<' => 0,
'/' => 1,
'>' => 2
}
flags = {
# 0 1 2 3 4
0 => [1, 0, 0, 0, 0], #
1 => [0, 2, 0, 3, 0], # <
2 => [0, 0, 0, 4, 0], # </
3 => [0, 0, 5, 3, 5], # <t
4 => [0, 0, 6, 4, 0], # </t
5 => [1, 0, 0, 0, 0], # <tag...
6 => [1, 0, 0, 0, 0] # </tag>
}
@log = ""
@buf = ""
current = 0
line = 1
in_script = false
while @pos < @len
ch = @str[@pos].chr
line += 1 if ch == "\n"
token = ch =~ /[a-z0-9]/i ? 3 : (tokens[ch] || 4)
flag = flags[current][token]
case flag
when 0
when 1
@buf = ""
when 2
@buf = ""
when 3
@buf += ch
when 4
@buf += ch
when 5
@tags << Tag.new(@buf, false, line, in_script)
in_script = true if @buf == 'script'
@buf = ""
when 6
@tags << Tag.new(@buf, true, line, in_script)
in_script = false if @buf == 'script'
@buf = ""
end
current = flag
@pos += 1
end
return @tags
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment