aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/aflow/verify.go
blob: 8486560f8b94c0fe7138bee0fc1335e0059b125b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Copyright 2025 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package aflow

import (
	"fmt"
	"maps"
	"reflect"
	"slices"
)

type verifyContext struct {
	actions map[string]bool
	state   map[string]*varState
	models  map[string]bool
	err     error
}

type varState struct {
	action string
	typ    reflect.Type
	used   bool
}

func (ctx *verifyContext) errorf(who, msg string, args ...any) {
	noteError(&ctx.err, fmt.Sprintf("action %v: %v", who, msg), args...)
}

func (ctx *verifyContext) requireNotEmpty(who, name, value string) {
	if value == "" {
		ctx.errorf(who, "%v must not be empty", name)
	}
}

func (ctx *verifyContext) requireInput(who, name string, typ reflect.Type) {
	state := ctx.state[name]
	if state == nil {
		ctx.errorf(who, "no input %v, available inputs: %v",
			name, slices.Collect(maps.Keys(ctx.state)))
		return
	}
	if typ != state.typ {
		ctx.errorf(who, "input %v has wrong type: want %v, has %v",
			name, typ, state.typ)
	}
	state.used = true
}

func (ctx *verifyContext) provideOutput(who, name string, typ reflect.Type, unique bool) {
	state := ctx.state[name]
	if state != nil {
		if unique {
			ctx.errorf(who, "output %v is already set", name)
		} else if typ != state.typ {
			ctx.errorf(who, "output %v changes type: %v -> %v",
				name, state.typ, typ)
		} else if !state.used {
			ctx.errorf(state.action, "output %v is unused", name)
		}
	}
	ctx.state[name] = &varState{
		action: who,
		typ:    typ,
	}
}

func (ctx *verifyContext) finalize() error {
	for name, state := range ctx.state {
		if !state.used {
			ctx.errorf(state.action, "output %v is unused", name)
		}
	}
	return ctx.err
}

func noteError(errp *error, msg string, args ...any) {
	if *errp == nil {
		*errp = fmt.Errorf(msg, args...)
	}
}

func requireInputs[T any](ctx *verifyContext, who string) {
	for name, typ := range foreachFieldOf[T]() {
		ctx.requireInput(who, name, typ)
	}
}

func provideOutputs[T any](ctx *verifyContext, who string) {
	for name, typ := range foreachFieldOf[T]() {
		ctx.provideOutput(who, name, typ, true)
	}
}

func provideArrayOutputs[T any](ctx *verifyContext, who string) {
	for name, typ := range foreachFieldOf[T]() {
		ctx.provideOutput(who, name, reflect.SliceOf(typ), true)
	}
}

func requireSchema[T any](ctx *verifyContext, who, what string) {
	if _, err := schemaFor[T](); err != nil {
		ctx.errorf(who, "%v: %v", what, err)
	}
}