autoClose function

({String text, bool wasIncomplete}) autoClose(
  1. String input
)

lang-core autoClose: closes unclosed strings and brackets of a partial program so it parses.

Implementation

({String text, bool wasIncomplete}) autoClose(String input) {
  final stack = <String>[];
  String? inStr;
  var esc = false;
  for (var i = 0; i < input.length; i++) {
    final c = input[i];
    if (esc) {
      esc = false;
      continue;
    }
    if (c == r'\' && inStr != null) {
      esc = true;
      continue;
    }
    if (inStr != null) {
      if (c == inStr) inStr = null;
      continue;
    }
    if (c == '"' || c == "'") {
      inStr = c;
      continue;
    }
    if (c == '(' || c == '[' || c == '{') {
      stack.add(c);
    } else if (stack.isNotEmpty &&
        ((c == ')' && stack.last == '(') ||
            (c == ']' && stack.last == '[') ||
            (c == '}' && stack.last == '{'))) {
      stack.removeLast();
    }
  }
  if (inStr == null && stack.isEmpty) {
    return (text: input, wasIncomplete: false);
  }
  final out = StringBuffer(input);
  if (inStr != null) {
    if (esc) out.write(r'\');
    out.write(inStr);
  }
  for (final open in stack.reversed) {
    out.write(switch (open) {
      '(' => ')',
      '[' => ']',
      _ => '}',
    });
  }
  return (text: out.toString(), wasIncomplete: true);
}