All machine instantiations are now implicitly referenced and always generated,
[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), isExport(false) { }
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         bool isExport;
222 };
223
224
225 /*
226  * LongestMatch
227  *
228  * Wherever possible the item match will execute on the character. If not
229  * possible the item match will execute on a lookahead character and either
230  * hold the current char (if one away) or backup.
231  *
232  * How to handle the problem of backing up over a buffer break?
233  * 
234  * Don't want to use pending out transitions for embedding item match because
235  * the role of item match action is different: it may sometimes match on the
236  * final transition, or may match on a lookahead character.
237  *
238  * Don't want to invent a new operator just for this. So just trail action
239  * after machine, this means we can only use literal actions.
240  *
241  * The item action may 
242  *
243  * What states of the machine will be final. The item actions that wrap around
244  * on the last character will go straight to the start state.
245  *
246  * Some transitions will be lookahead transitions, they will hold the current
247  * character. Crossing them with regular transitions must be restricted
248  * because it does not make sense. The transition cannot simultaneously hold
249  * and consume the current character.
250  */
251 struct LongestMatchPart
252 {
253         LongestMatchPart( Join *join, Action *action, 
254                         InputLoc &semiLoc, int longestMatchId )
255         : 
256                 join(join), action(action), semiLoc(semiLoc), 
257                 longestMatchId(longestMatchId), inLmSelect(false) { }
258
259         InputLoc getLoc();
260         
261         Join *join;
262         Action *action;
263         InputLoc semiLoc;
264
265         Action *setActId;
266         Action *actOnLast;
267         Action *actOnNext;
268         Action *actLagBehind;
269         int longestMatchId;
270         bool inLmSelect;
271         LongestMatch *longestMatch;
272
273         LongestMatchPart *prev, *next;
274 };
275
276 /* Declare a new type so that ptreetypes.h need not include dlist.h. */
277 struct LmPartList : DList<LongestMatchPart> {};
278
279 struct LongestMatch
280 {
281         /* Construct with a list of joins */
282         LongestMatch( const InputLoc &loc, LmPartList *longestMatchList ) : 
283                 loc(loc), longestMatchList(longestMatchList), name(0), 
284                 lmSwitchHandlesError(false) { }
285
286         /* Tree traversal. */
287         FsmAp *walk( ParseData *pd );
288         void makeNameTree( ParseData *pd );
289         void resolveNameRefs( ParseData *pd );
290         void runLonestMatch( ParseData *pd, FsmAp *graph );
291         Action *newAction( ParseData *pd, const InputLoc &loc, char *name, 
292                         InlineList *inlineList );
293         void makeActions( ParseData *pd );
294         void findName( ParseData *pd );
295         void restart( FsmAp *graph, TransAp *trans );
296
297         InputLoc loc;
298         LmPartList *longestMatchList;
299         char *name;
300
301         Action *lmActSelect;
302         bool lmSwitchHandlesError;
303
304         LongestMatch *next, *prev;
305 };
306
307
308 /* List of Expressions. */
309 typedef DList<Expression> ExprList;
310
311 struct JoinOrLm
312 {
313         enum Type {
314                 JoinType,
315                 LongestMatchType
316         };
317
318         JoinOrLm( Join *join ) : 
319                 join(join), type(JoinType) {}
320         JoinOrLm( LongestMatch *longestMatch ) :
321                 longestMatch(longestMatch), type(LongestMatchType) {}
322
323         FsmAp *walk( ParseData *pd );
324         void makeNameTree( ParseData *pd );
325         void resolveNameRefs( ParseData *pd );
326         
327         Join *join;
328         LongestMatch *longestMatch;
329         Type type;
330 };
331
332 /*
333  * Join
334  */
335 struct Join
336 {
337         /* Construct with the first expression. */
338         Join( Expression *expr );
339         Join( const InputLoc &loc, Expression *expr );
340
341         /* Tree traversal. */
342         FsmAp *walk( ParseData *pd );
343         FsmAp *walkJoin( ParseData *pd );
344         void makeNameTree( ParseData *pd );
345         void resolveNameRefs( ParseData *pd );
346
347         /* Data. */
348         InputLoc loc;
349         ExprList exprList;
350 };
351
352 /*
353  * Expression
354  */
355 struct Expression
356 {
357         enum Type { 
358                 OrType,
359                 IntersectType, 
360                 SubtractType, 
361                 StrongSubtractType,
362                 TermType, 
363                 BuiltinType
364         };
365
366         /* Construct with an expression on the left and a term on the right. */
367         Expression( Expression *expression, Term *term, Type type ) : 
368                 expression(expression), term(term), 
369                 builtin(builtin), type(type), prev(this), next(this) { }
370
371         /* Construct with only a term. */
372         Expression( Term *term ) : 
373                 expression(0), term(term), builtin(builtin), 
374                 type(TermType) , prev(this), next(this) { }
375         
376         /* Construct with a builtin type. */
377         Expression( BuiltinMachine builtin ) : 
378                 expression(0), term(0), builtin(builtin), 
379                 type(BuiltinType), prev(this), next(this) { }
380
381         ~Expression();
382
383         /* Tree traversal. */
384         FsmAp *walk( ParseData *pd, bool lastInSeq = true );
385         void makeNameTree( ParseData *pd );
386         void resolveNameRefs( ParseData *pd );
387
388         /* Node data. */
389         Expression *expression;
390         Term *term;
391         BuiltinMachine builtin;
392         Type type;
393
394         Expression *prev, *next;
395 };
396
397 /*
398  * Term
399  */
400 struct Term 
401 {
402         enum Type { 
403                 ConcatType, 
404                 RightStartType,
405                 RightFinishType,
406                 LeftType,
407                 FactorWithAugType
408         };
409
410         Term( Term *term, FactorWithAug *factorWithAug ) :
411                 term(term), factorWithAug(factorWithAug), type(ConcatType) { }
412
413         Term( Term *term, FactorWithAug *factorWithAug, Type type ) :
414                 term(term), factorWithAug(factorWithAug), type(type) { }
415
416         Term( FactorWithAug *factorWithAug ) :
417                 term(0), factorWithAug(factorWithAug), type(FactorWithAugType) { }
418         
419         ~Term();
420
421         FsmAp *walk( ParseData *pd, bool lastInSeq = true );
422         void makeNameTree( ParseData *pd );
423         void resolveNameRefs( ParseData *pd );
424
425         Term *term;
426         FactorWithAug *factorWithAug;
427         Type type;
428
429         /* Priority descriptor for RightFinish type. */
430         PriorDesc priorDescs[2];
431 };
432
433
434 /* Third level of precedence. Augmenting nodes with actions and priorities. */
435 struct FactorWithAug
436 {
437         FactorWithAug( FactorWithRep *factorWithRep ) :
438                 priorDescs(0), factorWithRep(factorWithRep) { }
439         ~FactorWithAug();
440
441         /* Tree traversal. */
442         FsmAp *walk( ParseData *pd );
443         void makeNameTree( ParseData *pd );
444         void resolveNameRefs( ParseData *pd );
445
446         void assignActions( ParseData *pd, FsmAp *graph, int *actionOrd );
447         void assignPriorities( FsmAp *graph, int *priorOrd );
448
449         void assignConditions( FsmAp *graph );
450
451         /* Actions and priorities assigned to the factor node. */
452         Vector<ParserAction> actions;
453         Vector<PriorityAug> priorityAugs;
454         PriorDesc *priorDescs;
455         Vector<Label> labels;
456         Vector<EpsilonLink> epsilonLinks;
457         Vector<ParserAction> conditions;
458
459         FactorWithRep *factorWithRep;
460 };
461
462 /* Fourth level of precedence. Trailing unary operators. Provide kleen star,
463  * optional and plus. */
464 struct FactorWithRep
465 {
466         enum Type { 
467                 StarType,
468                 StarStarType,
469                 OptionalType,
470                 PlusType, 
471                 ExactType,
472                 MaxType,
473                 MinType,
474                 RangeType,
475                 FactorWithNegType
476         };
477
478          FactorWithRep( const InputLoc &loc, FactorWithRep *factorWithRep, 
479                         int lowerRep, int upperRep, Type type ) :
480                 loc(loc), factorWithRep(factorWithRep), 
481                 factorWithNeg(0), lowerRep(lowerRep), 
482                 upperRep(upperRep), type(type) { }
483         
484         FactorWithRep( FactorWithNeg *factorWithNeg )
485                 : factorWithNeg(factorWithNeg), type(FactorWithNegType) { }
486
487         ~FactorWithRep();
488
489         /* Tree traversal. */
490         FsmAp *walk( ParseData *pd );
491         void makeNameTree( ParseData *pd );
492         void resolveNameRefs( ParseData *pd );
493
494         InputLoc loc;
495         FactorWithRep *factorWithRep;
496         FactorWithNeg *factorWithNeg;
497         int lowerRep, upperRep;
498         Type type;
499
500         /* Priority descriptor for StarStar type. */
501         PriorDesc priorDescs[2];
502 };
503
504 /* Fifth level of precedence. Provides Negation. */
505 struct FactorWithNeg
506 {
507         enum Type { 
508                 NegateType, 
509                 CharNegateType,
510                 FactorType
511         };
512
513         FactorWithNeg( const InputLoc &loc, FactorWithNeg *factorWithNeg, Type type) :
514                 loc(loc), factorWithNeg(factorWithNeg), factor(0), type(type) { }
515
516         FactorWithNeg( Factor *factor ) :
517                 factorWithNeg(0), factor(factor), type(FactorType) { }
518
519         ~FactorWithNeg();
520
521         /* Tree traversal. */
522         FsmAp *walk( ParseData *pd );
523         void makeNameTree( ParseData *pd );
524         void resolveNameRefs( ParseData *pd );
525
526         InputLoc loc;
527         FactorWithNeg *factorWithNeg;
528         Factor *factor;
529         Type type;
530 };
531
532 /*
533  * Factor
534  */
535 struct Factor
536 {
537         /* Language elements a factor node can be. */
538         enum Type {
539                 LiteralType, 
540                 RangeType, 
541                 OrExprType,
542                 RegExprType, 
543                 ReferenceType,
544                 ParenType,
545                 LongestMatchType,
546         }; 
547
548         /* Construct with a literal fsm. */
549         Factor( Literal *literal ) :
550                 literal(literal), type(LiteralType) { }
551
552         /* Construct with a range. */
553         Factor( Range *range ) : 
554                 range(range), type(RangeType) { }
555         
556         /* Construct with the or part of a regular expression. */
557         Factor( ReItem *reItem ) :
558                 reItem(reItem), type(OrExprType) { }
559
560         /* Construct with a regular expression. */
561         Factor( RegExpr *regExpr ) :
562                 regExpr(regExpr), type(RegExprType) { }
563
564         /* Construct with a reference to a var def. */
565         Factor( const InputLoc &loc, VarDef *varDef ) :
566                 loc(loc), varDef(varDef), type(ReferenceType) {}
567
568         /* Construct with a parenthesized join. */
569         Factor( Join *join ) :
570                 join(join), type(ParenType) {}
571         
572         /* Construct with a longest match operator. */
573         Factor( LongestMatch *longestMatch ) :
574                 longestMatch(longestMatch), type(LongestMatchType) {}
575
576         /* Cleanup. */
577         ~Factor();
578
579         /* Tree traversal. */
580         FsmAp *walk( ParseData *pd );
581         void makeNameTree( ParseData *pd );
582         void resolveNameRefs( ParseData *pd );
583
584         InputLoc loc;
585         Literal *literal;
586         Range *range;
587         ReItem *reItem;
588         RegExpr *regExpr;
589         VarDef *varDef;
590         Join *join;
591         LongestMatch *longestMatch;
592         int lower, upper;
593         Type type;
594 };
595
596 /* A range machine. Only ever composed of two literals. */
597 struct Range
598 {
599         Range( Literal *lowerLit, Literal *upperLit ) 
600                 : lowerLit(lowerLit), upperLit(upperLit) { }
601
602         ~Range();
603         FsmAp *walk( ParseData *pd );
604
605         Literal *lowerLit;
606         Literal *upperLit;
607 };
608
609 /* Some literal machine. Can be a number or literal string. */
610 struct Literal
611 {
612         enum LiteralType { Number, LitString };
613
614         Literal( const Token &token, LiteralType type )
615                 : token(token), type(type) { }
616
617         FsmAp *walk( ParseData *pd );
618         
619         Token token;
620         LiteralType type;
621 };
622
623 /* Regular expression. */
624 struct RegExpr
625 {
626         enum RegExpType { RecurseItem, Empty };
627
628         /* Constructors. */
629         RegExpr() : 
630                 type(Empty), caseInsensitive(false) { }
631         RegExpr(RegExpr *regExpr, ReItem *item) : 
632                 regExpr(regExpr), item(item), 
633                 type(RecurseItem), caseInsensitive(false) { }
634
635         ~RegExpr();
636         FsmAp *walk( ParseData *pd, RegExpr *rootRegex );
637
638         RegExpr *regExpr;
639         ReItem *item;
640         RegExpType type;
641         bool caseInsensitive;
642 };
643
644 /* An item in a regular expression. */
645 struct ReItem
646 {
647         enum ReItemType { Data, Dot, OrBlock, NegOrBlock };
648         
649         ReItem( const InputLoc &loc, const Token &token ) 
650                 : loc(loc), token(token), star(false), type(Data) { }
651         ReItem( const InputLoc &loc, ReItemType type )
652                 : loc(loc), star(false), type(type) { }
653         ReItem( const InputLoc &loc, ReOrBlock *orBlock, ReItemType type )
654                 : loc(loc), orBlock(orBlock), star(false), type(type) { }
655
656         ~ReItem();
657         FsmAp *walk( ParseData *pd, RegExpr *rootRegex );
658
659         InputLoc loc;
660         Token token;
661         ReOrBlock *orBlock;
662         bool star;
663         ReItemType type;
664 };
665
666 /* An or block item. */
667 struct ReOrBlock
668 {
669         enum ReOrBlockType { RecurseItem, Empty };
670
671         /* Constructors. */
672         ReOrBlock()
673                 : type(Empty) { }
674         ReOrBlock(ReOrBlock *orBlock, ReOrItem *item)
675                 : orBlock(orBlock), item(item), type(RecurseItem) { }
676
677         ~ReOrBlock();
678         FsmAp *walk( ParseData *pd, RegExpr *rootRegex );
679         
680         ReOrBlock *orBlock;
681         ReOrItem *item;
682         ReOrBlockType type;
683 };
684
685 /* An item in an or block. */
686 struct ReOrItem
687 {
688         enum ReOrItemType { Data, Range };
689
690         ReOrItem( const InputLoc &loc, const Token &token ) 
691                 : loc(loc), token(token), type(Data) {}
692         ReOrItem( const InputLoc &loc, char lower, char upper )
693                 : loc(loc), lower(lower), upper(upper), type(Range) { }
694
695         FsmAp *walk( ParseData *pd, RegExpr *rootRegex );
696
697         InputLoc loc;
698         Token token;
699         char lower;
700         char upper;
701         ReOrItemType type;
702 };
703
704
705 /*
706  * Inline code tree
707  */
708 struct InlineList;
709 struct InlineItem
710 {
711         enum Type 
712         {
713                 Text, Goto, Call, Next, GotoExpr, CallExpr, NextExpr, Ret, PChar,
714                 Char, Hold, Curs, Targs, Entry, Exec, LmSwitch, LmSetActId,
715                 LmSetTokEnd, LmOnLast, LmOnNext, LmOnLagBehind, LmInitAct,
716                 LmInitTokStart, LmSetTokStart, Break
717         };
718
719         InlineItem( const InputLoc &loc, char *data, Type type ) : 
720                 loc(loc), data(data), nameRef(0), children(0), type(type) { }
721
722         InlineItem( const InputLoc &loc, NameRef *nameRef, Type type ) : 
723                 loc(loc), data(0), nameRef(nameRef), children(0), type(type) { }
724
725         InlineItem( const InputLoc &loc, LongestMatch *longestMatch, 
726                 LongestMatchPart *longestMatchPart, Type type ) : loc(loc), data(0),
727                 nameRef(0), children(0), longestMatch(longestMatch),
728                 longestMatchPart(longestMatchPart), type(type) { } 
729
730         InlineItem( const InputLoc &loc, NameInst *nameTarg, Type type ) : 
731                 loc(loc), data(0), nameRef(0), nameTarg(nameTarg), children(0),
732                 type(type) { }
733
734         InlineItem( const InputLoc &loc, Type type ) : 
735                 loc(loc), data(0), nameRef(0), children(0), type(type) { }
736         
737         InputLoc loc;
738         char *data;
739         NameRef *nameRef;
740         NameInst *nameTarg;
741         InlineList *children;
742         LongestMatch *longestMatch;
743         LongestMatchPart *longestMatchPart;
744         Type type;
745
746         InlineItem *prev, *next;
747 };
748
749 /* Normally this would be atypedef, but that would entail including DList from
750  * ptreetypes, which should be just typedef forwards. */
751 struct InlineList : public DList<InlineItem> { };
752
753
754
755 #endif /* _PARSETREE_H */