Debian Codegraph @

tools/antithesis-go-instrumentor/scanners/assertions/assertion_scanner.go

raw
1 package assertions
2
3 import (
4 "fmt"
5 "go/ast"
6 "go/token"
7 "go/types"
8 "path/filepath"
9 "strconv"
10 "strings"
11 "time"
12
13 "github.com/antithesishq/antithesis-sdk-go/tools/antithesis-go-instrumentor/common"
14 "golang.org/x/tools/go/packages"
15 )
16
17 type AntExpect struct {
18 *AssertionFuncInfo
19 Assertion string
20 Message string
21 Classname string
22 Funcname string
23 Receiver string
24 Filename string
25 Line int
26 }
27
28 type AntGuidance struct {
29 *GuidanceFuncInfo
30 Assertion string
31 Message string
32 Classname string
33 Funcname string
34 Receiver string
35 Filename string
36 Line int
37 }
38
39 // AssertionScanner scans Go packages using go/packages to find assertion
40 // and guidance calls, producing per-binary catalog data.
41 type AssertionScanner struct {
42 assertionHintMap AssertionHints
43 guidanceHintMap GuidanceHints
44 baseInputDir string
45 baseTargetDir string
46 filesCataloged int
47
48 // Results: per-binary catalogs
49 binaries []*binaryCatalog
50 }
51
52 // binaryCatalog represents a discovered main package and its reachable assertions.
53 type binaryCatalog struct {
54 dir string // absolute path of the main package directory
55 relDir string // directory relative to the module root
56 expects []*AntExpect
57 guidance []*AntGuidance
58 }
59
60 func (bc *binaryCatalog) hasAssertions() bool {
61 return len(bc.expects) > 0 || len(bc.guidance) > 0
62 }
63
64 // PackageSyntax is everything cataloguing needs to know about one package: its
65 // import path, position information, and resolved type information. Assertion
66 // calls can only be identified with types
67 type PackageSyntax struct {
68 PkgPath string
69 Fset *token.FileSet
70 TypesInfo *types.Info
71 Files []*ast.File
72 }
73
74 // PackageResult is the catalog data found in a single package.
75 type PackageResult struct {
76 Expects []*AntExpect
77 Guidance []*AntGuidance
78 }
79
80 // HasAssertions reports whether anything was found worth cataloguing.
81 func (pr *PackageResult) HasAssertions() bool {
82 return len(pr.Expects) > 0 || len(pr.Guidance) > 0
83 }
84
85 // NumericGuidance filters guidance entries to the numeric kind.
86 func NumericGuidance(guidance []*AntGuidance) []*AntGuidance { return numericGuidance(guidance) }
87
88 // BooleanGuidance filters guidance entries to the boolean kind.
89 func BooleanGuidance(guidance []*AntGuidance) []*AntGuidance { return booleanGuidance(guidance) }
90
91 // ConstMap reports which template constants a set of assertions needs declared.
92 func ConstMap(expects []*AntExpect) map[string]bool { return getConstMap(expects) }
93
94 // filter Guidance to just numeric
95 func numericGuidance(guidance []*AntGuidance) []*AntGuidance {
96 numeric_guidance := []*AntGuidance{}
97 for _, aG := range guidance {
98 gp := aG.GuidanceFn
99 if gp == GuidanceFnMaximize || gp == GuidanceFnMinimize {
100 numeric_guidance = append(numeric_guidance, aG)
101 }
102 }
103 return numeric_guidance
104 }
105
106 // filter Guidance to just boolean
107 func booleanGuidance(guidance []*AntGuidance) []*AntGuidance {
108 boolean_guidance := []*AntGuidance{}
109 for _, aG := range guidance {
110 gp := aG.GuidanceFn
111 if gp == GuidanceFnWantAll || gp == GuidanceFnWantNone {
112 boolean_guidance = append(boolean_guidance, aG)
113 }
114 }
115 return boolean_guidance
116 }
117
118 func NewAssertionScanner(sourceDir string, targetDir string) *AssertionScanner {
119 aScanner := AssertionScanner{
120 baseInputDir: sourceDir,
121 baseTargetDir: targetDir,
122 assertionHintMap: SetupHintMap(),
123 guidanceHintMap: SetupGuidanceHintMap(),
124 filesCataloged: 0,
125 }
126 return &aScanner
127 }
128
129 // HasAssertionsDefined returns true if any binary has assertions.
130 func (aScanner *AssertionScanner) HasAssertionsDefined() bool {
131 for _, bc := range aScanner.binaries {
132 if bc.hasAssertions() {
133 return true
134 }
135 }
136 return false
137 }
138
139 // WriteAssertionCatalogs writes one catalog per binary into the appropriate
140 // directory under baseTargetDir. For assert-only mode, baseTargetDir ==
141 // baseInputDir.
142 func (aScanner *AssertionScanner) WriteAssertionCatalogs(versionText string) {
143 now := time.Now()
144 createDate := now.Format("Mon Jan 2 15:04:05 MST 2006")
145
146 for _, bc := range aScanner.binaries {
147 if !bc.hasAssertions() {
148 continue
149 }
150
151 expects := bc.expects
152 numericGuidance := numericGuidance(bc.guidance)
153 booleanGuidance := booleanGuidance(bc.guidance)
154
155 genInfo := GenInfo{
156 ExpectedVals: expects,
157 NumericGuidanceVals: numericGuidance,
158 BooleanGuidanceVals: booleanGuidance,
159 AssertPackageName: common.AssertPackageName(),
160 // The antithesis-go-instrumentor tool operates on a whole program and writes into the `main package`
161 PackageName: "main",
162 VersionText: versionText,
163 CreateDate: createDate,
164 HasAssertions: len(expects) > 0,
165 HasNumericGuidance: len(numericGuidance) > 0,
166 HasBooleanGuidance: len(booleanGuidance) > 0,
167 ConstMap: getConstMap(expects),
168 }
169
170 outputDir := filepath.Join(aScanner.baseTargetDir, bc.relDir)
171 if err := GenerateAssertionsCatalog(outputDir, &genInfo); err != nil {
172 panic(err)
173 }
174 }
175 }
176
177 func (aScanner *AssertionScanner) SummarizeWork() {
178 numCataloged := aScanner.filesCataloged
179 common.Logger.Printf(common.Normal, "%d '.go' %s cataloged", numCataloged, common.Pluralize(numCataloged, "file"))
180 numBinaries := len(aScanner.binaries)
181 catalogsWritten := 0
182 for _, bc := range aScanner.binaries {
183 if bc.hasAssertions() {
184 catalogsWritten++
185 }
186 }
187 common.Logger.Printf(common.Normal, "%d %s discovered, %d %s written",
188 numBinaries, common.Pluralize(numBinaries, "binary"),
189 catalogsWritten, common.Pluralize(catalogsWritten, "catalog"))
190 }
191
192 // ScanAll loads all packages under baseInputDir using go/packages, identifies
193 // main packages, computes per-binary reachability, and scans for assertions.
194 func (aScanner *AssertionScanner) ScanAll() error {
195 cfg := &packages.Config{
196 Mode: packages.NeedName |
197 packages.NeedFiles |
198 packages.NeedTypes |
199 packages.NeedTypesInfo |
200 packages.NeedSyntax |
201 packages.NeedImports |
202 packages.NeedDeps |
203 packages.NeedModule,
204 Dir: aScanner.baseInputDir,
205 }
206
207 common.Logger.Printf(common.Info, "Loading packages from %s", aScanner.baseInputDir)
208
209 pkgs, err := packages.Load(cfg, "./...")
210 if err != nil {
211 return fmt.Errorf("go/packages load failed: %w", err)
212 }
213
214 // Check for package errors
215 var loadErrors []string
216 packages.Visit(pkgs, nil, func(pkg *packages.Package) {
217 for _, e := range pkg.Errors {
218 loadErrors = append(loadErrors, fmt.Sprintf("%s: %s", pkg.PkgPath, e.Msg))
219 }
220 })
221 if len(loadErrors) > 0 {
222 return fmt.Errorf("package load errors:\n %s", strings.Join(loadErrors, "\n "))
223 }
224
225 // Identify main packages
226 var mainPkgs []*packages.Package
227 for _, pkg := range pkgs {
228 if pkg.Name == "main" {
229 mainPkgs = append(mainPkgs, pkg)
230 }
231 }
232
233 if len(mainPkgs) == 0 {
234 common.Logger.Printf(common.Normal, "Warning: no main packages found in %s", aScanner.baseInputDir)
235 return nil
236 }
237
238 common.Logger.Printf(common.Info, "Found %d main %s", len(mainPkgs), common.Pluralize(len(mainPkgs), "package"))
239 for _, pkg := range mainPkgs {
240 common.Logger.Printf(common.Info, " main: %s", pkg.PkgPath)
241 }
242
243 // For each main package, compute reachable packages and scan.
244 // Cache per-package results so shared dependencies are only scanned once.
245 pkgCache := make(map[string]*PackageResult)
246
247 for _, mainPkg := range mainPkgs {
248 common.Logger.Printf(common.Normal, "Cataloging %s", mainPkg.PkgPath)
249 reachable := collectReachable(mainPkg)
250
251 bc := &binaryCatalog{
252 dir: mainPkg.Dir,
253 relDir: aScanner.relativeDir(mainPkg.Dir),
254 }
255 for _, pkg := range reachable {
256 pr, ok := pkgCache[pkg.ID]
257 if !ok {
258 common.Logger.Printf(common.Info, "Scanning %s", pkg.PkgPath)
259 pr = aScanner.ScanPackage(PackageSyntax{
260 PkgPath: pkg.PkgPath,
261 Fset: pkg.Fset,
262 TypesInfo: pkg.TypesInfo,
263 Files: pkg.Syntax,
264 })
265 pkgCache[pkg.ID] = pr
266 }
267 bc.expects = append(bc.expects, pr.Expects...)
268 bc.guidance = append(bc.guidance, pr.Guidance...)
269 }
270 aScanner.binaries = append(aScanner.binaries, bc)
271
272 common.Logger.Printf(common.Info, "Binary %s: %d assertions, %d guidance entries",
273 bc.relDir, len(bc.expects), len(bc.guidance))
274 }
275
276 return nil
277 }
278
279 // ScanPackage catalogs one already-parsed, already-type-checked package
280 func (aScanner *AssertionScanner) ScanPackage(pkg PackageSyntax) *PackageResult {
281 result := &PackageResult{}
282 for _, file := range pkg.Files {
283 aScanner.filesCataloged++
284 funcName := ""
285 receiver := ""
286 ast.Inspect(file, func(x ast.Node) bool {
287 funcName, receiver = aScanner.node_inspector(x, pkg, common.AssertPackageName(), result, funcName, receiver)
288 return true
289 })
290 }
291 return result
292 }
293
294 func (aScanner *AssertionScanner) node_inspector(x ast.Node, pkg PackageSyntax, assertPkgPath string, data *PackageResult, funcName string, receiver string) (string, string) {
295 var func_decl *ast.FuncDecl
296 var call_expr *ast.CallExpr
297 var ok bool
298
299 // Track current funcName and receiver (type)
300 if func_decl, ok = x.(*ast.FuncDecl); ok {
301 funcName = common.NAME_NOT_AVAILABLE
302 if func_ident := func_decl.Name; func_ident != nil {
303 funcName = func_ident.Name
304 }
305 receiver = ""
306 if recv := func_decl.Recv; recv != nil {
307 if num_fields := recv.NumFields(); num_fields > 0 {
308 if field_list := recv.List; field_list != nil {
309 if recv_type := field_list[0].Type; recv_type != nil {
310 receiver = types.ExprString(recv_type)
311 }
312 }
313 }
314 }
315 }
316
317 if call_expr, ok = x.(*ast.CallExpr); ok {
318 var sel_expr *ast.SelectorExpr
319 if sel_expr, ok = call_expr.Fun.(*ast.SelectorExpr); ok {
320 // Use type info to resolve the called function
321 // in the SDK assert package
322 obj := pkg.TypesInfo.Uses[sel_expr.Sel]
323 if obj == nil {
324 return funcName, receiver
325 }
326
327 fn, ok := obj.(*types.Func)
328 if !ok {
329 return funcName, receiver
330 }
331
332 if fn.Pkg() == nil || fn.Pkg().Path() != assertPkgPath {
333 return funcName, receiver
334 }
335
336 target_func := fn.Name()
337 full_position := pkg.Fset.Position(sel_expr.Pos())
338 relative_file_path := aScanner.relativeDir(full_position.Filename)
339 packageName := pkg.PkgPath
340 call_args := call_expr.Args
341
342 if func_hints := aScanner.assertionHintMap.HintsForName(target_func); func_hints != nil {
343 test_name := arg_at_index(call_args, func_hints.MessageArg)
344 if test_name == common.NAME_NOT_AVAILABLE {
345 generated_msg := fmt.Sprintf("%s[%d]", relative_file_path, full_position.Line)
346 test_name = fmt.Sprintf("Message from %s", strconv.Quote(generated_msg))
347 }
348 expect := AntExpect{
349 Assertion: target_func,
350 Message: test_name,
351 Classname: packageName,
352 Funcname: funcName,
353 Receiver: receiver,
354 Filename: relative_file_path,
355 Line: full_position.Line,
356 AssertionFuncInfo: func_hints,
357 }
358 data.Expects = append(data.Expects, &expect)
359 }
360
361 if guidance_func_hints := aScanner.guidanceHintMap.GuidanceHintsForName(target_func); guidance_func_hints != nil {
362 test_name := arg_at_index(call_args, guidance_func_hints.MessageArg)
363 if test_name == common.NAME_NOT_AVAILABLE {
364 generated_msg := fmt.Sprintf("%s[%d]", relative_file_path, full_position.Line)
365 test_name = fmt.Sprintf("Message from %s", strconv.Quote(generated_msg))
366 }
367 // The registration for the Guidance function itself
368 guidance_expect := AntGuidance{
369 Assertion: target_func,
370 Message: test_name,
371 Classname: packageName,
372 Funcname: funcName,
373 Receiver: receiver,
374 Filename: relative_file_path,
375 Line: full_position.Line,
376 GuidanceFuncInfo: guidance_func_hints,
377 }
378 data.Guidance = append(data.Guidance, &guidance_expect)
379
380 // The Related Assertion derived from target_func("AlwaysGreaterThan") => derived_target_func("Always")
381 expect := AntExpect{
382 Assertion: target_func_from_guidance(target_func),
383 Message: test_name,
384 Classname: packageName,
385 Funcname: funcName,
386 Receiver: receiver,
387 Filename: relative_file_path,
388 Line: full_position.Line,
389 // NOTE: AssertionFuncInfo.TargetFunc is a guidance func name
390 // and AssertionFuncInfo.MessageArg refers to a Guidance Function argument number.
391 //
392 // GenerateAssertionsCatalog() does not use either of TargetFunc or MessageArg
393 // attributes of AssertionFuncInfo, so it is safe to pass the AssertionFuncInfo
394 // from the guidance func here.
395 AssertionFuncInfo: &guidance_func_hints.AssertionFuncInfo,
396 }
397 data.Expects = append(data.Expects, &expect)
398 } // assertionHint
399 }
400 }
401 return funcName, receiver
402 }
403
404 func (aScanner *AssertionScanner) relativeDir(dir string) string {
405 rel, err := filepath.Rel(aScanner.baseInputDir, dir)
406 if err != nil {
407 return dir
408 }
409 return rel
410 }
411
412 // collectReachable returns all packages transitively reachable from pkg
413 // that belong to the same module. Packages from the standard library or
414 // other modules are skipped.
415 func collectReachable(pkg *packages.Package) []*packages.Package {
416 if pkg.Module == nil {
417 return nil
418 }
419 modulePath := pkg.Module.Path
420
421 visited := make(map[string]bool)
422 var result []*packages.Package
423
424 var walk func(p *packages.Package)
425 walk = func(p *packages.Package) {
426 if visited[p.ID] {
427 return
428 }
429 visited[p.ID] = true
430 if p.Module == nil || p.Module.Path != modulePath {
431 return
432 }
433 result = append(result, p)
434 for _, imp := range p.Imports {
435 walk(imp)
436 }
437 }
438 walk(pkg)
439 return result
440 }
441
442 func target_func_from_guidance(guidance_func string) string {
443 target_func := ""
444 if strings.HasPrefix(guidance_func, "Always") {
445 target_func = "Always"
446 } else if strings.HasPrefix(guidance_func, "Sometimes") {
447 target_func = "Sometimes"
448 }
449 return target_func
450 }
451
452 func arg_at_index(args []ast.Expr, idx int) string {
453 if args == nil || idx < 0 || len(args) <= idx {
454 return common.NAME_NOT_AVAILABLE
455 }
456 arg := args[idx]
457
458 var basic_lit *ast.BasicLit
459 var basic_lit2 *ast.BasicLit
460 var ident *ast.Ident
461 var value_spec *ast.ValueSpec
462 var ok bool
463
464 // A string literal was provided - nice
465 if basic_lit, ok = arg.(*ast.BasicLit); ok {
466 text, _ := strconv.Unquote(basic_lit.Value)
467 return text
468 }
469
470 // Not so nice.
471 // A reference to a const or a var or an indexed value was provided
472 //
473 // Dig in and see if is resolvable at compile-time
474 // When a const is declared in another file, it might not be available here
475 if ident, ok = arg.(*ast.Ident); ok {
476 if ident.Obj == nil || ident.Obj.Decl == nil {
477 return ident.String()
478 }
479 if value_spec, ok = ident.Obj.Decl.(*ast.ValueSpec); ok {
480 values := value_spec.Values
481 if len(values) > 0 {
482 this_value := values[0]
483 if basic_lit2, ok = this_value.(*ast.BasicLit); ok {
484 const_text, _ := strconv.Unquote(basic_lit2.Value)
485 return const_text
486 }
487 }
488 }
489 }
490 return common.NAME_NOT_AVAILABLE
491 }
492
493 const (
494 Cond_false = iota
495 Cond_true
496 Was_hit
497 Not_hit
498 Must_be_hit
499 Optionally_hit
500 Universal_test
501 Existential_test
502 Reachability_test
503 Num_conditions
504 )
505
506 // --------------------------------------------------------------------------------
507 // The 'ConstMap' is used by GenerateAssertionsCatalog to define the
508 // go constants referenced in the registration statements
509 // that are generated.
510 //
511 // This will prevent go build warnings/errors related to defining
512 // a const that is not actually used anywhere.
513 //
514 // Example, if none of the generated registrations use an AssertType
515 // "reachability", then the corresponding go const should not be
516 // output to the generated Assertions Catalog '.go' file.
517 // --------------------------------------------------------------------------------
518 func getConstMap(expects []*AntExpect) map[string]bool {
519 cond_tracker := make([]bool, Num_conditions)
520 if len(expects) > 0 {
521 cond_tracker[Not_hit] = true
522 }
523 for _, an_expect := range expects {
524 pAFI := an_expect.AssertionFuncInfo
525 if pAFI.MustHit {
526 cond_tracker[Must_be_hit] = true
527 } else {
528 cond_tracker[Optionally_hit] = true
529 }
530 if pAFI.Condition {
531 cond_tracker[Cond_true] = true
532 } else {
533 cond_tracker[Cond_false] = true
534 }
535 if pAFI.AssertType == "always" {
536 cond_tracker[Universal_test] = true
537 }
538 if pAFI.AssertType == "sometimes" {
539 cond_tracker[Existential_test] = true
540 }
541 if pAFI.AssertType == "reachability" {
542 cond_tracker[Reachability_test] = true
543 }
544 }
545
546 const_map := make(map[string]bool)
547 const_map["condFalse"] = cond_tracker[Cond_false]
548 const_map["condTrue"] = cond_tracker[Cond_true]
549 const_map["wasHit"] = cond_tracker[Was_hit]
550 const_map["notHit"] = cond_tracker[Not_hit]
551 const_map["mustBeHit"] = cond_tracker[Must_be_hit]
552 const_map["optionallyHit"] = cond_tracker[Optionally_hit]
553 const_map["universalTest"] = cond_tracker[Universal_test]
554 const_map["existentialTest"] = cond_tracker[Existential_test]
555 const_map["reachabilityTest"] = cond_tracker[Reachability_test]
556 return const_map
557 }