scanExpressions function

({String? error, List<Expression> expressions}) scanExpressions(
  1. String text
)

The expressions in text, and the first syntax problem (an unclosed ${, an empty ${}), as the SDK scans them: quotes and nested braces inside an expression are skipped; \${ is literal.

Implementation

({List<Expression> expressions, String? error}) scanExpressions(String text) {
  final out = <Expression>[];
  var from = 0;
  while (true) {
    final start = text.indexOf(r'${', from);
    if (start < 0) return (expressions: out, error: null);
    if (start > 0 && text[start - 1] == r'\') {
      from = start + 2;
      continue;
    }
    var depth = 1;
    var pos = start + 2;
    String? quote;
    while (pos < text.length && depth > 0) {
      final c = text[pos];
      if (quote != null) {
        if (c == r'\') {
          pos++;
        } else if (c == quote) {
          quote = null;
        }
      } else if (c == "'" || c == '"') {
        quote = c;
      } else if (c == '{') {
        depth++;
      } else if (c == '}') {
        depth--;
      }
      pos++;
    }
    if (depth > 0) {
      final shown = text.length - start > 40 ? '${text.substring(start, start + 40)}...' : text.substring(start);
      return (
        expressions: out,
        error: '"$shown" is not closed: write \${name} or \${= formula}, with its quotes closed and braces balanced.',
      );
    }
    final inner = text.substring(start + 2, pos - 1);
    final trimmed = inner.trim();
    if (trimmed.isEmpty || trimmed == '=') {
      return (expressions: out, error: 'An empty expression "${text.substring(start, pos)}".');
    }
    final formula = trimmed.startsWith('=');
    out.add((source: formula ? trimmed.substring(1).trim() : trimmed, formula: formula, start: start));
    from = pos;
  }
}