tuil
ReferencePackages@mwillbanks/tuil-codeAPI

RegexCodeParser

class exported by @mwillbanks/tuil-code.

View rawEdit

class

Public class exported by @mwillbanks/tuil-code.

export class RegexCodeParser implements CodeParser {
  readonly id = "tuil-regex";
  readonly languages = ["*"];
  #version: number;

  constructor() {
    this.#version = 0;
  }

  parse(
    source: string,
    options: { readonly signal: AbortSignal },
  ): CodeParseResult {
    if (options.signal.aborted) throw options.signal.reason;
    const spans: CodeSpan[] = [];
    const patterns: readonly [string, RegExp][] = [
      ["comment", /\/\/.*$|\/\*[\s\S]*?\*\/|#.*$/gm],
      ["string", /(["'`])(?:\\.|(?!\1)[^\\])*\1/g],
      [
        "keyword",
        /\b(const|let|var|function|class|interface|type|return|if|else|for|while|import|export|from|async|await|throw|try|catch|new)\b/g,
      ],
      ["number", /\b\d+(?:\.\d+)?\b/g],
    ];
    for (const [kind, pattern] of patterns) {
      for (const match of source.matchAll(pattern)) {
        spans.push({
          start: match.index,
          end: match.index + match[0].length,
          kind,
        });
      }
    }
    const folds: {
      startLine: number;
      endLine: number;
    }[] = [];
    const stack: number[] = [];
    source.split("\n").forEach((line, index) => {
      for (const character of line) {
        if (character === "{") stack.push(index);
        if (character === "}") {
          const startLine = stack.pop();
          if (startLine !== undefined && index > startLine) {
            folds.push({ startLine, endLine: index });
          }
        }
      }
    });
    return Object.freeze({
      language: "text",
      version: ++this.#version,
      spans: Object.freeze(
        spans.sort((left, right) => left.start - right.start),
      ),
      folds: Object.freeze(folds),
      diagnostics: Object.freeze(
        stack.map((line) => ({
          start: source.split("\n").slice(0, line).join("\n").length,
          end: source.length,
          kind: "syntax",
          severity: "warning" as const,
          message: "Unclosed block",
        })),
      ),
    });
  }
}

Members

MemberTypeRequiredDescriptionRelated types
id"tuil-regex"YesThe id member uses the "tuil-regex" contract.
languagesstring[]YesThe languages member uses the string[] contract.
#versionnumberYesThe #version member uses the number contract.
__constructoranyYesThe __constructor member uses the any contract.
parse(source: string, options: { readonly signal: AbortSignal; }) => CodeParseResultYesThe parse member uses the (source: string, options: { readonly signal: AbortSignal; }) => CodeParseResult contract.CodeParseResult

Parameters

This declaration has no public members.

Returns

This declaration does not return a value.

Throws

No thrown errors are documented for this declaration.

Source

View the secondary source reference

Package

@mwillbanks/tuil-code

On this page