File: textfileparser.cpp

package info (click to toggle)
asc 2.6.1.0-9
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 81,740 kB
  • sloc: cpp: 158,704; sh: 11,544; ansic: 6,736; makefile: 604; perl: 138
file content (518 lines) | stat: -rw-r--r-- 15,632 bytes parent folder | download | duplicates (7)
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
/***************************************************************************
                          textfileparser.cpp  -  description
                             -------------------
    begin                : Thu Jul 26 2001
    copyright            : (C) 2001 by Martin Bickel
    email                : bickel@asc-hq.org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include <vector>
#include <SDL_image.h>
#include <algorithm>
#include "ascstring.h"
#include "textfileparser.h"
#include "stringtokenizer.h"
#include "textfile_evaluation.h"


const int TextFormatParser::operationsNum = 6;
const char* TextFormatParser::operations[6] =  { "=", "*=", "+=", "->", "->*", "-=" };
const char* TextFormatParser::whiteSpace = " \t";




ASCString TextPropertyGroup::Entry::toString() const
{
   Operator o = op;
   if ( o == alias_all_resolved )
     o = alias_all;

   ASCString s = propertyName + TextFormatParser::operations[o] + value ;
   return s;
}

void TextPropertyList::buildIDs()
{
   for ( iterator i = begin(); i != end(); i++ ) {
      int id = (*i)->evalID();
      if ( id > 0 ) {

         if ( identCache.find ( id ) != identCache.end() )
            fatalError("Duplicate ID in text file group " + (*i)->typeName + ": " + (*i)->location + " and " + identCache.find ( id )->second->location + " both have ID " + strrr(id ) + "\n\nThis is NOT a bug in ASC, this is a conflict between two data files.");

         identCache[id] = *i;
      }
   }
}

TextPropertyGroup* TextPropertyList::get ( int id )
{
   IdentCache::iterator f = identCache.find ( id );
   if ( f != identCache.end() )
      return &(*(f->second));
   else
      return NULL;
}


///////////////////// TextPropertyGroup //////////////////////////


void TextPropertyGroup :: error ( const ASCString& msg, bool printInheritance )
{
   ASCString message = "Error evaluating file " + location + "\n" + msg;
   if ( printInheritance )
      message += "\nThe inheritance is\n" + listInheritanceFilenames() ;

   fatalError ( message );
}

void TextPropertyGroup :: print( int indent )
{
   for ( Entries::iterator i = entries.begin(); i != entries.end(); i++ ) {
      for ( int m = 0; m<= indent; m++ )
         displayLogMessage(10, "  " );

      displayLogMessage(10,  i->toString());
      displayLogMessage(10,  "\n");
   }

   for ( Parents::iterator i = parents.begin(); i != parents.end(); i++ ) {
      for ( int n = 0; n< indent; n++ )
         printf("  " );
      displayLogMessage(10, "  is inheriting from " + (*i)->location + "\n" );
      (*i)->print(indent+1 );
   }
}


void TextPropertyGroup :: buildInheritance(TextPropertyList& tpl )
{
   static list<TextPropertyGroup*> callStack;

   if ( !inheritanceBuild ) {
      if ( std::find ( callStack.begin(), callStack.end(), this ) != callStack.end() )
         error ( "endless inheritance loop detected: type " + typeName + "; ID " + strrr ( id ), false);

      callStack.push_back( this );

      PropertyReadingContainer prc ( typeName, this );
      prc.addBool ( "abstract", abstract, false );
      int iid;
      prc.addInteger("ID", iid, 0 );

      if ( find ( typeName+".parent") != NULL ) {
         typedef vector<int> ParentIDs;
         ParentIDs parentIDs;
         prc.addIntegerArray ( "parent", parentIDs );
         for ( ParentIDs::iterator i = parentIDs.begin(); i != parentIDs.end(); i++ ) {
            TextPropertyGroup* p = tpl.get ( *i );
            if ( p ) {
               parents.push_back ( p );
               displayLogMessage( 10, ASCString("  entering parent with ID ") + strrr(*i) + " ("+p->location+")\n" );
               p->buildInheritance( tpl );
               displayLogMessage( 10, ASCString("  leaving parent with ID ") + strrr(*i) + "\n" );
            } else
               error ( location + " : no parent with ID " + strrr(*i) + " of type " + typeName + " could be found !" );
         }
      }

      //! building inheritance
      /*
      for ( Entries::iterator i = entries.begin(); i != entries.end(); i++ ) {
         if ( i->op != Entry::eq && i->op != Entry::alias_all && i->op != Entry::alias) {
            Parents::iterator p = parents.begin();
            while ( p != parents.end() ) {
               i->parent = (*p)->find( i->propertyName );
               if ( i->parent )
                  break;
               p++;
            }
            if ( p == parents.end())
               error ( "could not find a parent entry for " + typeName + " :: " + i->propertyName  );
         }
      }
      */

      resolveAllAlias();

      callStack.pop_back();
      inheritanceBuild = true;
   }
}

