/
info.cpp
910 lines (781 loc) · 23.6 KB
/
info.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
/*
* The Doomsday Engine Project -- libcore
*
* Copyright © 2012-2015 Jaakko Keränen <jaakko.keranen@iki.fi>
*
* @par License
* LGPL: http://www.gnu.org/licenses/lgpl.html
*
* <small>This program 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 3 of the License, or (at your
* option) any later version. This program 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 program; if not, see:
* http://www.gnu.org/licenses</small>
*/
#include "de/Info"
#include "de/ScriptLex"
#include "de/Log"
#include "de/LogBuffer"
#include "de/App"
#include "de/SourceLineTable"
#include <QFile>
namespace de {
static QString const WHITESPACE = " \t\r\n";
static QString const WHITESPACE_OR_COMMENT = " \t\r\n#";
static QString const TOKEN_BREAKING_CHARS = "#:=$(){}<>,;\"" + WHITESPACE;
static QString const INCLUDE_TOKEN = "@include";
static QString const SCRIPT_TOKEN = "script";
static SourceLineTable sourceLineTable;
DENG2_PIMPL(Info)
{
DENG2_ERROR(OutOfElements);
DENG2_ERROR(EndOfFile);
struct DefaultIncludeFinder : public IIncludeFinder
{
String findIncludedInfoSource(String const &includeName, Info const &info,
String *sourcePath) const
{
String path = info.sourcePath().fileNamePath() / includeName;
if(sourcePath) *sourcePath = path;
return String::fromUtf8(Block(App::rootFolder().locate<File const>(path)));
}
};
QStringList scriptBlockTypes;
QStringList allowDuplicateBlocksOfType;
String implicitBlockType;
String sourcePath; ///< May be unknown (empty).
String content;
int currentLine;
int cursor; ///< Index of the next character from the source.
QChar currentChar;
int tokenStartOffset;
String currentToken;
BlockElement rootBlock;
DefaultIncludeFinder defaultFinder;
IIncludeFinder const *finder;
typedef Info::Element::Value InfoValue;
Instance(Public *i)
: Base(i)
, currentLine(0)
, cursor(0)
, tokenStartOffset(0)
, rootBlock("", "", *i)
, finder(&defaultFinder)
{
scriptBlockTypes << SCRIPT_TOKEN;
}
/**
* Initialize the parser for reading a block of source content.
* @param source Text to be parsed.
*/
void init(String const &source)
{
rootBlock.clear();
// The source data. Add an extra newline so the character reader won't
// get confused.
content = source + "\n";
currentLine = 1;
currentChar = '\0';
cursor = 0;
nextChar();
tokenStartOffset = 0;
// When nextToken() is called and the current token is empty,
// it is deduced that the source file has ended. We must
// therefore set a dummy token that will be discarded
// immediately.
currentToken = " ";
nextToken();
}
/**
* Returns the next character from the source file.
*/
QChar peekChar()
{
return currentChar;
}
/**
* Move to the next character in the source file.
*/
void nextChar()
{
if(cursor >= content.size())
{
// No more characters to read.
throw EndOfFile(QString("EOF on line %1").arg(currentLine));
}
if(currentChar == '\n')
{
currentLine++;
}
currentChar = content[cursor];
cursor++;
}
/**
* Read a line of text from the content and return it.
*/
String readLine()
{
String line;
nextChar();
while(currentChar != '\n')
{
line += currentChar;
nextChar();
}
return line;
}
/**
* Read until a newline is encountered. Returns the contents of the line.
*/
String readToEOL()
{
cursor = tokenStartOffset;
String line = readLine();
try
{
nextChar();
}
catch(EndOfFile const &)
{
// If the file ends right after the line, we'll get the EOF
// exception. We can safely ignore it for now.
}
return line;
}
String peekToken()
{
return currentToken;
}
/**
* Returns the next meaningful token from the source file.
*/
String nextToken()
{
// Already drawn a blank?
if(currentToken.isEmpty()) throw EndOfFile("out of tokens");
currentToken = "";
try
{
// Skip over any whitespace.
while(WHITESPACE_OR_COMMENT.contains(peekChar()))
{
// Comments are considered whitespace.
if(peekChar() == '#') readLine();
nextChar();
}
// Store the offset where the token begins.
tokenStartOffset = cursor;
// The first nonwhite is accepted.
currentToken += peekChar();
nextChar();
// Token breakers are tokens all by themselves.
if(TOKEN_BREAKING_CHARS.contains(currentToken[0]))
return currentToken;
while(!TOKEN_BREAKING_CHARS.contains(peekChar()))
{
currentToken += peekChar();
nextChar();
}
}
catch(EndOfFile const &)
{}
return currentToken;
}
/**
* This is the method that the user calls to retrieve the next element from
* the source file. If there are no more elements to return, a
* OutOfElements exception is thrown.
*
* @return Parsed element. Caller gets owernship.
*/
Element *get()
{
Element *e = parseElement();
if(!e) throw OutOfElements("");
return e;
}
/**
* Returns the next element from the source file.
* @return An instance of one of the Element classes, or @c NULL if there are none.
*/
Element *parseElement()
{
String key;
String next;
try
{
key = peekToken();
// The next token decides what kind of element we have here.
next = nextToken();
}
catch(EndOfFile const &)
{
// The file ended.
return 0;
}
int const elementLine = currentLine;
Element *result = 0;
if(next == ":" || next == "=" || next == "$")
{
result = parseKeyElement(key);
}
else if(next == "<")
{
result = parseListElement(key);
}
else
{
// It must be a block element.
result = parseBlockElement(key);
}
DENG2_ASSERT(result != 0);
result->setSourceLocation(sourcePath, elementLine);
return result;
}
/**
* Parse a string literal. Returns the string sans the quotation marks in
* the beginning and the end.
*/
String parseString()
{
if(peekToken() != "\"")
{
throw SyntaxError("Info::parseString",
QString("Expected string to begin with '\"', but '%1' found instead (on line %2).")
.arg(peekToken()).arg(currentLine));
}
// The collected characters.
String chars;
while(peekChar() != '"')
{
if(peekChar() == '\'')
{
// Double single quotes form a double quote ('' => ").
nextChar();
if(peekChar() == '\'')
{
chars.append("\"");
}
else
{
chars.append("'");
continue;
}
}
else
{
// Other characters are appended as-is, even newlines.
chars.append(peekChar());
}
nextChar();
}
// Move the parser to the next token.
nextChar();
nextToken();
return chars;
}
/**
* Parse a value from the source file. The current token should be on the
* first token of the value. Values come in different flavours:
* - single token
* - string literal (can be split)
*
* An optional semicolon may follow a value.
*/
InfoValue parseValue()
{
InfoValue value;
if(peekToken() == "$")
{
// Marks a script value.
value.flags |= InfoValue::Script;
nextToken();
}
// Check if it is the beginning of a string literal.
// The value will be composed of any number of sub-strings.
if(peekToken() == "\"")
{
value.flags |= InfoValue::StringLiteral;
while(peekToken() == "\"")
{
value.text += parseString();
}
}
else
{
// Then it must be a single token.
if(peekToken() != ";")
{
value = peekToken();
nextToken();
if(peekToken() == ";") nextToken(); // Ignore the semicolon.
}
}
return value;
}
InfoValue parseScript(int requiredStatementCount = 0)
{
int startPos = cursor - 1;
String remainder = content.substr(startPos);
ScriptLex lex(remainder);
TokenBuffer tokens;
int count = 0;
// Read an appropriate number of statements.
while(lex.getStatement(tokens, ScriptLex::StopAtMismatchedCloseBrace))
{
if(requiredStatementCount > 0 &&
++count == requiredStatementCount) break; // We're good now.
}
// Continue parsing normally from here.
int endPos = startPos + lex.pos();
do { nextChar(); } while(cursor < endPos); // fast-forward
// Update the current token.
currentToken = QString(peekChar());
nextChar();
if(currentToken != ")" && currentToken != "}")
{
// When parsing just a statement, we might stop at something else
// than a bracket; if so, skip to the next valid token.
nextToken();
}
//qDebug() << "now at" << content.substr(endPos - 15, endPos) << "^" << content.substr(endPos);
// Whitespace is removed from beginning and end.
return InfoValue(content.substr(startPos, lex.pos() - 1).trimmed(), InfoValue::Script);
}
/**
* Parse a key element.
* @param name Name of the parsed key element.
*/
KeyElement *parseKeyElement(String const &name)
{
InfoValue value;
if(peekToken() == "$")
{
// This is a script value.
value.flags |= InfoValue::Script;
nextToken();
}
// A colon means that that the rest of the line is the value of
// the key element.
if(peekToken() == ":")
{
value.text = readToEOL().trimmed();
nextToken();
}
else if(peekToken() == "=")
{
if(value.flags.testFlag(InfoValue::Script))
{
// Parse one script statement.
value = parseScript(1);
value.text = value.text.trimmed();
}
else
{
/**
* Key =
* "This is a long string "
* "that spans multiple lines."
*/
nextToken();
value.text = parseValue();
}
}
else
{
throw SyntaxError("Info::parseKeyElement",
QString("Expected either '=' or ':', but '%1' found instead (on line %2).")
.arg(peekToken()).arg(currentLine));
}
return new KeyElement(name, value);
}
/**
* Parse a list element, identified by the given name.
*/
ListElement *parseListElement(String const &name)
{
if(peekToken() != "<")
{
throw SyntaxError("Info::parseListElement",
QString("List must begin with a '<', but '%1' found instead (on line %2).")
.arg(peekToken()).arg(currentLine));
}
QScopedPointer<ListElement> element(new ListElement(name));
/// List syntax:
/// list ::= list-identifier '<' [value {',' value}] '>'
/// list-identifier ::= token
// Move past the opening angle bracket.
nextToken();
forever
{
element->add(parseValue());
// List elements are separated explicitly.
String separator = peekToken();
nextToken();
// The closing bracket?
if(separator == ">") break;
// There should be a comma here.
if(separator != ",")
{
throw SyntaxError("Info::parseListElement",
QString("List values must be separated with a comma, but '%1' found instead (on line %2).")
.arg(separator).arg(currentLine));
}
}
return element.take();
}
/**
* Parse a block element, identified by the given name.
* @param blockType Identifier of the block.
*/
BlockElement *parseBlockElement(String blockType)
{
DENG2_ASSERT(blockType != "}");
DENG2_ASSERT(blockType != ")");
String blockName;
if(!scriptBlockTypes.contains(blockType)) // script blocks are never named
{
if(peekToken() != "(" && peekToken() != "{")
{
blockName = parseValue();
}
}
if(!implicitBlockType.isEmpty() && blockName.isEmpty() &&
blockType != implicitBlockType &&
!scriptBlockTypes.contains(blockType))
{
blockName = blockType;
blockType = implicitBlockType;
}
QScopedPointer<BlockElement> block(new BlockElement(blockType, blockName, self));
int startLine = currentLine;
String endToken;
try
{
// How about some attributes?
// Syntax: {token value} '('|'{'
while(peekToken() != "(" && peekToken() != "{")
{
String keyName = peekToken();
nextToken();
if(peekToken() == "(" || peekToken() == "{")
{
throw SyntaxError("Info::parseBlockElement",
QString("Attribute on line %1 is missing a value")
.arg(currentLine));
}
InfoValue value = parseValue();
// This becomes a key element inside the block but it's
// flagged as Attribute.
block->add(new KeyElement(keyName, value, KeyElement::Attribute));
}
endToken = (peekToken() == "("? ")" : "}");
// Parse the contents of the block.
if(scriptBlockTypes.contains(blockType))
{
// Parse as Doomsday Script.
block->add(new KeyElement(SCRIPT_TOKEN, parseScript()));
}
else
{
// Move past the opening parentheses.
nextToken();
// Parse normally as Info.
while(peekToken() != endToken)
{
Element *element = parseElement();
if(!element)
{
throw SyntaxError("Info::parseBlockElement",
QString("Block element (on line %1) was never closed, end of file encountered before '%2' was found (on line %3).")
.arg(startLine).arg(endToken).arg(currentLine));
}
block->add(element);
}
}
}
catch(EndOfFile const &)
{
throw SyntaxError("Info::parseBlockElement",
QString("End of file encountered unexpectedly while parsing a block element (block started on line %1).")
.arg(startLine));
}
DENG2_ASSERT(peekToken() == endToken);
// Move past the closing parentheses.
nextToken();
return block.take();
}
void includeFrom(String const &includeName)
{
try
{
DENG2_ASSERT(finder != 0);
String includePath;
String content = finder->findIncludedInfoSource(includeName, self, &includePath);
Info included;
included.setImplicitBlockType(implicitBlockType);
included.setScriptBlocks(scriptBlockTypes);
included.setAllowDuplicateBlocksOfType(allowDuplicateBlocksOfType);
included.setFinder(*finder); // use ours
included.setSourcePath(includePath);
included.parse(content);
// Move the contents of the resulting root block to our root block.
included.d->rootBlock.moveContents(rootBlock);
}
catch(Error const &er)
{
throw IIncludeFinder::NotFoundError("Info::includeFrom",
QString("Cannot include '%1': %2")
.arg(includeName)
.arg(er.asText()));
}
}
void parse(String const &source)
{
init(source);
forever
{
Element *e = parseElement();
if(!e) break;
// If this is an include directive, try to acquire the inclusion and parse it
// instead. Inclusions are only possible at the root level.
if(e->isList() && e->name() == INCLUDE_TOKEN)
{
foreach(Element::Value const &val, e->as<ListElement>().values())
{
includeFrom(val);
}
}
rootBlock.add(e);
}
}
void parse(File const &file)
{
sourcePath = file.path();
parse(String::fromUtf8(Block(file)));
}
};
//---------------------------------------------------------------------------------------
DENG2_PIMPL_NOREF(Info::Element)
{
Type type;
String name;
BlockElement *parent = nullptr;
SourceLineTable::LineId sourceLine = 0;
};
Info::Element::Element(Type type, String const &name)
: d(new Instance)
{
d->type = type;
setName(name);
}
Info::Element::~Element()
{}
void Info::Element::setParent(BlockElement *parent)
{
d->parent = parent;
}
Info::BlockElement *Info::Element::parent() const
{
return d->parent;
}
void Info::Element::setSourceLocation(String const &sourcePath, int line)
{
d->sourceLine = de::sourceLineTable.lineId(sourcePath, line);
}
String Info::Element::sourceLocation() const
{
return de::sourceLineTable.sourceLocation(d->sourceLine);
}
duint32 Info::Element::sourceLineId() const
{
return d->sourceLine;
}
Info::Element::Type Info::Element::type() const
{
return d->type;
}
String const &Info::Element::name() const
{
return d->name;
}
void Info::Element::setName(String const &name)
{
d->name = name;
}
Info::BlockElement::~BlockElement()
{
clear();
}
void Info::BlockElement::clear()
{
for(ContentsInOrder::iterator i = _contentsInOrder.begin(); i != _contentsInOrder.end(); ++i)
{
delete *i;
}
_contents.clear();
_contentsInOrder.clear();
}
void Info::BlockElement::add(Info::Element *elem)
{
DENG2_ASSERT(elem != 0);
elem->setParent(this);
_contentsInOrder.append(elem); // owned
if(!elem->name().isEmpty())
{
_contents.insert(elem->name().toLower(), elem); // not owned (name may be empty)
}
}
Info::Element *Info::BlockElement::find(String const &name) const
{
Contents::const_iterator found = _contents.find(name.toLower());
if(found == _contents.end()) return 0;
return found.value();
}
Info::Element::Value Info::BlockElement::keyValue(String const &name) const
{
Element *e = find(name);
if(!e || !e->isKey()) return Value();
return e->as<KeyElement>().value();
}
Info::Element *Info::BlockElement::findByPath(String const &path) const
{
String name;
String remainder;
int pos = path.indexOf(':');
if(pos >= 0)
{
name = path.left(pos);
remainder = path.mid(pos + 1);
}
else
{
name = path;
}
name = name.trimmed();
// Does this element exist?
Element *e = find(name);
if(!e) return 0;
if(e->isBlock())
{
// Descend into sub-blocks.
return e->as<BlockElement>().findByPath(remainder);
}
return e;
}
void Info::BlockElement::moveContents(BlockElement &destination)
{
foreach(Element *e, _contentsInOrder)
{
destination.add(e);
}
_contentsInOrder.clear();
_contents.clear();
}
//---------------------------------------------------------------------------------------
Info::Info() : d(new Instance(this))
{}
Info::Info(String const &source) : d(nullptr)
{
QScopedPointer<Instance> inst(new Instance(this)); // parsing may throw exception
inst->parse(source);
d.reset(inst.take());
}
Info::Info(File const &file) : d(nullptr)
{
QScopedPointer<Instance> inst(new Instance(this)); // parsing may throw exception
inst->parse(file);
d.reset(inst.take());
}
Info::Info(String const &source, IIncludeFinder const &finder) : d(nullptr)
{
QScopedPointer<Instance> inst(new Instance(this)); // parsing may throw exception
inst->finder = &finder;
inst->parse(source);
d.reset(inst.take());
}
void Info::setFinder(IIncludeFinder const &finder)
{
d->finder = &finder;
}
void Info::useDefaultFinder()
{
d->finder = &d->defaultFinder;
}
void Info::setScriptBlocks(QStringList const &blocksToParseAsScript)
{
d->scriptBlockTypes = blocksToParseAsScript;
}
void Info::setAllowDuplicateBlocksOfType(QStringList const &duplicatesAllowed)
{
d->allowDuplicateBlocksOfType = duplicatesAllowed;
}
void Info::setImplicitBlockType(String const &implicitBlock)
{
d->implicitBlockType = implicitBlock;
}
void Info::parse(String const &infoSource)
{
d->parse(infoSource);
}
void Info::parse(File const &file)
{
d->parse(file);
}
void Info::parseNativeFile(NativePath const &nativePath)
{
QFile file(nativePath);
if(file.open(QFile::ReadOnly | QFile::Text))
{
parse(file.readAll().constData());
}
}
void Info::clear()
{
d->sourcePath.clear();
parse("");
}
void Info::setSourcePath(String const &path)
{
d->sourcePath = path;
}
String Info::sourcePath() const
{
return d->sourcePath;
}
Info::BlockElement const &Info::root() const
{
return d->rootBlock;
}
Info::Element const *Info::findByPath(String const &path) const
{
if(path.isEmpty()) return &d->rootBlock;
return d->rootBlock.findByPath(path);
}
bool Info::findValueForKey(String const &key, String &value) const
{
Element const *element = findByPath(key);
if(element && element->isKey())
{
value = element->as<KeyElement>().value();
return true;
}
return false;
}
bool Info::isEmpty() const
{
return d->rootBlock.isEmpty();
}
String Info::sourceLocation(duint32 lineId) // static
{
return de::sourceLineTable.sourceLocation(lineId);
}
SourceLineTable const &Info::sourceLineTable() // static
{
return de::sourceLineTable;
}
} // namespace de