-
Notifications
You must be signed in to change notification settings - Fork 9
/
xmlreader.cpp
1441 lines (1338 loc) · 44.7 KB
/
xmlreader.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- mode: C++; c-file-style: "stroustrup"; c-basic-offset: 4; indent-tabs-mode: nil; -*-
/* libutap - Uppaal Timed Automata Parser.
Copyright (C) 2010-2020 Aalborg University.
Copyright (C) 2002-2006 Uppsala University and Aalborg University.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation; either version 2.1 of
the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
*/
#include "keywords.hpp"
#include "libparser.h"
#include "utap/utap.h"
#include <libxml/parser.h>
#include <libxml/xmlreader.h>
#include <libxml/xmlstring.h>
#include <libxml/xpath.h>
#include <algorithm>
#include <list>
#include <map>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
#include <cassert>
#include <charconv>
#include <cstring> // strncmp
namespace UTAP {
enum class tag_t {
NTA,
PROJECT,
IMPORTS,
DECLARATION,
TEMPLATE,
INSTANTIATION,
SYSTEM,
NAME,
PARAMETER,
LOCATION,
INIT,
TRANSITION,
URGENT,
COMMITTED,
BRANCHPOINT,
SOURCE,
TARGET,
LABEL,
NAIL,
LSC,
TYPE,
MODE,
YLOCCOORD,
LSCLOCATION,
PRECHART,
INSTANCE,
TEMPERATURE,
MESSAGE,
CONDITION,
UPDATE,
ANCHOR,
QUERIES,
QUERY,
FORMULA,
COMMENT,
OPTION,
RESOURCE,
EXPECT,
RESULT,
DETAILS,
SAMPLES,
PLOT,
TITLE,
SERIES,
POINT,
NONE
};
// clang-format off
static const auto tag_map = std::unordered_map<std::string_view, const tag_t>{
{"nta", tag_t::NTA},
{"project", tag_t::PROJECT},
{"imports", tag_t::IMPORTS},
{"declaration", tag_t::DECLARATION},
{"template", tag_t::TEMPLATE},
{"instantiation", tag_t::INSTANTIATION},
{"system", tag_t::SYSTEM},
{"name", tag_t::NAME},
{"parameter", tag_t::PARAMETER},
{"location", tag_t::LOCATION},
{"init", tag_t::INIT},
{"transition", tag_t::TRANSITION},
{"urgent", tag_t::URGENT},
{"committed", tag_t::COMMITTED},
{"branchpoint", tag_t::BRANCHPOINT},
{"source", tag_t::SOURCE},
{"target", tag_t::TARGET},
{"label", tag_t::LABEL},
{"nail", tag_t::NAIL},
{"lsc", tag_t::LSC},
{"type", tag_t::TYPE},
{"mode", tag_t::MODE},
{"yloccoord", tag_t::YLOCCOORD},
{"lsclocation", tag_t::LSCLOCATION},
{"prechart", tag_t::PRECHART},
{"instance", tag_t::INSTANCE},
{"temperature", tag_t::TEMPERATURE},
{"message", tag_t::MESSAGE},
{"condition", tag_t::CONDITION},
{"update", tag_t::UPDATE},
{"anchor", tag_t::ANCHOR},
{"queries", tag_t::QUERIES},
{"query", tag_t::QUERY},
{"formula", tag_t::FORMULA},
{"comment", tag_t::COMMENT},
{"option", tag_t::OPTION},
{"resource", tag_t::RESOURCE},
{"expect", tag_t::EXPECT},
{"result", tag_t::RESULT},
{"details", tag_t::DETAILS},
{"samples", tag_t::SAMPLES},
{"plot", tag_t::PLOT},
{"series", tag_t::SERIES}
};
// clang-format on
/**
* Returns true if string is zero length or contains only white spaces
* otherwise false.
*/
static bool is_blank(std::string_view str) { return std::all_of(str.cbegin(), str.cend(), ::isspace); }
static inline bool is_blank(const xmlChar* str) { return is_blank((const char*)str); }
static inline bool is_alpha(unsigned char c) { return std::isalpha(c) || c == '_'; }
static bool is_id_char(unsigned char c) { return std::isalnum(c) || c == '_' || c == '$' || c == '#'; }
struct id_expected_error : std::logic_error
{
id_expected_error(): std::logic_error{"Identifier expected"} {}
};
struct invalid_id_error : std::logic_error
{
invalid_id_error(): std::logic_error{"Invalid identifier"} {}
};
struct xpath_corrupt_error : std::logic_error
{
xpath_corrupt_error(): std::logic_error{"XPath is corrupted"} {}
};
/**
* Extracts the alpha-numerical symbol used for variable/type
* identifiers. Identifier starts with alpha and further might
* contain digits, white spaces are ignored.
*
* Throws a TypeException is identifier is invalid or a newly
* allocated string to be destroyed with delete [].
*/
static std::string_view symbol(std::string_view sv)
{ // TODO: LSC revisit: this is very similar to trimming whitespace
if (sv.empty())
throw id_expected_error{};
auto first = std::begin(sv);
const auto end = std::end(sv);
while (first != end && std::isspace(*first))
++first;
if (first == end)
throw id_expected_error{};
if (!is_alpha(*first))
throw id_expected_error{};
auto last = first;
while (last != end && is_id_char(*last))
++last;
auto p = last;
while (p != end && std::isspace(*p))
++p;
if (p != end)
throw invalid_id_error{};
return std::string_view(first, std::distance(first, last));
}
/**
* Path to current node. This path also contains information about
* the left siblings of the nodes. This information is used to
* generated an XPath expression.
*
* @see get()
*/
class Path
{
private:
std::list<std::vector<tag_t>> path;
public:
Path() { path.emplace_back(); };
void push(tag_t tag)
{
path.back().push_back(tag);
path.emplace_back();
}
tag_t pop()
{
path.pop_back();
return path.back().back();
}
[[nodiscard]] std::string str(tag_t tag = tag_t::NONE) const;
};
static inline size_t count(const std::vector<tag_t>& level, tag_t tag)
{
return std::count(std::begin(level), std::end(level), tag);
}
/** Returns the XPath encoding of the current path. */
[[nodiscard]] std::string Path::str(tag_t tag) const
{
std::ostringstream str;
for (auto&& level : path) {
if (level.empty())
break;
switch (level.back()) {
case tag_t::NTA: str << "/nta"; break;
case tag_t::PROJECT: str << "/project"; break;
case tag_t::IMPORTS: str << "/imports"; break;
case tag_t::DECLARATION: str << "/declaration"; break;
case tag_t::TEMPLATE: str << "/template[" << count(level, tag_t::TEMPLATE) << "]"; break;
case tag_t::INSTANTIATION: str << "/instantiation"; break;
case tag_t::SYSTEM: str << "/system"; break;
case tag_t::NAME: str << "/name"; break;
case tag_t::PARAMETER: str << "/parameter"; break;
case tag_t::LOCATION: str << "/location[" << count(level, tag_t::LOCATION) << "]"; break;
case tag_t::BRANCHPOINT: str << "/branchpoint[" << count(level, tag_t::BRANCHPOINT) << "]"; break;
case tag_t::INIT: str << "/init"; break;
case tag_t::TRANSITION: str << "/transition[" << count(level, tag_t::TRANSITION) << "]"; break;
case tag_t::LABEL: str << "/label[" << count(level, tag_t::LABEL) << "]"; break;
case tag_t::URGENT: str << "/urgent"; break;
case tag_t::COMMITTED: str << "/committed"; break;
case tag_t::SOURCE: str << "/source"; break;
case tag_t::TARGET: str << "/target"; break;
case tag_t::NAIL: str << "/nail[" << count(level, tag_t::NAIL) << "]"; break;
case tag_t::LSC: str << "/lscTemplate[" << count(level, tag_t::LSC) << "]"; break;
case tag_t::TYPE: str << "/type"; break;
case tag_t::MODE: str << "/mode"; break;
case tag_t::YLOCCOORD: str << "/ylocoord[" << count(level, tag_t::YLOCCOORD) << "]"; break;
case tag_t::LSCLOCATION: str << "/lsclocation"; break;
case tag_t::PRECHART: str << "/prechart"; break;
case tag_t::INSTANCE: str << "/instance[" << count(level, tag_t::INSTANCE) << "]"; break;
case tag_t::TEMPERATURE: str << "/temperature[" << count(level, tag_t::TEMPERATURE) << "]"; break;
case tag_t::MESSAGE: str << "/message[" << count(level, tag_t::MESSAGE) << "]"; break;
case tag_t::CONDITION: str << "/condition[" << count(level, tag_t::CONDITION) << "]"; break;
case tag_t::UPDATE: str << "/update[" << count(level, tag_t::UPDATE) << "]"; break;
case tag_t::ANCHOR: str << "/anchor[" << count(level, tag_t::ANCHOR) << "]"; break;
case tag_t::QUERIES: str << "/queries"; break;
case tag_t::QUERY: str << "/query[" << count(level, tag_t::QUERY) << "]"; break;
case tag_t::FORMULA: str << "/formula"; break;
case tag_t::COMMENT: str << "/comment"; break;
case tag_t::OPTION: str << "/option"; break;
case tag_t::RESOURCE: str << "/resource"; break;
case tag_t::EXPECT: str << "/expect"; break;
case tag_t::RESULT: str << "/result"; break;
case tag_t::DETAILS: str << "/details"; break;
case tag_t::SAMPLES: str << "/samples"; break;
default:
/* Strange tag on stack */
throw xpath_corrupt_error{};
}
if (level.back() == tag) {
break;
}
}
return str.str();
}
/**
* Implements a recursive descent parser for UPPAAL XML documents.
* Uses the xmlTextReader API from libxml2.
*/
class XMLReader
{
private:
using elementmap_t = std::map<std::string, std::string>;
using xmlTextReader_ptr = std::unique_ptr<xmlTextReader, decltype(xmlFreeTextReader)&>;
xmlTextReader_ptr reader; /**< The underlying xmlTextReader */
elementmap_t names; /**< Map from id to name */
ParserBuilder* parser; /**< The parser builder to which to push the model. */
bool newxta; /**< True if we should use new syntax. */
Path path;
bool nta; /**< True if the enclosing tag is "nta" (false if it is "project") */
int bottomPrechart; /**< y location of the prechart bottom */
std::string currentType; /**< type of the current LSC template */
std::string currentMode; /**< mode of the current LSC template */
[[nodiscard]] tag_t getElement() const;
/** Reads an attribute value of the currently parsed tag with manual deallocation.
* @param name the name of the XML tag attribute
* @return the value of the attribute, remember to xmlFree() it!
*/
char* getAttribute(const char* name) const;
/** Reads an attribute value of the currently parsed tag with automatic deallocation.
* @param name the name of the XML tag attribute
* @return the value of the attribute.
*/
std::string getAttributeStr(std::string_view name) const;
bool isEmpty() const;
int getNodeType() const;
void read();
bool begin(tag_t, bool skipEmpty = true);
bool end(tag_t);
/** skips the content until tag is closed and then looks ahead */
void close(tag_t tag)
{
if (!isEmpty()) {
while (!end(tag))
read();
}
read();
}
/** calls fn zero or one times unless closing tag is found */
template <typename Fn>
void zero_or_one(tag_t closing_tag, Fn&& fn)
{
if (!end(closing_tag))
fn();
}
/** calls fn zero or more times unless closing tag is found */
template <typename Fn>
void zero_or_more(tag_t closing_tag, Fn&& fn)
{
while (!end(closing_tag) && fn())
;
}
/** Returns the name of a location. */
const std::string& get_name(const char* id) const;
/** Invokes the bison generated parser to parse the given string. */
int parse(const xmlChar*, xta_part_t syntax);
/** Parse optional declaration. */
bool declaration();
/** Parse optional label. */
bool label(bool required = false, const std::string& kind = "");
int invariant();
/** Parse optional committed tag. */
bool committed();
/** Parse optional urgent tag. */
bool urgent();
/** Parse optional location. */
bool location();
/** Parse optional branchpoint. */
bool branchpoint();
/** Parse optional init tag. The caller must define a position to
* which any error messages are attached.
*/
bool init();
/** Parse optional name tag. */
std::string name(bool instanceLine = false);
std::string readString(tag_t tag, bool instanceLine = false);
std::string readText(bool instanceLine = false);
int readNumber();
/** Parse obligatory source tag. */
std::string source();
/** Parse obligatory target tag. */
std::string target();
/** Parse optional transition. */
bool transition();
/** Parse optional template. */
bool templ();
/** Parses an optional parameter tag and returns the number of parameters. */
int parameter();
/** Parse optional instantiation tag. */
bool instantiation();
/** Parse required system tag. */
void system();
std::string reference(const std::string& attributeName);
// LSC elements:
/** Parse optional LSC template. */
bool lscTempl();
/** Parse obligatory anchor tag for update. */
std::string anchor();
/** Parse obligatory anchor tag for condition. */
std::vector<std::string> anchors();
/** Parse optional type tag. */
std::string type();
/** Parse optional mode tag. */
std::string mode();
/** Parse required lsclocation tag for the prechart (bottom location or the messages) */
int lscLocation();
std::string temperature();
bool yloccoord();
bool instance();
bool prechart();
bool message();
bool condition();
bool update();
// integrated query elements:
/** Parse optional enclosed queries inside the model file. */
bool queries();
bool model_options();
bool query();
bool formula();
bool comment();
bool option();
bool expectation();
bool result();
public:
XMLReader(xmlTextReaderPtr reader, ParserBuilder* parser, bool newxta):
reader(reader, xmlFreeTextReader), parser{parser}, newxta{newxta}
{
read();
}
/** Parse the project document (either NTA or PROJECT tag). */
void project();
};
static const auto non_unique_id = std::string{"$Non-unique_id_attribute_value: "};
/** Returns the type of the current node. */
int XMLReader::getNodeType() const { return xmlTextReaderNodeType(reader.get()); }
/**
* Returns the tag of the current element. Throws an exception if
* the tag is not known.
*/
tag_t XMLReader::getElement() const
{
const char* element = (const char*)xmlTextReaderConstLocalName(reader.get());
const auto tag = tag_map.find(element);
if (tag == std::end(tag_map)) {
/* Unknown element. */
return tag_t::NONE;
}
return tag->second;
}
char* XMLReader::getAttribute(const char* name) const
{
return (char*)xmlTextReaderGetAttribute(reader.get(), (xmlChar*)name);
}
std::string XMLReader::getAttributeStr(std::string_view name) const
{
char* value = getAttribute(name.data());
auto res = std::string{value};
xmlFree(value);
return res;
}
/** Returns true if the current element is an empty element. */
bool XMLReader::isEmpty() const
{
int res = xmlTextReaderIsEmptyElement(reader.get());
assert(0 <= res);
assert(res <= 1);
return res == 1;
}
/**
* Read until start element. Returns true if that element has the
* given tag. If skipEmpty is true, empty elements with the given
* tag are ignored.
*/
bool XMLReader::begin(tag_t tag, bool skipEmpty)
{
for (;;) {
int node_type = getNodeType();
while (node_type != XML_READER_TYPE_ELEMENT) {
read();
node_type = getNodeType();
}
tag_t elem = getElement();
if (elem != tag) {
// if the tag was not recognized, try skipping over it until
// an end element is found with unknown tag.
if (elem == tag_t::NONE) {
end(tag_t::NONE);
read();
continue;
}
return false;
}
if (!skipEmpty || !isEmpty())
return true;
read();
}
}
/**
* Is end of the tag in xml ?
* @param tag - XML tag
* @return True - if </...> tag found
* Ignores whitespace
*/
bool UTAP::XMLReader::end(UTAP::tag_t tag)
{
int node_type = getNodeType();
// Ignore whitespace
while (node_type == XML_READER_TYPE_WHITESPACE || node_type == XML_READER_TYPE_SIGNIFICANT_WHITESPACE) {
read();
node_type = getNodeType();
}
// </...> tag found
return node_type == XML_READER_TYPE_END_ELEMENT && getElement() == tag;
}
/**
* Advances the reader. It maintains the path to the current node.
*/
void XMLReader::read()
{
if ((getNodeType() == XML_READER_TYPE_END_ELEMENT) || (getNodeType() == XML_READER_TYPE_ELEMENT && isEmpty())) {
if (path.pop() != getElement()) {
/* Path is corrupted */
throw XMLDocError("Invalid nesting");
}
}
if (xmlTextReaderRead(reader.get()) != 1) {
/* Premature end of document. */
throw XMLReaderError(errno, std::system_category(), "$unexpected $end");
}
if (getNodeType() == XML_READER_TYPE_ELEMENT) {
path.push(getElement());
}
}
const std::string& XMLReader::get_name(const char* id) const
{
if (id) {
if (auto l = names.find(id); l != names.end())
return l->second;
}
throw XMLDocError("Missing reference");
}
int XMLReader::parse(const xmlChar* text, xta_part_t syntax)
{
return parse_XTA((const char*)text, parser, newxta, syntax, path.str());
}
bool XMLReader::declaration()
{
if (begin(tag_t::DECLARATION)) {
read();
if (getNodeType() == XML_READER_TYPE_TEXT) {
parse(xmlTextReaderConstValue(reader.get()), S_DECLARATION);
}
return true;
}
return false;
}
bool XMLReader::label(bool required, const std::string& s_kind)
{
if (begin(tag_t::LABEL)) {
/* Get kind attribute. */
char* kind = getAttribute("kind");
if (kind == nullptr)
throw TypeException("A label must have a \"kind\" attribute");
read();
/* Read the text and push it to the parser. */
if (getNodeType() == XML_READER_TYPE_TEXT) {
const xmlChar* text = xmlTextReaderConstValue(reader.get());
static const auto map = std::map<std::string_view, xta_part_t>{
{"invariant", S_INVARIANT}, {"select", S_SELECT}, {"guard", S_GUARD},
{"synchronisation", S_SYNC}, {"assignment", S_ASSIGN}, {"probability", S_PROBABILITY},
{"message", S_MESSAGE}, {"update", S_UPDATE}, {"condition", S_CONDITION},
};
if (auto part = map.find(kind); part != map.end())
parse(text, part->second);
}
xmlFree(kind);
return true;
} else if (required) {
tracker.setPath(parser, path.str());
if (s_kind == "message") // LSC
parser->handle_error(TypeException{"$Message_label_is_required"});
else if (s_kind == "update") // LSC
parser->handle_error(TypeException{"$Update_label_is_required"});
else if (s_kind == "condition") // LSC
parser->handle_error(TypeException{"$Condition_label_is_required"});
}
return false;
}
int XMLReader::invariant()
{
int result = -1;
if (begin(tag_t::LABEL)) {
/* Get kind attribute. */
char* kind = getAttribute("kind");
if (kind == nullptr)
throw TypeException{"A label must have a \"kind\" attribute"};
read();
/* Read the text and push it to the parser. */
if (getNodeType() == XML_READER_TYPE_TEXT) {
const xmlChar* text = xmlTextReaderConstValue(reader.get());
auto kind_sv = std::string_view{kind};
// This is a terrible mess but it's too badly designed
// to fix at this moment.
if (kind_sv == "invariant") {
if (parse(text, S_INVARIANT) == 0)
result = 0;
} else if (kind_sv == "exponentialrate") {
if (parse(text, S_EXPONENTIAL_RATE) == 0)
result = 1;
}
}
xmlFree(kind);
}
return result;
}
std::string XMLReader::name(bool instanceLine)
{
std::string text = readString(tag_t::NAME, instanceLine);
if (instanceLine && text.empty())
parser->handle_error(TypeException{"$Instance_name_is_required"});
return text;
}
std::string XMLReader::readText(bool instanceLine)
{
if (getNodeType() == XML_READER_TYPE_TEXT) { // text content of a node
xmlChar* text = xmlTextReaderValue(reader.get());
auto len = text ? std::strlen((const char*)text) : 0;
auto text_sv = std::string_view{(const char*)text, len};
tracker.setPath(parser, path.str());
tracker.increment(parser, text_sv.size());
try {
std::string_view id = (instanceLine) ? text_sv : symbol(text_sv);
if (!is_keyword(id, syntax_t::OLD_PROPERTY)) {
auto res = std::string{id};
xmlFree(text);
return res;
}
parser->handle_error(TypeException{"$Keywords_are_not_allowed_here"});
} catch (std::logic_error& str) {
parser->handle_error(TypeException{str.what()});
}
xmlFree(text);
}
return "";
}
int XMLReader::readNumber()
{
read();
if (getNodeType() == XML_READER_TYPE_TEXT) { // text content of a node
tracker.setPath(parser, path.str());
xmlChar* text = xmlTextReaderValue(reader.get());
const char* pc = (const char*)text;
auto len = std::strlen(pc);
tracker.increment(parser, len);
try {
int value;
if (auto [p, ec] = std::from_chars(pc, pc + len, value); ec != std::errc{})
throw std::logic_error{std::make_error_code(ec).category().name()};
xmlFree(text);
return value;
} catch (const char* str) {
parser->handle_error(TypeException{str});
}
xmlFree(text);
}
return -1;
}
std::string XMLReader::readString(tag_t tag, bool instanceLine)
{
if (begin(tag)) {
read();
return readText(instanceLine);
}
return "";
}
std::string XMLReader::type() { return readString(tag_t::TYPE); }
std::string XMLReader::mode() { return readString(tag_t::MODE); }
int XMLReader::lscLocation()
{
int n = -1;
if (begin(tag_t::LSCLOCATION)) {
n = readNumber();
}
if (n == -1)
throw XMLDocError("Missing LSC location");
return n;
}
bool XMLReader::committed()
{
if (begin(tag_t::COMMITTED, false)) {
read();
return true;
}
return false;
}
bool XMLReader::urgent()
{
if (begin(tag_t::URGENT, false)) {
read();
return true;
}
return false;
}
bool XMLReader::location()
{
bool l_invariant = false;
bool l_exponentialRate = false;
if (begin(tag_t::LOCATION, false)) {
try {
std::string l_path = path.str(tag_t::LOCATION);
/* Extract ID attribute. */
auto l_id = getAttributeStr("id");
if (is_blank(l_id))
throw TypeException{"Every location must have a unique id attribute value"};
read();
/* Get name of the location. */
std::string l_name = name();
/* Read the invariant. */
while (begin(tag_t::LABEL)) {
int res = invariant();
l_invariant |= res == 0;
l_exponentialRate |= res == 1;
}
/* Is the location urgent or committed? */
bool l_urgent = urgent();
bool l_committed = committed();
// anonymous locations get an internal name based on the ID
if (is_blank(l_name))
l_name = "_" + l_id;
/* Remember the mapping from id to name */
if (auto [_, ins] = names.insert_or_assign(l_id, l_name); !ins)
parser->handle_warning(TypeException{non_unique_id + l_id});
/* Any error messages generated by any of the
* procStateXXX calls must be attributed to the state
* element. To do this, we add a dummy position of
* length 1.
*/
tracker.setPath(parser, l_path);
tracker.increment(parser, 1);
/* Push location to parser builder. */
parser->proc_location(l_name.c_str(), l_invariant, l_exponentialRate);
if (l_committed)
parser->proc_location_commit(l_name.c_str());
if (l_urgent)
parser->proc_location_urgent(l_name.c_str());
} catch (TypeException& e) {
parser->handle_error(e);
}
return true;
}
return false;
}
/** Parse optional instance. */
bool XMLReader::instance()
{
if (begin(tag_t::INSTANCE, false)) {
try {
std::string i_path = path.str(tag_t::INSTANCE);
/* Extract ID attribute. */
auto i_id = getAttributeStr("id");
read();
if (is_blank(i_id))
throw TypeException{"Instance tag must have a unique \"id\" attribute"};
/* Get name of the instance. */
tracker.setPath(parser, i_path);
tracker.increment(parser, 1);
std::string i_name = name(true);
/* Remember the mapping from id to name */
if (auto [_, ins] = names.insert_or_assign(i_id, i_name); !ins)
parser->handle_warning(TypeException{non_unique_id + i_id});
/* Any error messages generated by the
* proc_instance_line call must be attributed to the
* instance line element. To do this, we add a dummy
* position of length 1.
*/
tracker.setPath(parser, i_path);
tracker.increment(parser, 1);
/* Push instance to parser builder. */
parser->proc_instance_line();
parse((xmlChar*)i_name.c_str(), S_INSTANCE_LINE);
} catch (TypeException& e) {
parser->handle_error(e);
}
return true;
}
return false;
}
/** Parse optional yloccoord */
bool XMLReader::yloccoord()
{
if (begin(tag_t::YLOCCOORD, false)) {
read(); // used only for the GUI
return true;
}
return false;
}
std::string XMLReader::temperature()
{
if (begin(tag_t::TEMPERATURE, false)) {
read();
/* Get the temperature of the condition */
return readText();
}
throw TypeException{"Missing temperature"};
}
bool XMLReader::prechart()
{
if (begin(tag_t::PRECHART, false)) {
try {
std::string p_path = path.str(tag_t::PRECHART);
/* Get the bottom location number */
read();
bottomPrechart = lscLocation();
if (strcasecmp(currentType.c_str(), "existential") == 0) {
tracker.setPath(parser, p_path);
tracker.increment(parser, 1);
parser->handle_error(TypeException{"$Existential_charts_must_not_have_prechart"});
}
parser->prechart_set(true);
} catch (TypeException& e) {
parser->handle_error(e);
}
return true;
} else {
bottomPrechart = -1;
parser->prechart_set(false);
}
return false;
}
bool XMLReader::message()
{
if (begin(tag_t::MESSAGE)) {
/* Add dummy position mapping to the message element. */
try {
std::string m_path = path.str(tag_t::MESSAGE);
read();
std::string from = source();
std::string to = target();
int location = lscLocation();
bool pch = (location < bottomPrechart);
tracker.setPath(parser, m_path);
tracker.increment(parser, 1);
parser->proc_message(from.c_str(), to.c_str(), location, pch);
tracker.setPath(parser, m_path);
tracker.increment(parser, 1);
label(true, "message");
} catch (TypeException& e) {
parser->handle_error(e);
}
return true;
}
return false;
}
bool XMLReader::condition()
{
if (begin(tag_t::CONDITION)) {
try {
std::string c_path = path.str(tag_t::CONDITION);
read();
std::vector<std::string> instance_anchors = anchors();
int location = lscLocation();
bool pch = (location < bottomPrechart);
tracker.setPath(parser, c_path);
tracker.increment(parser, 1);
std::string temp = temperature();
bool hot = (temp == "hot");
parser->proc_condition(instance_anchors, location, pch, hot);
label(true, "condition");
} catch (TypeException& e) {
parser->handle_error(e);
}
return true;
}
return false;
}
bool XMLReader::update()
{
if (begin(tag_t::UPDATE)) {
try {
std::string u_path = path.str(tag_t::UPDATE);
// location = atoi((char*)xmlTextReaderGetAttribute(reader, (const xmlChar*)"y"));
// pch = (location < bottomPrechart);
read();
std::string instance_anchor = anchor();
int location = lscLocation();
bool pch = (location < bottomPrechart);
tracker.setPath(parser, u_path);
tracker.increment(parser, 1);
parser->proc_LSC_update(instance_anchor.c_str(), location, pch);
label(true, "update");
} catch (TypeException& e) {
parser->handle_error(e);
}
return true;
}
return false;
}
bool XMLReader::branchpoint()
{
if (begin(tag_t::BRANCHPOINT, false)) {
try {
std::string b_path = path.str(tag_t::BRANCHPOINT);
auto b_id = getAttributeStr("id");
if (is_blank(b_id)) {
throw TypeException{"Branchpoint must have a unique \"id\" attribute"};
}
/* assign an internal name based on the ID of the branchpoint. */
std::string b_name = "_" + b_id;
/* Remember the mapping from id to name */
if (auto [_, ins] = names.insert_or_assign(b_id, b_name); !ins)
parser->handle_warning(TypeException{non_unique_id + b_id});
// FIXME: probably not necessary
/* Any error messages generated by any of the
* procStateXXX calls must be attributed to the state
* element. To do this, we add a dummy position of
* length 1.
*/
tracker.setPath(parser, b_path);
tracker.increment(parser, 1);
/* Push branchpoint to parser builder. */
parser->proc_branchpoint(b_name.c_str());
} catch (TypeException& e) {
parser->handle_error(e);
}
read(); // ignore any content and read next tag
return true;
}
return false;
}
bool XMLReader::init()
{
if (begin(tag_t::INIT, false)) {
/* Get reference attribute. */
char* ref = getAttribute("ref");
/* Find location name for the reference. */
if (ref) {
std::string name = get_name(ref);
try {
parser->proc_location_init(name.c_str());
} catch (TypeException& te) {
parser->handle_error(te);
}
} else {
parser->handle_error(TypeException{"$Missing_initial_location"});
}
xmlFree(ref);
read();
return true;
} else {
parser->handle_error(TypeException{"$Missing_initial_location"});
}
return false;