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/src/Drivers/ReplIoDriverInterface.php
src/Drivers/ReplIoDriverInterface.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Drivers; interface ReplIoDriverInterface extends StdIoDriverInterface { public function addToHistory(string $item): void; public function loadHistory(string $path): void; public function storeHistory(string $path): void; }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Drivers/VoidIoDriver.php
src/Drivers/VoidIoDriver.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Drivers; use \Smuuf\StrictObject; use \Smuuf\Primi\Ex\EngineError; class VoidIoDriver implements StdIoDriverInterface { use StrictObject; public function input(string $prompt): string { throw new EngineError("Trying to get input from void"); } public function stdout(string ...$text): void { // Void. } public function stderr(string ...$text): void { // Void. } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Drivers/TerminalIoDriver.php
src/Drivers/TerminalIoDriver.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Drivers; use \Smuuf\StrictObject; use \Smuuf\Primi\Cli\Term; class TerminalIoDriver implements StdIoDriverInterface { use StrictObject; private ?string $buffer = null; private function bufferInput(?string $buffer): void { $this->buffer = (string) $buffer; } public function input(string $prompt): string { // Using a bit more complex logic instead of just calling readline(). // That's because with readline() any multiline entries browsed for via // the readline history (up arrow) wouldn't be returned in full for // some reason (only its last line). // Register callback that will be called for every entered line // (that is, after the user presses enter). \readline_callback_handler_install($prompt, [$this, 'bufferInput']); while (\true) { // Wait for a single character input. \readline_callback_read_char(); // After the user presses enter, buffer will be (even empty) string, // so at that point we know we got the full input we want to return. if ($this->buffer !== \null) { break; } } \readline_callback_handler_remove(); $buffer = $this->buffer; $this->buffer = \null; return $buffer; } public function stdout(string ...$text): void { echo \implode('', $text); } public function stderr(string ...$text): void { Term::stderr(\implode('', $text)); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Drivers/StdIoDriverInterface.php
src/Drivers/StdIoDriverInterface.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Drivers; interface StdIoDriverInterface { public function input(string $prompt): string; public function stdout(string ...$text): void; public function stderr(string ...$text): void; }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Drivers/ReadlineUserIoDriver.php
src/Drivers/ReadlineUserIoDriver.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Drivers; use \Smuuf\StrictObject; class ReadlineUserIoDriver extends TerminalIoDriver implements ReplIoDriverInterface { use StrictObject; /** * Keep the latest item added to history for future reference. * * @var string */ private $lastItem = ''; public function addToHistory(string $item): void { // Avoid storing the same value again, if it's the same value // as before. Also don't store empty values to history. if (trim($item) === '' || $this->lastItem === $item) { return; } \readline_add_history($item); $this->lastItem = $item; } public function loadHistory(string $path): void { // Prior to loading the history file: // - Read it, // - Remove duplicates, // - And save it again. $entries = \file($path, \FILE_SKIP_EMPTY_LINES | \FILE_IGNORE_NEW_LINES); $fixed = \array_reverse(\array_unique(\array_reverse($entries))); \file_put_contents($path, \implode(\PHP_EOL, $fixed)); \readline_read_history($path); } public function storeHistory(string $path): void { \readline_write_history($path); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Parser/ParserFactory.php
src/Parser/ParserFactory.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Parser; use \Smuuf\StrictObject; use \Smuuf\Primi\EnvInfo; use \hafriedlander\Peg\Compiler; abstract class ParserFactory { use StrictObject; private const PARSER_CLASS = __NAMESPACE__ . '\\Compiled\\PrimiParser'; private const GRAMMAR_FILE = __DIR__ . '/Grammar/Primi.peg'; private const TARGET_PARSER_FILE = __DIR__ . '/Compiled/PrimiParser.php'; private const VERSION_FILE = __DIR__ . '/Compiled/version'; /** * Recompile only once per runtime to avoid expensive checks on each use. * If the grammar changes, the client just needs to restart the process. */ private static bool $recompiled = \false; public static function getParserClass(): string { // If we're running inside Phar, we assume the parser already is // compiled in the newest version (also, compiling it again - within the // Phar - would be nonsense). if (self::$recompiled === \true || EnvInfo::isRunningInPhar()) { return self::PARSER_CLASS; } $grammarVersion = \md5((string) \filemtime(self::GRAMMAR_FILE)); $parserVersion = \file_exists(self::VERSION_FILE) ? \file_get_contents(self::VERSION_FILE) : \false; if ($grammarVersion !== $parserVersion) { self::recompileParser($grammarVersion); } self::$recompiled = \true; return self::PARSER_CLASS; } private static function recompileParser(string $newVersion): void { $grammar = \file_get_contents(self::GRAMMAR_FILE); $code = Compiler::compile($grammar); \file_put_contents(self::TARGET_PARSER_FILE, $code, \LOCK_EX); \file_put_contents(self::VERSION_FILE, $newVersion, \LOCK_EX); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Parser/GrammarRulesLabels.php
src/Parser/GrammarRulesLabels.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Parser; abstract class GrammarRulesLabels { const LABELS = [ 'NumberLiteral' => "number literal", 'BoolLiteral' => "bool literal", 'StringLiteral' => "string literal", 'StringInside' => "start of string literal", 'FStringLiteral' => "f-string literal", 'FStringInside' => "start of f-string literal", 'FStringTxt' => "start of f-string literal", 'VectorAttr' => "attribute access operator", 'AttrAccess' => "attribute access operator", 'DictDefinition' => "dict definition", 'DictItem' => "dict item", 'ListDefinition' => "list definition", 'TupleDefinition' => "tuple definition", 'AbstractLiteral' => "literal", 'AbstractValue' => "literal or variable name", 'AddOperator' => "'+' or '-' operator", 'MultiplyOperator' => "'*' or '/' operator", 'PowerOperator' => "'**' operator", 'AssignmentOperator' => "assignment operator", 'ComparisonOperator' => "comparison operator", 'ComparisonOperatorWithWhitespace' => "membership operator", 'AndOperator' => "'and' operator", 'OrOperator' => "'or' operator", 'NegationOperator' => "negation operator", 'CondExpr' => "conditional expr", 'ArgumentList' => "arguments list", 'ParameterList' => "parameters list", 'FunctionDefinition' => "function definition", 'ClassDefinition' => "class definition", 'ImportStatement' => "import ...", 'IfStatement' => "if ...", 'ForStatement' => "for ...", 'WhileStatement' => "while ...", 'TryStatement' => "try ...", 'ReturnStatement' => "return statement", 'BreakStatement' => "break statement", 'ContinueStatement' => "continue statement", 'Block' => "code block", 'SEP' => "';' or newline", 'VectorItem' => "square bracket access", 'VariableName' => "variable name", ]; public static function getRuleLabel(?string $ruleName): ?string { return self::LABELS[$ruleName] ?? \null; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Parser/GrammarHelpers.php
src/Parser/GrammarHelpers.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Parser; use \Smuuf\StrictObject; abstract class GrammarHelpers { use StrictObject; const VALID_NAME_REGEX = '[a-zA-Z_][a-zA-Z0-9_]*'; const RESERVED_WORDS = [ 'false', 'true', 'null', 'if', 'else', 'return', 'for', 'and', 'or', 'function', 'break', 'continue', 'while', 'try', 'catch', 'not', 'in', 'import' ]; public static function isReservedWord(string $name): bool { return \in_array($name, self::RESERVED_WORDS, \true); } public static function isValidName(string $name): bool { return (bool) \preg_match( sprintf('#^(?:%s)$#S', self::VALID_NAME_REGEX), $name ); } public static function isSimpleAttrAccess(string $name): bool { return (bool) \preg_match( sprintf('#^(?:%1$s)(?:\.%1$s)*$#S', self::VALID_NAME_REGEX), $name ); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Parser/ParserHandler.php
src/Parser/ParserHandler.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Parser; use \Smuuf\Primi\Ex\InternalSyntaxError; use \Smuuf\Primi\Ex\InternalPostProcessSyntaxError; use \Smuuf\Primi\Parser\Compiled\PrimiParser; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\Timer; use \Smuuf\Primi\Handlers\HandlerFactory; use \Smuuf\Primi\Handlers\KnownHandlers; class ParserHandler { /** Primi source code as string that is to be parsed and executed. */ private string $source; /** @var array<string, scalar> Parser statistics. */ private array $stats = []; /** Compiled parser object. */ private PrimiParser $parser; public function __construct(string $source) { $class = ParserFactory::getParserClass(); $source = self::sanitizeSource($source); $this->parser = new $class($source); $this->source = $source; } /** * Return parser stats. * * @return array<string, float> */ public function getStats(): array { return $this->stats; } /** * @return TypeDef_AstNode */ public function run(): array { $t = (new Timer)->start(); $result = $this->parser->match_Program(); $this->stats['Parsing AST'] = $t->get(); if ($result['text'] !== $this->source) { // $this->pos is an internal PEG Parser position counter and // we will use it to determine the line and position in the source. $farthestRuleLabel = GrammarRulesLabels::getRuleLabel( $this->parser->getFarthestRule() ); $reason = $farthestRuleLabel ? "after $farthestRuleLabel" : \null; $this->syntaxError($this->parser->getFarthestPos(), $reason); } $t = (new Timer)->start(); $processed = $this->processAST($result, $this->source); $this->stats['AST postprocess total'] = $t->get(); return $processed; } /** * @return never */ private function syntaxError(int $position, ?string $reason = \null) { $line = \false; if ($position !== \false) { [$line, $linePos] = Func::get_position_estimate( $this->source, $position ); } throw new InternalSyntaxError( (int) $line, (int) $position, (int) $linePos, $reason ); } private static function sanitizeSource(string $s): string { // Unify new-lines. $s = \str_replace("\r\n", "\n", $s); // Ensure newline at the end (parser needs this to be able to correctly // parse comments in one line source codes.) return \rtrim($s) . "\n"; } /** * @param TypeDef_AstNode $ast * @return TypeDef_AstNode $ast */ private function processAST(array $ast, string $source): array { $t = (new Timer)->start(); self::preprocessNode($ast); $this->stats['AST nodes preprocessing'] = $t->get(); $t = (new Timer)->start(); $this->reduceNode($ast); $this->stats['AST nodes reducing'] = $t->get(); $t = (new Timer)->start(); $this->convertNamesToIds($ast); $this->stats['AST name conversion'] = $t->get(); return $ast; } /** * Go recursively through each of the nodes and strip unnecessary data * in the abstract syntax tree. * * @param TypeDef_AstNode $node */ private function preprocessNode(array &$node): void { // Add information about the node's offset (line & position) for // later use (e.g. for informative error messages). if (isset($node['offset'])) { [$line, $pos] = Func::get_position_estimate( $this->source, $node['offset'], ); $node['_l'] = $line; $node['_p'] = $pos; // Offset no longer necessary. unset($node['offset']); } // If node has "skip" node defined, replace the whole node with the // "skip" subnode. unset($node['_matchrule']); foreach ($node as &$item) { while ($inner = ($item['skip'] ?? \false)) { $item = $inner; } if (\is_array($item)) { self::preprocessNode($item); } } } /** * Go recursively through each of the nodes and strip unnecessary data * in the abstract syntax tree. * * @param TypeDef_AstNode $node */ private function reduceNode(array &$node): void { foreach ($node as &$item) { if (\is_array($item)) { $this->reduceNode($item); } } if (!isset($node['name'])) { return; } if (!$handler = HandlerFactory::tryGetForName($node['name'], \false)) { return; } // Remove text from nodes that don't need it. if (!$handler::NODE_NEEDS_TEXT) { unset($node['text']); } // If a handler knows how to reduce its node, let it. try { $handler::reduce($node); } catch (InternalPostProcessSyntaxError $e) { $this->syntaxError($node['_p'], $e->getReason()); } } private static function convertNamesToIds(array &$node): void { foreach ($node as &$item) { if (\is_array($item)) { self::convertNamesToIds($item); } } // Handler name to handler ID. if (isset($node['name'])) { $node['name'] = KnownHandlers::fromName($node['name'], \false); } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Modules/AllowedInSandboxTrait.php
src/Modules/AllowedInSandboxTrait.php
<?php namespace Smuuf\Primi\Modules; /** * Native Primi modules (written in PHP) implemented by a PHP class which * uses this trait will be allowed to be imported if Primi is running * in a sandbox mode. */ trait AllowedInSandboxTrait { }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Modules/NativeModuleExecutor.php
src/Modules/NativeModuleExecutor.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Modules; use \Smuuf\StrictObject; use \Smuuf\Primi\Context; use \Smuuf\Primi\Extensions\MethodExtractor; class NativeModuleExecutor { use StrictObject; /** * @return array<string, AbstractValue|mixed> Dict array that represents the * contents of the module. */ public static function execute(Context $ctx, NativeModule $module): array { // Basic execution. $attrs = $module->execute($ctx); // Extract additional functions from object. $functions = MethodExtractor::extractMethods($module); return \array_merge($attrs, $functions); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Modules/Importer.php
src/Modules/Importer.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Modules; use \Smuuf\StrictObject; use \Smuuf\Primi\Scope; use \Smuuf\Primi\Logger; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\ImportError; use \Smuuf\Primi\Ex\ModuleNotFoundError; use \Smuuf\Primi\Ex\ImportBeyondTopException; use \Smuuf\Primi\Ex\ImportRelativeWithoutParentException; use \Smuuf\Primi\Values\ModuleValue; use \Smuuf\Primi\Helpers\Wrappers\ContextPushPopWrapper; use \Smuuf\Primi\Helpers\Wrappers\ImportStackWrapper; use \Smuuf\Primi\Modules\Dotpath; use \Smuuf\Primi\StackFrame; /** * @internal */ class Importer { use StrictObject; private const MODULE_FILE_EXTENSIONS = [ NativeModuleLoader::class => ".primi.php", PrimiModuleLoader::class => ".primi", ]; /** Runtime context object. */ private Context $ctx; /** @var array<string, ModuleValue> Storage for loaded modules. */ private array $loaded = []; /** @var array<string> Import stack for circular import detection. */ private array $importStack = []; /** @var array<string> Known import paths. */ private array $importPaths = []; /** * Array dict cache for storing determined base paths when looking for * modules in various import paths. * * @var array<string, ?string> */ private array $baseCache = []; /** * @param array<string> $importPaths */ public function __construct( Context $ctx, array $importPaths = [] ) { $this->ctx = $ctx; $this->importPaths = $importPaths; } /** * @return array<string, ModuleValue> */ public function getLoaded(): array { return $this->loaded; } public function pushImport(string $importId): bool { // If this import ID is already in the stack, it is a circular import. if (\in_array($importId, $this->importStack, \true)) { return \false; } $this->importStack[] = $importId; return \true; } public function popImport(): void { \array_pop($this->importStack); } /** * Fetch module value object by its dot path. * * If the module has been already loaded, it will be just returned. If the * module has not been loaded yet, it will be loaded, stored into cache, and * then returned. */ public function getModule(string $dotpath): ModuleValue { $originPackage = ''; if ($currentModule = $this->ctx->getCurrentModule()) { $originPackage = $currentModule->getPackage(); } Logger::debug("Getting module '$dotpath' (with origin '$originPackage')"); try { $dp = new Dotpath($dotpath, $originPackage); } catch (ImportRelativeWithoutParentException $e) { throw new ImportError("Relative import without origin package"); } catch (ImportBeyondTopException $e) { throw new ImportError("Relative import {$e->getMessage()} reached beyond top-level package"); } $dotpathString = $dp->getAbsolute(); if (isset($this->loaded[$dotpathString])) { Logger::debug("Returned '$dotpathString' from module cache"); return $this->loaded[$dotpathString]; } // Determine which import path matches the first part of dotpath. // For example if we're trying to import module 'a.b.c', this returns // the first import path that contains the module 'a' (a package/dir 'a' // or module 'a.primi' or 'a.primi.php'). $base = $this->determineBase($dp, $this->importPaths); if ($base) { Logger::debug("Determined base '$base' for module '{$dp->getAbsolute()}'"); if ($module = $this->tryWithBase($base, $dp)) { return $module; } } Logger::debug("Module '$dotpath' could not be found"); throw new ModuleNotFoundError($dotpath); } /** * Go through each of the possible paths from where modules can be imported * and return the first path that actually contains the first part of the * dotpath of the module that is requested to be imported. * * For example, for given import paths (order is important) and their * contents: * * ``` * - /xxx/ * - a/bruh.primi * - b/bruh.primi * - /yyy/ * - b/bruh.primi * - c/bruh.primi * - /zzz/ * - c/bruh.primi * - d/bruh.primi * ``` * * ... importing 'c.bruh' would look through '/xxx/' first and then '/yyy/', * where 'c' directory is present - the resulting base is determined as * '/yyy/', ignoring the '/zzz/', because '/yyy/' was before it and thus * had a higher priority. * * @param array<string> $possiblePaths */ private function determineBase( Dotpath $dp, array $possiblePaths ): ?string { $first = $dp->getFirstPart(); if (\array_key_exists($first, $this->baseCache)) { return $this->baseCache[$first]; } foreach ($possiblePaths as $base) { $path = "$base/$first"; if (self::isModule($path)) { return $this->baseCache[$first] = $base; } } return $this->baseCache[$first] = \null; } private function tryWithBase(string $basepath, Dotpath $dp): ?ModuleValue { $module = \null; // Go through each of the paths (originating from this basepath) leading // to the target module - and try to import each one of them. foreach ($dp->iterPaths($basepath) as [$dotpath, $package, $filepath]) { if (!$module = $this->importModule($filepath, $dotpath, $package)) { // Stop importing if any of the paths doesn't represent a // module. Modules imported so far are still loaded and cached. return \null; } } // If the whole tree of module was successfully imported/fetched, return // the last one (which is what the user wants - when doing // 'import a.b.c' the 'c' module is returned from this function). return $module; } private function importModule( string $filepath, string $dotpath, string $packageDotpath ): ?ModuleValue { if (isset($this->loaded[$dotpath])) { return $this->loaded[$dotpath]; } // If the module is - in fact - a package (dir), import it as such. if (\is_dir($filepath)) { $module = $this->importPackage($filepath, $dotpath); return $module; } // Build dict of possible filenames with supported extensions // (differentiating whether the module is a native/PHP module or a // Primi module). The keys of the dict are the class names of loaders // that know how to load that particular extension. // Native modules ('.../module_name.primi.php') have priority over // Primi modules ('.../module_name.primi'). $candidates = self::withSupportedExtensions($filepath); foreach ($candidates as $loader => $candidate) { // If this file with this extension does in fact exist, load it // using the correct loader. if (!\is_file($candidate)) { continue; } return $this->loadModule( $loader, $candidate, $dotpath, $packageDotpath ); } // No filepath that corresponds to this dotpath exists, return null, // telling the caller that this import was a failure. return \null; } private function importPackage( string $filepath, string $dotpath ): ModuleValue { // Try importing the package's init file. $init = "$filepath/__init__"; if ($module = $this->importModule($init, $dotpath, $dotpath)) { return $module; } Logger::debug("Creating implicit package '$dotpath' from '$filepath'"); // If the package has no init file, just create an empty module object. $module = new ModuleValue($dotpath, $dotpath, new Scope); $this->loaded[$dotpath] = $module; return $module; } private function loadModule( string $loader, string $filepath, string $dotpath, string $packageDotpath ): ModuleValue { Logger::debug("Loading module '$dotpath' from file '$filepath'"); $wrapper = new ImportStackWrapper($this, $filepath, $dotpath); return $wrapper->wrap(function() use ( $loader, $filepath, $dotpath, $packageDotpath ) { // Imported module will have its own global scope. $scope = new Scope; $module = new ModuleValue( $dotpath, $packageDotpath, $scope ); // Put the newly created module immediately in the "loaded // module" cache. Relative imports made from this new module // might need to load this module again (because if module 'a' // wants to import '.b' relatively, the resulting absolute // module path is 'a.b' - and import mechanism wants to import // 'a' first and then 'b'). And we don't want the new module to // be imported again (that would result in circular import). $this->loaded[$dotpath] = $module; $frame = new StackFrame("<module>", $module); $wrapper = new ContextPushPopWrapper($this->ctx, $frame, $scope); $wrapper->wrap(function() use ( $loader, $filepath, $dotpath, $packageDotpath ) { return $loader::loadModule( $this->ctx, $filepath, $dotpath, $packageDotpath ); }); return $module; }); } // Static Helpers. /** * Returns true if a filepath (without extension) represents a module * or a package (which is a kind of module). Otherwise returns false. */ private static function isModule(string $filepath): bool { Logger::debug("Is '$filepath' a module?"); // Just a simple directory is a package (a package is a module). if (\is_dir($filepath)) { Logger::debug(" YES (package)"); return \true; } // Try adding supported module (file) extensions and go see if it // matches the filesystem contents. $candidates = self::withSupportedExtensions($filepath); foreach ($candidates as $candidate) { if (\is_file($candidate)) { Logger::debug(" YES (module)"); return \true; } } Logger::debug(" NO"); return \false; } /** * @return array<string> */ private static function withSupportedExtensions(string $filepath): array { $result = []; foreach (self::MODULE_FILE_EXTENSIONS as $loaderClass => $ext) { $result[$loaderClass] = "{$filepath}{$ext}"; } return $result; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Modules/Dotpath.php
src/Modules/Dotpath.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Modules; use \Smuuf\StrictObject; use \Smuuf\Primi\Ex\EngineInternalError; use \Smuuf\Primi\Ex\ImportBeyondTopException; class Dotpath { use StrictObject; private const VALID_REGEX = '#^(:?|(\.*))(?:[a-zA-Z_][a-zA-Z0-9_]*\.)*(?:[a-zA-Z_][a-zA-Z0-9_]*)$#'; /** Final absolute dotpath (with relativity resolved). */ private string $absolute; /** * Parts of the resolved dotpath. * * @var array<string> */ private array $parts; public function __construct( string $dotpath, string $originPackage = '' ) { if (!self::isValid($dotpath)) { throw new EngineInternalError("Invalid dot path '$dotpath'"); } if ($originPackage !== '' && !self::isValid($originPackage)) { throw new EngineInternalError("Invalid origin package dot path '$originPackage'"); } [ $this->absolute, $this->parts, ] = self::resolve($dotpath, $originPackage); } /** * Resolve the original, possibly relative, dotpath into an absolute * dotpath using origin as the origin dotpath. * * @return array{string, array<string>} */ private static function resolve( string $dotpath, string $originPackage ): array { $parts = []; $steps = \explode('.', $dotpath); // If the dotpath is absolute, we don't need to process it further. if (!\str_starts_with($dotpath, '.')) { return [$dotpath, $steps]; } // If the dotpath is relative (starts with a dot), use passed origin as // the origin. $parts = $originPackage ? \explode('.', $originPackage) : []; // Exploding relative import dotpath '.a.b' results in array list // with three items - empty string being the first - so let's get // rid of it. It's because the "while" algo below handles each one // of these empty strings as "go-one-level-up" from the origin // package dotpath, but we want the first dot in relative path // to mean "current level", not "one level up". \array_shift($steps); while (\true) { // If there are no more steps to process, break the loop. if (!$steps) { break; } $step = array_shift($steps); // Empty step means a single dot exploded from the original dotpath. // And if ($step === '') { // If there are no parts left and one level up was requested, // it's a beyond-top-level error. if (!$parts) { throw new ImportBeyondTopException($dotpath); } array_pop($parts); continue; } $parts[] = $step; } // Save final dotpath (with relativity resolved). $absolute = \implode('.', $parts); return [$absolute, $parts]; } public function getAbsolute(): string { return $this->absolute; } public function getFirstPart(): string { return \reset($this->parts); } /** * @return iterable<array{string, string, string}> */ public function iterPaths(string $basepath = ''): iterable { $dotpath = ''; $package = ''; $filepath = "{$basepath}/"; foreach ($this->parts as $part) { $dotpath .= $part; $filepath .= $part; yield [$dotpath, $package, $filepath]; $package = $dotpath; $dotpath .= '.'; $filepath .= '/'; } } // Helpers. /** Returns true if the dotpath string is a valid dotpath. */ private static function isValid(string $dotpath): bool { return (bool) \preg_match(self::VALID_REGEX, $dotpath); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Modules/PrimiModuleLoader.php
src/Modules/PrimiModuleLoader.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Modules; use \Smuuf\StrictObject; use \Smuuf\Primi\Context; use \Smuuf\Primi\DirectInterpreter; use \Smuuf\Primi\Code\SourceFile; class PrimiModuleLoader { use StrictObject; public static function loadModule(Context $ctx, string $filepath): void { $source = new SourceFile($filepath); $ast = $ctx->getAstProvider()->getAst($source); // Execute the source code within the new scope. DirectInterpreter::execute($ast, $ctx); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Modules/NativeModule.php
src/Modules/NativeModule.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Modules; use \Smuuf\Primi\Context; use \Smuuf\Primi\Helpers\ValueFriends; abstract class NativeModule extends ValueFriends { /** * This method is called by the importer during import. Resulting array, * which maps variable name to some value, is then used to populate the * module scope. * * @return array<string, AbstractValue|mixed> Pairs that will constitute * the contents of the scope of the module. */ public function execute(Context $ctx): array { return []; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Modules/NativeModuleLoader.php
src/Modules/NativeModuleLoader.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Modules; use \Smuuf\StrictObject; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\EngineError; use \Smuuf\Primi\Ex\RuntimeError; class NativeModuleLoader { use StrictObject; public static function loadModule(Context $ctx, string $filepath): void { // Closure to block access of the file's code to this PHP scope. $loader = static fn($modulePath) => require $modulePath; $result = $loader($filepath); if (!$result instanceof NativeModule) { throw new EngineError("Native module loader encountered a non-native module file"); } $traits = \class_uses($result, \false) ?: []; if ( !\in_array(AllowedInSandboxTrait::class, $traits, \true) && $ctx->getConfig()->getSandboxMode() ) { throw new RuntimeError("Access to native module forbidden when in sandbox"); } $dict = NativeModuleExecutor::execute($ctx, $result); $ctx->getCurrentScope()->setVariables($dict); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/BuiltinTypes.php
src/Stdlib/BuiltinTypes.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib; use \Smuuf\StrictObject; use \Smuuf\Primi\MagicStrings; use \Smuuf\Primi\Stdlib\TypeExtensions\BoolTypeExtension; use \Smuuf\Primi\Stdlib\TypeExtensions\BytesTypeExtension; use \Smuuf\Primi\Stdlib\TypeExtensions\DictTypeExtension; use \Smuuf\Primi\Stdlib\TypeExtensions\ListTypeExtension; use \Smuuf\Primi\Stdlib\TypeExtensions\NullTypeExtension; use \Smuuf\Primi\Stdlib\TypeExtensions\TypeTypeExtension; use \Smuuf\Primi\Stdlib\TypeExtensions\RegexTypeExtension; use \Smuuf\Primi\Stdlib\TypeExtensions\TupleTypeExtension; use \Smuuf\Primi\Stdlib\TypeExtensions\NumberTypeExtension; use \Smuuf\Primi\Stdlib\TypeExtensions\ObjectTypeExtension; use \Smuuf\Primi\Stdlib\TypeExtensions\StringTypeExtension; use \Smuuf\Primi\Stdlib\TypeExtensions\ForbiddenTypeExtension; use \Smuuf\Primi\Values\BuiltinTypeValue; use \Smuuf\Primi\Values\BoolValue; use \Smuuf\Primi\Values\DictValue; use \Smuuf\Primi\Values\FuncValue; use \Smuuf\Primi\Values\ListValue; use \Smuuf\Primi\Values\NullValue; use \Smuuf\Primi\Values\BytesValue; use \Smuuf\Primi\Values\TupleValue; use \Smuuf\Primi\Values\RegexValue; use \Smuuf\Primi\Values\MethodValue; use \Smuuf\Primi\Values\ModuleValue; use \Smuuf\Primi\Values\NumberValue; use \Smuuf\Primi\Values\StringValue; use \Smuuf\Primi\Values\NotImplementedValue; use \Smuuf\Primi\Values\IteratorFactoryValue; /** * Global provider for builtin global and immutable native types. */ abstract class BuiltinTypes { use StrictObject; private static BuiltinTypeValue $objectType; private static BuiltinTypeValue $typeType; private static BuiltinTypeValue $nullType; private static BuiltinTypeValue $boolType; private static BuiltinTypeValue $numberType; private static BuiltinTypeValue $stringType; private static BuiltinTypeValue $bytesType; private static BuiltinTypeValue $regexType; private static BuiltinTypeValue $listType; private static BuiltinTypeValue $dictType; private static BuiltinTypeValue $tupleType; private static BuiltinTypeValue $funcType; private static BuiltinTypeValue $methodType; private static BuiltinTypeValue $iteratorFactoryType; private static BuiltinTypeValue $moduleType; // Specials. private static BuiltinTypeValue $notImplementedType; public static function getObjectType(): BuiltinTypeValue { return self::$objectType ??= new BuiltinTypeValue(MagicStrings::TYPE_OBJECT, \null, ObjectTypeExtension::execute(), \false); } public static function getTypeType(): BuiltinTypeValue { return self::$typeType ??= new BuiltinTypeValue(BuiltinTypeValue::TYPE, self::getObjectType(), TypeTypeExtension::execute()); } public static function getNullType(): BuiltinTypeValue { return self::$nullType ??= new BuiltinTypeValue(NullValue::TYPE, self::getObjectType(), NullTypeExtension::execute()); } public static function getBoolType(): BuiltinTypeValue { return self::$boolType ??= new BuiltinTypeValue(BoolValue::TYPE, self::getObjectType(), BoolTypeExtension::execute()); } public static function getNumberType(): BuiltinTypeValue { return self::$numberType ??= new BuiltinTypeValue(NumberValue::TYPE, self::getObjectType(), NumberTypeExtension::execute()); } public static function getStringType(): BuiltinTypeValue { return self::$stringType ??= new BuiltinTypeValue(StringValue::TYPE, self::getObjectType(), StringTypeExtension::execute()); } public static function getBytesType(): BuiltinTypeValue { return self::$bytesType ??= new BuiltinTypeValue(BytesValue::TYPE, self::getObjectType(), BytesTypeExtension::execute()); } public static function getRegexType(): BuiltinTypeValue { return self::$regexType ??= new BuiltinTypeValue(RegexValue::TYPE, self::getObjectType(), RegexTypeExtension::execute()); } public static function getListType(): BuiltinTypeValue { return self::$listType ??= new BuiltinTypeValue(ListValue::TYPE, self::getObjectType(), ListTypeExtension::execute()); } public static function getDictType(): BuiltinTypeValue { return self::$dictType ??= new BuiltinTypeValue(DictValue::TYPE, self::getObjectType(), DictTypeExtension::execute()); } public static function getTupleType(): BuiltinTypeValue { return self::$tupleType ??= new BuiltinTypeValue(TupleValue::TYPE, self::getObjectType(), TupleTypeExtension::execute()); } public static function getFuncType(): BuiltinTypeValue { return self::$funcType ??= new BuiltinTypeValue(FuncValue::TYPE, self::getObjectType(), ForbiddenTypeExtension::execute()); } public static function getMethodType(): BuiltinTypeValue { return self::$methodType ??= new BuiltinTypeValue(MethodValue::TYPE, self::getObjectType(), ForbiddenTypeExtension::execute()); } public static function getIteratorFactoryType(): BuiltinTypeValue { return self::$iteratorFactoryType ??= new BuiltinTypeValue(IteratorFactoryValue::TYPE, self::getObjectType(), ForbiddenTypeExtension::execute()); } public static function getModuleType(): BuiltinTypeValue { return self::$moduleType ??= new BuiltinTypeValue(ModuleValue::TYPE, self::getObjectType(), ForbiddenTypeExtension::execute()); } public static function getNotImplementedType(): BuiltinTypeValue { return self::$notImplementedType ??= new BuiltinTypeValue(NotImplementedValue::TYPE, self::getObjectType(), ForbiddenTypeExtension::execute()); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/Modules/std/__builtins__.primi.php
src/Stdlib/Modules/std/__builtins__.primi.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\Modules; use \Smuuf\Primi\Repl; use \Smuuf\Primi\Context; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Ex\LookupError; use \Smuuf\Primi\Ex\RuntimeError; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Values\NullValue; use \Smuuf\Primi\Values\BoolValue; use \Smuuf\Primi\Values\TupleValue; use \Smuuf\Primi\Values\NumberValue; use \Smuuf\Primi\Values\StringValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Values\IteratorFactoryValue; use \Smuuf\Primi\Values\ListValue; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Modules\NativeModule; use \Smuuf\Primi\Structures\CallArgs; use \Smuuf\Primi\Modules\AllowedInSandboxTrait; return new /** * Internal module where _built-ins_ are stored. * * This module doesn't need to be imported - its contents are available by * default in every scope. */ class extends NativeModule { use AllowedInSandboxTrait; public function execute(Context $ctx): array { $types = $ctx->getImporter() ->getModule('std.types') ->getCoreValue(); return [ 'object' => $types->getVariable('object'), 'type' => $types->getVariable('type'), 'bool' => $types->getVariable('bool'), 'dict' => $types->getVariable('dict'), 'list' => $types->getVariable('list'), 'tuple' => $types->getVariable('tuple'), 'number' => $types->getVariable('number'), 'regex' => $types->getVariable('regex'), 'string' => $types->getVariable('string'), 'NotImplemented' => Interned::constNotImplemented(), ]; } /** * _**Only in [CLI](https://w.wiki/QPE)**_. * * Prints value to standard output. */ #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function print( CallArgs $args, Context $ctx ): NullValue { $io = $ctx->getStdIoDriver(); if ($args->isEmpty()) { $io->stdout("\n"); return Interned::null(); } $args = $args->extract(['*args', 'end', 'sep'], ['end', 'sep']); $end = $args['end'] ?? Interned::string("\n"); $sep = $args['sep'] ?? Interned::string(" "); $pieces = \array_map( static fn($v) => $v->getStringValue(), $args['args']->getCoreValue() ); $io->stdout( \implode($sep->getStringValue(), $pieces), $end->getStringValue() ); return Interned::null(); } /** * _**Only in [CLI](https://w.wiki/QPE)**_. * * Injects a [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) * session for debugging at the specified line. */ #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function debugger( CallArgs $args, Context $ctx ): AbstractValue { $args->extractPositional(0); if ($ctx->getConfig()->getSandboxMode()) { throw new RuntimeError("Function 'debugger' disabled in sandbox"); } $repl = new Repl('debugger'); $repl->start($ctx); return Interned::null(); } /** * Returns length of a value. * * ```js * len("hello, Česká Třebová") == 20 * len(123456) == 6 * len([1, 2, 3]) == 3 * len({'a': 1, 'b': 'c'}) == 2 * ``` */ #[PrimiFunc (toStack: \false)] public static function len(AbstractValue $value): NumberValue { $length = $value->getLength(); if ($length === \null) { $type = $value->getTypeName(); throw new RuntimeError("Type '$type' does not support length"); } return Interned::number((string) $value->getLength()); } /** * This function returns `true` if a `bool` value passed into it is `true` * and throws error if it's `false`. Optional `string` description can be * provided, which will be visible in the eventual error message. */ #[PrimiFunc] public static function assert( BoolValue $assumption, ?StringValue $description = \null ): BoolValue { $desc = $description; if ($assumption->value !== \true) { $desc = ($desc && $desc->value !== '') ? " ($desc->value)" : ''; throw new RuntimeError(\sprintf("Assertion failed%s", $desc)); } return Interned::bool(\true); } /** * This function returns `true` if a `bool` value passed into it is `true` * and throws error if it's `false`. Optional `string` description can be * provided, which will be visible in the eventual error message. */ #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function range(CallArgs $args): IteratorFactoryValue { $args = $args->extract(['start', 'end', 'step'], ['end', 'step']); // No explicit 'end' argument? That means 'start' actually means 'end'. if (!isset($args['end'])) { $end = $args['start']->getCoreValue(); $start = '0'; } else { $start = $args['start']->getCoreValue(); $end = $args['end']->getCoreValue(); } $step = isset($args['step']) ? $args['step']->getCoreValue() : '1'; if ( !Func::is_round_int($start) || !Func::is_round_int($end) || !Func::is_round_int($step) ) { throw new RuntimeError( "All numbers passed to range() must be integers"); } if ($step <= 0) { throw new RuntimeError( "Range must have a non-negative non-zero step"); } $direction = $end >= $start ? 1 : -1; $step *= $direction; $gen = function(int $start, int $end, int $step) { if ($start === $end) { return; } $c = $start; while (\true) { if ($start < $end && $c >= $end) { break; } if ($start > $end && $c <= $end) { break; } yield Interned::number((string) $c); $c += $step; } return; }; return new IteratorFactoryValue( // Short closure syntax gives latest PHPStan a headache and // reports some nonsense about the function "should not return // anything". function() use ($gen, $start, $end, $step): \Generator { return $gen((int) $start, (int) $end, (int) $step); }, 'range' ); } /** * Return list of names of attributes present in an object. */ #[PrimiFunc] public static function dir(AbstractValue $value): ListValue { return new ListValue( array_map( [Interned::class, 'string'], $value->dirItems() ?? [] ) ); } /** * Returns iterator yielding tuples of index and items from an iterator. * * ```js * a_list = ['a', 'b', 123, false] * list(enumerate(a_list)) == [(0, 'a'), (1, 'b'), (2, 123), (3, false)] * * b_list = ['a', 'b', 123, false] * list(enumerate(b_list, -5)) == [(-5, 'a'), (-4, 'b'), (-3, 123), (-2, false)] * ``` */ #[PrimiFunc(toStack: \true, callConv: PrimiFunc::CONV_CALLARGS)] public static function enumerate(CallArgs $args): IteratorFactoryValue { [$iterable, $start] = $args->extractPositional(2, 1); $start ??= Interned::number('0'); if (!$start instanceof NumberValue) { throw new RuntimeError("Start must be a number"); } $counter = $start->getStringValue(); $it = function($iterable, $counter): \Generator { $iter = $iterable->getIterator(); if ($iter === \null) { throw new RuntimeError("Passed iterable is not iterable"); } foreach ($iter as $item) { yield new TupleValue([ Interned::number((string) $counter), $item ]); $counter++; } }; return new IteratorFactoryValue( // Short closure syntax gives latest PHPStan a headache and // reports some nonsense about the function "should not return // anything". function() use ($it, $iterable, $counter): \Generator { return $it($iterable, $counter); }, 'enumerate' ); } /** * Returns `true` if object has an attribute with specified name. */ #[PrimiFunc] public static function hasattr( AbstractValue $obj, StringValue $name ): BoolValue { return Interned::bool(isset($obj->attrs[$name->getStringValue()])); } /** * Returns value of object's attribute with specified name. If the object * has no attribute of that name, error is thrown. * * If the optional `default` argument is specified its value is returned * instead of throwing an error. */ #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function getattr( CallArgs $args ): AbstractValue { [$obj, $name, $default] = $args->extractPositional(3, 1); $attrName = $name->getStringValue(); if ($attrValue = $obj->attrGet($attrName)) { return $attrValue; } if ($default !== \null) { return $default; } $typeName = $obj->getTypeName(); throw new LookupError( "Object of type '$typeName' has no attribute '$attrName'"); } };
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/Modules/std/math.primi.php
src/Stdlib/Modules/std/math.primi.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\Modules; use \Smuuf\Primi\Context; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Ex\RelationError; use \Smuuf\Primi\Values\NumberValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Modules\NativeModule; use \Smuuf\Primi\Modules\AllowedInSandboxTrait; return new /** * Functions and tools for common mathematical operations. */ class extends NativeModule { use AllowedInSandboxTrait; public function execute(Context $ctx): array { return [ // π 'PI' => Interned::number('3.14159265358979323846'), // Euler's number 'E' => Interned::number('2.718281828459045'), ]; } /** * @param array<AbstractValue> $items */ private static function minmax(string $op, array $items): AbstractValue { $minmax = $items[0]; foreach ($items as $item) { $rel = $item->hasRelationTo($op, $minmax); if ($rel === \null) { throw new RelationError($op, $item, $minmax); } elseif ($rel) { $minmax = $item; } } return $minmax; } /** * Return the highest value from iterable or from two or more arguments. */ #[PrimiFunc] public static function max(AbstractValue ...$items): AbstractValue { return self::minmax('>', $items); } /** * Return the highest value from iterable or from two or more arguments. */ #[PrimiFunc] public static function min(AbstractValue ...$items): AbstractValue { return self::minmax('<', $items); } // // Trigonometry functions.. // /** * Returns the sine of number `n` specified in radians. */ #[PrimiFunc] public static function sin(NumberValue $n): NumberValue { $result = (string) \sin((float) $n->value); return new NumberValue(Func::scientific_to_decimal($result)); } /** * Returns the cosine of number `n` specified in radians. */ #[PrimiFunc] public static function cos(NumberValue $n): NumberValue { $result = (string) \cos((float) $n->value); return new NumberValue(Func::scientific_to_decimal($result)); } /** * Returns the tangent of number `n` specified in radians. */ #[PrimiFunc] public static function tan(NumberValue $n): NumberValue { $result = (string) \tan((float) $n->value); return new NumberValue(Func::scientific_to_decimal($result)); } /** * Returns the arc tangent of number `n` specified in radians. */ #[PrimiFunc] public static function atan(NumberValue $n): NumberValue { $result = (string) \atan((float) $n->value); return new NumberValue(Func::scientific_to_decimal($result)); } // // Rounding. // /** * Returns number `n` rounded to specified `precision`. If the * precision is not specified, a default `precision` of zero is used. */ #[PrimiFunc] public static function round( NumberValue $n, NumberValue $precision = \null ): NumberValue { return Interned::number((string) \round( (float) $n->value, $precision ? (int) $precision->value : 0 )); } /** * Returns number `n` rounded up. */ #[PrimiFunc] public static function ceil(NumberValue $n): NumberValue { return Interned::number((string) \ceil((float) $n->value)); } /** * Returns number `n` rounded down. */ #[PrimiFunc] public static function floor(NumberValue $n): NumberValue { return Interned::number((string) \floor((float) $n->value)); } /** * Returns the absolute value of number `n`. */ #[PrimiFunc] public static function abs(NumberValue $n): NumberValue { return Interned::number(\ltrim($n->value, '-')); } /** * Returns the square root of a number `n`. */ #[PrimiFunc] public static function sqrt(NumberValue $n): NumberValue { return new NumberValue((string) \bcsqrt( $n->value, NumberValue::PRECISION )); } /** * Returns number `n` squared to the power of `power`. */ #[PrimiFunc] public static function pow( NumberValue $n, ?NumberValue $power = \null ): NumberValue { /** @var NumberValue */ $result = $n->doPower($power ?? new NumberValue('2')); return $result; } /** * Returns the remainder (modulo) of the division of the arguments. */ #[PrimiFunc] public static function mod( NumberValue $a, NumberValue $b ): NumberValue { return new NumberValue(\bcmod( $a->value, $b->value, NumberValue::PRECISION) ); } };
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/Modules/std/types.primi.php
src/Stdlib/Modules/std/types.primi.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\Modules; use \Smuuf\Primi\Context; use \Smuuf\Primi\MagicStrings; use \Smuuf\Primi\Stdlib\BuiltinTypes; use \Smuuf\Primi\Values\BoolValue; use \Smuuf\Primi\Values\DictValue; use \Smuuf\Primi\Values\FuncValue; use \Smuuf\Primi\Values\ListValue; use \Smuuf\Primi\Values\NullValue; use \Smuuf\Primi\Values\TypeValue; use \Smuuf\Primi\Values\RegexValue; use \Smuuf\Primi\Values\TupleValue; use \Smuuf\Primi\Values\MethodValue; use \Smuuf\Primi\Values\ModuleValue; use \Smuuf\Primi\Values\NumberValue; use \Smuuf\Primi\Values\StringValue; use \Smuuf\Primi\Values\NotImplementedValue; use \Smuuf\Primi\Values\IteratorFactoryValue; use \Smuuf\Primi\Modules\NativeModule; use \Smuuf\Primi\Modules\AllowedInSandboxTrait; return new /** * Module housing Primi's basic data types. */ class extends NativeModule { use AllowedInSandboxTrait; public function execute(Context $ctx): array { return [ // Super-basic types. MagicStrings::TYPE_OBJECT => BuiltinTypes::getObjectType(), TypeValue::TYPE => BuiltinTypes::getTypeType(), NullValue::TYPE => BuiltinTypes::getNullType(), BoolValue::TYPE => BuiltinTypes::getBoolType(), NumberValue::TYPE => BuiltinTypes::getNumberType(), StringValue::TYPE => BuiltinTypes::getStringType(), RegexValue::TYPE => BuiltinTypes::getRegexType(), DictValue::TYPE => BuiltinTypes::getDictType(), ListValue::TYPE => BuiltinTypes::getListType(), TupleValue::TYPE => BuiltinTypes::getTupleType(), // Other basic types (basic == they're implemented in PHP). FuncValue::TYPE => BuiltinTypes::getFuncType(), MethodValue::TYPE => BuiltinTypes::getMethodType(), IteratorFactoryValue::TYPE => BuiltinTypes::getIteratorFactoryType(), ModuleValue::TYPE => BuiltinTypes::getModuleType(), // Other types. NotImplementedValue::TYPE => BuiltinTypes::getNotImplementedType(), ]; } };
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/Modules/std/time.primi.php
src/Stdlib/Modules/std/time.primi.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\Modules; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Ex\RuntimeError; use \Smuuf\Primi\Values\NullValue; use \Smuuf\Primi\Values\StringValue; use \Smuuf\Primi\Values\NumberValue; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Modules\NativeModule; use \Smuuf\Primi\Structures\CallArgs; use \Smuuf\Primi\Modules\AllowedInSandboxTrait; return new /** * Functions and tools for basic time-related operations. */ class extends NativeModule { use AllowedInSandboxTrait; /** * Returns high-resolution monotonic time. It is an arbitrary number that * keeps increasing by 1 every second. */ #[PrimiFunc] public static function monotonic(): NumberValue { return new NumberValue((string) Func::monotime()); } /** * Returns current high-resolution UNIX time. */ #[PrimiFunc] public static function now(): NumberValue { return new NumberValue((string) \microtime(\true)); } /** * Sleep specified number of seconds. */ #[PrimiFunc] public static function sleep(NumberValue $duration): NullValue { $d = $duration->value; if (Func::is_round_int($d)) { \sleep((int) $duration->value); } else { \usleep((int) ($duration->value * 1_000_000)); } return Interned::null(); } /** * Return UNIX timestamp from human readable string. * * @see https://www.php.net/manual/en/function.strtotime.php */ #[PrimiFunc] public static function from_string(StringValue $when): NumberValue { $when = $when->value; if (!\trim($when)) { throw new RuntimeError("Cannot convert empty string into UNIX timestamp"); } $ts = \strtotime($when); if ($ts === \false) { throw new RuntimeError("Cannot convert '$when' into UNIX timestamp"); } return new NumberValue((string) $ts); } /** * Return string UNIX timestamp to a string representation specified by * format. If timestamp is provided, current time will be used. */ #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function format( CallArgs $args ): StringValue { [$format, $now] = $args->extractPositional(2, 1); if ($now) { Func::allow_argument_types(1, $now, NumberValue::class); $now = (int) $now->getStringValue(); } else { $now = \time(); } Func::allow_argument_types(2, $format, StringValue::class); $format = $format->getStringValue(); return Interned::string(\date($format, $now)); } };
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/Modules/std/hash.primi.php
src/Stdlib/Modules/std/hash.primi.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\Modules; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Values\NumberValue; use \Smuuf\Primi\Values\StringValue; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Modules\NativeModule; use \Smuuf\Primi\Modules\AllowedInSandboxTrait; return new /** * Hashing functions. */ class extends NativeModule { use AllowedInSandboxTrait; /** * Return [`crc32`](https://en.wikipedia.org/wiki/Cyclic_redundancy_check) * representation of a `string` value as `number`. * * ```js * crc32('hello') == 907060870 * crc32('123') == 2286445522 * ``` */ #[PrimiFunc] public static function crc32(StringValue $data): NumberValue { return Interned::number((string) \crc32($data->value)); } /** * Return [`md5` hash](https://en.wikipedia.org/wiki/MD5) representation * of a `string` value as `string`. * * ```js * md5('hello') == '5d41402abc4b2a76b9719d911017c592' * md5('123') == '202cb962ac59075b964b07152d234b70' * ``` */ #[PrimiFunc] public static function md5(StringValue $data): StringValue { return Interned::string(\md5($data->value)); } /** * Return [`sha256` hash](https://en.wikipedia.org/wiki/SHA-2) representation * of a `string` value as `string`. * * ```js * sha256('hello') == '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824' * sha256('123') == 'a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3' * ``` */ #[PrimiFunc] public static function sha256(StringValue $data): StringValue { return Interned::string(\hash('sha256', $data->value)); } };
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/Modules/std/base64.primi.php
src/Stdlib/Modules/std/base64.primi.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\Modules; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Ex\RuntimeError; use \Smuuf\Primi\Values\StringValue; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Modules\NativeModule; use \Smuuf\Primi\Modules\AllowedInSandboxTrait; return new /** * Encoding and decoding [`base64`](https://en.wikipedia.org/wiki/Base64). */ class extends NativeModule { use AllowedInSandboxTrait; /** * Return [`base64`](https://en.wikipedia.org/wiki/Base64) * representation of a `string` value as `number`. * * ```js * base64.encode('hello there, fellow kids') == "aGVsbG8gdGhlcmUsIGZlbGxvdyBraWRz" * ``` */ #[PrimiFunc] public static function encode(StringValue $data): StringValue { return Interned::string(\base64_encode($data->value)); } /** * Return [`base64`](https://en.wikipedia.org/wiki/Base64) * representation of a `string` value as `number`. * * ```js * base64.encode('hello there, fellow kids') == "aGVsbG8gdGhlcmUsIGZlbGxvdyBraWRz" * ``` */ #[PrimiFunc] public static function decode(StringValue $data): StringValue { $result = \base64_decode($data->value, \true); if ($result === \false) { throw new RuntimeError("Failed to decode base64 string"); } return Interned::string($result); } };
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/Modules/std/datetime.primi.php
src/Stdlib/Modules/std/datetime.primi.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\Modules; use \Smuuf\Primi\Context; use \Smuuf\Primi\Stdlib\BuiltinTypes; use \Smuuf\Primi\Stdlib\TypeExtensions\Stdlib\DatetimeTypeExtension; use \Smuuf\Primi\Stdlib\TypeExtensions\Stdlib\DurationTypeExtension; use \Smuuf\Primi\Values\TypeValue; use \Smuuf\Primi\Modules\NativeModule; use \Smuuf\Primi\Modules\AllowedInSandboxTrait; return new /** * Tools for date and time related operations. */ class extends NativeModule { use AllowedInSandboxTrait; public function execute(Context $ctx): array { return [ 'Datetime' => new TypeValue( 'Datetime', BuiltinTypes::getObjectType(), DatetimeTypeExtension::execute(), ), 'Duration' => new TypeValue( 'Duration', BuiltinTypes::getObjectType(), DurationTypeExtension::execute(), ), ]; } };
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/Modules/std/__engine__/importing.primi.php
src/Stdlib/Modules/std/__engine__/importing.primi.php
<?php namespace Smuuf\Primi\Stdlib\Modules; use \Smuuf\Primi\Context; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Modules\NativeModule; /** * Native '__engine__.importing' module. */ return new class extends NativeModule { /** Context instance. */ private Context $ctx; public function execute(Context $ctx): array { $this->ctx = $ctx; return [ 'get_loaded' => [$this, 'get_loaded'], ]; } /** * _**Only in [CLI](https://w.wiki/QPE)**_. * * Returns memory peak usage used by Primi _(engine behind the scenes)_ in * bytes. */ public function get_loaded(): AbstractValue { $loaded = $this->ctx->getImporter()->getLoaded(); // We want to return only information about module objects and not paths // they were loaded from, so strip that information (paths are keys) in // the dict returned from importer instance. Get rid of them. return AbstractValue::buildAuto($loaded); } };
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/Modules/std/__engine__/ast.primi.php
src/Stdlib/Modules/std/__engine__/ast.primi.php
<?php namespace Smuuf\Primi\Stdlib\Modules; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Values\StringValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Parser\ParserHandler; use \Smuuf\Primi\Modules\NativeModule; /** * Native '__engine__.ast' module. */ return new class extends NativeModule { /** * Return parsed Primi code provided as string represented as (possibly * nested) dicts/lists. * * ```js * tree = ast.parse('tree = ast.parse()') * ``` */ #[PrimiFunc] public static function parse(StringValue $source): AbstractValue { $ast = (new ParserHandler($source->value))->run(); return AbstractValue::buildAuto($ast); } };
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/Modules/std/runtime/memory.primi.php
src/Stdlib/Modules/std/runtime/memory.primi.php
<?php namespace Smuuf\Primi\Stdlib\Modules; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Values\DictValue; use \Smuuf\Primi\Values\NumberValue; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Modules\NativeModule; /** * Native 'std.runtime.memory' module. */ return new class extends NativeModule { /** * _**Only in [CLI](https://w.wiki/QPE)**_. * * Returns memory peak usage used by Primi _(engine behind the scenes)_ in * bytes. */ #[PrimiFunc] public static function get_peak(): NumberValue { return Interned::number((string) \memory_get_peak_usage()); } /** * _**Only in [CLI](https://w.wiki/QPE)**_. * * Returns current memory usage used by Primi _(engine behind the scenes)_ * in bytes. */ #[PrimiFunc] public static function get_current(): NumberValue { return Interned::number((string) \memory_get_usage()); } /** * _**Only in [CLI](https://w.wiki/QPE)**_. * * Run PHP garbage collection. Return the number of cycles collected. * See https://www.php.net/manual/en/features.gc.collecting-cycles.php */ #[PrimiFunc] public static function gc_run(): NumberValue { return Interned::number((string) \gc_collect_cycles()); } /** * _**Only in [CLI](https://w.wiki/QPE)**_. * * Get PHP garbage collection stats. * See https://www.php.net/manual/en/function.gc-status.php */ #[PrimiFunc] public static function gc_status(): DictValue { return new DictValue(Func::array_to_couples(\gc_status())); } };
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/Modules/std/runtime/__init__.primi.php
src/Stdlib/Modules/std/runtime/__init__.primi.php
<?php namespace Smuuf\Primi\Stdlib\Modules; use \Smuuf\Primi\Context; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Modules\NativeModule; use \Smuuf\Primi\Structures\CallArgs; /** * Native 'std.runtime' module. */ return new class extends NativeModule { /** * _**Only in [CLI](https://w.wiki/QPE)**_. * Return traceback as a list. */ #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function get_stack( CallArgs $_, Context $ctx ): AbstractValue { return AbstractValue::buildAuto(\array_map( static fn($f) => $f->asString(), $ctx->getCallStack() )); } };
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/TypeExtensions/DictTypeExtension.php
src/Stdlib/TypeExtensions/DictTypeExtension.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\TypeExtensions; use \Smuuf\Primi\Context; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Ex\TypeError; use \Smuuf\Primi\Ex\UnhashableTypeException; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Values\DictValue; use \Smuuf\Primi\Values\BoolValue; use \Smuuf\Primi\Values\ListValue; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Extensions\TypeExtension; use \Smuuf\Primi\Stdlib\BuiltinTypes; use \Smuuf\Primi\Structures\CallArgs; use \Smuuf\Primi\Values\TupleValue; use \Smuuf\Primi\Values\TypeValue; class DictTypeExtension extends TypeExtension { #[PrimiFunc] public static function __new__( TypeValue $type, ?AbstractValue $value = \null ): DictValue { if ($type !== BuiltinTypes::getDictType()) { throw new TypeError("Passed invalid type object"); } // Default value for a new number is 0. if ($value === \null) { return new DictValue([]); } $iter = $value->getIterator(); if ($iter === \null) { throw new TypeError('dict() argument must be iterable'); } try { return new DictValue(Func::mapping_to_couples($value)); } catch (UnhashableTypeException $e) { throw new TypeError(\sprintf( "Cannot create dict with key containing unhashable type '%s'", $e->getType() )); } } /** * Returns value stored under `key`, if it in dict, otherwise returns the * value of the `default` argument, which is `null` by default, but can * optionally be specified. * * ```js * d = {'a': 1, 100: 'yes'} * d.get('a') == 1 * d.get(100) == 'yes' * d.get('100') == null * d.get('100', ['one', 'hundred']) == ['one', 'hundred'] * ``` */ #[PrimiFunc] public static function get( DictValue $dict, AbstractValue $key, ?AbstractValue $default = \null ): AbstractValue { try { return $dict->value->get($key) ?? $default ?? Interned::null(); } catch (UnhashableTypeException $e) { throw new TypeError($e->getMessage()); } } /** * Returns `true` if the value exists in dict. Return `false` otherwise. * * ```js * d = {'a': 1, 100: 'yes'} * d.has_value(1) == true * d.has_value('yes') == true * d.has_value(100) == false * d.has_value(false) == false * ``` */ #[PrimiFunc] public static function has_value( DictValue $dict, AbstractValue $needle ): BoolValue { return Interned::bool($dict->value->findValue($needle) !== \null); } /** * Returns `true` if the key exists in dict. Return `false` otherwise. * * ```js * d = {'a': 1, 100: 'yes'} * d.has_key('a') == true * d.has_key(100) == true * d.has_key('100') == false * d.has_key('yes') == false * ``` */ #[PrimiFunc] public static function has_key( DictValue $dict, AbstractValue $key ): BoolValue { try { return Interned::bool($dict->doesContain($key)); } catch (UnhashableTypeException $e) { throw new TypeError($e->getMessage()); } } /** * Returns a new `list` of `tuples` of **key and value pairs** from this * `dict`. * * ```js * {'a': 1, 100: 'yes'}.items() == [('a', 1), (100: 'yes')] * ``` */ #[PrimiFunc] public static function items(DictValue $dict): ListValue { $list = []; foreach ($dict->value->getItemsIterator() as $arrayTuple) { $list[] = new TupleValue($arrayTuple); } return new ListValue($list); } /** * Returns a new `list` containing **values** from this `dict`. * * ```js * {'a': 1, 100: 'yes'}.values() == [1, 'yes'] * ``` */ #[PrimiFunc] public static function values(DictValue $dict): ListValue { return new ListValue( \iterator_to_array($dict->value->getValuesIterator()) ); } /** * Returns a new `list` containing **keys** from this `dict`. * * ```js * {'a': 1, 100: 'yes'}.values() == [1, 'yes'] * ``` */ #[PrimiFunc] public static function keys(DictValue $dict): ListValue { return new ListValue( \iterator_to_array($dict->value->getKeysIterator()) ); } /** * Returns a new shallow copy of this dict. * * ```js * a_dict = {'a': 1, 100: 'yes'} * b_dict = a_dict.copy() * b_dict[100] = 'nope' * * a_dict == {'a': 1, 100: 'yes'} * b_dict == {'a': 1, 100: 'nope'} * ``` */ #[PrimiFunc] public static function copy(DictValue $dict): DictValue { return clone $dict; } /** * Returns a new dict with same keys but values returned by a passed * function _(callback)_ applied to each item. * * Callback arguments: `callback(value, key)`. * * ```js * a_dict = {'key_a': 'val_a', 'key_b': 'val_b'} * fn = (v, k) => { return k + "|" + v; } * a_dict.map(fn) == {"key_a": "key_a|val_a", "key_b": "key_b|val_b"} * ``` */ #[PrimiFunc(toStack: \true, callConv: PrimiFunc::CONV_CALLARGS)] public static function map( CallArgs $args, Context $ctx ): DictValue { [$self, $callable] = $args->extractPositional(2); Func::allow_argument_types(1, $self, BuiltinTypes::getDictType()); $result = []; foreach ($self->value->getItemsIterator() as [$k, $v]) { $result[] = [ $k, $callable->invoke($ctx, new CallArgs([$v, $k])) ]; } return new DictValue($result); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/TypeExtensions/NullTypeExtension.php
src/Stdlib/TypeExtensions/NullTypeExtension.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\TypeExtensions; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Ex\TypeError; use \Smuuf\Primi\Values\TypeValue; use \Smuuf\Primi\Values\NullValue; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Extensions\TypeExtension; use \Smuuf\Primi\Stdlib\BuiltinTypes; class NullTypeExtension extends TypeExtension { #[PrimiFunc] public static function __new__(TypeValue $type): NullValue { if ($type !== BuiltinTypes::getNullType()) { throw new TypeError("Passed invalid type object"); } return Interned::null(); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/TypeExtensions/StringTypeExtension.php
src/Stdlib/TypeExtensions/StringTypeExtension.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\TypeExtensions; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Ex\RuntimeError; use \Smuuf\Primi\Ex\TypeError; use \Smuuf\Primi\Stdlib\BuiltinTypes; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Values\BoolValue; use \Smuuf\Primi\Values\DictValue; use \Smuuf\Primi\Values\ListValue; use \Smuuf\Primi\Values\RegexValue; use \Smuuf\Primi\Values\TypeValue; use \Smuuf\Primi\Values\StringValue; use \Smuuf\Primi\Values\NumberValue; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Extensions\TypeExtension; use \Smuuf\Primi\Structures\CallArgs; class StringTypeExtension extends TypeExtension { private const ATTR_DIGITS = '0123456789'; private const ATTR_LETTERS_LOWERCASE = 'abcdefghijklmnopqrstuvwxyz'; private const ATTR_LETTERS_UPPERCASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; private const ATTR_LETTERS_ALL = self::ATTR_LETTERS_LOWERCASE . self::ATTR_LETTERS_UPPERCASE; public static function execute(): array { $attrs = [ 'ascii_letters' => Interned::string(self::ATTR_LETTERS_LOWERCASE), 'ascii_lowercase' => Interned::string(self::ATTR_LETTERS_UPPERCASE), 'ascii_uppercase' => Interned::string(self::ATTR_LETTERS_ALL), 'digits' => Interned::string(self::ATTR_DIGITS), ]; return $attrs + parent::execute(); } #[PrimiFunc(callConv: PrimiFunc::CONV_NATIVE)] public static function __new__( TypeValue $type, ?AbstractValue $value = \null ): StringValue { if ($type !== BuiltinTypes::getStringType()) { throw new TypeError("Passed invalid type object"); } if ($value === \null) { return Interned::string(''); } return Interned::string($value->getStringValue()); } /** * Returns a new `string` from shuffled characters of the original `string`. * * ```js * "hello".shuffle() // "leohl" or something similar. * ``` */ #[PrimiFunc] public static function shuffle(StringValue $str): StringValue { // str_shuffle() doesn't work with unicode, so let's do this ourselves. $original = $str->value; $length = \mb_strlen($original); $indices = \range(0, $length - 1); \shuffle($indices); $result = ""; while (($i = \array_pop($indices)) !== \null) { $result .= \mb_substr($original, $i, 1); } return Interned::string($result); } /** * Returns a new `string` with placeholders from the original `string` * replaced by additional arguments. * * Placeholders can be either _(but these can't be combined)_: * - Non-positional: `{}` * - Positional: `{0}`, `{1}`, `{2}`, etc. * * ```js * "x{}x, y{}y".format(1, 2) == "x1x, y2y" * "x{1}x, y{0}y".format(111, 222) == "x222x, y111y" * ``` */ #[PrimiFunc] public static function format( StringValue $str, AbstractValue ...$items ): StringValue { // Extract PHP values from passed in value objects, because later we // will pass the values to sprintf(). $items = \array_map(function($item) { return $item->getStringValue(); }, $items); $passedCount = \count($items); $expectedCount = 0; $indexedMode = \null; // Convert {} syntax to a something sprintf() understands. // {} will be converted to "%s", positional {456} will be converted to // "%456$s". $prepared = \preg_replace_callback("#\{(\d+)?\}#", function($m) use ( $passedCount, &$indexedMode, &$expectedCount ) { if (isset($m[1])) { // A positional placeholder was used when a non-positional one // is already present. if ($indexedMode === \false) { throw new RuntimeError("Cannot combine positional and non-positional placeholders."); } $indexedMode = \true; $index = (int) $m[1]; if ($index < 0) { throw new RuntimeError("Position ($index) cannot be less than 0."); } if ($index > $passedCount) { throw new RuntimeError("Position ($index) does not match the number of parameters ($passedCount)."); } $plusOne = $index + 1; $converted = "%{$plusOne}\$s"; } else { if ($indexedMode === \true) { // A non-positional placeholder was used when a positional // one is already present. throw new RuntimeError( \sprintf("Cannot combine positional and non-positional placeholders.") ); } $indexedMode = \false; $converted = "%s"; } $expectedCount++; return $converted; }, $str->value); // If there are more args expected than passed, throw error. if ($expectedCount > $passedCount) { throw new RuntimeError( \sprintf( "Not enough arguments passed (expected %s, got %s).", $expectedCount, $passedCount ) ); } return Interned::string(\sprintf($prepared, ...$items)); } /** * Perform search and replace and return the results as new `string`. * * ```js * "abcdef".replace("c", "X") == "abXdef" * "přítmí ve městě za dvě stě".replace("stě", "šci") == "přítmí ve měšci za dvě šci" * "přítmí ve městě za dvě stě".replace(rx"\wt\w", "lol") == "přlolí ve mělol za dvě lol" * ``` * */ #[PrimiFunc] public static function replace( StringValue $string, AbstractValue $search, StringValue $replace ): StringValue { if ($search instanceof StringValue || $search instanceof NumberValue) { // Handle both string/number values the same way. return Interned::string( \str_replace( (string) $search->value, $replace->value, $string->value ) ); } elseif ($search instanceof RegexValue) { return Interned::string( \preg_replace( $search->value, $replace->value, $string->value ) ); } else { $type = $search->getTypeName(); throw new RuntimeError("Cannot use '$type' as needle"); } } /** * Search and replace strings within a string and return the new resulting * string. The from-to pairs are to be provided as a `dict`. * * ```js * "abcdef".replace({'c': 'X', 'e': 'Y'}) == "abXdYf" * "abcdef".replace({'b': 'X', 'ab': 'Y'}) == "Ycdef" * ``` * * The longest keys will be tried first. Once a substring has been replaced, * its new value will not be searched again. This behavior is identical * to PHP function [`strtr()`](https://www.php.net/manual/en/function.strtr.php). * */ #[PrimiFunc] public static function translate( StringValue $string, DictValue $pairs ): StringValue { $mapping = []; $c = 0; // Extract <from: to> pairs from the dict. foreach ($pairs->value->getItemsIterator() as [$key, $value]) { if (!$key instanceof StringValue) { $type = $key->getTypeName(); throw new RuntimeError("Replacement dict key must be a string, '$type' given."); } if (!$value instanceof StringValue) { $type = $value->getTypeName(); throw new RuntimeError("Replacement dict value must be a string, '$type' given."); } $mapping[$key->value] = $value->value; $c++; } return Interned::string(\strtr($string->value, $mapping)); } /** * Return reversed string. * * ```js * "hello! tady čaj".reverse() == "jač ydat !olleh" * ``` * */ #[PrimiFunc] public static function reverse(StringValue $string): StringValue { // strrev() does not support multibyte. // Let's do it ourselves then! $result = ''; $len = \mb_strlen($string->value); for ($i = $len; $i-- > 0;) { $result .= \mb_substr($string->value, $i, 1); } return Interned::string($result); } /** * Split original `string` by some `delimiter` and return result the as a * `list`. If the `delimiter` is not specified, the `string` is splat by * whitespace characters. * * ```js * "a b c\nd e f".split() == ['a', 'b', 'c', 'd', 'e', 'f'] * "a,b,c,d".split(',') == ['a', 'b', 'c', 'd'] * ``` */ #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function split( CallArgs $args ): ListValue { $args = $args->extract( ['self', 'delimiter', 'limit'], ['delimiter', 'limit'] ); // Split by whitespaces by default. $self = $args['self']; $delimiter = $args['delimiter'] ?? Interned::regex('\s+'); $limit = $args['limit'] ?? Interned::number('-1'); // Allow only some value types. Func::allow_argument_types(1, $self, StringValue::class); Func::allow_argument_types(2, $delimiter, StringValue::class, RegexValue::class); Func::allow_argument_types(3, $limit, NumberValue::class); if ($delimiter instanceof RegexValue) { $splat = \preg_split($delimiter->value, $self->value, (int) $limit->value); } if ($delimiter instanceof StringValue) { if ($delimiter->value === '') { throw new RuntimeError("String delimiter must not be empty."); } $splat = \explode($delimiter->value, $self->value, (int) $limit->value); } return new ListValue(\array_map(function($part) { return Interned::string($part); }, $splat ?? [])); } /** * Returns `true` if the `string` contains `needle`. Returns `false` * otherwise. * * ```js * "this is a sentence".contains("sen") == true * "this is a sentence".contains("yay") == false * ``` */ #[PrimiFunc] public static function contains( StringValue $haystack, AbstractValue $needle ): BoolValue { return Interned::bool($haystack->doesContain($needle)); } /** * Returns `number` of occurrences of `needle` in a string. * * ```js * "this is a sentence".number_of("s") == 3 * "this is a sentence".number_of("x") == 0 * ``` */ #[PrimiFunc] public static function number_of( StringValue $haystack, AbstractValue $needle ): NumberValue { // Allow only some value types. Func::allow_argument_types(1, $needle, StringValue::class); $count = (string) \mb_substr_count( (string) $haystack->value, (string) $needle->value ); return Interned::number($count); } /** * Returns the position _(index)_ of **first** occurrence of `needle` in * the `string`. If the `needle` was not found, `null` is returned. * * ```js * "this is a sentence".find_first("s") == 3 * "this is a sentence".find_first("t") == 0 * "this is a sentence".find_first("x") == null * ``` */ #[PrimiFunc] public static function find_first(StringValue $haystack, AbstractValue $needle): AbstractValue { // Allow only some value types. Func::allow_argument_types(1, $needle, StringValue::class, NumberValue::class); $pos = \mb_strpos($haystack->value, (string) $needle->value); if ($pos !== \false) { return Interned::number((string) $pos); } else { return Interned::null(); } } /** * Returns the position _(index)_ of **last** occurrence of `needle` in * the `string`. If the `needle` was not found, `null` is returned. * * ```js * "this is a sentence".find_first("s") == 3 * "this is a sentence".find_first("t") == 0 * "this is a sentence".find_first("x") == null * ``` */ #[PrimiFunc] public static function find_last( StringValue $haystack, AbstractValue $needle ): AbstractValue { // Allow only some value types. Func::allow_argument_types(1, $needle, StringValue::class, NumberValue::class); $pos = \mb_strrpos($haystack->value, (string) $needle->value); if ($pos !== \false) { return Interned::number((string) $pos); } else { return Interned::null(); } } /** * Join items from `iterable` with this `string` and return the result as * a new string. * * ```js * ','.join(['a', 'b', 3]) == "a,b,3" * ':::'.join({'a': 1, 'b': 2, 'c': '3'}) == "1:::2:::3" * '-PADDING-'.join("abc") == "a-PADDING-b-PADDING-c" // String is also iterable. * ``` */ #[PrimiFunc(toStack: \true)] public static function join( StringValue $string, AbstractValue $iterable ): StringValue { $iter = $iterable->getIterator(); if ($iter === \null) { $type = $iterable->getTypeName(); throw new RuntimeError("Cannot join unsupported type '$type'"); } $prepared = []; foreach ($iter as $item) { switch (\true) { case $item instanceof DictValue: $prepared[] = self::join($string, $item)->value; break; case $item instanceof ListValue: $prepared[] = self::join($string, $item)->value; break; default: $prepared[] = $item->getStringValue(); break; } } return Interned::string(\implode($string->value, $prepared)); } /** * Returns `true` if the string starts with specified string. * * ```js * "this is a sentence".starts_with("tence") == true * "this is a sentence".starts_with("e") == true * "this is a sentence".starts_with("x") == false * ``` */ #[PrimiFunc] public static function starts_with( StringValue $haystack, StringValue $needle ): BoolValue { return Interned::bool(\str_starts_with($haystack->value, $needle->value)); } /** * Returns `true` if the string ends with specified string suffix. * * ```js * "this is a sentence".ends_with("tence") == true * "this is a sentence".ends_with("e") == true * "this is a sentence".ends_with("x") == false * ``` */ #[PrimiFunc] public static function ends_with( StringValue $haystack, StringValue $needle ): BoolValue { return Interned::bool(\str_ends_with($haystack->value, $needle->value)); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/TypeExtensions/ForbiddenTypeExtension.php
src/Stdlib/TypeExtensions/ForbiddenTypeExtension.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\TypeExtensions; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Ex\RuntimeError; use \Smuuf\Primi\Values\TypeValue; use \Smuuf\Primi\Values\TupleValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Extensions\TypeExtension; class ForbiddenTypeExtension extends TypeExtension { #[PrimiFunc] public static function __new__( TypeValue $type, ?AbstractValue $value = \null ): TupleValue { throw new RuntimeError( "Object of type '{$type->getName()}' cannot be created directly"); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/TypeExtensions/RegexTypeExtension.php
src/Stdlib/TypeExtensions/RegexTypeExtension.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\TypeExtensions; use \Smuuf\Primi\Ex\TypeError; use \Smuuf\Primi\Stdlib\BuiltinTypes; use \Smuuf\Primi\Values\BoolValue; use \Smuuf\Primi\Values\DictValue; use \Smuuf\Primi\Values\TypeValue; use \Smuuf\Primi\Values\RegexValue; use \Smuuf\Primi\Values\StringValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Extensions\TypeExtension; class RegexTypeExtension extends TypeExtension { #[PrimiFunc] public static function __new__( TypeValue $type, ?AbstractValue $value = \null ): RegexValue { if ($type !== BuiltinTypes::getRegexType()) { throw new TypeError("Passed invalid type object"); } $value ??= Interned::string(''); if (!$value instanceof StringValue && !$value instanceof RegexValue) { throw new TypeError("Invalid argument passed to regex()"); } return Interned::regex($value->getStringValue()); } /** * Regular expression find. Returns the first occurence of matching string. * Otherwise returns `false`. * * ```js * rx"[xyz]+".find("abbcxxyzzdeef") == "xxyzz" * ``` */ #[PrimiFunc] public static function find( RegexValue $regex, StringValue $haystack ): StringValue|BoolValue { if (!\preg_match($regex->value, $haystack->value, $matches)) { return Interned::bool(\false); } return Interned::string($matches[0]); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/TypeExtensions/NumberTypeExtension.php
src/Stdlib/TypeExtensions/NumberTypeExtension.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\TypeExtensions; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Ex\RuntimeError; use \Smuuf\Primi\Ex\TypeError; use \Smuuf\Primi\Values\BoolValue; use \Smuuf\Primi\Values\TypeValue; use \Smuuf\Primi\Values\NumberValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Extensions\TypeExtension; use \Smuuf\Primi\Stdlib\BuiltinTypes; class NumberTypeExtension extends TypeExtension { #[PrimiFunc] public static function __new__( TypeValue $type, ?AbstractValue $value = \null ): NumberValue { if ($type !== BuiltinTypes::getNumberType()) { throw new TypeError("Passed invalid type object"); } // Default value for a new number is 0. if ($value === \null) { return Interned::number('0'); } if ($value instanceof BoolValue) { return Interned::number($value->isTruthy() ? '1' : '0'); } $number = Func::scientific_to_decimal($value->getStringValue()); if (!Func::is_decimal($number)) { throw new RuntimeError("Invalid number value '$number'"); } return Interned::number($number); } /** * Return `true` if first argument is divisible by the second argument. */ #[PrimiFunc] public static function is_divisible_by( NumberValue $a, NumberValue $b ): BoolValue { $truth = ((int) $a->value % (int) $b->value) === 0; return Interned::bool($truth); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/TypeExtensions/ObjectTypeExtension.php
src/Stdlib/TypeExtensions/ObjectTypeExtension.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\TypeExtensions; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\TypeError; use \Smuuf\Primi\Values\TypeValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Values\InstanceValue; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Extensions\TypeExtension; use \Smuuf\Primi\Structures\CallArgs; use Smuuf\Primi\Values\BuiltinTypeValue; class ObjectTypeExtension extends TypeExtension { #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function __new__( CallArgs $args, Context $ctx, ): AbstractValue { $posArgs = $args->getArgs(); $type = \array_shift($posArgs); if (!$type instanceof TypeValue) { throw new TypeError("First argument for object.__new__() must be a type"); } // Instantiated native types (non-userland) are represented as "real" // PHP objects (e.g. NumberValue, DictValue) and not PHP instances of // PHP class "InstanceValues". Therefore only userland types/classes // can be instantiated into PHP `InstanceValue` objects. Otherwise // things would get messy (for example `DictValue::__construct()` would // not get used in any way, etc.) if ($type instanceof BuiltinTypeValue) { throw new TypeError("First argument for object.__new__() must not be a builtin type"); } return new InstanceValue($type, $ctx); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/TypeExtensions/TupleTypeExtension.php
src/Stdlib/TypeExtensions/TupleTypeExtension.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\TypeExtensions; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Ex\TypeError; use \Smuuf\Primi\Values\TypeValue; use \Smuuf\Primi\Values\TupleValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Stdlib\BuiltinTypes; use \Smuuf\Primi\Extensions\TypeExtension; class TupleTypeExtension extends TypeExtension { #[PrimiFunc] public static function __new__( TypeValue $type, ?AbstractValue $value = \null ): TupleValue { if ($type !== BuiltinTypes::getTupleType()) { throw new TypeError("Passed invalid type object"); } // Default value for a new number is 0. if ($value === \null) { return new TupleValue; } $iter = $value->getIterator(); if ($iter === \null) { throw new TypeError('tuple() argument must be iterable'); } return new TupleValue(\iterator_to_array($iter)); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/TypeExtensions/BoolTypeExtension.php
src/Stdlib/TypeExtensions/BoolTypeExtension.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\TypeExtensions; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Ex\TypeError; use \Smuuf\Primi\Values\TypeValue; use \Smuuf\Primi\Values\BoolValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Extensions\TypeExtension; use \Smuuf\Primi\Stdlib\BuiltinTypes; class BoolTypeExtension extends TypeExtension { #[PrimiFunc] public static function __new__( TypeValue $type, ?AbstractValue $value = \null ): BoolValue { if ($type !== BuiltinTypes::getBoolType()) { throw new TypeError("Passed invalid type object"); } return $value === \null ? Interned::bool(\false) : Interned::bool($value->isTruthy()); } /** * Returns a negation (logical `NOT`) of a single boolean value. * * ```js * false.not() == true * true.not() == false * bool.not(false) == true * bool.not(true) == false * ``` */ #[PrimiFunc] public static function not(BoolValue $value): BoolValue { return Interned::bool(!$value->value); } /** * Returns result of logical `AND` between two boolean values. * * ```js * true.and(false) == false * true.and(true) == true * bool_and(true, false) == false * ``` */ #[PrimiFunc] public static function and(BoolValue $a, BoolValue $b): BoolValue { return Interned::bool($a->value && $b->value); } /** * Returns an `OR` of two boolean values. * * ```js * true.or(true) == true * true.or(false) == true * false.or(true) == true * false.or(false) == false * * bool_or(true, true) == true * bool_or(true, false) == true * bool_or(false, true) == true * bool_or(false, false) == false * ``` */ #[PrimiFunc] public static function or(BoolValue $a, BoolValue $b): BoolValue { return Interned::bool($a->value || $b->value); } /** * Returns an exclusive `OR` (`XOR`) of two boolean values. * * ```js * true.xor(true) == false * true.xor(false) == true * false.xor(true) == true * false.xor(false) == false * * bool_xor(true, true) == false * bool_xor(true, false) == true * bool_xor(false, true) == true * bool_xor(false, false) == false * ``` */ #[PrimiFunc] public static function xor(BoolValue $a, BoolValue $b): BoolValue { return Interned::bool($a->value xor $b->value); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/TypeExtensions/TypeTypeExtension.php
src/Stdlib/TypeExtensions/TypeTypeExtension.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\TypeExtensions; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Values\TypeValue; use \Smuuf\Primi\Values\DictValue; use \Smuuf\Primi\Values\StringValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Extensions\TypeExtension; /** * This extension defines methods on the "type" type object - how the instance * of the type "type" behaves. */ class TypeTypeExtension extends TypeExtension { #[PrimiFunc] public static function __call__( AbstractValue $value, ?TypeValue $parentType = \null, ?DictValue $attrs = \null ): TypeValue { // If more than one argument was provided, let's create a new type! if ($parentType === \null) { return $value->getType(); } $attrs = $attrs ? Func::couples_to_variables_array( Func::mapping_to_couples($attrs), 'Attribute name' ) : []; Func::allow_argument_types(1, $value, StringValue::class); return new TypeValue( $value->getStringValue(), $parentType, $attrs, isFinal: \false, ); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/TypeExtensions/ListTypeExtension.php
src/Stdlib/TypeExtensions/ListTypeExtension.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\TypeExtensions; use \Smuuf\Primi\Context; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Ex\IndexError; use \Smuuf\Primi\Ex\TypeError; use \Smuuf\Primi\Values\ListValue; use \Smuuf\Primi\Values\NullValue; use \Smuuf\Primi\Values\BoolValue; use \Smuuf\Primi\Values\NumberValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Extensions\TypeExtension; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\Indices; use \Smuuf\Primi\Stdlib\BuiltinTypes; use \Smuuf\Primi\Structures\CallArgs; use \Smuuf\Primi\Values\TypeValue; class ListTypeExtension extends TypeExtension { #[PrimiFunc] public static function __new__( TypeValue $type, ?AbstractValue $value = \null ): ListValue { if ($type !== BuiltinTypes::getListType()) { throw new TypeError("Passed invalid type object"); } // No argument - create empty list. if ($value === \null) { return new ListValue([]); } $iter = $value->getIterator(); if ($iter === \null) { throw new TypeError('list() argument must be iterable'); } return new ListValue(\iterator_to_array($iter)); } /** * Returns a new copy of the `list`. */ #[PrimiFunc] public static function copy(ListValue $list): ListValue { return clone $list; } /** * Returns a new `list` with values of the original `list` reversed. * * ```js * [1, 2, 3].reverse() == [3, 2, 1] * ``` */ #[PrimiFunc] public static function reverse(ListValue $list): ListValue { return new ListValue(\array_reverse($list->value)); } /** * Returns a random item from the `list`. * * ```js * [1, 2, 3].random() // Either 1, 2, or 3. * ``` */ #[PrimiFunc] public static function random(ListValue $list): AbstractValue { return $list->value[\array_rand($list->value)]; } /** * Returns number of occurrences of some value in the `list`. * * ```js * [1, 2, 3, 1].count(1) == 2 * [1, 2, 3, 1].count(2) == 1 * [1, 2, 3, 1].count(666) == 0 * * // NOTE: Lists with same items with different order are different. * [[1, 2], [2, 1]].count([1, 2]) == 1 * * // NOTE: Dicts with same items with different order are the same. * [{'a': 1, 'b': 2}, {'b': 2, 'a': 1}].count({'a': 1, 'b': 2}) == 2 * ``` */ #[PrimiFunc] public static function count( ListValue $list, AbstractValue $needle ): NumberValue { $counter = 0; foreach ($list->value as $item) { if ($item->isEqualTo($needle)) { $counter++; } } return Interned::number((string) $counter); } /** * Returns a new `list` with shuffled items. * * ```js * [1, 2].shuffle() // Either [1, 2] or [2, 1] * ``` */ #[PrimiFunc] public static function shuffle(ListValue $list): ListValue { // Do NOT modify the original array (as PHP would do). $copy = clone $list; \shuffle($copy->value); return $copy; } /** * Returns a new `list` from results of a passed function _(callback)_ * applied to each item. * * Callback arguments: `callback(value)`. * * ```js * [-1, 0, 2].map(to_bool) == [true, false, true] * ``` */ #[PrimiFunc(toStack: \true, callConv: PrimiFunc::CONV_CALLARGS)] public static function map( CallArgs $args, Context $ctx ): ListValue { [$self, $callable] = $args->extractPositional(2); Func::allow_argument_types(1, $self, BuiltinTypes::getListType()); $result = []; foreach ($self->value as $k => $v) { $result[$k] = $callable->invoke($ctx, new CallArgs([$v])); } return new ListValue($result); } /** * Returns `true` if the `needle` is present in the `list` at least once. * * ```js * [1, 2, 3, 1].contains(1) == true * [1, 2, 3, 1].contains(666) == false * * // NOTE: Lists with same items with different order are different. * [[1, 2], 'xxx'].contains([1, 2]) == true * [[1, 2], 'xxx'].contains([2, 1]) == false * * // NOTE: Dicts with same items with different order are the same. * [{'b': 2, 'a': 1}, 'xxx'].contains({'a': 1, 'b': 2}) == true * ``` */ #[PrimiFunc] public static function contains( ListValue $list, AbstractValue $needle ): BoolValue { return Interned::bool($list->doesContain($needle)); } /** * Returns an item from `list` by its index _(starting at 0)_. Negative * indexes can be used to get items from the end. * * A default is returned in case the index is not found. This default * value can be optionally specified via the `default` parameter _(`null` * by default)_ * * ```js * ['a', 'b', 'c'].get(0) == 'a' * ['a', 'b', 'c'].get(1) == 'b' * ['a', 'b', 'c'].get(2) == 'c' * ['a', 'b', 'c'].get(3) == null * ['a', 'b', 'c'].get(3, 'NOT FOUND') == 'NOT FOUND' * * // Using negative index. * ['a', 'b', 'c'].get(-1) == 'c' * ['a', 'b', 'c'].get(-2) == 'b' * ['a', 'b', 'c'].get(-3) == 'a' * ['a', 'b', 'c'].get(-4) == null * ['a', 'b', 'c'].get(-4, 'NOT FOUND') == 'NOT FOUND' * ``` */ #[PrimiFunc] public static function get( ListValue $list, NumberValue $index, AbstractValue $default = \null ): AbstractValue { // If the index is not found, this will return null. $actualIndex = Indices::resolveNegativeIndex( (int) $index->value, \count($list->value) - 1 ); if ($actualIndex === \null) { return $default ?? Interned::null(); } return $list->value[$actualIndex]; } /** * Add (push) an item to the end of the `list`. * * ```js * a_list = ['a', 'b', 'c'] * a_list.push({'some_key': 'some_value'}) * a_list == ['a', 'b', 'c', {'some_key': 'some_value'}] * ``` */ #[PrimiFunc] public static function push( ListValue $list, AbstractValue $value ): NullValue { $list->value[] = $value; return Interned::null(); } /** * Prepend an item to the beginning of the `list`. * * ```js * a_list = ['a', 'b', 'c'] * a_list.prepend({'some_key': 'some_value'}) * a_list == [{'some_key': 'some_value'}, 'a', 'b', 'c'] * ``` */ #[PrimiFunc] public static function prepend( ListValue $list, AbstractValue $value ): NullValue { // array_unshift() will reindex internal array, which is what we want. \array_unshift($list->value, $value); return Interned::null(); } /** * Remove (pop) item at specified `index` from the `list` and return it. * * If the `index` is not specified, last item in the `list` will be * removed. Negative index can be used. * * ```js * a_list = [1, 2, 3, 4, 5] * * a_list.pop() == 5 // a_list == [1, 2, 3, 4], 5 is returned * a_list.pop(1) == 2 // a_list == [1, 3, 4], 2 is returned. * a_list.pop(-3) == 1 // a_list == [3, 4], 1 is returned * ``` */ #[PrimiFunc] public static function pop( ListValue $list, ?NumberValue $index = \null ): AbstractValue { if ($index === \null) { if (!$list->value) { throw new IndexError(-1); } // If index was not specified, pop and return the last item. return \array_pop($list->value); } else { // If the index is not found, this will throw IndexError. $actualIndex = Indices::resolveIndexOrError( (int) $index->value, $list->value ); $popped = $list->value[$actualIndex]; // Take the part of the array before the item we've just popped // and after it - and merge it using the spread operator, which // will reindex the array, which we probably want. $list->value = [ ...\array_slice($list->value, 0, $actualIndex), ...\array_slice($list->value, $actualIndex + 1) ]; return $popped; } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/TypeExtensions/Stdlib/DatetimeTypeExtension.php
src/Stdlib/TypeExtensions/Stdlib/DatetimeTypeExtension.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\TypeExtensions\Stdlib; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\RuntimeError; use \Smuuf\Primi\Values\StringValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Values\InstanceValue; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Extensions\TypeExtension; use \Smuuf\Primi\Structures\CallArgs; class DatetimeTypeExtension extends TypeExtension { private const FMT_SQL = 'Y-m-d H:i:sP'; /** @const string Timestamp attr name. */ private const ATTR_TS = '_ts'; #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function __init__( CallArgs $args ): void { [$self, $dateString] = $args->extractPositional(2, 1); if ($dateString) { Func::allow_argument_types(2, $dateString, StringValue::class); $str = $dateString->getStringValue(); } else { $str = 'now'; } $timestamp = \strtotime($str); if ($timestamp === \false) { throw new RuntimeError("Unable to parse date from string '$str'"); } $self->attrSet(self::ATTR_TS, Interned::number((string) $timestamp)); } #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function __repr__( CallArgs $args ): AbstractValue { [$self] = $args->extractPositional(1); $ts = (int) $self->attrGet(self::ATTR_TS)->getCoreValue(); $formatted = \date(self::FMT_SQL, $ts); $repr = "Datetime('$formatted')"; return Interned::string($repr); } #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function __op_sub__( CallArgs $args, Context $ctx ): AbstractValue { [$self, $other] = $args->extractPositional(2); $durationType = $ctx->getImporter() ->getModule('std.datetime') ->attrGet('Duration'); $selfType = $self->getType(); Func::allow_argument_types(2, $other, $selfType, $durationType); // Subtracting Datetime (other) from Datetime (self). if ($selfType === $other->getType()) { $duration = $self->attrGet(self::ATTR_TS) ->doSubtraction($other->attrGet(self::ATTR_TS)); // By invoking the class we're gonna create a new instance. return $durationType->invoke($ctx, new CallArgs([$duration])); } // Subtracting Duration (other) from Datetime (self). $newTimestamp = $self->attrGet(self::ATTR_TS) ->doSubtraction($other->attrGet('total_seconds')); $newDatetime = new InstanceValue($selfType, $ctx); $newDatetime->attrSet(self::ATTR_TS, $newTimestamp); return $newDatetime; } #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function __op_add__( CallArgs $args, Context $ctx ): AbstractValue { [$self, $other] = $args->extractPositional(2); $durationType = $ctx->getImporter() ->getModule('std.datetime') ->attrGet('Duration'); Func::allow_argument_types(2, $other, $durationType); // Subtracting Duration (other) from Datetime (self). $newTimestamp = $self->attrGet(self::ATTR_TS) ->doAddition($other->attrGet('total_seconds')); $newDatetime = new InstanceValue($self->getType(), $ctx); $newDatetime->attrSet(self::ATTR_TS, $newTimestamp); return $newDatetime; } #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function __op_eq__( CallArgs $args ): AbstractValue { [$self, $other] = $args->extractPositional(2); if ($other->getType() !== $self->getType()) { return Interned::constNotImplemented(); } $equal = $self->attrGet(self::ATTR_TS) ->isEqualTo($other->attrGet(self::ATTR_TS)); return Interned::bool($equal); } #[PrimiFunc] public static function format( AbstractValue $self, StringValue $format ): AbstractValue { $timestamp = (int) $self->attrGet(self::ATTR_TS)->getStringValue(); return Interned::string(\date($format->getStringValue(), $timestamp)); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Stdlib/TypeExtensions/Stdlib/DurationTypeExtension.php
src/Stdlib/TypeExtensions/Stdlib/DurationTypeExtension.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Stdlib\TypeExtensions\Stdlib; use \Smuuf\Primi\Context; use \Smuuf\Primi\Extensions\PrimiFunc; use \Smuuf\Primi\Values\NumberValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Values\InstanceValue; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Extensions\TypeExtension; use \Smuuf\Primi\Structures\CallArgs; class DurationTypeExtension extends TypeExtension { /** @const string Total seconds attr name. */ private const ATTR_TOTSEC = 'total_seconds'; #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function __init__( CallArgs $args ): void { [$self, $totalSec] = $args->extractPositional(2); Func::allow_argument_types(2, $totalSec, NumberValue::class); $self->attrSet(self::ATTR_TOTSEC, $totalSec); $totalSecInt = $totalSec->getCoreValue(); $self->attrSet( 'days', Interned::number((string) floor((int) $totalSecInt / 86400)) ); $self->attrSet( 'seconds', Interned::number((string) ((int) $totalSecInt % 86400)) ); } #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function __op_eq__( CallArgs $args ): AbstractValue { [$self, $other] = $args->extractPositional(2); if ($other->getType() !== $self->getType()) { return Interned::constNotImplemented(); } $equal = $self->attrGet(self::ATTR_TOTSEC) ->isEqualTo($other->attrGet(self::ATTR_TOTSEC)); return Interned::bool($equal); } #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function __op_add__( CallArgs $args, Context $ctx ): AbstractValue { [$self, $other] = $args->extractPositional(2); if ($other->getType() !== $self->getType()) { return Interned::constNotImplemented(); } $totalSeconds = $self->attrGet(self::ATTR_TOTSEC) ->doAddition($other->attrGet(self::ATTR_TOTSEC)); $new = new InstanceValue($self->getType(), $ctx); $new->attrSet(self::ATTR_TOTSEC, $totalSeconds); return $new; } #[PrimiFunc(callConv: PrimiFunc::CONV_CALLARGS)] public static function __op_sub__( CallArgs $args, Context $ctx ): AbstractValue { [$self, $other] = $args->extractPositional(2); if ($other->getType() !== $self->getType()) { return Interned::constNotImplemented(); } $totalSeconds = $self->attrGet(self::ATTR_TOTSEC) ->doSubtraction($other->attrGet(self::ATTR_TOTSEC)); $new = new InstanceValue($self->getType(), $ctx); $new->attrSet(self::ATTR_TOTSEC, $totalSeconds); return $new; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Structures/AssignmentTargets.php
src/Structures/AssignmentTargets.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Structures; use \Smuuf\StrictObject; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\EngineError; use \Smuuf\Primi\Ex\RuntimeError; use \Smuuf\Primi\Values\AbstractValue; /** * @internal */ class AssignmentTargets { use StrictObject; /** @var string[] List of target variable names. */ private array $targets; /** * If true, there is only a single target and assigned value does not need * unpacking. */ private ?string $singleTarget; /** Total number of targets. */ private int $targetsCount; /** * @param array<int, string> $targets */ public function __construct(array $targets = []) { if (!\array_is_list($targets)) { throw new EngineError( "Assignment targets must be specified as a list array"); } $this->targets = $targets; $this->targetsCount = \count($targets); $this->singleTarget = $this->targetsCount === 1 ? $targets[0] : \null; } /** * @param AbstractValue $value * @return void */ public function assign(AbstractValue $value, Context $ctx) { if ($this->singleTarget !== \null) { $ctx->setVariable($this->singleTarget, $value); return; } $iter = $value->getIterator(); if ($iter === \null) { throw new RuntimeError("Cannot unpack non-iterable"); } $buffer = []; $targetIndex = 0; foreach ($iter as $value) { if (\array_key_exists($targetIndex, $this->targets)) { $buffer[$this->targets[$targetIndex]] = $value; } else { throw new RuntimeError( "Too many values to unpack (expected {$this->targetsCount})"); } $targetIndex++; } if ($targetIndex < $this->targetsCount) { throw new RuntimeError("Not enough values to unpack (expected {$this->targetsCount} but got {$targetIndex})"); } $ctx->setVariables($buffer); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Structures/FnContainer.php
src/Structures/FnContainer.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Structures; use \Smuuf\StrictObject; use \Smuuf\Primi\Scope; use \Smuuf\Primi\Context; use \Smuuf\Primi\Location; use \Smuuf\Primi\StackFrame; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Values\ModuleValue; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Helpers\CallConventions\PhpCallConvention; use \Smuuf\Primi\Helpers\CallConventions\CallArgsCallConvention; use \Smuuf\Primi\Handlers\HandlerFactory; /** * @internal */ class FnContainer { public const FLAG_TO_STACK = 1; public const FLAG_CALLCONV_CALLARGS = 2; use StrictObject; /** Closure wrapping the function itself. */ private \Closure $closure; /** Function name. */ private string $name; /** * True if the function represents a native PHP function instead of Primi * function. */ private bool $isPhpFunction = \false; /** * Build and return a closure wrapper around a Primi function (represented * by its node tree). * * The closure returns some Primi value object as a result. * * @param TypeDef_AstNode $entryNode * @param ?array{names: array<string, string>, defaults: array<string, TypeDef_AstNode>} $defParams * @return self */ public static function build( array $entryNode, string $definitionName, ModuleValue $definitionModule, ?array $defParams = \null, ?Scope $defScope = \null ) { // Invoking this closure is equal to standard execution of the nodes // that make up the body of the function. $closure = function( Context $ctx, ?CallArgs $args = \null, ?Location $callsite = \null ) use ( $entryNode, $defScope, $defParams, $definitionModule, $definitionName ) { $scope = new Scope([], parent: $defScope); $frame = new StackFrame( $definitionName, $definitionModule, $callsite ); try { // Push call first for more precise traceback for errors when // resolving arguments (expected args may be missing, for // example) below. // For performance reasons (function calls are frequent) push // and pop stack frame and scope manually, without the overhead // of using ContextPushPopWrapper. $ctx->pushCallScopePair($frame, $scope); if ($defParams) { $callArgs = $args ?? CallArgs::getEmpty(); $scope->setVariables( Func::resolve_default_args( $callArgs->extract( $defParams['names'], \array_keys($defParams['defaults']) ), $defParams['defaults'], $ctx ) ); } HandlerFactory::runNode($entryNode, $ctx); // This is the return value of the function call. if ($ctx->hasRetval()) { return $ctx->popRetval()->getValue(); } // Return null if no "return" was present in the called // function. return Interned::null(); } finally { $ctx->popCallScopePair(); } }; return new self($closure, \false, $definitionName); } /** * @param array<int> $flags * @return self */ public static function buildFromClosure(callable $fn, array $flags = []) { $closure = \Closure::fromCallable($fn); $rf = new \ReflectionFunction($closure); $callName = $rf->getName(); $flagToStack = \in_array(self::FLAG_TO_STACK, $flags, \true); $flagCallConventionArgsObject = \in_array(self::FLAG_CALLCONV_CALLARGS, $flags, \true); $callConvention = $flagCallConventionArgsObject ? new CallArgsCallConvention($closure) : new PhpCallConvention($closure, $rf); $wrapper = function( Context $ctx, ?CallArgs $args, ?Location $callsite = \null ) use ( $callConvention, $callName, $flagToStack ) { // Add this function call to the call stack. This is done manually // without ContextPushPopWrapper for performance reasons. if ($flagToStack) { $frame = new StackFrame( $callName, $ctx->getCurrentModule(), $callsite ); $ctx->pushCall($frame); } try { $result = $callConvention->call( $args ?? CallArgs::getEmpty(), $ctx ); } finally { // Remove the latest entry from call stack. // This is done manually without ContextPushPopWrapper for // performance reasons. if ($flagToStack) { $ctx->popCall(); } } return $result; }; return new self($wrapper, \true, $callName); } /** * Disallow direct instantiation. Always use the static factories above. */ private function __construct( \Closure $closure, bool $isPhpFunction, string $name ) { $this->closure = $closure; $this->isPhpFunction = $isPhpFunction; $this->name = $name; } public function callClosure( Context $ctx, ?CallArgs $args = \null, ?Location $callsite = \null ): ?AbstractValue { return ($this->closure)($ctx, $args, $callsite); } public function isPhpFunction(): bool { return $this->isPhpFunction; } public function getName(): string { return $this->name; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Structures/ItemInsertionProxy.php
src/Structures/ItemInsertionProxy.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Structures; use \Smuuf\Primi\Ex\TypeError; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\StrictObject; /** * @internal * @see InsertionProxyInterface */ class ItemInsertionProxy implements InsertionProxyInterface { use StrictObject; protected AbstractValue $target; protected ?AbstractValue $key; public function __construct( ?AbstractValue $key, AbstractValue $target ) { $this->target = $target; $this->key = $key; } public function commit(AbstractValue $value): void { $success = $this->target->itemSet($this->key, $value); if ($success === \false) { throw new TypeError(sprintf( "Type '%s' does not support item assignment", ($this->target)->getTypeName() )); } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Structures/AttrInsertionProxy.php
src/Structures/AttrInsertionProxy.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Structures; use \Smuuf\Primi\Ex\TypeError; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\StrictObject; /** * @internal * @see InsertionProxyInterface */ class AttrInsertionProxy implements InsertionProxyInterface { use StrictObject; protected string $key; protected AbstractValue $target; public function __construct( string $key, AbstractValue $target ) { $this->target = $target; $this->key = $key; } public function commit(AbstractValue $value): void { $success = $this->target->attrSet($this->key, $value); if ($success === \false) { throw new TypeError(sprintf( "Object of type '%s' does not support attribute assignment", $this->target->getTypeName() )); } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Structures/MapContainer.php
src/Structures/MapContainer.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Structures; use \Smuuf\Primi\Ex\UnhashableTypeException; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\StrictObject; /** * Map container structure supporting Primi value objects as keys. * * Slightly simpler and faster than php-ds or its polyfill, which both seem * slower than this. (Or I made a mistake when measuring its performance.) * * Also these map containers can be compared with ordinary == operator (at least * it seems so - until someone finds a problem with it). * * @internal */ class MapContainer implements \Countable { use StrictObject; /** @var AbstractValue[] Storage for dict values. */ private $values = []; /** @var AbstractValue[] Storage for key values. */ private $keys = []; /** * Create new instance from iterable list containing `[key, value]` Primi * value tuples. * * @param TypeDef_PrimiObjectCouples $couples * @return self * @internal */ public static function fromCouples(iterable $couples) { return new self($couples); } /** * @param TypeDef_PrimiObjectCouples $couples */ private function __construct(iterable $couples = []) { $this->setAll($couples); } /** * Returns a scalar key based on hash provided by the `key` value. * This scalar key can be then used as key for internal ordinary PHP array. * * @throws UnhashableTypeException */ private static function buildScalarKey(AbstractValue $key): string { return "{$key->getTypeName()}.{$key->hash()}"; } /** * @param TypeDef_PrimiObjectCouples $couples */ public function setAll(iterable $couples): void { foreach ($couples as [$key, $value]) { $scalarKey = self::buildScalarKey($key); $this->values[$scalarKey] = $value; $this->keys[$scalarKey] = $key; } } /** * Sets a `key: value` pair to the map. * * @throws UnhashableTypeException */ public function set(AbstractValue $key, AbstractValue $value): void { $scalarKey = self::buildScalarKey($key); $this->values[$scalarKey] = $value; $this->keys[$scalarKey] = $key; } /** * Return `true` if this key is present in the map. Return `false` * otherwise. * * @throws UnhashableTypeException */ public function hasKey(AbstractValue $key): bool { return \array_key_exists(self::buildScalarKey($key), $this->values); } /** * Returns the first `key` value found under which this `value` is stored, * or `null` if not found at all. */ public function findValue(AbstractValue $value): ?AbstractValue { // Non-strict on purpose, so that different value instances having // the same internal value are considered to be equal. $scalarKey = \array_search($value, $this->values); if ($scalarKey === \false) { return \null; } return $this->keys[$scalarKey]; } /** * Removes `key: value` pair from the map, based on the `key`. * * @throws UnhashableTypeException */ public function remove(AbstractValue $key): void { $scalarKey = self::buildScalarKey($key); unset($this->values[$scalarKey]); unset($this->keys[$scalarKey]); } public function get(AbstractValue $key): ?AbstractValue { return $this->values[self::buildScalarKey($key)] ?? \null; } /** * Return number of items in the map. */ public function count(): int { return \count($this->values); } /** * Returns a generator yielding keys and items from this container (as * expected). * * @return \Generator<int, TypeDef_PrimiObjectCouple, null, void> */ public function getItemsIterator(): \Generator { foreach ($this->values as $scalarKey => $value) { yield [$this->keys[$scalarKey], $value]; } } /** * Returns a generator yielding keys and items from this container (as * expected). * * @return \Generator<int, AbstractValue, null, void> */ public function getKeysIterator(): \Generator { yield from $this->keys; } /** * Returns a generator yielding values from this container. * @return \Generator<int, AbstractValue, null, void> */ public function getValuesIterator(): \Generator { yield from $this->values; } /** * Returns a generator yielding keys and items from this container in * reversed order. * * @return \Generator<int, TypeDef_PrimiObjectCouple, null, void> */ public function getReverseIterator(): \Generator { $reversed = \array_reverse($this->values, \true); foreach ($reversed as $scalarKey => $value) { yield [$this->keys[$scalarKey], $value]; } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Structures/CallRetval.php
src/Structures/CallRetval.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Structures; use \Smuuf\StrictObject; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Helpers\Interned; /** * @internal */ class CallRetval { use StrictObject; private AbstractValue $value; public function __construct(?AbstractValue $value = \null) { $this->value = $value ?? Interned::null(); } public function getValue(): AbstractValue { return $this->value; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Structures/CallArgs.php
src/Structures/CallArgs.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Structures; use \Smuuf\StrictObject; use \Smuuf\Primi\Ex\TypeError; use \Smuuf\Primi\Ex\EngineError; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Values\DictValue; use \Smuuf\Primi\Values\TupleValue; use \Smuuf\Primi\Values\AbstractValue; /** * Container for passing arguments - positional and keyword arguments - to the * function-invoking mechanism. * * NOTE: Instances of this class are meant to be immutable, so self::getEmpty() * singleton factory really can always return the same instance of empty * CallArgs object. * * NOTE: Only docblock type-hinting for performance reasons. * * @internal */ class CallArgs { use StrictObject; private static self $emptySingleton; /** @var AbstractValue[] Positional arguments. */ private $args = []; /** @var array<string, AbstractValue> Keyword argument. */ private $kwargs = []; /** True if there are no args and no kwargs specified. */ private bool $isEmpty = \false; /** Total number of args and kwargs combined. */ private ?int $totalCount = \null; /** * @param array<int, AbstractValue> $args * @param array<string, AbstractValue> $kwargs */ public function __construct(array $args = [], array $kwargs = []) { if (!\array_is_list($args)) { throw new EngineError( "Positional arguments must be specified as a list array"); } $this->args = $args; $this->kwargs = $kwargs; } public static function initEmpty(): void { self::$emptySingleton = new self; } public static function getEmpty(): self { return self::$emptySingleton; } /** * Returns true if there are no args and no kwargs specified. Return false * otherwise. */ public function isEmpty(): bool { return $this->isEmpty ?? ($this->isEmpty = !($this->args || $this->kwargs)); } public function getTotalCount(): int { return $this->totalCount ?? ($this->totalCount = \count($this->args) + \count($this->kwargs)); } /** * @return AbstractValue[] */ public function getArgs() { return $this->args; } /** * @return array<string, AbstractValue> */ public function getKwargs() { return $this->kwargs; } /** * @param int $count Number of expected arguments. * @param int $optional Number of optional arguments (at the end). * @return array<int, AbstractValue|null> */ public function extractPositional($count, $optional = 0) { if ($this->kwargs) { $first = \array_key_first($this->kwargs); throw new TypeError("Unexpected keyword argument '$first'"); } $argCount = \count($this->args); if ($argCount > $count) { throw new TypeError("Expected maximum of $count arguments"); } $mandatoryCount = $count - $optional; if ($argCount < $mandatoryCount) { throw new TypeError("Expected at least $mandatoryCount arguments"); } // Return exactly expected number of arguments. Any non-specified // optional arguments will be returned as null. return \array_pad($this->args, $count, \null); } /** * NOTE: Only docblock type-hinting for performance reasons. * * @param array<string> $names * @param array<string> $optional * @return array<string, AbstractValue|null> */ public function extract($names, $optional = []) { // Find names for variadic *args and **kwargs parameters. $varArgsName = \false; $varKwargsName = \false; $varArgs = []; $varKwargs = []; $final = []; $i = 0; foreach ($this->args as $value) { $name = $names[$i] ?? \null; if ($name === \null) { throw new TypeError("Too many positional arguments"); } if ($name[0] === '*') { // If we encountered variadic kwarg parameter during assigning // positional arguments, it is obvious the caller sent us // too many positional arguments. if ($name[1] === '*') { throw new TypeError("Too many positional arguments"); } if (!$varArgsName) { $varArgsName = \substr($name, 1); } $varArgs[] = $value; } else { $final[$name] = $value; $i++; } } // Go through the rest of names to find any potentially specified // *args and **kwargs parameters. while ($name = $names[$i++] ?? \null) { if ($name[0] === '*') { if ($name[1] === '*' && !$varKwargsName) { $varKwargsName = \substr($name, 2); } elseif (!$varArgsName) { $varArgsName = \substr($name, 1); } } } if ($varArgsName) { $final[$varArgsName] = new TupleValue($varArgs); } // Now let's process keyword arguments. foreach ($this->kwargs as $key => $value) { // If this kwarg key is not at all present in known definition // args, we don't expect this kwarg, so we throw an error. if (\in_array($key, $names, \true)) { // If this kwarg overwrites already specified final arg // (unspecified are false, so isset() works here), throw an // error. if (!empty($final[$key])) { throw new TypeError("Argument '$key' passed multiple times"); } $final[$key] = $value; } elseif ($varKwargsName) { // If there was an unexpected kwarg, but there is a kwarg // collector defined, add this unexpected kwarg to it. $varKwargs[$key] = $value; } else { throw new TypeError("Unexpected keyword argument '$key'"); } } if ($varKwargsName) { $final[$varKwargsName] = new DictValue(Func::array_to_couples($varKwargs)); } // If there are any "null" values left in the final args dict, // some arguments were left out and that is an error. foreach ($names as $name) { if ( $name[0] !== '*' && !\array_key_exists($name, $final) && !\in_array($name, $optional, \true) ) { throw new TypeError("Missing required argument '$name'"); } } return $final; } /** * Return new `CallArgs` object with original args and kwargs being * added (positional args) or overwritten (keyword args) by the args * from the "extra" `CallArgs` object passed as the argument. */ public function withExtra(CallArgs $extra): self { return new self( [...$this->args, ...$extra->getArgs()], \array_merge($this->kwargs, $extra->getKwargs()) ); } } CallArgs::initEmpty();
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Structures/InsertionProxyInterface.php
src/Structures/InsertionProxyInterface.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Structures; use \Smuuf\Primi\Values\AbstractValue; /** * Insertion proxy is a special structure that encapsulates a value object which * supports insertion. This proxy is used in situations when we already know * the KEY under which we want to store something into encapsulated value, but * at the same time we don't yet know what VALUE will be stored. * At that point an insertion proxy is created with KEY being set and * VALUE can be "commited" later. * * @internal * @see \Smuuf\Primi\Handlers\Kinds\VectorAttr * @see \Smuuf\Primi\Handlers\Kinds\VectorItem * @see \Smuuf\Primi\Handlers\Kinds\Assignment */ interface InsertionProxyInterface { public function commit(AbstractValue $value): void; }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Code/SourceFile.php
src/Code/SourceFile.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Code; use \Smuuf\StrictObject; use \Smuuf\Primi\Ex\EngineError; /** * Helper class for representing Primi source code provided as path to the * source file. * * @internal */ class SourceFile extends Source { use StrictObject; /** * Directory path of the source file. This is then used to perform relative * imports. */ private string $directory; public function __construct(string $path) { if (!\file_exists($path) || !\is_file($path)) { throw new EngineError("File '$path' not found"); } $code = \file_get_contents($path); $id = \sprintf("<file '%s'>", $path); $this->sourceId = $id; $this->sourceCode = $code; $this->directory = \dirname($path); } public function getDirectory(): string { return $this->directory; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Code/Ast.php
src/Code/Ast.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Code; use \Smuuf\StrictObject; /** * Abstract syntax tree object (result from parsing Primi source code).. * * @see https://en.wikipedia.org/wiki/Abstract_syntax_tree * @internal */ class Ast { use StrictObject; /** * Abstract syntax tree as (nested) array. * * @var TypeDef_AstNode */ private array $tree; /** * @param TypeDef_AstNode $ast */ public function __construct(array $ast) { $this->tree = $ast; } /** * @return TypeDef_AstNode */ public function getTree(): array { return $this->tree; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Code/Source.php
src/Code/Source.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Code; use \Smuuf\StrictObject; use \Smuuf\Primi\Helpers\Func; /** * Helper class for representing Primi source code. * * @internal */ class Source { use StrictObject; /** Source ID meant for human-friendly identification. */ protected string $sourceId; /** Primi source code string. */ protected string $sourceCode; public function __construct(string $code) { $id = \sprintf("<string %s>", Func::string_hash($code)); $this->sourceId = $id; $this->sourceCode = $code; } public function getSourceId(): string { return $this->sourceId; } public function getSourceCode(): string { return $this->sourceCode; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Code/AstProvider.php
src/Code/AstProvider.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Code; use \Smuuf\StrictObject; use \Smuuf\Primi\Ex\SyntaxError; use \Smuuf\Primi\Ex\InternalSyntaxError; use \Smuuf\Primi\Parser\ParserHandler; use \Smuuf\Primi\Handlers\KnownHandlers; class AstProvider { use StrictObject; /** Path to temporary directory for storing cached AST files. */ private ?string $tempDir; public function __construct(?string $tempDir = \null) { // $tempDir is taken from Config object - that means we're sure // it already is an existing directory - or null. $this->tempDir = $tempDir; } public function getAst(Source $source, bool $caching = \true): Ast { if (!$caching) { return new Ast(self::parseSource($source)); } $key = \json_encode([ KnownHandlers::getStateId(), $source->getSourceCode(), ]); if ($ast = $this->loadFromCache($key)) { return new Ast($ast); } $ast = self::parseSource($source); // Store/cache parsed AST, if caching is enabled. $this->storeIntoCache($key, $ast); return new Ast($ast); } /** * @return TypeDef_AstNode|null */ private function loadFromCache(string $key): ?array { if ($this->tempDir === \null) { return \null; } $path = self::buildCachedPath($key, $this->tempDir); if (\is_file($path)) { return \json_decode(file_get_contents($path), \true); } return \null; } /** * @param TypeDef_AstNode $ast */ private function storeIntoCache(string $key, array $ast): void { if ($this->tempDir === \null) { return; } $path = self::buildCachedPath($key, $this->tempDir); file_put_contents($path, \json_encode($ast)); } /** * @return TypeDef_AstNode * @throws SyntaxError */ private static function parseSource(Source $source): array { $sourceString = $source->getSourceCode(); try { return (new ParserHandler($sourceString))->run(); } catch (InternalSyntaxError $e) { throw SyntaxError::fromInternal($e, $source); } } private static function buildCachedPath(string $key, string $dir): string { return \sprintf('%s/ast_cache_%s.json', $dir, \md5($key)); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Cli/Term.php
src/Cli/Term.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Cli; use \Smuuf\Primi\Helpers\Colors; abstract class Term { public static function line(string $text = ''): string { return "$text\n"; } public static function error(string $text): string { return Colors::get("{red}Error:{_} ") . "$text\n"; } public static function debug(string $text): string { return Colors::get("{yellow}Debug:{_} ") . "$text\n"; } public static function stderr(string $text): void { \fwrite(\STDERR, $text); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Cli/Entrypoint.php
src/Cli/Entrypoint.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Cli; use \Smuuf\StrictObject; use \Smuuf\Primi\Repl; use \Smuuf\Primi\Logger; use \Smuuf\Primi\Config; use \Smuuf\Primi\EnvInfo; use \Smuuf\Primi\Interpreter; use \Smuuf\Primi\Ex\EngineError; use \Smuuf\Primi\Ex\BaseException; use \Smuuf\Primi\Ex\EngineInternalError; use \Smuuf\Primi\Ex\InternalSyntaxError; use \Smuuf\Primi\Ex\SyntaxError; use \Smuuf\Primi\Code\Source; use \Smuuf\Primi\Code\SourceFile; use \Smuuf\Primi\Parser\ParserHandler; use \Smuuf\Primi\Helpers\Stats; use \Smuuf\Primi\Helpers\Colors; use \Smuuf\Primi\Helpers\Func; class Entrypoint { use StrictObject; /** @var array<string, mixed> */ private array $config = [ // Print only parsed AST and then exit. 'only_tree' => false, // Parse the input (build AST), print parser stats and exit. 'print_runtime_stats' => false, // After the script finishes, print out contents of main global scope. 'parser_stats' => false, // The default argument represents Primi code to run. 'input' => false, // Print verbose logging to stderr. 'verbose' => false, // True if the input is not a Primi file to run, but just a string // containing Primi source code to run. 'input_is_code' => false, ]; /** * @param array<string> $args Arguments to the CLI script (without the * first $0 argument). */ public function __construct(array $args) { self::globalInit(); $this->config = $this->parseArguments($this->config, $args); } private static function globalInit(): void { error_reporting(E_ALL); set_error_handler(function($severity, $message, $file, $line) { // This error code is not included in error_reporting, so let it fall // through to the standard PHP error handler. if (!(error_reporting() & $severity)) { return false; } throw new \ErrorException($message, 0, $severity, $file, $line); }, E_ALL); set_exception_handler(function($ex) { echo "PHP ERROR " . get_class($ex); echo ": {$ex->getMessage()} @ {$ex->getFile()}:{$ex->getLine()}\n"; echo $ex->getTraceAsString() . "\n"; }); try { EnvInfo::bootCheck(); } catch (EngineError $e) { self::errorExit($e->getMessage()); } } public function execute(): void { $cfg = $this->config; // Enable verbose logging. if ($cfg['verbose']) { Logger::enable(); } // If requested, print stats at the absolute end of runtime. if ($cfg['print_runtime_stats']) { register_shutdown_function(fn() => Stats::print()); } // Determine the source. Act as REPL if no source was specified. if (empty($cfg['input'])) { $this->runRepl(); return; } if ($cfg['input_is_code']) { // If the input is passed as a string of Primi source code, consider // the current working directory as runtime's main directory. $source = new Source($cfg['input']); $mainDir = getcwd(); } else { try { $filepath = $cfg['input']; $source = new SourceFile($filepath); $mainDir = $source->getDirectory(); } catch (EngineError $e) { self::errorExit($e->getMessage()); } } if ($cfg['parser_stats'] || $cfg['only_tree']) { $ph = new ParserHandler($source->getSourceCode()); // Run parser and catch any error that may have occurred. try { try { $tree = $ph->run(); } catch (InternalSyntaxError $e) { throw SyntaxError::fromInternal($e, $source); } } catch (BaseException $e) { self::errorExit("{$e->getMessage()}"); } // If requested, just print the syntax tree. if ($cfg['only_tree']) { print_r($tree); return; } echo Term::line(Colors::get("{green}Parser stats:{_}")); foreach ($ph->getStats() as $name => $value) { $value = round($value, 4); echo Term::line(Colors::get("- $name: {yellow}{$value} s{_}")); } return; } $config = Config::buildDefault(); $config->addImportPath($mainDir); // Create interpreter. try { $interpreter = new Interpreter($config); } catch (EngineError $e) { self::errorExit($e->getMessage()); } // Run interpreter and catch any error that may have occurred. try { $interpreter->run($source); } catch (EngineInternalError $e) { throw $e; } catch (BaseException $e) { $colorized = Func::colorize_traceback($e); self::errorExit($colorized); } } private function runRepl(): void { Term::stderr($this->getHeaderString('REPL')); $repl = new Repl; $repl->start(); } /** * @return never */ private static function errorExit(string $text): void { Term::stderr(Term::error($text)); die(1); } /** * @param array<string, mixed> $defaults * @param array<string, mixed> $args * @return array<string, mixed> */ private function parseArguments(array $defaults, array $args): array { $cfg = $defaults; while ($a = array_shift($args)) { switch ($a) { case "-h": case "--help": self::dieWithHelp(); case "-t": case "--tree": $cfg['only_tree'] = true; break; case "-pst": case "--parser-stats": $cfg['parser_stats'] = true; break; case "-s": case "--source": $cfg['input_is_code'] = true; break; case "-rst": case "--runtime-stats": $cfg['print_runtime_stats'] = true; break; case "-v": case "--verbose": $cfg['verbose'] = true; break; default: $cfg['input'] = $a; break; } } return $cfg; } /** * @return never */ private static function dieWithHelp(): void { $header = self::getHeaderString('CLI'); $help = <<<HELP $header {green}Usage:{_} primi [<options>] [<input file>] {green}Examples:{_} primi ./some_file.primi primi -s 'something = 1; print(something + 1)' primi -rst -s 'something = 1; print(something + 1)' {green}Options:{_} {yellow}-h, --help{_} Print this help. {yellow}-pst, --parser-stats{_} Print parser stats upon exit (code is not executed). {yellow}-rst, --stats{_} Print interpreter runtime stats upon exit. {yellow}-s, --source{_} Treat <input file> as string instead of a source file path. {yellow}-t, --tree{_} Only print syntax tree and exit. {yellow}-v, --verbose{_} Enable verbose debug logging. HELP; die(Colors::get($help)); } private static function getHeaderString(string $env = null): string { $env = $env ? "($env)" : null; $php = PHP_VERSION; $buildInfo = EnvInfo::getPrimiBuild(); $string = "Primi {$env}, Copyright (c) Premysl Karbula " . "{darkgrey}(build {$buildInfo}){_}\n" . "{yellow}Running on PHP {$php}{_}\n"; return Colors::get($string); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/HandlerFactory.php
src/Handlers/HandlerFactory.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers; use \Smuuf\StrictObject; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\EngineInternalError; /** * Static helper class for getting correct handler class for specific AST node. * * @internal */ abstract class HandlerFactory { use StrictObject; /** @var array<string, string|null> Dict of handler classes we know exist. */ private static $handlersCache = []; private const PREFIX = '\Smuuf\Primi\Handlers\Kinds'; /** * @return class-string|string */ private static function buildHandlerClassName(string $name) { return self::PREFIX . "\\$name"; } /** * NOTE: This is used only during parsing/compilation. * * @return class-string|string */ public static function tryGetForName(string $name): ?string { $class = self::buildHandlerClassName($name); if (!\class_exists($class)) { return null; } return $class; } /** * Get handler class as string for a AST-node-type specific handler * identified by handler type. * * NOTE: Return type is omitted for performance reasons, as this method will * be called VERY often. * * @param string $name * @return ?class-string */ public static function getFor($id) { // Using caching is of course faster than repeatedly building strings // and checking classes and stuff. if (\array_key_exists($id, self::$handlersCache)) { return self::$handlersCache[$id]; } $class = self::buildHandlerClassName(KnownHandlers::fromId($id)); if (!\class_exists($class)) { $msg = "Handler class '$class' for handler ID '$id' not found"; throw new EngineInternalError($msg); } return self::$handlersCache[$id] = $class; } /** * Shorthand function for running a AST node passed as array. * * @param TypeDef_AstNode $node * @param Context $ctx * @return mixed */ public static function runNode($node, $ctx) { return self::getFor($node['name'])::run($node, $ctx); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Handler.php
src/Handlers/Handler.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers; use \Smuuf\StrictObject; /** * Base abstract class for node handler (always static). The `Node::reduce()` * method is used for optional AST node post-process (e.g. reduction) after * parsing. */ abstract class Handler { use StrictObject; /** * If true, 'text' node value won't be removed during AST postprocessing. * If false, it will be removed. This can reduce size of cached AST, because * some (most, in fact) nodes don't really need to keep the 'text'. * * @const bool */ const NODE_NEEDS_TEXT = \false; /** * Additional node-type-specific post-process of the AST node provided by * parser. AST node array is passed by reference. * * @param TypeDef_AstNode $node */ public static function reduce(array &$node): void { // Nothing is done to the AST node by default. } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/SimpleHandler.php
src/Handlers/SimpleHandler.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers; use \Smuuf\Primi\Context; use \Smuuf\Primi\Location; use \Smuuf\Primi\Ex\SyntaxError; use \Smuuf\Primi\Ex\RuntimeError; use \Smuuf\Primi\Ex\ErrorException; use \Smuuf\Primi\Ex\SystemException; /** * Base node handler class for evaluating some AST node within given context. */ abstract class SimpleHandler extends Handler { /** * @param TypeDef_AstNode $node * @return mixed */ final public static function run( array $node, Context $context ) { try { return static::handle($node, $context); } catch (RuntimeError|SyntaxError|SystemException $e) { $location = new Location( $context->getCurrentModule()->getStringRepr(), (int) $node['_l'], (int) $node['_p'] ); throw new ErrorException( $e->getMessage(), $location, $context->getCallStack() ); } } /** * @param TypeDef_AstNode $node * @return mixed */ abstract protected static function handle(array $node, Context $context); }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/SharedArithmeticHandler.php
src/Handlers/SharedArithmeticHandler.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers; use \Smuuf\Primi\Context; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\ArithmeticLTR; use \Smuuf\Primi\Handlers\SimpleHandler; /** * Common ancestor of Addition, Multiplication handlers, both of which have * the exact same implementation, but are separated on a grammar level for * operators "and" and "or" to have a distinct precedences. */ abstract class SharedArithmeticHandler extends SimpleHandler { protected static function handle(array $node, Context $context) { return ArithmeticLTR::handle($node, $context); } public static function reduce(array &$node): void { // If there is no operator, then there's no need to keep this as // a complex node of this type. Reduce this node to its only operand. if (!isset($node['ops'])) { $node = $node['operands']; } else { $node['ops'] = Func::ensure_indexed($node['ops']); } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/ChainedHandler.php
src/Handlers/ChainedHandler.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers; use \Smuuf\Primi\Context; use \Smuuf\Primi\Values\AbstractValue; /** * Base node handler class for evaluating some AST node within given context * with passed (chained) AbstractValue object. */ abstract class ChainedHandler extends Handler { /** * @param TypeDef_AstNode $node * @return mixed */ abstract public static function chain( array $node, Context $context, AbstractValue $subject ); }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/KnownHandlers.php
src/Handlers/KnownHandlers.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers; use \Smuuf\Primi\Ex\EngineInternalError; abstract class KnownHandlers { private static bool $initialized = \false; /** * State ID of present handlers. This ID will be different if any handler * is added, removed or modified. * * Why do we track this? Because if anything changes, old parsed and cached * ASTs are invalid and we need to tell our cache not to use them. */ private static string $stateId = ''; /** @var array<string, int> */ private static array $namesToIdsMapping = []; /** @var array<int, string> */ private static array $idsToNamesMapping = []; /** * Helper function which returns *.php files from the directory where * source files of handlers are present. * * @return array<int, string> */ private static function listHandlerFiles(): array { $files = []; // One might think that `glob()` would be enough, but `glob()` doesn't // work when we're inside PHAR, so we need the old-fashioned non-glob way. foreach (\scandir(__DIR__ . "/Kinds/") as $filename) { if (!\str_ends_with($filename, '.php')) { continue; } $files[] = __DIR__ . "/Kinds/$filename"; } return $files; } public static function init(): void { if (self::$initialized) { return; } $handlerStateId = []; foreach (self::listHandlerFiles() as $id => $filepath) { // Don't start at zero, so that no handler has ID of zero - let's // prevent any dumb errors that might be caused by something // somewhere comparing the handler ID the wrong way (0 is falsy). $id += 1; // "./Kinds/SomeHandler.php" -> "SomeHandler" $name = \strchr(\basename($filepath), '.php', \true); self::$namesToIdsMapping[$name] = $id; self::$idsToNamesMapping[$id] = $name; // Get hash of the handler source code, so we track changes inside. $handlerStateId[$name] = \md5(\file_get_contents($filepath)); } self::$stateId = md5(\json_encode([ self::$namesToIdsMapping, self::$idsToNamesMapping, $handlerStateId, ])); self::$initialized = \true; } public static function getStateId(): string { return self::$stateId; } public static function fromId(int $id): string { $name = self::$idsToNamesMapping[$id] ?? \null; if ($name === \null) { throw new EngineInternalError("Unknown handler ID '$id'"); } return $name; } public static function fromName(string $name, bool $strict = \true): ?int { $id = self::$namesToIdsMapping[$name] ?? \null; if ($id === \null) { if ($strict) { throw new EngineInternalError("Unknown handler name '$name'"); } else { return \null; } } return $id; } } KnownHandlers::init();
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/SharedLogicalHandler.php
src/Handlers/SharedLogicalHandler.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\EngineInternalError; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Values\BoolValue; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\Interned; /** * Common ancestor of LogicalAnd and LogicalOr handlers, both of which have * almost exact same implementation, but are separated on a grammar level for * operators "and" and "or" to have a distinct precedences. * * Both "and" and "or" operators do support short-circuiting. */ abstract class SharedLogicalHandler extends SimpleHandler { protected static function handle(array $node, Context $context) { $type = $node['type']; if ($type === "and") { return self::handleAnd($node, $context); } if ($type === "or") { return self::handleOr($node, $context); } // Unknown operator - should not ever happen, unless there's // any unexpected output of source code parting. throw new EngineInternalError("Unknown operator '$type'"); } public static function reduce(array &$node): void { // If there is no operator "and"/"or", reduce the node to it's only // operand, because no "logical" operation is necessary during runtime.. if (!isset($node['ops'])) { $node = $node['operands']; } else { // Even though operators are the same under a single logical // node, the "ops" list is expected by the Func::yield_left_to_right // helper, so we need to keep it. $node['ops'] = Func::ensure_indexed($node['ops']); // The type of operator will not ever change in a single logical // operation node - let's extract it right now for easy access // during runtime. $node['type'] = $node['ops'][0]['text']; } } /** * @param TypeDef_AstNode $node */ private static function handleAnd( array $node, Context $context ): BoolValue { $gen = Func::yield_left_to_right($node, $context); foreach ($gen as [$_, $operand]) { // Short-circuiting OR operator: if any of the results is already // true, do not do the rest. if (!$operand->isTruthy()) { return Interned::bool(\false); } } return Interned::bool(\true); } /** * @param TypeDef_AstNode $node */ private static function handleOr( array $node, Context $context ): AbstractValue { $gen = Func::yield_left_to_right($node, $context); foreach ($gen as [$_, $operand]) { // Short-circuiting OR operator: if any of the results is already // truthy, do not do the rest and return the first truthy value. if ($operand->isTruthy()) { return $operand; } } return Interned::bool(\false); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/Assignment.php
src/Handlers/Kinds/Assignment.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\EngineInternalError; use \Smuuf\Primi\Handlers\SimpleHandler; use \Smuuf\Primi\Handlers\HandlerFactory; use \Smuuf\Primi\Structures\AssignmentTargets; use \Smuuf\Primi\Structures\InsertionProxyInterface; class Assignment extends SimpleHandler { protected static function handle(array $node, Context $context) { // Execute the right-hand node first. $return = HandlerFactory::runNode($node['right'], $context); $target = HandlerFactory::runNode($node['left'], $context); if (\is_string($target)) { // Store the return value into variable in current scope. $context->setVariable($target, $return); return $return; } if ($target instanceof InsertionProxyInterface) { // Vector handler returns a proxy with the key being // pre-configured. Commit the value to that key into the correct // value object. $target->commit($return); return $return; } if ($target instanceof AssignmentTargets) { $target->assign($return, $context); return $return; } throw new EngineInternalError("Invalid assignment target"); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/BreakStatement.php
src/Handlers/Kinds/BreakStatement.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\BreakException; use \Smuuf\Primi\Handlers\SimpleHandler; class BreakStatement extends SimpleHandler { protected static function handle(array $node, Context $context) { throw new BreakException; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/ContinueStatement.php
src/Handlers/Kinds/ContinueStatement.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\ContinueException; use \Smuuf\Primi\Handlers\SimpleHandler; class ContinueStatement extends SimpleHandler { protected static function handle(array $node, Context $context) { throw new ContinueException; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/ListDefinition.php
src/Handlers/Kinds/ListDefinition.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Values\ListValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Handlers\SimpleHandler; use \Smuuf\Primi\Handlers\HandlerFactory; class ListDefinition extends SimpleHandler { protected static function handle(array $node, Context $context) { if (empty($node['items'])) { return new ListValue([]); } return new ListValue(self::buildValues($node['items'], $context)); } /** * @param array<TypeDef_AstNode> $itemNodes * @return array<AbstractValue> */ protected static function buildValues( array $itemNodes, Context $context ): array { $result = []; foreach ($itemNodes as $itemNode) { $result[] = HandlerFactory::runNode($itemNode, $context); } return $result; } public static function reduce(array &$node): void { // Make sure this is always list, even with one item. if (isset($node['items'])) { $node['items'] = Func::ensure_indexed($node['items']); } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/LogicalOr.php
src/Handlers/Kinds/LogicalOr.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Handlers\SharedLogicalHandler; /** * @see SharedLogicalHandler */ class LogicalOr extends SharedLogicalHandler { }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/Addition.php
src/Handlers/Kinds/Addition.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Handlers\SharedArithmeticHandler; /** * @see SharedArithmeticHandler */ class Addition extends SharedArithmeticHandler { }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/Exponentiation.php
src/Handlers/Kinds/Exponentiation.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\BinaryOperationError; use \Smuuf\Primi\Handlers\SimpleHandler; use \Smuuf\Primi\Handlers\HandlerFactory; class Exponentiation extends SimpleHandler { protected static function handle(array $node, Context $context) { $operand = HandlerFactory::runNode($node['operand'], $context); $factor = HandlerFactory::runNode($node['factor'], $context); $result = $operand->doPower($factor); if ($result === \null) { throw new BinaryOperationError('**', $operand, $factor); } return $result; } public static function reduce(array &$node): void { // If there is no factor, then there's no need to keep this as // a complex node of this type. Reduce this node to its only operand. if (!isset($node['factor'])) { $node = $node['operand']; } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/VectorItemNoIndex.php
src/Handlers/Kinds/VectorItemNoIndex.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Handlers\ChainedHandler; use \Smuuf\Primi\Structures\ItemInsertionProxy; class VectorItemNoIndex extends ChainedHandler { public static function chain( array $node, Context $context, AbstractValue $subject ) { // This can only be a leaf node. Key is null, since it is not specified. return new ItemInsertionProxy(\null, $subject); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/AttrAccess.php
src/Handlers/Kinds/AttrAccess.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\LookupError; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Handlers\ChainedHandler; class AttrAccess extends ChainedHandler { public static function chain( array $node, Context $context, AbstractValue $subject ) { $attrName = $node['attr']; $value = $subject->attrGet($attrName); if ($value) { return $value; } $typeName = $subject->getTypeName(); throw new LookupError("Object of type '$typeName' has no attribute '$attrName'"); } public static function reduce(array &$node): void { $node['attr'] = $node['attr']['text']; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/TupleDefinition.php
src/Handlers/Kinds/TupleDefinition.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Values\TupleValue; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Handlers\SimpleHandler; use \Smuuf\Primi\Handlers\HandlerFactory; class TupleDefinition extends SimpleHandler { protected static function handle(array $node, Context $context) { if (empty($node['items'])) { return new TupleValue; } return new TupleValue(self::buildValues($node['items'], $context)); } /** * @param array<TypeDef_AstNode> $itemNodes * @return array<AbstractValue> */ protected static function buildValues( array $itemNodes, Context $context ): array { $result = []; foreach ($itemNodes as $itemNode) { $result[] = HandlerFactory::runNode($itemNode, $context); } return $result; } public static function reduce(array &$node): void { // Make sure this is always list, even with one item. if (isset($node['items'])) { $node['items'] = Func::ensure_indexed($node['items']); } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/ImportStatement.php
src/Handlers/Kinds/ImportStatement.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\VariableImportError; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Handlers\SimpleHandler; class ImportStatement extends SimpleHandler { protected static function handle(array $node, Context $context) { $dotpath = $node['module']; $symbols = $node['symbols'] ?? []; $moduleValue = $context->getImporter()->getModule($dotpath); $currentScope = $context->getCurrentScope(); // Import only a specific symbol (variable) from the module. if ($symbols) { foreach ($symbols as $symbol) { $value = $moduleValue->attrGet($symbol); if ($value === \null) { throw new VariableImportError($symbol, $dotpath); } $currentScope->setVariable($symbol, $value); } } else { // Importing the whole module - save it into current scope as // variable named after the last part of the module's dot path. $parts = \explode('.', $dotpath); $name = \end($parts); $currentScope->setVariable($name, $moduleValue); } } public static function reduce(array &$node): void { $node['module'] = $node['module']['text']; if (!empty($node['symbols'])) { $symbols = []; foreach (Func::ensure_indexed($node['symbols']) as $s) { $symbols[] = $s['text']; } $node['symbols'] = $symbols; } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/Multiplication.php
src/Handlers/Kinds/Multiplication.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Handlers\SharedArithmeticHandler; /** * @see SharedArithmeticHandler */ class Multiplication extends SharedArithmeticHandler { }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/ForStatement.php
src/Handlers/Kinds/ForStatement.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\RuntimeError; use \Smuuf\Primi\Ex\BreakException; use \Smuuf\Primi\Ex\ContinueException; use \Smuuf\Primi\Handlers\SimpleHandler; use \Smuuf\Primi\Handlers\HandlerFactory; use \Smuuf\Primi\Structures\AssignmentTargets; /** * Node fields: * left: A source iterator. * item: Variable name to store the single item in. * right: Node representing contents of code to execute while iterating the iterator structure. */ class ForStatement extends SimpleHandler { protected static function handle(array $node, Context $context) { // Execute the left-hand node and get its return value. $subject = HandlerFactory::runNode($node['left'], $context); $iter = $subject->getIterator(); if ($iter === \null) { throw new RuntimeError( \sprintf("Cannot iterate over '%s'", $subject->getTypeName()) ); } /** @var AssignmentTargets */ $targets = HandlerFactory::runNode($node['targets'], $context); $blockHandler = HandlerFactory::getFor($node['right']['name']); // 1-bit value for ticking task queue once per two iterations. $tickBit = 0; $queue = $context->getTaskQueue(); foreach ($iter as $i) { // Switch the bit from 1/0 or vice versa. if ($tickBit ^= 1) { $queue->tick(); } $targets->assign($i, $context); try { $blockHandler::run($node['right'], $context); if ($context->hasRetval()) { return; } } catch (ContinueException $e) { continue; } catch (BreakException $e) { break; } } $context->getTaskQueue()->tick(); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/Negation.php
src/Handlers/Kinds/Negation.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Handlers\SimpleHandler; use \Smuuf\Primi\Handlers\HandlerFactory; class Negation extends SimpleHandler { protected static function handle(array $node, Context $context) { $truthness = HandlerFactory::runNode($node['core'], $context) ->isTruthy(); // Should we even handle negation? If there's an even number of negation // operators, the result would always have the same truthness as its // input. $isNegation = \count($node['nots'] ?? []) % 2; return Interned::bool($isNegation ? !$truthness : $truthness); } public static function reduce(array &$node): void { // If this truly has a negation, do not reduce this node. // If not, return only core. if (!isset($node['nots'])) { $node = $node['core']; } else { $node['nots'] = Func::ensure_indexed($node['nots']); } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/VectorItem.php
src/Handlers/Kinds/VectorItem.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\RuntimeError; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Handlers\HandlerFactory; use \Smuuf\Primi\Handlers\ChainedHandler; use \Smuuf\Primi\Structures\ItemInsertionProxy; class VectorItem extends ChainedHandler { public static function chain( array $node, Context $context, AbstractValue $subject ) { $key = HandlerFactory::runNode($node['index'], $context); // If this is a leaf node, return an insertion proxy. if ($node['leaf']) { return new ItemInsertionProxy($key, $subject); } // This is not a leaf node, so just return the value this non-leaf node // points to. $value = $subject->itemGet($key); if ($value === \null) { throw new RuntimeError(\sprintf( "Type '%s' does not support item access", $subject->getTypeName() )); } return $value; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/Targets.php
src/Handlers/Kinds/Targets.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Handlers\SimpleHandler; use \Smuuf\Primi\Structures\AssignmentTargets; class Targets extends SimpleHandler { protected static function handle(array $node, Context $context) { return new AssignmentTargets($node['t']); } public static function reduce(array &$node): void { // Make sure this is always list, even with one item. $node['t'] = \array_column(Func::ensure_indexed($node['t']), 'text'); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/ReturnStatement.php
src/Handlers/Kinds/ReturnStatement.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Handlers\SimpleHandler; use \Smuuf\Primi\Handlers\HandlerFactory; use \Smuuf\Primi\Structures\CallRetval; class ReturnStatement extends SimpleHandler { protected static function handle(array $node, Context $context) { $retval = new CallRetval( \array_key_exists('subject', $node) ? HandlerFactory::runNode($node['subject'], $context) : \null ); $context->setRetval($retval); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/Dereference.php
src/Handlers/Kinds/Dereference.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\RuntimeError; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Handlers\ChainedHandler; use \Smuuf\Primi\Handlers\HandlerFactory; class Dereference extends ChainedHandler { public static function chain( array $node, Context $context, AbstractValue $subject ) { $key = HandlerFactory::runNode($node['key'], $context); $returned = $subject->itemGet($key); if ($returned === \null) { throw new RuntimeError(\sprintf( "Type '%s' does not support item access", $subject->getTypeName() )); } return $returned; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/CondExpr.php
src/Handlers/Kinds/CondExpr.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Handlers\HandlerFactory; use \Smuuf\Primi\Handlers\SimpleHandler; class CondExpr extends SimpleHandler { protected static function handle(array $node, Context $context) { // Execute the left-hand node and get its return value. $return = HandlerFactory::runNode($node['cond'], $context); // If the result of the left hand equals to truthy value, // execute the code branch stored in the right-hand node. if ($return->isTruthy()) { return HandlerFactory::runNode($node['true'], $context); } else { return HandlerFactory::runNode($node['false'], $context); } } public static function reduce(array &$node): void { if (!isset($node['cond'])) { $node = $node['true']; } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/VariableName.php
src/Handlers/Kinds/VariableName.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Handlers\SimpleHandler; class VariableName extends SimpleHandler { const NODE_NEEDS_TEXT = \true; protected static function handle(array $node, Context $context) { return $node['text']; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/LogicalAnd.php
src/Handlers/Kinds/LogicalAnd.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Handlers\SharedLogicalHandler; /** * @see SharedLogicalHandler */ class LogicalAnd extends SharedLogicalHandler { }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/StringLiteral.php
src/Handlers/Kinds/StringLiteral.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Helpers\StringEscaping; use \Smuuf\Primi\Handlers\SimpleHandler; class StringLiteral extends SimpleHandler { const NODE_NEEDS_TEXT = \true; protected static function handle(array $node, Context $context) { return Interned::string($node['text']); } public static function reduce(array &$node): void { $node['text'] = StringEscaping::unescapeString($node['core']['text']); unset($node['quote']); unset($node['core']); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/AnonymousFunction.php
src/Handlers/Kinds/AnonymousFunction.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Handlers\SimpleHandler; use \Smuuf\Primi\Values\FuncValue; use \Smuuf\Primi\Structures\FnContainer; class AnonymousFunction extends SimpleHandler { protected static function handle(array $node, Context $context) { $module = $context->getCurrentModule(); $name = \sprintf("%s.<anonymous>()", $module->getName()); $fn = FnContainer::build( $node['body'], $name, $module, $node['params'], $context->getCurrentScope(), ); return new FuncValue($fn); } public static function reduce(array &$node): void { if (isset($node['params'])) { $node['params'] = FunctionDefinition::prepareParameters($node['params']); } else { $node['params'] = []; } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/TryStatement.php
src/Handlers/Kinds/TryStatement.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\ErrorException; use \Smuuf\Primi\Handlers\HandlerFactory; use \Smuuf\Primi\Handlers\SimpleHandler; class TryStatement extends SimpleHandler { protected static function handle(array $node, Context $context) { try { // Execute the main code. return HandlerFactory::runNode($node['main'], $context); } catch (ErrorException $e) { // Execute the onerror block if any error occurred with the main code. return HandlerFactory::runNode($node['onerror'], $context); } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/Operand.php
src/Handlers/Kinds/Operand.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Handlers\HandlerFactory; use \Smuuf\Primi\Handlers\SimpleHandler; class Operand extends SimpleHandler { protected static function handle(array $node, Context $context) { // Handle the item; pass in the chained value, if it was given. $value = HandlerFactory::runNode($node['core'], $context); // If there's chain, handle it. if (\array_key_exists('chain', $node)) { $handler = HandlerFactory::getFor($node['chain']['name']); return $handler::chain($node['chain'], $context, $value); } return $value; } public static function reduce(array &$node): void { // If this node has a value method call with it, don't reduce it. if (!isset($node['chain'])) { $node = $node['core']; } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/DictDefinition.php
src/Handlers/Kinds/DictDefinition.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\TypeError; use \Smuuf\Primi\Ex\UnhashableTypeException; use \Smuuf\Primi\Values\DictValue; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Handlers\HandlerFactory; use \Smuuf\Primi\Handlers\SimpleHandler; class DictDefinition extends SimpleHandler { protected static function handle(array $node, Context $context) { if (!$node['items']) { return new DictValue; } try { return new DictValue( self::buildPairs($node['items'], $context) ); } catch (UnhashableTypeException $e) { throw new TypeError(\sprintf( "Cannot create dict with key containing unhashable type '%s'", $e->getType() )); } } /** * @param array<TypeDef_AstNode> $itemNodes * @return TypeDef_PrimiObjectCouples */ private static function buildPairs( array $itemNodes, Context $context ): iterable { $result = []; foreach ($itemNodes as $node) { $result[] = [ HandlerFactory::runNode($node['key'], $context), HandlerFactory::runNode($node['value'], $context), ]; } return $result; } public static function reduce(array &$node): void { // Make sure this is always list, even with one item. if (isset($node['items'])) { $node['items'] = Func::ensure_indexed($node['items']); } else { $node['items'] = []; } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/WhileStatement.php
src/Handlers/Kinds/WhileStatement.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Handlers\HandlerFactory; use \Smuuf\Primi\Ex\BreakException; use \Smuuf\Primi\Ex\ContinueException; use \Smuuf\Primi\Handlers\SimpleHandler; class WhileStatement extends SimpleHandler { protected static function handle( array $node, Context $context ) { // Execute the left-hand node and get its return value. $condHandler = HandlerFactory::getFor($node['left']['name']); $blockHandler = HandlerFactory::getFor($node['right']['name']); // Counter for determining when to tick the task queue. $tickCounter = 0; $queue = $context->getTaskQueue(); while ( $condHandler::run($node['left'], $context)->isTruthy() ) { // Tick the task queue every 4 iterations. if (++$tickCounter === 4) { $queue->tick(); $tickCounter = 0; } try { $blockHandler::run($node['right'], $context); if ($context->hasRetval()) { return; } } catch (ContinueException $_) { continue; } catch (BreakException $_) { break; } } $queue->tick(); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/ClassDefinition.php
src/Handlers/Kinds/ClassDefinition.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Scope; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\RuntimeError; use \Smuuf\Primi\Values\TypeValue; use \Smuuf\Primi\Stdlib\BuiltinTypes; use \Smuuf\Primi\Helpers\Types; use \Smuuf\Primi\Helpers\Wrappers\ContextPushPopWrapper; use \Smuuf\Primi\Handlers\SimpleHandler; use \Smuuf\Primi\Handlers\HandlerFactory; class ClassDefinition extends SimpleHandler { protected static function handle(array $node, Context $context) { $className = $node['cls']; $parentTypeName = $node['parent']; if ($parentTypeName !== \false) { $parentType = $context->getVariable($parentTypeName); } else { $parentType = BuiltinTypes::getObjectType(); } if (!$parentType instanceof TypeValue) { throw new RuntimeError( "Specified parent class '$parentTypeName' is not a type object" ); } // Create a new scope for this class. // Set scope's type to be 'class scope', so that functions defined as a // method inside a class won't have direct access to its class's scope. // (All access to class' attributes should be done by accessing class // reference inside the function). $classScope = new Scope( [], type: Scope::TYPE_CLASS, parent: $context->getCurrentScope() ); // Execute the class's insides with the class scope. // Variables (and functions) declared inside the class will then // be attributes $wrapper = new ContextPushPopWrapper($context, \null, $classScope); $wrapper->wrap(static fn($ctx) => HandlerFactory::runNode($node['def'], $ctx)); $classAttrs = Types::prepareTypeMethods($classScope->getVariables()); $result = new TypeValue( $className, $parentType, $classAttrs, isFinal: \false, isMutable: \true, ); $context->getCurrentScope()->setVariable($className, $result); } public static function reduce(array &$node): void { $node['cls'] = $node['cls']['text']; $node['parent'] = $node['parent']['text'] ?? \false; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/VariableVector.php
src/Handlers/Kinds/VariableVector.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Handlers\HandlerFactory; use \Smuuf\Primi\Handlers\SimpleHandler; use \Smuuf\Primi\Helpers\Func; /** * This handler is used to access nested items or attributes and prepare it * for nested assignment. * * For example, this is a vector: * ```js * a[1].b['x'].c[0] = 'yes' * ``` * * The code is saying that someone wants to: * * _Store 'yes' under index `0` of the value `c`, which is an attribute of value * stored in `b` under the key `x`, which itself is the value stored under * index `1` of the value `a`._ * * We need to process this chunk of AST nodes and **return an insertion proxy**, * which can then be used for assignment in the `Assignment` handler. */ class VariableVector extends SimpleHandler { protected static function handle(array $node, Context $context) { // Retrieve the original value. $value = HandlerFactory::runNode($node['core'], $context); // And handle the nesting according to the specified vector. foreach ($node['vector'] as $next) { $handler = HandlerFactory::getFor($next['name']); $value = $handler::chain($next, $context, $value); } return $value; } public static function reduce(array &$node): void { $node['vector'] = Func::ensure_indexed($node['vector']); // Mark the last vector node as leaf, so it knows that we expect // insertion proxy from it. $first = \true; for ($i = \count($node['vector']); $i !== 0; $i--) { $node['vector'][$i - 1]['leaf'] = $first; $first = \false; } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/Program.php
src/Handlers/Kinds/Program.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Handlers\SimpleHandler; use \Smuuf\Primi\Handlers\HandlerFactory; class Program extends SimpleHandler { protected static function handle(array $node, Context $context) { foreach ($node['stmts'] as $sub) { $returnValue = HandlerFactory::runNode($sub, $context); if ($context->hasRetval()) { return; } } return $returnValue ?? Interned::null(); } public static function reduce(array &$node): void { // Make sure the list of statements has proper form. if (isset($node['stmts'])) { $node['stmts'] = Func::ensure_indexed($node['stmts']); } else { // ... even if there are no statements at all. $node['stmts'] = []; } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/BoolLiteral.php
src/Handlers/Kinds/BoolLiteral.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Handlers\SimpleHandler; class BoolLiteral extends SimpleHandler { const NODE_NEEDS_TEXT = \true; protected static function handle(array $node, Context $context) { return Interned::bool($node['text'] === "true"); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/IfStatement.php
src/Handlers/Kinds/IfStatement.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Handlers\HandlerFactory; use \Smuuf\Primi\Handlers\SimpleHandler; /** * Node fields: * left: A comparison expression node. * right: Node representing contents of code to execute if left-hand result is truthy. */ class IfStatement extends SimpleHandler { protected static function handle(array $node, Context $context) { // Execute the left-hand node and get its return value. $result = HandlerFactory::runNode($node['cond'], $context); // If the result of the left hand equals to truthy value, // execute the code branch stored in the right-hand node. if ($result->isTruthy()) { HandlerFactory::runNode($node['block'], $context); return; } // If there are any elifs, go through each one of them and if condition // of any them evaluates as truthy, run their block (but only the first // elif with the truthy condition). foreach ($node['elifs'] as $elif) { $result = HandlerFactory::runNode($elif['cond'], $context); if ($result->isTruthy()) { HandlerFactory::runNode($elif['block'], $context); return; } } // Check existence of "else" block and execute it, if it's present. if (isset($node['elseBlock'])) { HandlerFactory::runNode($node['elseBlock'], $context); } } public static function reduce(array &$node): void { $elifs = []; if (isset($node['elifCond'])) { $node['elifCond'] = Func::ensure_indexed($node['elifCond']); $node['elifBlock'] = Func::ensure_indexed($node['elifBlock'] ?? []); foreach ($node['elifCond'] as $i => $elifCond) { $elifs[] = [ 'cond' => $elifCond, 'block' => $node['elifBlock'][$i], ]; } unset($node['elifCond']); unset($node['elifBlock']); } $node['elifs'] = $elifs; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/ArgumentList.php
src/Handlers/Kinds/ArgumentList.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Ex\InternalPostProcessSyntaxError; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Handlers\SimpleHandler; use \Smuuf\Primi\Handlers\HandlerFactory; use \Smuuf\Primi\Structures\CallArgs; /** * Node fields: * function: Function name. * args: List of arguments. * body: Node representing contents of code to execute as a function.. */ class ArgumentList extends SimpleHandler { protected static function handle(array $node, Context $context) { if (!\array_key_exists('args', $node)) { return []; } $args = []; $kwargs = []; foreach ($node['args'] as $arg) { if (\array_key_exists('argKey', $arg)) { $kwargs[$arg['argKey']['text']] = HandlerFactory::runNode($arg['argVal'], $context); } else { $result = HandlerFactory::runNode($arg['argVal'], $context); // Argument might have been a starred expression, in which case // the result is an array (see StarredExpression handler) - so // let's unpack it. // Single-starred expression is returned as a list array. // Double-starred expression is returned as a dict array. if (\is_array($result)) { if (\array_is_list($result)) { $args = [...$args, ...$result]; } else { $kwargs = \array_replace($kwargs, $result); } } else { $args[] = $result; } } } return new CallArgs($args, $kwargs); } public static function reduce(array &$node): void { // Make sure this is always list, even with one item. if (isset($node['args'])) { $node['args'] = Func::ensure_indexed($node['args']); } // Handle positional and keyword arguments. // If both types of arguments are used, keyword arguments MUST be // places after positional arguments. So let's check it. $foundKwargs = []; $foundAnyKwargs = \false; foreach ($node['args'] as $arg) { // Detect: // 1. literal keyword arguments, or // 2. Keyword arguments used as starred "**kwargs" argument. $isLiteralKwarg = isset($arg['argKey']); $areStarredKwargs = $arg['argVal']['name'] === 'StarredExpression' && $arg['argVal']['stars'] === StarredExpression::STARS_TWO; $isAnyKwarg = $isLiteralKwarg || $areStarredKwargs; if (!$isAnyKwarg && $foundAnyKwargs) { // This is a positional argument, but we already encountered // some keyword argument - that's a syntax error (easier to // check and handle here and not via grammar). // // This happens if calling function like: // > result = f(1, arg_b: 2, 3) throw new InternalPostProcessSyntaxError( "Keyword arguments must be placed after positional arguments" ); } if ($isLiteralKwarg) { $kwargKey = $arg['argKey']['text']; // Specifying a single kwarg multiple times is a syntax error. // // This happens if calling function like: // > f = (a, b, c) => {} // > result = f(1, b: 2, b: 3, c: 4) if (\array_key_exists($kwargKey, $foundKwargs)) { throw new InternalPostProcessSyntaxError( "Repeated keyword argument '$kwargKey'" ); } // Monitor kwargs as keys in an array for faster lookup // via array_key_exists() above. $foundKwargs[$kwargKey] = \null; } $foundAnyKwargs |= $isAnyKwarg; } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/NumberLiteral.php
src/Handlers/Kinds/NumberLiteral.php
<?php declare(strict_types=1); declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Handlers\SimpleHandler; class NumberLiteral extends SimpleHandler { const NODE_NEEDS_TEXT = \true; protected static function handle(array $node, Context $context) { return Interned::number($node['number']); } public static function reduce(array &$node): void { // As string. $node['number'] = \str_replace('_', '', $node['text']); unset($node['text']); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/Comparison.php
src/Handlers/Kinds/Comparison.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Helpers\Func; use \Smuuf\Primi\Handlers\SimpleHandler; use \Smuuf\Primi\Helpers\ComparisonLTR; class Comparison extends SimpleHandler { protected static function handle(array $node, Context $context) { return ComparisonLTR::handle($node, $context); } public static function reduce(array &$node): void { // If there is no operator, that means there's only one operand. // In that case, return only the operand node inside. if (!isset($node['ops'])) { $node = $node['operands']; } else { $node['ops'] = Func::ensure_indexed($node['ops']); } } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/Chain.php
src/Handlers/Kinds/Chain.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Handlers\ChainedHandler; use \Smuuf\Primi\Handlers\HandlerFactory; class Chain extends ChainedHandler { public static function chain( array $node, Context $context, AbstractValue $subject ) { // Handle the item; pass in the origin subject. $handler = HandlerFactory::getFor($node['core']['name']); $value = $handler::chain($node['core'], $context, $subject); // If there's chain, handle it, too. if (\array_key_exists('chain', $node)) { $handler = HandlerFactory::getFor($node['chain']['name']); return $handler::chain($node['chain'], $context, $value); } return $value; } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/Invocation.php
src/Handlers/Kinds/Invocation.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Location; use \Smuuf\Primi\Values\AbstractValue; use \Smuuf\Primi\Handlers\ChainedHandler; use \Smuuf\Primi\Handlers\HandlerFactory; class Invocation extends ChainedHandler { public static function chain( array $node, Context $context, AbstractValue $fn ) { $arguments = \null; if (\array_key_exists('args', $node)) { $arguments = HandlerFactory::runNode($node['args'], $context); } // Gather info about call location - for some quality tracebacks. $callsite = new Location( $context->getCurrentModule()->getStringRepr(), $node['_l'], $node['_p'], ); return $fn->invoke($context, $arguments, $callsite); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false
smuuf/primi
https://github.com/smuuf/primi/blob/d66ad6a397080a4caec9b634c925c0e085a00bb0/src/Handlers/Kinds/NullLiteral.php
src/Handlers/Kinds/NullLiteral.php
<?php declare(strict_types=1); namespace Smuuf\Primi\Handlers\Kinds; use \Smuuf\Primi\Context; use \Smuuf\Primi\Helpers\Interned; use \Smuuf\Primi\Handlers\SimpleHandler; class NullLiteral extends SimpleHandler { protected static function handle(array $node, Context $context) { return Interned::null(); } }
php
MIT
d66ad6a397080a4caec9b634c925c0e085a00bb0
2026-01-05T05:19:57.676815Z
false