Make tablegen take an input filename to parse if one is specified, otherwise
[oota-llvm.git] / utils / TableGen / FileParser.y
1 //===-- FileParser.y - Parser for TableGen files ----------------*- C++ -*-===//
2 //
3 //  This file implements the bison parser for Table Generator files...
4 //
5 //===------------------------------------------------------------------------=//
6
7 %{
8 #include "Record.h"
9 #include "Support/StringExtras.h"
10 #include <iostream>
11 #include <algorithm>
12 #include <cstdio>
13 #define YYERROR_VERBOSE 1
14
15 int yyerror(const char *ErrorMsg);
16 int yylex();
17 extern FILE *Filein;
18 extern int Filelineno;
19 int Fileparse();
20 static Record *CurRec = 0;
21
22 typedef std::pair<Record*, std::vector<Init*>*> SubClassRefTy;
23
24 static std::vector<std::pair<std::pair<std::string, std::vector<unsigned>*>,
25                              Init*> > SetStack;
26
27 void ParseFile(const std::string &Filename) {
28   FILE *F = stdin;
29   if (Filename != "-") {
30     F = fopen(Filename.c_str(), "r");
31
32     if (F == 0) {
33       std::cerr << "Could not open input file '" + Filename + "'!\n";
34       abort();
35     }
36   }
37
38
39   Filein = F;
40   Filelineno = 1;
41   Fileparse();
42
43   if (F != stdin)
44     fclose(F);
45   Filein = stdin;
46 }
47
48 static std::ostream &err() {
49   return std::cerr << "Parsing Line #" << Filelineno << ": ";
50 }
51
52 static void addValue(const RecordVal &RV) {
53   if (CurRec->getValue(RV.getName())) {
54     err() << "Value '" << RV.getName() << "' multiply defined!\n";
55     abort();
56   }
57
58   CurRec->addValue(RV);
59 }
60
61 static void addSuperClass(Record *SC) {
62   if (CurRec->isSubClassOf(SC)) {
63     err() << "Already subclass of '" << SC->getName() << "'!\n";
64     abort();
65   }
66   CurRec->addSuperClass(SC);
67 }
68
69 static void setValue(const std::string &ValName, 
70                      std::vector<unsigned> *BitList, Init *V) {
71   if (!V) return ;
72
73   RecordVal *RV = CurRec->getValue(ValName);
74   if (RV == 0) {
75     err() << "Value '" << ValName << "' unknown!\n";
76     abort();
77   }
78   
79   // If we are assigning to a subset of the bits in the value... then we must be
80   // assigning to a field of BitsRecTy, which must have a BitsInit
81   // initializer...
82   //
83   if (BitList) {
84     BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
85     if (CurVal == 0) {
86       err() << "Value '" << ValName << "' is not a bits type!\n";
87       abort();
88     }
89
90     // Convert the incoming value to a bits type of the appropriate size...
91     Init *BI = V->convertInitializerTo(new BitsRecTy(BitList->size()));
92     if (BI == 0) {
93       V->convertInitializerTo(new BitsRecTy(BitList->size()));
94       err() << "Initializer '" << *V << "' not compatible with bit range!\n";
95       abort();
96     }
97
98     // We should have a BitsInit type now...
99     assert(dynamic_cast<BitsInit*>(BI) != 0 || &(std::cerr << *BI) == 0);
100     BitsInit *BInit = (BitsInit*)BI;
101
102     BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
103
104     // Loop over bits, assigning values as appropriate...
105     for (unsigned i = 0, e = BitList->size(); i != e; ++i) {
106       unsigned Bit = (*BitList)[i];
107       if (NewVal->getBit(Bit)) {
108         err() << "Cannot set bit #" << Bit << " of value '" << ValName
109               << "' more than once!\n";
110         abort();
111       }
112       NewVal->setBit(Bit, BInit->getBit(i));
113     }
114
115     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
116       if (NewVal->getBit(i) == 0)
117         NewVal->setBit(i, CurVal->getBit(i));
118
119     V = NewVal;
120   }
121
122   if (RV->setValue(V)) {
123     err() << "Value '" << ValName << "' of type '" << *RV->getType()
124           << "' is incompatible with initializer '" << *V << "'!\n";
125     abort();
126   }
127 }
128
129 static void addSubClass(Record *SC, const std::vector<Init*> &TemplateArgs) {
130   // Add all of the values in the subclass into the current class...
131   const std::vector<RecordVal> &Vals = SC->getValues();
132   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
133     addValue(Vals[i]);
134
135   const std::vector<std::string> &TArgs = SC->getTemplateArgs();
136
137   // Ensure that an appropriate number of template arguments are specified...
138   if (TArgs.size() < TemplateArgs.size()) {
139     err() << "ERROR: More template args specified than expected!\n";
140     abort();
141   } else {    // This class expects template arguments...
142     // Loop over all of the template arguments, setting them to the specified
143     // value or leaving them as the default as neccesary.
144     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
145       if (i < TemplateArgs.size()) {  // A value is specified for this temp-arg?
146         // Set it now.
147         setValue(TArgs[i], 0, TemplateArgs[i]);
148       } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
149         err() << "ERROR: Value not specified for template argument #"
150               << i << " (" << TArgs[i] << ") of subclass '" << SC->getName()
151               << "'!\n";
152         abort();
153       }
154     }
155   }
156
157
158   // Since everything went well, we can now set the "superclass" list for the
159   // current record.
160   const std::vector<Record*>   &SCs  = SC->getSuperClasses();
161   for (unsigned i = 0, e = SCs.size(); i != e; ++i)
162     addSuperClass(SCs[i]);
163   addSuperClass(SC);
164 }
165
166
167 %}
168
169 %union {
170   std::string          *StrVal;
171   int                   IntVal;
172   RecTy                *Ty;
173   Init                 *Initializer;
174   std::vector<Init*>   *FieldList;
175   std::vector<Record*> *RecPtr;
176   std::vector<unsigned>*BitList;
177   Record               *Rec;
178   SubClassRefTy        *SubClassRef;
179   std::vector<SubClassRefTy> *SubClassList;
180 };
181
182 %token INT BIT STRING BITS LIST CLASS DEF FIELD SET IN
183 %token <IntVal>      INTVAL
184 %token <StrVal>      ID STRVAL
185
186 %type <Ty>           Type
187 %type <RecPtr>       DefList DefListNE
188 %type <Rec>          ClassInst DefInst Object ObjectBody ClassID DefID
189
190 %type <SubClassRef>  SubClassRef
191 %type <SubClassList> ClassList ClassListNE
192 %type <IntVal>       OptPrefix
193 %type <Initializer>  Value OptValue
194 %type <FieldList>    ValueList ValueListNE
195 %type <BitList>      BitList OptBitList RBitList
196 %type <StrVal>       Declaration OptID
197
198 %start File
199 %%
200
201 ClassID : ID {
202     $$ = Records.getClass(*$1);
203     if ($$ == 0) {
204       err() << "Couldn't find class '" << *$1 << "'!\n";
205       abort();
206     }
207     delete $1;
208   };
209
210 DefID : ID {
211     $$ = Records.getDef(*$1);
212     if ($$ == 0) {
213       err() << "Couldn't find def '" << *$1 << "'!\n";
214       abort();
215     }
216     delete $1;
217   };
218
219
220 // TableGen types...
221 Type : STRING {                       // string type
222     $$ = new StringRecTy();
223   } | BIT {                           // bit type
224     $$ = new BitRecTy();
225   } | BITS '<' INTVAL '>' {           // bits<x> type
226     $$ = new BitsRecTy($3);
227   } | INT {                           // int type
228     $$ = new IntRecTy();
229   } | LIST '<' ClassID '>' {          // list<x> type
230     $$ = new ListRecTy($3);
231   } | ClassID {                       // Record Type
232     $$ = new RecordRecTy($1);
233   };
234
235 OptPrefix : /*empty*/ { $$ = 0; } | FIELD { $$ = 1; };
236
237 OptValue : /*empty*/ { $$ = 0; } | '=' Value { $$ = $2; };
238
239 Value : INTVAL {
240     $$ = new IntInit($1);
241   } | STRVAL {
242     $$ = new StringInit(*$1);
243     delete $1;
244   } | '?' {
245     $$ = new UnsetInit();
246   } | '{' ValueList '}' {
247     BitsInit *Init = new BitsInit($2->size());
248     for (unsigned i = 0, e = $2->size(); i != e; ++i) {
249       struct Init *Bit = (*$2)[i]->convertInitializerTo(new BitRecTy());
250       if (Bit == 0) {
251         err() << "Element #" << i << " (" << *(*$2)[i]
252               << ") is not convertable to a bit!\n";
253         abort();
254       }
255       Init->setBit($2->size()-i-1, Bit);
256     }
257     $$ = Init;
258     delete $2;
259   } | ID {
260     if (CurRec == 0) {
261       err() << "Def/Class name '" << *$1 << "' not allowed here!\n";
262       abort();
263     }
264     if (const RecordVal *RV = CurRec->getValue(*$1)) {
265       $$ = new VarInit(*$1, RV->getType());
266     } else if (Record *D = Records.getDef(*$1)) {
267       $$ = new DefInit(D);
268     } else {
269       err() << "Variable not defined: '" << *$1 << "'!\n";
270       abort();
271     }
272     
273     delete $1;
274   } | Value '{' BitList '}' {
275     $$ = $1->convertInitializerBitRange(*$3);
276     if ($$ == 0) {
277       err() << "Invalid bit range for value '" << *$1 << "'!\n";
278       abort();
279     }
280     delete $3;
281   } | '[' DefList ']' {
282     $$ = new ListInit(*$2);
283     delete $2;
284   } | Value '.' ID {
285     if (!$1->getFieldType(*$3)) {
286       err() << "Cannot access field '" << *$3 << "' of value '" << *$1 << "!\n";
287       abort();
288     }
289     $$ = new FieldInit($1, *$3);
290     delete $3;
291   };
292
293 DefList : /*empty */ {
294     $$ = new std::vector<Record*>();
295   } | DefListNE {
296     $$ = $1;
297   };
298 DefListNE : DefID {
299     $$ = new std::vector<Record*>();
300     $$->push_back($1);
301   } | DefListNE ',' DefID {
302     ($$=$1)->push_back($3);
303   };
304
305
306 RBitList : INTVAL {
307     $$ = new std::vector<unsigned>();
308     $$->push_back($1);
309   } | INTVAL '-' INTVAL {
310     if ($1 < $3 || $1 < 0 || $3 < 0) {
311       err() << "Invalid bit range: " << $1 << "-" << $3 << "!\n";
312       abort();
313     }
314     $$ = new std::vector<unsigned>();
315     for (int i = $1; i >= $3; --i)
316       $$->push_back(i);
317   } | INTVAL INTVAL {
318     $2 = -$2;
319     if ($1 < $2 || $1 < 0 || $2 < 0) {
320       err() << "Invalid bit range: " << $1 << "-" << $2 << "!\n";
321       abort();
322     }
323     $$ = new std::vector<unsigned>();
324     for (int i = $1; i >= $2; --i)
325       $$->push_back(i);
326   } | RBitList ',' INTVAL {
327     ($$=$1)->push_back($3);
328   } | RBitList ',' INTVAL '-' INTVAL {
329     if ($3 < $5 || $3 < 0 || $5 < 0) {
330       err() << "Invalid bit range: " << $3 << "-" << $5 << "!\n";
331       abort();
332     }
333     $$ = $1;
334     for (int i = $3; i >= $5; --i)
335       $$->push_back(i);
336   } | RBitList ',' INTVAL INTVAL {
337     $4 = -$4;
338     if ($3 < $4 || $3 < 0 || $4 < 0) {
339       err() << "Invalid bit range: " << $3 << "-" << $4 << "!\n";
340       abort();
341     }
342     $$ = $1;
343     for (int i = $3; i >= $4; --i)
344       $$->push_back(i);
345   };
346
347 BitList : RBitList { $$ = $1; std::reverse($1->begin(), $1->end()); };
348
349 OptBitList : /*empty*/ { $$ = 0; } | '{' BitList '}' { $$ = $2; };
350
351
352
353 ValueList : /*empty*/ {
354     $$ = new std::vector<Init*>();
355   } | ValueListNE {
356     $$ = $1;
357   };
358
359 ValueListNE : Value {
360     $$ = new std::vector<Init*>();
361     $$->push_back($1);
362   } | ValueListNE ',' Value {
363     ($$ = $1)->push_back($3);
364   };
365
366 Declaration : OptPrefix Type ID OptValue {
367   addValue(RecordVal(*$3, $2, $1));
368   setValue(*$3, 0, $4);
369   $$ = $3;
370 };
371
372 BodyItem : Declaration ';' {
373   delete $1;
374 } | SET ID OptBitList '=' Value ';' {
375   setValue(*$2, $3, $5);
376   delete $2;
377   delete $3;
378 };
379
380 BodyList : /*empty*/ | BodyList BodyItem;
381 Body : ';' | '{' BodyList '}';
382
383 SubClassRef : ClassID {
384     $$ = new SubClassRefTy($1, new std::vector<Init*>());
385   } | ClassID '<' ValueListNE '>' {
386     $$ = new SubClassRefTy($1, $3);
387   };
388
389 ClassListNE : SubClassRef {
390     $$ = new std::vector<SubClassRefTy>();
391     $$->push_back(*$1);
392     delete $1;
393   }
394   | ClassListNE ',' SubClassRef {
395     ($$=$1)->push_back(*$3);
396     delete $3;
397   };
398
399 ClassList : /*empty */ {
400     $$ = new std::vector<SubClassRefTy>();
401   }
402   | ':' ClassListNE {
403     $$ = $2;
404   };
405
406 DeclListNE : Declaration {
407   CurRec->addTemplateArg(*$1);
408   delete $1;
409 } | DeclListNE ',' Declaration {
410   CurRec->addTemplateArg(*$3);
411   delete $3;
412 };
413
414 TemplateArgList : '<' DeclListNE '>' {};
415 OptTemplateArgList : /*empty*/ | TemplateArgList;
416
417 OptID : ID { $$ = $1; } | /*empty*/ { $$ = new std::string(); };
418
419 ObjectBody : OptID {
420            static unsigned AnonCounter = 0;
421            if ($1->empty())
422              *$1 = "anonymous."+utostr(AnonCounter++);
423            CurRec = new Record(*$1);
424            delete $1;
425          } OptTemplateArgList ClassList {
426            for (unsigned i = 0, e = $4->size(); i != e; ++i) {
427              addSubClass((*$4)[i].first, *(*$4)[i].second);
428              // Delete the template arg values for the class
429              delete (*$4)[i].second;
430            }
431
432            // Process any variables on the set stack...
433            for (unsigned i = 0, e = SetStack.size(); i != e; ++i)
434              setValue(SetStack[i].first.first, SetStack[i].first.second,
435                       SetStack[i].second);
436          } Body {
437   CurRec->resolveReferences();
438
439   // Now that all of the references have been resolved, we can delete template
440   // arguments for superclasses, so they don't pollute our record, and so that
441   // their names won't conflict with later uses of the name...
442   for (unsigned i = 0, e = $4->size(); i != e; ++i) {
443     Record *SuperClass = (*$4)[i].first;
444     for (unsigned i = 0, e = SuperClass->getTemplateArgs().size(); i != e; ++i)
445     CurRec->removeValue(SuperClass->getTemplateArgs()[i]);
446   }
447   delete $4;   // Delete the class list...
448
449   $$ = CurRec;
450   CurRec = 0;
451 };
452
453 ClassInst : CLASS ObjectBody {
454   if (Records.getClass($2->getName())) {
455     err() << "Class '" << $2->getName() << "' already defined!\n";
456     abort();
457   }
458   Records.addClass($$ = $2);
459 };
460
461 DefInst : DEF ObjectBody {
462   if (!$2->getTemplateArgs().empty()) {
463     err() << "Def '" << $2->getName()
464           << "' is not permitted to have template arguments!\n";
465     abort();
466   }
467   // If ObjectBody has template arguments, it's an error.
468   if (Records.getDef($2->getName())) {
469     err() << "Def '" << $2->getName() << "' already defined!\n";
470     abort();
471   }
472   Records.addDef($$ = $2);
473 };
474
475
476 Object : ClassInst | DefInst;
477
478 // SETCommand - A 'SET' statement start...
479 SETCommand : SET ID OptBitList '=' Value IN {
480   SetStack.push_back(std::make_pair(std::make_pair(*$2, $3), $5));
481   delete $2;
482 };
483
484 // Support Set commands wrapping objects... both with and without braces.
485 Object : SETCommand '{' ObjectList '}' {
486     delete SetStack.back().first.second; // Delete OptBitList
487     SetStack.pop_back();
488   }
489   | SETCommand Object {
490     delete SetStack.back().first.second; // Delete OptBitList
491     SetStack.pop_back();
492   };
493
494 ObjectList : Object {} | ObjectList Object {};
495
496 File : ObjectList {};
497
498 %%
499
500 int yyerror(const char *ErrorMsg) {
501   err() << "Error parsing: " << ErrorMsg << "\n";
502   abort();
503 }