# All files / src/parser while-loop.js

100% Statements 22/22
83.33% Branches 5/6
100% Functions 1/1
100% Lines 22/22

    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
    49
    50
    51
    52
    53
    54
    28x

    28x
    28x

    28x

    28x
    2x
    2x
    2x

    2x
    2x

    2x
    2x

    2x

    2x
    2x

    2x
    2x
    6x
    6x
    3x

    2x

    2x

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

    // Truth tables are tricky.
    const reverse = {
      ">": "<=",
      "<": ">=",
      ">=": "<",
      "<=": ">",
      "==": "!=",
      "!=": "==",
    };

    const whileLoop = (ctx: Context): NodeType => {
      const node = ctx.startNode();
      ctx.eat(["while"]);
      ctx.expect(["("]);

      const initializer = ctx.makeNode({}, Syntax.Noop);
      const condition = expression(ctx);
      // This could also be instead patched with a Eqz instruction
      Eif (reverse[condition.value]) {
        condition.value = reverse[condition.value];
      }
      const body = [];

      ctx.expect([")"]);
      ctx.expect(["{"]);

      let stmt = null;
      while (ctx.token && ctx.token.value !== "}") {
        stmt = statement(ctx);
        if (stmt) {
          body.push(stmt);
        }
      }

      ctx.expect(["}"]);

      return ctx.endNode(
        {
          ...node,
          params: [initializer, condition, ...body],
        },
        Syntax.Loop
      );
    };

    export default whileLoop;