2 * Copyright 2001-2006 Adrian Thurston <thurston@cs.queensu.ca>
5 /* This file is part of Ragel.
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.
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.
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
31 #include "parsetree.h"
34 ostream &operator<<( ostream &out, const NameRef &nameRef );
35 ostream &operator<<( ostream &out, const NameInst &nameInst );
37 /* Convert the literal string which comes in from the scanner into an array of
38 * characters with escapes and options interpreted. Also null terminates the
39 * string. Though this null termination should not be relied on for
40 * interpreting literals in the parser because the string may contain \0 */
41 char *prepareLitString( const InputLoc &loc, char *data, long length,
42 long &resLen, bool &caseInsensitive )
44 char *resData = new char[length+1];
45 caseInsensitive = false;
48 char *end = data + length - 1;
50 while ( *end != '\'' && *end != '\"' ) {
52 caseInsensitive = true;
54 error( loc ) << "literal string '" << *end <<
55 "' option not supported" << endl;
62 while ( src != end ) {
65 case '0': dest[len++] = '\0'; break;
66 case 'a': dest[len++] = '\a'; break;
67 case 'b': dest[len++] = '\b'; break;
68 case 't': dest[len++] = '\t'; break;
69 case 'n': dest[len++] = '\n'; break;
70 case 'v': dest[len++] = '\v'; break;
71 case 'f': dest[len++] = '\f'; break;
72 case 'r': dest[len++] = '\r'; break;
74 default: dest[len++] = src[1]; break;
88 FsmAp *VarDef::walk( ParseData *pd )
90 /* We enter into a new name scope. */
91 NameFrame nameFrame = pd->enterNameScope( true, 1 );
93 /* Recurse on the expression. */
94 FsmAp *rtnVal = joinOrLm->walk( pd );
96 /* Do the tranfer of local error actions. */
97 LocalErrDictEl *localErrDictEl = pd->localErrDict.find( name );
98 if ( localErrDictEl != 0 ) {
99 for ( StateList::Iter state = rtnVal->stateList; state.lte(); state++ )
100 rtnVal->transferErrorActions( state, localErrDictEl->value );
103 /* If the expression below is a join operation with multiple expressions
104 * then it just had epsilon transisions resolved. If it is a join
105 * with only a single expression then run the epsilon op now. */
106 if ( joinOrLm->type == JoinOrLm::JoinType && joinOrLm->join->exprList.length() == 1 )
109 /* We can now unset entry points that are not longer used. */
110 pd->unsetObsoleteEntries( rtnVal );
112 /* If the name of the variable is referenced then add the entry point to
114 if ( pd->curNameInst->numRefs > 0 )
115 rtnVal->setEntry( pd->curNameInst->id, rtnVal->startState );
117 /* Pop the name scope. */
118 pd->popNameScope( nameFrame );
122 void VarDef::makeNameTree( const InputLoc &loc, ParseData *pd )
124 /* The variable definition enters a new scope. */
125 NameInst *prevNameInst = pd->curNameInst;
126 pd->curNameInst = pd->addNameInst( loc, name, false );
128 if ( joinOrLm->type == JoinOrLm::LongestMatchType )
129 pd->curNameInst->isLongestMatch = true;
132 joinOrLm->makeNameTree( pd );
134 /* The name scope ends, pop the name instantiation. */
135 pd->curNameInst = prevNameInst;
138 void VarDef::resolveNameRefs( ParseData *pd )
140 /* Entering into a new scope. */
141 NameFrame nameFrame = pd->enterNameScope( true, 1 );
144 joinOrLm->resolveNameRefs( pd );
146 /* The name scope ends, pop the name instantiation. */
147 pd->popNameScope( nameFrame );
150 InputLoc LongestMatchPart::getLoc()
152 return action != 0 ? action->loc : semiLoc;
156 * If there are any LMs then all of the following entry points must reset
159 * 1. fentry(StateRef)
160 * 2. ftoto(StateRef), fcall(StateRef), fnext(StateRef)
161 * 3. targt of any transition that has an fcall (the return loc).
162 * 4. start state of all longest match routines.
165 Action *LongestMatch::newAction( ParseData *pd, const InputLoc &loc,
166 const char *name, InlineList *inlineList )
168 Action *action = new Action( loc, name, inlineList, pd->nextCondId++ );
169 action->actionRefs.append( pd->curNameInst );
170 pd->actionList.append( action );
171 action->isLmAction = true;
175 void LongestMatch::makeActions( ParseData *pd )
177 /* Make actions that set the action id. */
178 for ( LmPartList::Iter lmi = *longestMatchList; lmi.lte(); lmi++ ) {
179 /* For each part create actions for setting the match type. We need
180 * to do this so that the actions will go into the actionIndex. */
181 InlineList *inlineList = new InlineList;
182 inlineList->append( new InlineItem( lmi->getLoc(), this, lmi,
183 InlineItem::LmSetActId ) );
184 char *actName = new char[50];
185 sprintf( actName, "store%i", lmi->longestMatchId );
186 lmi->setActId = newAction( pd, lmi->getLoc(), actName, inlineList );
189 /* Make actions that execute the user action and restart on the last
191 for ( LmPartList::Iter lmi = *longestMatchList; lmi.lte(); lmi++ ) {
192 /* For each part create actions for setting the match type. We need
193 * to do this so that the actions will go into the actionIndex. */
194 InlineList *inlineList = new InlineList;
195 inlineList->append( new InlineItem( lmi->getLoc(), this, lmi,
196 InlineItem::LmOnLast ) );
197 char *actName = new char[50];
198 sprintf( actName, "last%i", lmi->longestMatchId );
199 lmi->actOnLast = newAction( pd, lmi->getLoc(), actName, inlineList );
202 /* Make actions that execute the user action and restart on the next
203 * character. These actions will set tokend themselves (it is the current
205 for ( LmPartList::Iter lmi = *longestMatchList; lmi.lte(); lmi++ ) {
206 /* For each part create actions for setting the match type. We need
207 * to do this so that the actions will go into the actionIndex. */
208 InlineList *inlineList = new InlineList;
209 inlineList->append( new InlineItem( lmi->getLoc(), this, lmi,
210 InlineItem::LmOnNext ) );
211 char *actName = new char[50];
212 sprintf( actName, "next%i", lmi->longestMatchId );
213 lmi->actOnNext = newAction( pd, lmi->getLoc(), actName, inlineList );
216 /* Make actions that execute the user action and restart at tokend. These
217 * actions execute some time after matching the last char. */
218 for ( LmPartList::Iter lmi = *longestMatchList; lmi.lte(); lmi++ ) {
219 /* For each part create actions for setting the match type. We need
220 * to do this so that the actions will go into the actionIndex. */
221 InlineList *inlineList = new InlineList;
222 inlineList->append( new InlineItem( lmi->getLoc(), this, lmi,
223 InlineItem::LmOnLagBehind ) );
224 char *actName = new char[50];
225 sprintf( actName, "lag%i", lmi->longestMatchId );
226 lmi->actLagBehind = newAction( pd, lmi->getLoc(), actName, inlineList );
233 /* Create the error action. */
234 InlineList *il6 = new InlineList;
235 il6->append( new InlineItem( loc, this, 0, InlineItem::LmSwitch ) );
236 lmActSelect = newAction( pd, loc, "switch", il6 );
239 void LongestMatch::findName( ParseData *pd )
241 NameInst *nameInst = pd->curNameInst;
242 while ( nameInst->name == 0 ) {
243 nameInst = nameInst->parent;
244 /* Since every machine must must have a name, we should always find a
245 * name for the longest match. */
246 assert( nameInst != 0 );
248 name = nameInst->name;
251 void LongestMatch::makeNameTree( ParseData *pd )
253 /* Create an anonymous scope for the longest match. Will be used for
254 * restarting machine after matching a token. */
255 NameInst *prevNameInst = pd->curNameInst;
256 pd->curNameInst = pd->addNameInst( loc, 0, false );
258 /* Recurse into all parts of the longest match operator. */
259 for ( LmPartList::Iter lmi = *longestMatchList; lmi.lte(); lmi++ )
260 lmi->join->makeNameTree( pd );
262 /* Traverse the name tree upwards to find a name for this lm. */
265 /* Also make the longest match's actions at this point. */
268 /* The name scope ends, pop the name instantiation. */
269 pd->curNameInst = prevNameInst;
272 void LongestMatch::resolveNameRefs( ParseData *pd )
274 /* The longest match gets its own name scope. */
275 NameFrame nameFrame = pd->enterNameScope( true, 1 );
277 /* Take an action reference for each longest match item and recurse. */
278 for ( LmPartList::Iter lmi = *longestMatchList; lmi.lte(); lmi++ ) {
279 /* Record the reference if the item has an action. */
280 if ( lmi->action != 0 )
281 lmi->action->actionRefs.append( pd->localNameScope );
283 /* Recurse down the join. */
284 lmi->join->resolveNameRefs( pd );
287 /* The name scope ends, pop the name instantiation. */
288 pd->popNameScope( nameFrame );
291 void LongestMatch::restart( FsmAp *graph, TransAp *trans )
293 StateAp *fromState = trans->fromState;
294 graph->detachTrans( fromState, trans->toState, trans );
295 graph->attachTrans( fromState, graph->startState, trans );
298 void LongestMatch::runLongestMatch( ParseData *pd, FsmAp *graph )
300 graph->markReachableFromHereStopFinal( graph->startState );
301 for ( StateList::Iter ms = graph->stateList; ms.lte(); ms++ ) {
302 if ( ms->stateBits & STB_ISMARKED ) {
303 ms->lmItemSet.insert( 0 );
304 ms->stateBits &= ~ STB_ISMARKED;
308 /* Transfer the first item of non-empty lmAction tables to the item sets
309 * of the states that follow. Exclude states that have no transitions out.
310 * This must happen on a separate pass so that on each iteration of the
311 * next pass we have the item set entries from all lmAction tables. */
312 for ( StateList::Iter st = graph->stateList; st.lte(); st++ ) {
313 for ( TransList::Iter trans = st->outList; trans.lte(); trans++ ) {
314 if ( trans->lmActionTable.length() > 0 ) {
315 LmActionTableEl *lmAct = trans->lmActionTable.data;
316 StateAp *toState = trans->toState;
319 /* Can only optimize this if there are no transitions out.
320 * Note there can be out transitions going nowhere with
321 * actions and they too must inhibit this optimization. */
322 if ( toState->outList.length() > 0 ) {
323 /* Fill the item sets. */
324 graph->markReachableFromHereStopFinal( toState );
325 for ( StateList::Iter ms = graph->stateList; ms.lte(); ms++ ) {
326 if ( ms->stateBits & STB_ISMARKED ) {
327 ms->lmItemSet.insert( lmAct->value );
328 ms->stateBits &= ~ STB_ISMARKED;
336 /* The lmItem sets are now filled, telling us which longest match rules
337 * can succeed in which states. First determine if we need to make sure
338 * act is defaulted to zero. We need to do this if there are any states
339 * with lmItemSet.length() > 1 and NULL is included. That is, that the
340 * switch may get called when in fact nothing has been matched. */
341 int maxItemSetLength = 0;
342 graph->markReachableFromHereStopFinal( graph->startState );
343 for ( StateList::Iter ms = graph->stateList; ms.lte(); ms++ ) {
344 if ( ms->stateBits & STB_ISMARKED ) {
345 if ( ms->lmItemSet.length() > maxItemSetLength )
346 maxItemSetLength = ms->lmItemSet.length();
347 ms->stateBits &= ~ STB_ISMARKED;
351 /* The actions executed on starting to match a token. */
352 graph->isolateStartState();
353 graph->startState->toStateActionTable.setAction( pd->initTokStartOrd, pd->initTokStart );
354 graph->startState->fromStateActionTable.setAction( pd->setTokStartOrd, pd->setTokStart );
355 if ( maxItemSetLength > 1 ) {
356 /* The longest match action switch may be called when tokens are
357 * matched, in which case act must be initialized, there must be a
358 * case to handle the error, and the generated machine will require an
360 lmSwitchHandlesError = true;
361 pd->lmRequiresErrorState = true;
362 graph->startState->toStateActionTable.setAction( pd->initActIdOrd, pd->initActId );
365 /* The place to store transitions to restart. It maybe possible for the
366 * restarting to affect the searching through the graph that follows. For
367 * now take the safe route and save the list of transitions to restart
368 * until after all searching is done. */
369 Vector<TransAp*> restartTrans;
371 /* Set actions that do immediate token recognition, set the longest match part
372 * id and set the token ending. */
373 for ( StateList::Iter st = graph->stateList; st.lte(); st++ ) {
374 for ( TransList::Iter trans = st->outList; trans.lte(); trans++ ) {
375 if ( trans->lmActionTable.length() > 0 ) {
376 LmActionTableEl *lmAct = trans->lmActionTable.data;
377 StateAp *toState = trans->toState;
380 /* Can only optimize this if there are no transitions out.
381 * Note there can be out transitions going nowhere with
382 * actions and they too must inhibit this optimization. */
383 if ( toState->outList.length() == 0 ) {
384 /* Can execute the immediate action for the longest match
385 * part. Redirect the action to the start state.
387 * NOTE: When we need to inhibit on_last due to leaving
388 * actions the above test suffices. If the state has out
389 * actions then it will fail because the out action will
390 * have been transferred to an error transition, which
391 * makes the outlist non-empty. */
392 trans->actionTable.setAction( lmAct->key,
393 lmAct->value->actOnLast );
394 restartTrans.append( trans );
397 /* Look for non final states that have a non-empty item
398 * set. If these are present then we need to record the
399 * end of the token. Also Find the highest item set
400 * length reachable from here (excluding at transtions to
402 bool nonFinalNonEmptyItemSet = false;
403 maxItemSetLength = 0;
404 graph->markReachableFromHereStopFinal( toState );
405 for ( StateList::Iter ms = graph->stateList; ms.lte(); ms++ ) {
406 if ( ms->stateBits & STB_ISMARKED ) {
407 if ( ms->lmItemSet.length() > 0 && !ms->isFinState() )
408 nonFinalNonEmptyItemSet = true;
409 if ( ms->lmItemSet.length() > maxItemSetLength )
410 maxItemSetLength = ms->lmItemSet.length();
411 ms->stateBits &= ~ STB_ISMARKED;
415 /* If there are reachable states that are not final and
416 * have non empty item sets or that have an item set
417 * length greater than one then we need to set tokend
418 * because the error action that matches the token will
420 if ( nonFinalNonEmptyItemSet || maxItemSetLength > 1 )
421 trans->actionTable.setAction( pd->setTokEndOrd, pd->setTokEnd );
423 /* Some states may not know which longest match item to
424 * execute, must set it. */
425 if ( maxItemSetLength > 1 ) {
426 /* There are transitions out, another match may come. */
427 trans->actionTable.setAction( lmAct->key,
428 lmAct->value->setActId );
435 /* Now that all graph searching is done it certainly safe set the
436 * restarting. It may be safe above, however this must be verified. */
437 for ( Vector<TransAp*>::Iter pt = restartTrans; pt.lte(); pt++ )
438 restart( graph, *pt );
440 int lmErrActionOrd = pd->curActionOrd++;
442 /* Embed the error for recognizing a char. */
443 for ( StateList::Iter st = graph->stateList; st.lte(); st++ ) {
444 if ( st->lmItemSet.length() == 1 && st->lmItemSet[0] != 0 ) {
445 if ( st->isFinState() ) {
446 /* On error execute the onActNext action, which knows that
447 * the last character of the token was one back and restart. */
448 graph->setErrorTarget( st, graph->startState, &lmErrActionOrd,
449 &st->lmItemSet[0]->actOnNext, 1 );
450 st->eofActionTable.setAction( lmErrActionOrd,
451 st->lmItemSet[0]->actOnNext );
452 st->eofTarget = graph->startState;
455 graph->setErrorTarget( st, graph->startState, &lmErrActionOrd,
456 &st->lmItemSet[0]->actLagBehind, 1 );
457 st->eofActionTable.setAction( lmErrActionOrd,
458 st->lmItemSet[0]->actLagBehind );
459 st->eofTarget = graph->startState;
462 else if ( st->lmItemSet.length() > 1 ) {
463 /* Need to use the select. Take note of which items the select
464 * is needed for so only the necessary actions are included. */
465 for ( LmItemSet::Iter plmi = st->lmItemSet; plmi.lte(); plmi++ ) {
467 (*plmi)->inLmSelect = true;
469 /* On error, execute the action select and go to the start state. */
470 graph->setErrorTarget( st, graph->startState, &lmErrActionOrd,
472 st->eofActionTable.setAction( lmErrActionOrd, lmActSelect );
473 st->eofTarget = graph->startState;
477 /* Finally, the start state should be made final. */
478 graph->setFinState( graph->startState );
481 void LongestMatch::transferScannerLeavingActions( FsmAp *graph )
483 for ( StateList::Iter st = graph->stateList; st.lte(); st++ ) {
484 if ( st->outActionTable.length() > 0 )
485 graph->setErrorActions( st, st->outActionTable );
489 FsmAp *LongestMatch::walk( ParseData *pd )
491 /* The longest match has it's own name scope. */
492 NameFrame nameFrame = pd->enterNameScope( true, 1 );
494 /* Make each part of the longest match. */
495 FsmAp **parts = new FsmAp*[longestMatchList->length()];
496 LmPartList::Iter lmi = *longestMatchList;
497 for ( int i = 0; lmi.lte(); lmi++, i++ ) {
498 /* Create the machine and embed the setting of the longest match id. */
499 parts[i] = lmi->join->walk( pd );
500 parts[i]->longMatchAction( pd->curActionOrd++, lmi );
503 /* Before we union the patterns we need to deal with leaving actions. They
504 * are transfered to error transitions out of the final states (like local
505 * error actions) and to eof actions. In the scanner we need to forbid
506 * on_last for any final state that has an leaving action. */
507 for ( int i = 0; i < longestMatchList->length(); i++ )
508 transferScannerLeavingActions( parts[i] );
510 /* Union machines one and up with machine zero. The grammar dictates that
511 * there will always be at least one part. */
512 FsmAp *rtnVal = parts[0];
513 for ( int i = 1; i < longestMatchList->length(); i++ ) {
514 rtnVal->unionOp( parts[i] );
515 afterOpMinimize( rtnVal );
518 runLongestMatch( pd, rtnVal );
520 /* Pop the name scope. */
521 pd->popNameScope( nameFrame );
527 FsmAp *JoinOrLm::walk( ParseData *pd )
532 rtnVal = join->walk( pd );
534 case LongestMatchType:
535 rtnVal = longestMatch->walk( pd );
541 void JoinOrLm::makeNameTree( ParseData *pd )
545 join->makeNameTree( pd );
547 case LongestMatchType:
548 longestMatch->makeNameTree( pd );
553 void JoinOrLm::resolveNameRefs( ParseData *pd )
557 join->resolveNameRefs( pd );
559 case LongestMatchType:
560 longestMatch->resolveNameRefs( pd );
566 /* Construct with a location and the first expression. */
567 Join::Join( const InputLoc &loc, Expression *expr )
571 exprList.append( expr );
574 /* Construct with a location and the first expression. */
575 Join::Join( Expression *expr )
579 exprList.append( expr );
582 /* Walk an expression node. */
583 FsmAp *Join::walk( ParseData *pd )
585 if ( exprList.length() > 1 )
586 return walkJoin( pd );
588 return exprList.head->walk( pd );
591 /* There is a list of expressions to join. */
592 FsmAp *Join::walkJoin( ParseData *pd )
594 /* We enter into a new name scope. */
595 NameFrame nameFrame = pd->enterNameScope( true, 1 );
597 /* Evaluate the machines. */
598 FsmAp **fsms = new FsmAp*[exprList.length()];
599 ExprList::Iter expr = exprList;
600 for ( int e = 0; e < exprList.length(); e++, expr++ )
601 fsms[e] = expr->walk( pd );
603 /* Get the start and final names. Final is
604 * guaranteed to exist, start is not. */
605 NameInst *startName = pd->curNameInst->start;
606 NameInst *finalName = pd->curNameInst->final;
609 if ( startName != 0 ) {
610 /* Take note that there was an implicit link to the start machine. */
611 pd->localNameScope->referencedNames.append( startName );
612 startId = startName->id;
615 /* A final id of -1 indicates there is no epsilon that references the
616 * final state, therefor do not create one or set an entry point to it. */
618 if ( finalName->numRefs > 0 )
619 finalId = finalName->id;
621 /* Join machines 1 and up onto machine 0. */
622 FsmAp *retFsm = fsms[0];
623 retFsm->joinOp( startId, finalId, fsms+1, exprList.length()-1 );
625 /* We can now unset entry points that are not longer used. */
626 pd->unsetObsoleteEntries( retFsm );
628 /* Pop the name scope. */
629 pd->popNameScope( nameFrame );
635 void Join::makeNameTree( ParseData *pd )
637 if ( exprList.length() > 1 ) {
638 /* Create the new anonymous scope. */
639 NameInst *prevNameInst = pd->curNameInst;
640 pd->curNameInst = pd->addNameInst( loc, 0, false );
642 /* Join scopes need an implicit "final" target. */
643 pd->curNameInst->final = new NameInst( InputLoc(), pd->curNameInst, "final",
644 pd->nextNameId++, false );
646 /* Recurse into all expressions in the list. */
647 for ( ExprList::Iter expr = exprList; expr.lte(); expr++ )
648 expr->makeNameTree( pd );
650 /* The name scope ends, pop the name instantiation. */
651 pd->curNameInst = prevNameInst;
654 /* Recurse into the single expression. */
655 exprList.head->makeNameTree( pd );
660 void Join::resolveNameRefs( ParseData *pd )
662 /* Branch on whether or not there is to be a join. */
663 if ( exprList.length() > 1 ) {
664 /* The variable definition enters a new scope. */
665 NameFrame nameFrame = pd->enterNameScope( true, 1 );
667 /* The join scope must contain a start label. */
668 NameSet resolved = pd->resolvePart( pd->localNameScope, "start", true );
669 if ( resolved.length() > 0 ) {
670 /* Take the first. */
671 pd->curNameInst->start = resolved[0];
672 if ( resolved.length() > 1 ) {
673 /* Complain about the multiple references. */
674 error(loc) << "multiple start labels" << endl;
675 errorStateLabels( resolved );
679 /* Make sure there is a start label. */
680 if ( pd->curNameInst->start != 0 ) {
681 /* There is an implicit reference to start name. */
682 pd->curNameInst->start->numRefs += 1;
685 /* No start label. Complain and recover by adding a label to the
686 * adding one. Recover ignoring the problem. */
687 error(loc) << "no start label" << endl;
690 /* Recurse into all expressions in the list. */
691 for ( ExprList::Iter expr = exprList; expr.lte(); expr++ )
692 expr->resolveNameRefs( pd );
694 /* The name scope ends, pop the name instantiation. */
695 pd->popNameScope( nameFrame );
698 /* Recurse into the single expression. */
699 exprList.head->resolveNameRefs( pd );
703 /* Clean up after an expression node. */
704 Expression::~Expression()
707 case OrType: case IntersectType: case SubtractType:
708 case StrongSubtractType:
720 /* Evaluate a single expression node. */
721 FsmAp *Expression::walk( ParseData *pd, bool lastInSeq )
726 /* Evaluate the expression. */
727 rtnVal = expression->walk( pd, false );
728 /* Evaluate the term. */
729 FsmAp *rhs = term->walk( pd );
731 rtnVal->unionOp( rhs );
732 afterOpMinimize( rtnVal, lastInSeq );
735 case IntersectType: {
736 /* Evaluate the expression. */
737 rtnVal = expression->walk( pd );
738 /* Evaluate the term. */
739 FsmAp *rhs = term->walk( pd );
740 /* Perform intersection. */
741 rtnVal->intersectOp( rhs );
742 afterOpMinimize( rtnVal, lastInSeq );
746 /* Evaluate the expression. */
747 rtnVal = expression->walk( pd );
748 /* Evaluate the term. */
749 FsmAp *rhs = term->walk( pd );
750 /* Perform subtraction. */
751 rtnVal->subtractOp( rhs );
752 afterOpMinimize( rtnVal, lastInSeq );
755 case StrongSubtractType: {
756 /* Evaluate the expression. */
757 rtnVal = expression->walk( pd );
759 /* Evaluate the term and pad it with any* machines. */
760 FsmAp *rhs = dotStarFsm( pd );
761 FsmAp *termFsm = term->walk( pd );
762 FsmAp *trailAnyStar = dotStarFsm( pd );
763 rhs->concatOp( termFsm );
764 rhs->concatOp( trailAnyStar );
766 /* Perform subtraction. */
767 rtnVal->subtractOp( rhs );
768 afterOpMinimize( rtnVal, lastInSeq );
772 /* Return result of the term. */
773 rtnVal = term->walk( pd );
777 /* Duplicate the builtin. */
778 rtnVal = makeBuiltin( builtin, pd );
786 void Expression::makeNameTree( ParseData *pd )
792 case StrongSubtractType:
793 expression->makeNameTree( pd );
794 term->makeNameTree( pd );
797 term->makeNameTree( pd );
804 void Expression::resolveNameRefs( ParseData *pd )
810 case StrongSubtractType:
811 expression->resolveNameRefs( pd );
812 term->resolveNameRefs( pd );
815 term->resolveNameRefs( pd );
822 /* Clean up after a term node. */
828 case RightFinishType:
831 delete factorWithAug;
833 case FactorWithAugType:
834 delete factorWithAug;
839 /* Evaluate a term node. */
840 FsmAp *Term::walk( ParseData *pd, bool lastInSeq )
845 /* Evaluate the Term. */
846 rtnVal = term->walk( pd, false );
847 /* Evaluate the FactorWithRep. */
848 FsmAp *rhs = factorWithAug->walk( pd );
849 /* Perform concatenation. */
850 rtnVal->concatOp( rhs );
851 afterOpMinimize( rtnVal, lastInSeq );
854 case RightStartType: {
855 /* Evaluate the Term. */
856 rtnVal = term->walk( pd );
858 /* Evaluate the FactorWithRep. */
859 FsmAp *rhs = factorWithAug->walk( pd );
861 /* Set up the priority descriptors. The left machine gets the
862 * lower priority where as the right get the higher start priority. */
863 priorDescs[0].key = pd->nextPriorKey++;
864 priorDescs[0].priority = 0;
865 rtnVal->allTransPrior( pd->curPriorOrd++, &priorDescs[0] );
867 /* The start transitions of the right machine gets the higher
868 * priority. Use the same unique key. */
869 priorDescs[1].key = priorDescs[0].key;
870 priorDescs[1].priority = 1;
871 rhs->startFsmPrior( pd->curPriorOrd++, &priorDescs[1] );
873 /* Perform concatenation. */
874 rtnVal->concatOp( rhs );
875 afterOpMinimize( rtnVal, lastInSeq );
878 case RightFinishType: {
879 /* Evaluate the Term. */
880 rtnVal = term->walk( pd );
882 /* Evaluate the FactorWithRep. */
883 FsmAp *rhs = factorWithAug->walk( pd );
885 /* Set up the priority descriptors. The left machine gets the
886 * lower priority where as the finishing transitions to the right
887 * get the higher priority. */
888 priorDescs[0].key = pd->nextPriorKey++;
889 priorDescs[0].priority = 0;
890 rtnVal->allTransPrior( pd->curPriorOrd++, &priorDescs[0] );
892 /* The finishing transitions of the right machine get the higher
893 * priority. Use the same unique key. */
894 priorDescs[1].key = priorDescs[0].key;
895 priorDescs[1].priority = 1;
896 rhs->finishFsmPrior( pd->curPriorOrd++, &priorDescs[1] );
898 /* If the right machine's start state is final we need to guard
899 * against the left machine persisting by moving through the empty
901 if ( rhs->startState->isFinState() ) {
902 rhs->startState->outPriorTable.setPrior(
903 pd->curPriorOrd++, &priorDescs[1] );
906 /* Perform concatenation. */
907 rtnVal->concatOp( rhs );
908 afterOpMinimize( rtnVal, lastInSeq );
912 /* Evaluate the Term. */
913 rtnVal = term->walk( pd );
915 /* Evaluate the FactorWithRep. */
916 FsmAp *rhs = factorWithAug->walk( pd );
918 /* Set up the priority descriptors. The left machine gets the
919 * higher priority. */
920 priorDescs[0].key = pd->nextPriorKey++;
921 priorDescs[0].priority = 1;
922 rtnVal->allTransPrior( pd->curPriorOrd++, &priorDescs[0] );
924 /* The right machine gets the lower priority. We cannot use
925 * allTransPrior here in case the start state of the right machine
926 * is final. It would allow the right machine thread to run along
927 * with the left if just passing through the start state. Using
928 * startFsmPrior prevents this. */
929 priorDescs[1].key = priorDescs[0].key;
930 priorDescs[1].priority = 0;
931 rhs->startFsmPrior( pd->curPriorOrd++, &priorDescs[1] );
933 /* Perform concatenation. */
934 rtnVal->concatOp( rhs );
935 afterOpMinimize( rtnVal, lastInSeq );
938 case FactorWithAugType: {
939 rtnVal = factorWithAug->walk( pd );
946 void Term::makeNameTree( ParseData *pd )
951 case RightFinishType:
953 term->makeNameTree( pd );
954 factorWithAug->makeNameTree( pd );
956 case FactorWithAugType:
957 factorWithAug->makeNameTree( pd );
962 void Term::resolveNameRefs( ParseData *pd )
967 case RightFinishType:
969 term->resolveNameRefs( pd );
970 factorWithAug->resolveNameRefs( pd );
972 case FactorWithAugType:
973 factorWithAug->resolveNameRefs( pd );
978 /* Clean up after a factor with augmentation node. */
979 FactorWithAug::~FactorWithAug()
981 delete factorWithRep;
983 /* Walk the vector of parser actions, deleting function names. */
985 /* Clean up priority descriptors. */
986 if ( priorDescs != 0 )
990 void FactorWithAug::assignActions( ParseData *pd, FsmAp *graph, int *actionOrd )
992 /* Assign actions. */
993 for ( int i = 0; i < actions.length(); i++ ) {
994 switch ( actions[i].type ) {
995 /* Transition actions. */
997 graph->startFsmAction( actionOrd[i], actions[i].action );
998 afterOpMinimize( graph );
1001 graph->allTransAction( actionOrd[i], actions[i].action );
1004 graph->finishFsmAction( actionOrd[i], actions[i].action );
1007 graph->leaveFsmAction( actionOrd[i], actions[i].action );
1010 /* Global error actions. */
1011 case at_start_gbl_error:
1012 graph->startErrorAction( actionOrd[i], actions[i].action, 0 );
1013 afterOpMinimize( graph );
1015 case at_all_gbl_error:
1016 graph->allErrorAction( actionOrd[i], actions[i].action, 0 );
1018 case at_final_gbl_error:
1019 graph->finalErrorAction( actionOrd[i], actions[i].action, 0 );
1021 case at_not_start_gbl_error:
1022 graph->notStartErrorAction( actionOrd[i], actions[i].action, 0 );
1024 case at_not_final_gbl_error:
1025 graph->notFinalErrorAction( actionOrd[i], actions[i].action, 0 );
1027 case at_middle_gbl_error:
1028 graph->middleErrorAction( actionOrd[i], actions[i].action, 0 );
1031 /* Local error actions. */
1032 case at_start_local_error:
1033 graph->startErrorAction( actionOrd[i], actions[i].action,
1034 actions[i].localErrKey );
1035 afterOpMinimize( graph );
1037 case at_all_local_error:
1038 graph->allErrorAction( actionOrd[i], actions[i].action,
1039 actions[i].localErrKey );
1041 case at_final_local_error:
1042 graph->finalErrorAction( actionOrd[i], actions[i].action,
1043 actions[i].localErrKey );
1045 case at_not_start_local_error:
1046 graph->notStartErrorAction( actionOrd[i], actions[i].action,
1047 actions[i].localErrKey );
1049 case at_not_final_local_error:
1050 graph->notFinalErrorAction( actionOrd[i], actions[i].action,
1051 actions[i].localErrKey );
1053 case at_middle_local_error:
1054 graph->middleErrorAction( actionOrd[i], actions[i].action,
1055 actions[i].localErrKey );
1060 graph->startEOFAction( actionOrd[i], actions[i].action );
1061 afterOpMinimize( graph );
1064 graph->allEOFAction( actionOrd[i], actions[i].action );
1067 graph->finalEOFAction( actionOrd[i], actions[i].action );
1069 case at_not_start_eof:
1070 graph->notStartEOFAction( actionOrd[i], actions[i].action );
1072 case at_not_final_eof:
1073 graph->notFinalEOFAction( actionOrd[i], actions[i].action );
1076 graph->middleEOFAction( actionOrd[i], actions[i].action );
1079 /* To State Actions. */
1080 case at_start_to_state:
1081 graph->startToStateAction( actionOrd[i], actions[i].action );
1082 afterOpMinimize( graph );
1084 case at_all_to_state:
1085 graph->allToStateAction( actionOrd[i], actions[i].action );
1087 case at_final_to_state:
1088 graph->finalToStateAction( actionOrd[i], actions[i].action );
1090 case at_not_start_to_state:
1091 graph->notStartToStateAction( actionOrd[i], actions[i].action );
1093 case at_not_final_to_state:
1094 graph->notFinalToStateAction( actionOrd[i], actions[i].action );
1096 case at_middle_to_state:
1097 graph->middleToStateAction( actionOrd[i], actions[i].action );
1100 /* From State Actions. */
1101 case at_start_from_state:
1102 graph->startFromStateAction( actionOrd[i], actions[i].action );
1103 afterOpMinimize( graph );
1105 case at_all_from_state:
1106 graph->allFromStateAction( actionOrd[i], actions[i].action );
1108 case at_final_from_state:
1109 graph->finalFromStateAction( actionOrd[i], actions[i].action );
1111 case at_not_start_from_state:
1112 graph->notStartFromStateAction( actionOrd[i], actions[i].action );
1114 case at_not_final_from_state:
1115 graph->notFinalFromStateAction( actionOrd[i], actions[i].action );
1117 case at_middle_from_state:
1118 graph->middleFromStateAction( actionOrd[i], actions[i].action );
1121 /* Remaining cases, prevented by the parser. */
1129 void FactorWithAug::assignPriorities( FsmAp *graph, int *priorOrd )
1131 /* Assign priorities. */
1132 for ( int i = 0; i < priorityAugs.length(); i++ ) {
1133 switch ( priorityAugs[i].type ) {
1135 graph->startFsmPrior( priorOrd[i], &priorDescs[i]);
1136 /* Start fsm priorities are a special case that may require
1137 * minimization afterwards. */
1138 afterOpMinimize( graph );
1141 graph->allTransPrior( priorOrd[i], &priorDescs[i] );
1144 graph->finishFsmPrior( priorOrd[i], &priorDescs[i] );
1147 graph->leaveFsmPrior( priorOrd[i], &priorDescs[i] );
1151 /* Parser Prevents this case. */
1157 void FactorWithAug::assignConditions( FsmAp *graph )
1159 for ( int i = 0; i < conditions.length(); i++ ) {
1160 switch ( conditions[i].type ) {
1161 /* Transition actions. */
1163 graph->startFsmCondition( conditions[i].action, conditions[i].sense );
1164 afterOpMinimize( graph );
1167 graph->allTransCondition( conditions[i].action, conditions[i].sense );
1170 graph->leaveFsmCondition( conditions[i].action, conditions[i].sense );
1179 /* Evaluate a factor with augmentation node. */
1180 FsmAp *FactorWithAug::walk( ParseData *pd )
1182 /* Enter into the scopes created for the labels. */
1183 NameFrame nameFrame = pd->enterNameScope( false, labels.length() );
1185 /* Make the array of function orderings. */
1187 if ( actions.length() > 0 )
1188 actionOrd = new int[actions.length()];
1190 /* First walk the list of actions, assigning order to all starting
1192 for ( int i = 0; i < actions.length(); i++ ) {
1193 if ( actions[i].type == at_start ||
1194 actions[i].type == at_start_gbl_error ||
1195 actions[i].type == at_start_local_error ||
1196 actions[i].type == at_start_to_state ||
1197 actions[i].type == at_start_from_state ||
1198 actions[i].type == at_start_eof )
1199 actionOrd[i] = pd->curActionOrd++;
1202 /* Evaluate the factor with repetition. */
1203 FsmAp *rtnVal = factorWithRep->walk( pd );
1205 /* Compute the remaining action orderings. */
1206 for ( int i = 0; i < actions.length(); i++ ) {
1207 if ( actions[i].type != at_start &&
1208 actions[i].type != at_start_gbl_error &&
1209 actions[i].type != at_start_local_error &&
1210 actions[i].type != at_start_to_state &&
1211 actions[i].type != at_start_from_state &&
1212 actions[i].type != at_start_eof )
1213 actionOrd[i] = pd->curActionOrd++;
1216 /* Embed conditions. */
1217 assignConditions( rtnVal );
1219 /* Embed actions. */
1220 assignActions( pd, rtnVal , actionOrd );
1222 /* Make the array of priority orderings. Orderings are local to this walk
1223 * of the factor with augmentation. */
1225 if ( priorityAugs.length() > 0 )
1226 priorOrd = new int[priorityAugs.length()];
1228 /* Walk all priorities, assigning the priority ordering. */
1229 for ( int i = 0; i < priorityAugs.length(); i++ )
1230 priorOrd[i] = pd->curPriorOrd++;
1232 /* If the priority descriptors have not been made, make them now. Make
1233 * priority descriptors for each priority asignment that will be passed to
1234 * the fsm. Used to keep track of the key, value and used bit. */
1235 if ( priorDescs == 0 && priorityAugs.length() > 0 ) {
1236 priorDescs = new PriorDesc[priorityAugs.length()];
1237 for ( int i = 0; i < priorityAugs.length(); i++ ) {
1238 /* Init the prior descriptor for the priority setting. */
1239 priorDescs[i].key = priorityAugs[i].priorKey;
1240 priorDescs[i].priority = priorityAugs[i].priorValue;
1244 /* Assign priorities into the machine. */
1245 assignPriorities( rtnVal, priorOrd );
1247 /* Assign epsilon transitions. */
1248 for ( int e = 0; e < epsilonLinks.length(); e++ ) {
1249 /* Get the name, which may not exist. If it doesn't then silently
1250 * ignore it because an error has already been reported. */
1251 NameInst *epTarg = pd->epsilonResolvedLinks[pd->nextEpsilonResolvedLink++];
1252 if ( epTarg != 0 ) {
1253 /* Make the epsilon transitions. */
1254 rtnVal->epsilonTrans( epTarg->id );
1256 /* Note that we have made a link to the name. */
1257 pd->localNameScope->referencedNames.append( epTarg );
1261 /* Set entry points for labels. */
1262 if ( labels.length() > 0 ) {
1263 /* Pop the names. */
1264 pd->resetNameScope( nameFrame );
1266 /* Make labels that are referenced into entry points. */
1267 for ( int i = 0; i < labels.length(); i++ ) {
1268 pd->enterNameScope( false, 1 );
1270 /* Will always be found. */
1271 NameInst *name = pd->curNameInst;
1273 /* If the name is referenced then set the entry point. */
1274 if ( name->numRefs > 0 )
1275 rtnVal->setEntry( name->id, rtnVal->startState );
1278 pd->popNameScope( nameFrame );
1281 if ( priorOrd != 0 )
1283 if ( actionOrd != 0 )
1288 void FactorWithAug::makeNameTree( ParseData *pd )
1290 /* Add the labels to the tree of instantiated names. Each label
1291 * makes a new scope. */
1292 NameInst *prevNameInst = pd->curNameInst;
1293 for ( int i = 0; i < labels.length(); i++ )
1294 pd->curNameInst = pd->addNameInst( labels[i].loc, labels[i].data, true );
1296 /* Recurse, then pop the names. */
1297 factorWithRep->makeNameTree( pd );
1298 pd->curNameInst = prevNameInst;
1302 void FactorWithAug::resolveNameRefs( ParseData *pd )
1304 /* Enter into the name scope created by any labels. */
1305 NameFrame nameFrame = pd->enterNameScope( false, labels.length() );
1307 /* Note action references. */
1308 for ( int i = 0; i < actions.length(); i++ )
1309 actions[i].action->actionRefs.append( pd->localNameScope );
1311 /* Recurse first. IMPORTANT: we must do the exact same traversal as when
1312 * the tree is constructed. */
1313 factorWithRep->resolveNameRefs( pd );
1315 /* Resolve epsilon transitions. */
1316 for ( int ep = 0; ep < epsilonLinks.length(); ep++ ) {
1318 EpsilonLink &link = epsilonLinks[ep];
1319 NameInst *resolvedName = 0;
1321 if ( link.target.length() == 1 && strcmp( link.target.data[0], "final" ) == 0 ) {
1322 /* Epsilon drawn to an implicit final state. An implicit final is
1323 * only available in join operations. */
1324 resolvedName = pd->localNameScope->final;
1327 /* Do an search for the name. */
1329 pd->resolveFrom( resolved, pd->localNameScope, link.target, 0 );
1330 if ( resolved.length() > 0 ) {
1331 /* Take the first one. */
1332 resolvedName = resolved[0];
1333 if ( resolved.length() > 1 ) {
1334 /* Complain about the multiple references. */
1335 error(link.loc) << "state reference " << link.target <<
1336 " resolves to multiple entry points" << endl;
1337 errorStateLabels( resolved );
1342 /* This is tricky, we stuff resolved epsilon transitions into one long
1343 * vector in the parse data structure. Since the name resolution and
1344 * graph generation both do identical walks of the parse tree we
1345 * should always find the link resolutions in the right place. */
1346 pd->epsilonResolvedLinks.append( resolvedName );
1348 if ( resolvedName != 0 ) {
1349 /* Found the name, bump of the reference count on it. */
1350 resolvedName->numRefs += 1;
1353 /* Complain, no recovery action, the epsilon op will ignore any
1354 * epsilon transitions whose names did not resolve. */
1355 error(link.loc) << "could not resolve label " << link.target << endl;
1359 if ( labels.length() > 0 )
1360 pd->popNameScope( nameFrame );
1364 /* Clean up after a factor with repetition node. */
1365 FactorWithRep::~FactorWithRep()
1368 case StarType: case StarStarType: case OptionalType: case PlusType:
1369 case ExactType: case MaxType: case MinType: case RangeType:
1370 delete factorWithRep;
1372 case FactorWithNegType:
1373 delete factorWithNeg;
1378 /* Evaluate a factor with repetition node. */
1379 FsmAp *FactorWithRep::walk( ParseData *pd )
1385 /* Evaluate the FactorWithRep. */
1386 retFsm = factorWithRep->walk( pd );
1387 if ( retFsm->startState->isFinState() ) {
1388 warning(loc) << "applying kleene star to a machine that "
1389 "accepts zero length word" << endl;
1390 retFsm->unsetFinState( retFsm->startState );
1393 /* Shift over the start action orders then do the kleene star. */
1394 pd->curActionOrd += retFsm->shiftStartActionOrder( pd->curActionOrd );
1396 afterOpMinimize( retFsm );
1399 case StarStarType: {
1400 /* Evaluate the FactorWithRep. */
1401 retFsm = factorWithRep->walk( pd );
1402 if ( retFsm->startState->isFinState() ) {
1403 warning(loc) << "applying kleene star to a machine that "
1404 "accepts zero length word" << endl;
1407 /* Set up the prior descs. All gets priority one, whereas leaving gets
1408 * priority zero. Make a unique key so that these priorities don't
1409 * interfere with any priorities set by the user. */
1410 priorDescs[0].key = pd->nextPriorKey++;
1411 priorDescs[0].priority = 1;
1412 retFsm->allTransPrior( pd->curPriorOrd++, &priorDescs[0] );
1414 /* Leaveing gets priority 0. Use same unique key. */
1415 priorDescs[1].key = priorDescs[0].key;
1416 priorDescs[1].priority = 0;
1417 retFsm->leaveFsmPrior( pd->curPriorOrd++, &priorDescs[1] );
1419 /* Shift over the start action orders then do the kleene star. */
1420 pd->curActionOrd += retFsm->shiftStartActionOrder( pd->curActionOrd );
1422 afterOpMinimize( retFsm );
1425 case OptionalType: {
1426 /* Make the null fsm. */
1427 FsmAp *nu = new FsmAp();
1430 /* Evaluate the FactorWithRep. */
1431 retFsm = factorWithRep->walk( pd );
1433 /* Perform the question operator. */
1434 retFsm->unionOp( nu );
1435 afterOpMinimize( retFsm );
1439 /* Evaluate the FactorWithRep. */
1440 retFsm = factorWithRep->walk( pd );
1441 if ( retFsm->startState->isFinState() ) {
1442 warning(loc) << "applying plus operator to a machine that "
1443 "accpets zero length word" << endl;
1446 /* Need a duplicated for the star end. */
1447 FsmAp *dup = new FsmAp( *retFsm );
1449 /* The start func orders need to be shifted before doing the star. */
1450 pd->curActionOrd += dup->shiftStartActionOrder( pd->curActionOrd );
1452 /* Star the duplicate. */
1454 afterOpMinimize( dup );
1456 retFsm->concatOp( dup );
1457 afterOpMinimize( retFsm );
1461 /* Get an int from the repetition amount. */
1462 if ( lowerRep == 0 ) {
1463 /* No copies. Don't need to evaluate the factorWithRep.
1464 * This Defeats the purpose so give a warning. */
1465 warning(loc) << "exactly zero repetitions results "
1466 "in the null machine" << endl;
1468 retFsm = new FsmAp();
1469 retFsm->lambdaFsm();
1472 /* Evaluate the first FactorWithRep. */
1473 retFsm = factorWithRep->walk( pd );
1474 if ( retFsm->startState->isFinState() ) {
1475 warning(loc) << "applying repetition to a machine that "
1476 "accepts zero length word" << endl;
1479 /* The start func orders need to be shifted before doing the
1481 pd->curActionOrd += retFsm->shiftStartActionOrder( pd->curActionOrd );
1483 /* Do the repetition on the machine. Already guarded against n == 0 */
1484 retFsm->repeatOp( lowerRep );
1485 afterOpMinimize( retFsm );
1490 /* Get an int from the repetition amount. */
1491 if ( upperRep == 0 ) {
1492 /* No copies. Don't need to evaluate the factorWithRep.
1493 * This Defeats the purpose so give a warning. */
1494 warning(loc) << "max zero repetitions results "
1495 "in the null machine" << endl;
1497 retFsm = new FsmAp();
1498 retFsm->lambdaFsm();
1501 /* Evaluate the first FactorWithRep. */
1502 retFsm = factorWithRep->walk( pd );
1503 if ( retFsm->startState->isFinState() ) {
1504 warning(loc) << "applying max repetition to a machine that "
1505 "accepts zero length word" << endl;
1508 /* The start func orders need to be shifted before doing the
1510 pd->curActionOrd += retFsm->shiftStartActionOrder( pd->curActionOrd );
1512 /* Do the repetition on the machine. Already guarded against n == 0 */
1513 retFsm->optionalRepeatOp( upperRep );
1514 afterOpMinimize( retFsm );
1519 /* Evaluate the repeated machine. */
1520 retFsm = factorWithRep->walk( pd );
1521 if ( retFsm->startState->isFinState() ) {
1522 warning(loc) << "applying min repetition to a machine that "
1523 "accepts zero length word" << endl;
1526 /* The start func orders need to be shifted before doing the repetition
1527 * and the kleene star. */
1528 pd->curActionOrd += retFsm->shiftStartActionOrder( pd->curActionOrd );
1530 if ( lowerRep == 0 ) {
1531 /* Acts just like a star op on the machine to return. */
1533 afterOpMinimize( retFsm );
1536 /* Take a duplicate for the plus. */
1537 FsmAp *dup = new FsmAp( *retFsm );
1539 /* Do repetition on the first half. */
1540 retFsm->repeatOp( lowerRep );
1541 afterOpMinimize( retFsm );
1543 /* Star the duplicate. */
1545 afterOpMinimize( dup );
1547 /* Tak on the kleene star. */
1548 retFsm->concatOp( dup );
1549 afterOpMinimize( retFsm );
1554 /* Check for bogus range. */
1555 if ( upperRep - lowerRep < 0 ) {
1556 error(loc) << "invalid range repetition" << endl;
1558 /* Return null machine as recovery. */
1559 retFsm = new FsmAp();
1560 retFsm->lambdaFsm();
1562 else if ( lowerRep == 0 && upperRep == 0 ) {
1563 /* No copies. Don't need to evaluate the factorWithRep. This
1564 * defeats the purpose so give a warning. */
1565 warning(loc) << "zero to zero repetitions results "
1566 "in the null machine" << endl;
1568 retFsm = new FsmAp();
1569 retFsm->lambdaFsm();
1572 /* Now need to evaluate the repeated machine. */
1573 retFsm = factorWithRep->walk( pd );
1574 if ( retFsm->startState->isFinState() ) {
1575 warning(loc) << "applying range repetition to a machine that "
1576 "accepts zero length word" << endl;
1579 /* The start func orders need to be shifted before doing both kinds
1581 pd->curActionOrd += retFsm->shiftStartActionOrder( pd->curActionOrd );
1583 if ( lowerRep == 0 ) {
1584 /* Just doing max repetition. Already guarded against n == 0. */
1585 retFsm->optionalRepeatOp( upperRep );
1586 afterOpMinimize( retFsm );
1588 else if ( lowerRep == upperRep ) {
1589 /* Just doing exact repetition. Already guarded against n == 0. */
1590 retFsm->repeatOp( lowerRep );
1591 afterOpMinimize( retFsm );
1594 /* This is the case that 0 < lowerRep < upperRep. Take a
1595 * duplicate for the optional repeat. */
1596 FsmAp *dup = new FsmAp( *retFsm );
1598 /* Do repetition on the first half. */
1599 retFsm->repeatOp( lowerRep );
1600 afterOpMinimize( retFsm );
1602 /* Do optional repetition on the second half. */
1603 dup->optionalRepeatOp( upperRep - lowerRep );
1604 afterOpMinimize( dup );
1606 /* Tak on the duplicate machine. */
1607 retFsm->concatOp( dup );
1608 afterOpMinimize( retFsm );
1613 case FactorWithNegType: {
1614 /* Evaluate the Factor. Pass it up. */
1615 retFsm = factorWithNeg->walk( pd );
1621 void FactorWithRep::makeNameTree( ParseData *pd )
1632 factorWithRep->makeNameTree( pd );
1634 case FactorWithNegType:
1635 factorWithNeg->makeNameTree( pd );
1640 void FactorWithRep::resolveNameRefs( ParseData *pd )
1651 factorWithRep->resolveNameRefs( pd );
1653 case FactorWithNegType:
1654 factorWithNeg->resolveNameRefs( pd );
1659 /* Clean up after a factor with negation node. */
1660 FactorWithNeg::~FactorWithNeg()
1664 case CharNegateType:
1665 delete factorWithNeg;
1673 /* Evaluate a factor with negation node. */
1674 FsmAp *FactorWithNeg::walk( ParseData *pd )
1680 /* Evaluate the factorWithNeg. */
1681 FsmAp *toNegate = factorWithNeg->walk( pd );
1683 /* Negation is subtract from dot-star. */
1684 retFsm = dotStarFsm( pd );
1685 retFsm->subtractOp( toNegate );
1686 afterOpMinimize( retFsm );
1689 case CharNegateType: {
1690 /* Evaluate the factorWithNeg. */
1691 FsmAp *toNegate = factorWithNeg->walk( pd );
1693 /* CharNegation is subtract from dot. */
1694 retFsm = dotFsm( pd );
1695 retFsm->subtractOp( toNegate );
1696 afterOpMinimize( retFsm );
1700 /* Evaluate the Factor. Pass it up. */
1701 retFsm = factor->walk( pd );
1707 void FactorWithNeg::makeNameTree( ParseData *pd )
1711 case CharNegateType:
1712 factorWithNeg->makeNameTree( pd );
1715 factor->makeNameTree( pd );
1720 void FactorWithNeg::resolveNameRefs( ParseData *pd )
1724 case CharNegateType:
1725 factorWithNeg->resolveNameRefs( pd );
1728 factor->resolveNameRefs( pd );
1733 /* Clean up after a factor node. */
1754 case LongestMatchType:
1755 delete longestMatch;
1760 /* Evaluate a factor node. */
1761 FsmAp *Factor::walk( ParseData *pd )
1766 rtnVal = literal->walk( pd );
1769 rtnVal = range->walk( pd );
1772 rtnVal = reItem->walk( pd, 0 );
1775 rtnVal = regExpr->walk( pd, 0 );
1778 rtnVal = varDef->walk( pd );
1781 rtnVal = join->walk( pd );
1783 case LongestMatchType:
1784 rtnVal = longestMatch->walk( pd );
1791 void Factor::makeNameTree( ParseData *pd )
1800 varDef->makeNameTree( loc, pd );
1803 join->makeNameTree( pd );
1805 case LongestMatchType:
1806 longestMatch->makeNameTree( pd );
1811 void Factor::resolveNameRefs( ParseData *pd )
1820 varDef->resolveNameRefs( pd );
1823 join->resolveNameRefs( pd );
1825 case LongestMatchType:
1826 longestMatch->resolveNameRefs( pd );
1831 /* Clean up a range object. Must delete the two literals. */
1838 /* Evaluate a range. Gets the lower an upper key and makes an fsm range. */
1839 FsmAp *Range::walk( ParseData *pd )
1841 /* Construct and verify the suitability of the lower end of the range. */
1842 FsmAp *lowerFsm = lowerLit->walk( pd );
1843 if ( !lowerFsm->checkSingleCharMachine() ) {
1844 error(lowerLit->token.loc) <<
1845 "bad range lower end, must be a single character" << endl;
1848 /* Construct and verify the upper end. */
1849 FsmAp *upperFsm = upperLit->walk( pd );
1850 if ( !upperFsm->checkSingleCharMachine() ) {
1851 error(upperLit->token.loc) <<
1852 "bad range upper end, must be a single character" << endl;
1855 /* Grab the keys from the machines, then delete them. */
1856 Key lowKey = lowerFsm->startState->outList.head->lowKey;
1857 Key highKey = upperFsm->startState->outList.head->lowKey;
1861 /* Validate the range. */
1862 if ( lowKey > highKey ) {
1863 /* Recover by setting upper to lower; */
1864 error(lowerLit->token.loc) << "lower end of range is greater then upper end" << endl;
1868 /* Return the range now that it is validated. */
1869 FsmAp *retFsm = new FsmAp();
1870 retFsm->rangeFsm( lowKey, highKey );
1874 /* Evaluate a literal object. */
1875 FsmAp *Literal::walk( ParseData *pd )
1877 /* FsmAp to return, is the alphabet signed. */
1882 /* Make the fsm key in int format. */
1883 Key fsmKey = makeFsmKeyNum( token.data, token.loc, pd );
1884 /* Make the new machine. */
1885 rtnVal = new FsmAp();
1886 rtnVal->concatFsm( fsmKey );
1890 /* Make the array of keys in int format. */
1892 bool caseInsensitive;
1893 char *data = prepareLitString( token.loc, token.data, token.length,
1894 length, caseInsensitive );
1895 Key *arr = new Key[length];
1896 makeFsmKeyArray( arr, data, length, pd );
1898 /* Make the new machine. */
1899 rtnVal = new FsmAp();
1900 if ( caseInsensitive )
1901 rtnVal->concatFsmCI( arr, length );
1903 rtnVal->concatFsm( arr, length );
1911 /* Clean up after a regular expression object. */
1924 /* Evaluate a regular expression object. */
1925 FsmAp *RegExpr::walk( ParseData *pd, RegExpr *rootRegex )
1927 /* This is the root regex, pass down a pointer to this. */
1928 if ( rootRegex == 0 )
1934 /* Walk both items. */
1935 rtnVal = regExpr->walk( pd, rootRegex );
1936 FsmAp *fsm2 = item->walk( pd, rootRegex );
1937 rtnVal->concatOp( fsm2 );
1941 rtnVal = new FsmAp();
1942 rtnVal->lambdaFsm();
1949 /* Clean up after an item in a regular expression. */
1963 /* Evaluate a regular expression object. */
1964 FsmAp *ReItem::walk( ParseData *pd, RegExpr *rootRegex )
1966 /* The fsm to return, is the alphabet signed? */
1971 /* Move the data into an integer array and make a concat fsm. */
1972 Key *arr = new Key[token.length];
1973 makeFsmKeyArray( arr, token.data, token.length, pd );
1975 /* Make the concat fsm. */
1976 rtnVal = new FsmAp();
1977 if ( rootRegex != 0 && rootRegex->caseInsensitive )
1978 rtnVal->concatFsmCI( arr, token.length );
1980 rtnVal->concatFsm( arr, token.length );
1985 /* Make the dot fsm. */
1986 rtnVal = dotFsm( pd );
1990 /* Get the or block and minmize it. */
1991 rtnVal = orBlock->walk( pd, rootRegex );
1992 if ( rtnVal == 0 ) {
1993 rtnVal = new FsmAp();
1994 rtnVal->lambdaFsm();
1996 rtnVal->minimizePartition2();
2000 /* Get the or block and minimize it. */
2001 FsmAp *fsm = orBlock->walk( pd, rootRegex );
2002 fsm->minimizePartition2();
2004 /* Make a dot fsm and subtract from it. */
2005 rtnVal = dotFsm( pd );
2006 rtnVal->subtractOp( fsm );
2007 rtnVal->minimizePartition2();
2012 /* If the item is followed by a star, then apply the star op. */
2014 if ( rtnVal->startState->isFinState() ) {
2015 warning(loc) << "applying kleene star to a machine that "
2016 "accpets zero length word" << endl;
2020 rtnVal->minimizePartition2();
2025 /* Clean up after an or block of a regular expression. */
2026 ReOrBlock::~ReOrBlock()
2039 /* Evaluate an or block of a regular expression. */
2040 FsmAp *ReOrBlock::walk( ParseData *pd, RegExpr *rootRegex )
2045 /* Evaluate the two fsm. */
2046 FsmAp *fsm1 = orBlock->walk( pd, rootRegex );
2047 FsmAp *fsm2 = item->walk( pd, rootRegex );
2051 fsm1->unionOp( fsm2 );
2064 /* Evaluate an or block item of a regular expression. */
2065 FsmAp *ReOrItem::walk( ParseData *pd, RegExpr *rootRegex )
2067 /* The return value, is the alphabet signed? */
2071 /* Make the or machine. */
2072 rtnVal = new FsmAp();
2074 /* Put the or data into an array of ints. Note that we find unique
2075 * keys. Duplicates are silently ignored. The alternative would be to
2076 * issue warning or an error but since we can't with [a0-9a] or 'a' |
2077 * 'a' don't bother here. */
2079 makeFsmUniqueKeyArray( keySet, token.data, token.length,
2080 rootRegex != 0 ? rootRegex->caseInsensitive : false, pd );
2082 /* Run the or operator. */
2083 rtnVal->orFsm( keySet.data, keySet.length() );
2087 /* Make the upper and lower keys. */
2088 Key lowKey = makeFsmKeyChar( lower, pd );
2089 Key highKey = makeFsmKeyChar( upper, pd );
2091 /* Validate the range. */
2092 if ( lowKey > highKey ) {
2093 /* Recover by setting upper to lower; */
2094 error(loc) << "lower end of range is greater then upper end" << endl;
2098 /* Make the range machine. */
2099 rtnVal = new FsmAp();
2100 rtnVal->rangeFsm( lowKey, highKey );
2102 if ( rootRegex != 0 && rootRegex->caseInsensitive ) {
2103 if ( lowKey <= 'Z' && 'A' <= highKey ) {
2104 Key otherLow = lowKey < 'A' ? Key('A') : lowKey;
2105 Key otherHigh = 'Z' < highKey ? Key('Z') : highKey;
2107 otherLow = 'a' + ( otherLow - 'A' );
2108 otherHigh = 'a' + ( otherHigh - 'A' );
2110 FsmAp *otherRange = new FsmAp();
2111 otherRange->rangeFsm( otherLow, otherHigh );
2112 rtnVal->unionOp( otherRange );
2113 rtnVal->minimizePartition2();
2115 else if ( lowKey <= 'z' && 'a' <= highKey ) {
2116 Key otherLow = lowKey < 'a' ? Key('a') : lowKey;
2117 Key otherHigh = 'z' < highKey ? Key('z') : highKey;
2119 otherLow = 'A' + ( otherLow - 'a' );
2120 otherHigh = 'A' + ( otherHigh - 'a' );
2122 FsmAp *otherRange = new FsmAp();
2123 otherRange->rangeFsm( otherLow, otherHigh );
2124 rtnVal->unionOp( otherRange );
2125 rtnVal->minimizePartition2();