ASCString TextPropertyGroup :: listInheritanceFilenames()
{
   ASCString s;
   for ( Parents::iterator p = parents.begin(); p != parents.end(); p++ )
      s += (*p)->listInheritanceFilenames();
   s += location + "\n";
   return s;
}

void TextPropertyGroup :: resolveAllAlias( )
{
   int loop = 0;
   typedef list<Entry*> Unresolved;
   Unresolved unresolved;
   do {
      Entries additionalEntries;
      int resolvedCounter = 0;
      EntryPointerList toResolve;

      if ( loop == 0 ) {
         for ( Entries::iterator i = entries.begin(); i != entries.end(); i++ ) {
            bool resolved = processAlias ( *i , additionalEntries, toResolve );
            if ( !resolved )
                unresolved.push_back ( &(*i) );
            else
                resolvedCounter++;
         }
      } else {
         Unresolved newunresolved;
         for ( Unresolved::iterator i = unresolved.begin(); i != unresolved.end(); i++ ) {
            bool resolved = processAlias ( **i , additionalEntries, toResolve );
            if ( !resolved )
                newunresolved.push_back ( *i );
            else
                resolvedCounter++;
         }
         unresolved = newunresolved;
      }

      for ( Entries::iterator i = additionalEntries.begin(); i != additionalEntries.end(); i++ )
         // if ( find ( i->propertyName ) == NULL )
            addEntry ( *i );

      for ( EntryPointerList::iterator i = toResolve.begin(); i != toResolve.end(); i++ )
         (*i)->op = Entry::alias_all_resolved;

      if ( !resolvedCounter && !unresolved.empty() )
         for ( Unresolved::iterator i = unresolved.begin(); i != unresolved.end(); i++ ) {
            error (  "could not resolve the reference for " + typeName + " :: " + (*i)->propertyName + " with operand " + (*i)->value + "\nSee STDOUT for a dump of current item" );
            print();
         }
         
      loop++;
   } while ( !unresolved.empty() );
}

bool reallyVerbose = false;

int TextPropertyGroup::findGeneration ( Entry* e )
{
   for ( Entries::iterator i = entries.begin(); i != entries.end(); i++ )
      if ( &(*i) == e )
         return 0;

   for ( Parents::iterator i = parents.begin(); i != parents.end(); i++ ) {
      int fg = (*i)->findGeneration( e );
      if ( fg >= 0 )
         return fg+1;
   }
   return -1;
}


