collectDecls collects const and var declarations from a file. This is used to resolve constant and variable references in metric definitions.
(file *ast.File)
| 322 | // collectDecls collects const and var declarations from a file. |
| 323 | // This is used to resolve constant and variable references in metric definitions. |
| 324 | func collectDecls(file *ast.File) declarations { |
| 325 | decls := declarations{ |
| 326 | strings: make(map[string]string), |
| 327 | stringSlices: make(map[string][]string), |
| 328 | } |
| 329 | |
| 330 | for _, decl := range file.Decls { |
| 331 | genDecl, ok := decl.(*ast.GenDecl) |
| 332 | if !ok { |
| 333 | continue |
| 334 | } |
| 335 | |
| 336 | for _, spec := range genDecl.Specs { |
| 337 | valueSpec, ok := spec.(*ast.ValueSpec) |
| 338 | if !ok { |
| 339 | continue |
| 340 | } |
| 341 | |
| 342 | for i, name := range valueSpec.Names { |
| 343 | if i >= len(valueSpec.Values) { |
| 344 | continue |
| 345 | } |
| 346 | |
| 347 | switch v := valueSpec.Values[i].(type) { |
| 348 | case *ast.BasicLit: |
| 349 | // String literal: const name = "value" |
| 350 | decls.strings[name.Name] = strings.Trim(v.Value, `"`) |
| 351 | case *ast.BinaryExpr: |
| 352 | // Concatenation: const name = prefix + "suffix" |
| 353 | if resolved := resolveBinaryExpr(v, decls); resolved != "" { |
| 354 | decls.strings[name.Name] = resolved |
| 355 | } |
| 356 | case *ast.CompositeLit: |
| 357 | // Slice literal: var labels = []string{"a", "b"} |
| 358 | if resolved := extractStringSlice(v, decls); resolved != nil { |
| 359 | decls.stringSlices[name.Name] = resolved |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | return decls |
| 367 | } |
| 368 | |
| 369 | // extractLabels extracts label names from an expression passed as an argument |
| 370 | // to a metric constructor. Handles both inline []string literals and |
no test coverage detected