map function

State map(
  1. String type,
  2. State state,
  3. String expression
)

Creates a State that generates source that will transform the result of the state computation.

To use the result in a transformation expression, result access placeholders are available.

The result access placeholders look like {{n}}, where n is the index.

When used with Sequence state, the index corresponds to the result of the corresponding sequence element, in all other cases the result value is not multiple and the index can only be 0.

Example:

final s1 = seq([
  s(1),
  s(2),
  s(3),
 ]);
final s0 = map('String', s1, '"{{0}}{{1}}{{2}}"');

Implementation

State map(String type, State state, String expression) {
  state.listenToAcceptors((acceptor, allocate) {
    var result = expression;
    if (state is SequenceState) {
      final states = state.states;
      for (var i = 0; i < states.length; i++) {
        final state = states[i];
        result = result.replaceAll('{{$i}}', state.result);
      }
    } else {
      result = result.replaceAll('{{0}}', acceptor.result);
    }

    final v = allocate('v');
    final acceptance = '''
final $v = $result;
{{@accept}}''';
    acceptor.renderAcceptance(acceptance);
    acceptor.result = v;
    state.type = type;
  });

  return state;
}