feat: expose the lexer to be used by users

This commit is contained in:
Laytan Laats 2023-04-11 22:38:29 +02:00
parent f98b59a5f0
commit 6b3673ece4
3 changed files with 41 additions and 13 deletions

28
pkg/lexer/lexer.go Normal file
View File

@ -0,0 +1,28 @@
package lexer
import (
"errors"
"github.com/laytan/php-parser/internal/php7"
"github.com/laytan/php-parser/internal/php8"
"github.com/laytan/php-parser/pkg/conf"
"github.com/laytan/php-parser/pkg/token"
)
var ErrVersionOutOfRange = errors.New("the version is out of supported range")
type Lexer interface {
Lex() *token.Token
}
func New(src []byte, config conf.Config) (Lexer, error) {
if config.Version.InPhp7Range() {
return php7.NewLexer(src, config), nil
}
if config.Version.InPhp8Range() {
return php8.NewLexer(src, config), nil
}
return nil, ErrVersionOutOfRange
}

View File

@ -10,16 +10,8 @@ import (
"github.com/laytan/php-parser/pkg/version"
)
var (
// ErrVersionOutOfRange is returned if the version is not supported
ErrVersionOutOfRange = errors.New("the version is out of supported range")
php7RangeStart = &version.Version{Major: 7}
php7RangeEnd = &version.Version{Major: 7, Minor: 4}
php8RangeStart = &version.Version{Major: 8}
php8RangeEnd = &version.Version{Major: 8, Minor: 2}
)
var ErrVersionOutOfRange = errors.New("the version is out of supported range")
// Parser interface
type Parser interface {
@ -31,17 +23,17 @@ func Parse(src []byte, config conf.Config) (ast.Vertex, error) {
var parser Parser
if config.Version == nil {
config.Version = php7RangeEnd
config.Version = &version.Version{Major: 7, Minor: 4}
}
if config.Version.InRange(php7RangeStart, php7RangeEnd) {
if config.Version.InPhp7Range() {
lexer := php7.NewLexer(src, config)
parser = php7.NewParser(lexer, config)
parser.Parse()
return parser.GetRootNode(), nil
}
if config.Version.InRange(php8RangeStart, php8RangeEnd) {
if config.Version.InPhp8Range() {
lexer := php8.NewLexer(src, config)
parser = php8.NewParser(lexer, config)
parser.Parse()

View File

@ -81,6 +81,14 @@ func (v *Version) InRange(s, e *Version) bool {
return v.Compare(s) >= 0 && v.Compare(e) <= 0
}
func (v *Version) InPhp7Range() bool {
return v.InRange(php7RangeStart, php7RangeEnd)
}
func (v *Version) InPhp8Range() bool {
return v.InRange(php8RangeStart, php8RangeEnd)
}
// Compare compares this version to another one. It returns -1, 0, or 1 if
// the version smaller, equal, or larger than the other version.
func (v *Version) Compare(o *Version) int {