-
Notifications
You must be signed in to change notification settings - Fork 187
/
simplify_definitions.go
60 lines (48 loc) · 1.48 KB
/
simplify_definitions.go
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
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
*/
package pipeline
import (
"context"
kerrors "k8s.io/apimachinery/pkg/util/errors"
"github.com/Azure/azure-service-operator/v2/tools/generator/internal/astmodel"
)
const SimplifyDefinitionsStageId = "simplifyDefinitions"
// SimplifyDefinitions creates a pipeline stage that removes any wrapper types prior to actual code generation
func SimplifyDefinitions() *Stage {
return NewLegacyStage(
SimplifyDefinitionsStageId,
"Flatten definitions by removing wrapper types",
func(ctx context.Context, defs astmodel.TypeDefinitionSet) (astmodel.TypeDefinitionSet, error) {
visitor := createSimplifyingVisitor()
var errs []error
result := make(astmodel.TypeDefinitionSet)
for _, def := range defs {
visited, err := visitor.VisitDefinition(def, nil)
if err != nil {
errs = append(errs, err)
} else {
result.Add(visited)
}
}
if len(errs) > 0 {
return nil, kerrors.NewAggregate(errs)
}
return result, nil
})
}
func createSimplifyingVisitor() astmodel.TypeVisitor[any] {
removeFlags := func(tv *astmodel.TypeVisitor[any], ft *astmodel.FlaggedType, ctx any) (astmodel.Type, error) {
element := ft.Element()
return tv.Visit(element, ctx)
}
skipComplexTypes := func(ot *astmodel.ObjectType) astmodel.Type {
return ot
}
result := astmodel.TypeVisitorBuilder[any]{
VisitFlaggedType: removeFlags,
VisitObjectType: skipComplexTypes,
}.Build()
return result
}