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

     1  package singletondefinitions
     2  
     3  import (
     4  	"reflect"
     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: "singletondefinitions",
    13  		Doc:  "check that the file contains at most one of all singleton definitions",
    14  		Run:  run,
    15  	}
    16  }
    17  
    18  func singletonDefinitions() []dbc.Def {
    19  	return []dbc.Def{
    20  		&dbc.VersionDef{},
    21  		&dbc.NewSymbolsDef{},
    22  		&dbc.BitTimingDef{},
    23  		&dbc.NodesDef{},
    24  	}
    25  }
    26  
    27  func run(pass *analysis.Pass) error {
    28  	defsByType := make(map[reflect.Type][]dbc.Def)
    29  	for _, def := range pass.File.Defs {
    30  		t := reflect.TypeOf(def)
    31  		defsByType[t] = append(defsByType[t], def)
    32  	}
    33  	for _, singletonDef := range singletonDefinitions() {
    34  		singletonDefs := defsByType[reflect.TypeOf(singletonDef)]
    35  		if len(singletonDefs) > 1 {
    36  			for i := 1; i < len(singletonDefs); i++ {
    37  				pass.Reportf(singletonDefs[i].Position(), "more than one definition not allowed")
    38  			}
    39  		}
    40  	}
    41  	return nil
    42  }