Update BUILD
[lqt/mk.git] / generator / xml.lua
blobd8f1fbdaccf9ae86e1b73c1058f47776988e62a0
1 #!/usr/bin/lua
3 --[[
5 Copyright (c) 2007-2008 Mauro Iazzi
7 Permission is hereby granted, free of charge, to any person
8 obtaining a copy of this software and associated documentation
9 files (the "Software"), to deal in the Software without
10 restriction, including without limitation the rights to use,
11 copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the
13 Software is furnished to do so, subject to the following
14 conditions:
16 The above copyright notice and this permission notice shall be
17 included in all copies or substantial portions of the Software.
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
21 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
23 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
24 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
26 OTHER DEALINGS IN THE SOFTWARE.
28 --]]
31 local parseargs, collect
33 local escapes = {
34 amp = '&',
35 quot = '"',
36 apos = '\'',
37 gt = '>',
38 lt = '<',
41 local strip_escapes = function (s)
42 s = string.gsub(s, '&(%a+);', escapes)
43 s = string.gsub(s, '&amp;', '&')
44 return s
45 end
48 function parseargs(s)
49 local arg = {}
50 string.gsub(s, "([%w_]+)=([\"'])(.-)%2", function (w, _, a)
51 arg[strip_escapes(w)] = strip_escapes(a)
52 end)
53 return arg
54 end
56 function collect(s)
57 local stack = {}
58 local index = {}
59 local top = {}
60 table.insert(stack, top)
61 local ni,c,label,xarg, empty
62 local i, j = 1, 1
63 while true do
64 ni,j,c,label,xarg, empty = string.find(s, "<(%/?)(%w+)(.-)(%/?)>", j)
65 if not ni then break end
66 local text = string.sub(s, i, ni-1)
67 if not string.find(text, "^%s*$") then
68 table.insert(top, strip_escapes(text))
69 end
70 if empty == "/" then -- empty element tag
71 table.insert(top, {label=label, xarg=parseargs(xarg), empty=1})
72 elseif c == "" then -- start tag
73 top = {label=label, xarg=parseargs(xarg)}
74 table.insert(stack, top) -- new level
75 else -- end tag
76 local toclose = table.remove(stack) -- remove top
77 top = stack[#stack]
78 if #stack < 1 then
79 error("nothing to close with "..label)
80 end
81 if toclose.label ~= label then
82 error("trying to close "..toclose.label.." with "..label)
83 end
84 table.insert(top, toclose)
85 -- toclose.parent = top
86 toclose.index = #top
87 index[toclose] = true
88 end
89 i = j+1
90 end
91 local text = string.sub(s, i)
92 if not string.find(text, "^%s*$") then
93 table.insert(stack[#stack], text)
94 end
95 if #stack > 1 then
96 error("unclosed "..stack[#stack].label)
97 end
98 return stack[1], index
99 end
101 return collect