github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/pkg/caveats/structure.go (about)

     1  package caveats
     2  
     3  import (
     4  	"fmt"
     5  
     6  	exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
     7  
     8  	"github.com/authzed/spicedb/pkg/genutil/mapz"
     9  )
    10  
    11  // referencedParameters traverses the expression given and finds all parameters which are referenced
    12  // in the expression for the purpose of usage tracking.
    13  func referencedParameters(definedParameters *mapz.Set[string], expr *exprpb.Expr, referencedParams *mapz.Set[string]) {
    14  	if expr == nil {
    15  		return
    16  	}
    17  
    18  	switch t := expr.ExprKind.(type) {
    19  	case *exprpb.Expr_ConstExpr:
    20  		// nothing to do
    21  
    22  	case *exprpb.Expr_IdentExpr:
    23  		if definedParameters.Has(t.IdentExpr.Name) {
    24  			referencedParams.Add(t.IdentExpr.Name)
    25  		}
    26  
    27  	case *exprpb.Expr_SelectExpr:
    28  		referencedParameters(definedParameters, t.SelectExpr.Operand, referencedParams)
    29  
    30  	case *exprpb.Expr_CallExpr:
    31  		referencedParameters(definedParameters, t.CallExpr.Target, referencedParams)
    32  		for _, arg := range t.CallExpr.Args {
    33  			referencedParameters(definedParameters, arg, referencedParams)
    34  		}
    35  
    36  	case *exprpb.Expr_ListExpr:
    37  		for _, elem := range t.ListExpr.Elements {
    38  			referencedParameters(definedParameters, elem, referencedParams)
    39  		}
    40  
    41  	case *exprpb.Expr_StructExpr:
    42  		for _, entry := range t.StructExpr.Entries {
    43  			referencedParameters(definedParameters, entry.Value, referencedParams)
    44  		}
    45  
    46  	case *exprpb.Expr_ComprehensionExpr:
    47  		referencedParameters(definedParameters, t.ComprehensionExpr.AccuInit, referencedParams)
    48  		referencedParameters(definedParameters, t.ComprehensionExpr.IterRange, referencedParams)
    49  		referencedParameters(definedParameters, t.ComprehensionExpr.LoopCondition, referencedParams)
    50  		referencedParameters(definedParameters, t.ComprehensionExpr.LoopStep, referencedParams)
    51  		referencedParameters(definedParameters, t.ComprehensionExpr.Result, referencedParams)
    52  
    53  	default:
    54  		panic(fmt.Sprintf("unknown CEL expression kind: %T", t))
    55  	}
    56  }