Doxygen
Loading...
Searching...
No Matches
xml.l
Go to the documentation of this file.
1/******************************************************************************
2 *
3 * Copyright (C) 1997-2020 by Dimitri van Heesch.
4 *
5 * Permission to use, copy, modify, and distribute this software and its
6 * documentation under the terms of the GNU General Public License is hereby
7 * granted. No representations are made about the suitability of this software
8 * for any purpose. It is provided "as is" without express or implied warranty.
9 * See the GNU General Public License for more details.
10 *
11 * Documents produced by Doxygen are derivative works derived from the
12 * input used in their production; they are not affected by this license.
13 *
14 */
15/******************************************************************************
16 * Minimal flex based parser for XML
17 ******************************************************************************/
18
19%option never-interactive
20%option prefix="xmlYY"
21%option reentrant
22%option extra-type="struct xmlYY_state *"
23%option 8bit noyywrap
24%top{
25#include <stdint.h>
26#define yyguts_t xmlYYguts_t
27}
28
29%{
30
31#include <ctype.h>
32#include <vector>
33#include <stdio.h>
34#include "xml.h"
35
36#define YY_NEVER_INTERACTIVE 1
37#define YY_NO_INPUT 1
38#define YY_NO_UNISTD_H 1
39
41{
42 std::string fileName;
43 int lineNr = 1;
44 const char * inputString = nullptr; //!< the code fragment as text
45 int inputPosition = 0; //!< read offset during parsing
46 std::string name;
47 bool isEnd = false;
48 bool selfClose = false;
49 std::string data;
50 std::string attrValue;
51 std::string attrName;
57 std::string encoding;
58 std::vector<std::string> xpath;
59 std::function<XMLParser::Transcode> transcodeFunc;
60};
61
62#if USE_STATE2STRING
63static const char *stateToString(int state);
64#endif
65
66static int yyread(yyscan_t yyscanner,char *buf,int max_size);
67static void initElement(yyscan_t yyscanner);
68static void addCharacters(yyscan_t yyscanner);
69static void addElement(yyscan_t yyscanner);
70static void addAttribute(yyscan_t yyscanner);
71static void countLines(yyscan_t yyscanner, const char *txt,yy_size_t len);
72static void reportError(yyscan_t yyscanner, const std::string &msg);
73static std::string processData(yyscan_t yyscanner,const char *txt,yy_size_t len);
74
75#undef YY_INPUT
76#define YY_INPUT(buf,result,max_size) result=yyread(yyscanner,buf,max_size);
77
Event handlers that can installed by the client and called while parsing a XML document.
Definition xml.h:27
std::unordered_map< std::string, std::string > Attributes
Definition xml.h:29
yyguts_t * yyscan_t
Definition code.l:25
#define msg(fmt,...)
Definition message.h:94
std::string name
Definition xml.l:46
std::string encoding
Definition xml.l:57
XMLHandlers handlers
Definition xml.l:53
char stringChar
Definition xml.l:56
XMLHandlers::Attributes attrs
Definition xml.l:52
bool isEnd
Definition xml.l:47
bool selfClose
Definition xml.l:48
std::string attrValue
Definition xml.l:50
std::string attrName
Definition xml.l:51
int cdataContext
Definition xml.l:54
std::vector< std::string > xpath
Definition xml.l:58
std::string fileName
Definition xml.l:42
int inputPosition
read offset during parsing
Definition xml.l:45
int lineNr
Definition xml.l:43
std::string data
Definition xml.l:49
int commentContext
Definition xml.l:55
const char * inputString
the code fragment as text
Definition xml.l:44
std::function< XMLParser::Transcode > transcodeFunc
Definition xml.l:59
static int yyread(yyscan_t yyscanner, char *buf, int max_size)
Definition xml.l:231
static void addCharacters(yyscan_t yyscanner)
Definition xml.l:330
static void reportError(yyscan_t yyscanner, const std::string &msg)
Definition xml.l:362
static void addAttribute(yyscan_t yyscanner)
Definition xml.l:351
static void addElement(yyscan_t yyscanner)
Definition xml.l:287
static void countLines(yyscan_t yyscanner, const char *txt, yy_size_t len)
Definition xml.l:246
static std::string processData(yyscan_t yyscanner, const char *txt, yy_size_t len)
Definition xml.l:381
static void initElement(yyscan_t yyscanner)
Definition xml.l:255
78%}
79
80NL (\r\n|\r|\n)
81SP [ \t\r\n]+
82OPEN {SP}?"<"
83OPENSPECIAL {SP}?"<?"
84CLOSE ">"{NL}?
85CLOSESPECIAL "?>"{NL}?
86NAMESTART [:A-Za-z\200-\377_]
87NAMECHAR [:A-Za-z\200-\377_0-9.-]
88NAME {NAMESTART}{NAMECHAR}*
89ESC "&#"[0-9]+";"|"&#x"[0-9a-fA-F]+";"
90COLON ":"
91PCDATA [^<]+
92COMMENT {OPEN}"!--"
93COMMENTEND "--"{CLOSE}
94STRING \"([^"&]|{ESC})*\"|\'([^'&]|{ESC})*\'
95DOCTYPE {SP}?"<!DOCTYPE"{SP}
96CDATA {SP}?"<![CDATA["
97ENDCDATA "]]>"
98
99%option noyywrap
100
101%s Initial
102%s Content
103%s CDataSection
104%s Element
105%s Attributes
106%s AttributeValue
107%s AttrValueStr
108%s Prolog
109%s Comment
110
112
113<Initial>{
114 {SP} { countLines(yyscanner,yytext,yyleng); }
115 {DOCTYPE} { countLines(yyscanner,yytext,yyleng); }
116 {OPENSPECIAL} { countLines(yyscanner,yytext,yyleng); BEGIN(Prolog); }
117 {OPEN} { countLines(yyscanner,yytext,yyleng);
118 initElement(yyscanner);
119 BEGIN(Element); }
120 {COMMENT} { yyextra->commentContext = YY_START;
121 BEGIN(Comment);
122 }
123}
124<Content>{
125 {CDATA} { countLines(yyscanner,yytext,yyleng);
126 yyextra->cdataContext = YY_START;
127 BEGIN(CDataSection);
128 }
129 {PCDATA} { yyextra->data += processData(yyscanner,yytext,yyleng); }
130 {OPEN} { countLines(yyscanner,yytext,yyleng);
131 addCharacters(yyscanner);
132 initElement(yyscanner);
133 BEGIN(Element);
134 }
135 {COMMENT} { yyextra->commentContext = YY_START;
136 countLines(yyscanner,yytext,yyleng);
137 BEGIN(Comment);
138 }
139}
140<Element>{
141 "/" { yyextra->isEnd = true; }
142 {NAME} { yyextra->name = yytext;
143 BEGIN(Attributes); }
144 {CLOSE} { addElement(yyscanner);
145 countLines(yyscanner,yytext,yyleng);
146 yyextra->data = "";
147 BEGIN(Content);
148 }
149 {SP} { countLines(yyscanner,yytext,yyleng); }
150}
151<Attributes>{
152 "/" { yyextra->selfClose = true; }
153 {NAME} { yyextra->attrName = yytext; }
154 "=" { BEGIN(AttributeValue); }
155 {CLOSE} { addElement(yyscanner);
156 countLines(yyscanner,yytext,yyleng);
157 yyextra->data = "";
158 BEGIN(Content);
159 }
160 {SP} { countLines(yyscanner,yytext,yyleng); }
161}
162<AttributeValue>{
163 {SP} { countLines(yyscanner,yytext,yyleng); }
164 ['"] { yyextra->stringChar = *yytext;
165 yyextra->attrValue = "";
166 BEGIN(AttrValueStr);
167 }
168 . { std::string msg = std::string("Missing attribute value. Unexpected character `")+yytext+"` found";
169 reportError(yyscanner,msg);
170 unput(*yytext);
171 BEGIN(Attributes);
172 }
173}
174<AttrValueStr>{
175 [^'"\n]+ { yyextra->attrValue += processData(yyscanner,yytext,yyleng); }
176 ['"] { if (*yytext==yyextra->stringChar)
177 {
178 addAttribute(yyscanner);
179 BEGIN(Attributes);
180 }
181 else
182 {
183 yyextra->attrValue += processData(yyscanner,yytext,yyleng);
184 }
185 }
186 \n { yyextra->lineNr++; yyextra->attrValue+=' '; }
187}
188<CDataSection>{
189 {ENDCDATA} { BEGIN(yyextra->cdataContext); }
190 [^]\n]+ { yyextra->data += yytext; }
191 \n { yyextra->data += yytext;
192 yyextra->lineNr++;
193 }
194 . { yyextra->data += yytext; }
195}
196<Prolog>{
197 "encoding"\s*=\s*\"[^\"]*\" {
198 std::string encoding=yytext;
199 size_t i=encoding.find('"');
200 encoding=encoding.substr(i+1,yyleng-i-2);
201 if (encoding!="UTF-8") // need to transcode to UTF-8
202 {
203 yyextra->encoding=encoding;
204 }
205 }
206 {CLOSESPECIAL} { countLines(yyscanner,yytext,yyleng);
207 BEGIN(Initial);
208 }
209 \n { yyextra->lineNr++; }
210 . { }
211}
212<Comment>{
213 {COMMENTEND} { countLines(yyscanner,yytext,yyleng);
214 BEGIN(yyextra->commentContext);
215 }
216 [^\n-]+ { }
217 \n { yyextra->lineNr++; }
218 . { }
219}
220\n { yyextra->lineNr++; }
221. { std::string msg = "Unexpected character `";
222 msg+=yytext;
223 msg+="` found";
224 reportError(yyscanner,msg);
225 }
226
227%%
228
229//----------------------------------------------------------------------------------------
230
231static int yyread(yyscan_t yyscanner,char *buf,int max_size)
232{
233 struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
234 int inputPosition = yyextra->inputPosition;
235 const char *s = yyextra->inputString + inputPosition;
236 int c=0;
237 while( c < max_size && *s)
238 {
239 *buf++ = *s++;
240 c++;
241 }
242 yyextra->inputPosition += c;
243 return c;
244}
245
246static void countLines(yyscan_t yyscanner, const char *txt,yy_size_t len)
247{
248 struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
249 for (yy_size_t i=0;i<len;i++)
250 {
251 if (txt[i]=='\n') yyextra->lineNr++;
252 }
253}
254
255static void initElement(yyscan_t yyscanner)
256{
257 struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
258 yyextra->isEnd = false; // true => </tag>
259 yyextra->selfClose = false; // true => <tag/>
260 yyextra->name = "";
261 yyextra->attrs.clear();
262}
263
264static void checkAndUpdatePath(yyscan_t yyscanner)
265{
266 struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
267 if (yyextra->xpath.empty())
268 {
269 std::string msg = "found closing tag '"+yyextra->name+"' without matching opening tag";
270 reportError(yyscanner,msg);
271 }
272 else
273 {
274 std::string expectedTagName = yyextra->xpath.back();
275 if (expectedTagName!=yyextra->name)
276 {
277 std::string msg = "Found closing tag '"+yyextra->name+"' that does not match the opening tag '"+expectedTagName+"' at the same level";
278 reportError(yyscanner,msg);
279 }
280 else // matching end tag
281 {
282 yyextra->xpath.pop_back();
283 }
284 }
285}
286
287static void addElement(yyscan_t yyscanner)
288{
289 struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
290 if (!yyextra->isEnd)
291 {
292 yyextra->xpath.push_back(yyextra->name);
293 if (yyextra->handlers.startElement)
294 {
295 yyextra->handlers.startElement(yyextra->name,yyextra->attrs);
296 }
297 if (yy_flex_debug)
298 {
299 fprintf(stderr,"%d: startElement(%s,attr=[",yyextra->lineNr,yyextra->name.data());
300 for (auto attr : yyextra->attrs)
301 {
302 fprintf(stderr,"%s='%s' ",attr.first.c_str(),attr.second.c_str());
303 }
304 fprintf(stderr,"])\n");
305 }
306 }
307 if (yyextra->isEnd || yyextra->selfClose)
308 {
309 if (yy_flex_debug)
310 {
311 fprintf(stderr,"%d: endElement(%s)\n",yyextra->lineNr,yyextra->name.data());
312 }
313 checkAndUpdatePath(yyscanner);
314 if (yyextra->handlers.endElement)
315 {
316 yyextra->handlers.endElement(yyextra->name);
317 }
318 }
319}
320
321static std::string trimSpaces(const std::string &str)
322{
323 const int l = static_cast<int>(str.length());
324 int s=0, e=l-1;
325 while (s<l && isspace(str.at(s))) s++;
326 while (e>s && isspace(str.at(e))) e--;
327 return str.substr(s,1+e-s);
328}
329
330static void addCharacters(yyscan_t yyscanner)
331{
332 struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
333 std::string data = trimSpaces(yyextra->data);
334 if (!yyextra->encoding.empty() && !yyextra->transcodeFunc(data,yyextra->encoding.c_str()))
335 {
336 reportError(yyscanner,"failed to transcode string '"+data+"' from encoding '"+yyextra->encoding+"' to UTF-8");
337 }
338 if (yyextra->handlers.characters)
339 {
340 yyextra->handlers.characters(data);
341 }
342 if (!data.empty())
343 {
344 if (yy_flex_debug)
345 {
346 fprintf(stderr,"characters(%s)\n",data.c_str());
347 }
348 }
349}
350
351static void addAttribute(yyscan_t yyscanner)
352{
353 struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
354 std::string val = yyextra->attrValue;
355 if (!yyextra->encoding.empty() && !yyextra->transcodeFunc(val,yyextra->encoding.c_str()))
356 {
357 reportError(yyscanner,"failed to transcode string '"+val+"' from encoding '"+yyextra->encoding+"' to UTF-8");
358 }
359 yyextra->attrs.insert(std::make_pair(yyextra->attrName,val));
360}
361
362static void reportError(yyscan_t yyscanner,const std::string &msg)
363{
364 struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
365 if (yy_flex_debug)
366 {
367 fprintf(stderr,"%s:%d: Error '%s'\n",yyextra->fileName.c_str(),yyextra->lineNr,msg.c_str());
368 }
369 if (yyextra->handlers.error)
370 {
371 yyextra->handlers.error(yyextra->fileName,yyextra->lineNr,msg);
372 }
373}
374
375static const char *entities_enc[] = { "amp", "quot", "gt", "lt", "apos" };
376static const char entities_dec[] = { '&', '"', '>', '<', '\'' };
377static const int num_entities = 5;
378
379// replace character entities such as &amp; in txt and return the string where entities
380// are replaced
381static std::string processData(yyscan_t yyscanner,const char *txt,yy_size_t len)
382{
383 std::string result;
384 result.reserve(len);
385 for (yy_size_t i=0; i<len; i++)
386 {
387 char c = txt[i];
388 if (c=='&')
389 {
390 const int maxEntityLen = 10;
391 char entity[maxEntityLen+1];
392 entity[maxEntityLen]='\0';
393 for (yy_size_t j=0; j<maxEntityLen && i+j+1<len; j++)
394 {
395 if (txt[i+j+1]!=';')
396 {
397 entity[j]=txt[i+j+1];
398 }
399 else
400 {
401 entity[j]=0;
402 break;
403 }
404 }
405 bool found=false;
406 for (int e=0; !found && e<num_entities; e++)
407 {
408 if (strcmp(entity,entities_enc[e])==0)
409 {
410 result+=entities_dec[e];
411 i+=strlen(entities_enc[e])+1;
412 found=true;
413 }
414 }
415 if (!found)
416 {
417 std::string msg = std::string("Invalid character entity '&") + entity + ";' found\n";
418 reportError(yyscanner,msg);
419 }
420 }
421 else
422 {
423 result+=c;
424 }
425 }
426 return result;
427}
428
429//--------------------------------------------------------------
430
436
438{
439 xmlYYlex_init_extra(&p->xmlYY_extra,&p->yyscanner);
440 p->xmlYY_extra.handlers = handlers;
441}
442
444{
445 xmlYYlex_destroy(p->yyscanner);
446}
447
448void XMLParser::parse(const char *fileName,
449 const char *inputStr,
450 bool debugEnabled,
451 std::function<void()> debugStart,
452 std::function<void()> debugEnd,
453 std::function<Transcode> transcodeFunc)
454{
455 yyscan_t yyscanner = p->yyscanner;
456 struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
457
458#ifdef FLEX_DEBUG
459 xmlYYset_debug(debugEnabled?1:0,p->yyscanner);
460#endif
461
462 if (inputStr==nullptr || inputStr[0]=='\0') return; // empty input
463
464 debugStart();
465
466 BEGIN(Initial);
467 yyextra->fileName = fileName;
468 yyextra->lineNr = 1;
469 yyextra->inputString = inputStr;
470 yyextra->inputPosition = 0;
471 yyextra->transcodeFunc = transcodeFunc;
472
473 if (static_cast<unsigned char>(inputStr[0])==0xEF &&
474 static_cast<unsigned char>(inputStr[1])==0xBB &&
475 static_cast<unsigned char>(inputStr[2])==0xBF)
476 {
477 yyextra->inputPosition = 3; // remove UTF-8 BOM
478 }
479
480 xmlYYrestart( 0, yyscanner );
481
482 if (yyextra->handlers.startDocument)
483 {
484 yyextra->handlers.startDocument();
485 }
486 xmlYYlex(yyscanner);
487 if (yyextra->handlers.endDocument)
488 {
489 yyextra->handlers.endDocument();
490 }
491
492 if (!yyextra->xpath.empty())
493 {
494 std::string tagName = yyextra->xpath.back();
495 std::string msg = "End of file reached while expecting closing tag '"+tagName+"'";
496 reportError(yyscanner,msg);
497 }
498
499 debugEnd();
500}
501
503{
504 struct yyguts_t *yyg = (struct yyguts_t*)p->yyscanner;
505 return yyextra->lineNr;
506}
507
508std::string XMLParser::fileName() const
509{
510 struct yyguts_t *yyg = (struct yyguts_t*)p->yyscanner;
511 return yyextra->fileName;
512}
513
514#if USE_STATE2STRING
515#include "xml.l.h"
516#endif
int lineNr() const override
Definition xml.l:502
std::unique_ptr< Private > p
Definition xml.h:109
std::string fileName() const override
Definition xml.l:508
XMLParser(const XMLHandlers &handlers)
Definition xml.l:437
void parse(const char *fileName, const char *inputString, bool debugEnabled, std::function< void()> debugStart, std::function< void()> debugEnd, std::function< Transcode > transcoder=[](std::string &s, const char *){ return true;})
Definition xml.l:448
~XMLParser() override
Definition xml.l:443
#define yyguts_t
Definition code.l:23
struct xmlYY_state xmlYY_extra
Definition xml.l:434
yyscan_t yyscanner
Definition xml.l:433
static std::string trimSpaces(const std::string &str)
Definition xml.l:321
static const int num_entities
Definition xml.l:377
static const char entities_dec[]
Definition xml.l:376
static void checkAndUpdatePath(yyscan_t yyscanner)
Definition xml.l:264
static const char * entities_enc[]
Definition xml.l:375