repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/phpcb-benchmarks/subclass_vs_cache.php | tools/phpcb-benchmarks/subclass_vs_cache.php | <?php
require __DIR__ . "/../../vendor/autoload.php";
$bench = new \Smuuf\Phpcb\PhpBenchmark;
class FirstParentClass {}
class SecondParentClass {}
class FirstChildClass extends FirstParentClass {}
class SecondChildClass extends SecondParentClass {}
function check_without_cache($className) {
return !is_subclass_of($className, \FirstParentClass::class);
}
function check_with_cache($className) {
static $cache = [];
return $cache[$className] ?? ($cache[$className] = !is_subclass_of($className, \FirstParentClass::class));
}
$bench->addBench(function() {
$x = check_without_cache('\\FirstChildClass');
$y = check_without_cache('\\SecondChildClass'); // Intentionally check child of SecondParentClass
});
$bench->addBench(function() {
$x = check_with_cache('\\FirstChildClass');
$y = check_with_cache('\\SecondChildClass');
});
$bench->run();
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/phpcb-benchmarks/array_list_dict.php | tools/phpcb-benchmarks/array_list_dict.php | #!/usr/bin/env php
<?php
require __DIR__ . "/../../vendor/autoload.php";
$bench = new \Smuuf\Phpcb\PhpBenchmark(new \Smuuf\Phpcb\SerialEngine);
function shuffle_assoc(array $array): array {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
return $new;
}
$arr = [
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 'c'],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm' => 4],
['x' => 100, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm' => 4],
range(0, 100000),
array_merge(...[range(0, 10000), array_fill(50000, 10000, 'x')]),
array_merge(...[range(0, 10000), ['a' => 1, 'b' => 2]]),
[1, 2, 3, 4, 'c' => true, 6, 7, 8, 9],
];
$megaarr = [];
foreach ($arr as $a) {
foreach (range(1, 100) as $_) {
$megaarr[] = shuffle_assoc($a);
}
}
function is_array_dict_A(array $input): bool {
// Let's say that empty PHP array is not a dictionary.
if (!$input) {
return false;
}
return array_keys($input) !== range(0, count($input) - 1);
}
function is_array_dict_B(array $input): bool {
// Let's say that empty PHP array is not a dictionary.
if (!$input) {
return false;
}
$length = count($input);
for ($i = 0; $i < $length; $i++) {
if (!array_key_exists($i, $input)) {
return false;
}
}
return true;
}
function is_array_dict_C(array $input): bool {
// Let's say that empty PHP array is not a dictionary.
if (!$input) {
return false;
}
$c = 0;
foreach ($input as $i => $_) {
if ($c++ !== $i) {
return false;
}
}
return true;
}
$bench->addBench(function() use ($megaarr) {
$results = [];
foreach ($megaarr as $a) {
$results[] = is_array_dict_A($a);
}
return $results;
});
$bench->addBench(function() use ($megaarr) {
$results = [];
foreach ($megaarr as $a) {
$results[] = is_array_dict_B($a);
}
return $results;
});
$bench->addBench(function() use ($megaarr) {
$results = [];
foreach ($megaarr as $a) {
$results[] = is_array_dict_C($a);
}
return $results;
});
$bench->run(50);
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/phpcb-benchmarks/array_pop_check_first.php | tools/phpcb-benchmarks/array_pop_check_first.php | #!/usr/bin/env php
<?php
require __DIR__ . "/../../vendor/autoload.php";
$bench = new \Smuuf\Phpcb\PhpBenchmark(new \Smuuf\Phpcb\SerialEngine);
$arrayFilled = [1, 2, 3, 4, 5];
$arrayEmpty = [];
// Was the winner.
$bench->addBench(function() use ($arrayEmpty) {
if ($arrayEmpty) {
return array_pop($arrayEmpty);
}
return null;
});
$bench->addBench(function() use ($arrayEmpty) {
return array_pop($arrayEmpty);
});
$bench->addBench(function() use ($arrayFilled) {
if ($arrayFilled) {
return array_pop($arrayFilled);
}
return null;
});
$bench->addBench(function() use ($arrayFilled) {
return array_pop($arrayFilled);
});
$bench->run(1e7);
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/phpcb-benchmarks/string_numbers_engines.php | tools/phpcb-benchmarks/string_numbers_engines.php | <?php
require __DIR__ . "/../../vendor/autoload.php";
$bench = new \Smuuf\Phpcb\PhpBenchmark;
$bench->addBench(function() {
$res = [];
$res[] = $x = 123 + 456;
$res[] = $x * 789;
$res[] = $x / 1024;
$res[] = $x - 1024;
$res[] = $x * 123456789;
$res[] = $x * 987654321;
return array_map('intval', $res);
});
$bench->addBench(function() {
$res = [];
$res[] = $x = "123" + "456";
$res[] = $x * "789";
$res[] = $x / "1024";
$res[] = $x - "1024";
$res[] = $x * "123456789";
$res[] = $x * "987654321";
return array_map('intval', $res);
});
$bench->addBench(function() {
$res = [];
$res[] = $x = \bcadd("123", "456");
$res[] = \bcmul($x, "789");
$res[] = \bcdiv($x, "1024");
$res[] = \bcsub($x, "1024");
$res[] = \bcmul($x, "123456789");
$res[] = \bcmul($x, "987654321");
return array_map('intval', $res);
});
$bench->addBench(function() {
$res = [];
$res[] = $x = \gmp_add("123", "456");
$res[] = \gmp_mul($x, "789");
$res[] = \gmp_div($x, "1024");
$res[] = \gmp_sub($x, "1024");
$res[] = \gmp_mul($x, "123456789");
$res[] = \gmp_mul($x, "987654321");
return array_map('intval', $res);
});
$bench->run(1000000);
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/phpcb-benchmarks/empty_bool_vs_array.php | tools/phpcb-benchmarks/empty_bool_vs_array.php | #!/usr/bin/env php
<?php
require __DIR__ . "/../../vendor/autoload.php";
$bench = new \Smuuf\Phpcb\PhpBenchmark;
$emptyList = [];
$nonEmptyList = range(1, 100);
$boolTrue = true;
$boolFalse = false;
$bench->addBench(function() use ($emptyList) {
$x = 0;
if ($emptyList) {
$x += 1;
} else {
$x += 1;
}
});
$bench->addBench(function() use ($nonEmptyList) {
$x = 0;
if ($nonEmptyList) {
$x += 1;
} else {
$x += 1;
}
});
$bench->addBench(function() use ($boolTrue) {
$x = 0;
if ($boolTrue) {
$x += 1;
} else {
$x += 1;
}
});
$bench->addBench(function() use ($boolFalse) {
$x = 0;
if ($boolFalse) {
$x += 1;
} else {
$x += 1;
}
});
$bench->run(1e7);
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/phpcb-benchmarks/if_equality.php | tools/phpcb-benchmarks/if_equality.php | #!/usr/bin/env php
<?php
require __DIR__ . "/../../vendor/autoload.php";
$bench = new \Smuuf\Phpcb\PhpBenchmark(new \Smuuf\Phpcb\SerialEngine);
// Was the winner.
$bench->addBench(function() {
$c = 0;
$z = null;
if (!$z) {
$c++;
}
});
$bench->addBench(function() {
$c = 0;
$z = null;
if ($z === null) {
$c++;
}
});
$bench->addBench(function() {
$c = 0;
$z = true;
if ($z) {
$c++;
}
});
$bench->addBench(function() {
$c = 0;
$z = true;
if ($z === true) {
$c++;
}
});
$bench->run(1e6);
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/phpcb-benchmarks/key_exists_vs_isset.php | tools/phpcb-benchmarks/key_exists_vs_isset.php | <?php
require __DIR__ . "/../../vendor/autoload.php";
$bench = new \Smuuf\Phpcb\PhpBenchmark;
$arr = [...range(50, 500), 'x' => 1, 'y' => 2, 'z' => false, "key" => 1, 'a' => 'b', 'c' => 0];
$arr2 = [...range(50, 500), 'x' => 1, 'y' => 2, 'z' => false, "foo" => 1, 'a' => 'b', 'c' => 0];
$arr3 = [...range(50, 500), 'x' => 1, 'y' => 2, 'z' => false, "key" => null, 'a' => 'b', 'c' => 0];
$bench->addBench(function() use ($arr) {
$x = isset($arr['key']);
});
$bench->addBench(function() use ($arr2) {
$x = isset($arr2['key']);
});
$bench->addBench(function() use ($arr3) {
$x = isset($arr3['key']);
});
$bench->addBench(function() use ($arr) {
$x = array_key_exists("key", $arr);
});
$bench->addBench(function() use ($arr2) {
$x = array_key_exists("key", $arr2);
});
$bench->addBench(function() use ($arr3) {
$x = array_key_exists("key", $arr3);
});
$bench->run();
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/phpcb-benchmarks/string_concat_extrapolate.php | tools/phpcb-benchmarks/string_concat_extrapolate.php | <?php
require __DIR__ . "/../../vendor/autoload.php";
$bench = new \Smuuf\Phpcb\PhpBenchmark;
define('SOME_CONST', md5(random_bytes(100)));
class Something {
public function method(): string {
return md5('whatever');
}
}
$obj = new Something;
$bench->addBench(function() use ($obj) {
return SOME_CONST . '.' . $obj->method();
});
$bench->addBench(function() use ($obj) {
return SOME_CONST . ".{$obj->method()}";
});
// Add more benchmarks...
// Run the benchmark (with default number of iterations)
$bench->run(1e7);
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/phpcb-benchmarks/ifs_just_ifs.php | tools/phpcb-benchmarks/ifs_just_ifs.php | <?php
require __DIR__ . "/../../vendor/autoload.php";
$bench = new \Smuuf\Phpcb\PhpBenchmark(new \Smuuf\Phpcb\SerialEngine);
const FLAG_C_BOOL = true;
define('FLAG_A_INT', 1);
define('FLAG_B_BOOL', true);
abstract class Flagger {
public static $flagAInt = 1;
public static $flagBBool = true;
}
$bench->addBench(function() {
if (FLAG_B_BOOL) {
$x = 1;
}
if (!FLAG_B_BOOL) {
$x = 2;
}
return $x;
});
$bench->addBench(function() {
if (FLAG_A_INT) {
$x = 1;
}
if (!FLAG_A_INT) {
$x = 2;
}
return $x;
});
$bench->addBench(function() {
if (FLAG_C_BOOL) {
$x = 1;
}
if (!FLAG_C_BOOL) {
$x = 2;
}
return $x;
});
$bench->addBench(function() {
if (Flagger::$flagAInt) {
$x = 1;
}
if (!Flagger::$flagAInt) {
$x = 2;
}
return $x;
});
$bench->addBench(function() {
if (Flagger::$flagBBool) {
$x = 1;
}
if (!Flagger::$flagBBool) {
$x = 2;
}
return $x;
});
$bench->run(10000000);
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/phpcb-benchmarks/fn_vs_static_method.php | tools/phpcb-benchmarks/fn_vs_static_method.php | <?php
require __DIR__ . "/../../vendor/autoload.php";
$bench = new \Smuuf\Phpcb\PhpBenchmark;
class SomeClass {
static function doStuff($a, $b, $c = null) {
$x = $a . $b . $c;
if ($x[0] == $a) {
$x = strrev($x);
}
return $x;
}
}
function do_stuff($a, $b, $c = null) {
$x = $a . $b . $c;
if ($x[0] == $a) {
$x = strrev($x);
}
return $x;
}
$bench->addBench(function() {
$x = do_stuff(1, 2, 3);
});
$bench->addBench(function() {
$x = SomeClass::doStuff(1, 2, 3);
});
$bench->run(2000000);
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/phpcb-benchmarks/numeric_int.php | tools/phpcb-benchmarks/numeric_int.php | <?php
require __DIR__ . "/../../vendor/autoload.php";
$bench = new \Smuuf\Phpcb\PhpBenchmark;
$data = [false, '+1', '-1', +1, 0, 1, 42, -1024, 0.2, -0.2, -0.7, 0.7, true, "ahoj", "0.1", "-4.2", "-4.7", "-1000000", "false", "75", "125"];
$bench->addBench(function() use ($data) {
$result = [];
foreach ($data as $x) {
$result[] = (bool) preg_match("#^[+-]?\d+$#", $x);
}
return $result;
});
$bench->addBench(function() use ($data) {
$result = [];
foreach ($data as $x) {
$result[] = (string) (int) $x === (string) \ltrim($x, "+");
}
return $result;
});
$bench->addBench(function() use ($data) {
$result = [];
foreach ($data as $x) {
$result[] = \ctype_digit(\ltrim($x, "+-"));
}
return $result;
});
$bench->run(5e5);
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/phpcb-benchmarks/if_vs_switch.php | tools/phpcb-benchmarks/if_vs_switch.php | <?php
require __DIR__ . "/../../vendor/autoload.php";
$bench = new \Smuuf\Phpcb\PhpBenchmark(new \Smuuf\Phpcb\ChaoticEngine);
const VALUES = [100, false, true, "ahoj", 0, "damn"];
function testA() {
$val = VALUES[array_rand(VALUES)];
if ($val === 100) {
$x = 1;
} elseif ($val === false) {
$x = 1;
} elseif ($val === true) {
$x = 1;
} elseif ($val === "ahoj") {
$x = 1;
} elseif ($val === 0) {
$x = 1;
} elseif ($val === "damn") {
$x = 1;
} else {
$x = 0;
}
return $x;
};
function testB() {
$val = VALUES[array_rand(VALUES)];
switch ($val) {
case 100:
$x = 1;
break;
case false:
$x = 1;
break;
case true:
$x = 1;
break;
case "ahoj":
$x = 1;
break;
case 0:
$x = 1;
break;
case "damn":
$x = 1;
break;
default:
$x = 0;
break;
}
return $x;
};
function testC() {
$val = VALUES[array_rand(VALUES)];
switch (\true) {
case $val === 100:
$x = 1;
break;
case $val === false:
$x = 1;
break;
case $val === true:
$x = 1;
break;
case $val === "ahoj":
$x = 1;
break;
case $val === 0:
$x = 1;
break;
case $val === "damn":
$x = 1;
break;
default:
$x = 0;
break;
}
return $x;
};
function testD() {
$val = VALUES[array_rand(VALUES)];
switch (\true) {
case $val == 100:
$x = 1;
break;
case $val == false:
$x = 1;
break;
case $val == true:
$x = 1;
break;
case $val == "ahoj":
$x = 1;
break;
case $val == 0:
$x = 1;
break;
case $val == "damn":
$x = 1;
break;
default:
$x = 0;
break;
}
return $x;
};
$bench->addBench('testA');
$bench->addBench('testB');
$bench->addBench('testC');
$bench->addBench('testD');
$bench->run(100000);
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/phpcb-benchmarks/if_true_equality.php | tools/phpcb-benchmarks/if_true_equality.php | #!/usr/bin/env php
<?php
require __DIR__ . "/../../vendor/autoload.php";
$bench = new \Smuuf\Phpcb\PhpBenchmark(new \Smuuf\Phpcb\ChaoticEngine);
$bench->addBench(function() {
$c = 0;
$bool = true;
if ($bool) {
$c++;
}
});
$bench->addBench(function() {
$c = 0;
$bool = true;
if ($bool === true) {
$c++;
}
});
$bench->addBench(function() {
$c = 0;
$string = '0';
if ($string) {
$c++;
}
});
$bench->addBench(function() {
$c = 0;
$string = '1';
if ($string) {
$c++;
}
});
$bench->addBench(function() {
$c = 0;
$string = '';
if ($string) {
$c++;
}
});
$bench->addBench(function() {
$c = 0;
$string = 'X';
if ($string) {
$c++;
}
});
$bench->addBench(function() {
$c = 0;
$int = 0;
if ($int) {
$c++;
}
});
$bench->addBench(function() {
$c = 0;
$int = 1;
if ($int) {
$c++;
}
});
$bench->run(1e6);
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/phpcb-benchmarks/array_iterate_keys.php | tools/phpcb-benchmarks/array_iterate_keys.php | #!/usr/bin/env php
<?php
require __DIR__ . "/../../vendor/autoload.php";
$bench = new \Smuuf\Phpcb\PhpBenchmark(new \Smuuf\Phpcb\SerialEngine);
$hugeArr = array_fill(0, 1_000_000, false);
$bigArr = array_fill(0, 100_000, false);
$smallArr = array_fill(0, 100, false);
$bench->addBench(function() use ($smallArr) {
$result = [];
foreach ($smallArr as $k => $_) {
$result[] = $k;
}
return $result;
});
$bench->addBench(function() use ($bigArr) {
$result = [];
foreach ($bigArr as $k => $_) {
$result[] = $k;
}
return $result;
});
$bench->addBench(function() use ($hugeArr) {
$result = [];
foreach ($hugeArr as $k => $_) {
$result[] = $k;
}
return $result;
});
$bench->addBench(function() use ($smallArr) {
$result = [];
foreach (array_keys($smallArr) as $k) {
$result[] = $k;
}
return $result;
});
$bench->addBench(function() use ($bigArr) {
$result = [];
foreach (array_keys($bigArr) as $k) {
$result[] = $k;
}
return $result;
});
$bench->addBench(function() use ($hugeArr) {
$result = [];
foreach (array_keys($hugeArr) as $k) {
$result[] = $k;
}
return $result;
});
$bench->run(100);
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/build-phar/run.php | tools/build-phar/run.php | #!/usr/bin/env php
<?php
use \Smuuf\Primi\Helpers\Colors;
if (!extension_loaded('phar')) {
die("Cannot create Phar files. Phar extension not enabled");
}
if (!\Phar::canWrite()) {
die("Cannot create Phar files: 'phar.readonly' must be set to 0");
}
// Composer's autoload.
require __DIR__ . '/../../vendor/autoload.php';
define('ROOT_DIR', dirname(__DIR__, 2));
chdir(ROOT_DIR);
const TARGET_PHAR = ROOT_DIR . '/build/primi.phar';
const APP_DIR = ROOT_DIR . '/src';
$tempDir = ROOT_DIR . '/temp/_builder-phar';
print_header();
info("Removing existing Phar ...");
shell_exec(sprintf("rm %s 2>/dev/null", TARGET_PHAR));
info("Copying files to temporary directory ...");
shell_exec("mkdir $tempDir 2>/dev/null");
shell_exec("rm -rf $tempDir/*");
shell_exec("cp --preserve -r ./primi ./src ./composer.* $tempDir/");
info("Removing first line (shebang) from Primi entrypoint ...");
shell_exec("tail -n +2 '$tempDir/primi' > '$tempDir/primi.tmp' && mv '$tempDir/primi.tmp' '$tempDir/primi'");
info("Installing Composer dependencies ...");
shell_exec("composer install -q -o --no-dev -d $tempDir");
info("Building Phar ...");
$p = new Phar(TARGET_PHAR);
$p->startBuffering();
$p->buildFromDirectory($tempDir . "/");
$p->compressFiles(\Phar::GZ);
$p->setStub(get_stub());
$p->stopBuffering();
info("Finishing up ...");
exec(sprintf("chmod +x %s", TARGET_PHAR)); // Mark as executable.
info("Done.");
function get_stub() {
$date = new \DateTime('now', new \DateTimeZone('UTC'));
$buildId = $date->format('y.m.d.Hi');
return <<<STUB
#!/usr/bin/env php
<?php
const BUILD_ID = "$buildId";
if (extension_loaded('phar')) {
set_include_path('phar://' . __FILE__ . '/' . get_include_path());
Phar::mapPhar(basename(__FILE__));
include 'phar://' . __FILE__ . '/primi';
die;
} else {
die("Cannot execute Phar archive. Phar extension is not enabled.");
}
__HALT_COMPILER();
STUB;
}
function info(string $string) {
$date = date('Y-m-d H:i:s');
echo Colors::get("{darkgrey}[{$date}]{_} {$string}\n");
}
function print_header(): void {
$php = PHP_VERSION;
$string = "Phar Builder: Primi Phar Builder\n"
. "{yellow}Running on PHP {$php}{_}\n";
echo Colors::get($string);
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/tools/docgen/docgen.php | tools/docgen/docgen.php | #!/usr/bin/env php
<?php
declare(strict_types=1);
use \Smuuf\Primi\Context;
use \Smuuf\Primi\Values\AbstractValue;
use \Smuuf\Primi\Helpers\Colors;
define('PRIMI_ROOT_DIT', realpath(__DIR__ . '/../..'));
// Composer's autoload.
require PRIMI_ROOT_DIT . '/vendor/autoload.php';
// Strict errors.
error_reporting(E_ALL);
set_error_handler(function($severity, $message, $file, $line) {
throw new \ErrorException($message, 0, $severity, $file, $line);
}, E_ALL);
// Helper functions.
function line($text = ''): void {
echo "$text\n";
}
function out($text): void {
echo $text;
}
function warn($text): void {
global $warnings;
$warnings[] = "$text";
}
function err($text): void {
echo Colors::get("{-red}█ Error:{_} $text\n");
die(1);
}
// Docgen.
line('█ DocGen: Primi Standard Library Docs Generator');
line();
array_shift($argv);
if ($argc !== 3) {
line('Usage:');
line('php ./docgen.php "<glob_path_to_PHP_files>" <path_to_result_markdown_file.md>');
die;
}
$phpFilesGlob = $argv[0];
$outputFile = $argv[1];
$warnings = [];
line(Colors::get("Parsing files at {cyan}$phpFilesGlob{_} ..."));
if (!$extensionFiles = glob($phpFilesGlob)) {
err("No files found at $phpFilesGlob");
}
function get_relevant_methods(string $className): array {
$classRef = new \ReflectionClass("\Smuuf\Primi\Stdlib\\Extensions\\{$className}");
// We want methods that are both public AND static AND non-PHP-magic.
return array_filter(
$classRef->getMethods(),
function ($ref) {
return $ref->isPublic()
&& \strpos($ref->getName(), '__') !== 0;
}
);
}
function clean_doc_whitespace(string $doc): string {
// Unify NL
$doc = preg_replace('#\r?\n#', "\n", $doc);
// Remove "/**"-NL
$doc = preg_replace('#^\/\*\*\s*\n#', '', $doc);
// Remove NL-WHITESPACE-"*/"
$doc = preg_replace('#\s*\*\/#', '', $doc);
$doc = preg_replace('#^\s*\*\h*#m', '', $doc);
$doc = trim($doc);
return $doc;
}
function extract_params(\ReflectionMethod $methodRef): array {
// For potential warning messages.
$methodName = $methodRef->getName();
$className = $methodRef->getDeclaringClass()->getName();
// Extract parameter types. info.
$params = [];
if ($paramsRef = $methodRef->getParameters()) {
foreach ($paramsRef as $paramRef) {
$paramName = $paramRef->getName();
$paramType = false;
if ($paramTypeRef = $paramRef->getType()) {
$paramType = $paramTypeRef->getName();
}
$isOptional = $paramRef->isOptional();
$isValue = is_a($paramType, AbstractValue::class, true);
$isCtx = is_a($paramType, Context::class, true);
if (!$isValue && !$isCtx) {
warn("Class '$className, method '$methodName', parameter '$paramName' does not hint Value|Context");
continue;
}
// Context is automatically injected to functions that need it.
// This has no place in function's signature. Skip this param type.
if ($isCtx) {
continue;
}
$params[] = [
'type' => ($paramType)::TYPE,
'name' => $paramName,
'optional' => $isOptional,
];
}
}
return $params;
}
$data = [];
foreach ($extensionFiles as $filepath) {
line(Colors::get("- File {cyan}$filepath{_}"));
$filename = basename($filepath);
$className = substr($filename, 0, strrpos($filename, '.'));
$methods = get_relevant_methods($className);
$data[$className] = [];
foreach ($methods as $methodRef) {
$methodName = $methodRef->getName();
out(Colors::get("{darkgrey} - Method{_} $className::$methodName{darkgrey} ... {_}"));
$docComment = $methodRef->getDocComment();
if (strpos($docComment ?: '', '@docgenSkip') !== false) {
line(Colors::get("{lightyellow}Skipped via @docgenSkip"));
continue;
}
$text = $docComment ? clean_doc_whitespace($docComment) : '';
// Extract return type, which must be specified.
$returnType = false;
if ($returnTypeRef = $methodRef->getReturnType()) {
try {
$returnType = ($returnTypeRef->getName())::TYPE;
} catch (\Throwable $e) {
warn("Class '$className, method '$methodName', referencing non-existent Primi type having class " . $returnTypeRef->getName());
}
} else {
warn("Class '$className, method '$methodName', return type does not hint Value");
}
if (!$text) {
line(Colors::get("{red}Missing or empty docstring"));
} else {
line(Colors::get("{green}OK"));
}
$data[$className][$methodName] = [
'doctext' => $text,
'parameters' => extract_params($methodRef) ?: false,
'returns' => $returnType ?: false,
];
}
}
line('Building docs...');
function remove_doc_tags(string $text) {
return preg_replace('#@[^\s]+#', '', $text);
}
function build_markdown(array $data): string {
$fnBullet = "### <i style='color: DodgerBlue; font-size: 90%'>fn</i>";
$md = '';
// List extensions alphabetically.
ksort($data);
foreach ($data as $extName => $extData) {
$md .= "## $extName\n";
// List functions alphabetically.
ksort($extData);
foreach ($extData as $funcName => $funcData) {
$parameters = [];
if ($funcData['parameters']) {
foreach ($funcData['parameters'] as $param) {
$paramName = $param['name'];
$paramType = $param['type'];
$tmp = "_{$paramType}_ **`$paramName`**";
if ($param['optional']) {
$tmp = "*[$tmp]*";
}
$parameters[] = $tmp;
}
}
$parameters = implode(', ', $parameters);
$returnType = $funcData['returns'] ?: '';
$md .= "$fnBullet **`$funcName`**($parameters) "
. ($returnType ? " → _{$returnType}_" : "")
. "\n\n";
$doctext = $funcData['doctext'] ?? '' ?: '_Missing description._';
// Process each line separately to aid advanced formatting.
$wasEmpty = false;
$indent = "";
foreach (preg_split('#\n#', $doctext) as $line) {
$isEmpty = trim($line) === '';
// Reduce multiple empty lines into a single empty line.
if ($wasEmpty && $isEmpty) {
continue;
}
$wasEmpty = $isEmpty;
$line = remove_doc_tags($line);
$md .= "{$indent}{$line}\n";
}
$md .= "\n---\n";
}
}
return $md;
}
$md = build_markdown($data);
line(Colors::get("Saving into {lightblue}$outputFile{_} ..."));
file_put_contents($outputFile, $md);
line('Done.');
// Print warnings at the end, if there were any.
if ($warnings) {
line(Colors::get("{yellow}Warnings: "));
foreach ($warnings as $warning) {
echo "- $warning\n";
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/DirectInterpreter.php | src/DirectInterpreter.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi;
use \Smuuf\StrictObject;
use \Smuuf\Primi\Ex\RuntimeError;
use \Smuuf\Primi\Ex\SystemException;
use \Smuuf\Primi\Ex\ControlFlowException;
use \Smuuf\Primi\Code\Ast;
use \Smuuf\Primi\Tasks\Emitters\PosixSignalTaskEmitter;
use \Smuuf\Primi\Values\AbstractValue;
use \Smuuf\Primi\Helpers\Wrappers\CatchPosixSignalsWrapper;
use \Smuuf\Primi\Handlers\HandlerFactory;
use \Smuuf\Primi\Structures\CallRetval;
/**
* Primi's direct raw abstract syntax tree interpreter.
*
* Raw interpreter can be used to simply execute some Primi source code
* within a given context.
*
* @see https://en.wikipedia.org/wiki/Interpreter_(computing)#Abstract_Syntax_Tree_interpreters
*/
abstract class DirectInterpreter {
use StrictObject;
/**
* Execute source code within a given context.
*
* This is a bit lower-level approach to running some source code provided
* as `Ast` object. This allows the client to specify a context object
* to run the code (represented by `Ast` object) within. This in turn
* allows, for example, the REPL to operate within some specific context
* representing a runtime-in-progress (where it can access local variables).
*
* @param Ast $ast `Ast` object representing the AST to execute.
*/
public static function execute(
Ast $ast,
Context $ctx
): AbstractValue {
EnvInfo::bootCheck();
// Register signal handling - maybe.
if ($ctx->getConfig()->getEffectivePosixSignalHandling()) {
PosixSignalTaskEmitter::catch(SIGINT);
PosixSignalTaskEmitter::catch(SIGQUIT);
PosixSignalTaskEmitter::catch(SIGTERM);
}
$wrapper = new CatchPosixSignalsWrapper($ctx->getTaskQueue());
return $wrapper->wrap(function() use ($ast, $ctx) {
try {
$tree = $ast->getTree();
$retval = HandlerFactory::runNode($tree, $ctx);
if ($ctx->hasRetval()) {
$ctx->popRetval();
throw new RuntimeError("Cannot 'return' from global scope");
}
return $retval;
} catch (ControlFlowException $e) {
$what = $e::ID;
throw new RuntimeError("Cannot '{$what}' from global scope");
} finally {
try {
// This is the end of a single runtime, so run any tasks
// that may be still left in the task queue (this means, for
// example, that all callbacks in the queue will still be
// executed).
$ctx->getTaskQueue()->deplete();
} catch (SystemException $e) {
throw new RuntimeError($e->getMessage());
}
}
});
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/EnvInfo.php | src/EnvInfo.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi;
use \Smuuf\Primi\Ex\EngineError;
/**
* Static helper for providing information about current runtime environment.
*/
abstract class EnvInfo {
private static bool $bootCheck = \false;
private static ?bool $runningInPhar = \null;
private static ?bool $runningInCli = \null;
private static ?string $homeDir = \null;
private static ?string $currentUser = \null;
private static ?string $bestTempDir = \null;
/**
* Throws if Primi cannot run in current PHP runtime.
*/
public static function bootCheck(): void {
if (self::$bootCheck) {
return;
}
$missingExt = [];
$missingExt['bcmath'] = !\extension_loaded('bcmath');
$missingExt['mbstring'] = !\extension_loaded('mbstring');
$missingExt = \array_filter($missingExt);
if ($missingExt) {
$list = \implode(', ', \array_keys($missingExt));
throw new EngineError("Primi requires PHP extensions: $list");
}
self::$bootCheck = \true;
}
/**
* Get Primi build ID (if executed within compiled Phar, else 'dev').
*/
public static function getPrimiBuild(): string {
return self::isRunningInPhar()
? \constant('BUILD_ID')
: 'dev';
}
/**
* Is current runtime being executed within Phar?
*/
public static function isRunningInPhar(): bool {
return self::$runningInPhar
?? (self::$runningInPhar = self::determineIsRunningInPhar());
}
/**
* Is current runtime being executed within Phar?
*/
public static function isRunningInCli(): bool {
return self::$runningInCli
?? (self::$runningInCli = \in_array(\PHP_SAPI, ['cli', 'phpdbg']));
}
/**
* Return current user's HOME directory, or `null` if there's not any.
*/
public static function getHomeDir(): ?string {
return self::$homeDir
?? (self::$homeDir = (\getenv('HOME') ?: \null));
}
/**
* Return current user's username.
*/
public static function getCurrentUser(): string {
return self::$currentUser
?? (self::$currentUser = \getenv('USER'));
}
/**
* Return path to best temporary dir available for current runtime.
*/
public static function getBestTempDir(): ?string {
return self::$bestTempDir
?? (self::$bestTempDir = self::determineBestTempDir());
}
//
// Helpers.
//
/**
* Determine if Phar extension is enabled and if we're being executed
* inside Phar.
*/
private static function determineIsRunningInPhar(): bool {
return \extension_loaded('phar') && \Phar::running();
}
/**
* Determine best directory to use as temporary directory for Primi.
*/
private static function determineBestTempDir(): ?string {
// If not running inside Phar, default dir will be in Primi's temp
// directory.
if (!EnvInfo::isRunningInPhar()) {
$tempDir = __DIR__ . '/../temp';
Logger::debug("Using library temp directory '$tempDir'");
return $tempDir;
}
//
// Now we handle situations where we're being executed as Phar archive.
//
// Determine if we can get home directory for current user.
$homeDir = EnvInfo::getHomeDir();
if ($homeDir === \null) {
$currentUser = EnvInfo::getCurrentUser();
Logger::debug("Current user '$currentUser' has no home directory. Temp directory disabled");
// Current user has no home directory, we're disabling temp dir.
return \null;
}
// Determine if current user's home directory contains ".primi" file/dir.
$tempDir = "{$homeDir}/.primi";
if (!\file_exists($tempDir)) {
// Home directory does not contain ".primi" - try creating it.
$success = @mkdir($tempDir);
if ($success === \false) {
Logger::debug("Failed to create temp directory '$tempDir'. Temp directory disabled");
return \null;
}
}
// Is ".primi" file/dir in home dir a file? We need it to be a dir...
if (\is_file($tempDir)) {
Logger::debug("Path to temp directory '$tempDir' exists, but is a file. Temp directory disabled");
return \null;
}
// And this dir needs to be writable by us...
if (!\is_writable($tempDir)) {
Logger::debug("Temp directory '$tempDir' is not writable. Temp directory disabled");
return \null;
}
// The ".primi" in home dir is a directory and we can write to it,
// let's use it!
Logger::debug("Using temp directory '$tempDir'");
return $tempDir;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Context.php | src/Context.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi;
use \Smuuf\StrictObject;
use \Smuuf\Primi\Scope;
use \Smuuf\Primi\Ex\RuntimeError;
use \Smuuf\Primi\Code\AstProvider;
use \Smuuf\Primi\Ex\EngineInternalError;
use \Smuuf\Primi\Tasks\TaskQueue;
use \Smuuf\Primi\Values\ModuleValue;
use \Smuuf\Primi\Values\AbstractValue;
use \Smuuf\Primi\Drivers\StdIoDriverInterface;
use \Smuuf\Primi\Modules\Importer;
use \Smuuf\Primi\Structures\CallRetval;
class Context {
use StrictObject;
/** Runtime config bound to this context. */
private Config $config;
//
// Call stack.
//
/** Configured call stack limit. */
private int $maxCallStackSize;
/** @var StackFrame[] Call stack list. */
private $callStack = [];
/**
* Current call stack size.
* Instead of count()ing $callStack property every time.
*
* @var int
*/
private $callStackSize = 0;
//
// Scope stack.
//
/** @var Scope[] Scope stack list. */
private $scopeStack = [];
/**
* Direct reference to the scope on the top of the stack.
* @var ?Scope
*/
private $currentScope;
//
// Context services.
//
/** Task queue for this context. */
private TaskQueue $taskQueue;
private Importer $importer;
private AstProvider $astProvider;
private StdIoDriverInterface $stdIoDriver;
//
// Return value storage.
//
private ?CallRetval $retval = null;
//
// References to essential modules for fast and direct access.
//
/** Native 'std.__builtins__' module. */
private Scope $builtins;
public function __construct(Config $config) {
$services = new ContextServices($this, $config);
$this->config = $config;
$this->stdIoDriver = $this->config->getStdIoDriver();
// Assign stuff to properties to avoid unnecessary indirections when
// accessing them (optimization).
$this->astProvider = $services->getAstProvider();
$this->taskQueue = $services->getTaskQueue();
$this->importer = $services->getImporter();
$this->maxCallStackSize = $this->config->getCallStackLimit();
// Import our builtins module.
$this->builtins = $this->importer
->getModule('std.__builtins__')
->getCoreValue();
}
// Access to runtime config.
public function getConfig(): Config {
return $this->config;
}
// Access to AST provider.
public function getAstProvider(): AstProvider {
return $this->astProvider;
}
// Standard IO driver.
public function getStdIoDriver(): StdIoDriverInterface {
return $this->stdIoDriver;
}
// Task queue management.
public function getTaskQueue(): TaskQueue {
return $this->taskQueue;
}
// Import management.
public function getImporter(): Importer {
return $this->importer;
}
public function getCurrentModule(): ?ModuleValue {
$currentFrame = \end($this->callStack);
return $currentFrame
? $currentFrame->getModule()
: \null;
}
// Call stack management.
/**
* @return array<StackFrame>
*/
public function getCallStack(): array {
return $this->callStack;
}
/**
* @param StackFrame $call
* @return void
*/
public function pushCall($call) {
// Increment current stack size.
$this->callStackSize++;
$this->callStack[] = $call;
// We can check this every time. Even if 'maxCallStackSize' is zero,
// the 'callStackSize' will never be.
if ($this->callStackSize === $this->maxCallStackSize) {
throw new RuntimeError(\sprintf(
"Maximum call stack size (%d) reached",
$this->maxCallStackSize
));
}
}
/**
* @return void
*/
public function popCall() {
\array_pop($this->callStack);
$this->callStackSize--;
$this->taskQueue->tick();
}
// Direct access to native 'builtins' module.
public function getBuiltins(): Scope {
return $this->builtins;
}
// Scope management.
/**
* @return Scope
*/
public function getCurrentScope() {
return $this->currentScope;
}
// Call + Scope management.
/**
* @param ?StackFrame $call
* @param ?Scope $scope
* @return void
*/
public function pushCallScopePair($call, $scope) {
// Push call, if there's any.
if ($call) {
// Increment current stack size.
$this->callStackSize++;
// Call stack.
$this->callStack[] = $call;
// We can check this every time. Even if 'maxCallStackSize' is zero,
// the 'callStackSize' will never be.
if ($this->callStackSize === $this->maxCallStackSize) {
throw new RuntimeError(\sprintf(
"Maximum call stack size (%d) reached",
$this->maxCallStackSize
));
}
}
// Push scope, if there's any.
if ($scope) {
$this->scopeStack[] = $scope;
$this->currentScope = $scope;
}
}
/**
* @param bool $popCall
* @param bool $popScope
* @return void
*/
public function popCallScopePair($popCall = \true, $popScope = \true) {
if ($popCall) {
\array_pop($this->callStack);
$this->callStackSize--;
}
if ($popScope) {
\array_pop($this->scopeStack);
$this->currentScope = \end($this->scopeStack) ?: \null;
}
$this->taskQueue->tick();
}
// Direct access to the current scope - which is the one on the top of the
// stack. Also fetches stuff from builtins module, if it's not found
// in current scope (and its parents).
public function getVariable(string $name): ?AbstractValue {
return $this->currentScope->getVariable($name)
?? $this->builtins->getVariable($name);
}
/**
* @return array<string, AbstractValue>
*/
public function getVariables(bool $includeParents = \false): array {
return array_merge(
$this->builtins->getVariables(),
$this->currentScope->getVariables($includeParents)
);
}
/**
* @return void
*/
public function setVariable(string $name, AbstractValue $value) {
$this->currentScope->setVariable($name, $value);
}
/**
* @param array<string, AbstractValue> $pairs
* @return void
*/
public function setVariables(array $pairs) {
$this->currentScope->setVariables($pairs);
}
/**
* Register a return value for function which is currently being executed.
*/
public function setRetval(CallRetval $retval): void {
if ($this->retval) {
throw new EngineInternalError("Retval already present");
}
$this->retval = $retval;
}
/**
* Return and reset return value that came from some function.
*/
public function popRetval(): CallRetval {
if (!$this->retval) {
throw new EngineInternalError("Retval not present");
}
[$retval, $this->retval] = [$this->retval, \null];
return $retval;
}
/**
* Returns true if a return value is currently registered from some
* function.
*/
public function hasRetval(): bool {
return isset($this->retval);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Repl.php | src/Repl.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi;
use \Smuuf\StrictObject;
use \Smuuf\Primi\Scope;
use \Smuuf\Primi\Ex\ErrorException;
use \Smuuf\Primi\Ex\EngineException;
use \Smuuf\Primi\Ex\SystemException;
use \Smuuf\Primi\Cli\Term;
use \Smuuf\Primi\Code\Source;
use \Smuuf\Primi\Parser\GrammarHelpers;
use \Smuuf\Primi\Values\NullValue;
use \Smuuf\Primi\Values\AbstractValue;
use \Smuuf\Primi\Values\ModuleValue;
use \Smuuf\Primi\Helpers\Func;
use \Smuuf\Primi\Helpers\Colors;
use \Smuuf\Primi\Helpers\Wrappers\ContextPushPopWrapper;
use \Smuuf\Primi\Drivers\ReadlineUserIoDriver;
use \Smuuf\Primi\Drivers\ReplIoDriverInterface;
class Repl {
use StrictObject;
/**
* @const string How this REPL identifies itself in call stack.
*/
private const REPL_NAME_FORMAT = "<repl: %s>";
private const HISTORY_FILE = '.primi_history';
private const PRIMARY_PROMPT = '>>> ';
private const MULTILINE_PROMPT = '... ';
private const PHP_ERROR_HEADER = "PHP ERROR";
private const ERROR_REPORT_PLEA =
"This is probably a bug in Primi or any of its components. "
. "Please report this to the maintainer.";
/** Full path to readline history file. */
private static string $historyFilePath;
/** REPL identifies itself in callstack with this string. */
protected string $replName;
/**
* IO driver used for user input/output.
*
* This is handy for our unit tests, so we can simulate user input and
* gather REPL output.
*/
protected ReplIoDriverInterface $driver;
/**
* If `false`, extra "user-friendly info" is not printed out.
* This is also handy for our unit tests - less output to test.
*
* @var bool
*/
public static $noExtras = false;
public function __construct(
?string $replName = null,
ReplIoDriverInterface $driver = null
) {
self::$historyFilePath = getenv("HOME") . '/' . self::HISTORY_FILE;
$this->replName = sprintf(self::REPL_NAME_FORMAT, $replName ?? 'cli');
$this->driver = $driver ?? new ReadlineUserIoDriver;
$this->loadHistory();
}
protected function printHelp(): void {
$this->driver->stderr(Colors::get("\n".
"{green}Use '{_}exit{green}' to exit REPL or '{_}exit!{green}' " .
"to terminate the process.\n" .
"Use '{_}?{green}' to view local variables, " .
"'{_}??{green}' to view all variables, " .
"'{_}?tb{green}' to see traceback. \n" .
"The latest result is stored in '{_}_{green}' variable.\n\n"
));
}
/**
* Main REPL entrypoint.
*
* Creates a new instance of interpreter and runs it with a Context, if it
* was specified as argument. Otherwise the interpreter creates its own
* new context and REPL operates within that one.
*/
public function start(?Context $ctx = null): void {
// If context was not provided, create and use a new one.
if (!$ctx) {
$scope = new Scope;
$config = Config::buildDefault();
$config->addImportPath(getcwd());
$ctx = new Context($config);
$module = new ModuleValue(MagicStrings::MODULE_MAIN_NAME, '', $scope);
} else {
$module = $ctx->getCurrentModule();
$scope = $ctx->getCurrentScope();
}
$frame = new StackFrame($this->replName, $module);
$wrapper = new ContextPushPopWrapper($ctx, $frame, $scope);
$wrapper->wrap(function($ctx) {
$this->loop($ctx);
});
}
private function loop(Context $ctx): void {
// Print out level (current frame's index in call stack).
if (!self::$noExtras) {
$level = self::getStackLevel($ctx);
$this->driver->stderr(Colors::get(
"{darkgrey}Starting REPL at F {$level}{_}\n"
));
$this->printHelp();
}
$currentScope = $ctx->getCurrentScope();
$cellNumber = 1;
readline_completion_function(
static fn($buffer) => self::autocomplete($buffer, $ctx)
);
while (true) {
// Display frame level - based on current level of call stack.
$level = self::getStackLevel($ctx);
if (!self::$noExtras && $level) {
$this->driver->stderr(Colors::get("{darkgrey}F {$level}{_}\n"));
}
$input = $this->gatherLines($ctx);
if (trim($input) && $input !== 'exit') {
$this->driver->addToHistory($input);
}
switch (trim($input)) {
case '?':
// Print defined variables.
$this->printScope($currentScope, false);
continue 2;
case '?tb':
// Print traceback.
$this->printTraceback($ctx);
continue 2;
case '??':
// Print all variables, including the ones from parent
// scopes (i.e. even from extensions).
$this->printScope($currentScope, true);
continue 2;
case '':
// Ignore (skip) empty input.
continue 2;
case 'exit':
// Catch a non-command 'exit'.
// Return the result of last expression executed, or null.
break 2;
case 'exit!':
// Catch a non-command 'exit!'.
// Just quit the whole thing.
die(1);
}
$this->saveHistory();
$source = new Source($input);
try {
// May throw syntax error - will be handled by the catch
// below.
$ast = $ctx->getAstProvider()->getAst($source, false);
$result = DirectInterpreter::execute($ast, $ctx);
// Store the result into _ variable for quick'n'easy
// retrieval.
$currentScope->setVariable('_', $result);
$this->printResult($result);
} catch (ErrorException|SystemException $e) {
$colorized = Func::colorize_traceback($e);
$this->driver->stderr(Term::error($colorized));
} catch (EngineException|\Throwable $e) {
// All exceptions other than ErrorException are likely to be a
// problem with Primi or PHP - print the whole PHP exception.
$this->printPhpTraceback($e);
}
$this->driver->stdout("\n");
$cellNumber++;
}
$this->saveHistory();
if (!self::$noExtras) {
$level = self::getStackLevel($ctx);
$this->driver->stderr(Colors::get(
"{yellow}Exiting REPL frame $level{_}\n"
));
}
}
/**
* Pretty-prints out a result of a Primi expression. No result or null
* values are not to be printed.
*/
private function printResult(?AbstractValue $result = null): void {
// Do not print out empty or NullValue results.
if ($result === null || $result instanceof NullValue) {
return;
}
$this->driver->stdout(self::formatValue($result), "\n");
}
/**
* Pretty-prints out all variables of a scope (with or without variables
* from parent scopes).
*/
private function printScope(Scope $c, bool $includeParents): void {
foreach ($c->getVariables($includeParents) as $name => $value) {
$this->driver->stdout(
Colors::get("{lightblue}$name{_}: "),
self::formatValue($value),
"\n",
);
}
$this->driver->stdout("\n");
}
/**
* Pretty-prints out traceback from a context.
*/
private function printTraceback(Context $ctx): void {
$tbString = Func::get_traceback_as_string($ctx->getCallStack());
$this->driver->stdout($tbString, "\n\n");
}
/**
* Pretty-prints out traceback from a PHP exception.
*/
private function printPhpTraceback(\Throwable $e): void {
$type = get_class($e);
$msg = Colors::get(sprintf("\n{white}{-red}%s", self::PHP_ERROR_HEADER));
$msg .= " $type: {$e->getMessage()} @ {$e->getFile()}:{$e->getLine()}\n";
$this->driver->stderr($msg);
// Best and easiest to get version of backtrace I can think of.
$this->driver->stderr(
$e->getTraceAsString(),
Colors::get(sprintf("\n{yellow}%s", self::ERROR_REPORT_PLEA)),
"\n\n",
);
}
/**
* Gathers and returns user input for REPL.
*
* Uses a "very sophisticated" way of allowing the user to enter multi-line
* input.
*/
private function gatherLines(Context $ctx): string {
$gathering = false;
$lines = '';
while (true) {
if ($gathering === false) {
$prompt = self::PRIMARY_PROMPT;
} else {
$prompt = self::MULTILINE_PROMPT;
}
$input = $this->driver->input($prompt);
[$incomplete, $trim] = self::isIncompleteInput($input);
if ($incomplete) {
// Consider non-empty line ending with a "\" character as
// a part of multiline input. That is: Trim the backslash and
// go read another line from the user.
$lines .= mb_substr($input, 0, mb_strlen($input) - $trim) . "\n";
$gathering = true;
} else {
// Normal non-multiline input. Add it to the line buffer and
// return the whole buffer (with all lines that may have been)
// gathered as multiline input so far.
$lines .= $input;
return $lines;
}
}
}
// Static helpers.
/**
* Returns a pretty string from AbstractValue representation with type info.
*/
private static function formatValue(AbstractValue $value): string {
return sprintf(
"%s %s",
$value->getStringRepr(),
!self::$noExtras ? self::formatType($value) : null
);
}
/**
* Returns a pretty string representing value's type info.
*/
private static function formatType(AbstractValue $value): string {
return Colors::get(sprintf(
"{darkgrey}(%s %s){_}",
$value->getTypeName(),
Func::object_hash($value)
));
}
/**
* @return array{bool, int}
*/
private static function isIncompleteInput(string $input): array {
if ($input === '') {
return [false, 0];
}
// Lines ending with opening curly brackets are considered incomplete.
if ($input[-1] === "{") {
return [true, 0];
}
// Lines ending with backslashes are considered incomplete.
// And such backslashes at the EOL are to be trimmed from real input.
if ($input[-1] === '\\') {
return [true, 1];
}
// Lines starting with a SPACE or a TAB are considered incomplete.
if (strspn($input, "\t ") !== 0) {
return [true, 0];
}
return [false, 0];
}
private function loadHistory(): void {
if (is_readable(self::$historyFilePath)) {
$this->driver->loadHistory(self::$historyFilePath);
}
}
private function saveHistory(): void {
if (is_writable(dirname(self::$historyFilePath))) {
$this->driver->storeHistory(self::$historyFilePath);
}
}
/**
* Return string with human-friendly information about current level
* of nested calls (that is the number of entries in the call stack).
*/
private static function getStackInfo(
Context $ctx,
bool $full = false
): string {
$level = self::getStackLevel($ctx);
// Do not print anything for level 0 (or less, lol).
if ($level < 0) {
return '';
}
$out = "F {$level}";
if ($full) {
$out = "REPL at frame {$level}.\n";
}
return Colors::get("{darkgrey}REPL at frame {$level}.\n{_}");
}
private static function getStackLevel(Context $ctx): int {
return \count($ctx->getCallStack()) - 1;
}
/**
* @return array<string>
*/
private static function autocomplete(
string $buffer,
Context $ctx
): array {
$names = [];
if (!$buffer || GrammarHelpers::isValidName($buffer)) {
// Buffer (word of input) is empty - or maybe a simple variable.
$names = array_keys($ctx->getVariables(true));
} elseif (GrammarHelpers::isSimpleAttrAccess(trim($buffer, '.'))) {
// Autocomplete for attr access of objects from current scope.
// We need to separate parts of nested attr access, so that
// for "obj" we suggest attrs from "obj", but for
// "obj.attr_a.attr_b" we complete attrs from the final "attr_b".
$parts = array_reverse(explode('.', $buffer));
// Fetch the actual variable (always for the first part).
$name = array_pop($parts);
if (!$obj = $ctx->getVariable($name)) {
return [];
}
$names[] = $name;
// Now go fetch the attrs inside that variable, if there are any
// specified in the buffer. E.g. "some_obj.attr_a.att[TAB]" needs
// to fetch "some_obj", then its attr "attr_a" and get all attrs
// inside it, so we can suggest "some_obj.attr_a.attr_b"
$prefix = $name;
while ($name = array_pop($parts)) {
if (!$innerObj = $obj->attrGet($name)) {
break;
}
$obj = $innerObj;
$prefix .= ".$name";
$names[] = $prefix;
}
// The name is now either the rest of the string after last dot,
// or null (we processed all parts already).
// If if's not null, we're going to suggest attributes from the
// object we encountered last.
if ($name !== null) {
$underscored = \str_starts_with($name, '_');
foreach ($obj->dirItems() as $name) {
// Skip underscored names if not requested explicitly.
if (!$underscored && Func::is_under_name($name)) {
continue;
}
$addName = "$prefix.$name";
$names[] = $addName;
}
}
}
$names = array_filter(
$names,
static fn($name) => \str_starts_with($name, $buffer)
);
// Typing "some_v[TAB]" if "some_var" exists should also
// suggest "some_var " with a space, so there are two options for
// the autocomplete. Why? Otherwise readline would just write
// "some_var " with a space when the TAB is pressed (it does that
// automatically). And that's not user friendly if our user would
// like to access attributes via "some_var." quickly.
$starting = array_filter(
$names,
static fn($n) => str_starts_with($n, $buffer)
);
// If there's only one candidate (eg. "debugger"), but it's not yet
// entered completely ("debugge"), add another candidate with space at
// the end ("debugger "), so that readline autocomplete stops at the
// latest common character ("debugger|") instead of resolving into
// "debugger |" directly (readline adds the space automatically and
// we don't want that).
if (count($starting) === 1 && reset($starting) !== $buffer) {
$names[] = reset($starting) . " ";
}
return $names;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/InterpreterResult.php | src/InterpreterResult.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi;
use \Smuuf\StrictObject;
use \Smuuf\Primi\Scope;
/**
* Object wrapping a single interpreter execution result.
*/
class InterpreterResult {
use StrictObject;
public function __construct(
private Scope $scope,
private Context $context,
) {}
public function getScope(): Scope {
return $this->scope;
}
public function getContext(): Context {
return $this->context;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Interpreter.php | src/Interpreter.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi;
use \Smuuf\StrictObject;
use \Smuuf\Primi\Scope;
use \Smuuf\Primi\Ex\EngineError;
use \Smuuf\Primi\Code\Source;
use \Smuuf\Primi\Code\SourceFile;
use \Smuuf\Primi\Values\ModuleValue;
use \Smuuf\Primi\Helpers\Wrappers\ContextPushPopWrapper;
/**
* Primi's primary abstract syntax tree interpreter.
*/
class Interpreter {
use StrictObject;
/** Runtime configuration. */
private Config $config;
/** Last context that was being executed. */
private ?Context $lastContext = null;
/**
* Create a new instance of interpreter.
*
* @param Config|null $config _(optional)_ Config for the interpreter.
*/
public function __construct(?Config $config = null) {
$this->config = $config ?? Config::buildDefault();
EnvInfo::bootCheck();
}
public function buildContext(): Context {
return new Context($this->config);
}
/**
* Return the last `Context` object that was being executed.
*
* This is handy for context inspection if any unhandled exception ocurred
* during Primi runtime.
*/
public function getLastContext(): ?Context {
return $this->lastContext;
}
/**
* Main entrypoint for executing Primi source code.
*
* @param string|Source $source Primi source code provided as string or
* as an instance of `Source` object.
* @param Scope|null $scope Optional scope object that is to be used as
* global scope of the main module.
* @param Context|null $context Optional context object the interpreter
* should use.
*/
public function run(
string|Source $source,
?Scope $scope = \null,
?Context $context = \null,
): InterpreterResult {
// This is forbidden - Context already has initialized importer
// with its import paths, but SourceFile would also expect its
// directory in the import paths.
if ($context && $source instanceof SourceFile) {
throw new EngineError(
"Cannot pass SourceFile and Context at the same time");
}
$source = \is_string($source)
? new Source($source)
: $source;
$scope = $scope ?? new Scope;
$context = $context ?? $this->buildContext();
$this->lastContext = $context;
$mainModule = new ModuleValue(MagicStrings::MODULE_MAIN_NAME, '', $scope);
$ast = $context->getAstProvider()->getAst($source);
$frame = new StackFrame('<main>', $mainModule);
$wrapper = new ContextPushPopWrapper($context, $frame, $scope);
$wrapper->wrap(function($context) use ($ast) {
return DirectInterpreter::execute($ast, $context);
});
return new InterpreterResult($scope, $context);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Location.php | src/Location.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi;
use \Smuuf\Primi\Helpers\Colors;
use \Smuuf\StrictObject;
class Location {
use StrictObject;
/** Name of the location (e.g. module name or source ID). */
private string $name;
/** Line in the file. */
private int $line;
/** Position on the line, if specified. */
private ?int $position = \null;
public function __construct(
string $name,
int $line,
?int $position = \null
) {
$this->name = $name;
$this->line = $line;
$this->position = $position;
}
public function asString(): string {
$posInfo = $this->position !== \null
? " at position {$this->position}"
: '';
return "{$this->name} on line {$this->line}$posInfo";
}
/**
* Get human-friendly name of the location.
*/
public function getName(): string {
return $this->name;
}
/**
* Get line in the source file.
*/
public function getLine(): int {
return $this->line;
}
/**
* Position on the line, if specified.
*/
public function getPosition(): ?int {
return $this->position;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Config.php | src/Config.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi;
use \Smuuf\StrictObject;
use \Smuuf\Primi\Ex\EngineError;
use \Smuuf\Primi\Helpers\Func;
use \Smuuf\Primi\Drivers\VoidIoDriver;
use \Smuuf\Primi\Drivers\TerminalIoDriver;
use \Smuuf\Primi\Drivers\StdIoDriverInterface;
class Config {
use StrictObject;
private bool $sandboxMode = true;
/**
* Return default config for current environment.
*
* If Primi is running in CLI (terminal) the sandbox mode is disabled by
* default.
*
* If Primi is running anywhere else, sandbox mode is enabled by default.
*/
final public static function buildDefault(): Config {
// If not running in CLI, enable sandbox mode by default.
if (!EnvInfo::isRunningInCli()) {
return new self;
}
$config = new self;
$config->setSandboxMode(false);
$config->setStdIoDriver(new TerminalIoDriver);
return $config;
}
// Sandbox mode.
public function setSandboxMode(bool $mode): void {
$this->sandboxMode = $mode;
}
public function getSandboxMode(): bool {
return $this->sandboxMode;
}
//
// Temporary directory.
//
/**
* Path to temporary directory for caching or `null` for disabled caching.
*/
private ?string $tempDir = '';
/**
* Set path to temporary directory for caching various stuff for the Primi
* engine.
*
* Default value is empty string, which means default temporary
* directory located inside the Primi library will be used.
*
* If necessary, another _existing_ directory can be specified to be used
* as the temporary directory.
*
* If the temporary directory is set to `null`, caching will be disabled.
*/
public function setTempDir(?string $path): void {
$this->tempDir = $path !== null
? Func::validate_dirs([$path])[0]
: null;
}
public function getTempDir(): ?string {
return $this->tempDir === ''
? EnvInfo::getBestTempDir()
: null;
}
//
// Paths for finding modules.
//
/** @var array<string> */
private array $importPaths = [
__DIR__ . '/Stdlib/Modules',
];
public function addImportPath(string $path): void {
$this->importPaths[] = Func::validate_dirs([$path])[0];
}
/**
* @return array<string>
*/
public function getImportPaths(): array {
return $this->importPaths;
}
//
// Callstack limit.
//
/**
* If greater than one, this number sets the maximum call stack size.
* If this maximum is reached, `\Smuuf\Primi\Ex\RuntimeError` is thrown.
*/
private int $callStackLimit = 4096;
/**
* Set maximum limit for runtime call stack object. This is the maximum
* number of allowed nested function calls.
*
* This can be set to zero to disable limiting.
*
* @see Context
*/
public function setCallStackLimit(int $limit): void {
if ($limit < 0) {
throw new EngineError('Callstack limit must be positive or zero');
}
$this->callStackLimit = $limit;
}
/**
* Return current value of configured callstack limit.
*/
public function getCallStackLimit(): int {
return $this->callStackLimit;
}
//
// Posix signal handling.
//
/**
* Automatically determine if POSIX signals should be handled or not -
* handling will be enabled only when running in CLI mode.
*/
public const POSIX_SIGNALS_AUTO = null;
/**
* Enable handling of POSIX signals by Primi engine.
*/
public const POSIX_SIGNALS_ENABLED = true;
/**
* Disable handling of POSIX signals by Primi engine.
*/
public const POSIX_SIGNALS_DISABLED = false;
/**
* Set if POSIX signals should be received and rendered into the Primi
* runtime. For example SIGTERM and SIGINT signals will raise an appropriate
* error.
*/
private ?bool $posixSignalHandling = self::POSIX_SIGNALS_AUTO;
/**
* Should POSIX signals be handled by the engine?
*
* @see self::POSIX_SIGNALS_AUTO
* @see self::POSIX_SIGNALS_ENABLED
* @see self::POSIX_SIGNALS_DISABLED
*/
public function setPosixSignalHandling(
?bool $state = self::POSIX_SIGNALS_AUTO
): void {
$this->posixSignalHandling = $state;
}
/**
* Return current value of configured callstack limit.
*/
public function getPosixSignalHandling(): ?bool {
return $this->posixSignalHandling;
}
/**
* Returns `true` or `false` if POSIX signals should be handled based
* by the actual configuration.
*/
public function getEffectivePosixSignalHandling(): bool {
// Explicit enabled or disabled.
if (\is_bool($this->posixSignalHandling)) {
return $this->posixSignalHandling;
}
// Automatic detection - handle POSIX signals only in CLI.
return EnvInfo::isRunningInCli();
}
//
// Posix signal handling - does SIGQUIT inject a debugging session?
//
private bool $sigQuitDebugging = \true;
/**
* If POSIX signal handling is enabled, received SIGQUIT causes a debugging
* session to be injected into currently executed code.
*
* SIGQUIT can usually be sent from terminal via `CTRL+\`.
*/
public function setSigQuitDebugging(bool $state): void {
$this->sigQuitDebugging = $state;
}
/**
* Return current config value of "SIGQUIT debugging".
*/
public function getSigQuitDebugging(): bool {
return $this->sigQuitDebugging;
}
//
// Standard IO driver.
//
private StdIoDriverInterface $stdIoDriver;
public function setStdIoDriver(StdIoDriverInterface $stdIoDriver): void {
$this->stdIoDriver = $stdIoDriver;
}
public function getStdIoDriver(): StdIoDriverInterface {
return $this->stdIoDriver
?? ($this->stdIoDriver = new VoidIoDriver);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/MagicStrings.php | src/MagicStrings.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi;
abstract class MagicStrings {
public const MODULE_MAIN_NAME = '__main__';
public const ATTR_NAME = '__name__';
public const TYPE_OBJECT = 'object';
public const MAGICMETHOD_NEW = '__new__';
public const MAGICMETHOD_INIT = '__init__';
public const MAGICMETHOD_CALL = '__call__';
public const MAGICMETHOD_REPR = '__repr__';
public const MAGICMETHOD_STRING = '__string__';
public const MAGICMETHOD_OP_EQ = '__op_eq__';
public const MAGICMETHOD_OP_ADD = '__op_add__';
public const MAGICMETHOD_OP_SUB = '__op_sub__';
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Scope.php | src/Scope.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi;
use \Smuuf\Primi\Values\AbstractValue;
use \Smuuf\StrictObject;
/**
* A structure for representing a variable scope - storage for variables.
*/
class Scope {
use StrictObject;
/**
* Flag for standard, ordinary scopes.
*/
public const TYPE_STANDARD = 0;
/**
* Flag to distinguish scopes representing a class scope.
*
* This is used to tell function definitions that they should not set their
* scopes' parent to this scope. In another words: Methods of a class
* should _not_ have direct access to the scope of the class. Those
* should be accessed only via the "self" special variable.
*
* @const int
*/
public const TYPE_CLASS = 1;
/**
* @param array<string, AbstractValue> $variables
* @param int $type Scope type.
* @param ?self $parent Parent scope, if any.
*/
public function __construct(
private array $variables = [],
private int $type = self::TYPE_STANDARD,
private ?self $parent = \null,
) {}
/**
* Return type of the scope.
*/
public function getType(): int {
return $this->type;
}
public function getParent(): ?Scope {
return $this->parent;
}
/**
* Get a variable by its name.
*
* If the variable is missing in current scope, look the variable up in the
* parent scope, if there's any.
*/
public function getVariable(string $name): ?AbstractValue {
return $this->variables[$name]
// Recursively up, if there's a parent scope.
?? (
$this->parent !== \null
? $this->parent->getVariable($name)
: \null
);
}
/**
* Returns a dictionary [var_name => AbstractValue] of all variables present
* in this scope.
*
* If the `$includeParents` argument is `true`, variables from parent scopes
* will be included too (variables in child scopes have priority over those
* from parent scopes).
*
* @return array<string, AbstractValue>
*/
public function getVariables(bool $includeParents = \false): array {
$fromParents = ($includeParents && $this->parent !== \null)
// Recursively up, if there's a parent scope.
? $this->parent->getVariables($includeParents)
: [];
return $this->variables + $fromParents;
}
/**
* @return void
*/
public function setVariable(string $name, AbstractValue $value) {
$this->variables[$name] = $value;
}
/**
* Set multiple variables to the scope.
*
* @param array<string, AbstractValue> $pairs
* @return void
*/
public function setVariables(array $pairs) {
// NOTE: array_merge() instead of '+' keeps original and expected order.
$this->variables = \array_merge($this->variables, $pairs);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/StackFrame.php | src/StackFrame.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi;
use \Smuuf\Primi\Helpers\Colors;
use \Smuuf\Primi\Values\ModuleValue;
use \Smuuf\StrictObject;
class StackFrame {
use StrictObject;
/** Name of the function call (often the name of the called function). */
private string $name;
/**
* Module the stack frame points to.
*
* This is also used for resolving relative imports performed within the
* stack frame.
*/
private ?ModuleValue $module;
/** Callsite location. */
private ?Location $location;
public function __construct(
string $name,
?ModuleValue $module = \null,
?Location $location = \null
) {
$this->name = $name;
$this->module = $module;
$this->location = $location;
}
public function asString(): string {
$loc = $this->location
? " called from {$this->location->asString()}"
: '';
$mod = $this->module
? $this->module->getStringRepr()
: '<unknown>';
return "{$this->name} in {$mod}{$loc}";
}
/**
* Get name of the call.
*/
public function getCallName(): string {
return $this->name;
}
public function getModule(): ModuleValue {
return $this->module;
}
/**
* Get call location.
*/
public function getLocation(): ?Location {
return $this->location;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Logger.php | src/Logger.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi;
use \Smuuf\Primi\Cli\Term;
use \Smuuf\StrictObject;
abstract class Logger {
use StrictObject;
private static bool $enabled = \false;
public static function enable(bool $state = \true): void {
self::$enabled = $state;
}
public static function debug(string $msg): void {
if (!self::$enabled) {
return;
}
Term::stderr(Term::debug($msg));
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/ContextServices.php | src/ContextServices.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi;
use \Smuuf\StrictObject;
use \Smuuf\Primi\Code\AstProvider;
use \Smuuf\Primi\Tasks\TaskQueue;
use \Smuuf\Primi\Modules\Importer;
/**
* Service provider for specific context instances.
*/
class ContextServices {
use StrictObject;
private TaskQueue $taskQueue;
private Importer $importer;
private AstProvider $astProvider;
public function __construct(
private Context $ctx,
private Config $config,
) {}
public function getTaskQueue(): TaskQueue {
return $this->taskQueue
??= new TaskQueue($this->ctx);
}
public function getImporter(): Importer {
return $this->importer
??= new Importer($this->ctx, $this->config->getImportPaths());
}
public function getAstProvider(): AstProvider {
return $this->astProvider
??= new AstProvider($this->config->getTempDir());
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/EngineInternalError.php | src/Ex/EngineInternalError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
/**
* Errors that represent some malfunction in Primi interpreter engine. These
* should not happen - and if they do, it means that Primi itself contains an
* error (some kind of unhandled edge-case, for example).
*/
class EngineInternalError extends EngineError {
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/TypeError.php | src/Ex/TypeError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class TypeError extends RuntimeError {
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/SyntaxError.php | src/Ex/SyntaxError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
use \Smuuf\Primi\Location;
use \Smuuf\Primi\Code\Source;
use \Smuuf\Primi\Helpers\StringEscaping;
class SyntaxError extends ErrorException {
public function __construct(
Location $location,
?string $excerpt = \null,
?string $reason = \null
) {
$sanitizedExcerpt = $excerpt
? StringEscaping::escapeString($excerpt, '"')
: false;
$msg = \sprintf(
"Syntax error%s%s",
$reason
? \sprintf(" (%s)", \trim($reason))
: '',
$sanitizedExcerpt
? \sprintf(" near \"%s\"", \trim($sanitizedExcerpt))
: ''
);
parent::__construct($msg, $location);
}
public static function fromInternal(
InternalSyntaxError $e,
Source $source
): SyntaxError {
// Show a bit of code where the syntax error occurred.
// And don't ever have negative start index (that would take characters
// indexed from the end).
$excerpt = \mb_substr(
$source->getSourceCode(),
max($e->getErrorPos() - 5, 0),
10
);
return new SyntaxError(
new Location(
$source->getSourceId(),
$e->getErrorLine(),
$e->getLinePos()
),
$excerpt,
$e->getReason()
);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/ImportRelativeWithoutParentException.php | src/Ex/ImportRelativeWithoutParentException.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class ImportRelativeWithoutParentException extends EngineException {
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/UndefinedVariableError.php | src/Ex/UndefinedVariableError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class UndefinedVariableError extends LookupError {
public function __construct(string $msg) {
parent::__construct("Undefined variable '$msg'");
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/InternalPostProcessSyntaxError.php | src/Ex/InternalPostProcessSyntaxError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
/**
* Post-process internal syntax error exception that can be thrown by any
* kind of node handler's "::reduce()" method.
* @internal
*/
class InternalPostProcessSyntaxError extends EngineException {
/** Specific reason of the syntax error, if specified. */
private ?string $reason;
public function __construct(?string $reason = \null) {
$this->reason = $reason;
}
public function getReason(): ?string {
return $this->reason;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/ControlFlowException.php | src/Ex/ControlFlowException.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
abstract class ControlFlowException extends EngineException {
/**
* Statement causing such control flow mechanism. This is a default value
* and ultimately shouldn't appear anywhere, as it should always be
* overridden in child classes.
*
* @const string
*/
public const ID = 'control flow';
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/ImportBeyondTopException.php | src/Ex/ImportBeyondTopException.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class ImportBeyondTopException extends EngineException {
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/KeyError.php | src/Ex/KeyError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class KeyError extends LookupError {
public function __construct(string $key) {
parent::__construct("Undefined key $key");
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/SystemException.php | src/Ex/SystemException.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class SystemException extends BaseException {
// System exception (raised, for example, when SIGINT is sent via CTRL+C).
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/ContinueException.php | src/Ex/ContinueException.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class ContinueException extends ControlFlowException {
public const ID = 'continue';
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/EngineError.php | src/Ex/EngineError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
/**
* Errors that represent runtime errors within the engine, but which might
* not be necessarily caused by faulty logic in the engine itself. It may be
* that someone is using Primi in some unexpected or just plainly wrong way.
*/
class EngineError extends EngineException {
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/VariableImportError.php | src/Ex/VariableImportError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class VariableImportError extends ImportError {
public function __construct(string $symbol, string $dotpath) {
parent::__construct("Variable '{$symbol}' not found in module '{$dotpath}'");
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/EngineException.php | src/Ex/EngineException.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class EngineException extends BaseException {
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/BaseException.php | src/Ex/BaseException.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
abstract class BaseException extends \Exception {
use \Smuuf\StrictObject;
// All exceptions thrown by Primi will extend this base exception class.
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/LookupError.php | src/Ex/LookupError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class LookupError extends RuntimeError {
// Base class for lookup (variables/indexes/keys) errors.
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/BreakException.php | src/Ex/BreakException.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class BreakException extends ControlFlowException {
public const ID = 'break';
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/RuntimeError.php | src/Ex/RuntimeError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class RuntimeError extends ErrorException {
public function __construct(string $msg) {
$this->message = $msg;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/IndexError.php | src/Ex/IndexError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class IndexError extends LookupError {
public function __construct(int $index) {
parent::__construct("Undefined index $index");
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/UnhashableTypeException.php | src/Ex/UnhashableTypeException.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class UnhashableTypeException extends EngineException {
/** @var string Type name. */
protected $type;
public function __construct(string $type) {
parent::__construct("Unhashable type '$type'");
$this->type = $type;
}
public function getType(): string {
return $this->type;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/InternalSyntaxError.php | src/Ex/InternalSyntaxError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
/**
* Internal syntax error exception thrown by the parser, which operates on a
* raw string, without any knowledge about a specific source code or
* module/file.
*
* This internal syntax error should be caught and converted to a proper syntax
* error represented by the SyntaxError exception, that is aware of the
* module/file the error occurred.
*
* @internal
*/
class InternalSyntaxError extends EngineException {
/** Line number of the syntax error. */
private int $errorLine;
/** Position of the syntax error on specified line. */
private int $linePos;
/** Position of the syntax error in the whole source string. */
private int $errorPos;
/** Specific reason of the syntax error, if specified. */
private ?string $reason;
public function __construct(
int $errorLine,
int $errorPos,
int $linePos,
?string $reason = \null
) {
$this->errorLine = $errorLine;
$this->errorPos = $errorPos;
$this->linePos = $linePos;
$this->reason = $reason;
}
/**
* Get line number of the syntax error.
*/
public function getErrorLine(): int {
return $this->errorLine;
}
/**
* Get position of the syntax error in the whole source string.
*/
public function getErrorPos(): int {
return $this->errorPos;
}
/**
* Get position of the syntax error on the specified error line.
*/
public function getLinePos(): int {
return $this->linePos;
}
/**
* Get specific reason of the syntax error, if specified.
*/
public function getReason(): ?string {
return $this->reason;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/ImportError.php | src/Ex/ImportError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class ImportError extends RuntimeError {
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/BinaryOperationError.php | src/Ex/BinaryOperationError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
use \Smuuf\Primi\Values\AbstractValue;
class BinaryOperationError extends RuntimeError {
public function __construct(
string $op,
AbstractValue $left,
AbstractValue $right
) {
$msg = \sprintf(
"Cannot use operator '%s' with '%s' and '%s'",
$op, $left->getTypeName(), $right->getTypeName()
);
parent::__construct($msg);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/RelationError.php | src/Ex/RelationError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
use \Smuuf\Primi\Values\AbstractValue;
class RelationError extends RuntimeError {
public function __construct(string $op, AbstractValue $left, AbstractValue $right) {
$lType = $left->getTypeName();
$rType = $right->getTypeName();
$msg = "Undefined relation '$op' between '{$lType}' and '{$rType}'";
parent::__construct($msg);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/ArgumentCountError.php | src/Ex/ArgumentCountError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class ArgumentCountError extends RuntimeError {
protected int $passed;
protected int $expected;
public function __construct(
int $passed,
int $expected
) {
$this->passed = $passed;
$this->expected = $expected;
parent::__construct($this->buildMessage());
}
private function buildMessage(): string {
// The value did not match any of the types provided.
return \sprintf(
"Expected %s arguments but got %s",
$this->expected,
$this->passed
);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/ErrorException.php | src/Ex/ErrorException.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
use \Smuuf\Primi\Location;
use \Smuuf\Primi\StackFrame;
use \Smuuf\Primi\Helpers\Func;
/**
* All errors that Primi knows will extend this base error exception class.
* When thrown, information about location of the error must be known and
* passed into this exception object.
*/
class ErrorException extends BaseException {
/** Location object representing location of the error. */
private Location $location;
/**
* Traceback (which is really just the callstack).
*
* @var ?array<StackFrame>
*/
private ?array $traceback = \null;
/**
* @param ?array<StackFrame> $traceback
*/
public function __construct(
string $msg,
Location $location,
?array $traceback = \null
) {
$loc = "@ {$location->asString()}";
$tb = $traceback
? "\n" . Func::get_traceback_as_string($traceback)
: '';
parent::__construct("$msg {$loc}{$tb}");
$this->location = $location;
$this->traceback = $traceback;
}
/** Get object representing location of the error. */
public function getLocation(): Location {
return $this->location;
}
/**
* Traceback, if there's any.
*
* @return ?array<StackFrame>
*/
public function getTraceback(): ?array {
return $this->traceback;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/ModuleNotFoundError.php | src/Ex/ModuleNotFoundError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class ModuleNotFoundError extends ImportError {
public function __construct(string $symbol) {
parent::__construct("Module '{$symbol}' not found");
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Ex/CircularImportError.php | src/Ex/CircularImportError.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Ex;
class CircularImportError extends ImportError {
/**
* @param string $nextModule Name of the module causing circular
* import.
*/
public function __construct(string $nextModule) {
parent::__construct("Circular import when importing: {$nextModule}");
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/NumberValue.php | src/Values/NumberValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Ex\RuntimeError;
use \Smuuf\Primi\Stdlib\BuiltinTypes;
use \Smuuf\Primi\Helpers\Func;
/**
* NOTE: You should not instantiate this PHP class directly - use the helper
* `Interned::number()` factory to get these.
*
* NOTE: You should _never_ modify the internal $value property directly,
* as it may later lead to unpredictable results.
*/
class NumberValue extends AbstractBuiltinValue {
/** @const int Floating point precision for bcmath operations. */
const PRECISION = 128;
public const TYPE = "number";
/**
* NOTE: Protected because you should use the Interned factory for building
* these.
*/
public function __construct(string $number) {
$this->value = Func::normalize_decimal($number);
}
public function getType(): TypeValue {
return BuiltinTypes::getNumberType();
}
public function isTruthy(): bool {
// Intentionally loose comparison. Better than casting to bool, because:
// '00.000' == 0 // true (we want that), but
// (bool) '00.000' // true (and we want false)
return $this->value != 0;
}
public function getLength(): ?int {
return \strlen($this->value);
}
public function getStringRepr(): string {
return $this->value;
}
public function hash(): string {
// PHP interns all strings (which is how we internally represent
// numbers) by default, so use the string itself as the hash, as doing
// anything more would be more expensive.
return $this->value;
}
public function doAddition(AbstractValue $right): ?AbstractValue {
if (!$right instanceof NumberValue) {
return \null;
}
return new self(\bcadd($this->value, $right->value, self::PRECISION));
}
public function doSubtraction(AbstractValue $right): ?AbstractValue {
if (!$right instanceof NumberValue) {
return \null;
}
return new self(\bcsub($this->value, $right->value, self::PRECISION));
}
public function doMultiplication(AbstractValue $right): ?AbstractValue {
if (!$right instanceof NumberValue) {
return \null;
}
return new self(\bcmul($this->value, $right->value, self::PRECISION));
}
public function doDivision(AbstractValue $right): ?AbstractValue {
if (!$right instanceof NumberValue) {
return \null;
}
// Avoid division by zero.
if (\bccomp($right->value, "0") === 0) {
throw new RuntimeError("Division by zero");
}
return new self(\bcdiv($this->value, $right->value, self::PRECISION));
}
public function doPower(AbstractValue $right): ?AbstractValue {
if (!$right instanceof NumberValue) {
return \null;
}
// If the exponent is a fractional decimal, bcmath can't handle it.
if (\bccomp(
\bcmod($right->value, '1', NumberValue::PRECISION),
'0',
self::PRECISION
) !== 0
) {
throw new RuntimeError("Exponent must be integer");
}
return new self(\bcpow($this->value, $right->value, self::PRECISION));
}
public function isEqualTo(AbstractValue $right): ?bool {
if ($right instanceof BoolValue) {
// Comparison with numbers: The only truths:
// a) 1 == true
// b) 0 == false
// Anything else is false.
// Number is normalized upon construction, so for example '01.00' is
// stored as '1', or '0.00' is '0', so the mechanism below works.
return $this->value === ($right->value ? '1' : '0');
}
if ($right instanceof NumberValue) {
return \bccomp($this->value, $right->value, self::PRECISION) === 0;
}
return \null;
}
public function hasRelationTo(string $operator, AbstractValue $right): ?bool {
if (!$right instanceof NumberValue) {
return \null;
}
$l = $this->value;
$r = $right->value;
switch (\true) {
case $operator === ">":
return \bccomp($l, $r, self::PRECISION) === 1;
case $operator === "<":
return \bccomp($l, $r, self::PRECISION) === -1;
case $operator === ">=":
$tmp = \bccomp($l, $r, self::PRECISION);
return $tmp === 1 || $tmp === 0;
case $operator === "<=":
$tmp = \bccomp($l, $r, self::PRECISION);
return $tmp === -1 || $tmp === 0;
}
return \null;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/TypeValue.php | src/Values/TypeValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\Location;
use \Smuuf\Primi\MagicStrings;
use \Smuuf\Primi\Ex\RuntimeError;
use \Smuuf\Primi\Stdlib\BuiltinTypes;
use \Smuuf\Primi\Values\AbstractValue;
use \Smuuf\Primi\Values\AbstractBuiltinValue;
use \Smuuf\Primi\Helpers\Types;
use \Smuuf\Primi\Structures\CallArgs;
/**
* Instance of this PHP class represents a Primi object which acts as type/class
* in Primi.
*
* Everything in Primi is an object -> types/classes themselves are also
* objects (instances of some type/class XYZ) -> and that type/class XYZ is
* represented by this `TypeValue` PHP class.
*
* Therefore, the type "type" is an instance of itself.
*/
class TypeValue extends AbstractBuiltinValue {
public const TYPE = "type";
/**
* @param string $name Name of the type.
* @param ?TypeValue $parent Parent Primi type of this type.
* @param array<string, AbstractValue> $attrs
* @param bool $isFinal Final type/class cannot be used as a parent type.
* @param bool $isMutable IF true, it is possible to mutate type's attrs
* in userland.
*/
public function __construct(
protected string $name,
protected ?TypeValue $parent = \null,
protected array $attrs = [],
protected bool $isFinal = \true,
protected bool $isMutable = \false,
) {
if ($this->parent?->isFinal()) {
throw new RuntimeError("Class '{$this->parent->getName()}' cannot be used as a parent class");
}
}
public function getType(): TypeValue {
return BuiltinTypes::getTypeType();
}
public function attrGet(string $name): ?AbstractValue {
// Try to lookup the attr in this objects attrs. If not found, search
// the attr in its parent types. And don't bind any found (and then
// returned) functions to this type object instance.
// This means "SomeType.some_method()" won't get "SomeType" as
// first argument - which is what we want - we're accessing the function
// through a type, not from an instance.
if ($attr = Types::attr_lookup($this, $name)) {
return $attr;
}
// If the attr was not found in this type object nor its parent types,
// search through the type of this type object (its metatype/metaclass).
// If we find a function, we'll bind it to this type object instance -
// that's because in this case this type object really acts as an
// instance of its type (metatype).
return Types::attr_lookup($this->getType(), $name, $this);
}
/**
* Assign an attr to the type instance. Immutable types (those are the
* basic types that are in the core of Primi) can't be mutated (as they
* can be shared among different instances of Primi engine within a single
* PHP runtime). Userland types can be mutable.
*/
public function attrSet(string $name, AbstractValue $value): bool {
if (!$this->isMutable) {
return false;
}
$this->attrs[$name] = $value;
return \true;
}
/**
* Unified method to return a type object any type object *INHERITS FROM*,
* which is the 'object' object. Easy.
*/
public function getParentType(): ?TypeValue {
return $this->parent;
}
public function getStringRepr(): string {
return "<type '{$this->name}'>";
}
/**
* Get name of the type this object represents - as string.
*/
public function getName(): string {
return $this->name;
}
/**
* Is this Primi type/class forbidden to be a parent of another type/class?
*/
public function isFinal(): bool {
return $this->isFinal;
}
public function invoke(
Context $context,
?CallArgs $args = \null,
?Location $callsite = \null
): ?AbstractValue {
// Special case: If this type object is _the_ "type" type object.
if ($this->name === self::TYPE) {
if ($fn = Types::attr_lookup($this, MagicStrings::MAGICMETHOD_CALL)) {
return $fn->invoke($context, $args, $callsite);
}
}
// The other possibility: This type object represents other type
// than the "type" type itself - and calling this object should
// represent instantiation of new object that will have this type.
if ($fn = Types::attr_lookup($this, MagicStrings::MAGICMETHOD_NEW, $this)) {
// The static '__new__()' will receive type object as the first
// argument.
$newArgs = $args
? (new CallArgs([$this]))->withExtra($args)
: new CallArgs([$this]);
$result = $fn->invoke($context, $newArgs, $callsite);
if ($init = $result->attrGet(MagicStrings::MAGICMETHOD_INIT)) {
$init->invoke($context, $args);
}
return $result;
}
return \null;
}
public function dirItems(): ?array {
$fromParents = [];
$t = $this;
while ($t = $t->getParentType()) {
$fromParents = [...$t->dirItems(), ...$fromParents];
}
return \array_unique([
...$fromParents,
...\array_keys($this->attrs),
]);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/FuncValue.php | src/Values/FuncValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\Helpers\Interned;
use \Smuuf\Primi\Location;
use \Smuuf\Primi\MagicStrings;
use \Smuuf\Primi\Stdlib\BuiltinTypes;
use \Smuuf\Primi\Structures\CallArgs;
use \Smuuf\Primi\Structures\FnContainer;
/**
* @property FnContainer $value Internal map container.
*/
class FuncValue extends AbstractBuiltinValue {
public const TYPE = "func";
protected string $name;
public function __construct(
FnContainer $fn,
protected ?CallArgs $partialArgs = \null,
) {
$this->value = $fn;
$this->name = $fn->getName();
$this->attrs[MagicStrings::ATTR_NAME] = Interned::string($this->name);
}
public function withBind(AbstractValue $bind): MethodValue {
return new MethodValue($this->value, false, $bind);
}
public function getType(): TypeValue {
return BuiltinTypes::getFuncType();
}
/**
* Get full name of the function.
*/
public function getName(): ?string {
return $this->name;
}
public function isTruthy(): bool {
return \true;
}
public function getStringRepr(): string {
return \sprintf(
"<%s%s%s>",
$this->value->isPhpFunction() ? 'native ' : '',
$this->partialArgs ? 'partial function' : 'function',
$this->name ? ": {$this->name}" : '',
);
}
public function invoke(
Context $context,
?CallArgs $args = \null,
?Location $callsite = \null
): ?AbstractValue {
// If there are any partial args specified, create a new args object
// combining partial args (its kwargs have lower priority) combined
// with the currently passed args (its kwargs have higher priority).
if ($this->partialArgs) {
if ($args) {
$args = $this->partialArgs->withExtra($args);
} else {
$args = $this->partialArgs;
}
}
// Simply call the closure with passed arguments and other info.
return $this->value->callClosure($context, $args, $callsite);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/DictValue.php | src/Values/DictValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Ex\KeyError;
use \Smuuf\Primi\Ex\TypeError;
use \Smuuf\Primi\Ex\RuntimeError;
use \Smuuf\Primi\Ex\UnhashableTypeException;
use \Smuuf\Primi\Stdlib\BuiltinTypes;
use \Smuuf\Primi\Helpers\Func;
use \Smuuf\Primi\Structures\MapContainer;
/**
* @property MapContainer $value Internal map container.
*/
class DictValue extends AbstractBuiltinValue {
public const TYPE = "dict";
/**
* Create new instance from iterable list containing `[key, value]` Primi
* value tuples.
*
* @param TypeDef_PrimiObjectCouples $items
*/
public function __construct(iterable $items = []) {
$this->value = MapContainer::fromCouples($items);
}
public function __clone() {
$this->value = clone $this->value;
}
public function getType(): TypeValue {
return BuiltinTypes::getDictType();
}
public function getStringRepr(): string {
return self::convertToString($this);
}
public function getLength(): ?int {
return $this->value->count();
}
public function isTruthy(): bool {
return (bool) $this->value->count();
}
private static function convertToString(
self $self
): string {
$return = [];
foreach ($self->value->getItemsIterator() as [$k, $v]) {
// This avoids infinite loops with self-nested structures by
// checking whether circular detector determined that we
// would end up going in (infinite) circles.
$str = $v === $self
? \sprintf("{ *recursion (%s)* }", Func::object_hash($v))
: $v->getStringRepr();
$return[] = \sprintf("%s: %s", $k->getStringRepr(), $str);
}
return sprintf("{%s}", \implode(', ', $return));
}
/**
* @return \Iterator<int, AbstractValue>
*/
public function getIterator(): \Iterator {
yield from $this->value->getKeysIterator();
}
public function itemGet(AbstractValue $key): AbstractValue {
try {
if (!$this->value->hasKey($key)) {
throw new KeyError($key->getStringRepr());
}
} catch (UnhashableTypeException $e) {
throw new TypeError(\sprintf(
"Key is of unhashable type '%s'",
$e->getType()
));
}
return $this->value->get($key);
}
public function itemSet(?AbstractValue $key, AbstractValue $value): bool {
if ($key === \null) {
throw new RuntimeError("Must specify key when inserting into dict");
}
try {
$this->value->set($key, $value);
} catch (UnhashableTypeException $e) {
throw new TypeError(\sprintf(
"Key is of unhashable type '%s'",
$e->getType()
));
}
return \true;
}
public function isEqualTo(AbstractValue $right): ?bool {
if (!$right instanceof self) {
return \null;
}
return $this->value == $right->value;
}
/**
* The 'in' operator for dictionaries looks for keys and not values.
*/
public function doesContain(AbstractValue $right): ?bool {
try {
return $this->value->hasKey($right);
} catch (UnhashableTypeException $e) {
throw new TypeError(\sprintf(
"Key is of unhashable type '%s'",
$e->getType()
));
}
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/NotImplementedValue.php | src/Values/NotImplementedValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Stdlib\BuiltinTypes;
use \Smuuf\Primi\Values\AbstractValue;
/**
* Special constant object representing a "not implemented" information usable
* in userland.
*/
class NotImplementedValue extends AbstractBuiltinValue {
public const TYPE = "NotImplementedType";
public function getType(): TypeValue {
return BuiltinTypes::getNotImplementedType();
}
public function getStringRepr(): string {
return "NotImplemented";
}
public function hash(): string {
return 'const:notimplemented';
}
public function isTruthy(): bool {
return \true;
}
public function isEqualTo(AbstractValue $right): ?bool {
// NotImplemented doesn't know or care about other types - the
// relationship is undefined from its point of view.
if (!$right instanceof self) {
return \null;
}
// NotImplemented is always equal to NotImplemented.
return \true;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/AbstractValue.php | src/Values/AbstractValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\Location;
use \Smuuf\Primi\Ex\TypeError;
use \Smuuf\Primi\Ex\EngineError;
use \Smuuf\Primi\Ex\UnhashableTypeException;
use \Smuuf\Primi\Values\TypeValue;
use \Smuuf\Primi\Helpers\Func;
use \Smuuf\Primi\Helpers\Types;
use \Smuuf\Primi\Helpers\Interned;
use \Smuuf\Primi\Helpers\ValueFriends;
use \Smuuf\Primi\Structures\CallArgs;
use \Smuuf\Primi\Structures\FnContainer;
/**
* Primi value == Primi object in our case.
*/
abstract class AbstractValue extends ValueFriends {
/** @const string Name of Primi (object) type. */
public const TYPE = '__undefined__';
/**
* Take any PHP value and convert it into a Primi value object of an
* appropriate type.
*
* NOTE: We're not checking \is_callable on bare $value, because for example
* string 'time' would be determined to be the PHP's 'time' function and
* we do not want that (and it would also be a security issue).
*
* @param mixed $value
* @return AbstractValue
*/
public static function buildAuto($value) {
switch (\true) {
case $value instanceof AbstractValue:
return $value;
case $value === \null:
return Interned::null();
case \is_bool($value):
return Interned::bool($value);
case \is_int($value) || \is_float($value) || \is_numeric($value):
return Interned::number(Func::scientific_to_decimal((string) $value));
case \is_string($value):
return Interned::string($value);
case \is_array($value):
if (\is_callable($value)) {
return new FuncValue(FnContainer::buildFromClosure($value));
}
$inner = \array_map(__METHOD__, $value);
if (!\array_is_list($value)) {
return new DictValue(Func::array_to_couples($inner));
}
return new ListValue($inner);
case $value instanceof \Closure;
return new FuncValue(FnContainer::buildFromClosure($value));
}
// Otherwise throw an error.
throw new EngineError(\sprintf(
"Unable to auto-build Primi object from '%s'",
\get_debug_type($value)
));
}
/**
* Returns the core PHP value of this Primi value object.
*
* @return mixed
*/
final public function getCoreValue() {
return $this->value;
}
/**
* Returns an unambiguous string representation of internal value.
*
* If possible, is should be in such form that it the result of this
* method can be used as Primi source code to recreate that value.
*/
abstract public function getStringRepr(): string;
/**
* Returns a string representation of value.
*/
public function getStringValue(): string {
return $this->getStringRepr();
}
/**
* Returns dict array with this all attributes of this value.
*
* @return array<string, AbstractValue>
*/
final public function getAttrs(): array {
return $this->attrs;
}
/**
* Return the Primi type object this Primi value is instance of.
*/
abstract public function getType(): TypeValue;
/**
* Return the name of Primi type of this value as string.
*/
public function getTypeName(): string {
return $this->getType()->getName();
}
// Length.
/**
* Values can report the length of it (i.e. its internal value).
* Values without any meaningful length can report null (default).
*/
public function getLength(): ?int {
return \null;
}
//
// Truthiness.
//
/**
* All values must be able to tell if they're truthy or falsey.
* All values are truthy unless they tell otherwise.
*/
public function isTruthy(): bool {
return \true;
}
//
// Comparisons - Equality.
//
/**
* All values support comparison.
*
* Default implementation below says that two values are equal if they're
* the same PHP object.
*/
public function isEqualTo(
AbstractValue $right
): ?bool {
return $this === $right;
}
//
// Comparisons - Relation.
//
/**
* If a value knows how to evaluate relation to other values, it shall
* define that by overriding this default logic. (By default a value does
* not know anything about its relation of itself to other values.)
*
* Relation in this scope means the result of <, >, <=, >= operations.
*/
public function hasRelationTo(string $operator, AbstractValue $right): ?bool {
return \null;
}
public function doesContain(AbstractValue $right): ?bool {
return \null;
}
public function doAddition(AbstractValue $right): ?AbstractValue {
return \null;
}
public function doSubtraction(AbstractValue $right): ?AbstractValue {
return \null;
}
public function doMultiplication(AbstractValue $right): ?AbstractValue {
return \null;
}
public function doDivision(AbstractValue $right): ?AbstractValue {
return \null;
}
public function doPower(AbstractValue $right): ?AbstractValue {
return \null;
}
/**
* Called when used as `some_value()`.
*
* If the value is not callable, throws TypeError.
*
* This API differs from "return null when unsupported" used elsewhere,
* because then someone would always have to check if the returned value
* was a PHP null, to find out the value does not support invocation. Every
* time, after each invocation (which doesn't even make much sense).
*
* This way the exception is just simply thrown once.
*
* @param Context $context Runtime context of the call-site.
* @param ?CallArgs $args Args object with call arguments (optional).
* @param ?Location $callsite Call site location (optional).
* @throws TypeError
*/
public function invoke(
Context $context,
?CallArgs $args = \null,
?Location $callsite = \null
): ?AbstractValue {
throw new TypeError("'{$this->getTypeName()}' object is not callable");
}
/**
* @return ?\Iterator<int, AbstractValue>
*/
public function getIterator(): ?\Iterator {
return \null;
}
/**
* Assign a value under specified key into this value.
*
* Must return `true` on successful assignment, or `false` if assignment is
* not supported.
*/
public function itemSet(?AbstractValue $key, AbstractValue $value): bool {
return \false;
}
/**
* Returns some internal value by specified key.
*
* Must return some value object, or `null` if such operation is not
* supported.
*/
public function itemGet(AbstractValue $key): ?AbstractValue {
return \null;
}
/**
* Assign an attr to the value.
*
* Must return true on successful assignment, or `false` if assignment is
* not supported.
*
* NOTE: This attribute name can only be strings, so there's no need to
* accept StringValue as $key.
*/
public function attrSet(string $name, AbstractValue $value): bool {
return \false;
}
/**
* Returns an attr from the value.
*
* This must return either a value object (which is an attribute of this
* value object) or `null`, if not found.
*
* If this returns `null`, object hierarchy will be traversed upwards and
* attr will be searched in the parent object.
*
* This API is differs from, for example, `self::itemGet()`, as `null` does
* NOT represent an "unsupported" operation, but rather "it's not here, try
* elsewhere".
*
* As the above is expected to be the most common thing to do, unsupported
* attr access instead should throw a RuntimeError.
*
* NOTE: This attribute name can only be strings, so there's no need to
* accept StringValue as $key.
*/
public function attrGet(string $name): ?AbstractValue {
return $this->attrs[$name]
?? Types::attr_lookup($this->getType(), $name, $this);
}
/**
* Return attribute from this Primi object - without any inheritance or
* type shenanigans.
*
* For internal usage by Primi engine - keeping the $attr property of
* PHP AbstractValue class protected.
*
* @internal
*/
final public function rawAttrGet(string $name): ?AbstractValue {
return $this->attrs[$name] ?? \null;
}
/**
* Returns a scalar value to be used as a hash value that can be used as
* scalar key for PHP arrays used in Primi internals.
*
* @throws UnhashableTypeException
*/
public function hash(): string {
throw new UnhashableTypeException($this->getTypeName());
}
/**
* Return PHP array contain listing of items/attrs inside the object.
*
* This is mainly for the builtin dir() function Primi provides for
* easy inspection of contents of an object.
*
* @return array<string>
*/
public function dirItems(): ?array {
$fromParents = $this->getType()->dirItems();
$t = $this->getType();
while ($t = $t->getParentType()) {
$fromParents = [...$t->dirItems(), ...$fromParents];
}
return \array_unique([
...$fromParents,
...\array_keys($this->attrs),
]);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/ModuleValue.php | src/Values/ModuleValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Scope;
use \Smuuf\Primi\Stdlib\BuiltinTypes;
/**
* @property Scope|null $value Global scope of the module or null, if
* the module has no global scope (which is handy for "anonymous" modules that
* wrap Primi functions that are wrappers for native PHP functions which might
* not be placed in any module).
*/
class ModuleValue extends AbstractBuiltinValue {
public const TYPE = "module";
/** Name of the module */
protected string $name;
/** Package name of the module. */
protected string $package;
public function __construct(
string $name,
string $package = '',
?Scope $scope = \null
) {
$this->name = $name;
$this->package = $package;
$this->value = $scope;
}
public function getType(): TypeValue {
return BuiltinTypes::getModuleType();
}
/**
* Get full name of the module.
*/
public function getName(): string {
return $this->name;
}
/**
* Get package name of the module.
*/
public function getPackage(): string {
return $this->package;
}
public function getStringRepr(): string {
return "<module: {$this->name}>";
}
/**
* Return number of variables in the module's scope.
*/
public function getLength(): ?int {
return \count($this->value->getVariables());
}
/**
* Returns true if there are any variables present in the module's scope.
*/
public function isTruthy(): bool {
return (bool) $this->value->getVariables();
}
/**
* Accessing module attributes equals to accessing variables from module's
* scope.
*/
public function attrGet(string $key): ?AbstractValue {
return $this->value->getVariable($key);
}
/**
* Setting module attributes equals to setting variables into module's
* scope.
*/
public function attrSet(string $name, AbstractValue $value): bool {
$this->value->setVariable($name, $value);
return \true;
}
/**
* The 'in' operator for dictionaries looks for keys and not values.
*/
public function doesContain(AbstractValue $key): ?bool {
return (bool) $this->value->getVariable($key->getStringValue());
}
public function dirItems(): ?array {
return \array_keys($this->value->getVariables());
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/BuiltinTypeValue.php | src/Values/BuiltinTypeValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
/**
* Sometimes Primi engine needs to differentiate between:
* 1) Builtin global and immutable Primi types are at the core of Primi
* engine.
* 2) All other Primi types (either implemented in PHP or created in Primi
* userland).
*
* Therefore all Primi type objects that represent the most basic builtin types
* as mentioned 1) will be represented as inctances of this PHP class (instead
* of just PHP `TypeValue` class).
*
* @see \Smuuf\Primi\Stdlib\BuiltinTypes
* @internal
*/
final class BuiltinTypeValue extends TypeValue {
public function getStringRepr(): string {
return "<builtin type '{$this->name}'>";
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/BoolValue.php | src/Values/BoolValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Stdlib\BuiltinTypes;
use \Smuuf\Primi\Values\NumberValue;
/**
* NOTE: You should not instantiate this PHP class directly - use the helper
* `Interned::bool()` factory to get these.
*/
class BoolValue extends AbstractBuiltinValue {
public const TYPE = "bool";
public function __construct(bool $value) {
$this->value = $value;
}
public function getType(): TypeValue {
return BuiltinTypes::getBoolType();
}
public function getStringRepr(): string {
return $this->value ? 'true' : 'false';
}
public function hash(): string {
return $this->value ? '1' : '0';
}
public function isTruthy(): bool {
return $this->value;
}
public function isEqualTo(AbstractValue $right): ?bool {
if ($right instanceof NumberValue) {
// Comparison with numbers - the only rules:
// a) 1 == true
// b) 0 == false
// c) Anything else is false.
// Number is normalized upon construction, so for example '01.00' is
// stored as '1', or '0.00' is '0', so the mechanism below works.
return $right->value === ($this->value ? '1' : '0');
}
if (!$right instanceof BoolValue) {
return \null;
}
return $this->value === $right->isTruthy();
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/MethodValue.php | src/Values/MethodValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Ex\EngineError;
use \Smuuf\Primi\Stdlib\BuiltinTypes;
use \Smuuf\Primi\Structures\CallArgs;
use \Smuuf\Primi\Structures\FnContainer;
/**
* NOTE: Although this PHP class extends from `FuncValue`, in Primi runtime
* the `MethodType` doesn't extend `FuncType` but actually extends `object`
* directly.
*
* @internal
* @property FnContainer $value Internal map container.
*/
class MethodValue extends FuncValue {
public const TYPE = "method";
public function __construct(
FnContainer $fn,
private bool $isStatic = false,
?AbstractValue $bind = \null,
) {
if ($isStatic && $bind) {
throw new EngineError("Cannot create bound static method");
}
parent::__construct(
$fn,
$bind ? new CallArgs([$bind]) : null,
);
}
public function withBind(AbstractValue $bind): self {
if ($this->isStatic) {
return $this;
}
return new MethodValue($this->value, false, $bind);
}
public function getType(): TypeValue {
return BuiltinTypes::getMethodType();
}
public function getStringRepr(): string {
$adjectives = \array_filter([
$this->value->isPhpFunction() ? 'native' : '',
$this->isStatic ? 'static' : '',
$this->partialArgs ? 'bound' : '',
]);
return \sprintf(
"<%s%s%s>",
\implode(' ', \array_filter($adjectives)) . ($adjectives ? ' ' : ''),
'method',
$this->name ? ": {$this->name}" : '',
);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/ListValue.php | src/Values/ListValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Ex\RuntimeError;
use \Smuuf\Primi\Stdlib\BuiltinTypes;
use \Smuuf\Primi\Helpers\Func;
use \Smuuf\Primi\Helpers\Indices;
class ListValue extends AbstractBuiltinValue {
public const TYPE = "list";
/**
* @param array<AbstractValue> $items
*/
public function __construct(array $items) {
// Ensuring the list is indexed from 0. Keys will be ignored.
$this->value = \array_values($items);
}
public function __clone() {
// Contents of a list is internally really just a PHP array of other
// Primi value objects, so we need to do deep copy.
\array_walk($this->value, function(&$item) {
$item = clone $item;
});
}
public function getType(): TypeValue {
return BuiltinTypes::getListType();
}
public function getLength(): ?int {
return \count($this->value);
}
public function isTruthy(): bool {
return (bool) $this->value;
}
public function getStringRepr(): string {
return self::convertToString($this);
}
private static function convertToString(
self $self
): string {
$return = [];
foreach ($self->value as $item) {
// This avoids infinite loops with self-nested structures by
// checking whether circular detector determined that we
// would end up going in (infinite) circles.
$return[] = $item === $self
? \sprintf("[ *recursion (%s)* ]", Func::object_hash($item))
: $item->getStringRepr();
}
return \sprintf("[%s]", \implode(', ', $return));
}
/**
* @return \Iterator<int, AbstractValue>
*/
public function getIterator(): \Iterator {
yield from $this->value;
}
public function itemGet(AbstractValue $index): AbstractValue {
if (
!$index instanceof NumberValue
|| !Func::is_round_int($index->value)
) {
throw new RuntimeError("List index must be integer");
}
$actualIndex = Indices::resolveIndexOrError(
(int) $index->value,
$this->value
);
// Numbers are internally stored as strings, so get it as PHP integer.
return $this->value[$actualIndex];
}
public function itemSet(?AbstractValue $index, AbstractValue $value): bool {
if ($index === \null) {
$this->value[] = $value;
return \true;
}
if (
!$index instanceof NumberValue
|| !Func::is_round_int($index->value)
) {
throw new RuntimeError("List index must be integer");
}
$actualIndex = Indices::resolveIndexOrError(
(int) $index->value,
$this->value
);
$this->value[$actualIndex] = $value;
return \true;
}
public function doAddition(AbstractValue $right): ?AbstractValue {
// Lists can only be added to lists.
if (!$right instanceof self) {
return \null;
}
return new self(\array_merge($this->value, $right->value));
}
public function doMultiplication(AbstractValue $right): ?AbstractValue {
// Lists can only be multiplied by a number...
if (!$right instanceof NumberValue) {
return \null;
}
// ... and that number must be an integer.
if (!Func::is_round_int((string) $right->value)) {
throw new RuntimeError("List can be only multiplied by an integer");
}
// Helper contains at least one empty array, so array_merge doesn't
// complain about empty arguments for PHP<7.4.
$helper = [[]];
// Multiplying lists by an integer N returns a new list consisting of
// the original list appended to itself N-1 times.
$limit = $right->value;
for ($i = 0; $i++ < $limit;) {
$helper[] = $this->value;
}
// This should be efficient, since a new array (apart from the empty
// helper) is created only once, using the splat operator on the helper,
// which contains only references to the original array (and not copies
// of it).
return new self(\array_merge(...$helper));
}
public function isEqualTo(AbstractValue $right): ?bool {
if (!$right instanceof ListValue) {
return \null;
}
// Simple comparison of both arrays should be sufficient.
// PHP manual describes object (which are in these arrays) comparison:
// Two object instances are equal if they have the same attributes and
// values (values are compared with ==).
// See https://www.php.net/manual/en/language.oop5.object-comparison.php.
return $this->value == $right->value;
}
public function doesContain(AbstractValue $right): ?bool {
// Let's see if the needle object is in list value (which is an array of
// Primi value objects). Non-strict search allows to match dictionaries
// with the same key-values but in different order.
return \in_array($right, $this->value);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/InstanceValue.php | src/Values/InstanceValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\MagicStrings;
use \Smuuf\Primi\Values\TypeValue;
use \Smuuf\Primi\Helpers\Func;
use \Smuuf\Primi\Helpers\Interned;
use \Smuuf\Primi\Structures\CallArgs;
/**
* Class for representing instances of userland classes/types.
*/
class InstanceValue extends AbstractValue {
protected Context $ctx;
protected TypeValue $type;
public function __construct(TypeValue $type, Context $ctx) {
$this->type = $type;
$this->ctx = $ctx;
}
/**
* Returns a string representation of value.
*/
public function getStringValue(): string {
if ($magic = $this->attrGet(MagicStrings::MAGICMETHOD_STRING)) {
$result = $magic->invoke($this->ctx);
return $result->getStringValue();
}
return parent::getStringValue();
}
public function getStringRepr(): string {
if ($magic = $this->attrGet(MagicStrings::MAGICMETHOD_REPR)) {
$result = $magic->invoke($this->ctx);
return $result->getStringValue();
}
$id = Func::object_hash($this);
return "<instance '{$this->type->getName()}' {$id}>";
}
public function getType(): TypeValue {
return $this->type;
}
public function getTypeName(): string {
return $this->type->getName();
}
public function attrSet(string $key, AbstractValue $value): bool {
$this->attrs[$key] = $value;
return \true;
}
public function isEqualTo(
AbstractValue $right
): ?bool {
if ($magic = $this->attrGet(MagicStrings::MAGICMETHOD_OP_EQ)) {
$result = $magic->invoke($this->ctx, new CallArgs([$right]));
if ($result === Interned::constNotImplemented()) {
return null;
}
return $result->isTruthy();
}
return parent::isEqualTo($right);
}
public function doAddition(AbstractValue $right): ?AbstractValue {
if ($magic = $this->attrGet(MagicStrings::MAGICMETHOD_OP_ADD)) {
$result = $magic->invoke($this->ctx, new CallArgs([$right]));
if ($result === Interned::constNotImplemented()) {
return null;
}
return $result;
}
return parent::doAddition($right);
}
public function doSubtraction(AbstractValue $right): ?AbstractValue {
if ($magic = $this->attrGet(MagicStrings::MAGICMETHOD_OP_SUB)) {
$result = $magic->invoke($this->ctx, new CallArgs([$right]));
if ($result === Interned::constNotImplemented()) {
return null;
}
return $result;
}
return parent::doSubtraction($right);
}
public function dirItems(): ?array {
return \array_merge(
\array_keys($this->attrs),
$this->getType()->dirItems()
);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/NullValue.php | src/Values/NullValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Stdlib\BuiltinTypes;
use \Smuuf\Primi\Values\AbstractValue;
/**
* NOTE: You should not instantiate this PHP class directly - use the helper
* `Interned::null()` factory to get these.
*/
class NullValue extends AbstractBuiltinValue {
public const TYPE = "null";
public function getType(): TypeValue {
return BuiltinTypes::getNullType();
}
public function getStringRepr(): string {
return "null";
}
public function hash(): string {
return 'n';
}
public function isTruthy(): bool {
return \false;
}
public function isEqualTo(AbstractValue $right): ?bool {
// Null doesn't know or care about other types - the relationship
// is undefined from its point of view.
if (!$right instanceof self) {
return \null;
}
// Null is always equal to null.
return \true;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/StringValue.php | src/Values/StringValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Ex\TypeError;
use \Smuuf\Primi\Ex\IndexError;
use \Smuuf\Primi\Ex\RuntimeError;
use \Smuuf\Primi\Stdlib\BuiltinTypes;
use \Smuuf\Primi\Helpers\Func;
use \Smuuf\Primi\Helpers\Types;
use \Smuuf\Primi\Helpers\StringEscaping;
/**
* NOTE: You should not instantiate this PHP class directly - use the helper
* `Interned::string()` factory to get these.
*/
class StringValue extends AbstractBuiltinValue {
public const TYPE = "string";
public function __construct(string $str) {
$this->value = $str;
}
public function getType(): TypeValue {
return BuiltinTypes::getStringType();
}
public function getLength(): ?int {
return \mb_strlen($this->value);
}
public function isTruthy(): bool {
return $this->value !== '';
}
public function getStringValue(): string {
return $this->value;
}
public function hash(): string {
// PHP interns all strings by default, so use the string itself as
// the hash, as doing anything more would be more expensive.
return $this->value;
}
public function getStringRepr(): string {
// We are about to put double-quotes around the return value,
// so let's "escape" double-quotes present in the string value.
$escaped = StringEscaping::escapeString($this->value, '"');
return "\"$escaped\"";
}
public function doAddition(AbstractValue $right): ?AbstractValue {
if (!$right instanceof StringValue) {
return \null;
}
return new self($this->value . $right->value);
}
public function doSubtraction(AbstractValue $right): ?AbstractValue {
if (!Types::is_any_of_types($right, StringValue::class, RegexValue::class)) {
return \null;
}
if ($right instanceof RegexValue) {
$match = \preg_replace($right->value, '', $this->value);
return new self($match);
}
$new = \str_replace($right->value, '', $this->value);
return new self($new);
}
public function doMultiplication(AbstractValue $right): ?AbstractValue {
if (!$right instanceof NumberValue) {
return \null;
}
$multiplier = $right->value;
if (Func::is_round_int($multiplier) && $multiplier >= 0) {
return new self(\str_repeat($this->value, (int) $multiplier));
}
throw new RuntimeError("String multiplier must be a positive integer");
}
public function isEqualTo(AbstractValue $right): ?bool {
if (!Types::is_any_of_types($right, StringValue::class, RegexValue::class)) {
return \null;
}
if ($right instanceof RegexValue) {
return (bool) \preg_match($right->value, $this->value);
} else {
return $this->value === $right->value;
}
}
public function hasRelationTo(string $operator, AbstractValue $right): ?bool {
if (!Types::is_any_of_types($right, StringValue::class)) {
return \null;
}
$l = $this->value;
$r = $right->value;
switch (\true) {
case $operator === ">":
return $l > $r;
case $operator === "<":
return $l < $r;
case $operator === ">=":
return $l >= $r;
case $operator === "<=":
return $l <= $r;
}
return \null;
}
public function itemGet(AbstractValue $index): AbstractValue {
if (!Func::is_round_int($index->value)) {
throw new RuntimeError("String index must be integer");
}
// Even though in other "container" types (eg. list, tuple) we need
// to manually handle negative indices via helper
// function Indices::resolveIndexOrError(), PHP supports negative
// indixes for strings out-of-the-box since PHP 7.1, so we don't need
// to do any magic here.
// See https://wiki.php.net/rfc/negative-string-offsets
$index = (int) $index->value;
if (!isset($this->value[$index])) {
throw new IndexError($index);
}
return new self($this->value[$index]);
}
/**
* @return \Iterator<int, AbstractValue>
*/
public function getIterator(): \Iterator {
return self::utfSplit($this->value);
}
public function doesContain(AbstractValue $right): ?bool {
if (!Types::is_any_of_types($right, StringValue::class, RegexValue::class)) {
throw new TypeError("'in' for string requires 'string|regex' as left operand");
}
if ($right instanceof RegexValue) {
return (bool) \preg_match($right->value, $this->value);
}
return \mb_strpos($this->value, $right->value) !== \false;
}
// Helpers.
/**
* Return a generator yielding each of this string's characters as
* new one-character StringValue objects.
*
* @return \Generator<int, self, null, void>
*/
private static function utfSplit(string $string): \Generator {
$strlen = \mb_strlen($string);
for ($i = 0; $i < $strlen; $i++) {
yield new self(\mb_substr($string, $i, 1));
}
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/RegexValue.php | src/Values/RegexValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Stdlib\BuiltinTypes;
use \Smuuf\Primi\Helpers\Types;
/**
* NOTE: You should not instantiate this PHP class directly - use the helper
* `Interned::regex()` factory to get these.
*/
class RegexValue extends AbstractBuiltinValue {
public const TYPE = "regex";
/**
* Prepared string for 'truthiness' evaluation.
* Regex value is truthy if the actual pattern, without delimiters and
* unicode modifier, is empty.
*/
const EMPTY_REGEX = "\x07\x07u";
public function __construct(string $regex) {
// We'll be using ASCII \x07 (bell) character as delimiters, so
// we won't need to deal with any escaping of input.
$this->value = "\x07$regex\x07u";
}
public function getType(): TypeValue {
return BuiltinTypes::getRegexType();
}
public function isTruthy(): bool {
return $this->value !== self::EMPTY_REGEX;
}
public function getStringRepr(): string {
// Cut off the first delim and the last delim + "u" modifier.
$string = $this->value;
$string = \mb_substr($string, 1, \mb_strlen($string) - 3);
return "rx\"{$string}\"";
}
public function getStringValue(): string {
// Cut off the first delim and the last delim + "u" modifier.
$string = $this->value;
return \mb_substr($string, 1, \mb_strlen($string) - 3);
}
public function isEqualTo(AbstractValue $right): ?bool {
if (!Types::is_any_of_types($right, StringValue::class, RegexValue::class)) {
return \null;
}
if ($right instanceof RegexValue) {
return $this->value === $right->value;
}
return (bool) \preg_match($this->value, $right->value);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/AbstractBuiltinValue.php | src/Values/AbstractBuiltinValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
/**
* Base PHP class for representing all Primi values/object builtin into the
* engine.
*/
abstract class AbstractBuiltinValue extends AbstractValue {
public function getTypeName(): string {
return static::TYPE;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/TupleValue.php | src/Values/TupleValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Ex\RuntimeError;
use \Smuuf\Primi\Stdlib\BuiltinTypes;
use \Smuuf\Primi\Helpers\Func;
use \Smuuf\Primi\Helpers\Indices;
/**
* @property array<AbstractValue> $value Internal tuple container.
*/
class TupleValue extends AbstractBuiltinValue {
public const TYPE = "tuple";
/**
* Computing hash can be expensive, so for this immutable type, let's
* memoize it, because it won't (should not) change.
*/
private ?string $savedHash = \null;
/**
* Create new instance from iterable list containing `[key, value]` Primi
* value tuples.
*
* @param array<AbstractValue> $items
*/
public function __construct(array $items = []) {
// Let's make sure the internal array is indexed from zero.
$this->value = \array_values($items);
}
public function __clone() {
// Contents of a tuple is internally really just a PHP array of other
// Primi value objects, so we need to do deep copy.
\array_walk($this->value, function(&$item) {
$item = clone $item;
});
}
public function getType(): TypeValue {
return BuiltinTypes::getTupleType();
}
public function getStringRepr(): string {
return self::convertToString($this);
}
private static function convertToString(
self $self
): string {
$return = [];
foreach ($self->value as $item) {
// This avoids infinite loops with self-nested structures by
// checking whether circular detector determined that we
// would end up going in (infinite) circles.
$return[] = $item === $self
? \sprintf("( *recursion (%s)* )", Func::object_hash($item))
: $item->getStringRepr();
}
return \sprintf("(%s)", \implode(', ', $return));
}
public function hash(): string {
if ($this->savedHash !== \null) {
return $this->savedHash;
}
$r = $this->savedHash = \array_reduce(
$this->value,
static fn($c, $i) => \md5("{$c},{$i->hash()}"),
''
);
return $r;
}
public function getLength(): ?int {
return \count($this->value);
}
public function isTruthy(): bool {
return (bool) $this->value;
}
/**
* @return \Iterator<int, AbstractValue>
*/
public function getIterator(): \Iterator {
yield from $this->value;
}
public function itemGet(AbstractValue $index): AbstractValue {
if (
!$index instanceof NumberValue
|| !Func::is_round_int($index->value)
) {
throw new RuntimeError("Tuple index must be integer");
}
$actualIndex = Indices::resolveIndexOrError(
(int) $index->value,
$this->value
);
// Numbers are internally stored as strings, so get it as PHP integer.
return $this->value[$actualIndex];
}
public function isEqualTo(AbstractValue $right): ?bool {
if (!$right instanceof self) {
return \null;
}
return $this->value == $right->value;
}
public function doesContain(AbstractValue $right): ?bool {
// Let's see if the needle object is in tuple value (which is internally
// an array of Primi value objects).
return \in_array($right, $this->value);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Values/IteratorFactoryValue.php | src/Values/IteratorFactoryValue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Values;
use \Smuuf\Primi\Stdlib\BuiltinTypes;
/**
* Class for representing dynamically created Primi iterables.
*
* For example, we want "range()" function (implemented in PHP) to return
* not only a one-time iterator, but an iterable that allows multiple uses
* as an iterator. Thus, PHP code handling the "range()" builtin Primi function
* will return this "iteratorfactory" with a callable acting as a factory
* function embedded within it.
*
* Then, every time someone requests an iterator from this "iteratorfactory",
* the factory callable will be executed and a brand-new generator is then
* used as the actual internal iterator which then yields the expected values.
*/
class IteratorFactoryValue extends AbstractBuiltinValue {
public const TYPE = "iteratorfactory";
protected string $name;
/**
* @param callable(mixed ...$args): \Iterator<AbstractValue> $factory
*/
public function __construct(callable $factory, string $name) {
$this->value = $factory;
$this->name = $name;
}
public function getType(): TypeValue {
return BuiltinTypes::getIteratorFactoryType();
}
public function getStringRepr(): string {
return "<iteratorfactory '{$this->name}'>";
}
/**
* @return \Iterator<AbstractValue>
*/
public function getIterator(): \Iterator {
yield from ($this->value)();
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/Func.php | src/Helpers/Func.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\StackFrame;
use \Smuuf\Primi\Ex\TypeError;
use \Smuuf\Primi\Ex\EngineError;
use \Smuuf\Primi\Ex\BaseException;
use \Smuuf\Primi\Parser\GrammarHelpers;
use \Smuuf\Primi\Values\StringValue;
use \Smuuf\Primi\Values\NumberValue;
use \Smuuf\Primi\Values\AbstractValue;
use \Smuuf\Primi\Handlers\HandlerFactory;
use \Smuuf\Primi\Structures\MapContainer;
use \Smuuf\Primi\Values\TypeValue;
abstract class Func {
/**
* Pair of regexes to match zeroes at the beginning and at the end of a
* string, if they're not the last zeroes on that side of decimal point.
*
* @const string[][]
*/
private const DECIMAL_TRIMMING_REGEXES = [
['#^(-?)0+(\d)#S', '#(\.0+$)|((\.\d+?[1-9]?)0+$)#S'],
['\1\2', '\3']
];
/**
* Returns a generator yielding `[primi key, primi value]` tuples from some
* PHP array. If the value is not an instance of `AbstractValue`
* object, it will be converted automatically to a `AbstractValue` object.
*
* @param array<mixed, mixed> $array
* @return TypeDef_PrimiObjectCouples
*/
public static function array_to_couples(array $array): iterable {
foreach ($array as $key => $value) {
yield [
AbstractValue::buildAuto($key),
AbstractValue::buildAuto($value)
];
}
}
/**
* Convert iterable of couples _(PHP 2-tuple arrays with two items
* containing Primi objects, where first item must a string object
* representing a valid Primi variable name)_ to PHP dict array mapping
* pairs of `['variable_name' => Some Primi object]`.
*
* @param TypeDef_PrimiObjectCouples $couples
* @return array<string, AbstractValue> PHP dict array mapping of variables.
* @throws TypeError
*/
public static function couples_to_variables_array(
iterable $couples,
string $intendedTarget
): array {
$attrs = [];
foreach ($couples as [$k, $v]) {
if (!$k instanceof StringValue) {
throw new TypeError(
"$intendedTarget is not a string but '{$k->getTypeName()}'");
}
$varName = $k->getStringValue();
if (!GrammarHelpers::isValidName($varName)) {
throw new TypeError(
"$intendedTarget '$varName' is not a valid name");
}
$attrs[$varName] = $v;
}
return $attrs;
}
/**
* Returns PHP iterable returning couples (2-tuples) of `[key, value]` from
* a iterable Primi object that can be interpreted as a mapping.
* Best-effort-style.
*
* @return TypeDef_PrimiObjectCouples
* @throws TypeError
*/
public static function mapping_to_couples(AbstractValue $value) {
$internalValue = $value->getCoreValue();
if ($internalValue instanceof MapContainer) {
// If the internal value already is a mapping represented by
// MapContainer, just return its items-iterator.
return $internalValue->getItemsIterator();
} else {
// We can also try to extract mapping from Primi iterable objects.
// If the Primi object provides an iterator, we're going to iterate
// over its items AND if each of these items is an iterable with
// two items in it, we can extract mapping from it - and convert
// it into Primi object couples.
// First, we try if the passed Primi object supports iteration.
$items = $value->getIterator();
if ($items === \null) {
throw new TypeError("Unable to create mapping from non-iterable");
}
// We prepare the result container for couples, which will be
// discarded if we encounter any errors when putting results in it.
$couples = [];
$i = -1;
foreach ($items as $item) {
$couple = [];
$i++;
$j = 0;
// Second, for each of the item of the top-iterator we check
// if the item also supports iteration.
$subitems = $item->getIterator();
if ($subitems === \null) {
throw new TypeError(
"Unable to create mapping from iterable: "
. "item #$i is not iterable"
);
}
foreach ($subitems as $subitem) {
$j++;
// Third, since we want to build and return iterable
// containing couples, the item needs to contain
// exactly two sub-items.
if ($j === 3) {
throw new TypeError(
"Unable to create mapping from iterable: "
. "item #$i contains more than two items ($j)"
);
}
$couple[] = $subitem;
}
if ($j < 2) {
throw new TypeError(
"Unable to create mapping from iterable: "
. "item #$i contains less than two items ($j)"
);
}
$couples[] = $couple;
}
// All went well, return iterable (list array) with all gathered
// couples.
return $couples;
}
}
public static function is_round_int(string $input): bool {
if (!\is_numeric($input)) {
return \false;
}
return \round((float) $input) == $input; // Intentionally ==
}
public static function is_decimal(string $input): bool {
return (bool) \preg_match('#^[+-]?\d+(\.\d+)?$#S', $input);
}
/**
* Returns a 8 character long hash unique for any existing PHP object and
* which is always the same for a specific PHP object instance.
*
* This is based on `spl_object_hash` but is visibly more "random" than what
* `spl_object_hash`.
*
* As is the case with `spl_object_hash`, a hash can be reused by a new
* object if the previous object with the same hash was destroyed during
* the PHP runtime.
*/
public static function object_hash(object $o): string {
return \substr(\md5(\spl_object_hash($o)), 0, 8);
}
/**
* Return a 8 character long hash for any string.
*
* This hash should be used for "information" purposes - for example
* to help a quick by-human-eye comparison that two things are different.
*/
public static function string_hash(string $o): string {
return \substr(\md5($o), 0, 8);
}
/**
* Normalize decimal number - trim zeroes from left and from right and
* do it, like, smart-like.
*
* Examples:
* - `00100.0` -> `100.0`
* - `00100.000` -> `100.0`
* - `00100.000100` -> `100.0001`
* - `000.000100` -> `0.0001`
* - `0100` -> `100`
* - `+0100` -> `100`
* - `-0100` -> `-100`
*/
public static function normalize_decimal(string $decimal): string {
return \preg_replace(
self::DECIMAL_TRIMMING_REGEXES[0],
self::DECIMAL_TRIMMING_REGEXES[1],
\ltrim(\trim($decimal), '+')
);
}
/**
* Converts a number represented with scientific notation to a decimal
* number which is returned as a string.
*
* If there's not a decimal point nor an exponent present in the
* number, or even if the `$number` is not really a number, the original
* value is returned.
*
* Examples:
* `1.123E+6` -> `1123000`
* `987654.123E-6` -> `0.98765412`
* `987654.123` -> `987654.123`
* `987654` -> `987654`
* `not a number, bruh` -> `not a number, bruh`
*/
public static function scientific_to_decimal(string $number): string {
// If not even in correct scientific form point, just return the
// original.
if (!\preg_match(
"#^([+-]?\d+\.\d+)(?:E([+-]\d+))?$#S",
$number,
$matches
)
) {
return $number;
}
// If there's no exponent, just return the original.
if (!isset($matches[2])) {
return $number;
}
// Otherwise, take the base and multiply it by the exponent.
$decimal = $matches[1];
$exp = $matches[2];
return \bcmul(
$decimal,
\bcpow('10', $exp, NumberValue::PRECISION),
NumberValue::PRECISION
);
}
/**
* Helper for easy type-checking inside Primi extensions.
*
* Given an argument index, its value as object, and allowed types (as class
* names) as the rest of the arguments, this function either throws a
* TypeError exception with a user-friendly message or doesn't do
* anything.
*
* @param class-string|AbstractValue $allowedTypes
* @throws TypeError
*/
public static function allow_argument_types(
int $pos,
AbstractValue $arg,
...$allowedTypes
): void {
// If any of the "instanceof" checks is true,
// the type is allowed - return without throwing exception.
foreach ($allowedTypes as $type) {
if (\is_string($type) && $arg instanceof $type) {
return;
} elseif (
$type instanceof TypeValue
&& $arg->getType() === $type
) {
return;
}
}
throw new TypeError(\sprintf(
"Expected '%s' but got '%s' as argument %d",
Types::php_classes_to_primi_types($allowedTypes),
$arg->getTypeName(),
$pos
));
}
/**
* @param array<string, AbstractValue|null> $current
* @param array<string, TypeDef_AstNode> $defaults
* @return array<string, AbstractValue>
*/
public static function resolve_default_args(
array $current,
array $defaults,
Context $ctx,
): array {
// Go through each of the known "defaults" for parameters and if its
// corresponding current argument is not yet defined, use that
// default's value definition (here presented as a AST node which we
// can execute - which is done at call-time) to fetch the
// argument's value.
foreach ($defaults as $name => $astNode) {
if (empty($current[$name])) {
$current[$name] = HandlerFactory::runNode($astNode, $ctx);
}
}
return $current;
}
/**
* Takes array representing AST node and makes sure that its contents are
* represented in a form of indexed sub-arrays. This comes handy if we want
* to be sure that multiple AST sub-nodes (which PHP-PEG parser returns) are
* universally iterable.
*
* @param TypeDef_AstNode $node
* @return TypeDef_AstNode
*/
public static function ensure_indexed(array $node): array {
return !isset($node[0]) ? [$node] : $node;
}
/**
* Return a `[line, pos]` tuple for given (probably multiline) string and
* some offset.
*
* @return array{int, int}
*/
public static function get_position_estimate(string $string, int $offset): array {
$substring = \mb_substr($string, 0, $offset);
// Current line number? Just count the newline characters up to the offset.
$line = \substr_count($substring, "\n") + 1;
// Position on the current line? Just count how many characters are there
// from the substring's end back to the latest newline character. If there
// were no newline characters (mb_strrchr() returns false), the source code
// is a single line and in that case the position is determined simply by
// our substring's length.
$lastLine = \mb_strrchr($substring, "\n");
$pos = $lastLine === \false
? \mb_strlen($substring)
: \mb_strlen($lastLine);
return [$line, $pos];
}
/**
* Helper function for easier left-to-right evaluation of various abstract
* trees representing logical/mathematical operations.
*
* Returns a generator yielding tuples of `[operator, operand]` with the
* exception of first iteration, where the tuple `[null, first operand]` is
* returned.
*
* For example when primi source code `1 and 2 and 3` is parsed and then
* represented in a similar way to...
*
* ```php
* [
* 'operands' => ['Number 1', 'Number 2', 'Number 3']
* 'ops' => ['Operator AND #1', 'Operator AND #2']
* ]
* ```
*
* ... the generator will yield (in this order):
* - `[null, 'Number 1']`
* - `['Operator AND #1', 'Number 2']`
* - `['Operator AND #2', 'Number 3']`
*
* This way client code can, for example, implement short-circuiting by
* using the result so-far and not processing the rest of what the generator
* would yield.
*
* @param TypeDef_AstNode $node
* @return \Generator<array{string|null, AbstractValue}>
*/
public static function yield_left_to_right(array $node, Context $ctx) {
foreach ($node['operands'] as $i => $operand) {
// First operator will be null and the last one too.
$operator = $node['ops'][$i - 1]['text'] ?? \null;
$value = HandlerFactory::runNode($operand, $ctx);
if (yield [$operator, $value]) {
break;
}
}
}
/**
* Return best available time for measuring things - as seconds.
*/
public static function monotime(): float {
return \hrtime(\true) / 1e9; // Nanoseconds to seconds.
}
/**
* Return a random, hopefully quite unique string.
*/
public static function unique_id(): string {
return md5(random_bytes(128));
}
/**
* @param array<StackFrame> $callstack Callstack.
*/
public static function get_traceback_as_string(array $callstack): string {
$result = [];
$result[] = "Traceback:";
foreach ($callstack as $level => $call) {
$call = $call->asString();
$result[] = "[$level] {$call}";
}
return \implode("\n", $result);
}
public static function colorize_traceback(BaseException $ex): string {
$result = \preg_replace_callback_array([
'#^Traceback:$#m' => // "Traceback:" string.
fn($m) => Colors::get("{green}$m[0]"),
'#(@|in|from) (<.*?>)#m' => // E.g. "in <module: blahblah>"
fn($m) => Colors::get("{$m[1]} {yellow}{$m[2]}{_}"),
'#^(\[\d+\]) (.+) in #m' => // E.g. "[4] __main__.somefunc()"
fn($m) => Colors::get("{darkgrey}{$m[1]}{_} {lightblue}{$m[2]}{_} in "),
'#near (["\'])(.*?)\\1 @#' => // E.g. '... near "some code" @ ...'
fn($m) => Colors::get("near {$m[1]}{lightcyan}{$m[2]}{_}{$m[1]}"),
], $ex->getMessage());
return $result;
}
/**
* Takes an array list of strings and returns array list of strings that are
* guaranteed to represent a "realpath" to a directory in filesystem.
*
* If any of the passed strings is NOT a directory, `EngineError` is thrown.
*
* @param array<string> $paths
* @return array<string>
*/
public static function validate_dirs(array $paths): array {
$result = [];
foreach ($paths as &$path) {
// Checked directory paths will be converted to "realpaths" -
// ie. absolute paths.
$rp = \realpath($path);
if ($rp === \false || !is_dir($rp)) {
throw new EngineError("Path '$path' is not a valid directory");
}
$result[] = rtrim($rp, '/');
}
return $result;
}
/**
* Is string a "dunder" (double-underscored) name? Dunder starts and ends
* with a double-underscore. For example `__init__` is a dunder.
*/
public static function is_dunder_name(string $input): bool {
return \str_starts_with($input, '__') && \str_ends_with($input, '__');
}
/**
* Is string an "under" (underscored) name?
*/
public static function is_under_name(string $input): bool {
return \str_starts_with($input, '_');
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/StringEscaping.php | src/Helpers/StringEscaping.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers;
use \Smuuf\Primi\Ex\RuntimeError;
use \Smuuf\StrictObject;
class StringEscaping {
use StrictObject;
/**
* Escape sequences that are supported in string literals.
*
* Left side represents character after a backslash which together form a
* supported escape sequence. Right side represents a result of such
* sequence.
*
* @const array
*/
private const ESCAPE_PAIRS = [
'\\\\' => "\\",
'\\n' => "\n",
'\\r' => "\r",
'\\t' => "\t",
'\\"' => '"',
"\\'" => "'",
"\\e" => "\e", // C-style octal code for an escape character.
"\\b" => "\x08", // Backspace character.
];
private const QUOTE_CHARS = ['"', "'"];
/**
* Return the provided string but with known escape sequences being expanded
* to their literal meaning. For example `\n` will be expanded to literal
* new-line.
*/
public static function unescapeString(string $str): string {
return \preg_replace_callback('#(\\\\.)#', function($m) {
$char = $m[1];
foreach (self::ESCAPE_PAIRS as $in => $out) {
if ($char === $in) {
return $out;
}
}
// The backslashed character doesn't represent any known escape
// sequence, therefore error.
throw new RuntimeError(
"Unrecognized string escape sequence '{$m[0]}'."
);
}, $str);
}
/**
* The string provided as an argument will be returned, but with added
* escaping for characters that represent a known escape sequence. For
* example a literal new-line will be replaced by `\n`.
*
* This is useful for converting a internal string value of StringValue to
* a source code representation of it - that is how a string literal would
* have to be written by hand for it to be - as a result - interpreted as
* that original string).
*
* If a third optional $quoteChar argument is passed, all other known
* quote characters will NOT be escaped - only the one specified by the
* third argument. The only known quote characters are `'` and `"`. For
* example the string `hello'there"` without $quoteChar specified will
* be escaped as `hello\'there\"`. But with $quoteChar being `"` it would
* result in `hello'there\"`, since the caller used the third argument to
* specify that the single-quote does NOT have to be escaped.
*/
public static function escapeString(
string $str,
string $quoteChar = \null
): string {
foreach (self::ESCAPE_PAIRS as $out => $in) {
// $in = <new line>
// $out = '\n'
if (
$quoteChar !== \null
&& \in_array($in, self::QUOTE_CHARS, \true)
&& $in !== $quoteChar
) {
// Do not escape quote characters that aren't necessary to be
// escaped.
continue;
}
$str = \str_replace($in, $out, $str);
}
return $str;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/Indices.php | src/Helpers/Indices.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers;
use \Smuuf\Primi\Ex\IndexError;
use \Smuuf\Primi\Values\AbstractValue;
/**
* Helpers for handling accessing PHP arrays via possibly negative indices.
*/
abstract class Indices {
/**
* Translate negative index to positive index that's a valid index for a
* given number of items.
*
* Return `null` when it's not possible to do so.
*
* For example:
* - index 1 for list with 2 items -> index == 1
* - index 2 for list with 2 items -> NOT FOUND!
* - index -1 for list with 2 items -> index == <max_index> - 1 (= 1)
* - index -2 for list with 2 items -> index == <max_index> - 2 (= 0)
* - index -3 for list with 2 items -> NOT FOUND!
*/
public static function resolveNegativeIndex(
int $index,
int $maxIndex
): ?int {
$normalized = $index < 0
? $maxIndex + $index + 1
: $index;
if ($normalized < 0 || $normalized > $maxIndex) {
return \null;
}
return $normalized;
}
/**
* Return resolved positive array index based on possibly negative index
* passed as the first argument.
*
* If the negative index could not be resolved, or if the index does not
* represent an existing index in the array passed as the second argument,
* an IndexError exception is thrown.
*
* @param array<int, AbstractValue>|\ArrayAccess<int, AbstractValue> $array
* @return mixed
*/
public static function resolveIndexOrError(int $index, $array) {
$actualIndex = self::resolveNegativeIndex($index, \count($array) - 1);
if ($actualIndex === \null || !isset($array[$actualIndex])) {
// $index on purpose - report error with the index originally used.
throw new IndexError($index);
}
return $actualIndex;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/Stats.php | src/Helpers/Stats.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers;
use \Smuuf\Primi\Cli\Term;
use \Smuuf\StrictObject;
/**
* A static runtime statistics gatherer.
*/
abstract class Stats {
use StrictObject;
/** @var float Point in time when stats gathering was enabled. */
private static float $startTime = 0;
/** @var array<string, int> Dictionary for gathered statistics. */
private static array $stats = [];
/**
* Initialize stats gathering.
*/
public static function init(): void {
self::$startTime = Func::monotime();
}
/**
* Increment counter of some stats entry by 1 (the entry is initialized
* with 0 if it doesn't exist yet
*/
public static function add(string $entryName): void {
self::$stats[$entryName] = (self::$stats[$entryName] ?? 0) + 1;
}
/**
* Return a single stats entry by its name.
*/
public static function get(string $name): int {
return self::$stats[$name] ?? 0;
}
public static function print(): void {
self::out(Colors::get("{yellow}Runtime stats:{_}"));
//
// Print general stats.
//
self::out(Colors::get("{green}General:{_}"));
self::out("PHP: " . PHP_VERSION);
$mb = round(memory_get_peak_usage(true) / 1e6, 2);
self::out("Memory peak: {$mb} MB");
$duration = round(Func::monotime() - self::$startTime, 2);
self::out("Runtime duration: {$duration} s");
//
// Print gathered stats, if there are any.
//
if (self::$stats) {
self::out(Colors::get("{green}Gathered:{_}"));
ksort(self::$stats);
foreach (self::$stats as $name => $value) {
self::out("- {$name}: {$value}");
}
}
}
private static function out(string $text): void {
Term::stderr(Term::line($text));
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/Types.php | src/Helpers/Types.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\MagicStrings;
use \Smuuf\Primi\Ex\EngineError;
use \Smuuf\Primi\Values\FuncValue;
use \Smuuf\Primi\Values\TypeValue;
use \Smuuf\Primi\Values\AbstractValue;
use \Smuuf\Primi\Values\NullValue;
use \Smuuf\Primi\Structures\CallArgs;
use \Smuuf\Primi\Values\MethodValue;
abstract class Types {
public static function is_subclass_of(
TypeValue $childType,
TypeValue $parentType,
): bool {
do {
if ($childType === $parentType) {
return \true;
}
} while ($childType = $childType->getParentType());
return \false;
}
/**
* Handles special treating of attributes that will represent attributas
* of a type.
*
* Special treating like, for example, `__new__` method must be converted
* from ordinary method to static method for the type system and object
* model to work correctly.
*
* @param array<string, AbstractValue> $methods
* @return array<string, AbstractValue>
*/
public static function prepareTypeMethods(
array $methods,
): array {
static $methodNameNew = MagicStrings::MAGICMETHOD_NEW;
if (isset($methods[$methodNameNew])) {
$methods[$methodNameNew] = new MethodValue(
$methods[$methodNameNew]->getCoreValue(),
isStatic: true,
);
}
return $methods;
}
/**
* Lookup and return attr from a type object - or its parents.
*
* If the `$bind` argument is specified and the attr is a function, this
* returns a new `FuncValue` with partial arguments having the object
* in the `$bind` argument (this is how Primi handles object methods -
* the instance object is bound as the first argument of the function its
* type object provides).
*
* @return AbstractValue|null
*/
public static function attr_lookup(
?TypeValue $typeObject,
string $attrName,
?AbstractValue $bind = \null
) {
if (!$typeObject) {
return \null;
}
//
// Try attr access on the type object itself.
//
// Example - Accessing `SomeClass.some_attr`:
// Try if there's `some_attr` attribute in the SomeClass type itself.
//
if ($value = $typeObject->rawAttrGet($attrName)) {
return $bind && $value instanceof FuncValue
? $value->withBind($bind)
: $value;
}
//
// If the type object itself doesn't have this attr, try inheritance -
// look for the attr in the parent type objects.
//
while ($typeObject = $typeObject->getParentType()) {
if ($value = $typeObject->rawAttrGet($attrName)) {
return $bind && $value instanceof FuncValue
? $value->withBind($bind)
: $value;
}
}
return \null;
}
/**
* Converts PHP class names to Primi type names represented as string.
* Throws an exception if any PHP class name doesn't represent a Primi type.
*
* @param array<class-string|AbstractValue> $types
*/
public static function php_classes_to_primi_types(array $types): string {
$primiTypes = \array_map(function($class) {
// Resolve PHP nulls as Primi nulls.
if (\is_string($class) && \strtolower($class) === 'null') {
return NullValue::TYPE;
}
return TypeResolver::resolve($class);
}, $types);
return \implode('|', $primiTypes);
}
/**
* Returns array of Primi value types (PHP class names) of parameters
* for a PHP function of which the \ReflectionFunction is provided.
*
* In another words: This function returns which Primi types a PHP function
* expects.
*
* @return array<string>
* @throws EngineError
*/
public static function check_allowed_parameter_types_of_function(
\ReflectionFunction $rf
): array {
$types = [];
foreach ($rf->getParameters() as $rp) {
$invalid = \false;
$type = $rp->getType();
if ($type === \null) {
$invalid = 'Type must be specified';
} else {
// See https://github.com/phpstan/phpstan/issues/3886#issuecomment-699599667
if (!$type instanceof \ReflectionNamedType) {
$invalid = "Union types not yet supported";
} else {
$typeName = $type->getName();
// a) Invalid if not hinting some AbstractValue class or its descendants.
// b) Invalid if not hinting the Context class.
if (\is_a($typeName, AbstractValue::class, \true)
|| \is_a($typeName, Context::class, \true)
|| \is_a($typeName, CallArgs::class, \true)
) {
$types[] = $typeName;
} else {
$invalid = "Type '$typeName' is not an allowed type";
}
}
}
if ($invalid) {
$declaringClass = $rp->getDeclaringClass();
$className = $declaringClass
? $declaringClass->getName()
: \null;
$fnName = $rp->getDeclaringFunction()->getName();
$paramName = $rp->getName();
$paramPosition = $rp->getPosition();
$fqn = $className ? "{$className}::{$fnName}()" : "{$fnName}()";
$msg = "Parameter {$paramPosition} '\${$paramName}' for function {$fqn} "
. "is invalid: $invalid";
throw new EngineError($msg);
};
}
return $types;
}
/**
* Return true if the value passed as first argument is any of the types
* passed as the rest of variadic arguments.
*
* We're using this helper e.g. in value methods for performing easy
* checks against allowed set of types of values. If PHP ever supports union
* types, I guess this helper method might become unnecessary (?).
*
*/
public static function is_any_of_types(?AbstractValue $value, string ...$types): bool {
// If any of the "instanceof" checks is true,
// the type is allowed - return without throwing exception.
foreach ($types as $type) {
if ($value instanceof $type) {
return \true;
}
}
return \false;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/ComparisonLTR.php | src/Helpers/ComparisonLTR.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\Ex\RelationError;
use \Smuuf\Primi\Ex\EngineInternalError;
use \Smuuf\Primi\Helpers\Func;
use \Smuuf\Primi\Handlers\HandlerFactory;
use \Smuuf\Primi\Values\AbstractValue;
use \Smuuf\StrictObject;
class ComparisonLTR {
use StrictObject;
/**
* @param TypeDef_AstNode $node
*/
public static function handle(
array $node,
Context $context
): AbstractValue {
$result = \true;
// Optimization for expressions with just two operands.
if (\count($node['ops']) === 1) {
$result = self::evaluate(
$node['ops'][0]['text'],
HandlerFactory::runNode($node['operands'][0], $context),
HandlerFactory::runNode($node['operands'][1], $context),
);
return Interned::bool((bool) $result);
}
// This shouldn't be necessary, since the first operator yielded below
// will always be null - and the result would be set to be the first
// operand, but let's make static analysis happy.
$left = Interned::null();
$gen = Func::yield_left_to_right($node, $context);
foreach ($gen as [$operator, $right]) {
if ($operator === \null) {
$left = $right;
continue;
}
$result &= static::evaluate($operator, $left, $right);
$left = $right;
}
$gen->send(\true);
return Interned::bool((bool) $result);
}
public static function evaluate(
string $op,
AbstractValue $left,
AbstractValue $right
): bool {
switch (\true) {
case $op === '==':
return self::evaluateEqual($left, $right);
case $op === '!=':
return self::evaluateNotEqual($left, $right);
case $op === 'in':
return self::evaluateIn($op, $left, $right);
case $op === 'not in':
return !self::evaluateIn($op, $left, $right);
case $op === '>':
case $op === '<':
case $op === '>=':
case $op === '<=':
return self::evaluateRelation($op, $left, $right);
default:
throw new EngineInternalError("Unknown operator '$op'");
}
}
private static function evaluateEqual(
AbstractValue $left,
AbstractValue $right
): bool {
// Compare identity first - if both operands are the same object, no
// need to compare them any further.
if ($left === $right) {
return \true;
}
// If the left side doesn't know how to evaluate equality with the right
// side (the first call returned null), switch operands and try again.
// If both sides did not know how to evaluate equality with themselves,
// the equality is false.
return $left->isEqualTo($right)
?? $right->isEqualTo($left)
?? \false;
}
private static function evaluateNotEqual(
AbstractValue $left,
AbstractValue $right
): bool {
// Compare identity first - if both operands are the same object, no
// need to compare them any further.
if ($left === $right) {
return \false;
}
// If the left side doesn't know how to evaluate equality with the right
// side (the first call returned null), switch operands and try again.
// If both sides did not know how to evaluate equality with themselves,
// the equality is false.
$result = $left->isEqualTo($right)
?? $right->isEqualTo($left)
?? \false;
return !$result;
}
private static function evaluateRelation(
string $op,
AbstractValue $left,
AbstractValue $right
): bool {
$result = $left->hasRelationTo($op, $right);
// If the left side didn't know how to evaluate relation with the right
// side (the hasRelationTo call returned null), the relation is
// undefined and thus raises an error.
if ($result === \null) {
throw new RelationError($op, $left, $right);
}
return $result;
}
private static function evaluateIn(
string $op,
AbstractValue $left,
AbstractValue $right
): bool {
// Note the apparently switched operands: A in B means asking if B
// contains A.
$result = $right->doesContain($left);
// If the left side didn't know how to evaluate relation with the right
// side (the hasRelationTo call returned null), the relation is
// undefined and thus raises an error.
if ($result === \null) {
throw new RelationError($op, $left, $right);
}
return $result;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/Timer.php | src/Helpers/Timer.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers;
use \Smuuf\StrictObject;
class Timer {
use StrictObject;
/** @var float|null Point in time where timer started. */
private $time = \null;
/**
* Start the timer (set a point in time to measure from).
*/
public function start(): self {
$this->time = Func::monotime();
return $this;
}
/**
* Get current duration from the timer start as float number.
*/
public function get(): float {
if ($this->time === \null) {
throw new \LogicException("Timer hasn't been started");
}
return Func::monotime() - $this->time;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/ArithmeticLTR.php | src/Helpers/ArithmeticLTR.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\Ex\BinaryOperationError;
use \Smuuf\Primi\Handlers\HandlerFactory;
use \Smuuf\Primi\Values\AbstractValue;
use \Smuuf\Primi\Helpers\Func;
use \Smuuf\Primi\Helpers\Interned;
use \Smuuf\StrictObject;
class ArithmeticLTR {
use StrictObject;
/**
* @param TypeDef_AstNode $node
*/
public static function handle(
array $node,
Context $context
): AbstractValue {
// Optimization for expressions with just two operands.
if (\count($node['ops']) === 1) {
return self::evaluate(
$node['ops'][0]['text'],
HandlerFactory::runNode($node['operands'][0], $context),
HandlerFactory::runNode($node['operands'][1], $context),
);
}
// This shouldn't be necessary, since the first operator yielded below
// will always be null - and the result would be set to be the first
// operand, but let's make static analysis happy.
$result = Interned::null();
$gen = Func::yield_left_to_right($node, $context);
foreach ($gen as [$operator, $operand]) {
if ($operator === \null) {
$result = $operand;
continue;
}
$result = self::evaluate($operator, $result, $operand);
}
$gen->send(\true);
return $result;
}
public static function evaluate(
string $op,
AbstractValue $left,
AbstractValue $right
): AbstractValue {
[$a, $b] = [$left, $right];
$result = \null;
$i = 0;
// We're going to have two tries at this. If the first try returns null,
// it means that the left side acknowledged it doesn't know how
// to evaluate the operation. If that's the case, we'll switch the
// left/right operators and try if the right side does know what
// to do. If not and it too returns null, NotImplementedException is
// raised.
for ($i = 0; $i < 2; $i++) {
switch (\true) {
case $op === "+":
$result = $a->doAddition($b);
break;
case $op === "-":
$result = $a->doSubtraction($b);
break;
case $op === "*":
$result = $a->doMultiplication($b);
break;
case $op === "/":
$result = $a->doDivision($b);
// No need for break here.
}
if ($result !== \null) {
break;
}
[$b, $a] = [$a, $b];
}
if ($result === \null) {
throw new BinaryOperationError($op, $left, $right);
}
return $result;
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/Interned.php | src/Helpers/Interned.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers;
use \Smuuf\Primi\Values\BoolValue;
use \Smuuf\Primi\Values\NullValue;
use \Smuuf\Primi\Values\BytesValue;
use \Smuuf\Primi\Values\RegexValue;
use \Smuuf\Primi\Values\NumberValue;
use \Smuuf\Primi\Values\StringValue;
use \Smuuf\Primi\Values\NotImplementedValue;
use \Smuuf\StrictObject;
/**
* Helper factory for building and interning primitive types and additional
* special constant singletons.
*
* Primitive types are:
* - null
* - bool
* - number
* - string
* - regex
*
* Special constants:
* - NotImplemented
*
* NOTE: Most typehints are in docstrings and not in PHP code for better
* performance.
*/
abstract class Interned {
use StrictObject;
/**
* Storage for interned instances of null objects.
* @var NullValue
*/
private static $internedNull;
/**
* Storage for interned instances of "false" bool object.
*
* By storing false/true separately and not under the 1/0 key, we save one
* array access operation each time we will be returning true or false bool
* object.
*
* @var BoolValue
*/
private static $internedBoolFalse;
/**
* Storage for interned instances of "true" objects.
*
* By storing false/true separately and not under the 1/0 key, we save one
* array access operation each time we will be returning true or false bool
* object.
*
* @var BoolValue
*/
private static $internedBoolTrue;
/**
* Storage for interned instances of number objects.
* @var array<string, NumberValue>
*/
private static $internedNumber = [];
/**
* Storage for interned instances of string objects.
* @var array<string, StringValue>
*/
private static $internedString = [];
/**
* Storage for interned instances of bytes objects.
* @var array<string, BytesValue>
*/
private static $internedBytes = [];
/**
* Storage for interned instances of regex objects.
* @var array<string, RegexValue>
*/
private static $internedRegex = [];
// Special constants.
/**
* Storage for NotImplemented object singleton.
*
* @var NotImplementedValue
*/
private static $internedNotImplemented;
/**
* Initialize several known possible objects.
*
* This saves us one null-check when building objects for these
* super-primitive values.
*/
public static function init(): void {
self::$internedNull = new NullValue;
self::$internedBoolFalse = new BoolValue(\false);
self::$internedBoolTrue = new BoolValue(\true);
self::$internedNotImplemented = new NotImplementedValue;
}
/**
* @return NullValue
*/
public static function null() {
return self::$internedNull;
}
/**
* @return BoolValue
*/
public static function bool(bool $truth) {
if ($truth) {
return self::$internedBoolTrue;
} else {
return self::$internedBoolFalse;
}
}
/**
* @return NumberValue
*/
public static function number(string $number) {
// Numbers up to 8 characters will be interned.
if (\strlen($number) <= 8) {
return self::$internedNumber[$number]
?? (self::$internedNumber[$number] = new NumberValue($number));
}
return new NumberValue($number);
}
/**
* @return StringValue
*/
public static function string(string $str) {
// Strings up to 8 characters will be interned.
if (\strlen($str) <= 8) {
return self::$internedString[$str]
?? (self::$internedString[$str] = new StringValue($str));
}
return new StringValue($str);
}
/**
* @return BytesValue
*/
public static function bytes(string $b) {
// Bytes values up to 8 bytes will be interned.
if (\strlen($b) <= 8) {
return self::$internedBytes[$b]
?? (self::$internedBytes[$b] = new BytesValue($b));
}
return new BytesValue($b);
}
/**
* @return RegexValue
*/
public static function regex(string $regex) {
// Regexes up to 8 characters will be interned.
if (\strlen($regex) <= 8) {
return self::$internedRegex[$regex]
?? (self::$internedRegex[$regex] = new RegexValue($regex));
}
return new RegexValue($regex);
}
/**
* @return NotImplementedValue
*/
public static function constNotImplemented() {
return self::$internedNotImplemented;
}
}
Interned::init();
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/ValueFriends.php | src/Helpers/ValueFriends.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers;
use \Smuuf\StrictObject;
use \Smuuf\Primi\Values\AbstractValue;
/**
* Emulate friend visibility - extending classes can access internal `$value`
* property of `AbstractValue` class.
*
* AbstractValue and Extension classes use this.
*
* This way both AbstractValue and Extension objects can access the value directly and
* thus we avoid unnecessary overhead when accessing the value via getter
* method, which would be often.
*/
abstract class ValueFriends {
use StrictObject;
/**
* Core value of a value object.
*
* This is relevant primarily for Primi objects that represent primitive
* values.
*/
protected mixed $value = \null;
/**
* Attributes of Primi object.
*
* @var array<string, AbstractValue>
*/
protected array $attrs = [];
/**
* Internal attributes of Primi object that are not directly accessible
* from Primi userland.
*
* @var array<string, mixed>
*/
protected array $internal = [];
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/Colors.php | src/Helpers/Colors.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers;
use \Smuuf\StrictObject;
abstract class Colors {
use StrictObject;
const COLOR_FORMAT = "\033[%sm";
const COLORS = [
// Reset.
'_' => '0',
// Fore.
'black' => '0;30',
'darkgrey' => '1;30',
'darkgray' => '1;30',
'blue' => '0;34',
'lightblue' => '1;34',
'green' => '0;32',
'lightgreen' => '1;32',
'cyan' => '0;36',
'lightcyan' => '1;36',
'red' => '0;31',
'lightred' => '1;31',
'purple' => '0;35',
'lightpurple' => '1;35',
'brown' => '0;33',
'yellow' => '0;33',
'lightyellow' => '1;33',
'lightgray' => '0;37',
'lightgrey' => '0;37',
'white' => '1;37',
// Back.
'-black' => '40',
'-red' => '41',
'-green' => '42',
'-yellow' => '43',
'-blue' => '44',
'-magenta' => '45',
'-cyan' => '46',
'-lightgray' => '47',
'-lightgrey' => '47',
// Styles.
'bold' => '1',
'dim' => '2',
'underline' => '4',
'blink' => '5',
'invert' => '7',
];
private static bool $noColor;
public static function init(): void {
// Disable colors if either of these is true ...
// 1) Env var "NO_COLOR" contains a truthy value.
// 2) Current STDOUT is _not_ a terminal (for example when output is
// being piped elsewhere - for example into a file).
self::$noColor = (
(bool) \getenv('NO_COLOR')
|| !posix_isatty(STDOUT)
);
}
public static function get(
string $string,
bool $reset = true,
bool $applyColors = true
): string {
$handler = $applyColors ? [self::class, 'handler'] : fn() => '';
return self::apply($string, $handler, $reset);
}
private static function apply(
string $string,
callable $handler,
bool $reset = true
): string {
// Insert reset character if we should reset styles on end.
if ($reset) {
$string .= '{_}';
}
return \preg_replace_callback(
'#(?<!\\\\)\{([a-z_-][a-z-]*)\}#i',
$handler,
$string
);
}
/**
* @param array<int, string> $matches
*/
private static function handler(array $matches): string {
if (self::$noColor !== \false) {
return '';
}
$color = $matches[1];
if (isset(self::COLORS[$color])) {
return \sprintf(self::COLOR_FORMAT, self::COLORS[$color]);
}
throw new \LogicException("Unknown color '$color'");
}
}
Colors::init();
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/TypeResolver.php | src/Helpers/TypeResolver.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers;
use \Smuuf\Primi\Ex\EngineInternalError;
use \Smuuf\Primi\Values\TypeValue;
use \Smuuf\Primi\Values\AbstractValue;
use \Smuuf\Primi\Values\InstanceValue;
abstract class TypeResolver {
/**
* Some classes used for representing Primi objects have "unfriendly"
* values of their "TYPE" class constants.
*
* If we, for example, want to display error message about wrong type
* of argument passed into a native PHP function (called from Primi) when
* a basic "AbstractValue" class is typehinted (because that PHP class
* is a base class for other PHP classes representing Primi objects), we
* want to display "object" instead of AbstractValue's "__undefined__" TYPE.
*/
private const OVERRIDE_TYPES = [
AbstractValue::class => 'object',
InstanceValue::class => 'object',
];
/**
* Return type name for a Primi object or for PHP class which represents
* object of a basic native type (e.g. `StringValue`).
*
* @param class-string|AbstractValue $type
*/
public static function resolve($type): string {
if (\is_string($type)) {
// Return Primi type name based on passed PHP class name
// representing a basic native Primi object.
// Normalize PHP class name to a form without leading backslash.
$type = \ltrim($type, '\\');
if (isset(self::OVERRIDE_TYPES[$type])) {
return self::OVERRIDE_TYPES[$type];
}
if (!\is_subclass_of($type, AbstractValue::class, \true)) {
throw new EngineInternalError(
"Unable to resolve Primi type name for PHP class '$type'");
}
return $type::TYPE;
} elseif ($type instanceof TypeValue) {
// Return Primi type name based on an actual Primi object (passed
// as PHP object representing a Primi object).
return $type->getName();
}
$type = \get_debug_type($type);
throw new EngineInternalError(
"Unable to resolve Primi type name from PHP value '$type'");
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/Traits/WatchLifecycle.php | src/Helpers/Traits/WatchLifecycle.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers\Traits;
use \Smuuf\Primi\Helpers\Func;
/**
* Use external scope for watching life-cycles, as different classes that
* use the WatchLifecycle trait don't share the one trait's static properties.
*/
abstract class WatchLifecycleScope {
public static int $instanceCounter = 0;
public static int $stackCounter = 0;
/** @var array<int, bool> */
public static array $alreadyVisualized = [];
/** @var array<int, string> */
public static array $stack = [];
}
/**
* Currently supports only classes without additional parent constructors/destructors.
*/
trait WatchLifecycle {
/** @var int Every unique instance of "watched" class's number. */
private static $instanceCounter;
public function watchLifecycle() {
// Assign a new, globally unique counter's number for this new object.
self::$instanceCounter = WatchLifecycleScope::$instanceCounter++;
// Build a completely unique hash for this object's instance.
$hash = self::getHash($this);
// Add this object to global watch stack.
$this->add($hash);
// Build a unique true color for this instance.
$colorHash = self::truecolor($hash, $hash);
$visual = $this->visualize();
// Visualize newly created object with a pretty sign.
echo "+ $colorHash $visual\n";
}
public function __destruct() {
// Build visualization string before removing this object from watched stack.
$visual = $this->visualize();
// Remove this object from global watch stack.
$hash = self::getHash($this);
$this->remove($hash);
$colorHash = self::truecolor($hash, $hash);
echo " - $colorHash $visual\n";
}
/**
* Add this currently watched instance to global stack.
*/
private function add(string $hash): void {
WatchLifecycleScope::$stack[++WatchLifecycleScope::$stackCounter] = $hash;
}
/**
* Remove this currently watched instance from global stack.
*/
private function remove(string $hash): void {
unset(
WatchLifecycleScope::$stack[
array_search($hash, WatchLifecycleScope::$stack, true)
]
);
}
private function visualize(): string {
if (!WatchLifecycleScope::$stack) return "x";
$max = max(array_keys(WatchLifecycleScope::$stack));
$return = null;
foreach (range(1, $max) as $pos) {
// If such position exists in our watching stack, display a character.
// If this stack item was not displayed yet, display a special character.
$return .= isset(WatchLifecycleScope::$stack[$pos])
? (isset(WatchLifecycleScope::$alreadyVisualized[$pos]) ? "|" : "o")
: " ";
WatchLifecycleScope::$alreadyVisualized[$pos] = true;
}
return $return;
}
/**
* Return a completely unique hash for this object's instance.
* Uniqueness is based off a 1) global counter, 2) class name, 3) spl_object_hash.
*
* Now that I'm thinking about it, the "1)" should be enough, but, well...
*/
private static function getHash(object $object): string {
return Func::string_hash(
self::$instanceCounter
. get_class($object)
. spl_object_hash($object)
);
}
private static function truecolor(string $hex, string $content): string {
$r = self::numpad(hexdec(substr($hex, 0, 2)) + 32);
$g = self::numpad(hexdec(substr($hex, 2, 2)) + 32);
$b = self::numpad(hexdec(substr($hex, 4, 2)) + 32);
$out = sprintf("\x1b[38;2;%s;%s;%sm", $r, $g, $b);
$out .= $content . "\033[0m"; // Reset colors.
return $out;
}
/**
* Return int number as hex and ensure it's of length of 3, padded with zeroes.
*/
private static function numpad(int $n): string {
return str_pad((string) $n, 3, "0", STR_PAD_LEFT);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/Wrappers/AbstractWrapper.php | src/Helpers/Wrappers/AbstractWrapper.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers\Wrappers;
/**
* A "wrapper" control structure emulating Python's context manager behavior.
* This is to provide easy-to-use resource management (so you don't forget
* anything important after doing something).
*
* For details about context managers in Python see:
* https://docs.python.org/3/library/contextlib.html.
*
* Classes may extend this abstract wrapper class and then use it:
*
* ```php
* class YayWrapper extends AbstractWrapper {
* public function executeBefore() {
* echo "yay enter";
* }
*
* public function executeAfter() {
* echo "yay exit";
* }
* }
*
* $wrapper = new YayWrapper;
* $wrapper->wrap(function() {
* // 'yay enter' will be echoed first.
* echo "something.";
* // 'yay exit' will be echoed last.
* });
* ```
*/
abstract class AbstractWrapper {
/**
* @return mixed
*/
public function wrap(callable $fn) {
$enterRetval = $this->executeBefore();
try {
$retval = $fn($enterRetval);
unset($fn);
return $retval;
} finally {
$this->executeAfter();
}
}
/**
* @return mixed
*/
abstract public function executeBefore();
abstract public function executeAfter(): void;
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/Wrappers/ContextPushPopWrapper.php | src/Helpers/Wrappers/ContextPushPopWrapper.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers\Wrappers;
use \Smuuf\StrictObject;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\StackFrame;
use \Smuuf\Primi\Scope;
/**
* @internal
*/
class ContextPushPopWrapper extends AbstractWrapper {
use StrictObject;
private Context $ctx;
/** Call frame to push to call stack. */
private ?StackFrame $call;
/** Scope to push to scope stack. (optional) */
private ?Scope $scope;
public function __construct(
Context $ctx,
?StackFrame $call = \null,
?Scope $scope = \null
) {
$this->ctx = $ctx;
$this->call = $call;
$this->scope = $scope;
}
/**
* Push the call ID and scope (if present) onto call stack and scope stack.
*
* @return mixed
*/
public function executeBefore() {
$this->ctx->pushCallScopePair(
$this->call,
$this->scope,
);
return $this->ctx;
}
/**
* Pop the items from call stack and scope stack.
*/
public function executeAfter(): void {
$this->ctx->popCallScopePair(
(bool) $this->call,
(bool) $this->scope,
);
unset($this->call, $this->scope);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/Wrappers/CatchPosixSignalsWrapper.php | src/Helpers/Wrappers/CatchPosixSignalsWrapper.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers\Wrappers;
use \Smuuf\Primi\Tasks\TaskQueue;
use \Smuuf\Primi\Tasks\Emitters\PosixSignalTaskEmitter;
class CatchPosixSignalsWrapper extends AbstractWrapper {
/**
* Dictionary for tracking how many times this wrapper registered some
* specific task queue (identified by its ID) to the POSIX signal handler.
*
* The task queue is registered before executing the wrapped function.
* The queue is then unregistered after the most outer wrapper exits.
*
* This allows us to have nested 'catch signals' wrappers and at the same
* time we don't keep the task queue referenced in `PosixSignalTaskEmitter`
* if no longer necessary (so they can be garbage collected and we don't
* risk memory leaks).
*
* @var array<string, int>
*/
private static $level = [];
/** Send Posix signal tasks to this queue. */
private TaskQueue $tq;
/** Unique ID for each TaskQueue instance. */
private string $tqId;
public function __construct(TaskQueue $tq) {
$this->tq = $tq;
$this->tqId = $tq->getId();
}
/**
* @return mixed
*/
public function executeBefore() {
// If this is the first (outermost) context that uses this task queue,
// register the queue from signal task emitter.
if (empty(self::$level[$this->tqId])) {
PosixSignalTaskEmitter::registerTaskQueue($this->tq);
self::$level[$this->tqId] = 1;
} else {
self::$level[$this->tqId]++;
}
}
public function executeAfter(): void {
self::$level[$this->tqId]--;
// If this was the last (outermost) context that uses this task queue,
// unregister the queue from signal task emitter.
if (self::$level[$this->tqId] === 0) {
PosixSignalTaskEmitter::unregisterTaskQueue($this->tq);
}
unset($this->tq);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/Wrappers/ImportStackWrapper.php | src/Helpers/Wrappers/ImportStackWrapper.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers\Wrappers;
use \Smuuf\StrictObject;
use \Smuuf\Primi\Ex\CircularImportError;
use \Smuuf\Primi\Modules\Importer;
class ImportStackWrapper extends AbstractWrapper {
use StrictObject;
/** Importer instance. */
private Importer $importer;
/** Import ID for circular import detection. */
private string $importId;
/** Dotpath as string for pretty error messages. */
private string $dotpath;
public function __construct(
Importer $importer,
string $importId,
string $dotpath
) {
$this->importer = $importer;
$this->importId = $importId;
$this->dotpath = $dotpath;
}
/**
* @return mixed
*/
public function executeBefore() {
// Detect circular imports.
if (!$this->importer->pushImport($this->importId)) {
throw new CircularImportError($this->dotpath);
}
}
public function executeAfter(): void {
$this->importer->popImport();
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/CallConventions/PhpCallConvention.php | src/Helpers/CallConventions/PhpCallConvention.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers\CallConventions;
use \Smuuf\StrictObject;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\Ex\TypeError;
use \Smuuf\Primi\Ex\RuntimeError;
use \Smuuf\Primi\Ex\ArgumentCountError;
use \Smuuf\Primi\Values\AbstractValue;
use \Smuuf\Primi\Helpers\Types;
use \Smuuf\Primi\Structures\CallArgs;
use \Smuuf\BetterExceptions\BetterException;
use \Smuuf\BetterExceptions\Types\ArgumentTypeError;
use \Smuuf\BetterExceptions\Types\ArgumentCountError as BetterArgumentCountError;
/**
* Call convention for invoking PHP callables from within Primi code/engine.
*
* This convention passes positional args contained in CallArgs object
* into the PHP callable as variadic arguments.
*
* This convention does not support sending kwargs into PHP callable.
* (...yet? Maybe with PHP 8.1 with named parameters we might support it.)
*
* @internal
*/
class PhpCallConvention implements CallConventionInterface {
use StrictObject;
private \Closure $closure;
public function __construct(
\Closure $closure,
\ReflectionFunction $rf
) {
$this->closure = $closure;
Types::check_allowed_parameter_types_of_function($rf);
}
public function call(
CallArgs $args,
Context $ctx
): ?AbstractValue {
$finalArgs = $args->getArgs();
if ($args->getKwargs()) {
throw new RuntimeError(
"Calling native functions with kwargs is not allowed");
}
try {
$result = ($this->closure)(...$finalArgs);
return $result instanceof AbstractValue
? $result
: AbstractValue::buildAuto($result);
} catch (\TypeError $e) {
$better = BetterException::from($e);
// We want to handle only argument type errors. Other errors
// (for example "return type errors") are a sign of badly used
// return type hint for PHP function and should bubble up (be
// rethrown) for the developer to see it.
if ($better instanceof ArgumentTypeError) {
$argIndex = $better->getArgumentIndex();
throw new TypeError(\sprintf(
"Expected '%s' but got '%s' as argument %d",
Types::php_classes_to_primi_types($better->getExpected()),
$finalArgs[$argIndex - 1]->getTypeName(),
$argIndex
));
}
if ($better instanceof BetterArgumentCountError) {
// If function requested injecting Context object into its
// arguments, this should be transparent to the caller and
// thus we subtract 1 from the number of arguments we report
// here.
throw new ArgumentCountError(
$better->getActual(),
$better->getExpected()
);
}
throw $e;
}
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/CallConventions/CallArgsCallConvention.php | src/Helpers/CallConventions/CallArgsCallConvention.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers\CallConventions;
use \Smuuf\StrictObject;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\Values\AbstractValue;
use \Smuuf\Primi\Structures\CallArgs;
/**
* Call convention for invoking PHP callables from within Primi code/engine.
*
* This convention passes pure CallArgs object into the PHP callable and
* how args and kwargs are handled is left to the PHP callable to decide and
* implement.
*
* @internal
*/
class CallArgsCallConvention implements CallConventionInterface {
use StrictObject;
private \Closure $closure;
public function __construct(\Closure $closure) {
$this->closure = $closure;
}
public function call(
CallArgs $args,
Context $ctx
): ?AbstractValue {
return ($this->closure)($args, $ctx);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Helpers/CallConventions/CallConventionInterface.php | src/Helpers/CallConventions/CallConventionInterface.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Helpers\CallConventions;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\Values\AbstractValue;
use \Smuuf\Primi\Structures\CallArgs;
interface CallConventionInterface {
public function call(CallArgs $args, Context $ctx): ?AbstractValue;
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Tasks/TaskInterface.php | src/Tasks/TaskInterface.php | <?php
namespace Smuuf\Primi\Tasks;
use \Smuuf\Primi\Context;
interface TaskInterface {
public function execute(Context $ctx): void;
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Tasks/TaskQueue.php | src/Tasks/TaskQueue.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Tasks;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\Helpers\Func;
use \Smuuf\StrictObject;
class TaskQueue {
use StrictObject;
private Context $context;
/** Run queued tasks after this time interval passes (in seconds). */
public static float $interval = 0.25;
/** For measuring time. */
private float $timer;
/**
* FIFO queue for scheduling tasks.
*
* @var array<array{TaskInterface, float}>
*/
private array $queue = [];
/**
* Random ID for this queue instance (safer than spl_object_id() or similar
* for checking uniqueness).
*/
private string $id;
public function __construct(Context $ctx) {
$this->id = Func::unique_id();
$this->context = $ctx;
$this->timer = Func::monotime();
}
public function getId(): string {
return $this->id;
}
public function addTask(TaskInterface $task, float $delay = 0): void {
$eta = Func::monotime() + $delay;
$this->queue[] = [$task, $eta];
}
public function tick(): void {
if (!$this->queue) {
return;
}
if ((Func::monotime() - $this->timer) < self::$interval) {
return;
}
$this->timer = Func::monotime();
$this->executeQueued();
}
/**
* Run all remaining tasks.
*
* Tasks with ETA in the future are skipped and kept in the queue..
*/
public function deplete(): void {
$this->executeQueued(\true);
}
/**
* Execute queued tasks. Tasks with ETA in the future will be skipped
* and placed into the queue again, unless `$force` parameter is `true`, in
* which case all tasks, regardless on their ETA, will be executed.
*/
private function executeQueued(bool $force = \false): void {
// Because asynchronous events (e.g. signals) could modify (add tasks to)
// the $queue property while we're iterating through it, and
// the same (adding more tasks) could be done by any tasks we're now
// actually going to execute, we need to handle these edge-case
// situations.
// Create a copy of the queue and empty the main queue, so that any
// new entries are added to the empty queue.
[$queue, $this->queue] = [$this->queue, []];
$skipped = [];
foreach ($queue as [$task, $eta]) {
if ($eta > Func::monotime() && !$force) {
$skipped[] = [$task, $eta];
continue;
}
$this->executeTask($task);
}
// If there were any tasks skipped, add it to the end of the "cleared"
// queue (but which may now already have new tasks in it. See above.)
if ($skipped) {
$this->queue = \array_merge($this->queue, $skipped);
}
}
private function executeTask(TaskInterface $task): void {
$task->execute($this->context);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Tasks/Types/PosixSignalTask.php | src/Tasks/Types/PosixSignalTask.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Tasks\Types;
use \Smuuf\Primi\Repl;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\Ex\EngineInternalError;
use \Smuuf\Primi\Ex\SystemException;
use \Smuuf\Primi\Tasks\TaskInterface;
use \Smuuf\StrictObject;
class PosixSignalTask implements TaskInterface {
use StrictObject;
/** @var int Posix signal number. */
private $signum = \null;
public function __construct(int $signum) {
$this->signum = $signum;
}
public function execute(Context $ctx): void {
switch ($this->signum) {
case SIGINT:
throw new SystemException('Received SIGINT');
case SIGTERM:
throw new SystemException('Received SIGTERM');
case SIGQUIT:
if (!$ctx->getConfig()->getSigQuitDebugging()) {
throw new SystemException('Received SIGQUIT');
}
$repl = new Repl('debugger');
$repl->start($ctx);
return;
default:
$msg = sprintf('Unable to handle unknown signal %d', $this->signum);
throw new EngineInternalError($msg);
}
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Tasks/Types/CallbackTask.php | src/Tasks/Types/CallbackTask.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Tasks\Types;
use \Smuuf\StrictObject;
use \Smuuf\Primi\Context;
use \Smuuf\Primi\Structures\CallArgs;
use \Smuuf\Primi\Tasks\TaskInterface;
use \Smuuf\Primi\Values\FuncValue;
class CallbackTask implements TaskInterface {
use StrictObject;
/** The callback function. */
private FuncValue $fn;
/** Arguments passed to callback. */
private CallArgs $args;
public function __construct(FuncValue $fn, ?CallArgs $args = null) {
$this->fn = $fn;
$this->args = $args ?? CallArgs::getEmpty();
}
public function execute(Context $ctx): void {
$this->fn->invoke($ctx, $this->args);
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
smuuf/primi | https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Tasks/Emitters/PosixSignalTaskEmitter.php | src/Tasks/Emitters/PosixSignalTaskEmitter.php | <?php
declare(strict_types=1);
namespace Smuuf\Primi\Tasks\Emitters;
use \Smuuf\Primi\Ex\EngineInternalError;
use \Smuuf\Primi\Tasks\TaskQueue;
use \Smuuf\Primi\Tasks\Types\PosixSignalTask;
abstract class PosixSignalTaskEmitter {
/**
* A list of signals that have been registered into `pcntl_signal`
* and it is not necessary to do so again.
*
* @var int[]
*/
private static $signalsToCatch = [];
/**
* List of registered task queues to which we'll push a signal
* task each time a signal is caught.
*
* @var TaskQueue[]
*/
private static $queues = [];
public static function catch(int $signum): void {
if (!\function_exists('pcntl_async_signals')) {
return;
}
// Call this only once - before registering the first signal handler.
if (!self::$signalsToCatch) {
\pcntl_async_signals(\true);
}
// A specific signal can be registered only once.
if (\in_array($signum, self::$signalsToCatch, \true)) {
return;
}
$signalsToCatch[] = $signum;
// Let's make sure any already registered signal handler is also called.
$original = \pcntl_signal_get_handler($signum);
\pcntl_signal($signum, function(...$args) use ($original) {
// Do our signal handling.
self::handle(...$args);
// Call also the original signal handler (if it was a callable).
if (\is_callable($original)) {
$original(...$args);
}
});
}
public static function registerTaskQueue(TaskQueue $queue): void {
// A specific receiver instance can be added only once.
if (\in_array($queue, self::$queues, \true)) {
throw new EngineInternalError('This receiver is already registered');
}
self::$queues[] = $queue;
}
/**
* Remove a registered receiver from signal receiving.
*
* You should always do this after you don't need to use the received, to
* avoid keeping unnecessary reference to the receiver object - to avoid
* leaks caused by blocking proper garbage collection.
*/
public static function unregisterTaskQueue(TaskQueue $queue): void {
$index = \array_search($queue, self::$queues, \true);
if ($index === \false) {
throw new EngineInternalError('This receiver was not previously registered');
}
unset(self::$queues[$index]);
}
public static function handle(int $signum): void {
foreach (self::$queues as $rec) {
$rec->addTask(new PosixSignalTask($signum));
}
}
}
| php | MIT | d66ad6a397080a4caec9b634c925c0e085a00bb0 | 2026-01-05T05:19:57.676815Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.