bool TextPropertyGroup::processAlias( Entry& e, Entries& entriesToAdd, EntryPointerList& markAsResolved )
{
   if ( e.op == Entry::alias_all ) {
      ASCString ss = e.value;
      ss.toLower();
      ASCString::size_type pos;
      do {
         pos = ss.find ( " " );
         if ( pos != ss.npos )
            ss.erase(pos,1);
      } while ( pos != ss.npos );

      ASCString s_without_dot = ss;
      if ( ss.length() > 0 )
         if ( ss[ss.length()-1] != '.' )
            ss = ss + ".";

      if ( s_without_dot.length() > 0 )
         if ( s_without_dot[s_without_dot.length()-1] == '.' )
            s_without_dot.erase ( s_without_dot.length()-1 );

      ASCString newName = e.propertyName;
      if ( newName.length() > 0 )
         if ( newName[newName.length()-1] != '.' )
            newName = newName + ".";

      int counter = 0;
      Matches matches;


      findMatches ( ss, s_without_dot, matches );

      for ( Matches::iterator i = matches.begin(); i != matches.end(); i++ )
         if ( (*i)->op == Entry::alias_all ) {
            displayLogMessage ( 9, "  alias is pending " + ss + "* <- " + e.propertyName + " because " + (*i)->propertyName + " is unresolved\n" );
            return false;
         }

      for ( Matches::iterator i = matches.begin(); i != matches.end(); i++ )
         if ( (*i)->op != Entry::alias_all_resolved ) {
            Entry e = **i;
            e.propertyName.replace ( 0, ss.length(), newName );
            TextPropertyGroup::Entry* existent = find ( e.propertyName );
            // if ( existent == NULL || findGeneration(*i) <= findGeneration( existent ) ) {
            if ( existent == NULL || findGeneration( existent ) > 0 ) {
               /* if ( existent && findGeneration( existent ) == 0 ) {
                  displayLogMessage(10, "    overwriting entry " + existent->toString() + " because it belongs to an older generation\n" );
                  *existent = e;
               } else */
               entriesToAdd.push_back ( e );
               displayLogMessage(10, "   aliasing entry " + (*i)->toString() + " to " + e.propertyName + " \n" );
            }
            counter++;
         } else
            displayLogMessage(10, "   skipping aliasing entry " + (*i)->toString() + " to " + e.propertyName + " because it is already resolved\n" );

      if ( !counter ) {
         displayLogMessage ( 9, "  could not successfully resolve alias " + ss + "* <- " + e.propertyName + "\n" );
         return false;
      } else {
         markAsResolved.push_back ( &e );
         displayLogMessage ( 9, "  successfully resolved alias " + e.propertyName + " ->* " + ss + "\n" );
         return true;
      }
   }

   if ( e.op == Entry::alias ) {
      ASCString s = e.value;
      s.toLower();
      ASCString::size_type pos;
      do {
            pos = s.find ( " " );
            if ( pos != s.npos )
               s.erase(pos,1);
      } while ( pos != s.npos );
      Entry* alias = find ( s );
      if ( !alias )
         return false;
      else {
         e.value = alias->value;
         e.op = alias->op;
         e.parent = alias->parent;
         return true;
      }
   }

   //! building inheritance
   if ( e.op != Entry::eq && e.op != Entry::alias_all && e.op != Entry::alias && e.op != Entry::alias_all_resolved  ) {
      Parents::iterator p = parents.begin();
      while ( p != parents.end() ) {
         e.parent = (*p)->find( e.propertyName );
         if ( e.parent )
            break;
         p++;
      }
      if ( p == parents.end())
         return false;
      else
         return true;
   }


   return true;
}


int TextPropertyGroup :: evalID()
{
   PropertyReadingContainer prc ( typeName, this );
   prc.addInteger ( "ID", id, 0 );
   return id;
}




TextPropertyGroup::Entry*  TextPropertyGroup :: find( const ASCString& n )
{
   EntryCache::iterator i = entryCache.find ( n );
   if ( i != entryCache.end() )
      return i->second;
   else {
      for ( Parents::iterator p = parents.begin(); p != parents.end(); p++ ) {
         TextPropertyGroup::Entry* ent = (*p)->find ( n );
         if ( ent )
            return ent;
      }
      return NULL;
   }
}

void TextPropertyGroup::findMatches( const ASCString& name, const ASCString& name_without_dot, Matches& matches )
{
   for ( Entries::iterator i = entries.begin(); i != entries.end(); i++ ) 
      if ( i->propertyName.find ( name ) == 0 || i->propertyName == name_without_dot )
         matches.push_back ( &(*i) );

   for ( Parents::iterator p = parents.begin(); p != parents.end(); p++ )
      (*p)->findMatches ( name, name_without_dot, matches );
}


