0.2.0 • Published 1 month ago

nanolex v0.2.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 month ago

nanolex

@TODO readme

Very experimental parser building library

Usage

npm i nanolex
import { createToken, framework, getComposedTokens } from "nanolex";

// Define tokens
const Whitespace = createToken(/[ \t\n\r]+/, "WhiteSpace", /* skip */ true);
const LParen = createToken("(");
const RParen = createToken(")");
const Comma = createToken(",");
const Integer = createToken(/-?\d+/, "Integer");
const Identifier = createToken(/\w+/, "Identifier");

// List of tokenizable tokens
const tokens = getComposedTokens([
  Whitespace,
  LParen,
  RParen,
  Comma,
  Integer,
]);

// Define the usage of your parser
export function parser(value: string) {
  // Initiate grammar
  const {
    consume,
    consumeEOF,
    zeroOrOne,
    zeroOrMany,
    zeroOrManySep,
    and,
    or,
    throwIfError,
  } = framework(value, tokens);

  // Write parser grammar patterns here

  function FUNCTION() {
    return and([
      consume(Identifier),
      consume(LParen),
      PARAMS,
      consume(RParen),
    ], transform)();

    function transform([name, _, params]) {
      return {
        type: "function",
        name,
        params,
      };
    }
  }

  function PARAMS() {
    return zeroOrManySep(
      VALUE,
      consume(Comma),
    )();
  }

  function VALUE() {
    return or([
      consume(Integer, Number),
      FUNCTION,
    ])();
  }

  // Run the grammar
  const [output] = throwIfError(and([FUNCTION, consumeEOF()]));

  return output;
}
import { parser } from "./parser.ts";

parser("SUM(1, SUM(2, 3))");
/*
{
  "type": "function",
  "name": "SUM",
  "params": [
    1,
    {
      "type": "function",
      "name": "SUM",
      "params": [2, 3]
    }
  ]
}
*/
0.2.0

1 month ago

0.1.3

1 month ago

0.1.2

2 months ago

0.1.1

2 months ago

0.1.0

2 months ago