jsep

repository·master·Indexed 21 days ago

https://github.com/ericsmekens/jsep

A tiny, lightweight JavaScript expression parser (v1.4.0) that produces an AST similar to Esprima. It is designed to be extensible via custom grammar configurations and a variety of official plugins, including support for arrow functions, assignment, async/await, comments, new expressions, advanced number formats, object expressions, regular expressions, spread syntax, template literals, and ternary operators.

Tokens
12.1K
Snippets
61
Records
71
Agent score
76%

What's inside jsep

  1. How to write a custom jsep plugin

    master

    A plugin is an object containing a name and an init function. The init function receives the jsep instance and is used to register hooks.

    Plugin Structure

    const plugin = {
      name: 'my-plugin',
      init(jsep) {
        // Use jsep methods or hooks here
      },
    };

    Using Hooks

    Hooks are used to modify parsing behavior. They are called with a single argument (often an object containing the node or env) and return void. The this context of a hook provides access to internal parsing methods like gobbleSpaces, gobbleExpression, etc.

    Available Hook Types

    • before-all: Called before starting all expression parsing.
    • after-all: Called after parsing is complete. Can read/write arg.node.
    • gobble-expression: Called before attempting to parse an expression. Can set arg.node.
    • after-expression: Called after parsing an expression. Can read/write arg.node.
    • gobble-token: Called before attempting to parse a token. Can set arg.node.
    • after-token: Called after parsing a token. Can read/write arg.node.
    • gobble-spaces: Called when gobbling whitespace.
    const plugin = {
      name: 'the plugin',
      init(jsep) {
        jsep.addIdentifierChar('@');
        jsep.hooks.add('gobble-expression', function myPlugin(env) {
          if (this.char === '@') {
            this.index += 1;
            env.node = {
              type: 'MyCustom@Detector',
            };
          }
        });
      },
    };