/
info.cpp
707 lines (614 loc) · 18.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
/*
* The Doomsday Engine Project -- libdeng2
*
* Copyright (c) 2012-2013 Jaakko Keränen <jaakko.keranen@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "de/Info"
#include "de/ScriptLex"
#include "de/Log"
#include "de/LogBuffer"
#include <QFile>
using 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;
DENG2_PIMPL(Info)
{
DENG2_ERROR(OutOfElements);
DENG2_ERROR(EndOfFile);
QStringList scriptBlockTypes;
QStringList allowDuplicateBlocksOfType;
String content;
int currentLine;
int cursor; ///< Index of the next character from the source.
QChar currentChar;
int tokenStartOffset;
String currentToken;
BlockElement rootBlock;
typedef Info::Element::Value InfoValue;
Instance(Public *i)
: Base(i),
currentLine(0), cursor(0), tokenStartOffset(0),
rootBlock("", "", *i)
{
scriptBlockTypes << "script";
}
/**
* 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->setLineNumber(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)
*/
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.
if(peekToken() == "\"")
{
try
{
// The value will be composed of any number of sub-strings.
forever { value.text += parseString(); }
}
catch(de::Error const &)
{
// No more strings to append.
return value;
}
}
// Then it must be a single token.
value = peekToken();
nextToken();
return value;
}
InfoValue parseScript(int numStatements = 0)
{
int startPos = cursor - 1;
String remainder = content.substr(startPos);
ScriptLex lex(remainder);
try
{
TokenBuffer tokens;
int count = 0;
// Read an appropriate number of statements.
while(lex.getStatement(tokens))
{
if(numStatements > 0 && ++count == numStatements)
goto success;
}
throw SyntaxError("Info::parseScript",
QString("Unexpected end of script starting at line %1").arg(currentLine));
success:;
}
catch(ScriptLex::MismatchedBracketError const &)
{
// A mismatched bracket signals the end of the script block.
}
// 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);
return InfoValue(content.substr(startPos, lex.pos() - 1), 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 const &blockType)
{
DENG2_ASSERT(blockType != "}");
DENG2_ASSERT(blockType != ")");
String blockName;
if(peekToken() != "(" && peekToken() != "{")
{
blockName = parseValue();
}
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();
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", 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 was never closed, end of file encountered before '%1' was found (on line %2).")
.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 parse(String const &source)
{
init(source);
forever
{
Element *e = parseElement();
if(!e) break;
rootBlock.add(e);
}
}
};
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);
/*
/// @todo This check is at the wrong level. Conditions may be applied
/// to resolve duplicates. Check when processing...
// Check for duplicate identifiers in this block.
if(elem->name() && _contents.contains(elem->name()))
{
if(!elem->isBlock() || !info().d->allowDuplicateBlocksOfType.contains(
elem->as<BlockElement>().blockType()))
{
LOG_AS("Info::BlockElement");
LOG_WARNING("Block '%s' already has an element named '%s'")
<< name() << elem->name();
}
}
*/
elem->setParent(this);
_contentsInOrder.append(elem); // owned
if(!elem->name().isEmpty())
{
_contents.insert(elem->name(), elem); // not owned (name may be empty)
}
}
Info::Element *Info::BlockElement::find(String const &name) const
{
Contents::const_iterator found = _contents.find(name);
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;
}
Info::Info() : d(new Instance(this))
{}
Info::Info(String const &source)
{
QScopedPointer<Instance> inst(new Instance(this)); // parsing may throw exception
inst->parse(source);
d.reset(inst.take());
}
void Info::setScriptBlocks(QStringList const &blocksToParseAsScript)
{
d->scriptBlockTypes = blocksToParseAsScript;
}
void Info::setAllowDuplicateBlocksOfType(QStringList const &duplicatesAllowed)
{
d->allowDuplicateBlocksOfType = duplicatesAllowed;
}
void Info::parse(String const &infoSource)
{
d->parse(infoSource);
}
void Info::parseNativeFile(NativePath const &nativePath)
{
QFile file(nativePath);
if(file.open(QFile::ReadOnly | QFile::Text))
{
parse(file.readAll().constData());
}
}
void Info::clear()
{
parse("");
}
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;
}