github.com/joomcode/cue@v0.4.4-0.20221111115225-539fe3512047/internal/core/adt/comprehension.go (about)

     1  // Copyright 2021 CUE Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package adt
    16  
    17  type envYield struct {
    18  	comp *Comprehension
    19  	env  *Environment
    20  	id   CloseInfo
    21  	err  *Bottom
    22  }
    23  
    24  func (n *nodeContext) insertComprehension(env *Environment, x *Comprehension, ci CloseInfo) {
    25  	n.comprehensions = append(n.comprehensions, envYield{x, env, ci, nil})
    26  }
    27  
    28  // injectComprehensions evaluates and inserts comprehensions.
    29  func (n *nodeContext) injectComprehensions(all *[]envYield) (progress bool) {
    30  	ctx := n.ctx
    31  
    32  	k := 0
    33  	for i := 0; i < len(*all); i++ {
    34  		d := (*all)[i]
    35  
    36  		sa := []*Environment{}
    37  		f := func(env *Environment) {
    38  			sa = append(sa, env)
    39  		}
    40  
    41  		if err := ctx.Yield(d.env, d.comp, f); err != nil {
    42  			if err.IsIncomplete() {
    43  				d.err = err
    44  				(*all)[k] = d
    45  				k++
    46  			} else {
    47  				// continue to collect other errors.
    48  				n.addBottom(err)
    49  			}
    50  			continue
    51  		}
    52  
    53  		if len(sa) == 0 {
    54  			continue
    55  		}
    56  		id := d.id.SpawnSpan(d.comp.Clauses, ComprehensionSpan)
    57  
    58  		n.ctx.nonMonotonicInsertNest++
    59  		for _, env := range sa {
    60  			n.addExprConjunct(Conjunct{env, d.comp.Value, id})
    61  		}
    62  		n.ctx.nonMonotonicInsertNest--
    63  	}
    64  
    65  	progress = k < len(*all)
    66  
    67  	*all = (*all)[:k]
    68  
    69  	return progress
    70  }