void TextPropertyGroup::addEntry( const Entry& entry )
{
   entries.push_back ( entry );
   entryCache[entry.propertyName] = &entries.back();
}



///////////////////// TextFormatParser //////////////////////////

ASCString TextFormatParser::readLine ( )
{
   ASCString s;
   int noCommentLines = 0;
   int bracketsOpen = 0;
   do {
      ASCString t = stream->readString();
      ASCString::size_type pos = t.find_first_not_of ( whiteSpace );
      if ( pos != ASCString::npos ) {
         if ( t[pos] != ';' ) {
            noCommentLines++;
            if ( !s.empty() )
               s += " ";

            s += t.substr ( pos );

            if ( t.find ( "[" ) != t.npos )
               bracketsOpen++;

            if ( t.find ( "]" ) != t.npos )
               bracketsOpen--;
         }
      } else {
         // empty line
         if ( bracketsOpen )
            s += "\n";
      }

   } while ( noCommentLines == 0 || bracketsOpen > 0 );

   ASCString::size_type pos = s.find ( "[" );
   if ( pos != s.npos )
      s.erase ( pos, 1 );

   pos = s.rfind ( "]" );
   if ( pos != s.npos )
      s.erase ( pos, 1 );

   return s;
}



void TextFormatParser::parseLine ( const ASCString& line )
{

   StringTokenizer st ( line );
   s1 = st.getNextToken();
   s2 = st.getNextToken();
   s3 = st.getRemaining();

   int op = -1;
   for ( int i = 0; i < operationsNum; i++ )
      if ( s2 == operations[i] )
         op = i;

   if ( op != -1 ) {
      /*
      if ( s3.empty() )
         error ( "missing data after operand");
      */

      ASCString s;
      for ( Level::iterator i = level.begin(); i != level.end(); i++ )
         s += *i + ".";
      s += s1;
      textPropertyGroup->addEntry ( TextPropertyGroup::Entry (s, TextPropertyGroup::Entry::Operator(op), s3 ) );
      return;
   }

   if ( !s1.empty() && s2 == "{" ) {
      s1.toLower();
      startLevel ( s1 );
      return;
   }

   if ( s1 == "}" ) {
      if ( level.empty() )
         error ("closing unopened bracket");

      s2.toLower();
      if ( s2 != level.back() )
         error ( "unmatching close brackets: " + s2 );

      level.pop_back();
      levelDepth--;
      return;
   }
   error ( "unknown operator in entry " + line + "\n token1: " + s1 + " ; token2: " + s2 + " ; token3: " + s3 );
}


void TextFormatParser::startLevel ( const ASCString& levelName )
{

   if ( levelDepth == 0  ) {
      if ( !primaryName.empty() )
         if ( levelName.compare_ci ( primaryName )  )
            error ( "expecting group " + primaryName + " , found " + levelName );
      textPropertyGroup->typeName = levelName;
      textPropertyGroup->typeName.toLower();
   }

   int curlevel = ++levelDepth;
   level.push_back ( levelName );

   do {
       parseLine ( readLine() );
   } while ( levelDepth >= curlevel );
}


TextPropertyGroup* TextFormatParser::run (  )
{
   textPropertyGroup = new TextPropertyGroup ;
   textPropertyGroup->fileName = stream->getDeviceName();
   textPropertyGroup->location = stream->getLocation();
   textPropertyGroup->archive = stream->getArchive();
   parseLine ( readLine() );
   return textPropertyGroup;
}

void TextFormatParser::error ( const ASCString& errmsg )
{
   ASCString msg;
   if ( stream )
      msg =  stream->getLocation() + " : " + errmsg;
   else
      msg =  " : " + errmsg ;

   displayLogMessage ( 0, msg + "\n" );

   throw ParsingError ( msg );
}