Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ruleguard/quasigo: add variadic native func calls support #312

Merged
merged 1 commit into from
Nov 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 34 additions & 5 deletions ruleguard/quasigo/compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ func (cl *compiler) compileBuiltinCall(fn *ast.Ident, call *ast.CallExpr) {
funcName = "PrintInt"
}
key := funcKey{qualifier: "builtin", name: funcName}
if !cl.compileNativeCall(key, nil, call.Args) {
if !cl.compileNativeCall(key, 0, nil, call.Args) {
panic(cl.errorf(fn, "builtin.%s native func is not registered", funcName))
}

Expand Down Expand Up @@ -548,13 +548,16 @@ func (cl *compiler) compileCallExpr(call *ast.CallExpr) {
} else {
key.qualifier = fn.Pkg().Path()
}

if !cl.compileNativeCall(key, expr, call.Args) {
variadic := 0
if sig.Variadic() {
variadic = sig.Params().Len() - 1
}
if !cl.compileNativeCall(key, variadic, expr, call.Args) {
panic(cl.errorf(call.Fun, "can't compile a call to %s func", key))
}
}

func (cl *compiler) compileNativeCall(key funcKey, expr ast.Expr, args []ast.Expr) bool {
func (cl *compiler) compileNativeCall(key funcKey, variadic int, expr ast.Expr, args []ast.Expr) bool {
funcID, ok := cl.ctx.Env.nameToNativeFuncID[key]
if !ok {
return false
Expand All @@ -572,9 +575,35 @@ func (cl *compiler) compileNativeCall(key funcKey, expr ast.Expr, args []ast.Exp
}
}
}
for _, arg := range args {

normalArgs := args
var variadicArgs []ast.Expr
if variadic != 0 {
normalArgs = args[:variadic]
variadicArgs = args[variadic:]
}

for _, arg := range normalArgs {
cl.compileExpr(arg)
}
if variadic != 0 {
for _, arg := range variadicArgs {
cl.compileExpr(arg)
// int-typed values should appear in the interface{}-typed
// objects slice, so we get all variadic args placed in one place.
if typeIsInt(cl.ctx.Types.TypeOf(arg)) {
cl.emit(opConvIntToIface)
}
}
if len(variadicArgs) > 255 {
panic(cl.errorf(expr, "too many variadic args"))
}
// Even if len(variadicArgs) is 0, we still need to overwrite
// the old variadicLen value, so the variadic func is not confused
// by some unrelated value.
cl.emit8(opSetVariadicLen, len(variadicArgs))
}

cl.emit16(opCallNative, int(funcID))
return true
}
Expand Down
29 changes: 27 additions & 2 deletions ruleguard/quasigo/compile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -330,13 +330,34 @@ func TestCompile(t *testing.T) {
` SetLocal 0 # err`,
` SetIntLocal 1 # v`,
` PushIntLocal 1 # v`,
` CallNative 3 # builtin.PrintInt`,
` CallNative 4 # builtin.PrintInt`,
` PushLocal 0 # err`,
` IsNil`,
` CallNative 4 # builtin.Print`,
` CallNative 5 # builtin.Print`,
` PushLocal 0 # err`,
` ReturnTop`,
},

`v := sprintf("no formatting"); return v`: {
` PushConst 0 # value="no formatting"`,
` SetVariadicLen 0`,
` CallNative 3 # testpkg.sprintf`,
` SetLocal 0 # v`,
` PushLocal 0 # v`,
` ReturnTop`,
},

`v := sprintf("%s:%d", "foo", 5); return v`: {
` PushConst 0 # value="%s:%d"`,
` PushConst 1 # value="foo"`,
` PushIntConst 0 # value=5`,
` ConvIntToIface`,
` SetVariadicLen 2`,
` CallNative 3 # testpkg.sprintf`,
` SetLocal 0 # v`,
` PushLocal 0 # v`,
` ReturnTop`,
},
}

makePackageSource := func(body string) string {
Expand All @@ -348,6 +369,7 @@ func TestCompile(t *testing.T) {
func imul(x, y int) int
func idiv(x, y int) int
func atoi(s string) (int, error)
func sprintf(format string, args ...interface{}) string
`
}

Expand All @@ -361,6 +383,9 @@ func TestCompile(t *testing.T) {
env.AddNativeFunc(testPackage, "atoi", func(stack *quasigo.ValueStack) {
panic("should not be called")
})
env.AddNativeFunc(testPackage, "sprintf", func(stack *quasigo.ValueStack) {
panic("should not be called")
})
env.AddNativeFunc("builtin", "PrintInt", func(stack *quasigo.ValueStack) {
panic("should not be called")
})
Expand Down
2 changes: 2 additions & 0 deletions ruleguard/quasigo/disasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ func disasm(env *Env, fn *Func) string {
index := int(code[pc+1])
arg = index
comment = dbg.localNames[index]
case opSetVariadicLen:
arg = int(code[pc+1])
case opPushConst:
arg = int(code[pc+1])
comment = fmt.Sprintf("value=%#v", fn.constants[code[pc+1]])
Expand Down
7 changes: 7 additions & 0 deletions ruleguard/quasigo/eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ func eval(env *EvalEnv, fn *Func, args []interface{}) CallResult {
stack.PushInt(fn.intConstants[id])
pc += 2

case opConvIntToIface:
stack.Push(stack.PopInt())
pc++

case opPushTrue:
stack.Push(true)
pc++
Expand All @@ -117,6 +121,9 @@ func eval(env *EvalEnv, fn *Func, args []interface{}) CallResult {
case opReturn:
return CallResult{}

case opSetVariadicLen:
stack.variadicLen = int(code[pc+1])
pc += 2
case opCallNative:
id := decode16(code, pc+1)
fn := env.nativeFuncs[id].mappedFunc
Expand Down
21 changes: 20 additions & 1 deletion ruleguard/quasigo/eval_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"testing"

"github.com/quasilyte/go-ruleguard/ruleguard/quasigo"
"github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qfmt"
)

type benchTestCase struct {
Expand Down Expand Up @@ -75,7 +76,22 @@ func TestNoAllocs(t *testing.T) {
}

func BenchmarkEval(b *testing.B) {
var tests []*benchTestCase
var tests = []*benchTestCase{
{
`CallNativeVariadic0`,
`return fmt.Sprintf("no formatting")`,
},
{
`CallNativeVariadic1`,
`return fmt.Sprintf("Hello, %s!", "world")`,
},

{
`CallNativeVariadic2`,
`return fmt.Sprintf("%s:%d", "foo.go", 105)`,
},
}

tests = append(tests, benchmarksNoAlloc...)

runBench := func(b *testing.B, env *quasigo.EvalEnv, fn *quasigo.Func) {
Expand All @@ -98,6 +114,8 @@ func compileBenchFunc(t testing.TB, bodySrc string) (*quasigo.Env, *quasigo.Func
makePackageSource := func(body string) string {
return `
package test
import "fmt"
var _ = fmt.Sprintf
func f() interface{} {
` + body + `
}
Expand All @@ -111,6 +129,7 @@ func compileBenchFunc(t testing.TB, bodySrc string) (*quasigo.Env, *quasigo.Func
x := stack.PopInt()
stack.PushInt(x * y)
})
qfmt.ImportAll(env)
src := makePackageSource(bodySrc)
parsed, err := parseGoFile(src)
if err != nil {
Expand Down
2 changes: 2 additions & 0 deletions ruleguard/quasigo/eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/google/go-cmp/cmp"
"github.com/quasilyte/go-ruleguard/ruleguard/quasigo"
"github.com/quasilyte/go-ruleguard/ruleguard/quasigo/internal/evaltest"
"github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qfmt"
"github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qstrconv"
"github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qstrings"
)
Expand Down Expand Up @@ -276,6 +277,7 @@ func TestEvalFile(t *testing.T) {

qstrings.ImportAll(env)
qstrconv.ImportAll(env)
qfmt.ImportAll(env)

var mainFunc *quasigo.Func
for _, decl := range parsed.ast.Decls {
Expand Down
4 changes: 4 additions & 0 deletions ruleguard/quasigo/gen_opcodes.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build main
// +build main

package main
Expand Down Expand Up @@ -25,6 +26,8 @@ var opcodePrototypes = []opcodeProto{
{"PushConst", "op constid:u8", "() -> (const)"},
{"PushIntConst", "op constid:u8", "() -> (const:int)"},

{"ConvIntToIface", "op", "(value:int) -> (value)"},

{"SetLocal", "op index:u8", "(value) -> ()"},
{"SetIntLocal", "op index:u8", "(value:int) -> ()"},
{"IncLocal", "op index:u8", stackUnchanged},
Expand All @@ -40,6 +43,7 @@ var opcodePrototypes = []opcodeProto{
{"JumpFalse", "op offset:i16", "(cond:bool) -> ()"},
{"JumpTrue", "op offset:i16", "(cond:bool) -> ()"},

{"SetVariadicLen", "op len:u8", stackUnchanged},
{"CallNative", "op funcid:u16", "(args...) -> (results...)"},

{"IsNil", "op", "(value) -> (result:bool)"},
Expand Down
68 changes: 35 additions & 33 deletions ruleguard/quasigo/opcode_string.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading