In the variable statement changed the name "curstate" to "cs" (the default
[external/ragel.git] / ragel / parsedata.h
1 /*
2  *  Copyright 2001-2006 Adrian Thurston <thurston@cs.queensu.ca>
3  */
4
5 /*  This file is part of Ragel.
6  *
7  *  Ragel is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  * 
12  *  Ragel is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  * 
17  *  You should have received a copy of the GNU General Public License
18  *  along with Ragel; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
20  */
21
22 #ifndef _PARSEDATA_H
23 #define _PARSEDATA_H
24
25 #include <iostream>
26 #include <limits.h>
27 #include "avlmap.h"
28 #include "bstmap.h"
29 #include "vector.h"
30 #include "dlist.h"
31 #include "fsmgraph.h"
32 #include "compare.h"
33 #include "vector.h"
34 #include "common.h"
35 #include "parsetree.h"
36
37 /* Forwards. */
38 using std::ostream;
39
40 struct VarDef;
41 struct Join;
42 struct Expression;
43 struct Term;
44 struct FactorWithAug;
45 struct FactorWithLabel;
46 struct FactorWithRep;
47 struct FactorWithNeg;
48 struct Factor;
49 struct Literal;
50 struct Range;
51 struct RegExpr;
52 struct ReItem;
53 struct ReOrBlock;
54 struct ReOrItem;
55 struct LongestMatch;
56 typedef DList<LongestMatch> LmList;
57
58
59 /* Graph dictionary. */
60 struct GraphDictEl 
61 :
62         public AvlTreeEl<GraphDictEl>,
63         public DListEl<GraphDictEl>
64 {
65         GraphDictEl( char *k ) 
66                 : key(k), value(0), isInstance(false) { }
67         GraphDictEl( char *k, VarDef *value ) 
68                 : key(k), value(value), isInstance(false) { }
69
70         const char *getKey() { return key; }
71
72         char *key;
73         VarDef *value;
74         bool isInstance;
75
76         /* Location info of graph definition. Points to variable name of assignment. */
77         InputLoc loc;
78 };
79
80 typedef AvlTree<GraphDictEl, char*, CmpStr> GraphDict;
81 typedef DList<GraphDictEl> GraphList;
82
83 /* Priority name dictionary. */
84 typedef AvlMapEl<char*, int> PriorDictEl;
85 typedef AvlMap<char*, int, CmpStr> PriorDict;
86
87 /* Local error name dictionary. */
88 typedef AvlMapEl<char*, int> LocalErrDictEl;
89 typedef AvlMap<char*, int, CmpStr> LocalErrDict;
90
91 /* Tree of instantiated names. */
92 typedef BstMapEl<char*, NameInst*> NameMapEl;
93 typedef BstMap<char*, NameInst*, CmpStr> NameMap;
94 typedef Vector<NameInst*> NameVect;
95 typedef BstSet<NameInst*> NameSet;
96
97 /* Node in the tree of instantiated names. */
98 struct NameInst
99 {
100         NameInst( const InputLoc &loc, NameInst *parent, char *name, int id, bool isLabel ) : 
101                 loc(loc), parent(parent), name(name), id(id), isLabel(isLabel),
102                 isLongestMatch(false), numRefs(0), numUses(0), start(0), final(0) {}
103
104         InputLoc loc;
105
106         /* Keep parent pointers in the name tree to retrieve 
107          * fully qulified names. */
108         NameInst *parent;
109
110         char *name;
111         int id;
112         bool isLabel;
113         bool isLongestMatch;
114
115         int numRefs;
116         int numUses;
117
118         /* Names underneath us, excludes anonymous names. */
119         NameMap children;
120
121         /* All names underneath us in order of appearance. */
122         NameVect childVect;
123
124         /* Join scopes need an implicit "final" target. */
125         NameInst *start, *final;
126
127         /* During a fsm generation walk, lists the names that are referenced by
128          * epsilon operations in the current scope. After the link is made by the
129          * epsilon reference and the join operation is complete, the label can
130          * have its refcount decremented. Once there are no more references the
131          * entry point can be removed from the fsm returned. */
132         NameVect referencedNames;
133
134         /* Pointers for the name search queue. */
135         NameInst *prev, *next;
136
137         /* Check if this name inst or any name inst below is referenced. */
138         bool anyRefsRec();
139 };
140
141 typedef DList<NameInst> NameInstList;
142
143 /* Stack frame used in walking the name tree. */
144 struct NameFrame 
145 {
146         NameInst *prevNameInst;
147         int prevNameChild;
148         NameInst *prevLocalScope;
149 };
150
151 /* Class to collect information about the machine during the 
152  * parse of input. */
153 struct ParseData
154 {
155         /* Create a new parse data object. This is done at the beginning of every
156          * fsm specification. */
157         ParseData( char *fileName, char *sectionName, const InputLoc &sectionLoc );
158         ~ParseData();
159
160         /*
161          * Setting up the graph dict.
162          */
163
164         /* Initialize a graph dict with the basic fsms. */
165         void initGraphDict();
166         void createBuiltin( char *name, BuiltinMachine builtin );
167
168         /* Make a name id in the current name instantiation scope if it is not
169          * already there. */
170         NameInst *addNameInst( const InputLoc &loc, char *data, bool isLabel );
171         void makeRootNames();
172         void makeNameTree( GraphDictEl *gdNode );
173         void makeExportsNameTree();
174         void fillNameIndex( NameInst *from );
175         void printNameTree();
176
177         /* Increments the usage count on entry names. Names that are no longer
178          * needed will have their entry points unset. */
179         void unsetObsoleteEntries( FsmAp *graph );
180
181         /* Resove name references in action code and epsilon transitions. */
182         NameSet resolvePart( NameInst *refFrom, char *data, bool recLabelsOnly );
183         void resolveFrom( NameSet &result, NameInst *refFrom, 
184                         const NameRef &nameRef, int namePos );
185         NameInst *resolveStateRef( const NameRef &nameRef, InputLoc &loc, Action *action );
186         void resolveNameRefs( InlineList *inlineList, Action *action );
187         void resolveActionNameRefs();
188
189         /* Set the alphabet type. If type types are not valid returns false. */
190         bool setAlphType( char *s1, char *s2 );
191         bool setAlphType( char *s1 );
192
193         /* Override one of the variables ragel uses. */
194         bool setVariable( char *var, InlineList *inlineList );
195
196         /* Unique actions. */
197         void removeDups( ActionTable &actionTable );
198         void removeActionDups( FsmAp *graph );
199
200         /* Dumping the name instantiation tree. */
201         void printNameInst( NameInst *nameInst, int level );
202
203         /* Make the graph from a graph dict node. Does minimization. */
204         FsmAp *makeInstance( GraphDictEl *gdNode );
205         FsmAp *makeSpecific( GraphDictEl *gdNode );
206         FsmAp *makeAll();
207
208         /* Checking the contents of actions. */
209         void checkAction( Action *action );
210         void checkInlineList( Action *act, InlineList *inlineList );
211
212         void analyzeAction( Action *action, InlineList *inlineList );
213         void analyzeGraph( FsmAp *graph );
214         void makeExports();
215
216         void prepareMachineGen( GraphDictEl *graphDictEl );
217         void generateXML( ostream &out );
218         FsmAp *sectionGraph;
219         bool generatingSectionSubset;
220
221         void initKeyOps();
222
223         /*
224          * Data collected during the parse.
225          */
226
227         /* Dictionary of graphs. Both instances and non-instances go here. */
228         GraphDict graphDict;
229
230         /* The list of instances. */
231         GraphList instanceList;
232
233         /* Dictionary of actions. Lets actions be defined and then referenced. */
234         ActionDict actionDict;
235
236         /* Dictionary of named priorities. */
237         PriorDict priorDict;
238
239         /* Dictionary of named local errors. */
240         LocalErrDict localErrDict;
241
242         /* List of actions. Will be pasted into a switch statement. */
243         ActionList actionList;
244
245         /* The id of the next priority name and label. */
246         int nextPriorKey, nextLocalErrKey, nextNameId, nextCondId;
247         
248         /* The default priority number key for a machine. This is active during
249          * the parse of the rhs of a machine assignment. */
250         int curDefPriorKey;
251
252         int curDefLocalErrKey;
253
254         /* Alphabet type. */
255         HostType *userAlphType;
256         bool alphTypeSet;
257
258         /* Element type and get key expression. */
259         InlineList *getKeyExpr;
260         InlineList *accessExpr;
261
262         /* Overriding variables. */
263         InlineList *pExpr;
264         InlineList *peExpr;
265         InlineList *csExpr;
266         InlineList *topExpr;
267         InlineList *stackExpr;
268         InlineList *actExpr;
269         InlineList *tokstartExpr;
270         InlineList *tokendExpr;
271
272         /* The alphabet range. */
273         char *lowerNum, *upperNum;
274         Key lowKey, highKey;
275         InputLoc rangeLowLoc, rangeHighLoc;
276
277         /* The name of the file the fsm is from, and the spec name. */
278         char *fileName;
279         char *sectionName;
280         InputLoc sectionLoc;
281
282         /* Number of errors encountered parsing the fsm spec. */
283         int errorCount;
284
285         /* Counting the action and priority ordering. */
286         int curActionOrd;
287         int curPriorOrd;
288
289         /* Root of the name tree. One root is for the instantiated machines. The
290          * other root is for exported definitions. */
291         NameInst *rootName;
292         NameInst *exportsRootName;
293         
294         /* Name tree walking. */
295         NameInst *curNameInst;
296         int curNameChild;
297
298         /* The place where resolved epsilon transitions go. These cannot go into
299          * the parse tree because a single epsilon op can resolve more than once
300          * to different nameInsts if the machine it's in is used more than once. */
301         NameVect epsilonResolvedLinks;
302         int nextEpsilonResolvedLink;
303
304         /* Root of the name tree used for doing local name searches. */
305         NameInst *localNameScope;
306
307         void setLmInRetLoc( InlineList *inlineList );
308         void initLongestMatchData();
309         void setLongestMatchData( FsmAp *graph );
310         void initNameWalk();
311         void initExportsNameWalk();
312         NameInst *nextNameScope() { return curNameInst->childVect[curNameChild]; }
313         NameFrame enterNameScope( bool isLocal, int numScopes );
314         void popNameScope( const NameFrame &frame );
315         void resetNameScope( const NameFrame &frame );
316
317         /* Make name ids to name inst pointers. */
318         NameInst **nameIndex;
319
320         /* Counter for assigning ids to longest match items. */
321         int nextLongestMatchId;
322         bool lmRequiresErrorState;
323
324         /* List of all longest match parse tree items. */
325         LmList lmList;
326
327         Action *newAction( char *name, InlineList *inlineList );
328
329         Action *initTokStart;
330         int initTokStartOrd;
331
332         Action *setTokStart;
333         int setTokStartOrd;
334
335         Action *initActId;
336         int initActIdOrd;
337
338         Action *setTokEnd;
339         int setTokEndOrd;
340
341         void beginProcessing()
342         {
343                 ::condData = &thisCondData;
344                 ::keyOps = &thisKeyOps;
345         }
346
347         CondData thisCondData;
348         KeyOps thisKeyOps;
349
350         ExportList exportList;
351 };
352
353 void afterOpMinimize( FsmAp *fsm, bool lastInSeq = true );
354 Key makeFsmKeyHex( char *str, const InputLoc &loc, ParseData *pd );
355 Key makeFsmKeyDec( char *str, const InputLoc &loc, ParseData *pd );
356 Key makeFsmKeyNum( char *str, const InputLoc &loc, ParseData *pd );
357 Key makeFsmKeyChar( char c, ParseData *pd );
358 void makeFsmKeyArray( Key *result, char *data, int len, ParseData *pd );
359 void makeFsmUniqueKeyArray( KeySet &result, char *data, int len, 
360                 bool caseInsensitive, ParseData *pd );
361 FsmAp *makeBuiltin( BuiltinMachine builtin, ParseData *pd );
362 FsmAp *dotFsm( ParseData *pd );
363 FsmAp *dotStarFsm( ParseData *pd );
364
365 void errorStateLabels( const NameSet &locations );
366
367 /* Data used by the parser specific to the current file. Supports the include
368  * system, since a new parser is executed for each included file. */
369 struct InputData
370 {
371         InputData( char *fileName, char *includeSpec, char *includeTo ) :
372                 pd(0), sectionName(0), defaultParseData(0), 
373                 first_line(1), first_column(1), 
374                 last_line(1), last_column(0), 
375                 fileName(fileName), includeSpec(includeSpec), 
376                 includeTo(includeTo), active(true)
377                 {}
378
379         /* For collecting a name references. */
380         NameRef nameRef;
381         NameRefList nameRefList;
382
383         /* The parse data. For each fsm spec, the parser collects things that it parses
384          * in data structures in here. */
385         ParseData *pd;
386
387         char *sectionName;
388         ParseData *defaultParseData;
389
390         int first_line;
391         int first_column;
392         int last_line;
393         int last_column;
394
395         char *fileName;
396
397         /* If this is an included file, this contains the specification to search
398          * for. IncludeTo will contain the spec name that does the includng. */
399         char *includeSpec;
400         char *includeTo;
401
402         bool active;
403         InputLoc sectionLoc;
404 };
405
406 struct Parser;
407
408 typedef AvlMap<char*, Parser *, CmpStr> ParserDict;
409 typedef AvlMapEl<char*, Parser *> ParserDictEl;
410
411 extern ParserDict parserDict;
412
413
414 #endif /* _PARSEDATA_H */