lexer

Rule-based tokenizer and lexer builder with line/column tracking and syntax errors.

v1.0.0Tooling & CLIbundledimport "lexer";
Overview Installation Documentation Examples

Overview

Generic rule-based tokenizer and lexer builder for HolyPHP with line/column tracking and clear syntax errors.

bundled — works offline tokenizer parser compiler

Quick start

import "lexer";

$lex = lexer_create()
    ->addSkipWhitespace()
    ->addLineComment("//")
    ->addKeyword("LET", "let")
    ->addLiteral("EQ", "==")
    ->addLiteral("ASSIGN", "=")
    ->addLiteral("PLUS", "+")
    ->addLiteral("SEMI", ";")
    ->addString("STRING")
    ->addNumber("NUMBER", true, true)
    ->addIdentifier("IDENT");

$tokens = $lex->tokenize("let x = 42.5 + 1e3;");
println(lexer_format_tokens($tokens));

Installation

In a project

Inside a project (a folder with hphp.yaml, see Projects & packages):

hphp install lexer

This adds the library to hphp.yaml, installs it into .hphp/packages/lexer/ and pins the exact version in hphp.lock:

require:
  lexer: "^1.0"

Use it

import "lexer";

lexer is bundled with the compiler, so import "lexer"; also works in a single file without installing anything, and hphp install works offline.

Outside a project

hphp install lexer          # for your user, shared by all scripts
hphp create myapp                 # or start a project, then: hphp install lexer
Packagelexer
Version1.0.0 (follows the compiler)
Entry filelexer.hphp
Sourcepackages/lib/lexer ↗

Documentation

API Reference

Token

Represents a single lexical token.

Lexer

Fluent rule-based tokenizer. Rules are evaluated in the order they are added (first match wins), so place longer literals (e.g. ==) before shorter prefixes (e.g. =) and keywords before identifiers.

Helper Functions

Error Handling

All errors throw Exception with a lexer: prefix and exact line:column location where applicable:

Examples

01Quick start

Bundled with the compiler — import "lexer"; works offline in any file, or add it to a project with hphp install lexer.

import "lexer";

$lex = lexer_create()
    ->addSkipWhitespace()
    ->addLineComment("//")
    ->addKeyword("LET", "let")
    ->addLiteral("EQ", "==")
    ->addLiteral("ASSIGN", "=")
    ->addLiteral("PLUS", "+")
    ->addLiteral("SEMI", ";")
    ->addString("STRING")
    ->addNumber("NUMBER", true, true)
    ->addIdentifier("IDENT");

$tokens = $lex->tokenize("let x = 42.5 + 1e3;");
println(lexer_format_tokens($tokens));
Try it
hphp install lexer
hphp run main.hphp

Covered by the official test suite in tests/positive/lib_lexer.hphp.