-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctionPaths.php
More file actions
96 lines (81 loc) · 2.87 KB
/
Copy pathFunctionPaths.php
File metadata and controls
96 lines (81 loc) · 2.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
declare(strict_types=1);
namespace Paths;
use function \ast\parse_file;
use function \ast\get_version;
use Paths\FunctionScanner;
use Paths\GraphNodeVisitor;
use Paths\Path;
class FunctionPaths
{
private string $function_name;
/** @var array<Path> */
private array $paths = [];
private ?int $max_length = null;
private ?float $sample_rate = null;
/** @param $paths array<Path> */
public function __construct(string $function_name, ?int $max_length = null)
{
$this->function_name = $function_name;
$this->max_length = $max_length;
}
public function appendPath(Path $path): void
{
if ($this->sample_rate === null) {
$this->paths[] = $path;
} else {
if (rand(0, 1000) / 1000.0 <= $this->sample_rate) {
$this->paths[] = $path;
}
}
// Once we break 2x the max paths, randomly cut it in half and start
// sampling at 50%
if ($this->max_length !== null) {
if (count($this->paths) == (2 * $this->max_length)) {
// Cut the sample rate in half
$this->sample_rate = ($this->sample_rate ?? 1.0) / 2.0;
// Trim off a random 50% of existing paths. This will
// produce the same fair distribution as if the sample
// rate had been it's current value from the beginning.
$paths = $this->paths;
shuffle($paths);
$this->paths = array_values(array_slice($paths, 0, $this->max_length));
}
}
}
/**
* @return \Generator<FunctionPaths>
*/
public static function fromFileName(string $file_name, bool $use_node_ids = false, ?int $max_length = null): \Generator
{
$ast = parse_file($file_name, get_version());
foreach ((new FunctionScanner())($ast) as $function_ast) {
$function_path = new FunctionPaths($function_ast->children['name'] ?? 'anonymous', $max_length);
foreach ((new GraphNodeVisitor(null, $use_node_ids))($function_ast)->allTerminals() as $terminal) {
foreach ($terminal->allPathsToOtherTerminals() as $path) {
$function_path->appendPath($path);
}
}
yield $function_path;
}
}
public function isEmpty(): bool
{
return empty($this->paths);
}
public function toString(): string
{
if ($this->isEmpty()) {
return '';
}
$paths = $this->paths;
if ($this->max_length !== null && count($paths) > $this->max_length) {
shuffle($paths);
$paths = array_slice($paths, 0, $this->max_length);
}
return implode(' ', [
$this->function_name,
implode(' ', array_map(fn (Path $path) => $path->__toString(), $paths))
]);
}
}