removed overload system
[lqt.git] / new / xml.lua
blobb4b408445519459453a41836ae9faeecf6a28860
1 #!/usr/bin/lua
3 local parseargs, collect, strip_escapes
5 strip_escapes = function (s)
6 s = string.gsub(s, '>', '>')
7 s = string.gsub(s, '&lt;', '<')
8 return s
9 end
12 function parseargs(s)
13 local arg = {}
14 string.gsub(s, "([%w_]+)=([\"'])(.-)%2", function (w, _, a)
15 arg[strip_escapes(w)] = strip_escapes(a)
16 end)
17 return arg
18 end
20 function collect(s)
21 local stack = {}
22 local idindex = {}
23 local top = {}
24 table.insert(stack, top)
25 local ni,c,label,xarg, empty
26 local i, j = 1, 1
27 while true do
28 ni,j,c,label,xarg, empty = string.find(s, "<(%/?)(%w+)(.-)(%/?)>", j)
29 if not ni then break end
30 local text = string.sub(s, i, ni-1)
31 if not string.find(text, "^%s*$") then
32 table.insert(top, text)
33 end
34 if empty == "/" then -- empty element tag
35 table.insert(top, {label=label, xarg=parseargs(xarg), empty=1})
36 elseif c == "" then -- start tag
37 top = {label=label, xarg=parseargs(xarg)}
38 table.insert(stack, top) -- new level
39 else -- end tag
40 local toclose = table.remove(stack) -- remove top
41 top = stack[#stack]
42 if #stack < 1 then
43 error("nothing to close with "..label)
44 end
45 if toclose.label ~= label then
46 error("trying to close "..toclose.label.." with "..label)
47 end
48 table.insert(top, toclose)
49 toclose.parent = top
50 if toclose.xarg.id then
51 idindex[toclose.xarg.id] = toclose
52 end
53 end
54 i = j+1
55 end
56 local text = string.sub(s, i)
57 if not string.find(text, "^%s*$") then
58 table.insert(stack[#stack], text)
59 end
60 if #stack > 1 then
61 error("unclosed "..stack[stack.n].label)
62 end
63 return stack[1], idindex
64 end
66 return collect