php-parser/pkg/parser/parser.go

54 lines
1.3 KiB
Go
Raw Normal View History

package parser
2018-04-10 17:15:15 +00:00
import (
2020-12-29 19:23:22 +00:00
"errors"
2020-05-12 21:16:36 +00:00
"github.com/z7zmey/php-parser/internal/php5"
"github.com/z7zmey/php-parser/internal/php7"
2020-06-29 20:00:56 +00:00
"github.com/z7zmey/php-parser/internal/scanner"
2020-05-12 21:16:36 +00:00
"github.com/z7zmey/php-parser/pkg/ast"
2021-02-13 21:54:34 +00:00
"github.com/z7zmey/php-parser/pkg/conf"
2020-12-29 19:23:22 +00:00
"github.com/z7zmey/php-parser/pkg/version"
)
var (
// ErrVersionOutOfRange is returned if the version is not supported
ErrVersionOutOfRange = errors.New("the version is out of supported range")
php5RangeStart = &version.Version{Major: 5}
php5RangeEnd = &version.Version{Major: 5, Minor: 6}
php7RangeStart = &version.Version{Major: 7}
php7RangeEnd = &version.Version{Major: 7, Minor: 4}
2018-04-10 17:15:15 +00:00
)
// Parser interface
2018-04-10 17:15:15 +00:00
type Parser interface {
Parse() int
2020-05-12 21:16:36 +00:00
GetRootNode() ast.Vertex
2018-04-10 17:15:15 +00:00
}
2019-12-26 15:57:56 +00:00
2021-02-13 21:54:34 +00:00
func Parse(src []byte, config conf.Config) (ast.Vertex, error) {
2019-12-26 15:57:56 +00:00
var parser Parser
2020-12-29 19:23:22 +00:00
if config.Version == nil {
config.Version = php7RangeEnd
2019-12-26 15:57:56 +00:00
}
2020-12-29 19:23:22 +00:00
if config.Version.InRange(php5RangeStart, php5RangeEnd) {
lexer := scanner.NewLexer(src, config)
parser = php5.NewParser(lexer, config)
parser.Parse()
return parser.GetRootNode(), nil
2019-12-26 15:57:56 +00:00
}
2020-12-29 19:23:22 +00:00
if config.Version.InRange(php7RangeStart, php7RangeEnd) {
lexer := scanner.NewLexer(src, config)
parser = php7.NewParser(lexer, config)
parser.Parse()
return parser.GetRootNode(), nil
}
2020-06-29 20:00:56 +00:00
2020-12-29 19:23:22 +00:00
return nil, ErrVersionOutOfRange
2019-12-26 15:57:56 +00:00
}