Improved compile errors

This commit is contained in:
Brandon Dyck 2022-11-27 09:53:49 -07:00
parent e2c1b19b3e
commit f2d14f03f1
2 changed files with 37 additions and 13 deletions

37
ph7.go
View File

@ -56,22 +56,28 @@ type Error struct {
// TODO create a CompileError that contains the error log text // TODO create a CompileError that contains the error log text
func newError(code C.int) error { func newError(code C.int) error {
if code != C.PH7_OK { if code == C.PH7_OK {
return nil
}
return Error{ return Error{
Code: ResultCode(code), Code: ResultCode(code),
} }
} }
return nil
}
func (e Error) Error() string { func (e Error) Error() string {
return fmt.Sprintf("ph7: %s", e.Code) return fmt.Sprintf("ph7: %s", e.Code.String())
}
type CompileError struct {
Msg string
}
func (e CompileError) Error() string {
return fmt.Sprintf("ph7 compile error: %s", e.Msg)
} }
type Engine C.ph7 type Engine C.ph7
// TODO strip off the enclosing struct if possible after wrapping all engine methods.
func NewEngine() (*Engine, error) { func NewEngine() (*Engine, error) {
var cengine *C.ph7 var cengine *C.ph7
result := C.ph7_init(&cengine) result := C.ph7_init(&cengine)
@ -96,6 +102,23 @@ func (e *Engine) ErrLog() (string, error) {
// TODO All the ph7_config verbs // TODO All the ph7_config verbs
func (e *Engine) compileError(code C.int) error {
switch code {
case C.PH7_OK:
return nil
case C.PH7_COMPILE_ERR:
errLog, errLogErr := e.ErrLog()
if errLogErr != nil || errLog == "" {
return newError(code)
}
return CompileError{
Msg: errLog,
}
default:
return newError(code)
}
}
func (e *Engine) Compile(source []byte, phpOnly bool) (*VM, error) { func (e *Engine) Compile(source []byte, phpOnly bool) (*VM, error) {
csource := C.CBytes(source) csource := C.CBytes(source)
defer C.free(csource) defer C.free(csource)
@ -104,7 +127,7 @@ func (e *Engine) Compile(source []byte, phpOnly bool) (*VM, error) {
flags |= C.PH7_PHP_ONLY flags |= C.PH7_PHP_ONLY
} }
var cvm *C.ph7_vm var cvm *C.ph7_vm
err := newError(C.ph7_compile_v2((*C.ph7)(e), (*C.char)(csource), C.int(len(source)), &cvm, flags)) err := e.compileError(C.ph7_compile_v2((*C.ph7)(e), (*C.char)(csource), C.int(len(source)), &cvm, flags))
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -2,6 +2,7 @@ package ph7_test
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"testing" "testing"
@ -63,10 +64,10 @@ func TestCompileError(t *testing.T) {
_, err = engine.Compile([]byte("<?php 1234 echo 'Hello world!'; ?>"), false) _, err = engine.Compile([]byte("<?php 1234 echo 'Hello world!'; ?>"), false)
mustFail(t, err) mustFail(t, err)
msg, err := engine.ErrLog() var target ph7.CompileError
mustSucceed(t, err) isCompileError := errors.As(err, &target)
if msg == "" { if !isCompileError || target.Msg == "" {
t.Fatalf("expected error message, got nothing") t.Fatalf("expected compile error, got %#v", err)
} }
} }