CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-pegjs

Parser generator for JavaScript that produces fast parsers with excellent error reporting

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

cli-tool.mddocs/

CLI Tool

Command-line interface for generating parser files from PEG grammar specifications with comprehensive configuration options and multiple output formats.

Capabilities

Command-Line Usage

The pegjs command provides a full-featured CLI for parser generation.

# Basic usage
pegjs [options] [input_file]

# Examples
pegjs grammar.pegjs                    # Generate grammar.js
pegjs -o parser.js grammar.pegjs      # Specify output file
pegjs --format commonjs grammar.pegjs # Generate CommonJS module

Installation:

# Global installation for CLI usage
npm install -g pegjs

# Local installation for programmatic usage
npm install pegjs

Basic Options

Core command-line options for parser generation.

# Input/Output
pegjs grammar.pegjs                   # Input from file, output to grammar.js
pegjs -o output.js input.pegjs       # Specify output file
pegjs < input.pegjs > output.js      # Use stdin/stdout
pegjs --                             # Read from stdin, write to stdout

# Output format
pegjs --format commonjs grammar.pegjs    # CommonJS module (default)
pegjs --format amd grammar.pegjs         # AMD module
pegjs --format globals grammar.pegjs     # Global variable
pegjs --format umd grammar.pegjs         # Universal Module Definition

# Help and version
pegjs --help                             # Show help information
pegjs --version                          # Show version number

Parser Configuration

Options that control parser behavior and capabilities.

# Start rules
pegjs --allowed-start-rules rule1,rule2 grammar.pegjs

# Caching and optimization  
pegjs --cache grammar.pegjs                    # Enable result caching
pegjs --optimize speed grammar.pegjs           # Optimize for speed (default)
pegjs --optimize size grammar.pegjs            # Optimize for size

# Debugging
pegjs --trace grammar.pegjs                    # Enable parser tracing

Module Configuration

Options for configuring generated module format and dependencies.

# Dependencies (for amd, commonjs, umd formats)
pegjs --dependency lodash grammar.pegjs              # Add dependency: lodash
pegjs --dependency utils:./utils grammar.pegjs      # Map variable to module
pegjs -d lodash -d utils:./utils grammar.pegjs     # Multiple dependencies

# Global variable (for globals, umd formats)
pegjs --export-var MyParser grammar.pegjs          # Set global variable name
pegjs -e MyParser grammar.pegjs                    # Short form

Advanced Options

Advanced configuration and plugin support.

# Extra options (JSON format)
pegjs --extra-options '{"customOption": true}' grammar.pegjs
pegjs --extra-options-file options.json grammar.pegjs

# Plugins
pegjs --plugin ./my-plugin.js grammar.pegjs
pegjs --plugin pegjs-plugin-name grammar.pegjs

Command Reference

Complete Option List

# Usage: pegjs [options] [--] [<input_file>]

# Start rule configuration
--allowed-start-rules <rules>    # Comma-separated list of allowed start rules
                                # Default: first rule in grammar

# Parser behavior  
--cache                         # Enable result caching
                               # Trade-off: speed vs memory usage

# Dependencies
-d, --dependency <dependency>   # Add module dependency  
                               # Format: variable or variable:module
                               # Can be specified multiple times

# Module format
-e, --export-var <variable>     # Global variable name for parser
                               # Valid for: globals, umd formats

--format <format>              # Output module format
                               # Options: amd, commonjs, globals, umd  
                               # Default: commonjs

# Optimization
-O, --optimize <goal>          # Optimization target
                               # Options: speed (default), size

# Output
-o, --output <file>            # Output file path
                               # Default: input file with .js extension

# Advanced configuration  
--extra-options <options>      # Additional options in JSON format
--extra-options-file <file>    # JSON file with additional options

# Plugins
--plugin <plugin>              # Use specified plugin  
                               # Can be specified multiple times

# Debugging
--trace                        # Enable parser tracing

# Information
-h, --help                     # Show help and exit
-v, --version                  # Show version and exit

# End of options
--                             # Treat remaining arguments as files

Input/Output Behavior

# File input/output
pegjs grammar.pegjs                    # grammar.pegjs → grammar.js
pegjs -o parser.js grammar.pegjs      # grammar.pegjs → parser.js

# Standard input/output  
pegjs < grammar.pegjs > parser.js     # stdin → stdout
echo 'start = "hello"' | pegjs        # pipe input
pegjs -                               # explicit stdin → stdout

# No input file specified
pegjs                                 # stdin → stdout
pegjs -o parser.js                    # stdin → parser.js

Usage Examples

Basic Parser Generation

