# All files / src/parser if-then-else.js

100% Statements 23/23
50% Branches 2/4
100% Functions 2/2
100% Lines 23/23

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    28x
    28x
    28x

    28x
    47x
    47x
    47x
    47x

    47x

    47x

    47x
    47x
    47x
    47x

    47x
    47x

    37x
    37x
    37x
    37x
    37x

    37x

    47x

     // @flow
    import Syntax from "../Syntax";
    import statement from "./statement";
    import expression from "./expression";
    import type Context from "./context";
    import type { NodeType } from "../flow/types";

    const condition = (ctx: Context): NodeType => {
      ctx.expect(["("]);
      const expr = expression(ctx);
      ctx.expect([")"]);
      return expr;
    };

    export default function parseIfStatement(ctx: Context): NodeType {
      const node: NodeType = {
        ...ctx.startNode(ctx.token),
      };

      ctx.eat(["if"]);
      // First operand is the expression
      const params: NodeType[] = [condition(ctx)];
      const statementNode = statement(ctx);
      Eif (statementNode) {
        params.push(statementNode);
      }

      ctx.eat([";"]);
      while (ctx.eat(["else"])) {
        // maybe another if statement
        const elseNode = ctx.makeNode(null, Syntax.Else);
        const elseParams = [];
        const stmt = statement(ctx);
        Eif (stmt) {
          elseParams.push(stmt);
        }
        params.push({ ...elseNode, params: elseParams });
      }

      return ctx.endNode(
        {
          ...node,
          params,
        },
        Syntax.IfThenElse
      );
    }