cuelang.org/go@v0.10.1/internal/value/value.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 value contains functions for converting values to internal types 16 // and various other Value-related utilities. 17 package value 18 19 import ( 20 "strings" 21 22 "cuelang.org/go/cue" 23 "cuelang.org/go/internal/core/adt" 24 "cuelang.org/go/internal/core/convert" 25 "cuelang.org/go/internal/core/eval" 26 "cuelang.org/go/internal/core/runtime" 27 "cuelang.org/go/internal/types" 28 ) 29 30 func ConvertToRuntime(c *cue.Context) *cue.Runtime { 31 return (*cue.Runtime)(c) 32 } 33 34 func ConvertToContext[Ctx *cue.Runtime | *cue.Context](ctx Ctx) *cue.Context { 35 if ctx, ok := any(ctx).(*cue.Runtime); ok { 36 (*runtime.Runtime)(ctx).Init() 37 } 38 return (*cue.Context)(ctx) 39 } 40 41 func ToInternal(v cue.Value) (*runtime.Runtime, *adt.Vertex) { 42 var t types.Value 43 v.Core(&t) 44 return t.R, t.V 45 } 46 47 // Make wraps cue.MakeValue. 48 func Make(ctx *adt.OpContext, v adt.Value) cue.Value { 49 return (*cue.Context)(ctx.Impl().(*runtime.Runtime)).Encode(v) 50 } 51 52 // UnifyBuiltin returns the given Value unified with the given builtin template. 53 func UnifyBuiltin(v cue.Value, kind string) cue.Value { 54 pkg, name, _ := strings.Cut(kind, ".") 55 s := runtime.SharedRuntime.LoadImport(pkg) 56 if s == nil { 57 return v 58 } 59 60 ctx := v.Context() 61 a := s.Lookup((*runtime.Runtime)(ctx).Label(name, false)) 62 if a == nil { 63 return v 64 } 65 66 return v.Unify(ctx.Encode(a)) 67 } 68 69 func FromGoValue(r *cue.Context, x interface{}, nilIsTop bool) cue.Value { 70 rt := (*runtime.Runtime)(r) 71 rt.Init() 72 ctx := eval.NewContext(rt, nil) 73 v := convert.GoValueToValue(ctx, x, nilIsTop) 74 n := adt.ToVertex(v) 75 return r.Encode(n) 76 } 77 78 func FromGoType(r *cue.Context, x interface{}) cue.Value { 79 rt := (*runtime.Runtime)(r) 80 rt.Init() 81 ctx := eval.NewContext(rt, nil) 82 expr, err := convert.GoTypeToExpr(ctx, x) 83 if err != nil { 84 expr = &adt.Bottom{Err: err} 85 } 86 n := &adt.Vertex{} 87 n.AddConjunct(adt.MakeRootConjunct(nil, expr)) 88 return r.Encode(n) 89 }