# Simple grammar file to parser
echo 'start = "hello" "world"' > hello.pegjs
pegjs hello.pegjs
# Generates hello.js with CommonJS parser

# Test the generated parser
node -e "
const parser = require('./hello.js');
console.log(parser.parse('helloworld'));
"

Advanced Configuration

# Generate optimized browser parser
pegjs \
  --format globals \
  --export-var Calculator \
  --optimize size \
  --cache \
  -o calculator.js \
  calculator.pegjs

# Generate Node.js module with dependencies
pegjs \
  --format commonjs \
  --dependency lodash \
  --dependency utils:./my-utils \
  --optimize speed \
  --allowed-start-rules expression,statement \
  -o language-parser.js \
  language.pegjs

JSON Configuration

Create options.json:

{
  "allowedStartRules": ["program", "expression"],
  "cache": true,
  "optimize": "speed",
  "dependencies": {
    "lodash": "lodash",
    "utils": "./utilities"
  }
}

Use with CLI:

pegjs --extra-options-file options.json --format commonjs grammar.pegjs

Plugin Usage

# Use built-in or installed plugin
pegjs --plugin pegjs-otherlib-parser grammar.pegjs

# Use local plugin file
pegjs --plugin ./plugins/my-plugin.js grammar.pegjs

# Multiple plugins
pegjs \
  --plugin ./plugin1.js \
  --plugin pegjs-plugin-name \
  --plugin ./plugin2.js \
  grammar.pegjs

Output Formats

CommonJS (Default)

pegjs --format commonjs grammar.pegjs
# or just:
pegjs grammar.pegjs

Generated output:

"use strict";
// ... parser code ...
module.exports = {
  SyntaxError: peg$SyntaxError,
  parse: peg$parse
};

AMD Module

pegjs --format amd grammar.pegjs

Generated output:

define(function() {
  "use strict";
  // ... parser code ...
  return {
    SyntaxError: peg$SyntaxError,
    parse: peg$parse
  };
});

Global Variable

pegjs --format globals --export-var MyParser grammar.pegjs

Generated output:

(function(root) {
  "use strict";
  // ... parser code ...
  root.MyParser = {
    SyntaxError: peg$SyntaxError,
    parse: peg$parse
  };
})(this);

Universal Module Definition

pegjs --format umd --export-var MyParser grammar.pegjs

Generated output supports AMD, CommonJS, and global formats.

Bare Format

pegjs --format bare grammar.pegjs

Generated output is plain JavaScript without module wrapper.

Error Handling

CLI Error Messages

The CLI provides detailed error reporting for various failure scenarios:

# Grammar syntax errors
pegjs invalid.pegjs
# Output: Line 2, Column 5: Expected rule name

# Grammar semantic errors  
pegjs grammar-with-undefined-rules.pegjs
# Output: Rule "undefined_rule" is not defined

# File system errors
pegjs nonexistent.pegjs
# Output: Can't read from file "nonexistent.pegjs"

pegjs -o /readonly/output.js grammar.pegjs  
# Output: Can't write to file "/readonly/output.js"

# Invalid options
pegjs --format invalid grammar.pegjs
# Output: Module format must be one of "amd", "commonjs", "globals", and "umd"

pegjs --optimize invalid grammar.pegjs
# Output: Optimization goal must be either "speed" or "size"

Exit Codes

# Success
pegjs grammar.pegjs
echo $?  # 0

# Error (syntax, semantic, file system, etc.)
pegjs invalid.pegjs
echo $?  # 1

Error Output Format

Location information for grammar errors:

Line:Column: Error message
2:15: Expected "}" but found end of input

Integration Examples

Build System Integration

Makefile:

# Generate all parsers
parsers: json.js css.js javascript.js

%.js: %.pegjs
	pegjs --format commonjs -o $@ $<

clean:
	rm -f *.js

.PHONY: parsers clean

npm scripts:

{
  "scripts": {
    "build:parsers": "pegjs --format commonjs -o lib/parser.js src/grammar.pegjs",
    "build": "npm run build:parsers && webpack",
    "watch:grammar": "nodemon --watch src/grammar.pegjs --exec 'npm run build:parsers'"
  }
}

Gulp task:

const gulp = require('gulp');
const { spawn } = require('child_process');

gulp.task('grammar', () => {
  return spawn('pegjs', [
    '--format', 'commonjs',
    '--optimize', 'speed', 
    '--cache',
    '-o', 'lib/parser.js',
    'src/grammar.pegjs'
  ], { stdio: 'inherit' });
});

Install with Tessl CLI

npx tessl i tessl/npm-pegjs

docs

cli-tool.md

compiler-system.md

grammar-parsing.md

index.md

parser-generation.md

utility-modules.md

tile.json