シェブロテインを使ったパーザー

Stardog で使っているパーザーのインターフェイス https://github.com/stardog-union/millan/blob/master/src/helpers/chevrotain/types.ts

import {
  IToken,
  IRecognitionException,
  CstNode,
  TokenType,
  IRecognizerContext,
} from 'chevrotain';

export interface IStardogParser {
  tokenize: (document: string) => IToken[];
  parse: (
    document: string
  ) => { errors: IRecognitionException[]; cst: CstNode };
}

tokenizeとparseという動詞〈バーブ〉をサポートする。どちらも引数に document : string を持つ。結果の返し方は違う。

/**
 * A Chevrotain Parser runtime exception.
 */
export interface IRecognitionException {
  name: string
  message: string
  /**
   * The token which caused the parser error.
   */
  token: IToken
  /**
   * Additional tokens which have been re-synced in error recovery due to the original error.
   * This information can be used the calculate the whole text area which has been skipped due to an error.
   * For example for displaying with a red underline in a text editor.
   */
  resyncedTokens: IToken[]
  context: IRecognizerContext
}
export interface IRecognizerContext {
  /**
   * A copy of the parser's rule stack at the "time" the RecognitionException occurred.
   * This can be used to help debug parsing errors (How did we get here?).
   */
  ruleStack: string[]
  /**
   * A copy of the parser's rule occurrence stack at the "time" the RecognitionException occurred.
   * This can be used to help debug parsing errors (How did we get here?).
   */
  ruleOccurrenceStack: number[]
}

ちかみに失敗の返し方は:

  1. 例外
  2. ユニオン型とエラー値
  3. ユニオン・レコード型とエラーフィールド
  4. コールバック(エラーファースト・コンベンション)
  5. プロミス