This will give us the basic generic generator in Listing 11.10, shown here in a
hypothetical template-based crawler language.
Listing 11.10 Simple C generator for state machines.
switch (state)
{
<% do .State %>
case <%=id%>:
switch (event)
{
<% do ~From>Transition %>
case <%=:Event%>:
if (<%=:Condition%>)
{
<%=~From.State:ExitAction%>;
<%=:Action%>;
<%=~To.State:EntryAction%>;
state = <%=~To.State%>;
}
break;
<% enddo %>
default:
break;
}
<% enddo %>
default:
break;
}
We start the switch statement, then iterate over each state. For each state we
generate a case statement and an inner switch statement. Inside that we iterate
GENERATOR OUTPUT PATTERNS 293
over each transition from that state, generating a case statement for each event.
Within this innermost case we generate an if statement for the condition, and
inside it the exit action for the previous state, the action along the transition, the
entry action for the new state, and an assignment that sets the new state as the
current state.
Transition Table A second way of implementing state machines is to represent
them as data rather than code. This approach is seen more often in object-oriented
languages, whereas the switch??“case approach is most common in procedural
languages like C. More complex state machine modeling languages also tend to be
better represented as transition tables.
Pages:
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545