github.com/blueinnovationsgroup/can-go@v0.0.0-20230518195432-d0567cda0028/pkg/dbc/analysis/passes/boolprefix/analyzer.go (about)

     1  package boolprefix
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/blueinnovationsgroup/can-go/pkg/dbc"
     7  	"github.com/blueinnovationsgroup/can-go/pkg/dbc/analysis"
     8  )
     9  
    10  func Analyzer() *analysis.Analyzer {
    11  	return &analysis.Analyzer{
    12  		Name: "boolprefix",
    13  		Doc:  "check that bools (1-bit signals) have a correct prefix",
    14  		Run:  run,
    15  	}
    16  }
    17  
    18  func allowedPrefixes() []string {
    19  	return []string{
    20  		"Is",
    21  		"Has",
    22  	}
    23  }
    24  
    25  func run(pass *analysis.Pass) error {
    26  	for _, d := range pass.File.Defs {
    27  		messageDef, ok := d.(*dbc.MessageDef)
    28  		if !ok {
    29  			continue
    30  		}
    31  	SignalLoop:
    32  		for _, signalDef := range messageDef.Signals {
    33  			if signalDef.Size != 1 {
    34  				continue // skip all non-bool signals
    35  			}
    36  			for _, allowedPrefix := range allowedPrefixes() {
    37  				if strings.HasPrefix(string(signalDef.Name), allowedPrefix) {
    38  					continue SignalLoop // has allowed prefix
    39  				}
    40  			}
    41  			// edge-case: allow non-prefixed 1-bit signals with value descriptions
    42  			for _, d := range pass.File.Defs {
    43  				valueDescriptionsDef, ok := d.(*dbc.ValueDescriptionsDef)
    44  				if !ok {
    45  					continue // not value descriptions
    46  				}
    47  				if valueDescriptionsDef.MessageID == messageDef.MessageID &&
    48  					valueDescriptionsDef.SignalName == signalDef.Name {
    49  					continue SignalLoop // has value descriptions
    50  				}
    51  			}
    52  			pass.Reportf(
    53  				signalDef.Pos,
    54  				"bool signals (1-bit) must have prefix %s",
    55  				strings.Join(allowedPrefixes(), " or "),
    56  			)
    57  		}
    58  	}
    59  	return nil
    60  }