-
Notifications
You must be signed in to change notification settings - Fork 3
/
planner.go
637 lines (523 loc) · 15.7 KB
/
planner.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
package velty
import (
"fmt"
"github.com/viant/velty/ast"
"github.com/viant/velty/ast/expr"
"github.com/viant/velty/est"
"github.com/viant/velty/est/op"
"github.com/viant/xreflect"
"github.com/viant/xunsafe"
"reflect"
"strings"
"time"
)
const (
fieldSeparator = "___"
)
var TimeType = reflect.TypeOf(time.Time{})
type (
Planner struct {
bufferSize int
*est.Control
Type *est.Type
selectors *op.Selectors
constants *constants
*op.Functions
cache *cache
escapeHTML bool
panicOnError bool
}
)
// EmbedVariable enrich the Type by adding Anonymous field with given name.
// val can be either of the reflect.Type or regular type (i.e. Foo)
func (p *Planner) EmbedVariable(val interface{}) error {
var rType reflect.Type
switch actual := val.(type) {
case reflect.Type:
rType = actual
default:
rType = reflect.TypeOf(val)
}
field := p.Type.EmbedType(rType)
vTag := Parse(field.Tag.Get(velty))
return p.addSelectors(vTag.Prefix, field, field.Name)
}
func (p *Planner) addSelectors(prefix string, field reflect.StructField, fieldName string) error {
detector := NewCycleDetector(field.Type)
return p.createSelectors(prefix, field, nil, 0, 0, false, detector, fieldName)
}
func (p *Planner) createSelectors(prefix string, field reflect.StructField, parent *op.Selector, offsetSoFar, initialOffset uintptr, indirect bool, cycleDetector *CycleDetector, fieldName string) error {
cycleNode, cycleSelector := p.cycle(cycleDetector, field, parent)
if field.Anonymous {
initialOffset += field.Offset
}
indirect = indirect || field.Type.Kind() == reflect.Ptr || field.Type.Kind() == reflect.Slice
vTag := Parse(field.Tag.Get(velty))
newParent, err := p.indexSelectorIfNeeded(prefix, field, parent, offsetSoFar, initialOffset, indirect, cycleSelector, fieldName)
if err != nil || cycleSelector != nil {
return err
}
if !field.Anonymous {
offsetSoFar += field.Offset
initialOffset = 0
if prefix == "" {
prefix = fieldName + fieldSeparator
} else {
prefix = prefix + fieldName + fieldSeparator
}
} else {
if vTag.Prefix != "" {
prefix += vTag.Prefix
}
}
fieldType, _ := elemIfNeeded(field.Type)
if fieldType == TimeType {
return nil
}
return p.addChildrenSelectors(prefix, field, offsetSoFar, initialOffset, indirect, cycleNode, newParent)
}
func (p *Planner) cycle(cycleDetector *CycleDetector, field reflect.StructField, parent *op.Selector) (*CycleDetector, *op.Selector) {
child, cycle := cycleDetector.Child(field.Type, parent)
if cycle {
return child, child.parentSelector
}
return child, nil
}
func (p *Planner) addChildrenSelectors(holderPrefix string, field reflect.StructField, offsetSoFar, initialOffset uintptr, indirect bool, detector *CycleDetector, parent *op.Selector) error {
rType, elemed := elemIfNeeded(field.Type)
if rType.Kind() == reflect.Struct {
fieldsLen := rType.NumField()
for i := 0; i < fieldsLen; i++ {
structField := rType.Field(i)
vTag := Parse(structField.Tag.Get(velty))
if vTag.Omit {
continue
}
fieldNames := []string{structField.Name}
if len(vTag.Names) != 0 {
fieldNames = vTag.Names
}
for _, name := range fieldNames {
if name == "_" {
continue
}
if err := p.createSelectors(holderPrefix, structField, parent, offsetSoFar, initialOffset, indirect || elemed, detector, name); err != nil {
return err
}
}
}
}
return nil
}
func (p *Planner) indexSelectorIfNeeded(prefix string, field reflect.StructField, parent *op.Selector, offset uintptr, anonymousOffset uintptr, indirect bool, cycleSelector *op.Selector, name string) (*op.Selector, error) {
if field.Anonymous && field.Type.Kind() != reflect.Ptr {
return parent, nil
}
newField := xunsafe.NewField(field)
newField.Offset += anonymousOffset
var err error
var fieldSelector *op.Selector
if cycleSelector != nil {
fieldSelector = op.NewCycleSelector(prefix+name, newField, parent, indirect, offset, cycleSelector)
} else {
fieldSelector = op.SelectorWithField(prefix+name, newField, parent, indirect, offset)
}
if field.Anonymous {
return fieldSelector, nil
}
if err = p.selectors.Append(fieldSelector); err != nil {
return nil, fmt.Errorf("%w, prefix is required, if parent field is an Anonymous, and any other parent field has the same name", err)
}
return fieldSelector, nil
}
func elemIfNeeded(rType reflect.Type) (reflect.Type, bool) {
wasPtr := false
for rType.Kind() == reflect.Ptr || rType.Kind() == reflect.Slice || rType.Kind() == reflect.Map {
wasPtr = true
rType = rType.Elem()
}
return rType, wasPtr
}
// DefineVariable enrich the Type by adding field with given name.
// val can be either of the reflect.Type or regular type (i.e. Foo)
func (p *Planner) DefineVariable(name string, v interface{}, names ...string) error {
if p.selectorByName(name) != nil {
return nil
}
var sType reflect.Type
switch t := v.(type) {
case reflect.Type:
sType = t
default:
sType = reflect.TypeOf(v)
}
field := p.Type.AddField(name, name, sType)
if err := p.addSelectors("", field, name); err != nil {
return err
}
for _, additionalFieldName := range names {
if err := p.addSelectors("", field, additionalFieldName); err != nil {
return err
}
}
return nil
}
func (p *Planner) selector(selector *expr.Select) (*op.Selector, error) {
resultSelector, call, err := p.matchFirstSelector(selector)
if err != nil || call == nil {
return resultSelector, err
}
parentType := resultSelector.Type
selectorId := selector.ID
upstreamSelector := p.copyWithParent(resultSelector, resultSelector.Parent)
for call != nil {
parentType = deref(parentType)
resultSelector, call, err = p.matchSelector(call, resultSelector, selectorId, parentType)
if err != nil {
return nil, err
}
parentType = resultSelector.Type
selectorId = resultSelector.ID
upstreamSelector = p.copyWithParent(resultSelector, upstreamSelector)
}
return upstreamSelector, nil
}
func (p *Planner) matchFirstSelector(selector *expr.Select) (*op.Selector, ast.Expression, error) {
opSelector, next, err := p.tryMatchFunc(selector.ID, selector.X)
if err == nil && opSelector != nil {
return opSelector, next, nil
}
resultSelector := p.selectorByName(selector.ID)
if resultSelector != nil {
return resultSelector, selector.X, nil
}
return nil, nil, nil
}
func (p *Planner) copyWithParent(dest, parent *op.Selector) *op.Selector {
selCopy := *dest
selCopy.Parent = parent
return &selCopy
}
func (p *Planner) matchSelector(call ast.Expression, resultSelector *op.Selector, selectorId string, parentType reflect.Type) (*op.Selector, ast.Expression, error) {
selector, next, err := p.tryMatchCall(call, resultSelector, selectorId)
if err != nil || selector != nil {
return selector, next, err
}
switch actual := call.(type) {
case *expr.Select:
if callSelector, callNext, callErr := p.tryMatchCall(actual.X, resultSelector, actual.ID); callSelector != nil || callErr != nil {
return callSelector, callNext, callErr
}
_, err = p.fieldByName(parentType, actual, actual.ID)
if err != nil {
return nil, nil, err
}
selectorId = selectorId + fieldSeparator + actual.ID
var found bool
resultSelector, found = p.selectors.ById(selectorId)
if !found {
return nil, nil, fmt.Errorf("not found selector for the %v", strings.ReplaceAll(selectorId, fieldSeparator, "."))
}
return resultSelector, actual.X, nil
}
return resultSelector, nil, nil
}
func (p *Planner) fieldByName(parentType reflect.Type, actual *expr.Select, selectorId string) (*xunsafe.Field, error) {
field := xunsafe.FieldByName(parentType, actual.ID)
if field != nil {
if Parse(field.Tag.Get(velty)).Omit {
return nil, fmt.Errorf("can't create selector for field %v", field.Name)
}
return field, nil
}
for i := 0; i < parentType.NumField(); i++ {
vTag := Parse(parentType.Field(i).Tag.Get(velty))
if vTag.nameEqual(actual.ID) {
return xunsafe.NewField(parentType.Field(i)), nil
}
}
return nil, fmt.Errorf("not found field %v at %v", strings.ReplaceAll(selectorId, fieldSeparator, "."), parentType.String())
}
func deref(rType reflect.Type) reflect.Type {
for {
switch rType.Kind() {
case reflect.Ptr, reflect.Slice:
rType = rType.Elem()
default:
return rType
}
}
}
func (p *Planner) accumulator(t reflect.Type) *op.Selector {
name := p.newName()
sel := op.NewSelector(name, name, t, nil)
if t != nil {
_ = p.selectors.Append(sel)
sel.Field = xunsafe.NewField(p.Type.AddFieldWithTag(name, name, "", t))
}
return sel
}
func (p *Planner) newName() string {
return p.Type.ReserveNewName()
}
func (p *Planner) adjustSelector(expr *op.Expression, t reflect.Type) error {
if expr.Selector.Type != nil {
return nil
}
if t == nil {
return fmt.Errorf("couldn't determine %v type", expr.Name)
}
if err := p.DefineVariable(expr.Name, t); err != nil {
return err
}
expr.Type = t
expr.Selector = p.selectorByName(expr.Name)
return nil
}
func (p *Planner) validateSelector(sel *op.Selector) error {
if sel.ID == "" {
return fmt.Errorf("selector ID was empty")
}
if sel.Type == nil {
return fmt.Errorf("selector %v type was empty", sel.Name)
}
if p.selectorByName(sel.ID) != nil {
return fmt.Errorf("variable %v already defined", sel.Name)
}
return nil
}
func (p *Planner) selectorByName(name string) *op.Selector {
if idx, ok := p.selectors.Index[name]; ok {
return p.selectors.Selector(idx)
}
if funcSelector, ok := p.Functions.FuncSelector(name, nil); ok {
return funcSelector
}
return nil
}
func (p *Planner) newFuncSelector(selectorId string, methodName string, call *expr.Call, prev *op.Selector) (*op.Selector, error) {
var err error
aFunc, err := p.Func(prev, methodName, call)
if err != nil {
return nil, err
}
operands, err := p.selectorOperands(call, prev)
if err != nil {
return nil, err
}
accumulator := p.accumulator(aFunc.ResultType)
newSelector := op.FunctionSelector(selectorId, accumulator.Field, aFunc, prev)
newSelector.Args = operands
newSelector.Type = aFunc.ResultType
if newSelector.Type == xreflect.InterfaceType {
actualType, err := p.Functions.TryDetectResultType(prev, methodName, call)
if err != nil {
return nil, err
}
if actualType != nil {
newSelector.Type = actualType
}
}
return newSelector, nil
}
func (p *Planner) Func(prev *op.Selector, methodName string, call *expr.Call) (*op.Func, error) {
var receiver reflect.Type
if prev != nil {
receiver = prev.Type
}
aFunc, err := p.Functions.Method(receiver, methodName, call)
if err == nil {
return aFunc, nil
}
return nil, fmt.Errorf("not found function %v", methodName)
}
func (p *Planner) selectorOperands(call *expr.Call, prev *op.Selector) ([]*op.Operand, error) {
operands := make([]*op.Operand, 0, len(call.Args)+1)
if prev != nil {
operand, err := op.NewExpression(prev).Operand(*p.Control)
if err != nil {
return nil, err
}
operands = append(operands, operand)
}
for i := 0; i < len(call.Args); i++ {
expression, err := p.compileExpr(call.Args[i])
if err != nil {
return nil, err
}
operand, err := expression.Operand(*p.Control)
if err != nil {
return nil, err
}
operands = append(operands, operand)
}
return operands, nil
}
func New(options ...Option) *Planner {
ctl := est.Control(0)
planner := &Planner{
Control: &ctl,
Type: est.NewType(),
selectors: op.NewSelectors(),
cache: newCache(0),
constants: newConstants(),
}
planner.init(options)
return planner
}
func (p *Planner) New() *Planner {
scope := &Planner{
bufferSize: p.bufferSize,
Control: p.Control,
Type: p.Type.Snapshot(),
selectors: p.selectors.Snapshot(),
constants: p.constants,
Functions: p.Functions,
cache: p.cache,
escapeHTML: p.escapeHTML,
}
return scope
}
func (p *Planner) apply(options []Option) {
for _, option := range options {
switch actual := option.(type) {
case BufferSize:
p.bufferSize = int(actual)
case CacheSize:
p.cache = newCache(int(actual))
case EscapeHTML:
p.escapeHTML = bool(actual)
case PanicOnError:
p.panicOnError = bool(actual)
case *op.Functions:
if p.Functions == nil {
p.Functions = actual
}
}
}
}
func (p *Planner) registerConst(i *[]int) {
p.constants.add(i)
}
func (p *Planner) init(options []Option) {
p.apply(options)
if p.Functions == nil {
ifaces := make([]interface{}, 0, len(options))
for _, option := range options {
ifaces = append(ifaces, option)
}
p.Functions = op.NewFunctions(ifaces...)
}
}
func (p *Planner) tryMatchCall(call ast.Expression, selector *op.Selector, ID string) (*op.Selector, ast.Expression, error) {
if call == nil {
return nil, nil, nil
}
matchCall, expression, err := p.matchCall(call, selector, ID)
if err != nil {
return nil, nil, err
}
return matchCall, expression, err
}
func (p *Planner) matchCall(call ast.Expression, selector *op.Selector, ID string) (*op.Selector, ast.Expression, error) {
switch actual := call.(type) {
case *expr.Call:
return p.matchFunc(ID, actual, selector)
case *expr.SliceIndex:
switch selector.Type.Kind() {
case reflect.Map:
mapSelector, err := p.newMapSelector(ID, actual, selector)
if err != nil {
return nil, nil, err
}
return mapSelector, actual.Y, nil
case reflect.Interface:
interfaceSelector, err := p.newInterfaceSelector(ID, actual, selector)
if err != nil {
return nil, nil, err
}
return interfaceSelector, actual.Y, nil
default:
sliceSelector, err := p.newSliceSelector(ID, actual, selector)
if err != nil {
return nil, nil, err
}
return sliceSelector, actual.Y, nil
}
}
return nil, nil, nil
}
func (p *Planner) newSliceSelector(id string, actual *expr.SliceIndex, selector *op.Selector) (*op.Selector, error) {
indexEpression, err := p.compileExpr(actual.X)
if err != nil {
return nil, err
}
operandExpression, err := indexEpression.Operand(*p.Control)
if err != nil {
return nil, err
}
sliceOperand, err := op.NewExpression(selector).Operand(*p.Control)
if err != nil {
return nil, err
}
return op.SliceSelector(id, "", sliceOperand, operandExpression, selector)
}
func (p *Planner) newMapSelector(id string, actual *expr.SliceIndex, selector *op.Selector) (*op.Selector, error) {
keyOperand, err := p.compileOperand(actual.X)
if err != nil {
return nil, err
}
mapOperand, err := op.NewExpression(selector).Operand(*p.Control)
if err != nil {
return nil, err
}
return op.NewMapSelector(id, "", mapOperand, keyOperand, selector)
}
func (p *Planner) newInterfaceSelector(id string, actual *expr.SliceIndex, selector *op.Selector) (*op.Selector, error) {
xOperand, err := op.NewExpression(selector).Operand(*p.Control)
if err != nil {
return nil, err
}
yOperand, err := p.compileOperand(actual.X)
if err != nil {
return nil, err
}
return op.NewInterfaceSelector(id, "", xOperand, yOperand, selector)
}
func (p *Planner) compileOperand(actual ast.Expression) (*op.Operand, error) {
if actual == nil {
return nil, nil
}
xExpr, err := p.compileExpr(actual)
if err != nil {
return nil, err
}
xOperand, err := xExpr.Operand(*p.Control)
if err != nil {
return nil, err
}
return xOperand, nil
}
func (p *Planner) derefHolderSelector(field reflect.StructField) *op.Selector {
return &op.Selector{
ID: "",
Type: field.Type,
Field: xunsafe.NewField(field),
Indirect: true,
ParentOffset: field.Offset,
}
}
func (p *Planner) tryMatchFunc(ID string, x ast.Expression) (*op.Selector, ast.Expression, error) {
call, ok := x.(*expr.Call)
if !ok {
return nil, nil, nil
}
return p.matchFunc(ID, call, nil)
}
func (p *Planner) matchFunc(ID string, actual *expr.Call, selector *op.Selector) (*op.Selector, ast.Expression, error) {
callSelector, err := p.newFuncSelector(ID, ID, actual, selector)
if err != nil {
return nil, nil, err
}
return callSelector, actual.X, nil
}