| 371 | } |
| 372 | |
| 373 | func variableNode(depth int) string { |
| 374 | // Generate 1-3 variable declarations with diverse names and then make sure |
| 375 | // at least one of them is used in the final expression. |
| 376 | namesPool := []string{"x", "y", "z", "foo", "bar", "foobar", "tmp"} |
| 377 | nDecls := oneOf(list[int]{ |
| 378 | {1, 60}, |
| 379 | {2, 30}, |
| 380 | {3, 10}, |
| 381 | }) |
| 382 | |
| 383 | var decls []string |
| 384 | var chosen []string |
| 385 | for i := 0; i < nDecls; i++ { |
| 386 | name := random(namesPool) |
| 387 | chosen = append(chosen, name) |
| 388 | decls = append(decls, fmt.Sprintf("let %s = %v", name, node(depth-1))) |
| 389 | } |
| 390 | |
| 391 | // Build a usage expression that references declared vars to guarantee coverage. |
| 392 | use := oneOf(list[string]{ |
| 393 | {chosen[0], 50}, |
| 394 | {fmt.Sprintf("%s + %v", chosen[0], node(depth-1)), 30}, |
| 395 | {fmt.Sprintf("%v + %s", node(depth-1), chosen[0]), 30}, |
| 396 | {fmt.Sprintf("if %v { %s } else { %v }", node(depth-1), chosen[0], node(depth-1)), 20}, |
| 397 | {fmt.Sprintf("%s ? %v : %v", chosen[0], node(depth-1), node(depth-1)), 10}, |
| 398 | }) |
| 399 | |
| 400 | return fmt.Sprintf("%s; %s", strings.Join(decls, "; "), use) |
| 401 | } |