removeComments method

String removeComments(
  1. String codeComments
)

Removes comments (both single-line and multi-line) from the given codeComments.

Implementation

String removeComments(String codeComments) {
  final buffer = StringBuffer();
  bool inSingleQuote = false;
  bool inDoubleQuote = false;
  bool inMultiLineStringSingle = false;
  bool inMultiLineStringDouble = false;
  bool inSingleLineComment = false;
  bool inMultiLineComment = false;

  for (int i = 0; i < codeComments.length; i++) {
    final currentChar = codeComments[i];

    if (!inSingleLineComment && !inMultiLineComment) {
      if (currentChar == "'" && !inDoubleQuote && !inMultiLineStringDouble) {
        if (i + 2 < codeComments.length &&
            codeComments.substring(i, i + 3) == "'''") {
          inMultiLineStringSingle = !inMultiLineStringSingle;
          buffer.write("'''");
          i += 2;
          continue;
        } else if (!inMultiLineStringSingle) {
          inSingleQuote = !inSingleQuote;
          buffer.write(currentChar);
          continue;
        }
      }

      if (currentChar == '"' && !inSingleQuote && !inMultiLineStringSingle) {
        if (i + 2 < codeComments.length &&
            codeComments.substring(i, i + 3) == '"""') {
          inMultiLineStringDouble = !inMultiLineStringDouble;
          buffer.write('"""');
          i += 2;
          continue;
        } else if (!inMultiLineStringDouble) {
          inDoubleQuote = !inDoubleQuote;
          buffer.write(currentChar);
          continue;
        }
      }
    }

    if (!inSingleQuote &&
        !inDoubleQuote &&
        !inMultiLineStringSingle &&
        !inMultiLineStringDouble) {
      if (codeComments.startsWith('//', i)) {
        inSingleLineComment = true;
        i++;
        continue;
      }

      if (codeComments.startsWith('/*', i)) {
        inMultiLineComment = true;
        i++;
        continue;
      }
    }

    if (inSingleLineComment && currentChar == '\n') {
      inSingleLineComment = false;
    }

    if (inMultiLineComment && codeComments.startsWith('*/', i)) {
      inMultiLineComment = false;
      i++;
      continue;
    }

    if (!inSingleLineComment && !inMultiLineComment) {
      buffer.write(currentChar);
    }
  }

  return buffer.toString();
}