github.com/oam-dev/kubevela@v1.9.11/references/cuegen/util.go (about)

     1  /*
     2  Copyright 2023 The KubeVela Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package cuegen
    18  
    19  import (
    20  	"fmt"
    21  	gotypes "go/types"
    22  	"strconv"
    23  
    24  	cueast "cuelang.org/go/cue/ast"
    25  	cuetoken "cuelang.org/go/cue/token"
    26  )
    27  
    28  // Ident returns a new cue identifier with the given name.
    29  func Ident(name string, isDef bool) *cueast.Ident {
    30  	if isDef {
    31  		name = "#" + name
    32  	}
    33  	return cueast.NewIdent(name)
    34  }
    35  
    36  func basicType(x *gotypes.Basic) cueast.Expr {
    37  	// byte is an alias for uint8 in go/types
    38  
    39  	switch t := x.String(); t {
    40  	case "uintptr":
    41  		return Ident("uint64", false)
    42  	case "byte":
    43  		return Ident("uint8", false)
    44  	default:
    45  		return Ident(t, false)
    46  	}
    47  }
    48  
    49  func basicLabel(t *gotypes.Basic, v string) (cueast.Expr, error) {
    50  	switch {
    51  	case t.Info()&gotypes.IsInteger != 0:
    52  		if _, err := strconv.ParseInt(v, 10, 64); err != nil {
    53  			return nil, err
    54  		}
    55  		return &cueast.BasicLit{Kind: cuetoken.INT, Value: v}, nil
    56  	case t.Info()&gotypes.IsFloat != 0:
    57  		if _, err := strconv.ParseFloat(v, 64); err != nil {
    58  			return nil, err
    59  		}
    60  		return &cueast.BasicLit{Kind: cuetoken.FLOAT, Value: v}, nil
    61  	case t.Info()&gotypes.IsBoolean != 0:
    62  		b, err := strconv.ParseBool(v)
    63  		if err != nil {
    64  			return nil, err
    65  		}
    66  		return cueast.NewBool(b), nil
    67  	case t.Info()&gotypes.IsString != 0:
    68  		return cueast.NewString(v), nil
    69  	default:
    70  		return nil, fmt.Errorf("unsupported basic type %s", t)
    71  	}
    72  }