# All files / src/validation index.js

100% Statements 80/80
98.08% Branches 51/52
100% Functions 18/18
100% Lines 80/80

    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
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278

    21x
    21x
    21x
    21x
    21x

    21x

    79x
    79x
    1x

    78x
    78x

    78x

    1x
    1x

    126x
    126x
    126x
    126x
    1x

    11x

    27x
    27x
    1x
    1x

    21x
    21x
    16x
    16x
    1x

    16x
    1x

    141x
    141x

    147x
    147x

    1x
    1x

    147x
    46x

    46x
    1x

    35x
    35x
    35x
    70x

    35x
    1x

    35x
    35x
    2x

    58x
    58x
    58x
    2x
    2x

    154x
    154x
    2x

    152x
    152x
    152x
    152x
    152x
    1x

    151x

    152x
    3x

    23x
    1x

    1x

    3x
    3x

    3x
    1x
    1x

    78x
    78x
    10x
    17x

    10x

     // @flow
    // AST Validator
    import Syntax, { statements as ALL_POSSIBLE_STATEMENTS } from "../Syntax";
    import walkNode from "../utils/walk-node";
    import error from "../utils/generate-error";
    import { isBuiltinType } from "../generator/utils";
    import {
      GLOBAL_INDEX,
      TYPE_CONST,
      ALIAS,
      AST_METADATA,
    } from "../semantics/metadata";
    import type { NodeType } from "../flow/types";

    const GLOBAL_LABEL = "global";

    // We walk the the entire tree and perform syntax validation before we continue
    // onto the generator. This may throw sometimes
    export default function validate(
      ast: NodeType,
      {
        filename,
      }: {
        filename: string,
      }
    ) {
      const metadata = ast.meta[AST_METADATA];
      if (metadata == null) {
        throw new Error("Missing AST metadata!");
      }
      const { types, functions } = metadata;
      const problems = [];

      walkNode({
        [Syntax.Pair]: pair => {
          const [start, end] = pair.range;
          problems.push(
            error(
              `Unexpected expression ${pair.Type}`,
              "",
              { start, end },
              filename,
              GLOBAL_LABEL
            )
          );
        },
        [Syntax.Export]: _export => {
          const target = _export.params[0];
          const [start, end] = target.range;
          const globalIndex = target.meta[GLOBAL_INDEX];
          if (globalIndex != null && !target.params.length) {
            problems.push(
              error(
                "Global exports must have a value",
                "",
                { start, end },
                filename,
                GLOBAL_LABEL
              )
            );
          }
        },
        [Syntax.Import]: (importNode, _) => {
          walkNode({
            [Syntax.Pair]: (pair, __) => {
              const type = pair.params[1];
              if (!isBuiltinType(type.value) && types[type.value] == null) {
                const [start, end] = type.range;
                problems.push(
                  error(
                    `Undefined Type ${type.value}`,
                    `Invalid Import. ${type.value} type does not exist`,
                    { start, end },
                    filename,
                    GLOBAL_LABEL
                  )
                );
              }
            },
          })(importNode);
        },
        // All of the validators below need to be implemented
        [Syntax.Struct]: (_, __) => {},
        [Syntax.ImmutableDeclaration]: (_, __) => {},
        [Syntax.Declaration]: (decl, _validator) => {
          const [initializer] = decl.params;
          if (decl.meta[TYPE_CONST] != null) {
            const [start, end] = decl.range;
            if (initializer != null && initializer.Type !== Syntax.Constant) {
              problems.push(
                error(
                  "Global Constants must be initialized with a Number literal.",
                  "WebAssembly does not allow for non number literal constant initializers.",
                  { start, end },
                  filename,
                  GLOBAL_LABEL
                )
              );
            }

            if (initializer == null) {
              problems.push(
                error(
                  "Constant declaration without an initializer.",
                  "Global constants must be initialized with a Number literal.",
                  { start, end },
                  filename,
                  GLOBAL_LABEL
                )
              );
            }
          }
        },
        [Syntax.FunctionDeclaration]: (func, __) => {
          const functionName = `${func.value}()`;
          walkNode({
            [Syntax.Declaration]: (node, _validator) => {
              const [initializer] = node.params;
              if (
                initializer != null &&
                ALL_POSSIBLE_STATEMENTS[initializer.Type] != null
              ) {
                const [start, end] = node.range;
                problems.push(
                  error(
                    `Unexpected statement ${initializer.Type}`,
                    "Attempting to assign a statement to a variable. Did you miss a semicolon(;)?",
                    { start, end },
                    filename,
                    functionName
                  )
                );
              }
              if (node.meta[TYPE_CONST] != null) {
                const [start, end] = node.range;

                if (initializer == null) {
                  problems.push(
                    error(
                      "Constant declaration without an initializer.",
                      "Local Constants must be initialized with an expression.",
                      { start, end },
                      filename,
                      GLOBAL_LABEL
                    )
                  );
                }
              }
            },
            [Syntax.Assignment]: node => {
              const [identifier] = node.params;
              const [start, end] = node.range;
              const statement = node.params.find(
                param => ALL_POSSIBLE_STATEMENTS[param.Type] != null
              );
              if (statement != null) {
                problems.push(
                  error(
                    "Unexpected statement in assignment",
                    "Statments cannot be used in assignment expressions. Did you miss a semicolon?",
                    { start: statement.range[0], end: statement.range[1] },
                    filename,
                    functionName
                  )
                );
              }

              const isConst = identifier.meta[TYPE_CONST];
              if (isConst != null) {
                problems.push(
                  error(
                    `Cannot reassign a const variable ${identifier.value}`,
                    "const variables cannot be reassigned, use let instead.",
                    { start, end },
                    filename,
                    functionName
                  )
                );
              }
            },
            [Syntax.ArraySubscript]: (node, _validator) => {
              const [identifier, offset] = node.params;
              const [start, end] = node.range;
              if (offset.value == null) {
                const alias = offset.meta[ALIAS];
                problems.push(
                  error(
                    "Cannot generate memory offset",
                    `Undefined key ${
                      alias != null ? alias : offset.value
                    } for type ${String(identifier.type)}`,
                    { start, end },
                    filename,
                    functionName
                  )
                );
              }
            },
            [Syntax.ReturnStatement]: (node, validator) => {
              node.params.map(validator);
              if (func.type == null) {
                return;
              }
              const [expression] = node.params;
              const [start] = node.range;
              const end = expression != null ? expression.range[1] : node.range[1];
              const type = (() => {
                if (expression == null) {
                  return null;
                }
                return [">", "<", ">=", "<=", "==", "!="].includes(expression.value)
                  ? "i32"
                  : expression.type;
              })();

              if (type !== func.type) {
                problems.push(
                  error(
                    "Missing return value",
                    "Inconsistent return value. Expected " +
                      func.type +
                      " received " +
                      String(type),
                    { start, end },
                    filename,
                    functionName
                  )
                );
              }
            },
            [Syntax.FunctionCall]: (node, _validator) => {
              if (functions[node.value] == null) {
                const [start, end] = node.range;

                problems.push(
                  error(
                    "Undefined function reference",
                    `${node.value} is not defined.`,
                    { start, end },
                    filename,
                    functionName
                  )
                );
              }
            },
            [Syntax.IndirectFunctionCall]: (node, _validator) => {
              const identifier = node.params[node.params.length - 1];
              const type = types[identifier.type];

              if (!isBuiltinType(identifier.type) && type == null) {
                const [start, end] = node.range;
                problems.push(
                  error(
                    "Cannot make an indirect call without a valid function type",
                    `${identifier.value} has type ${String(
                      identifier.type
                    )} which is not defined. Inidrect calls must have pre-defined types.`,
                    { start, end },
                    filename,
                    functionName
                  )
                );
              }
            },
          })(func);
        },
      })(ast);

      const problemCount = problems.length;
      if (problemCount > 0) {
        const errorString = problems.reduce((acc, value) => {
          return acc + "\n" + `${value}\n`;
        }, `Cannot generate WebAssembly for ${filename}. ${problemCount} problems.\n`);

        throw new Error(errorString);
      }
    }