Home

Awesome

PHP Parser written in Go

<img src="./parser.jpg" alt="PHP Parser written in Go" width="980"/>

GoDoc Build Status Go Report Card Maintainability Test Coverage

This project uses goyacc and ragel tools to create PHP parser. It parses source code into AST. It can be used to write static analysis, refactoring, metrics, code style formatting tools.

Try it online: demo

Features:

Who Uses

VKCOM/noverify - NoVerify is a pretty fast linter for PHP

quasilyte/phpgrep - phpgrep is a tool for syntax-aware PHP code search

Usage example

package main

import (
	"log"
	"os"

	"github.com/z7zmey/php-parser/pkg/cfg"
	"github.com/z7zmey/php-parser/pkg/errors"
	"github.com/z7zmey/php-parser/pkg/parser"
	"github.com/z7zmey/php-parser/pkg/version"
	"github.com/z7zmey/php-parser/pkg/visitor/dumper"
)

func main() {
	src := []byte(`<? echo "Hello world";`)

	// Error handler

	var parserErrors []*errors.Error
	errorHandler := func(e *errors.Error) {
		parserErrors = append(parserErrors, e)
	}

	// Parse

	rootNode, err := parser.Parse(src, cfg.Config{
		Version:          &version.Version{Major: 5, Minor: 6},
		ErrorHandlerFunc: errorHandler,
	})

	if err != nil {
		log.Fatal("Error:" + err.Error())
	}

	// Dump

	goDumper := dumper.NewDumper(os.Stdout).
		WithTokens().
		WithPositions()

	rootNode.Accept(goDumper)
}

Roadmap

Install

go get github.com/z7zmey/php-parser/cmd/php-parser

CLI

php-parser [flags] <path> ...
flagtypedescription
-pboolprint filepath
-eboolprint errors
-dbooldump in golang format
-rboolresolve names
-profstringstart profiler: [cpu, mem, trace]
-phpverstringphp version (default: 7.4)

Namespace resolver

Namespace resolver is a visitor that resolves nodes fully qualified name and saves into map[node.Node]string structure