tablePairExpr method

KeyValStmt tablePairExpr()

Implementation

KeyValStmt tablePairExpr() {
  /*
    Key-value statement pairs used in table declarations
    can be one of three:
      - Just a value (keyless).
      - An __expression__ wrapped in brackets.
      - A symbol (a string without quotes).
  */

  final Token first = peek();
  bool usedBracketNotation = false;
  MathExpr? expr;
  int offset = 1;
  if (first.type == TokenType.kLBracket) {
    advance();
    expr = math();
    consume(TokenType.kRBracket, 'Expecting closing bracket for table key.');
    usedBracketNotation = true;
    offset = 0;
  } else if (first.type == TokenType.kLCurly) {
    return KeyValStmt.autokey(math());
  }

  if (peek(offset: offset).type == TokenType.kAssign) {
    expr ??= rawExpr();

    // Literal keys cannot be used unless inside bracket notation
    final bool isLiteral = switch (expr) {
      final BooleanLiteral _ => true,
      final StringLiteral _ => true,
      final NumberLiteral _ => true,
      _ => false,
    };

    if (!usedBracketNotation && isLiteral) {
      throw '${first.pos} Literal keys cannot be used unless inside bracket notation.';
    }
    advance();

    return KeyValStmt(key: expr, value: math());
  }

  return KeyValStmt.autokey(expr ?? math());
}