buildFunction method

String buildFunction(
  1. String name,
  2. SubProductionsList productions,
  3. Map<String, Set<String>> firsts,
  4. GivenInformation givenInformation,
)

Build all functions that are inside the syntactic analyzer

Implementation

String buildFunction(
  final String name,
  final SubProductionsList productions,
  final Map<String, Set<String>> firsts,
  final GivenInformation givenInformation,
) {
  // Signature and general function declarations
  final excludedTerminals = givenInformation.keys.toSet();
  final buffer = _writeFunctionBegin(name, productions);
  buffer.writeln(
    '\ttemp_token_type = token_queue.peek().get_token_type()',
  );
  // Start of analysing
  for (var index = 0; index < productions.length; index++) {
    final production = productions[index];
    final firstProduction = production[0];
    buffer.writeln('\t# Predicting for production ${production.toString()}');
    final firstSet = firsts[firstProduction] ?? <String>{};
    final tokenTypesVerification = buildVerifyTokenTypes(
      firstSet,
      givenInformation,
      false,
    );
    final tokenTypesCondition = tokenTypesVerification.isNotEmpty
        ? ' or $tokenTypesVerification'
        : '';

    buffer.write('\t');
    if (index > 0) {
      buffer.write('el');
    }
    if (firstProduction.tokenType == TokenType.production) {
      buffer.writeln(
        'if token_queue.peek() and token_queue.peek().get_lexeme() in ${listTerminalToString(
          firstSet,
          excluded: excludedTerminals,
        )}$tokenTypesCondition:',
      );
      buffer.writeln(
        '\t\ttemp = ${genFunctionName(firstProduction.lexeme)}(token_queue, error_list)',
      );
      buffer.writeln('\t\tif temp and temp.is_not_empty():');
      buffer.writeln('\t\t\tnode.add(temp)');
    } else if (firstProduction.lexeme.isNotEmpty) {
      buffer.write('if token_queue.peek() and token_queue.peek()');
      if (givenInformation.containsKey(firstProduction)) {
        buffer.writeln(
          '.get_token_type() == ${givenInformation[firstProduction]}:',
        );
      } else {
        buffer.writeln(
          '.get_lexeme() == ${sanitizeTerminal(firstProduction.lexeme)}:',
        );
      }
      buffer.writeln('\t\tnode.add(token_queue.remove())');
    } else {
      buffer.writeln('se:\n\t\treturn node');
    }
    // Sub productions foreach
    final tabAmount = firstSet.contains('') ? 1 : 2;
    buffer.writeln(
      _buildVerifications(
        name,
        production,
        givenInformation,
        firsts,
        tabAmount,
      ),
    );
  }

  buffer.writeln('\treturn node');
  return buffer.toString();
}