...

Source file src/github.com/bazelbuild/buildtools/build/utils.go

Documentation: github.com/bazelbuild/buildtools/build

     1  /*
     2  Copyright 2021 Google LLC
     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      https://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 build
    18  
    19  // GetParamName extracts the param name from an item of function params.
    20  func GetParamName(param Expr) (name, op string) {
    21  	ident, op := GetParamIdent(param)
    22  	if ident == nil {
    23  		return "", ""
    24  	}
    25  	return ident.Name, op
    26  }
    27  
    28  // GetParamIdent extracts the param identifier from an item of function params.
    29  func GetParamIdent(param Expr) (ident *Ident, op string) {
    30  	switch param := param.(type) {
    31  	case *Ident:
    32  		return param, ""
    33  	case *TypedIdent:
    34  		return param.Ident, ""
    35  	case *AssignExpr:
    36  		// keyword parameter
    37  		return GetParamIdent(param.LHS)
    38  	case *UnaryExpr:
    39  		// *args, **kwargs, or *
    40  		if param.X == nil {
    41  			// An asterisk separating position and keyword-only arguments
    42  			break
    43  		}
    44  		ident, _ := GetParamIdent(param.X)
    45  		return ident, param.Op
    46  	}
    47  	return nil, ""
    48  }
    49  
    50  // GetTypes returns the list of types defined by the a given expression.
    51  // Examples:
    52  //
    53  // List[tuple[bool, int]] should return [List, Tuple, bool, int]
    54  // str should return str
    55  func GetTypes(t Expr) []string {
    56  	switch t := t.(type) {
    57  	case *TypedIdent:
    58  		return GetTypes(t.Type)
    59  	case *Ident:
    60  		return []string{t.Name}
    61  	case *DefStmt:
    62  		ret := GetTypes(t.Type)
    63  		params := make([]string, 0)
    64  		for _, p := range t.Params {
    65  			params = append(params, GetTypes(p)...)
    66  		}
    67  		return append(ret, params...)
    68  	case *IndexExpr:
    69  		left := GetTypes(t.X)
    70  		right := GetTypes(t.Y)
    71  		return append(left, right...)
    72  	case *DotExpr:
    73  		// Special handling for skylark-rust interpreter, types are referred to by a `.type` suffix
    74  		if t.Name == "type" {
    75  			return GetTypes(t.X)
    76  		}
    77  		return []string{}
    78  	default:
    79  		return []string{}
    80  	}
    81  }
    82  

View as plain text