Instantiating in-line state machines

Once an application-specific state machine class has been written, and its grammar made available as a runtime resource, an instance of it needs to be created. This is done by creating a state machine factory object using its FSMFactory<TStateMachine>(...) constructor, then by calling the factory object's CreateInstance() method.

Instantiating state machines from grammar descriptions

The factory for an in-line state machine must be created from its input grammar description, and by using a pre-existing application-specific state machine class that implements the action and guard functions referred to by the state machine grammar. The details for the constructor that creates this factory and its parameters are given below:


public FSMFactory<TStateMachine>
(
    TextReader input,
    bool ignoreErrorEvents,
    TextWriter sourceOutput = null
);

This constructor reads a character string that contains the input grammar description in ParseLR grammar format, and creates an instance of a state machine driven parser that is capable of processing input event or token streams according to that grammar.

ARGUMENT DESCRIPTION
TStateMachine This generic type parameter should be substituted with the class name for the application-specific state machine class that is expected by the input grammar. This class is described elsewhere, but basically should provide the action and guard functions referenced by code embedded in the grammar description.
input The input text stream containing the grammar description from which the parser will be constructed.
ignorErrorEvents When set to true, this enables the state machine to just ignore and drop input events that are not recognised as valid for the current state. When set to false, the first illegal event will abort the state machine.
sourceOutput If this optional parameter is provided, and is not null, the autogenerated source code for the finite state machine is written to this output stream. This might be useful if you are trying to debug an inline implementation of a state machine, as this source code would not normally be visible.

The resulting factory can subsequently be used to create as many separate instances of the finite state machine as you desire. This is done by calling the factory's CreateInstance() method.

Note that creating a state machine factory from the input grammar description is relatively slow and expensive, because the grammar must be parsed and the state machine internal tables built and optimised. By contrast, creating a new state machine instance using the factory is blindingly fast. A common pattern for creating multiple instances is to create a factory from the grammar description input and keep it around so that new instances of the state machine can be created from it as they are needed.