forked from tliron/puccini
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphase4-inheritance.go
330 lines (275 loc) · 8.39 KB
/
phase4-inheritance.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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package parser
import (
"fmt"
"reflect"
"strings"
"github.com/tliron/kutil/reflection"
"github.com/tliron/puccini/tosca"
)
func (self *ServiceContext) Inherit(debug func(Tasks)) {
self.Context.lock.Lock()
defer self.Context.lock.Unlock()
tasks := self.getInheritTasks()
if debug != nil {
debug(tasks)
}
tasks.Drain()
}
func (self *ServiceContext) getInheritTasks() Tasks {
inheritContext := NewInheritContext()
self.TraverseEntities(logInheritance, self.Context.getInheritTaskWork, func(entityPtr tosca.EntityPtr) bool {
inheritContext.GetInheritTask(entityPtr)
return true
})
return inheritContext.Tasks
}
//
// InheritContext
//
type InheritContext struct {
Tasks Tasks
TasksForEntities TasksForEntities
InheritFields InheritFields
}
func NewInheritContext() *InheritContext {
return &InheritContext{make(Tasks), make(TasksForEntities), make(InheritFields)}
}
func (self *InheritContext) GetInheritTask(entityPtr tosca.EntityPtr) *Task {
task, ok := self.TasksForEntities[entityPtr]
if !ok {
path := tosca.GetContext(entityPtr).Path.String()
if path == "" {
path = "<root>"
}
task = NewTask(path)
self.Tasks.Add(task)
self.TasksForEntities[entityPtr] = task
for dependencyEntityPtr := range self.GetDependencies(entityPtr) {
task.AddDependency(self.GetInheritTask(dependencyEntityPtr))
}
task.Executor = self.NewExecutor(entityPtr)
logInheritance.Debugf("new task: %s (%d)", task.Name, len(task.Dependencies))
} else {
logInheritance.Debugf("task cache hit: %s (%d)", task.Name, len(task.Dependencies))
}
return task
}
func (self *InheritContext) NewExecutor(entityPtr tosca.EntityPtr) Executor {
return func(task *Task) {
defer task.Done()
logInheritance.Debugf("task: %s", task.Name)
for _, inheritField := range self.InheritFields.Get(entityPtr) {
inheritField.Inherit()
}
// Custom inheritance after all fields have been inherited
tosca.Inherit(entityPtr)
}
}
func (self *InheritContext) GetDependencies(entityPtr tosca.EntityPtr) tosca.EntityPtrSet {
dependencies := make(tosca.EntityPtrSet)
// From "inherit" tags
for _, inheritField := range self.InheritFields.Get(entityPtr) {
dependencies.Add(inheritField.ParentEntityPtr)
}
// From field values
entity := reflect.ValueOf(entityPtr).Elem()
for _, structField := range reflection.GetStructFields(entity.Type()) {
// Does this case ever happen?
// Would conflict with anonymous pointer fields (Go "inheritance")
// if reflection.IsPtrToStruct(structField.Type) {
// // Compatible with *any
// field := entity.FieldByName(structField.Name)
// if !field.IsNil() {
// e := field.Interface()
// // We sometimes have pointers to non-entities, so make sure
// if _, ok := e.(tosca.Contextual); ok {
// dependencies[e] = true
// }
// }
// }
if reflection.IsMapOfStringToPtrToStruct(structField.Type) {
// Compatible with map[string]*any
field := entity.FieldByName(structField.Name)
for _, mapKey := range field.MapKeys() {
element := field.MapIndex(mapKey)
dependencies.Add(element.Interface())
}
} else if reflection.IsSliceOfPtrToStruct(structField.Type) {
// Compatible with []*any
field := entity.FieldByName(structField.Name)
length := field.Len()
for i := 0; i < length; i++ {
element := field.Index(i)
dependencies.Add(element.Interface())
}
}
}
return dependencies
}
//
// InheritField
//
type InheritField struct {
Entity reflect.Value
Key string
Field reflect.Value
ParentEntityPtr tosca.EntityPtr
ParentField reflect.Value
}
func (self *InheritField) Inherit() {
// TODO: do we really need all of these? some of them aren't used in TOSCA
fieldEntityPtr := self.Field.Interface()
if reflection.IsPtrToString(fieldEntityPtr) {
self.InheritEntity()
} else if reflection.IsPtrToInt64(fieldEntityPtr) {
self.InheritEntity()
} else if reflection.IsPtrToBool(fieldEntityPtr) {
self.InheritEntity()
} else if reflection.IsPtrToSliceOfString(fieldEntityPtr) {
self.InheritStringsFromSlice()
} else if reflection.IsPtrToMapOfStringToString(fieldEntityPtr) {
self.InheritStringsFromMap()
} else {
fieldType := self.Field.Type()
if reflection.IsPtrToStruct(fieldType) {
self.InheritEntity()
} else if reflection.IsSliceOfPtrToStruct(fieldType) {
self.InheritStructsFromSlice()
} else if reflection.IsMapOfStringToPtrToStruct(fieldType) {
self.InheritStructsFromMap()
} else {
panic(fmt.Sprintf("\"inherit\" tag's field type %q is not supported in struct: %T", fieldType, self.Entity.Interface()))
}
}
}
// Field is compatible with *any
func (self *InheritField) InheritEntity() {
if self.Field.IsNil() && !self.ParentField.IsNil() {
self.Field.Set(self.ParentField)
}
}
// Field is *[]string
func (self *InheritField) InheritStringsFromSlice() {
slicePtr := self.Field.Interface().(*[]string)
parentSlicePtr := self.ParentField.Interface().(*[]string)
if parentSlicePtr == nil {
return
}
parentSlice := *parentSlicePtr
length := len(parentSlice)
if length == 0 {
return
}
var slice []string
if slicePtr != nil {
slice = *slicePtr
} else {
slice = make([]string, 0, length)
}
for _, element := range parentSlice {
slice = append(slice, element)
}
self.Field.Set(reflect.ValueOf(&slice))
}
// Field is compatible with []*any
func (self *InheritField) InheritStructsFromSlice() {
slice := self.Field
length := self.ParentField.Len()
for i := 0; i < length; i++ {
element := self.ParentField.Index(i)
if _, ok := element.Interface().(tosca.Mappable); ok {
// For mappable elements only, *don't* inherit the same key
// (We'll merge everything else)
key := tosca.GetKey(element.Interface())
if ii, ok := getSliceElementIndexForKey(self.Field, key); ok {
element_ := self.Field.Index(ii)
logInheritance.Debugf("override: %s", tosca.GetContext(element_.Interface()).Path)
continue // skip this key
}
}
slice = reflect.Append(slice, element)
}
self.Field.Set(slice)
}
// Field is *map[string]string
func (self *InheritField) InheritStringsFromMap() {
mapPtr := self.Field.Interface().(*map[string]string)
parentMapPtr := self.ParentField.Interface().(*map[string]string)
if parentMapPtr == nil {
return
}
parentMap := *parentMapPtr
if length := len(parentMap); length == 0 {
return
}
var map_ map[string]string
if mapPtr != nil {
map_ = *mapPtr
} else {
map_ = make(map[string]string)
}
for key, value := range parentMap {
if _, ok := map_[key]; !ok {
map_[key] = value
}
}
self.Field.Set(reflect.ValueOf(&map_))
}
// Field is compatible with map[string]*any
func (self *InheritField) InheritStructsFromMap() {
for _, mapKey := range self.ParentField.MapKeys() {
element := self.ParentField.MapIndex(mapKey)
element_ := self.Field.MapIndex(mapKey)
if element_.IsValid() {
// We are overriding this element, so don't inherit it
logInheritance.Debugf("override: %s", tosca.GetContext(element_.Interface()).Path)
} else {
self.Field.SetMapIndex(mapKey, element)
}
}
}
func getSliceElementIndexForKey(slice reflect.Value, key string) (int, bool) {
length := slice.Len()
for i := 0; i < length; i++ {
element := slice.Index(i)
if tosca.GetKey(element.Elem()) == key {
return i, true
}
}
return -1, false
}
//
// InheritFields
//
type InheritFields map[tosca.EntityPtr][]*InheritField
// From "inherit" tags
func NewInheritFields(entityPtr tosca.EntityPtr) []*InheritField {
var inheritFields []*InheritField
entity := reflect.ValueOf(entityPtr).Elem()
for fieldName, tag := range reflection.GetFieldTagsForValue(entity, "inherit") {
key, referenceFieldName := parseInheritTag(tag)
if referenceField, referredField, ok := reflection.GetReferredField(entity, referenceFieldName, fieldName); ok {
field := entity.FieldByName(fieldName)
inheritFields = append(inheritFields, &InheritField{entity, key, field, referenceField.Interface(), referredField})
}
}
return inheritFields
}
func (self InheritFields) Get(entityPtr tosca.EntityPtr) []*InheritField {
// TODO: cache these, because we call twice for each entity
inheritFields, ok := self[entityPtr]
if !ok {
inheritFields = NewInheritFields(entityPtr)
self[entityPtr] = inheritFields
}
return inheritFields
}
func parseInheritTag(tag string) (string, string) {
t := strings.Split(tag, ",")
if len(t) != 2 {
panic("must be 2")
}
key := t[0]
referenceFieldName := t[1]
return key, referenceFieldName
}