variableDeclaration method

Parser<VariableDeclarationStatementNode> variableDeclaration()
inherited

Implementation

Parser<VariableDeclarationStatementNode> variableDeclaration() => [
  // 1. var x = 1, y = 2; (var cannot be accompanied by a type)
  seq3(
    ref0(lateToken).optional(),
    ref0(varToken),
    ref0(variableDeclarator)
        .plusSeparated(ref1(token, ','))
        .map((l) => l.elements),
  ).map3(
    (lateKw, _, vars) => VariableDeclarationStatementNode(
      variables: vars,
      isLate: lateKw != null,
      isVar: true,
    ),
  ),
  // 2. final / const with explicit type: final int x = 1;
  seq4(
    ref0(lateToken).optional(),
    [ref0(finalToken), ref0(constToken)].toChoiceParser(),
    ref0(type),
    ref0(variableDeclarator)
        .plusSeparated(ref1(token, ','))
        .map((l) => l.elements),
  ).map4(
    (lateKw, modifier, type, vars) => VariableDeclarationStatementNode(
      variables: vars,
      type: type,
      isLate: lateKw != null,
      isFinal: modifier.value == 'final',
      isConst: modifier.value == 'const',
    ),
  ),
  // 3. final / const without type: final x = 1;
  seq3(
    ref0(lateToken).optional(),
    [ref0(finalToken), ref0(constToken)].toChoiceParser(),
    ref0(variableDeclarator)
        .plusSeparated(ref1(token, ','))
        .map((l) => l.elements),
  ).map3(
    (lateKw, modifier, vars) => VariableDeclarationStatementNode(
      variables: vars,
      isLate: lateKw != null,
      isFinal: modifier.value == 'final',
      isConst: modifier.value == 'const',
    ),
  ),
  // 4. With type only (no final/const/var): int x = 1;
  seq3(
    ref0(lateToken).optional(),
    ref0(type),
    ref0(variableDeclarator)
        .plusSeparated(ref1(token, ','))
        .map((l) => l.elements),
  ).map3(
    (lateKw, type, vars) => VariableDeclarationStatementNode(
      variables: vars,
      type: type,
      isLate: lateKw != null,
    ),
  ),
].toChoiceParser();