Debian Codegraph @

texmf-dist/tex/luatex/luaxml/luaxml-mod-xml.lua

raw
1 -- module(...,package.seeall)
2 ---
3 -- Overview:
4 -- =========
5 --
6 -- This module provides a non-validating XML stream parser in Lua.
7 --
8 -- Features:
9 -- =========
10 --
11 -- * Tokenises well-formed XML (relatively robustly)
12 -- * Flexible handler based event api (see below)
13 -- * Parses all XML Infoset elements - ie.
14 -- - Tags
15 -- - Text
16 -- - Comments
17 -- - CDATA
18 -- - XML Decl
19 -- - Processing Instructions
20 -- - DOCTYPE declarations
21 -- * Provides limited well-formedness checking
22 -- (checks for basic syntax & balanced tags only)
23 -- * Flexible whitespace handling (selectable)
24 -- * Entity Handling (selectable)
25 --
26 -- Limitations:
27 -- ============
28 --
29 -- * Non-validating
30 -- * No charset handling
31 -- * No namespace support
32 -- * Shallow well-formedness checking only (fails
33 -- to detect most semantic errors)
34 --
35 -- API:
36 -- ====
37 --
38 -- The parser provides a partially object-oriented API with
39 -- functionality split into tokeniser and handler components.
40 --
41 -- The handler instance is passed to the tokeniser and receives
42 -- callbacks for each XML element processed (if a suitable handler
43 -- function is defined). The API is conceptually similar to the
44 -- SAX API but implemented differently.
45 --
46 -- The following events are generated by the tokeniser
47 --
48 -- handler:start - Start Tag
49 -- handler:end - End Tag
50 -- handler:text - Text
51 -- handler:decl - XML Declaration
52 -- handler:pi - Processing Instruction
53 -- handler:comment - Comment
54 -- handler:dtd - DOCTYPE definition
55 -- handler:cdata - CDATA
56 --
57 -- The function prototype for all the callback functions is
58 --
59 -- callback(val,attrs,start,end)
60 --
61 -- where attrs is a table and val/attrs are overloaded for
62 -- specific callbacks - ie.
63 --
64 -- Callback val attrs (table)
65 -- -------- --- -------------
66 -- start name { attributes (name=val).. }
67 -- end name nil
68 -- text <text> nil
69 -- cdata <text> nil
70 -- decl "xml" { attributes (name=val).. }
71 -- pi pi name { attributes (if present)..
72 -- _text = <PI Text>
73 -- }
74 -- comment <text> nil
75 -- dtd root element { _root = <Root Element>,
76 -- _type = SYSTEM|PUBLIC,
77 -- _name = <name>,
78 -- _uri = <uri>,
79 -- _internal = <internal dtd>
80 -- }
81 --
82 -- (start & end provide the character positions of the start/end
83 -- of the element)
84 --
85 -- XML data is passed to the parser instance through the 'parse'
86 -- method (Nore: must be passed a single string currently)
87 --
88 -- Options
89 -- =======
90 --
91 -- Parser options are controlled through the 'self.options' table.
92 -- Available options are -
93 --
94 -- * stripWS
95 --
96 -- Strip non-significant whitespace (leading/trailing)
97 -- and do not generate events for empty text elements
98 --
99 -- * expandEntities
100 --
101 -- Expand entities (standard entities + single char
102 -- numeric entities only currently - could be extended
103 -- at runtime if suitable DTD parser added elements
104 -- to table (see obj._ENTITIES). May also be possible
105 -- to expand multibyte entities for UTF-8 only
106 --
107 -- * errorHandler
108 --
109 -- Custom error handler function
110 --
111 -- NOTE: Boolean options must be set to 'nil' not '0'
112 --
113 -- Usage
114 -- =====
115 --
116 -- Create a handler instance -
117 --
118 -- h = { start = function(t,a,s,e) .... end,
119 -- end = function(t,a,s,e) .... end,
120 -- text = function(t,a,s,e) .... end,
121 -- cdata = text }
122 --
123 -- (or use predefined handler - see handler.lua)
124 --
125 -- Create parser instance -
126 --
127 -- p = xmlParser(h)
128 --
129 -- Set options -
130 --
131 -- p.options.xxxx = nil
132 --
133 -- Parse XML data -
134 --
135 -- xmlParser:parse("<?xml... ")
136 -- License:
137 -- ========
138 --
139 -- This code is freely distributable under the terms of the Lua license
140 -- (http://www.lua.org/copyright.html)
141 --
142 -- History
143 -- =======
144 -- Fixed some errors in DTD matching
145 -- Added functions serialize and xmlEscape
146 -- by Michal Hoftich
147 -- 2012/07/26
148 --
149 -- Added parameter parseAttributes (boolean) in xmlParser.parse method
150 -- If true, tag attributtes are parsed. The default value is true.
151 -- by Manoel Campos (https://about.me/manoelcampos)
152 --
153 -- $Id: xml.lua,v 1.1.1.1 2001/11/28 06:11:33 paulc Exp $
154 --
155 -- $Log: xml.lua,v $
156 -- Revision 1.1.1.1 2001/11/28 06:11:33 paulc
157 -- Initial Import
158 --
159 --@author Paul Chakravarti ([email protected])<p/>
160
161 local format= string.format
162 ---Parses a XML string
163 --@param handler Handler object to be used to convert the XML string
164 --to another formats. @see handler.lua
165 local M={}
166 local xmlParser = function(handler)
167 local obj = {}
168 -- Public attributes
169
170 obj.options = {
171 stripWS = 1,
172 expandEntities = 1,
173 voidElements = {},
174 errorHandler = function(err,pos)
175 error(format("%s [char=%d]\n",
176 err or "Parse Error",pos))
177 end,
178
179 }
180
181 -- Public methods
182
183 obj.parse = function(self, str, parseAttributes)
184 if parseAttributes == nil then
185 parseAttributes = true
186 end
187 self._handler.parseAttributes = parseAttributes
188 local handler_options = self._handler.options or {}
189 local void_elements = handler_options.voidElements or {}
190
191 local match,endmatch,pos = 0,0,1
192 local text,endt1,endt2,tagstr,tagname,attrs,starttext,endtext
193 local errstart,errend,extstart,extend
194 while match do
195 -- Get next tag (first pass - fix exceptions below)
196 match,endmatch,text,endt1,tagstr,endt2 = string.find(str,self._XML,pos)
197 if not match then
198 if string.find(str,self._WS,pos) then
199 -- No more text - check document complete
200 if #self._stack ~= 0 then
201 self:_err(self._errstr.incompleteXmlErr,pos)
202 else
203 break
204 end
205 else
206 -- Unparsable text
207 self:_err(self._errstr.xmlErr,pos)
208 end
209 end
210 -- Handle leading text
211 starttext = match
212 endtext = match + string.len(text) - 1
213 match = match + string.len(text)
214 text = self:_parseEntities(self:_stripWS(text))
215 if text ~= "" and self._handler.text then
216 self._handler:text(text,nil,match,endtext)
217 end
218 -- Test for tag type
219 if string.find(string.sub(tagstr,1,5),"?xml%s") then
220 -- XML Declaration
221 match,endmatch,text = string.find(str,self._PI,pos)
222 if not match then
223 self:_err(self._errstr.declErr,pos)
224 end
225 if match ~= 1 then
226 -- Must be at start of doc if present
227 self:_err(self._errstr.declStartErr,pos)
228 end
229 tagname,attrs = self:_parseTag(text)
230 -- TODO: Check attributes are valid
231 -- Check for version (mandatory)
232 if attrs.version == nil then
233 self:_err(self._errstr.declAttrErr,pos)
234 end
235 if self._handler.decl then
236 self._handler:decl(tagname,attrs,match,endmatch)
237 end
238 elseif string.sub(tagstr,1,1) == "?" then
239 -- Processing Instruction
240 match,endmatch,text = string.find(str,self._PI,pos)
241 if not match then
242 self:_err(self._errstr.piErr,pos)
243 end
244 if self._handler.pi then
245 -- Parse PI attributes & text
246 tagname,attrs = self:_parseTag(text)
247 local pi = string.sub(text,string.len(tagname)+1)
248 if pi ~= "" then
249 if attrs then
250 attrs._text = pi
251 else
252 attrs = { _text = pi }
253 end
254 end
255 self._handler:pi(tagname,attrs,match,endmatch)
256 end
257 elseif string.sub(tagstr,1,3) == "!--" then
258 -- Comment
259 match,endmatch,text = string.find(str,self._COMMENT,pos)
260 if not match then
261 self:_err(self._errstr.commentErr,pos)
262 end
263 if self._handler.comment then
264 text = self:_parseEntities(self:_stripWS(text))
265 self._handler:comment(text,next,match,endmatch)
266 end
267 elseif string.sub(tagstr,1,8) == "!DOCTYPE" then
268 -- DTD
269 --match,endmatch,attrs = self:_parseDTD(string,pos)
270 match,endmatch,attrs = self:_parseDTD(str,pos)
271 if not match then
272 self:_err(self._errstr.dtdErr,pos)
273 end
274 if self._handler.dtd then
275 self._handler:dtd(attrs._root,attrs,match,endmatch)
276 end
277 elseif string.sub(tagstr,1,8) == "![CDATA[" then
278 -- CDATA
279 match,endmatch,text = string.find(str,self._CDATA,pos)
280 if not match then
281 self:_err(self._errstr.cdataErr,pos)
282 end
283 if self._handler.cdata then
284 self._handler:cdata(text,nil,match,endmatch)
285 end
286 else
287 -- Normal tag
288
289 -- Need theck for embedded '>' in attribute value and extend
290 -- match recursively if necessary eg. <tag attr="123>456">
291
292 while 1 do
293 errstart,errend = string.find(tagstr,self._ATTRERR1)
294 if errend == nil then
295 errstart,errend = string.find(tagstr,self._ATTRERR2)
296 if errend == nil then
297 break
298 end
299 end
300 local errorstring = tagstr:sub(errstart, errend)
301 -- it seems that it causes error if an attribute starts with `=`
302 if errorstring:match("^=") then break end
303
304 extstart,extend,endt2 = string.find(str,self._TAGEXT,endmatch+1)
305 if not extstart then break end
306
307 tagstr = tagstr .. string.sub(str,endmatch,extend-1)
308 if not match then
309 self:_err(self._errstr.xmlErr,pos)
310 end
311 endmatch = extend
312 end
313
314 -- Extract tagname/attrs
315
316 tagname,attrs = self:_parseTag(tagstr)
317
318 if (endt1=="/") then
319 -- End tag
320 if self._handler.endtag then
321 if attrs then
322 -- Shouldn't have any attributes in endtag
323 self:_err(format("%s (/%s)",
324 self._errstr.endTagErr,
325 tagname)
326 ,pos)
327 end
328 if table.remove(self._stack) ~= tagname then
329 self:_err(format("%s (/%s)",
330 self._errstr.unmatchedTagErr,
331 tagname)
332 ,pos)
333 end
334 self._handler:endtag(tagname,nil,match,endmatch)
335 end
336 else
337 -- Start Tag
338 table.insert(self._stack,tagname)
339 if self._handler.starttag then
340 self._handler:starttag(tagname,attrs,match,endmatch)
341 end
342 -- Self-Closing Tag. Skip void elements
343 if (endt2=="/") and not void_elements[tagname] then
344 table.remove(self._stack)
345 if self._handler.endtag then
346 self._handler:endtag(tagname,nil,match,endmatch)
347 end
348 end
349 end
350 end
351 pos = endmatch + 1
352 end
353 end
354
355 -- Private attrobures/functions
356
357 obj._handler = handler
358 handler._xml = obj
359 obj._stack = {}
360
361 obj._XML = '^([^<]*)<(%/?)([^>]-)(%/?)>'
362 obj._ATTR1 = '([%w-:_]+)%s*=%s*"(.-)"'
363 obj._ATTR2 = '([%w-:_]+)%s*=%s*\'(.-)\''
364 obj._CDATA = '<%!%[CDATA%[(.-)%]%]>'
365 obj._PI = '<%?(.-)%?>'
366 obj._COMMENT = '<!%-%-(.-)%-%->'
367 obj._TAG = '^(.-)%s.*'
368 obj._LEADINGWS = '^%s+'
369 obj._TRAILINGWS = '%s+$'
370 obj._WS = '^%s*$'
371 local allowed_element_name_pattern = "[%w_%.%-]+"
372 obj._DTD1 = '<!DOCTYPE%s+(' .. allowed_element_name_pattern .. ')%s+(SYSTEM)%s+["\'](.-)["\']%s*(%b[])%s*>'
373 obj._DTD2 = '<!DOCTYPE%s+(' .. allowed_element_name_pattern .. ')%s+(PUBLIC)%s+["\'](.-)["\']%s+["\'](.-)["\']%s*(%b[])%s*>'
374 obj._DTD3 = '<!DOCTYPE%s+(' .. allowed_element_name_pattern .. ')%s*(%b[])%s*>'
375 obj._DTD4 = '<!DOCTYPE%s+(' .. allowed_element_name_pattern .. ')%s+(SYSTEM)%s+["\'](.-)["\']%s*>'
376 obj._DTD5 = '<!DOCTYPE%s+(' .. allowed_element_name_pattern .. ')%s+(PUBLIC)%s+["\'](.-)["\']%s+["\'](.-)["\']%s*>'
377 obj._DTD6 = '<!DOCTYPE%s+(' .. allowed_element_name_pattern .. ')%s*>'
378 --obj._DTD6 = "<!DOCTYPE%s+(.-)%s+(PUBLIC)%s+[\"'](.-)[\"']%s+[\"'](.-)[\"']%s*>"
379
380 obj._ATTRERR1 = '=%s*"[^"]*$'
381 obj._ATTRERR2 = '=%s*\'[^\']*$'
382 obj._TAGEXT = '(%/?)>'
383
384 obj._ENTITIES = { ["&lt;"] = "<",
385 ["&gt;"] = ">",
386 ["&amp;"] = "&",
387 ["&quot;"] = '"',
388 ["&apos;"] = "'",
389 ["&#(%d+);"] = function (x)
390 local d = tonumber(x)
391 if d >= 0 and d < 256 then
392 return string.char(d)
393 else
394 return "&#"..d..";"
395 end
396 end,
397 ["&#x(%x+);"] = function (x)
398 local d = tonumber(x,16)
399 if d >= 0 and d < 256 then
400 return string.char(d)
401 else
402 return "&#x"..x..";"
403 end
404 end,
405 }
406
407 obj._err = function(self,err,pos)
408 if self.options.errorHandler then
409 self.options.errorHandler(err,pos)
410 end
411 end
412
413 obj._errstr = { xmlErr = "Error Parsing XML",
414 declErr = "Error Parsing XMLDecl",
415 declStartErr = "XMLDecl not at start of document",
416 declAttrErr = "Invalid XMLDecl attributes",
417 piErr = "Error Parsing Processing Instruction",
418 commentErr = "Error Parsing Comment",
419 cdataErr = "Error Parsing CDATA",
420 dtdErr = "Error Parsing DTD",
421 endTagErr = "End Tag Attributes Invalid",
422 unmatchedTagErr = "Unbalanced Tag",
423 incompleteXmlErr = "Incomplete XML Document",
424 }
425
426 obj._stripWS = function(self,s)
427 if self.options.stripWS then
428 s = string.gsub(s,'^%s+','')
429 s = string.gsub(s,'%s+$','')
430 end
431 return s
432 end
433
434 obj._parseEntities = function(self,s)
435 if self.options.expandEntities then
436 --for k,v in self._ENTITIES do
437 for k,v in pairs(self._ENTITIES) do
438 --print (k, v)
439 s = string.gsub(s,k,v)
440 end
441 end
442 return s
443 end
444
445 obj._parseDTD = function(self,s,pos)
446 -- match,endmatch,root,type,name,uri,internal
447 --print(s.." : "..pos)
448 local m,e,r,t,n,u,i
449 m,e,r,t,n,u = string.find(s,self._DTD5,pos)
450 if m then
451 return m,e,{_root=r,_type=t,_name=n,_uri=u}
452 end
453 m,e,r,t,u,i = string.find(s,self._DTD1,pos)
454 if m then
455 return m,e,{_root=r,_type=t,_uri=u,_internal=i}
456 end
457 m,e,r,t,n,u,i = string.find(s,self._DTD2,pos)
458 if m then
459 return m,e,{_root=r,_type=t,_name=n,_uri=u,_internal=i}
460 end
461 m,e,r,i = string.find(s,self._DTD3,pos)
462 if m then
463 return m,e,{_root=r,_internal=i}
464 end
465 m,e,r,t,u = string.find(s,self._DTD4,pos)
466 if m then
467 return m,e,{_root=r,_type=t,_uri=u}
468 end
469 m,e,r = string.find(s, self._DTD6, pos)
470 if m then
471 return m,e, {_root=r }
472 end
473 return nil
474 end
475
476 obj._parseTag = function(self,s)
477 local attrs = {}
478 local tagname = string.gsub(s,self._TAG,'%1')
479 string.gsub(s,self._ATTR1,function (k,v)
480 attrs[string.lower(k)]=self:_parseEntities(v)
481 attrs._ = 1
482 end)
483 string.gsub(s,self._ATTR2,function (k,v)
484 attrs[string.lower(k)]=self:_parseEntities(v)
485 attrs._ = 1
486 end)
487 if attrs._ then
488 attrs._ = nil
489 else
490 attrs = nil
491 end
492 return tagname,attrs
493 end
494
495 return obj
496
497 end
498 M.xmlParser = xmlParser
499
500 local function xmlEscape(s)
501 local t = {['"']="&quot;",["'"]="&apos;",["&"]="&amp;",["<"]="&lt;",[">"]="&gt;"}
502 return string.gsub(s,"([\"'<>&])",t)
503 end
504
505 M.xmlEscape = xmlEscape
506
507
508 local function serialize(tb)
509 local function getAttributes(k,v)
510 local i = ""
511 if(type(v["_attr"])=="table") then
512 -- texio.write_nl("attr")
513 for p,n in pairs(v["_attr"]) do
514 i = i ..' '.. p .. '="'..xmlEscape(n)..'"'
515 end
516 --table.remove(v,"_attr")
517 end
518 return i
519 end
520
521 local function printable(tb, level,currTag)
522 local r ={}
523 local currTag = currTag or ""
524 level = level or 0
525 local spaces = string.rep(' ', level*2)
526 for k,v in pairs(tb) do
527 if type(v) ~= "table" then
528 local ct = k
529 if type(k)=="number" then
530 ct = currTag
531 end
532 if ct == "" then
533 table.insert(r,spaces .. xmlEscape(v).."\n")
534 else
535 local i = getAttributes(k,v)
536 table.insert(r,spaces .. '<'..ct..i..'>'..xmlEscape(v)..'</'..ct..'>'.."\n")
537 end
538 else
539 if k == "_attr" then
540 --table.insert(r,printable(v, level))
541 else
542 if type(k)=="string" then
543 --currTag = k
544 if type(k)=="numeric" then
545 k = currTag
546 end
547 if #v > 1 then
548 table.insert(r,printable(v, level+1,k))
549 else
550 local i = getAttributes(k,v)
551 table.insert(r,spaces.."<"..k..i..">\n")
552 table.insert(r,printable(v, level+1,k))
553 table.insert(r,spaces.."</"..k..">\n")
554 end
555 else
556 local i = getAttributes(k,v)
557 table.insert(r,spaces .. "<"..currTag..i..">\n")
558 --level = level + 1
559 table.insert(r,printable(v, level+1))
560 table.insert(r,spaces .. "</"..currTag..">\n")
561 end
562 end
563 end
564 end
565 return table.concat(r,"")
566 end
567 return table.concat({'<?xml version="1.0" encoding="UTF-8"?>',printable(tb)},"\n")
568 end
569 M.serialize = serialize
570 return M