// SPDX-FileCopyrightText: 2022 Johannes Loher
//
// SPDX-License-Identifier: MIT

import { literals, safeOperators } from "./grammar";
import { Lexer } from "./lexer";

export class Validator {
  constructor(private readonly predicate: (identifier: string) => boolean = Validator.defaultPredicate) {}

  static readonly defaultPredicate = (identifier: string) => [...literals, ...safeOperators].includes(identifier);

  public validate(input: string): void {
    const lexer = new Lexer(input);
    for (const token of lexer) {
      if (token.type === "iden" && !this.predicate(token.symbol)) {
        throw new ValidationError(token.symbol);
      }
      if (token.type === "invalid") {
        throw new SyntaxError(`Invalid or unexpected token (${token.pos})`);
      }
    }
  }
}

class ValidationError extends Error {
  constructor(identifier: string) {
    super(`'${identifier}' is not an allowed identifier.`);
  }
}
