php-parser
A Parser for PHP written in Go
About php-parser
PHP Parser written in Go
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:
- Fully support PHP 5 and PHP 7 syntax
- Abstract syntax tree (AST) representation
- Traversing AST
- Resolving namespaced names
- Parsing syntax-invalid PHP files
- Saving and printing free-floating comments and whitespaces
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
- Control Flow Graph (CFG)
- PHP8
Install
go get github.com/z7zmey/php-parser/cmd/php-parser
CLI
php-parser [flags] <path> ...
| flag | type | description |
|---|---|---|
| -p | bool | print filepath |
| -e | bool | print errors |
| -d | bool | dump in golang format |
| -r | bool | resolve names |
| -prof | string | start profiler: [cpu, mem, trace] |
| -phpver | string | php 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
- For
Class,Interface,Trait,Function,Constantnodes it saves name with current namespace. - For
Name,Relative,FullyQualifiednodes it resolvesusealiases and saves a fully qualified name.
Frequently Asked Questions
What is php-parser?
php-parser is a Code Analysis library for the Go programming language. A Parser for PHP written in Go
How do I install php-parser?
Install php-parser with the Go module system using `go get z7zmey/php-parser`. Check the repository for the current installation instructions.
What category does php-parser belong to?
php-parser is listed under Code Analysis, specifically Code Analysis.