Files
expr/patcher/with_context.go
DaenneyandGitHub 13451f69b4 Make WithContext work for methods on env struct (#602)
This makes the WithContext patcher work when passing in a struct for an
env that has methods that take a context.

This is a bit fiddly because we can't quite detect the difference of
function vs. method on a struct, so we have to check both the first and
the second param. Since it's highly unusual to pass the context as
anything other than the first parameter, this should work out just fine
in practice.

Fixes #600.
2024-04-12 22:54:01 +02:00

46 lines
923 B
Go

package patcher
import (
"reflect"
"github.com/expr-lang/expr/ast"
)
// WithContext adds WithContext.Name argument to all functions calls with a context.Context argument.
type WithContext struct {
Name string
}
// Visit adds WithContext.Name argument to all functions calls with a context.Context argument.
func (w WithContext) Visit(node *ast.Node) {
switch call := (*node).(type) {
case *ast.CallNode:
fn := call.Callee.Type()
if fn == nil {
return
}
if fn.Kind() != reflect.Func {
return
}
switch fn.NumIn() {
case 0:
return
case 1:
if fn.In(0).String() != "context.Context" {
return
}
default:
if fn.In(0).String() != "context.Context" &&
fn.In(1).String() != "context.Context" {
return
}
}
ast.Patch(node, &ast.CallNode{
Callee: call.Callee,
Arguments: append([]ast.Node{
&ast.IdentifierNode{Value: w.Name},
}, call.Arguments...),
})
}
}