stStripDartComments function

String stStripDartComments(
  1. String source
)

Implementation

String stStripDartComments(String source) {
  final out = StringBuffer();
  var i = 0;
  var lineComment = false;
  var blockComment = false;
  var quote = 0; // 0 none, 1 ', 2 "

  while (i < source.length) {
    final c = source[i];
    final next = i + 1 < source.length ? source[i + 1] : '';

    if (lineComment) {
      if (c == '\n') {
        lineComment = false;
        out.write(c);
      }
      i++;
      continue;
    }
    if (blockComment) {
      if (c == '*' && next == '/') {
        blockComment = false;
        i += 2;
        continue;
      }
      i++;
      continue;
    }
    if (quote != 0) {
      out.write(c);
      if (c == r'\' && next.isNotEmpty) {
        out.write(next);
        i += 2;
        continue;
      }
      if ((quote == 1 && c == "'") || (quote == 2 && c == '"')) {
        quote = 0;
      }
      i++;
      continue;
    }
    if (c == '/' && next == '/') {
      lineComment = true;
      i += 2;
      continue;
    }
    if (c == '/' && next == '*') {
      blockComment = true;
      i += 2;
      continue;
    }
    if (c == "'") {
      quote = 1;
      out.write(c);
      i++;
      continue;
    }
    if (c == '"') {
      quote = 2;
      out.write(c);
      i++;
      continue;
    }
    out.write(c);
    i++;
  }
  return out.toString();
}