Implemented an export feature, for exporting single-character machine
[external/ragel.git] / ragel / parsetree.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 _PARSETREE_H
23 #define _PARSETREE_H
24
25 #include "ragel.h"
26 #include "avlmap.h"
27 #include "bstmap.h"
28 #include "vector.h"
29 #include "dlist.h"
30
31 struct NameInst;
32
33 /* Types of builtin machines. */
34 enum BuiltinMachine
35 {
36         BT_Any,
37         BT_Ascii,
38         BT_Extend,
39         BT_Alpha,
40         BT_Digit,
41         BT_Alnum,
42         BT_Lower,
43         BT_Upper,
44         BT_Cntrl,
45         BT_Graph,
46         BT_Print,
47         BT_Punct,
48         BT_Space,
49         BT_Xdigit,
50         BT_Lambda,
51         BT_Empty
52 };
53
54
55 struct ParseData;
56
57 /* Leaf type. */
58 struct Literal;
59
60 /* Tree nodes. */
61
62 struct Term;
63 struct FactorWithAug;
64 struct FactorWithRep;
65 struct FactorWithNeg;
66 struct Factor;
67 struct Expression;
68 struct Join;
69 struct JoinOrLm;
70 struct LongestMatch;
71 struct LongestMatchPart;
72 struct LmPartList;
73 struct Range;
74
75 /* Type of augmentation. Describes locations in the machine. */
76 enum AugType
77 {
78         /* Transition actions/priorities. */
79         at_start,
80         at_all,
81         at_finish,
82         at_leave,
83
84         /* Global error actions. */
85         at_start_gbl_error,
86         at_all_gbl_error,
87         at_final_gbl_error,
88         at_not_start_gbl_error,
89         at_not_final_gbl_error,
90         at_middle_gbl_error,
91
92         /* Local error actions. */
93         at_start_local_error,
94         at_all_local_error,
95         at_final_local_error,
96         at_not_start_local_error,
97         at_not_final_local_error,
98         at_middle_local_error,
99         
100         /* To State Action embedding. */
101         at_start_to_state,
102         at_all_to_state,
103         at_final_to_state,
104         at_not_start_to_state,
105         at_not_final_to_state,
106         at_middle_to_state,
107
108         /* From State Action embedding. */
109         at_start_from_state,
110         at_all_from_state,
111         at_final_from_state,
112         at_not_start_from_state,
113         at_not_final_from_state,
114         at_middle_from_state,
115
116         /* EOF Action embedding. */
117         at_start_eof,
118         at_all_eof,
119         at_final_eof,
120         at_not_start_eof,
121         at_not_final_eof,
122         at_middle_eof
123 };
124
125 /* IMPORTANT: These must follow the same order as the state augs in AugType
126  * since we will be using this to compose AugType. */
127 enum StateAugType
128 {
129         sat_start = 0,
130         sat_all,
131         sat_final,
132         sat_not_start,
133         sat_not_final,
134         sat_middle
135 };
136
137 struct Action;
138 struct PriorDesc;
139 struct RegExpr;
140 struct ReItem;
141 struct ReOrBlock;
142 struct ReOrItem;
143 struct ExplicitMachine;
144 struct InlineItem;
145 struct InlineList;
146
147 /* Reference to a named state. */
148 typedef Vector<char*> NameRef;
149 typedef Vector<NameRef*> NameRefList;
150 typedef Vector<NameInst*> NameTargList;
151
152 /* Structure for storing location of epsilon transitons. */
153 struct EpsilonLink
154 {
155         EpsilonLink( const InputLoc &loc, NameRef &target )
156                 : loc(loc), target(target) { }
157
158         InputLoc loc;
159         NameRef target;
160 };
161
162 struct Label
163 {
164         Label( const InputLoc &loc, char *data )
165                 : loc(loc), data(data) { }
166
167         InputLoc loc;
168         char *data;
169 };
170
171 /* Structrue represents an action assigned to some FactorWithAug node. The
172  * factor with aug will keep an array of these. */
173 struct ParserAction
174 {
175         ParserAction( const InputLoc &loc, AugType type, int localErrKey, Action *action )
176                 : loc(loc), type(type), localErrKey(localErrKey), action(action) { }
177
178         InputLoc loc;
179         AugType type;
180         int localErrKey;
181         Action *action;
182 };
183
184 struct Token
185 {
186         char *data;
187         int length;
188         InputLoc loc;
189
190         void prepareLitString( Token &result, bool &caseInsensitive );
191         void append( const Token &other );
192         void set( char *str, int len );
193 };
194
195 /* Store the value and type of a priority augmentation. */
196 struct PriorityAug
197 {
198         PriorityAug( AugType type, int priorKey, int priorValue ) :
199                 type(type), priorKey(priorKey), priorValue(priorValue) { }
200
201         AugType type;
202         int priorKey;
203         int priorValue;
204 };
205
206 /*
207  * A Variable Definition
208  */
209 struct VarDef
210 {
211         VarDef( char *name, JoinOrLm *joinOrLm )
212                 : name(name), joinOrLm(joinOrLm) { }
213         
214         /* Parse tree traversal. */
215         FsmAp *walk( ParseData *pd );
216         void makeNameTree( const InputLoc &loc, ParseData *pd );
217         void resolveNameRefs( ParseData *pd );
218
219         char *name;
220         JoinOrLm *joinOrLm;
221
222         bool isExport;
223         bool isEntry;
224 };
225
226
227 /*
228  * LongestMatch
229  *
230  * Wherever possible the item match will execute on the character. If not
231  * possible the item match will execute on a lookahead character and either
232  * hold the current char (if one away) or backup.
233  *
234  * How to handle the problem of backing up over a buffer break?
235  * 
236  * Don't want to use pending out transitions for embedding item match because
237  * the role of item match action is different: it may sometimes match on the
238  * final transition, or may match on a lookahead character.
239  *
240  * Don't want to invent a new operator just for this. So just trail action
241  * after machine, this means we can only use literal actions.
242  *
243  * The item action may 
244  *
245  * What states of the machine will be final. The item actions that wrap around
246  * on the last character will go straight to the start state.
247  *
248  * Some transitions will be lookahead transitions, they will hold the current
249  * character. Crossing them with regular transitions must be restricted
250  * because it does not make sense. The transition cannot simultaneously hold
251  * and consume the current character.
252  */
253 struct LongestMatchPart
254 {
255         LongestMatchPart( Join *join, Action *action, 
256                         InputLoc &semiLoc, int longestMatchId )
257         : 
258                 join(join), action(action), semiLoc(semiLoc), 
259                 longestMatchId(longestMatchId), inLmSelect(false) { }
260
261         InputLoc getLoc();
262         
263         Join *join;
264         Action *action;
265         InputLoc semiLoc;
266
267         Action *setActId;
268         Action *actOnLast;
269         Action *actOnNext;
270         Action *actLagBehind;
271         int longestMatchId;
272         bool inLmSelect;
273         LongestMatch *longestMatch;
274
275         LongestMatchPart *prev, *next;
276 };
277
278 /* Declare a new type so that ptreetypes.h need not include dlist.h. */
279 struct LmPartList : DList<LongestMatchPart> {};
280
281 struct LongestMatch
282 {
283         /* Construct with a list of joins */
284         LongestMatch( const InputLoc &loc, LmPartList *longestMatchList ) : 
285                 loc(loc), longestMatchList(longestMatchList), name(0), 
286                 lmSwitchHandlesError(false) { }
287
288         /* Tree traversal. */
289         FsmAp *walk( ParseData *pd );
290         void makeNameTree( ParseData *pd );
291         void resolveNameRefs( ParseData *pd );
292         void runLonestMatch( ParseData *pd, FsmAp *graph );
293         Action *newAction( ParseData *pd, const InputLoc &loc, char *name, 
294                         InlineList *inlineList );
295         void makeActions( ParseData *pd );
296         void findName( ParseData *pd );
297         void restart( FsmAp *graph, TransAp *trans );
298
299         InputLoc loc;
300         LmPartList *longestMatchList;
301         char *name;
302
303         Action *lmActSelect;
304         bool lmSwitchHandlesError;
305
306         LongestMatch *next, *prev;
307 };
308
309
310 /* List of Expressions. */
311 typedef DList<Expression> ExprList;
312
313 struct JoinOrLm
314 {
315         enum Type {
316                 JoinType,
317                 LongestMatchType
318         };
319
320         JoinOrLm( Join *join ) : 
321                 join(join), type(JoinType) {}
322         JoinOrLm( LongestMatch *longestMatch ) :
323                 longestMatch(longestMatch), type(LongestMatchType) {}
324
325         FsmAp *walk( ParseData *pd );
326         void makeNameTree( ParseData *pd );
327         void resolveNameRefs( ParseData *pd );
328         
329         Join *join;
330         LongestMatch *longestMatch;
331         Type type;
332 };
333
334 /*
335  * Join
336  */
337 struct Join
338 {
339         /* Construct with the first expression. */
340         Join( Expression *expr );
341         Join( const InputLoc &loc, Expression *expr );
342
343         /* Tree traversal. */
344         FsmAp *walk( ParseData *pd );
345         FsmAp *walkJoin( ParseData *pd );
346         void makeNameTree( ParseData *pd );
347         void resolveNameRefs( ParseData *pd );
348
349         /* Data. */
350         InputLoc loc;
351         ExprList exprList;
352 };
353
354 /*
355  * Expression
356  */
357 struct Expression
358 {
359         enum Type { 
360                 OrType,
361                 IntersectType, 
362                 SubtractType, 
363                 StrongSubtractType,
364                 TermType, 
365                 BuiltinType
366         };
367
368         /* Construct with an expression on the left and a term on the right. */
369         Expression( Expression *expression, Term *term, Type type ) : 
370                 expression(expression), term(term), 
371                 builtin(builtin), type(type), prev(this), next(this) { }
372
373         /* Construct with only a term. */
374         Expression( Term *term ) : 
375                 expression(0), term(term), builtin(builtin), 
376                 type(TermType) , prev(this), next(this) { }
377         
378         /* Construct with a builtin type. */
379         Expression( BuiltinMachine builtin ) : 
380                 expression(0), term(0), builtin(builtin), 
381                 type(BuiltinType), prev(this), next(this) { }
382
383         ~Expression();
384
385         /* Tree traversal. */
386         FsmAp *walk( ParseData *pd, bool lastInSeq = true );
387         void makeNameTree( ParseData *pd );
388         void resolveNameRefs( ParseData *pd );
389
390         /* Node data. */
391         Expression *expression;
392         Term *term;
393         BuiltinMachine builtin;
394         Type type;
395
396         Expression *prev, *next;
397 };
398
399 /*
400  * Term
401  */
402 struct Term 
403 {
404         enum Type { 
405                 ConcatType, 
406                 RightStartType,
407                 RightFinishType,
408                 LeftType,
409                 FactorWithAugType
410         };
411
412         Term( Term *term, FactorWithAug *factorWithAug ) :
413                 term(term), factorWithAug(factorWithAug), type(ConcatType) { }
414
415         Term( Term *term, FactorWithAug *factorWithAug, Type type ) :
416                 term(term), factorWithAug(factorWithAug), type(type) { }
417
418         Term( FactorWithAug *factorWithAug ) :
419                 term(0), factorWithAug(factorWithAug), type(FactorWithAugType) { }
420         
421         ~Term();
422
423         FsmAp *walk( ParseData *pd, bool lastInSeq = true );
424         void makeNameTree( ParseData *pd );
425         void resolveNameRefs( ParseData *pd );
426
427         Term *term;
428         FactorWithAug *factorWithAug;
429         Type type;
430
431         /* Priority descriptor for RightFinish type. */
432         PriorDesc priorDescs[2];
433 };
434
435
436 /* Third level of precedence. Augmenting nodes with actions and priorities. */
437 struct FactorWithAug
438 {
439         FactorWithAug( FactorWithRep *factorWithRep ) :
440                 priorDescs(0), factorWithRep(factorWithRep) { }
441         ~FactorWithAug();
442
443         /* Tree traversal. */
444         FsmAp *walk( ParseData *pd );
445         void makeNameTree( ParseData *pd );
446         void resolveNameRefs( ParseData *pd );
447
448         void assignActions( ParseData *pd, FsmAp *graph, int *actionOrd );
449         void assignPriorities( FsmAp *graph, int *priorOrd );
450
451         void assignConditions( FsmAp *graph );
452
453         /* Actions and priorities assigned to the factor node. */
454         Vector<ParserAction> actions;
455         Vector<PriorityAug> priorityAugs;
456         PriorDesc *priorDescs;
457         Vector<Label> labels;
458         Vector<EpsilonLink> epsilonLinks;
459         Vector<ParserAction> conditions;
460
461         FactorWithRep *factorWithRep;
462 };
463
464 /* Fourth level of precedence. Trailing unary operators. Provide kleen star,
465  * optional and plus. */
466 struct FactorWithRep
467 {
468         enum Type { 
469                 StarType,
470                 StarStarType,
471                 OptionalType,
472                 PlusType, 
473                 ExactType,
474                 MaxType,
475                 MinType,
476                 RangeType,
477                 FactorWithNegType
478         };
479
480          FactorWithRep( const InputLoc &loc, FactorWithRep *factorWithRep, 
481                         int lowerRep, int upperRep, Type type ) :
482                 loc(loc), factorWithRep(factorWithRep), 
483                 factorWithNeg(0), lowerRep(lowerRep), 
484                 upperRep(upperRep), type(type) { }
485         
486         FactorWithRep( FactorWithNeg *factorWithNeg )
487                 : factorWithNeg(factorWithNeg), type(FactorWithNegType) { }
488
489         ~FactorWithRep();
490
491         /* Tree traversal. */
492         FsmAp *walk( ParseData *pd );
493         void makeNameTree( ParseData *pd );
494         void resolveNameRefs( ParseData *pd );
495
496         InputLoc loc;
497         FactorWithRep *factorWithRep;
498         FactorWithNeg *factorWithNeg;
499         int lowerRep, upperRep;
500         Type type;
501
502         /* Priority descriptor for StarStar type. */
503         PriorDesc priorDescs[2];
504 };
505
506 /* Fifth level of precedence. Provides Negation. */
507 struct FactorWithNeg
508 {
509         enum Type { 
510                 NegateType, 
511                 CharNegateType,
512                 FactorType
513         };
514
515         FactorWithNeg( const InputLoc &loc, FactorWithNeg *factorWithNeg, Type type) :
516                 loc(loc), factorWithNeg(factorWithNeg), factor(0), type(type) { }
517
518         FactorWithNeg( Factor *factor ) :
519                 factorWithNeg(0), factor(factor), type(FactorType) { }
520
521         ~FactorWithNeg();
522
523         /* Tree traversal. */
524         FsmAp *walk( ParseData *pd );
525         void makeNameTree( ParseData *pd );
526         void resolveNameRefs( ParseData *pd );
527
528         InputLoc loc;
529         FactorWithNeg *factorWithNeg;
530         Factor *factor;
531         Type type;
532 };
533
534 /*
535  * Factor
536  */
537 struct Factor
538 {
539         /* Language elements a factor node can be. */
540         enum Type {
541                 LiteralType, 
542                 RangeType, 
543                 OrExprType,
544                 RegExprType, 
545                 ReferenceType,
546                 ParenType,
547                 LongestMatchType,
548         }; 
549
550         /* Construct with a literal fsm. */
551         Factor( Literal *literal ) :
552                 literal(literal), type(LiteralType) { }
553
554         /* Construct with a range. */
555         Factor( Range *range ) : 
556                 range(range), type(RangeType) { }
557         
558         /* Construct with the or part of a regular expression. */
559         Factor( ReItem *reItem ) :
560                 reItem(reItem), type(OrExprType) { }
561
562         /* Construct with a regular expression. */
563         Factor( RegExpr *regExpr ) :
564                 regExpr(regExpr), type(RegExprType) { }
565
566         /* Construct with a reference to a var def. */
567         Factor( const InputLoc &loc, VarDef *varDef ) :
568                 loc(loc), varDef(varDef), type(ReferenceType) {}
569
570         /* Construct with a parenthesized join. */
571         Factor( Join *join ) :
572                 join(join), type(ParenType) {}
573         
574         /* Construct with a longest match operator. */
575         Factor( LongestMatch *longestMatch ) :
576                 longestMatch(longestMatch), type(LongestMatchType) {}
577
578         /* Cleanup. */
579         ~Factor();
580
581         /* Tree traversal. */
582         FsmAp *walk( ParseData *pd );
583         void makeNameTree( ParseData *pd );
584         void resolveNameRefs( ParseData *pd );
585
586         InputLoc loc;
587         Literal *literal;
588         Range *range;
589         ReItem *reItem;
590         RegExpr *regExpr;
591         VarDef *varDef;
592         Join *join;
593         LongestMatch *longestMatch;
594         int lower, upper;
595         Type type;
596 };
597
598 /* A range machine. Only ever composed of two literals. */
599 struct Range
600 {
601         Range( Literal *lowerLit, Literal *upperLit ) 
602                 : lowerLit(lowerLit), upperLit(upperLit) { }
603
604         ~Range();
605         FsmAp *walk( ParseData *pd );
606
607         Literal *lowerLit;
608         Literal *upperLit;
609 };
610
611 /* Some literal machine. Can be a number or literal string. */
612 struct Literal
613 {
614         enum LiteralType { Number, LitString };
615
616         Literal( const Token &token, LiteralType type )
617                 : token(token), type(type) { }
618
619         FsmAp *walk( ParseData *pd );
620         
621         Token token;
622         LiteralType type;
623 };
624
625 /* Regular expression. */
626 struct RegExpr
627 {
628         enum RegExpType { RecurseItem, Empty };
629
630         /* Constructors. */
631         RegExpr() : 
632                 type(Empty), caseInsensitive(false) { }
633         RegExpr(RegExpr *regExpr, ReItem *item) : 
634                 regExpr(regExpr), item(item), 
635                 type(RecurseItem), caseInsensitive(false) { }
636
637         ~RegExpr();
638         FsmAp *walk( ParseData *pd, RegExpr *rootRegex );
639
640         RegExpr *regExpr;
641         ReItem *item;
642         RegExpType type;
643         bool caseInsensitive;
644 };
645
646 /* An item in a regular expression. */
647 struct ReItem
648 {
649         enum ReItemType { Data, Dot, OrBlock, NegOrBlock };
650         
651         ReItem( const InputLoc &loc, const Token &token ) 
652                 : loc(loc), token(token), star(false), type(Data) { }
653         ReItem( const InputLoc &loc, ReItemType type )
654                 : loc(loc), star(false), type(type) { }
655         ReItem( const InputLoc &loc, ReOrBlock *orBlock, ReItemType type )
656                 : loc(loc), orBlock(orBlock), star(false), type(type) { }
657
658         ~ReItem();
659         FsmAp *walk( ParseData *pd, RegExpr *rootRegex );
660
661         InputLoc loc;
662         Token token;
663         ReOrBlock *orBlock;
664         bool star;
665         ReItemType type;
666 };
667
668 /* An or block item. */
669 struct ReOrBlock
670 {
671         enum ReOrBlockType { RecurseItem, Empty };
672
673         /* Constructors. */
674         ReOrBlock()
675                 : type(Empty) { }
676         ReOrBlock(ReOrBlock *orBlock, ReOrItem *item)
677                 : orBlock(orBlock), item(item), type(RecurseItem) { }
678
679         ~ReOrBlock();
680         FsmAp *walk( ParseData *pd, RegExpr *rootRegex );
681         
682         ReOrBlock *orBlock;
683         ReOrItem *item;
684         ReOrBlockType type;
685 };
686
687 /* An item in an or block. */
688 struct ReOrItem
689 {
690         enum ReOrItemType { Data, Range };
691
692         ReOrItem( const InputLoc &loc, const Token &token ) 
693                 : loc(loc), token(token), type(Data) {}
694         ReOrItem( const InputLoc &loc, char lower, char upper )
695                 : loc(loc), lower(lower), upper(upper), type(Range) { }
696
697         FsmAp *walk( ParseData *pd, RegExpr *rootRegex );
698
699         InputLoc loc;
700         Token token;
701         char lower;
702         char upper;
703         ReOrItemType type;
704 };
705
706
707 /*
708  * Inline code tree
709  */
710 struct InlineList;
711 struct InlineItem
712 {
713         enum Type 
714         {
715                 Text, Goto, Call, Next, GotoExpr, CallExpr, NextExpr, Ret, PChar,
716                 Char, Hold, Curs, Targs, Entry, Exec, LmSwitch, LmSetActId,
717                 LmSetTokEnd, LmOnLast, LmOnNext, LmOnLagBehind, LmInitAct,
718                 LmInitTokStart, LmSetTokStart, Break
719         };
720
721         InlineItem( const InputLoc &loc, char *data, Type type ) : 
722                 loc(loc), data(data), nameRef(0), children(0), type(type) { }
723
724         InlineItem( const InputLoc &loc, NameRef *nameRef, Type type ) : 
725                 loc(loc), data(0), nameRef(nameRef), children(0), type(type) { }
726
727         InlineItem( const InputLoc &loc, LongestMatch *longestMatch, 
728                 LongestMatchPart *longestMatchPart, Type type ) : loc(loc), data(0),
729                 nameRef(0), children(0), longestMatch(longestMatch),
730                 longestMatchPart(longestMatchPart), type(type) { } 
731
732         InlineItem( const InputLoc &loc, NameInst *nameTarg, Type type ) : 
733                 loc(loc), data(0), nameRef(0), nameTarg(nameTarg), children(0),
734                 type(type) { }
735
736         InlineItem( const InputLoc &loc, Type type ) : 
737                 loc(loc), data(0), nameRef(0), children(0), type(type) { }
738         
739         InputLoc loc;
740         char *data;
741         NameRef *nameRef;
742         NameInst *nameTarg;
743         InlineList *children;
744         LongestMatch *longestMatch;
745         LongestMatchPart *longestMatchPart;
746         Type type;
747
748         InlineItem *prev, *next;
749 };
750
751 /* Normally this would be atypedef, but that would entail including DList from
752  * ptreetypes, which should be just typedef forwards. */
753 struct InlineList : public DList<InlineItem> { };
754
755
756
757 #endif /* _PARSETREE_H */