mux function

State mux(
  1. State state
)

Creates a State that generates code that will multiplex the results of computations from different branches into one computation point, transforming multiple inputs computations into single output computation.

This function is used internally by the Sequence to prevent duplication of the generated code. All elements of the Sequence, except the last element, if they generate a computation with multiple outputs, are transformed into a computation with single output.

Implementation

State mux(State state) {
  final type = state.type.trim();
  if (type == 'void') {
    const template = '''
var {{tmp}} = false;
{{@state}}
if ({{tmp}}) {
  {{@accept}}
}
{{@reject}}
''';
    const automaton = Automaton(
      accept: '{{tmp}} = true;',
      reject: '',
      result: 'null',
      template: template,
    );
    const generator = AutomatonGenerator(automaton);
    final start = generator.generate(type, state);
    return start;
  } else {
    const template = '''
({{type}},)? {{tmp}};
{{@state}}
if ({{tmp}} != null) {
  {{@accept}}
}
{{@reject}}
''';
    const automaton = Automaton(
      accept: '{{tmp}} = ({{0}},);',
      reject: '',
      result: '{{tmp}}.\$1',
      template: template,
    );
    const generator = AutomatonGenerator(automaton);
    final start = generator.generate(type, state, values: {'type': type});
    return start;
  }
}