package unit; /** * GoInferTest — CWE-407 unit test for go-0001 * * Models the O(n) slices.Index membership check in tpWalker.isParameterized * (src/cmd/compile/internal/types2/infer.go:630) that fires for every TypeParam * node during type inference. * * slow(): simulates tpWalker with slice-based tparams — O(n) scan per lookup. * fast(): simulates tpWalker with map-based tparams — O(1) lookup. * * Both perform QUERIES * TPARAMS membership checks (same logical work). * We assert slow() requires >= 5x more comparisons than fast(). */ public class GoInferTest { static final int TPARAMS = 200; // type parameters in a large generic function static final int QUERIES = 500; // TypeParam nodes visited during walk static final int N = 5; // minimum speedup factor required /** * Slow path: slice-based tparams lookup (mirrors slices.Index). * For each query, scans from index 0 until the target is found. * Returns total number of element comparisons performed. */ static long slow() { // Build tparams slice (indices 0..TPARAMS-1) int[] tparams = new int[TPARAMS]; for (int i = 0; i < TPARAMS; i++) tparams[i] = i; long ops = 0; // Simulate QUERIES lookups — target is the last element (worst case) for (int q = 0; q < QUERIES; q++) { int target = TPARAMS - 1; // worst case: found at end for (int i = 0; i < tparams.length; i++) { ops++; if (tparams[i] == target) break; } } return ops; } /** * Fast path: map-based tparams lookup (mirrors map[*TypeParam]bool). * Each query is O(1) hash lookup. We simulate this by tracking * exactly 1 "probe" per lookup (hash table amortized cost). */ static long fast() { // Build tparams set java.util.HashSet tparams = new java.util.HashSet<>(); for (int i = 0; i < TPARAMS; i++) tparams.add(i); long ops = 0; for (int q = 0; q < QUERIES; q++) { int target = TPARAMS - 1; // Simulate O(1) hash lookup: count 1 operation per query ops++; tparams.contains(target); } return ops; } public static void main(String[] args) { long sOps = slow(); long fOps = fast(); System.out.println("slow ops: " + sOps); System.out.println("fast ops: " + fOps); System.out.println("ratio: " + sOps + "/" + fOps + " = " + (sOps / fOps) + "x"); // slow must be >= N times more expensive than fast if (sOps < fOps * N) { System.out.println("1/1 FAIL — expected slowOps >= " + N + "x fastOps, got ratio=" + (sOps / fOps)); System.exit(1); } System.out.println("1/1 PASS"); } }