code
stringlengths
31
1.39M
docstring
stringlengths
23
16.8k
func_name
stringlengths
1
126
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
166
url
stringlengths
50
220
license
stringclasses
7 values
public function setIsExternal($external): void { $this->external = (bool)$external; }
Sets if the class belongs to an external dependency or not.
setIsExternal
php
zephir-lang/zephir
src/CompilerFileAnonymous.php
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFileAnonymous.php
MIT
private function compileClass(CompilationContext $compilationContext): void { /** * Do the compilation */ $this->classDefinition->compile($compilationContext); $code = $this->generateCodeHeadersPre($this->classDefinition); $code .= '#include <Zend/zend_operators.h>' . PHP_EOL; $code .= '#include <Zend/zend_exceptions.h>' . PHP_EOL; $code .= '#include <Zend/zend_interfaces.h>' . PHP_EOL; $this->generateClassHeadersPost($code, $this->classDefinition, $compilationContext); }
Compiles the class/interface contained in the file. @throws Exception @throws ReflectionException
compileClass
php
zephir-lang/zephir
src/CompilerFileAnonymous.php
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFileAnonymous.php
MIT
public function __toString() { return (string)json_encode($this, JSON_PRETTY_PRINT); }
Returns JSON representation of the project config.
__toString
php
zephir-lang/zephir
src/Config.php
https://github.com/zephir-lang/zephir/blob/master/src/Config.php
MIT
public function dumpToFile(): void { file_put_contents('config.json', $this); }
Writes the configuration if it has been changed.
dumpToFile
php
zephir-lang/zephir
src/Config.php
https://github.com/zephir-lang/zephir/blob/master/src/Config.php
MIT
public static function fromServer(): self { $config = new self(); /** * Change configurations flags */ if ($_SERVER['argc'] >= 2) { $argv = $_SERVER['argv']; for ($i = 1; $i < $_SERVER['argc']; ++$i) { $parameter = $argv[$i]; if (preg_match('/^-fno-([a-z0-9\-]+)$/', $parameter, $matches)) { $config->set($matches[1], false, 'optimizations'); unset($argv[$i]); continue; } if (preg_match('/^-f([a-z0-9\-]+)$/', $parameter, $matches)) { $config->set($matches[1], true, 'optimizations'); unset($argv[$i]); continue; } if (preg_match('/^-W([a-z0-9\-]+)$/', $parameter, $matches)) { $config->set($matches[1], false, 'warnings'); unset($argv[$i]); continue; } if (preg_match('/^-w([a-z0-9\-]+)$/', $parameter, $matches)) { $config->set($matches[1], true, 'warnings'); unset($argv[$i]); continue; } if (preg_match('/^--([a-z0-9\-]+)$/', $parameter, $matches)) { // Only known options if (null !== $config->get($matches[1], 'extra')) { $config->set($matches[1], true, 'extra'); unset($argv[$i]); } continue; } if (preg_match('/^--([a-z0-9\-]+)=(.*)$/', $parameter, $matches)) { // Only known options if (null !== $config->get($matches[1], 'extra')) { $config->set($matches[1], $matches[2], 'extra'); unset($argv[$i]); } continue; } switch ($parameter) { case '-q': case '--quiet': $config->set('silent', true); break; case '-v': case '--verbose': $config->set('verbose', true); break; case '-V': $config->set('verbose', false); break; default: break; } } $_SERVER['argv'] = array_values($argv); $_SERVER['argc'] = count($argv); } return $config; }
Factory method to create a Config instance from the $_SERVER['argv'].
fromServer
php
zephir-lang/zephir
src/Config.php
https://github.com/zephir-lang/zephir/blob/master/src/Config.php
MIT
public function get($key, $namespace = null) { return null !== $namespace ? $this->offsetGet([$namespace => $key]) : $this->offsetGet($key); }
Retrieves a configuration setting. @param mixed $key @param mixed $namespace @return mixed|null
get
php
zephir-lang/zephir
src/Config.php
https://github.com/zephir-lang/zephir/blob/master/src/Config.php
MIT
public function jsonSerialize(): array { return $this->container; }
Specify data which should be serialized to JSON.
jsonSerialize
php
zephir-lang/zephir
src/Config.php
https://github.com/zephir-lang/zephir/blob/master/src/Config.php
MIT
public function offsetExists($offset): bool { return isset($this->container[$offset]) || array_key_exists($offset, $this->container); }
Allows to check whether a $key is defined. @param mixed $offset @return bool
offsetExists
php
zephir-lang/zephir
src/Config.php
https://github.com/zephir-lang/zephir/blob/master/src/Config.php
MIT
#[ReturnTypeWillChange] public function offsetGet($offset) { if (!is_array($offset)) { return $this->offsetExists($offset) ? $this->container[$offset] : null; } $namespace = key($offset); $offset = current($offset); if (!$this->offsetExists($namespace) || !is_array($this->container[$namespace])) { return null; } if (isset($this->container[$namespace][$offset]) || array_key_exists($offset, $this->container[$namespace])) { return $this->container[$namespace][$offset]; } return null; }
Gets a $key from the internal container. @param mixed $offset @return mixed|null
offsetGet
php
zephir-lang/zephir
src/Config.php
https://github.com/zephir-lang/zephir/blob/master/src/Config.php
MIT
#[ReturnTypeWillChange] public function offsetSet($offset, $value): void { if (!is_array($offset)) { $this->container[$offset] = $value; return; } $namespace = key($offset); $offset = current($offset); if (!array_key_exists($namespace, $this->container)) { $this->container[$namespace] = []; } $this->container[$namespace][$offset] = $value; }
Sets a configuration value. @param mixed $offset @param mixed $value
offsetSet
php
zephir-lang/zephir
src/Config.php
https://github.com/zephir-lang/zephir/blob/master/src/Config.php
MIT
#[ReturnTypeWillChange] public function offsetUnset($offset): void { unset($this->container[$offset]); }
Unsets a $key from internal container. @param mixed $offset @deprecated
offsetUnset
php
zephir-lang/zephir
src/Config.php
https://github.com/zephir-lang/zephir/blob/master/src/Config.php
MIT
public function set($key, $value, $namespace = null): void { null !== $namespace ? $this->offsetSet([$namespace => $key], $value) : $this->offsetSet($key, $value); }
Changes a configuration setting. @param mixed $key @param mixed $value @param mixed $namespace
set
php
zephir-lang/zephir
src/Config.php
https://github.com/zephir-lang/zephir/blob/master/src/Config.php
MIT
public function __construct(array $classes, Config $config, $templatesPath, array $options) { ksort($classes); $this->config = $config; $this->classes = $classes; $this->logger = new NullLogger(); $this->templatesPath = $templatesPath; $this->options = $options; $this->initialize(); }
Documentation constructor. @param CompilerFile[] $classes @param Config $config @param string $templatesPath @param array $options @throws ConfigException @throws Exception
__construct
php
zephir-lang/zephir
src/Documentation.php
https://github.com/zephir-lang/zephir/blob/master/src/Documentation.php
MIT
public function findThemePathByName($name) { // check the theme from the config $path = null; foreach ($this->themesDirectories as $themeDir) { $path = rtrim($themeDir, '\\/') . DIRECTORY_SEPARATOR . $name; if (!str_starts_with($path, 'phar://')) { $path = realpath($path); } if (is_dir($path)) { break; } } return $path; }
Search a theme by its name. Return the path to it if it exists, otherwise NULL. @param string $name @return string|null
findThemePathByName
php
zephir-lang/zephir
src/Documentation.php
https://github.com/zephir-lang/zephir/blob/master/src/Documentation.php
MIT
public function getOutputDirectory() { return $this->outputDirectory; }
get the directory where the doc is going to be generated. @return string
getOutputDirectory
php
zephir-lang/zephir
src/Documentation.php
https://github.com/zephir-lang/zephir/blob/master/src/Documentation.php
MIT
protected function initialize(): void { $themeConfig = $this->config->get('theme', 'api'); if (!$themeConfig) { throw new ConfigException('Theme configuration is not present'); } $themeDir = $this->findThemeDirectory($themeConfig, $this->options['path']); if (!file_exists($themeDir)) { throw new ConfigException('There is no theme named ' . $themeConfig['name']); } $outputDir = $this->findOutputDirectory($this->options['output']); if (!$outputDir) { throw new ConfigException('Api path (output directory) is not configured'); } $this->outputDirectory = $outputDir; if (!file_exists($outputDir)) { if (!mkdir($outputDir, 0777, true)) { throw new Exception("Can't write output directory $outputDir"); } } if (!is_writable($outputDir)) { throw new Exception("Can't write output directory $outputDir"); } $themeConfig['options'] = $this->prepareThemeOptions($themeConfig, $this->options['options']); $this->theme = new Theme($themeDir, $outputDir, $themeConfig, $this->config, $this); $this->baseUrl = $this->options['url']; }
TODO: options => to ApiOptions object TODO: Validate options. @throws ConfigException @throws Exception
initialize
php
zephir-lang/zephir
src/Documentation.php
https://github.com/zephir-lang/zephir/blob/master/src/Documentation.php
MIT
private function findOutputDirectory($outputDir) { $outputDir = str_replace('%version%', $this->config->get('version'), $outputDir); if ('/' !== $outputDir[0]) { $outputDir = getcwd() . '/' . $outputDir; } return $outputDir; }
Find the directory where the doc is going to be generated depending on the command line options and the config. output directory is checked in this order : => check if the command line argument --output-directory was given => if not ; check if config[api][path] was given @param string $outputDir @return string|null
findOutputDirectory
php
zephir-lang/zephir
src/Documentation.php
https://github.com/zephir-lang/zephir/blob/master/src/Documentation.php
MIT
private function findThemeDirectory($themeConfig, $path = null) { // check if there are additional theme paths in the config $themeDirectoriesConfig = $this->config->get('theme-directories', 'api'); if ($themeDirectoriesConfig) { if (is_array($themeDirectoriesConfig)) { $themesDirectories = $themeDirectoriesConfig; } else { throw new InvalidArgumentException("Invalid value for theme config 'theme-directories'"); } } else { $themesDirectories = []; } $themesDirectories[] = $this->templatesPath . '/Api/themes'; $this->themesDirectories = $themesDirectories; // check if the path was set from the command if (!empty($path)) { if (file_exists($path) && is_dir($path)) { return $path; } else { throw new InvalidArgumentException( sprintf( "Invalid value for option 'theme-path': the theme '%s' was not found or is not a valid theme.", $path ) ); } } if (!isset($themeConfig['name']) || !$themeConfig['name']) { throw new ConfigException( 'There is no theme neither in the the theme config nor as a command line argument' ); } return $this->findThemePathByName($themeConfig['name']); }
Find the theme directory depending on the command line options and the config. theme directory is checked in this order : => check if the command line argument --theme-path was given => if not ; find the different theme directories on the config $config['api']['theme-directories'] search the theme from the name ($config['api']['theme']['name'] in the theme directories, if nothing was found, we look in the zephir install dir default themes (templates/Api/themes) @param array $themeConfig @param string|null $path @return string|null @throws InvalidArgumentException @throws ConfigException
findThemeDirectory
php
zephir-lang/zephir
src/Documentation.php
https://github.com/zephir-lang/zephir/blob/master/src/Documentation.php
MIT
private function prepareThemeOptions($themeConfig, $options = null) { $parsedOptions = null; if (!empty($options)) { if ('{' == $options[0]) { $parsedOptions = json_decode(trim($options), true); if (!$parsedOptions || !is_array($parsedOptions)) { throw new Exception("Unable to parse json from 'theme-options' argument"); } } else { if (file_exists($options)) { $unparsed = file_get_contents($options); $parsedOptions = json_decode($unparsed, true); if (!$parsedOptions || !is_array($parsedOptions)) { throw new Exception( sprintf("Unable to parse json from the file '%s'", $options) ); } } else { throw new Exception(sprintf("Unable to find file '%s'", $options)); } } } if (is_array($parsedOptions)) { $options = array_merge($themeConfig['options'], $parsedOptions); } else { $options = $themeConfig['options']; } return $options; }
Prepare the options by merging the one in the project config with the one in the command line arg "theme-options". command line arg "theme-options" can be either a path to a json file containing the options or a raw json string @param array $themeConfig @param string|null $options @return array @throws Exception
prepareThemeOptions
php
zephir-lang/zephir
src/Documentation.php
https://github.com/zephir-lang/zephir/blob/master/src/Documentation.php
MIT
public function compile(CompilationContext $compilationContext): CompiledExpression { $expression = $this->expression; $type = $expression['type']; switch ($type) { case 'null': return new LiteralCompiledExpression('null', null, $expression); case 'int': case 'integer': return new LiteralCompiledExpression('int', $expression['value'], $expression); case 'long': case 'double': case 'bool': return new LiteralCompiledExpression($type, $expression['value'], $expression); case 'string': return new LiteralCompiledExpression( 'string', str_replace(PHP_EOL, '\\n', $expression['value']), $expression ); case 'istring': return new LiteralCompiledExpression( 'istring', str_replace(PHP_EOL, '\\n', $expression['value']), $expression ); case 'char': if (!strlen($expression['value'])) { throw new CompilerException('Invalid empty char literal', $expression); } if (strlen($expression['value']) > 2) { if (strlen($expression['value']) > 10) { throw new CompilerException( "Invalid char literal: '" . substr($expression['value'], 0, 10) . "...'", $expression ); } else { throw new CompilerException( "Invalid char literal: '" . $expression['value'] . "'", $expression ); } } return new LiteralCompiledExpression('char', $expression['value'], $expression); case 'variable': $var = $compilationContext->symbolTable->getVariable($expression['value']); if ($var) { if ('this' == $var->getRealName()) { $var = 'this'; } else { $var = $var->getName(); } } else { $var = $expression['value']; } return new CompiledExpression('variable', $var, $expression); case 'constant': $compilableExpression = new Constants(); break; case 'empty-array': return $this->emptyArray($expression, $compilationContext); case 'array-access': $compilableExpression = new NativeArrayAccess(); $compilableExpression->setNoisy($this->isNoisy()); break; case 'property-access': $compilableExpression = new PropertyAccess(); $compilableExpression->setNoisy($this->isNoisy()); break; case 'property-string-access': case 'property-dynamic-access': $compilableExpression = new PropertyDynamicAccess(); $compilableExpression->setNoisy($this->isNoisy()); break; case 'static-constant-access': $compilableExpression = new StaticConstantAccess(); break; case 'static-property-access': $compilableExpression = new StaticPropertyAccess(); break; case 'fcall': $functionCall = new FunctionCall(); return $functionCall->compile($this, $compilationContext); case 'mcall': $methodCall = new MethodCall(); return $methodCall->compile($this, $compilationContext); case 'scall': $staticCall = new StaticCall(); return $staticCall->compile($this, $compilationContext); case 'isset': $compilableExpression = new IssetOperator(); break; case 'fetch': $compilableExpression = new FetchOperator(); break; case 'empty': $compilableExpression = new EmptyOperator(); break; case 'array': $compilableExpression = new NativeArray(); break; case 'new': $compilableExpression = new NewInstanceOperator(); break; case 'new-type': $compilableExpression = new NewInstanceTypeOperator(); break; case 'not': $compilableExpression = new NotOperator(); break; case 'bitwise_not': $compilableExpression = new BitwiseNotOperator(); break; case 'equals': $compilableExpression = new EqualsOperator(); break; case 'not-equals': $compilableExpression = new NotEqualsOperator(); break; case 'identical': $compilableExpression = new IdenticalOperator(); break; case 'not-identical': $compilableExpression = new NotIdenticalOperator(); break; case 'greater': $compilableExpression = new GreaterOperator(); break; case 'less': $compilableExpression = new LessOperator(); break; case 'less-equal': $compilableExpression = new LessEqualOperator(); break; case 'greater-equal': $compilableExpression = new GreaterEqualOperator(); break; case 'add': $compilableExpression = new AddOperator(); break; case 'minus': $compilableExpression = new MinusOperator(); break; case 'sub': $compilableExpression = new SubOperator(); break; case 'mul': $compilableExpression = new MulOperator(); break; case 'div': $compilableExpression = new DivOperator(); break; case 'mod': $compilableExpression = new ModOperator(); break; case 'and': $compilableExpression = new AndOperator(); break; case 'or': $compilableExpression = new OrOperator(); break; case 'bitwise_and': $compilableExpression = new BitwiseAndOperator(); break; case 'bitwise_or': $compilableExpression = new BitwiseOrOperator(); break; case 'bitwise_xor': $compilableExpression = new BitwiseXorOperator(); break; case 'bitwise_shiftleft': $compilableExpression = new ShiftLeftOperator(); break; case 'bitwise_shiftright': $compilableExpression = new ShiftRightOperator(); break; case 'concat': $expr = new ConcatOperator(); $expr->setExpectReturn($this->expecting, $this->expectingVariable); return $expr->compile($expression, $compilationContext); case 'irange': $compilableExpression = new RangeInclusiveOperator(); break; case 'erange': $compilableExpression = new RangeExclusiveOperator(); break; case 'list': if ('list' == $expression['left']['type']) { $compilationContext->logger->warning( 'Unnecessary extra parentheses', ['extra-parentheses', $expression] ); } $numberPrints = $compilationContext->codePrinter->getNumberPrints(); $expr = new self($expression['left']); $expr->setExpectReturn($this->expecting, $this->expectingVariable); $resolved = $expr->compile($compilationContext); if (($compilationContext->codePrinter->getNumberPrints() - $numberPrints) <= 1) { if (str_contains($resolved->getCode(), ' ')) { return new CompiledExpression( $resolved->getType(), '(' . $resolved->getCode() . ')', $expression ); } } return $resolved; case 'cast': $compilableExpression = new CastOperator(); break; case 'type-hint': $expr = new TypeHintOperator(); $expr->setReadOnly($this->isReadOnly()); $expr->setExpectReturn($this->expecting, $this->expectingVariable); return $expr->compile($expression, $compilationContext); case 'instanceof': $compilableExpression = new InstanceOfOperator(); break; case 'clone': $compilableExpression = new CloneOperator(); break; case 'ternary': $compilableExpression = new TernaryOperator(); break; case 'short-ternary': $expr = new ShortTernaryOperator(); $expr->setReadOnly($this->isReadOnly()); $expr->setExpectReturn($this->expecting, $this->expectingVariable); return $expr->compile($expression, $compilationContext); case 'likely': if (!$this->evalMode) { throw new CompilerException( "'likely' operator can only be used in evaluation expressions", $expression ); } $expr = new LikelyOperator(); $expr->setReadOnly($this->isReadOnly()); return $expr->compile($expression, $compilationContext); case 'unlikely': if (!$this->evalMode) { throw new CompilerException( "'unlikely' operator can only be used in evaluation expressions", $expression ); } $expr = new UnlikelyOperator(); $expr->setReadOnly($this->isReadOnly()); return $expr->compile($expression, $compilationContext); case 'typeof': $compilableExpression = new TypeOfOperator(); break; case 'require': $compilableExpression = new RequireOperator(); break; case 'require_once': $compilableExpression = new RequireOnceOperator(); break; case 'closure': $compilableExpression = new Closure(); break; case 'closure-arrow': $compilableExpression = new ClosureArrow(); break; case 'reference': $compilableExpression = new Reference(); break; default: throw new CompilerException('Unknown expression: ' . $type, $expression); } $compilableExpression->setReadOnly($this->isReadOnly()); $compilableExpression->setExpectReturn($this->expecting, $this->expectingVariable); return $compilableExpression->compile($expression, $compilationContext); }
Resolves an expression. @throws CompilerException|Exception @throws Exception @throws ReflectionException
compile
php
zephir-lang/zephir
src/Expression.php
https://github.com/zephir-lang/zephir/blob/master/src/Expression.php
MIT
public function getExpectingVariable(): ?Variable { return $this->expectingVariable; }
Returns the variable which is expected to return the result of the expression evaluation.
getExpectingVariable
php
zephir-lang/zephir
src/Expression.php
https://github.com/zephir-lang/zephir/blob/master/src/Expression.php
MIT
public function isExpectingReturn(): bool { return $this->expecting; }
Checks if the returned value by the expression is expected to be assigned to an external symbol.
isExpectingReturn
php
zephir-lang/zephir
src/Expression.php
https://github.com/zephir-lang/zephir/blob/master/src/Expression.php
MIT
public function isNoisy(): bool { return $this->noisy; }
Checks whether the expression must be resolved in "noisy" mode.
isNoisy
php
zephir-lang/zephir
src/Expression.php
https://github.com/zephir-lang/zephir/blob/master/src/Expression.php
MIT
public function isReadOnly(): bool { return $this->readOnly; }
Checks if the result of the evaluated expression is read only.
isReadOnly
php
zephir-lang/zephir
src/Expression.php
https://github.com/zephir-lang/zephir/blob/master/src/Expression.php
MIT
public function setEvalMode(bool $evalMode): void { $this->evalMode = $evalMode; }
Sets if the expression is being evaluated in an evaluation like the ones in 'if' and 'while' statements.
setEvalMode
php
zephir-lang/zephir
src/Expression.php
https://github.com/zephir-lang/zephir/blob/master/src/Expression.php
MIT
public function setExpectReturn(bool $expecting, ?Variable $expectingVariable = null): void { $this->expecting = $expecting; $this->expectingVariable = $expectingVariable; }
Sets if the variable must be resolved into a direct variable symbol create a temporary value or ignore the return value.
setExpectReturn
php
zephir-lang/zephir
src/Expression.php
https://github.com/zephir-lang/zephir/blob/master/src/Expression.php
MIT
public function setNoisy(bool $noisy): void { $this->noisy = $noisy; }
Sets whether the expression must be resolved in "noisy" mode.
setNoisy
php
zephir-lang/zephir
src/Expression.php
https://github.com/zephir-lang/zephir/blob/master/src/Expression.php
MIT
public function setReadOnly(bool $readOnly): void { $this->readOnly = $readOnly; }
Sets if the result of the evaluated expression is read only.
setReadOnly
php
zephir-lang/zephir
src/Expression.php
https://github.com/zephir-lang/zephir/blob/master/src/Expression.php
MIT
public static function addOptimizerDir($directory): void { self::$optimizerDirectories[] = $directory; }
Appends an optimizer directory to the directory list. @param string $directory
addOptimizerDir
php
zephir-lang/zephir
src/FunctionCall.php
https://github.com/zephir-lang/zephir/blob/master/src/FunctionCall.php
MIT
public function compile(Expression $expr, CompilationContext $compilationContext) { $this->expression = $expr; $expression = $expr->getExpression(); return match ($expression['call-type']) { self::CALL_NORMAL => $this->_callNormal($expression, $compilationContext), self::CALL_DYNAMIC => $this->callDynamic($expression, $compilationContext), default => new CompiledExpression('null', null, $expression), }; }
Compiles a function. @throws Exception @throws ReflectionException
compile
php
zephir-lang/zephir
src/FunctionCall.php
https://github.com/zephir-lang/zephir/blob/master/src/FunctionCall.php
MIT
public function functionExists(string $functionName, CompilationContext $context): bool { if (function_exists($functionName)) { return true; } if ($this->isBuiltInFunction($functionName)) { return true; } $internalName = ['f__' . $functionName]; if (isset($context->classDefinition)) { $lowerNamespace = strtolower($context->classDefinition->getNamespace()); $prefix = 'f_' . str_replace('\\', '_', $lowerNamespace); $internalName[] = $prefix . '_' . $functionName; } foreach ($internalName as $name) { if (isset($context->compiler->functionDefinitions[$name])) { return true; } } return false; }
Checks if a function exists or is a built-in Zephir function.
functionExists
php
zephir-lang/zephir
src/FunctionCall.php
https://github.com/zephir-lang/zephir/blob/master/src/FunctionCall.php
MIT
public function getReflector(string $funcName): ?ReflectionFunction { /** * Check if the optimizer is already cached */ if (!isset(self::$functionReflection[$funcName])) { try { $reflectionFunction = new ReflectionFunction($funcName); } catch (ReflectionException) { $reflectionFunction = null; } self::$functionReflection[$funcName] = $reflectionFunction; $this->reflection = $reflectionFunction; return $reflectionFunction; } $reflectionFunction = self::$functionReflection[$funcName]; $this->reflection = $reflectionFunction; return $reflectionFunction; }
Process the ReflectionFunction for the specified function name.
getReflector
php
zephir-lang/zephir
src/FunctionCall.php
https://github.com/zephir-lang/zephir/blob/master/src/FunctionCall.php
MIT
public function isBuiltInFunction(string $functionName): bool { return match ($functionName) { 'memstr', 'get_class_ns', 'get_ns_class', 'camelize', 'uncamelize', 'starts_with', 'ends_with', 'prepare_virtual_path', 'create_instance', 'create_instance_params', 'create_symbol_table', 'globals_get', 'globals_set', 'merge_append', 'get_class_lower' => true, default => false, }; }
Checks if the function is a built-in provided by Zephir.
isBuiltInFunction
php
zephir-lang/zephir
src/FunctionCall.php
https://github.com/zephir-lang/zephir/blob/master/src/FunctionCall.php
MIT
protected function isReadOnly($funcName, array $expression): bool { if ($this->isBuiltInFunction($funcName)) { return false; } /** * These functions are supposed to be read-only, but they change parameters ref-count */ switch ($funcName) { case 'min': case 'max': case 'array_fill': case 'array_pad': case 'call_user_func': case 'call_user_func_array': return false; } $reflector = $this->getReflector($funcName); if (!$reflector instanceof ReflectionFunction) { return false; } $messageFormat = "The number of parameters passed is lesser than the number of required parameters by '%s'"; if (isset($expression['parameters'])) { /** * Check if the number of parameters. */ $numberParameters = count($expression['parameters']); if ( 'unpack' == $funcName && ( 0 == version_compare(PHP_VERSION, '7.1.0') || 0 == version_compare(PHP_VERSION, '7.1.1') ) ) { if ($numberParameters < 2) { throw new CompilerException(sprintf($messageFormat, $funcName), $expression); } } else { if ($numberParameters < $reflector->getNumberOfRequiredParameters()) { throw new CompilerException(sprintf($messageFormat, $funcName), $expression); } } } else { if ($reflector->getNumberOfRequiredParameters() > 0) { throw new CompilerException(sprintf($messageFormat, $funcName), $expression); } } if ($reflector->getNumberOfParameters() > 0) { foreach ($reflector->getParameters() as $parameter) { if ($parameter->isPassedByReference()) { return false; } } } return true; }
This method gets the reflection of a function to check if any of their parameters are passed by reference Built-in functions rarely change the parameters if they aren't passed by reference. @throws CompilerException
isReadOnly
php
zephir-lang/zephir
src/FunctionCall.php
https://github.com/zephir-lang/zephir/blob/master/src/FunctionCall.php
MIT
protected function markReferences( $funcName, $parameters, CompilationContext $compilationContext, &$references, $expression ): void { if ($this->isBuiltInFunction($funcName)) { return; } $reflector = $this->getReflector($funcName); if ($reflector) { $numberParameters = count($parameters); if ($numberParameters > 0) { $n = 1; $funcParameters = $reflector->getParameters(); foreach ($funcParameters as $parameter) { if ($numberParameters >= $n) { if ($parameter->isPassedByReference()) { /* TODO hack, fix this better */ if ('&' === $parameters[$n - 1][0]) { $parameters[$n - 1] = substr($parameters[$n - 1], 1); } if (!preg_match('/^[a-zA-Z0-9$_]+$/', $parameters[$n - 1])) { $compilationContext->logger->warning( 'Cannot mark complex expression as reference', ['invalid-reference', $expression] ); continue; } $variable = $compilationContext->symbolTable->getVariable($parameters[$n - 1]); if ($variable) { $variable->setDynamicTypes('undefined'); $referenceSymbol = $compilationContext->backend->getVariableCode($variable); $compilationContext->codePrinter->output('ZEPHIR_MAKE_REF(' . $referenceSymbol . ');'); $references[] = $parameters[$n - 1]; } } } ++$n; } } } }
Once the function processes the parameters we should mark specific parameters to be passed by reference. @param string $funcName @param array $parameters @param CompilationContext $compilationContext @param array $references @param array $expression
markReferences
php
zephir-lang/zephir
src/FunctionCall.php
https://github.com/zephir-lang/zephir/blob/master/src/FunctionCall.php
MIT
protected function optimize(string $funcName, array $expression, Call $call, CompilationContext $compilationContext) { $optimizer = false; /** * Check if the optimizer is already cached */ if (!isset(self::$optimizers[$funcName])) { $camelizeFunctionName = Name::camelize($funcName); /** * Check every optimizer directory for an optimizer */ foreach (self::$optimizerDirectories as $directory) { $path = $directory . DIRECTORY_SEPARATOR . $camelizeFunctionName . 'Optimizer.php'; $className = 'Zephir\Optimizers\FunctionCall\\' . $camelizeFunctionName . 'Optimizer'; if (file_exists($path)) { if (!class_exists($className, false)) { require_once $path; } if (!class_exists($className, false)) { throw new Exception("Class {$className} cannot be loaded"); } $optimizer = new $className(); if (!($optimizer instanceof OptimizerAbstract)) { throw new Exception("Class {$className} must be instance of OptimizerAbstract"); } break; } } self::$optimizers[$funcName] = $optimizer; } else { $optimizer = self::$optimizers[$funcName]; } if ($optimizer) { return $optimizer->optimize($expression, $call, $compilationContext); } return false; }
Tries to find specific a specialized optimizer for function calls. @param string $funcName @param array $expression @param Call $call @param CompilationContext $compilationContext @return bool|mixed @throws Exception
optimize
php
zephir-lang/zephir
src/FunctionCall.php
https://github.com/zephir-lang/zephir/blob/master/src/FunctionCall.php
MIT
public function getInternalName(): string { return ($this->isGlobal() ? 'g_' : 'f_') . str_replace('\\', '_', $this->namespace) . '_' . $this->getName(); }
Get the internal name used in generated C code.
getInternalName
php
zephir-lang/zephir
src/FunctionDefinition.php
https://github.com/zephir-lang/zephir/blob/master/src/FunctionDefinition.php
MIT
public function isTemporal(): bool { return false; }
Check if the global constant is temporal.
isTemporal
php
zephir-lang/zephir
src/GlobalConstant.php
https://github.com/zephir-lang/zephir/blob/master/src/GlobalConstant.php
MIT
public function add(string $path, int $position = 0): void { if (!$position) { $this->headers[$path] = $path; } elseif ($position === self::POSITION_FIRST) { $this->headersFirst[$path] = $path; } elseif ($position === self::POSITION_LAST) { $this->headersLast[$path] = $path; } }
Adds a header path to the manager. @throws InvalidArgumentException
add
php
zephir-lang/zephir
src/HeadersManager.php
https://github.com/zephir-lang/zephir/blob/master/src/HeadersManager.php
MIT
public function compile(Expression $expr, CompilationContext $compilationContext): mixed { $expression = $expr->getExpression(); $exprVariable = new Expression($expression['variable']); $exprVariable->setReadOnly(true); $exprCompiledVariable = $exprVariable->compile($compilationContext); $builtInType = false; switch ($exprCompiledVariable->getType()) { case 'variable': $variableVariable = $compilationContext->symbolTable->getVariableForRead( $exprCompiledVariable->getCode(), $compilationContext, $expression ); switch ($variableVariable->getType()) { case 'variable': $caller = $variableVariable; break; default: /* Check if there is a built-in type optimizer available */ $builtInTypeClass = 'Zephir\Types\\' . ucfirst($variableVariable->getType()) . 'Type'; if (class_exists($builtInTypeClass)) { /** * @var AbstractType $builtInType */ $builtInType = new $builtInTypeClass(); $caller = $exprCompiledVariable; } else { throw new CompilerException( 'Methods cannot be called on variable type: ' . $variableVariable->getType(), $expression ); } } break; default: /* Check if there is a built-in type optimizer available */ $builtInTypeClass = 'Zephir\Types\\' . ucfirst($exprCompiledVariable->getType()) . 'Type'; if (class_exists($builtInTypeClass)) { $builtInType = new $builtInTypeClass(); $caller = $exprCompiledVariable; } else { throw new CompilerException( 'Cannot use expression: ' . $exprCompiledVariable->getType() . ' as method caller', $expression['variable'] ); } } $codePrinter = $compilationContext->codePrinter; $type = $expression['call-type']; /** * In normal method calls and dynamic string method calls we just use the name given by the user */ if (self::CALL_NORMAL == $type || self::CALL_DYNAMIC_STRING == $type) { $methodName = strtolower($expression['name']); } else { $variableMethod = $compilationContext->symbolTable->getVariableForRead( $expression['name'], $compilationContext, $expression ); if (is_object($builtInType)) { throw new CompilerException( 'Dynamic method invocation for type: ' . $variableMethod->getType() . ' is not supported', $expression ); } if ($variableMethod->isNotVariableAndString()) { throw CompilerException::cannotUseVariableTypeAs( $variableMethod, 'as a dynamic method name', $expression ); } } $symbolVariable = null; /** * Create temporary variable if needed. */ $mustInit = false; $isExpecting = $expr->isExpectingReturn(); if ($isExpecting) { $symbolVariable = $expr->getExpectingVariable(); if (is_object($symbolVariable)) { $readDetector = new ReadDetector(); if ($caller == $symbolVariable || $readDetector->detect($symbolVariable->getName(), $expression)) { $symbolVariable = $compilationContext->symbolTable->getTempVariableForObserveOrNullify( 'variable', $compilationContext, ); } else { $mustInit = true; } } else { $symbolVariable = $compilationContext->symbolTable->getTempVariableForObserveOrNullify( 'variable', $compilationContext, ); } } /** * Method calls only return zvals, so we need to validate the target variable is also a zval */ if (!$builtInType) { if ($isExpecting) { $this->checkNotVariable($symbolVariable, $expression); /** * At this point, we don't know the exact dynamic type returned by the method call */ $symbolVariable->setDynamicTypes('undefined'); } } else { return $builtInType->invokeMethod($methodName, $caller, $compilationContext, $this, $expression); } $check = true; if (isset($expression['check'])) { $check = $expression['check']; } /** * Try to check if the method exist in the callee, only when method call is self::CALL_NORMAL */ if (self::CALL_NORMAL == $type) { if ('this' == $variableVariable->getRealName()) { $classDefinition = $compilationContext->classDefinition; if (!$classDefinition->hasMethod($methodName)) { if ($check) { $found = false; if ($classDefinition->isAbstract()) { $interfaces = $classDefinition->getImplementedInterfaces(); } else { $interfaces = null; } if (is_array($interfaces)) { $compiler = $compilationContext->compiler; foreach ($interfaces as $interface) { $classInterfaceDefinition = $compiler->getClassDefinition($interface); if (!$classInterfaceDefinition) { $classInterfaceDefinition = $compiler->getInternalClassDefinition($interface); if (!$classInterfaceDefinition) { throw new CompilerException( "Couldn't locate internal or external interface: " . $interface, $expression ); } } if ($classInterfaceDefinition->hasMethod($methodName)) { $found = true; $classMethod = $classInterfaceDefinition->getMethod($methodName); break; } } } if (!$found) { $possibleMethod = $classDefinition->getPossibleMethodName($expression['name']); if ($possibleMethod && $expression['name'] != $possibleMethod) { throw new CompilerException( sprintf( "Class '%s' does not implement method: '%s'. Did you mean '%s'?", $classDefinition->getCompleteName(), $expression['name'], $possibleMethod ), $expression ); } throw new CompilerException( sprintf( "Class '%s' does not implement method: '%s'", $classDefinition->getCompleteName(), $expression['name'] ), $expression ); } } } else { if ($check) { $classMethod = $classDefinition->getMethod($methodName); } } if ($check) { /* * Private methods must be called in their declaration scope */ if ($classMethod->isPrivate()) { if ($classMethod->getClassDefinition() !== $classDefinition) { throw new CompilerException( "Cannot call private method '" . $expression['name'] . "' out of its scope", $expression ); } } /* * Try to produce an exception if method is called with a wrong number of parameters */ if (isset($expression['parameters'])) { $callNumberParameters = count($expression['parameters']); } else { $callNumberParameters = 0; } $expectedNumberParameters = $classMethod->getNumberOfRequiredParameters(); if (!$expectedNumberParameters && $callNumberParameters > 0) { $numberParameters = $classMethod->getNumberOfParameters(); if ($callNumberParameters > $numberParameters) { throw new CompilerException( sprintf( "Method '%s::%s' called with a wrong number of parameters, " . 'the method has: %d, passed: %d', $classDefinition->getCompleteName(), $expression['name'], $expectedNumberParameters, $callNumberParameters ), $expression ); } } if ($callNumberParameters < $expectedNumberParameters) { throw new CompilerException( sprintf( "Method '%s::%s' called with a wrong number of parameters, " . 'the method has: %d, passed: %d', $classDefinition->getCompleteName(), $expression['name'], $expectedNumberParameters, $callNumberParameters ), $expression ); } $method = $classMethod; } } else { /* * Variables whose dynamic type is 'object' can be used * to determine method existence in compile time */ if ($check && $variableVariable->hasAnyDynamicType('object')) { $classTypes = $variableVariable->getClassTypes(); if (count($classTypes)) { $numberImplemented = 0; $compiler = $compilationContext->compiler; foreach ($classTypes as $classType) { if ( $compiler->isClass($classType) || $compiler->isInterface($classType) || $compiler->isBundledClass($classType) || $compiler->isBundledInterface($classType) ) { if ($compiler->isClass($classType) || $compiler->isInterface($classType)) { $classDefinition = $compiler->getClassDefinition($classType); } else { $classDefinition = $compiler->getInternalClassDefinition($classType); } if (!$classDefinition) { throw new CompilerException( 'Cannot locate class definition for class ' . $classType, $expression ); } if (!$classDefinition->hasMethod($methodName)) { if (!$classDefinition->isInterface()) { if (1 == count($classTypes)) { throw new CompilerException( sprintf( "Class '%s' does not implement method: '%s'", $classType, $expression['name'] ), $expression ); } } continue; } $method = $classDefinition->getMethod($methodName); /* * Private methods must be called in their declaration scope */ if ($method->isPrivate()) { if ($method->getClassDefinition() != $classDefinition) { throw new CompilerException( sprintf( "Cannot call private method '%s' out of its scope", $expression['name'] ), $expression ); } } /* * Check visibility for protected methods */ if ( $method->isProtected() && $method->getClassDefinition() != $classDefinition && $method->getClassDefinition() != $classDefinition->getExtendsClass() ) { throw new CompilerException( sprintf( "Cannot call protected method '%s' out of its scope", $expression['name'] ), $expression ); } /** * Try to produce an exception if a method is called with a wrong number of parameters * We only check extension parameters if methods are extension methods * Internal methods may have invalid Reflection information */ if ($method instanceof Method && !$method->isBundled()) { if (isset($expression['parameters'])) { $callNumberParameters = count($expression['parameters']); } else { $callNumberParameters = 0; } $classMethod = $classDefinition->getMethod($methodName); $expectedNumberParameters = $classMethod->getNumberOfRequiredParameters(); if (!$expectedNumberParameters && $callNumberParameters > 0) { $numberParameters = $classMethod->getNumberOfParameters(); if ($callNumberParameters > $numberParameters) { $className = $classDefinition->getCompleteName(); throw new CompilerException( sprintf( "Method '%s::%s' called with a wrong number of parameters, " . 'the method has: %d, passed: %s', $className, $expression['name'], $expectedNumberParameters, $callNumberParameters ), $expression ); } } if ($callNumberParameters < $expectedNumberParameters) { throw new CompilerException( sprintf( "Method '%s::%s' called with a wrong number of parameters, " . 'the method has: %d, passed: %d', $classDefinition->getCompleteName(), $expression['name'], $expectedNumberParameters, $callNumberParameters ), $expression ); } } /** * The method is checked in the first class that implements the method * We could probably have collisions here */ ++$numberImplemented; break; } else { ++$numberImplemented; $compilationContext->logger->warning( 'Class "' . $classType . '" does not exist at compile time', ['nonexistent-class', $expression] ); } } if (0 == $numberImplemented) { if (!$classDefinition->isInterface()) { if (count($classTypes) > 1) { throw new CompilerException( sprintf( "None of classes: '%s' implement method: '%s'", implode(' or ', $classTypes), $expression['name'] ), $expression ); } else { throw new CompilerException( sprintf( "Class '%s' does not implement method: '%s'", $classTypes[0], $expression['name'] ), $expression ); } } else { // TODO:, raise an exception here? } } } } } } if (isset($method)) { $this->reflection = $method; } /** * Transfer the return type-hint to the returned variable */ if ($isExpecting && isset($method)) { if ($method instanceof Method) { if ($method->isVoid()) { throw new CompilerException( sprintf( "Method '%s::%s' is marked as '%s' and it does not return anything", $classDefinition->getCompleteName(), $expression['name'], Types::T_VOID ), $expression ); } $returnClassTypes = $method->getReturnClassTypes(); if (null !== $returnClassTypes) { $symbolVariable->setDynamicTypes('object'); foreach ($returnClassTypes as &$returnClassType) { $returnClassType = $compilationContext->getFullName($returnClassType); } $symbolVariable->setClassTypes($returnClassTypes); } $returnTypes = $method->getReturnTypes(); if (null !== $returnTypes) { foreach ($returnTypes as $dataType => $returnType) { $symbolVariable->setDynamicTypes($dataType); } } } } /** * Some parameters in internal methods receive parameters as references */ if (isset($expression['parameters'])) { $references = []; if (self::CALL_NORMAL == $type || self::CALL_DYNAMIC_STRING == $type) { if (isset($method)) { if ($method instanceof ReflectionMethod) { $position = 0; foreach ($method->getParameters() as $parameter) { if ($parameter->isPassedByReference()) { $references[$position] = true; } ++$position; } } } } } /** * Include fcall header */ $compilationContext->headersManager->add('kernel/fcall'); /** * Call methods must grown the stack */ $compilationContext->symbolTable->mustGrownStack(true); /** * Mark references */ $params = []; if (isset($expression['parameters'])) { $params = $this->getResolvedParams( $expression['parameters'], $compilationContext, $expression, ); if (count($references)) { foreach ($params as $position => $param) { if (isset($references[$position])) { $compilationContext->codePrinter->output('Z_SET_ISREF_P(' . $param . ');'); } } } // We check here if a correct parameter type is passed to the called method if (self::CALL_NORMAL == $type) { if (isset($method) && $method instanceof Method && isset($expression['parameters'])) { $resolvedTypes = $this->getResolvedTypes(); $resolvedDynamicTypes = $this->getResolvedDynamicTypes(); foreach ($method->getParameters() as $n => $parameter) { if (isset($parameter['data-type'])) { if (!isset($resolvedTypes[$n])) { continue; } /** * If the passed parameter is different to the expected type we show a warning */ if ($resolvedTypes[$n] != $parameter['data-type']) { $template = sprintf( 'Passing possible incorrect type for parameter: %s::%s(%s), ' . 'passing: %s, expecting: %s', $classDefinition->getCompleteName(), $method->getName(), $parameter['name'], $resolvedTypes[$n], $parameter['data-type'] ); switch ($resolvedTypes[$n]) { case 'bool': case 'boolean': switch ($parameter['data-type']) { /* compatible types */ case 'bool': case 'boolean': case 'variable': break; default: $compilationContext->logger->warning( $template, ['possible-wrong-parameter', $expression] ); break; } break; case 'array': switch ($parameter['data-type']) { /* compatible types */ case 'array': case 'variable': break; case 'callable': /* * Array can be a callable type, example: [$this, "method"] * * TODO: we need to check this array if can... */ break; default: $compilationContext->logger->warning( $template, ['possible-wrong-parameter', $expression] ); break; } break; case 'callable': switch ($parameter['data-type']) { /* compatible types */ case 'callable': case 'variable': break; default: $compilationContext->logger->warning( $template, ['possible-wrong-parameter', $expression] ); break; } break; case 'string': switch ($parameter['data-type']) { /* compatible types */ case 'string': case 'variable': break; default: $compilationContext->logger->warning( $template, ['possible-wrong-parameter', $expression] ); break; } break; /** * Passing polymorphic variables to static typed parameters * could lead to potential unexpected type coercions */ case 'variable': if ($resolvedDynamicTypes[$n] != $parameter['data-type']) { if ('undefined' == $resolvedDynamicTypes[$n]) { $compilationContext->logger->warning( sprintf( 'Passing possible incorrect type for parameter: %s::%s(%s), ' . 'passing: undefined, expecting: %s', $classDefinition->getCompleteName(), $method->getName(), $parameter['name'], $parameter['data-type'] ), ['possible-wrong-parameter-undefined', $expression] ); } } break; } } } } } } } // Add the last call status to the current symbol table $this->addCallStatusFlag($compilationContext); // Initialize non-temporary variables if ($mustInit) { $symbolVariable->setMustInitNull(true); $symbolVariable->trackVariant($compilationContext); } // Generate the code according to the call type if (self::CALL_NORMAL == $type || self::CALL_DYNAMIC_STRING == $type) { $realMethod = $this->getRealCalledMethod($compilationContext, $variableVariable, $methodName); $isInternal = false; if (is_object($realMethod[1])) { $realMethod[1] = $realMethod[1]->getOptimizedMethod(); $method = $realMethod[1]; $isInternal = $realMethod[1]->isInternal(); if ($isInternal && $realMethod[0] > 1) { throw new CompilerException( "Cannot resolve method: '" . $expression['name'] . "' in polymorphic variable", $expression ); } } if (!$isInternal) { // Check if the method call can have an inline cache $methodCache = $compilationContext->cacheManager->getMethodCache(); $cachePointer = $methodCache->get( $compilationContext, $methodName, $variableVariable ); $compilationContext->backend->callMethod( $isExpecting ? $symbolVariable : null, $variableVariable, $methodName, $cachePointer, count($params) ? $params : null, $compilationContext ); } else { // TODO: also move to backend if ($isExpecting) { $symbolCode = $compilationContext->backend->getVariableCode($symbolVariable); } $variableCode = $compilationContext->backend->getVariableCode($variableVariable); $paramCount = count($params); $paramsStr = $paramCount ? ', ' . implode(', ', $params) : ''; if ($isExpecting) { if ('return_value' == $symbolVariable->getName()) { $macro = $compilationContext->backend->getFcallManager()->getMacro(false, 1, $paramCount); $codePrinter->output( $macro . '(' . $variableCode . ', ' . $method->getInternalName() . $paramsStr . ');' ); } else { $macro = $compilationContext->backend->getFcallManager()->getMacro(false, 2, $paramCount); $codePrinter->output( $macro . '(' . $symbolCode . ', ' . $variableCode . ', ' . $method->getInternalName( ) . $paramsStr . ');' ); } } else { $macro = $compilationContext->backend->getFcallManager()->getMacro(false, 0, $paramCount); $codePrinter->output( $macro . '(' . $variableCode . ', ' . $method->getInternalName() . $paramsStr . ');' ); } } } else { if (self::CALL_DYNAMIC == $type) { switch ($variableMethod->getType()) { case 'string': case 'variable': break; default: throw CompilerException::cannotUseVariableTypeAs( $variableMethod, 'as a method caller', $expression ); } $cachePointer = 'NULL, 0'; $compilationContext->backend->callMethod( $isExpecting ? $symbolVariable : null, $variableVariable, $variableMethod, $cachePointer, count($params) ? $params : null, $compilationContext ); } } // Temporary variables must be copied if they have more than one reference foreach ($this->getMustCheckForCopyVariables() as $checkVariable) { $codePrinter->output('zephir_check_temp_parameter(' . $checkVariable . ');'); } // We can mark temporary variables generated as idle foreach ($this->getTemporalVariables() as $tempVariable) { $tempVariable->setIdle(true); } // Release parameters marked as references if (isset($expression['parameters'])) { if (count($references)) { foreach ($params as $position => $param) { if (isset($references[$position])) { $compilationContext->codePrinter->output('Z_UNSET_ISREF_P(' . $param . ');'); } } } } $this->addCallStatusOrJump($compilationContext); if ($isExpecting) { return new CompiledExpression('variable', $symbolVariable->getRealName(), $expression); } return new CompiledExpression('null', null, $expression); }
Compiles a method call. @throws Exception @throws ReflectionException
compile
php
zephir-lang/zephir
src/MethodCall.php
https://github.com/zephir-lang/zephir/blob/master/src/MethodCall.php
MIT
private function getRealCalledMethod( CompilationContext $compilationContext, Variable $caller, string $methodName ): array { $compiler = $compilationContext->compiler; $numberPoly = 0; $method = null; if ('this' == $caller->getRealName()) { $classDefinition = $compilationContext->classDefinition; if ($classDefinition->hasMethod($methodName)) { ++$numberPoly; $method = $classDefinition->getMethod($methodName); } } else { $classTypes = $caller->getClassTypes(); foreach ($classTypes as $classType) { if ($compiler->isInterface($classType)) { continue; } if ( $compiler->isClass($classType) || $compiler->isBundledClass($classType) || $compiler->isBundledInterface($classType) ) { if ($compiler->isClass($classType)) { $classDefinition = $compiler->getClassDefinition($classType); } else { $classDefinition = $compiler->getInternalClassDefinition($classType); } if (!$classDefinition) { continue; } if ($classDefinition->hasMethod($methodName) && !$classDefinition->isInterface()) { ++$numberPoly; $method = $classDefinition->getMethod($methodName); } } } } return [$numberPoly, $method]; }
Examine internal class information and returns the method called. @throws ReflectionException
getRealCalledMethod
php
zephir-lang/zephir
src/MethodCall.php
https://github.com/zephir-lang/zephir/blob/master/src/MethodCall.php
MIT
public static function fetchFQN( string $class, ?string $namespace = null, ?AliasManager $aliasManager = null ): string { /** * Absolute class/interface name */ if ('\\' === $class[0]) { return substr($class, 1); } /** * If class/interface name not begin with \ * maybe an alias or a sub-namespace */ $firstSepPos = strpos($class, '\\'); if (false !== $firstSepPos) { $baseName = substr($class, 0, $firstSepPos); if ($aliasManager && $aliasManager->isAlias($baseName)) { return $aliasManager->getAlias($baseName) . '\\' . substr($class, $firstSepPos + 1); } } elseif ($aliasManager && $aliasManager->isAlias($class)) { return $aliasManager->getAlias($class); } return $namespace ? $namespace . '\\' . $class : $class; }
Transform class/interface name to Fully qualified path name (FQN) format.
fetchFQN
php
zephir-lang/zephir
src/Name.php
https://github.com/zephir-lang/zephir/blob/master/src/Name.php
MIT
public static function isWindows(): bool { return 0 === stripos(PHP_OS, 'WIN'); }
Checks if currently running under MS Windows.
isWindows
php
zephir-lang/zephir
src/Os.php
https://github.com/zephir-lang/zephir/blob/master/src/Os.php
MIT
public function compile( CompilationContext $compilationContext, ?bool $unreachable = null, int $branchType = Branch::TYPE_UNKNOWN ): Branch { $compilationContext->codePrinter->increaseLevel(); ++$compilationContext->currentBranch; /** * Create a new branch. */ $currentBranch = new Branch(); $currentBranch->setType($branchType); $currentBranch->setUnreachable($unreachable); /** * Activate branch in the branch manager */ $compilationContext->branchManager->addBranch($currentBranch); $this->unreachable = $unreachable; $statements = $this->statements; /** * Reference the block if it belongs to a loop */ if ($this->loop) { $compilationContext->cycleBlocks[] = $this; } $where = ''; if ($compilationContext->classDefinition) { $where = sprintf( 'in %s', $compilationContext->classDefinition->getCompleteName() ); if ($compilationContext->currentMethod) { $where .= sprintf('::%s', $compilationContext->currentMethod->getName()); } } foreach ($statements as $statement) { /** * TODO: Generate GDB hints */ if ($this->debug) { if (isset($statement['file'])) { if ('declare' != $statement['type'] && 'comment' != $statement['type']) { $compilationContext->codePrinter->outputNoIndent( '#line ' . $statement['line'] . ' "' . $statement['file'] . '"' ); } } } /** * Show warnings if code is generated when the 'unreachable state' is 'on' */ if (true === $this->unreachable) { switch ($statement['type']) { case 'echo': $compilationContext->logger->warning( sprintf('Unreachable code %s', $where), ['unreachable-code', $statement['expressions'][0]] ); break; case 'let': $compilationContext->logger->warning( sprintf('Unreachable code %s', $where), ['unreachable-code', $statement['assignments'][0]] ); break; case 'fetch': case 'fcall': case 'mcall': case 'scall': case 'if': case 'while': case 'do-while': case 'switch': case 'for': case 'return': case 'c-block': if (isset($statement['expr'])) { $compilationContext->logger->warning( sprintf('Unreachable code %s', $where), ['unreachable-code', $statement['expr']] ); } else { $compilationContext->logger->warning( sprintf('Unreachable code %s', $where), ['unreachable-code', $statement] ); } break; default: $compilationContext->logger->warning( sprintf('Unreachable code %s', $where), ['unreachable-code', $statement] ); } } switch ($statement['type']) { case 'let': $letStatement = new LetStatement($statement); $letStatement->compile($compilationContext); break; case 'echo': $echoStatement = new EchoStatement($statement); $echoStatement->compile($compilationContext); break; case 'declare': $declareStatement = new DeclareStatement($statement); $declareStatement->compile($compilationContext); break; case 'if': $ifStatement = new IfStatement($statement); $ifStatement->compile($compilationContext); break; case 'while': $whileStatement = new WhileStatement($statement); $whileStatement->compile($compilationContext); break; case 'do-while': $doWhileStatement = new DoWhileStatement($statement); $doWhileStatement->compile($compilationContext); break; case 'switch': $switchStatement = new SwitchStatement($statement); $switchStatement->compile($compilationContext); break; case 'for': $forStatement = new ForStatement($statement); $forStatement->compile($compilationContext); break; case 'return': $returnStatement = new ReturnStatement($statement); $returnStatement->compile($compilationContext); $this->unreachable = true; break; case 'require': $requireStatement = new RequireStatement($statement); $requireStatement->compile($compilationContext); break; case 'require_once': $requireOnceStatement = new RequireOnceStatement($statement); $requireOnceStatement->compile($compilationContext); break; case 'loop': $loopStatement = new LoopStatement($statement); $loopStatement->compile($compilationContext); break; case 'break': $breakStatement = new BreakStatement($statement); $breakStatement->compile($compilationContext); $this->unreachable = true; break; case 'continue': $continueStatement = new ContinueStatement($statement); $continueStatement->compile($compilationContext); $this->unreachable = true; break; case 'unset': $unsetStatement = new UnsetStatement($statement); $unsetStatement->compile($compilationContext); break; case 'throw': $throwStatement = new ThrowStatement($statement); $throwStatement->compile($compilationContext); $this->unreachable = true; break; case 'try-catch': $throwStatement = new TryCatchStatement($statement); $throwStatement->compile($compilationContext); $this->unreachable = false; break; case 'fetch': $expr = new Expression($statement['expr']); $expr->setExpectReturn(false); $compiledExpression = $expr->compile($compilationContext); $compilationContext->codePrinter->output($compiledExpression->getCode() . ';'); break; case 'mcall': $methodCall = new MethodCall(); $expr = new Expression($statement['expr']); $expr->setExpectReturn(false); $methodCall->compile($expr, $compilationContext); break; case 'fcall': $functionCall = new FunctionCall(); $expr = new Expression($statement['expr']); $expr->setExpectReturn(false); $compiledExpression = $functionCall->compile($expr, $compilationContext); switch ($compiledExpression->getType()) { case 'int': case 'double': case 'uint': case 'long': case 'ulong': case 'char': case 'uchar': case 'bool': $compilationContext->codePrinter->output($compiledExpression->getCode() . ';'); break; } break; case 'scall': $methodCall = new StaticCall(); $expr = new Expression($statement['expr']); $expr->setExpectReturn(false); $methodCall->compile($expr, $compilationContext); break; case 'cblock': $compilationContext->codePrinter->output($statement['value']); break; case 'comment': case 'empty': break; default: throw new Exception('Unsupported statement: ' . $statement['type']); } if ('comment' != $statement['type']) { $this->lastStatement = $statement; } } /** * Reference the block if it belongs to a loop */ if ($this->loop) { array_pop($compilationContext->cycleBlocks); } /** * Traverses temporal variables created in a specific branch * marking them as idle */ $compilationContext->symbolTable->markTemporalVariablesIdle($compilationContext); $compilationContext->branchManager->removeBranch($currentBranch); --$compilationContext->currentBranch; $compilationContext->codePrinter->decreaseLevel(); return $currentBranch; }
@param CompilationContext $compilationContext @param bool $unreachable @param int $branchType @return Branch @throws Exception @throws ReflectionException
compile
php
zephir-lang/zephir
src/StatementsBlock.php
https://github.com/zephir-lang/zephir/blob/master/src/StatementsBlock.php
MIT
public function getLastStatement() { return $this->lastStatement; }
Returns the last statement executed. @return array|null
getLastStatement
php
zephir-lang/zephir
src/StatementsBlock.php
https://github.com/zephir-lang/zephir/blob/master/src/StatementsBlock.php
MIT
public function getLastStatementType() { return $this->lastStatement['type']; }
Returns the type of the last statement executed. @return string
getLastStatementType
php
zephir-lang/zephir
src/StatementsBlock.php
https://github.com/zephir-lang/zephir/blob/master/src/StatementsBlock.php
MIT
public function getMutateGatherer(bool $pass = false): MutateGathererPass { if (!$this->mutateGatherer) { $this->mutateGatherer = new MutateGathererPass(); } if ($pass) { $this->mutateGatherer->pass($this); } return $this->mutateGatherer; }
Create/Returns a mutate gatherer pass for this block.
getMutateGatherer
php
zephir-lang/zephir
src/StatementsBlock.php
https://github.com/zephir-lang/zephir/blob/master/src/StatementsBlock.php
MIT
public function getStatements(): array { return $this->statements; }
Returns the statements in the block.
getStatements
php
zephir-lang/zephir
src/StatementsBlock.php
https://github.com/zephir-lang/zephir/blob/master/src/StatementsBlock.php
MIT
public function isEmpty(): bool { return 0 === count($this->statements); }
Checks whether the block is empty or not.
isEmpty
php
zephir-lang/zephir
src/StatementsBlock.php
https://github.com/zephir-lang/zephir/blob/master/src/StatementsBlock.php
MIT
public function isLoop(bool $loop): static { $this->loop = $loop; return $this; }
Sets whether the statements block belongs to a loop.
isLoop
php
zephir-lang/zephir
src/StatementsBlock.php
https://github.com/zephir-lang/zephir/blob/master/src/StatementsBlock.php
MIT
public function compile(Expression $expr, CompilationContext $compilationContext): CompiledExpression { $expression = $expr->getExpression(); $methodName = strtolower($expression['name']); $dynamicMethod = $expression['dynamic'] ?? false; $symbolVariable = null; /** * Create temporary variable if needed. */ $mustInit = false; $isExpecting = $expr->isExpectingReturn(); if ($isExpecting) { $symbolVariable = $expr->getExpectingVariable(); if (is_object($symbolVariable)) { $readDetector = new ReadDetector(); if ($readDetector->detect($symbolVariable->getName(), $expression)) { $symbolVariable = $compilationContext->symbolTable->getTempVariableForObserveOrNullify( 'variable', $compilationContext ); } else { $mustInit = true; } } else { $symbolVariable = $compilationContext->symbolTable->getTempVariableForObserveOrNullify( 'variable', $compilationContext ); } } /** * Method calls only return zvals, so we need to validate the target variable is also a zval */ if ($isExpecting) { /** * At this point, we don't know the exact dynamic type returned by the static method call */ $symbolVariable->setDynamicTypes('undefined'); $this->checkNotVariable($symbolVariable, $expression); } /** * Include fcall header */ $compilationContext->headersManager->add('kernel/fcall'); $compiler = $compilationContext->compiler; $dynamicClass = $expression['dynamic-class']; if (!$dynamicClass) { $className = $expression['class']; $classDefinition = false; if (!in_array($className, ['self', 'static', 'parent'])) { if (is_string($className)) { $className = $compilationContext->getFullName($className); if ($compiler->isClass($className)) { $classDefinition = $compiler->getClassDefinition($className); } else { if ($compiler->isBundledClass($className)) { $classDefinition = $compiler->getInternalClassDefinition($className); } else { throw new CompilerException('Class name: ' . $className . ' does not exist', $expression); } } } else { foreach ($className as $singleClass) { $className = $compilationContext->getFullName($singleClass); if ($compiler->isClass($singleClass)) { $classDefinition = $compiler->getClassDefinition($singleClass); } else { throw new CompilerException('Class name: ' . $className . ' does not exist', $expression); } } } } else { $classDefinition = $compilationContext->classDefinition; if ('parent' === $className) { $extendsClass = $classDefinition->getExtendsClass(); if (!$extendsClass) { throw new CompilerException( 'Cannot call method "' . $methodName . '" on parent because class ' . $classDefinition->getCompleteName() . ' does not extend any class', $expression ); } $currentClassDefinition = $classDefinition; $classDefinition = $classDefinition->getExtendsClassDefinition(); } } } /** * Check if the class implements the method */ if (!$dynamicMethod && !$dynamicClass) { // TODO: Consider to check instance of ClassDefinitionRuntime and throw another error, telling that class was not found. // TODO: This will give false if external class does not exists! if (!$classDefinition->hasMethod($methodName)) { $possibleMethod = $classDefinition->getPossibleMethodName($methodName); if ($possibleMethod) { throw new CompilerException( "Class '" . $classDefinition->getCompleteName() . "' does not implement static method: '" . $expression['name'] . "'. Did you mean '" . $possibleMethod . "'?", $expression ); } else { throw new CompilerException( "Class '" . $classDefinition->getCompleteName() . "' does not implement static method: '" . $expression['name'] . "'", $expression ); } } else { $method = $classDefinition->getMethod($methodName); if ($method->isPrivate() && $method->getClassDefinition() !== $compilationContext->classDefinition) { throw new CompilerException( "Cannot call private method '" . $methodName . "' out of its scope", $expression ); } if (!in_array($className, ['self', 'static', 'parent']) && !$method->isStatic()) { throw new CompilerException( "Cannot call non-static method '" . $methodName . "' in a static way", $expression ); } if (!$classDefinition->hasMethod('__callStatic')) { if ($method instanceof Method && !$method->isBundled()) { /** * Try to produce an exception if method is called with a wrong number of parameters */ $callNumberParameters = isset($expression['parameters']) ? count( $expression['parameters'] ) : 0; $classMethod = $classDefinition->getMethod($methodName); $expectedNumberParameters = $classMethod->getNumberOfRequiredParameters(); if (!$expectedNumberParameters && $callNumberParameters > 0) { $numberParameters = $classMethod->getNumberOfParameters(); if ($callNumberParameters > $numberParameters) { throw new CompilerException( "Method '" . $classDefinition->getCompleteName() . '::' . $expression['name'] . "' called with a wrong number of parameters, the method has: " . $expectedNumberParameters . ', passed: ' . $callNumberParameters, $expression ); } } if ($callNumberParameters < $expectedNumberParameters) { throw new CompilerException( "Method '" . $classDefinition->getCompleteName() . '::' . $expression['name'] . "' called with a wrong number of parameters, the method has: " . $expectedNumberParameters . ', passed: ' . $callNumberParameters, $expression ); } } } else { if (!isset($method)) { $method = $classDefinition->getMethod('__callStatic'); if ( $method->isPrivate() && $method->getClassDefinition() !== $compilationContext->classDefinition ) { throw new CompilerException( "Cannot call private magic method '__call' out of its scope", $expression ); } } } } } /** * Call static methods in the same class, use the special context 'self' or special context 'static' * Call static methods in the 'self' context */ if (!$dynamicMethod) { if ($dynamicClass) { $this->callFromDynamicClass( $methodName, $expression, $symbolVariable, $mustInit, $isExpecting, $compilationContext ); } else { if ( in_array($className, ['self', 'static']) || $classDefinition == $compilationContext->classDefinition ) { $this->call( strtoupper($className), $methodName, $expression, $mustInit, $isExpecting, $compilationContext, $symbolVariable, $method ?? null ); } else { if ('parent' == $className) { $this->callParent( $methodName, $expression, $symbolVariable, $mustInit, $isExpecting, $currentClassDefinition, $compilationContext, $method ?? null ); } else { $this->callFromClass( $methodName, $expression, $symbolVariable, $mustInit, $isExpecting, $classDefinition, $compilationContext, $method ?? null ); } } } } else { if ($dynamicClass) { $this->callFromDynamicClassDynamicMethod( $expression, $symbolVariable, $mustInit, $isExpecting, $compilationContext ); } } /** * Add the last call status to the current symbol table */ $this->addCallStatusFlag($compilationContext); /** * Transfer the return type-hint to the returned variable */ if ($isExpecting && isset($method) && $method instanceof Method) { $symbolVariable->setDynamicTypes('object'); foreach ($method->getReturnClassTypes() as $classType) { $symbolVariable->setClassTypes($compilationContext->getFullName($classType)); } foreach ($method->getReturnTypes() as $dataType => $returnType) { $symbolVariable->setDynamicTypes($dataType); } } /** * We can mark temporary variables generated as idle here */ foreach ($this->getTemporalVariables() as $tempVariable) { $tempVariable->setIdle(true); } if ($isExpecting) { return new CompiledExpression('variable', $symbolVariable->getRealName(), $expression); } return new CompiledExpression('null', null, $expression); }
Compiles a static method call. @throws Exception @throws ReflectionException
compile
php
zephir-lang/zephir
src/StaticCall.php
https://github.com/zephir-lang/zephir/blob/master/src/StaticCall.php
MIT
protected function call( string $context, string $methodName, array $expression, bool $mustInit, bool $isExpecting, CompilationContext $compilationContext, ?Variable $symbolVariable = null, ?Method $method = null ): void { if (!in_array($context, ['SELF', 'STATIC'])) { $context = 'SELF'; } /** * Do not optimize static:: calls, to allow late static binding */ if ('SELF' === $context) { $method = $method->getOptimizedMethod(); } $codePrinter = $compilationContext->codePrinter; /** * Call static methods must grow the stack */ $compilationContext->symbolTable->mustGrownStack(true); if ($mustInit) { $symbolVariable->setMustInitNull(true); $symbolVariable->trackVariant($compilationContext); } /** * Check if the method call can have an inline cache. */ $methodCache = $compilationContext->cacheManager->getStaticMethodCache(); $cachePointer = $methodCache->get($compilationContext, $method ?? null); $params = []; if (isset($expression['parameters']) && count($expression['parameters'])) { $params = $this->getResolvedParams($expression['parameters'], $compilationContext, $expression); } if ($symbolVariable) { $symbol = $compilationContext->backend->getVariableCode($symbolVariable); } $paramCount = count($params); $paramsStr = $paramCount ? ', ' . implode(', ', $params) : ''; $isInternal = isset($method) && $method->isInternal(); if (!$isInternal) { if ($isExpecting) { if ('return_value' == $symbolVariable->getName()) { $codePrinter->output( 'ZEPHIR_RETURN_CALL_' . $context . '("' . $methodName . '", ' . $cachePointer . $paramsStr . ');' ); } else { $codePrinter->output( 'ZEPHIR_CALL_' . $context . '(' . $symbol . ', "' . $methodName . '", ' . $cachePointer . $paramsStr . ');' ); } } else { $codePrinter->output( 'ZEPHIR_CALL_' . $context . '(NULL, "' . $methodName . '", ' . $cachePointer . $paramsStr . ');' ); } } else { $ce = $method->getClassDefinition()->getClassEntry($compilationContext); if ($isExpecting) { if ('return_value' == $symbolVariable->getName()) { $macro = $compilationContext->backend->getFcallManager()->getMacro(true, 1, $paramCount); $codePrinter->output($macro . '(' . $ce . ', ' . $method->getInternalName() . $paramsStr . ');'); } else { $macro = $compilationContext->backend->getFcallManager()->getMacro(true, 2, $paramCount); $codePrinter->output( $macro . '(' . $symbol . ', ' . $ce . ', ' . $method->getInternalName() . $paramsStr . ');' ); } } else { $macro = $compilationContext->backend->getFcallManager()->getMacro(true, 0, $paramCount); $codePrinter->output($macro . '(' . $ce . ', ' . $method->getInternalName() . $paramsStr . ');'); } } /** * Temporary variables must be copied if they have more than one reference */ foreach ($this->getMustCheckForCopyVariables() as $checkVariable) { $codePrinter->output('zephir_check_temp_parameter(' . $checkVariable . ');'); } $this->addCallStatusOrJump($compilationContext); }
Calls static methods on the 'self/static' context. @throws Exception @throws ReflectionException
call
php
zephir-lang/zephir
src/StaticCall.php
https://github.com/zephir-lang/zephir/blob/master/src/StaticCall.php
MIT
protected function callFromClass( $methodName, array $expression, $symbolVariable, $mustInit, $isExpecting, Definition $classDefinition, CompilationContext $compilationContext, Method $method ): void { $codePrinter = $compilationContext->codePrinter; if ($classDefinition->isBundled()) { $classEntryVariable = $compilationContext->symbolTable->addTemp('zend_class_entry', $compilationContext); $compilationContext->backend->fetchClass( $classEntryVariable, 'SL("' . str_replace('\\', '\\\\', $classDefinition->getName()) . '")', false, $compilationContext ); $classEntry = $classEntryVariable->getName(); } else { $classEntry = $classDefinition->getClassEntry($compilationContext); } /** * Call static methods must grow the stack */ $compilationContext->symbolTable->mustGrownStack(true); if ($mustInit) { $symbolVariable->setMustInitNull(true); $symbolVariable->trackVariant($compilationContext); } $method = $method->getOptimizedMethod(); /** * Check if the method call can have an inline cache. */ $methodCache = $compilationContext->cacheManager->getStaticMethodCache(); $cachePointer = $methodCache->get($compilationContext, $method); $params = []; if (isset($expression['parameters']) && count($expression['parameters'])) { $params = $this->getResolvedParams($expression['parameters'], $compilationContext, $expression); } if ($symbolVariable) { $symbol = $compilationContext->backend->getVariableCode($symbolVariable); } $paramCount = count($params); $paramsStr = $paramCount ? ', ' . implode(', ', $params) : ''; if ($method->isInternal()) { $ce = $classDefinition->getClassEntry($compilationContext); if ($isExpecting) { if ('return_value' == $symbolVariable->getName()) { $macro = $compilationContext->backend->getFcallManager()->getMacro(true, 1, $paramCount); $codePrinter->output($macro . '(' . $ce . ', ' . $method->getInternalName() . $paramsStr . ');'); } else { $macro = $compilationContext->backend->getFcallManager()->getMacro(true, 2, $paramCount); $codePrinter->output( $macro . '(' . $symbol . ', ' . $ce . ', ' . $method->getInternalName() . $paramsStr . ');' ); } } else { $macro = $compilationContext->backend->getFcallManager()->getMacro(true, 0, $paramCount); $codePrinter->output($macro . '(' . $ce . ', ' . $method->getInternalName() . $paramsStr . ');'); } } else { if ($isExpecting) { if ('return_value' == $symbolVariable->getName()) { $codePrinter->output( 'ZEPHIR_RETURN_CALL_CE_STATIC(' . $classEntry . ', "' . $methodName . '", ' . $cachePointer . $paramsStr . ');' ); } else { $codePrinter->output( 'ZEPHIR_CALL_CE_STATIC(' . $symbol . ', ' . $classEntry . ', "' . $methodName . '", ' . $cachePointer . $paramsStr . ');' ); } } else { $codePrinter->output( 'ZEPHIR_CALL_CE_STATIC(NULL, ' . $classEntry . ', "' . $methodName . '", ' . $cachePointer . $paramsStr . ');' ); } } /** * Temporary variables must be copied if they have more than one reference */ foreach ($this->getMustCheckForCopyVariables() as $checkVariable) { $codePrinter->output('zephir_check_temp_parameter(' . $checkVariable . ');'); } $this->addCallStatusOrJump($compilationContext); }
Calls static methods on some class context. @param string $methodName @param array $expression @param Variable $symbolVariable @param bool $mustInit @param bool $isExpecting @param Definition $classDefinition @param CompilationContext $compilationContext @param Method $method @throws Exception
callFromClass
php
zephir-lang/zephir
src/StaticCall.php
https://github.com/zephir-lang/zephir/blob/master/src/StaticCall.php
MIT
protected function callFromDynamicClass( string $methodName, array $expression, $symbolVariable, $mustInit, $isExpecting, CompilationContext $compilationContext ): void { [$params, $classEntry] = $this->fetchClassParams($expression, $compilationContext, $symbolVariable, $mustInit); if ($symbolVariable) { $symbol = $compilationContext->backend->getVariableCode($symbolVariable); } $cachePointer = 'NULL, 0'; if (!count($params)) { if ($isExpecting) { if ('return_value' == $symbolVariable->getName()) { $compilationContext->codePrinter->output( 'ZEPHIR_RETURN_CALL_CE_STATIC(' . $classEntry . ', "' . $methodName . '", ' . $cachePointer . ');' ); } else { $compilationContext->codePrinter->output( 'ZEPHIR_CALL_CE_STATIC(' . $symbol . ', ' . $classEntry . ', "' . $methodName . '", ' . $cachePointer . ');' ); } } else { $compilationContext->codePrinter->output( 'ZEPHIR_CALL_CE_STATIC(NULL, ' . $classEntry . ', "' . $methodName . '", ' . $cachePointer . ');' ); } } else { if ($isExpecting) { if ('return_value' == $symbolVariable->getName()) { $compilationContext->codePrinter->output( 'ZEPHIR_RETURN_CALL_CE_STATIC(' . $classEntry . ', "' . $methodName . '", ' . $cachePointer . ', ' . implode( ', ', $params ) . ');' ); } else { $compilationContext->codePrinter->output( 'ZEPHIR_CALL_CE_STATIC(' . $symbol . ', ' . $classEntry . ', "' . $methodName . '", ' . $cachePointer . ', ' . implode( ', ', $params ) . ');' ); } } else { $compilationContext->codePrinter->output( 'ZEPHIR_CALL_CE_STATIC(NULL, ' . $classEntry . ', "' . $methodName . '", ' . $cachePointer . ', ' . implode( ', ', $params ) . ');' ); } } /** * Temporary variables must be copied if they have more than one reference */ foreach ($this->getMustCheckForCopyVariables() as $checkVariable) { $compilationContext->codePrinter->output('zephir_check_temp_parameter(' . $checkVariable . ');'); } $this->addCallStatusOrJump($compilationContext); }
Calls static methods on using a dynamic variable as class. @param string $methodName @param array $expression @param Variable $symbolVariable @param bool $mustInit @param bool $isExpecting @param CompilationContext $compilationContext
callFromDynamicClass
php
zephir-lang/zephir
src/StaticCall.php
https://github.com/zephir-lang/zephir/blob/master/src/StaticCall.php
MIT
protected function callFromDynamicClassDynamicMethod( array $expression, $symbolVariable, bool $mustInit, bool $isExpecting, CompilationContext $compilationContext ): void { [$params, $classEntry] = $this->fetchClassParams($expression, $compilationContext, $symbolVariable, $mustInit); /** * Obtain the method name from the variable. */ $methodNameVariable = $compilationContext->symbolTable->getVariableForRead( $expression['name'], $compilationContext, $expression ); if ($methodNameVariable->isNotVariableAndString()) { throw new CompilerException('Only dynamic/string variables can be used in dynamic methods', $expression); } if ($symbolVariable) { $symbol = $compilationContext->backend->getVariableCode($symbolVariable); } $cachePointer = 'NULL, 0'; if (!count($params)) { if ($isExpecting) { if ('return_value' === $symbolVariable->getName()) { $compilationContext->codePrinter->output( 'ZEPHIR_RETURN_CALL_CE_STATIC_ZVAL(' . $classEntry . ', ' . $methodNameVariable->getName( ) . ', ' . $cachePointer . ');' ); } else { $compilationContext->codePrinter->output( 'ZEPHIR_CALL_CE_STATIC_ZVAL(' . $symbol . ', ' . $classEntry . ', ' . $methodNameVariable->getName( ) . ', ' . $cachePointer . ');' ); } } else { $compilationContext->codePrinter->output( 'ZEPHIR_CALL_CE_STATIC_ZVAL(NULL, ' . $classEntry . ', ' . $methodNameVariable->getName( ) . ', ' . $cachePointer . ');' ); } } else { if ($isExpecting) { if ('return_value' === $symbolVariable->getName()) { $compilationContext->codePrinter->output( 'ZEPHIR_RETURN_CALL_CE_STATIC_ZVAL(' . $classEntry . ', ' . $methodNameVariable->getName( ) . ', ' . $cachePointer . ', ' . implode(', ', $params) . ');' ); } else { $compilationContext->codePrinter->output( 'ZEPHIR_CALL_CE_STATIC_ZVAL(' . $symbol . ', ' . $classEntry . ', ' . $methodNameVariable->getName( ) . ', ' . $cachePointer . ', ' . implode(', ', $params) . ');' ); } } else { $compilationContext->codePrinter->output( 'ZEPHIR_CALL_CE_STATIC_ZVAL(NULL, ' . $classEntry . ', ' . $methodNameVariable->getName( ) . ', ' . $cachePointer . ', ' . implode(', ', $params) . ');' ); } } /** * Temporary variables must be copied if they have more than one reference */ foreach ($this->getMustCheckForCopyVariables() as $checkVariable) { $compilationContext->codePrinter->output('zephir_check_temp_parameter(' . $checkVariable . ');'); } $this->addCallStatusOrJump($compilationContext); }
Calls static methods on using a dynamic variable as class and a dynamic method. @param array $expression @param Variable $symbolVariable @param bool $mustInit @param bool $isExpecting @param CompilationContext $compilationContext
callFromDynamicClassDynamicMethod
php
zephir-lang/zephir
src/StaticCall.php
https://github.com/zephir-lang/zephir/blob/master/src/StaticCall.php
MIT
protected function callParent( string $methodName, array $expression, $symbolVariable, $mustInit, $isExpecting, Definition $classDefinition, CompilationContext $compilationContext, Method $method ): void { $codePrinter = $compilationContext->codePrinter; $classCe = $classDefinition->getClassEntry($compilationContext); /** * Call static methods must grow the stack */ $compilationContext->symbolTable->mustGrownStack(true); if ($mustInit) { $symbolVariable->setMustInitNull(true); $symbolVariable->trackVariant($compilationContext); } /** * Check if the method call can have an inline cache. */ $methodCache = $compilationContext->cacheManager->getStaticMethodCache(); $cachePointer = $methodCache->get($compilationContext, $method ?? null); $params = []; if (isset($expression['parameters']) && count($expression['parameters'])) { $params = $this->getResolvedParams($expression['parameters'], $compilationContext, $expression); } if (!count($params)) { if ($isExpecting) { if ('return_value' == $symbolVariable->getName()) { $codePrinter->output( 'ZEPHIR_RETURN_CALL_PARENT(' . $classCe . ', getThis(), "' . $methodName . '", ' . $cachePointer . ');' ); } else { $codePrinter->output( 'ZEPHIR_CALL_PARENT(&' . $symbolVariable->getName( ) . ', ' . $classCe . ', getThis(), "' . $methodName . '", ' . $cachePointer . ');' ); } } else { $codePrinter->output( 'ZEPHIR_CALL_PARENT(NULL, ' . $classCe . ', getThis(), "' . $methodName . '", ' . $cachePointer . ');' ); } } else { if ($isExpecting) { if ('return_value' == $symbolVariable->getName()) { $codePrinter->output( 'ZEPHIR_RETURN_CALL_PARENT(' . $classCe . ', getThis(), "' . $methodName . '", ' . $cachePointer . ', ' . implode( ', ', $params ) . ');' ); } else { $codePrinter->output( 'ZEPHIR_CALL_PARENT(&' . $symbolVariable->getName( ) . ', ' . $classCe . ', getThis(), "' . $methodName . '", ' . $cachePointer . ', ' . implode( ', ', $params ) . ');' ); } } else { $codePrinter->output( 'ZEPHIR_CALL_PARENT(NULL, ' . $classCe . ', getThis(), "' . $methodName . '", ' . $cachePointer . ', ' . implode( ', ', $params ) . ');' ); } } /** * Temporary variables must be copied if they have more than one reference */ foreach ($this->getMustCheckForCopyVariables() as $checkVariable) { $codePrinter->output('zephir_check_temp_parameter(' . $checkVariable . ');'); } $this->addCallStatusOrJump($compilationContext); }
Calls static methods on the 'parent' context. @param string $methodName @param array $expression @param Variable $symbolVariable @param bool $mustInit @param bool $isExpecting @param Definition $classDefinition @param CompilationContext $compilationContext @param Method $method @throws Exception
callParent
php
zephir-lang/zephir
src/StaticCall.php
https://github.com/zephir-lang/zephir/blob/master/src/StaticCall.php
MIT
public function addConcatKey(string $key): void { $this->concatKeys[$key] = true; }
Adds a concatenation combination to the manager.
addConcatKey
php
zephir-lang/zephir
src/StringsManager.php
https://github.com/zephir-lang/zephir/blob/master/src/StringsManager.php
MIT
public function addRawVariable(Variable $variable): Variable { if (!isset($this->branchVariables[1])) { $this->branchVariables[1] = []; } $this->branchVariables[1][$variable->getName()] = $variable; return $variable; }
Adds a raw variable to the symbol table (root branch).
addRawVariable
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function addVariable( string $type, string $name, CompilationContext $compilationContext ): Variable { $currentBranch = $compilationContext->branchManager->getCurrentBranch(); $branchId = $currentBranch->getUniqueId(); if ($this->globalsManager->isSuperGlobal($name) || 'zephir_fcall_cache_entry' == $type) { $branchId = 1; } $varName = $name; if ($branchId > 1 && Branch::TYPE_ROOT != $currentBranch->getType()) { $varName = $name . Variable::BRANCH_MAGIC . $branchId; } $variable = new Variable($type, $varName, $currentBranch); $variable->setUsed(true); /** * Checks whether a variable can be optimized to be static or not */ if ('variable' == $type && $this->localContext && $this->localContext->shouldBeLocal($name)) { $variable->setLocalOnly(true); } if (!isset($this->branchVariables[$branchId])) { $this->branchVariables[$branchId] = []; } $this->branchVariables[$branchId][$name] = $variable; return $variable; }
Adds a variable to the symbol table.
addVariable
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getExpectedMutations(string $variable): int { if ($this->localContext) { return $this->localContext->getNumberOfMutations($variable); } return 0; }
Returns the number of expected mutations for a variable.
getExpectedMutations
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getLastCallLine(): int { if ($this->localContext) { return $this->localContext->getLastCallLine(); } return 0; }
Returns the last line where any kind of call was performed within the method This is not necessary related to the symbol table but this information is gathered by the LocalContextPass.
getLastCallLine
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getLastUnsetLine(): int { if ($this->localContext) { return $this->localContext->getLastUnsetLine(); } return 0; }
Returns the last line where an 'unset' operation was made within the current method This is not necessary related to the symbol table but this information is gathered by the LocalContextPass.
getLastUnsetLine
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getMustGrownStack(): bool { return $this->mustGrownStack; }
Returns if the current symbol label must add a memory frame.
getMustGrownStack
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getTempComplexLiteralVariableForWrite($type, CompilationContext $context): Variable { $variable = $this->reuseTempVariable($type, 'heap-literal'); if (is_object($variable)) { $variable->increaseUses(); $variable->increaseMutates(); if ('variable' == $type || 'string' == $type || 'array' == $type) { $variable->initComplexLiteralVariant($context); } return $variable; } $tempVar = $this->getNextTempVar(); $variable = $this->addVariable($type, '_' . $tempVar, $context); $variable->setIsInitialized(true, $context); $variable->increaseUses(); $variable->increaseMutates(); $variable->setTemporal(true); if ('variable' == $type || 'string' == $type || 'array' == $type) { $variable->initComplexLiteralVariant($context); } $this->registerTempVariable($type, 'heap-literal', $variable); return $variable; }
Creates a temporary variable to be used in a write operation the body of the variable is freed between iterations instead of request a new full zval variable.
getTempComplexLiteralVariableForWrite
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getTempLocalVariableForWrite($type, CompilationContext $context): Variable { $variable = $this->reuseTempVariable($type, 'stack'); if (is_object($variable)) { $variable->increaseUses(); $variable->increaseMutates(); $variable->setLocalOnly(true); if ('variable' == $type || 'string' == $type || 'array' == $type) { $variable->initVariant($context); } return $variable; } $tempVar = $this->getNextTempVar(); $variable = $this->addVariable($type, '_' . $tempVar, $context); $variable->setIsInitialized(true, $context); $variable->increaseUses(); $variable->increaseMutates(); $variable->setLocalOnly(true); $variable->setTemporal(true); if ('variable' == $type || 'string' == $type || 'array' == $type) { $variable->initVariant($context); } $this->registerTempVariable($type, 'stack', $variable); return $variable; }
Creates a temporary variable to be used in a write operation.
getTempLocalVariableForWrite
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getTempNonTrackedUninitializedVariable(string $type, CompilationContext $context): Variable { $variable = $this->reuseTempVariable($type, 'non-tracked-uninitialized'); if (is_object($variable)) { $variable->increaseUses(); $variable->increaseMutates(); return $variable; } $tempVar = $this->getNextTempVar(); $variable = $this->addVariable($type, '_' . $tempVar, $context); $variable->setIsInitialized(true, $context); $variable->setTemporal(true); $variable->setMemoryTracked(false); $variable->increaseUses(); $variable->increaseMutates(); $this->registerTempVariable($type, 'non-tracked-uninitialized', $variable); return $variable; }
Creates a temporary variable to be used in a read-only operation within native-array-access and property-access These kind of variables MUST not be tracked by the Zephir memory manager.
getTempNonTrackedUninitializedVariable
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getTempNonTrackedVariable($type, CompilationContext $context, bool $initNonReferenced = false): Variable { $variable = $this->reuseTempVariable($type, 'non-tracked'); if (is_object($variable)) { $variable->increaseUses(); $variable->increaseMutates(); if ($initNonReferenced) { $variable->initNonReferenced($context); } return $variable; } $tempVar = $this->getNextTempVar(); $variable = $this->addVariable($type, '_' . $tempVar, $context); $variable->setIsInitialized(true, $context); $variable->setTemporal(true); $variable->setMemoryTracked(false); $variable->increaseUses(); $variable->increaseMutates(); $this->registerTempVariable($type, 'non-tracked', $variable); if ($initNonReferenced) { $variable->initNonReferenced($context); } return $variable; }
Creates a temporary variable to be used to point to a heap variable These kind of variables MUST not be tracked by the Zephir memory manager.
getTempNonTrackedVariable
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getTempVariableForObserve($type, CompilationContext $context): Variable { $variable = $this->reuseTempVariable($type, 'observe'); if (is_object($variable)) { $variable->increaseUses(); $variable->increaseMutates(); $variable->observeVariant($context); return $variable; } $tempVar = $this->getNextTempVar(); $variable = $this->addVariable($type, '_' . $tempVar, $context); $variable->setIsInitialized(true, $context); $variable->setTemporal(true); $variable->increaseUses(); $variable->increaseMutates(); $variable->observeVariant($context); $this->registerTempVariable($type, 'observe', $variable); return $variable; }
Creates a temporary variable to be used as intermediate variable of a read operation Variables are automatically tracked by the memory manager.
getTempVariableForObserve
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getTempVariableForObserveOrNullify(string $type, CompilationContext $context): Variable { $variable = $this->reuseTempVariable($type, 'observe-nullify'); if (is_object($variable)) { $variable->increaseUses(); $variable->increaseMutates(); $variable->observeOrNullifyVariant($context); return $variable; } $tempVar = $this->getNextTempVar(); $variable = $this->addVariable($type, '_' . $tempVar, $context); $variable->setIsInitialized(true, $context); $variable->setTemporal(true); $variable->increaseUses(); $variable->increaseMutates(); $variable->observeOrNullifyVariant($context); $this->registerTempVariable($type, 'observe-nullify', $variable); return $variable; }
Creates a temporary variable to be used as intermediate variable in a call operation Variables are automatically tracked by the memory manager.
getTempVariableForObserveOrNullify
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getTempVariableForWrite(string $type, CompilationContext $context, $init = true): Variable { $variable = $this->reuseTempVariable($type, 'heap'); if (is_object($variable)) { $variable->increaseUses(); $variable->increaseMutates(); if ($init && ('variable' == $type || 'string' == $type || 'array' == $type)) { $variable->initVariant($context); } return $variable; } $tempVar = $this->getNextTempVar(); $variable = $this->addVariable($type, '_' . $tempVar, $context); $variable->setIsInitialized(true, $context); $variable->setTemporal(true); $variable->increaseUses(); $variable->increaseMutates(); if ('variable' == $type || 'string' == $type || 'array' == $type) { $variable->initVariant($context); } $this->registerTempVariable($type, 'heap', $variable); return $variable; }
Creates a temporary variable to be used in a write operation.
getTempVariableForWrite
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getVariable(string $name, ?CompilationContext $compilationContext = null) { /* Check if the variable already is referencing a branch */ $pos = strpos($name, Variable::BRANCH_MAGIC); if ($pos > -1) { $branchId = (int)substr($name, $pos + strlen(Variable::BRANCH_MAGIC)); $name = substr($name, 0, $pos); } else { $compilationContext = $compilationContext ?: $this->compilationContext; $branch = $this->resolveVariableToBranch($name, $compilationContext); if (!$branch) { return false; } $branchId = $branch->getUniqueId(); } if (!isset($this->branchVariables[$branchId]) || !isset($this->branchVariables[$branchId][$name])) { return false; } $variable = $this->branchVariables[$branchId][$name]; $variable->setUsed(true); return $variable; }
Returns a variable in the symbol table.
getVariable
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getVariableForRead(string $name, ?CompilationContext $compilationContext = null, ?array $statement = null): Variable|bool { /** * Validate that 'this' cannot be used in a static function */ if ('this' == $name || 'this_ptr' == $name) { if ($compilationContext->staticContext) { throw new CompilerException("Cannot use variable 'this' in static context", $statement); } } /** * Create superglobals just in time */ if ($this->globalsManager->isSuperGlobal($name)) { if (!$this->hasVariable($name)) { /** * TODO: injecting globals, initialize to null and check first? */ $variable = new Variable('variable', $name, $compilationContext->branchManager->getCurrentBranch()); $variable->setIsInitialized(true, $compilationContext); $variable->setDynamicTypes('array'); $variable->setIsExternal(true); $this->addRawVariable($variable); } else { $variable = $this->getVariable($name); } $variable->increaseUses(); return $variable; } if (!$this->hasVariable($name)) { throw new CompilerException("Cannot read variable '" . $name . "' because it wasn't declared", $statement); } $variable = $this->getVariable($name); if (!$variable->isInitialized()) { /* DON'T REMOVE THIS!! */ throw new CompilerException( "Variable '" . $name . "' cannot be read because it's not initialized", $statement ); } $variable->increaseUses(); /** * Analise branches to detect possible initialization of variables in conditional branches */ if (!$variable->isTemporal() && !$variable->getSkipVariant()) { if ('return_value' != $name && 'this' != $name) { if (is_object($compilationContext) && is_object($compilationContext->branchManager)) { if ($compilationContext->config->get('check-invalid-reads', 'optimizations')) { switch ($variable->getType()) { case 'variable': case 'string': case 'array': case 'mixed': if (!$variable->isLocalOnly()) { $variable->setMustInitNull(true); } break; } } $initBranches = $variable->getInitBranches(); $currentBranch = $compilationContext->branchManager->getCurrentBranch(); $branches = array_reverse($initBranches); if (1 == count($branches)) { if (Branch::TYPE_CONDITIONAL_TRUE == $branches[0]->getType()) { if (true === $branches[0]->isUnreachable()) { throw new CompilerException( 'Initialization of variable "' . $name . '" depends on unreachable branch, consider initialize it at its declaration', $statement ); } } else { if (Branch::TYPE_CONDITIONAL_FALSE == $branches[0]->getType()) { if (false === $branches[0]->isUnreachable()) { throw new CompilerException( 'Initialization of variable "' . $name . '" depends on unreachable branch, consider initialize at its declaration', $statement ); } } } $tempBranch = $branches[0]->getParentBranch(); while ($tempBranch) { if (Branch::TYPE_CONDITIONAL_TRUE == $tempBranch->getType()) { if (true === $tempBranch->isUnreachable()) { throw new CompilerException( 'Initialization of variable "' . $name . '" depends on unreachable branch, consider initialize it at its declaration', $statement ); } } $tempBranch = $tempBranch->getParentBranch(); } } $found = false; foreach ($branches as $branch) { /* * Variable was initialized in the same current branch */ if ($branch === $currentBranch) { $found = true; break; } /* * 'root' and 'external' branches are safe branches */ if (Branch::TYPE_ROOT == $branch->getType() || Branch::TYPE_EXTERNAL == $branch->getType()) { $found = true; break; } } if (!$found) { /** * Check if last assignment * Variable was initialized in a sub-branch, and it's being used in a parent branch. */ $possibleBadAssignment = $currentBranch->getLevel() < $branches[0]->getLevel(); if ($possibleBadAssignment && count($branches) === 1) { /** * Variable is assigned just once, and it's assigned in a conditional branch */ if (Branch::TYPE_CONDITIONAL_TRUE == $branches[0]->getType()) { $evalExpression = $branches[0]->getRelatedStatement()->getEvalExpression(); if (true === $evalExpression->isUnreachable()) { throw new CompilerException( "Variable '" . $name . "' was assigned for the first time in conditional branch, consider initialize it at its declaration", $statement ); } else { $variable->enableDefaultAutoInitValue(); $compilationContext->logger->warning( "Variable '" . $name . "' was assigned for the first time in conditional branch, consider initialize it at its declaration", ['conditional-initialization', $statement] ); } } else { if (Branch::TYPE_CONDITIONAL_FALSE == $branches[0]->getType()) { $evalExpression = $branches[0]->getRelatedStatement()->getEvalExpression(); if (true === $evalExpression->isUnreachableElse()) { throw new CompilerException( "Variable '" . $name . "' was assigned for the first time in conditional branch, consider initialize it at its declaration", $statement ); } else { $variable->enableDefaultAutoInitValue(); $compilationContext->logger->warning( "Variable '" . $name . "' was assigned for the first time in conditional branch, consider initialize it at its declaration", ['conditional-initialization', $statement] ); } } } } } } } } /* * Saves the latest place where the variable was used */ $variable->setUsed(true, $statement); return $variable; }
Return a variable in the symbol table, it will be used for a read operation. @throws CompilerException
getVariableForRead
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getVariableForUpdate(string $name, CompilationContext $compilationContext, ?array $statement = null) { /** * Create superglobals just in time */ if ($this->globalsManager->isSuperGlobal($name)) { if (!$this->hasVariable($name)) { /** * TODO:, injecting globals, initialize to null and check first? */ $superVar = new Variable('variable', $name, $compilationContext->branchManager->getCurrentBranch()); $superVar->setIsInitialized(true, $compilationContext); $superVar->setDynamicTypes('array'); $superVar->increaseMutates(); $superVar->increaseUses(); $superVar->setIsExternal(true); $superVar->setUsed(true, $statement); $this->addRawVariable($superVar); return $superVar; } } if (!$this->hasVariable($name)) { throw new CompilerException("Cannot mutate variable '" . $name . "' because it wasn't defined", $statement); } $variable = $this->getVariable($name); $variable->increaseUses(); $variable->increaseMutates(); /** * Saves the last place where the variable was mutated * We discard mutations inside loops because iterations could use the value * and Zephir only provides top-down compilation */ $variable->setUsed(true, $statement); return $variable; }
Return a variable in the symbol table, it will be used for a mutating operation This method implies mutation of one of the members of the variable but no the variables itself.
getVariableForUpdate
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getVariableForWrite(string $name, CompilationContext $compilationContext, ?array $statement = null): Variable|bool { /** * Create superglobals just in time */ if ($this->globalsManager->isSuperGlobal($name)) { if (!$this->hasVariable($name)) { /** * TODO:, injecting globals, initialize to null and check first? */ $superVar = new Variable('variable', $name, $compilationContext->branchManager->getCurrentBranch()); $superVar->setIsInitialized(true, $compilationContext); $superVar->setDynamicTypes('array'); $superVar->increaseMutates(); $superVar->increaseUses(); $superVar->setIsExternal(true); $superVar->setUsed(true, $statement); $this->addRawVariable($superVar); return $superVar; } } if (!$this->hasVariable($name)) { throw new CompilerException("Cannot mutate variable '" . $name . "' because it wasn't defined", $statement); } $variable = $this->getVariable($name); $variable->increaseUses(); $variable->increaseMutates(); /** * Saves the last place where the variable was mutated * We discard mutations inside loops because iterations could use the value * and Zephir only provides top-down compilation */ if (!$compilationContext->insideCycle) { $variable->setUsed(false, $statement); } else { $variable->setUsed(true, $statement); } return $variable; }
Return a variable in the symbol table, it will be used for a write operation Some variables aren't writable themselves but their members do. @throws CompilerException
getVariableForWrite
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getVariables(): array { $ret = []; foreach ($this->branchVariables as $vars) { foreach ($vars as $var) { $ret[$var->getName()] = $var; } } return $ret; }
Returns all the variables defined in the symbol table. @return Variable[]
getVariables
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function hasVariable(string $name, ?CompilationContext $compilationContext = null): bool { return false !== $this->getVariable($name, $compilationContext ?: $this->compilationContext); }
Check if a variable is declared in the current symbol table.
hasVariable
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function markTemporalVariablesIdle(CompilationContext $compilationContext): void { $branchId = $compilationContext->branchManager->getCurrentBranchId(); if (!isset($this->branchTempVariables[$branchId])) { return; } foreach ($this->branchTempVariables[$branchId] as $typeVariables) { foreach ($typeVariables as $variables) { foreach ($variables as $variable) { $pos = strpos($variable->getName(), Variable::BRANCH_MAGIC); $otherBranchId = 1; if ($pos > -1) { $otherBranchId = (int)substr($variable->getName(), $pos + strlen(Variable::BRANCH_MAGIC)); } if ($branchId == $otherBranchId) { $variable->setIdle(true); } } } } }
Traverses temporal variables created in a specific branch marking them as idle.
markTemporalVariablesIdle
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function mustGrownStack(bool $mustGrownStack): void { $this->mustGrownStack = $mustGrownStack; }
Return a variable in the symbol table, it will be used for a write operation.
mustGrownStack
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
protected function reuseTempVariable( string $type, string $location, ?CompilationContext $compilationContext = null, ): ?Variable { $compilationContext = $compilationContext ?: $this->compilationContext; $branchId = $compilationContext->branchManager->getCurrentBranchId(); if (isset($this->branchTempVariables[$branchId][$location][$type])) { foreach ($this->branchTempVariables[$branchId][$location][$type] as $variable) { if (!$variable->isDoublePointer() && $variable->isIdle()) { $variable->setIdle(false); return $variable; } } } return null; }
Reuse variables marked as idle after leave a branch.
reuseTempVariable
php
zephir-lang/zephir
src/SymbolTable.php
https://github.com/zephir-lang/zephir/blob/master/src/SymbolTable.php
MIT
public function getInternalKernelPath(): string { return $this->kernelsPath; }
Resolves the path to the source kernel files of the backend.
getInternalKernelPath
php
zephir-lang/zephir
src/Backend/Backend.php
https://github.com/zephir-lang/zephir/blob/master/src/Backend/Backend.php
MIT
public function getTemplateFileContents(string $filename): string { $templatePath = rtrim((string)$this->config->get('templatepath', 'backend'), '\\/'); if (empty($templatePath)) { $templatePath = $this->templatesPath; } return file_get_contents("$templatePath/engine/$filename"); }
Resolves the path to the source template file of the backend.
getTemplateFileContents
php
zephir-lang/zephir
src/Backend/Backend.php
https://github.com/zephir-lang/zephir/blob/master/src/Backend/Backend.php
MIT
public function initArray(Variable $variable, CompilationContext $context, ?int $size = null): void { $code = $this->getVariableCode($variable); if (null === $size) { $output = "array_init({$code});"; } else { $output = "zephir_create_array({$code}, {$size}, 0);"; } $context->codePrinter->output($output); }
Initialize array Init empty array or specific size array. @param Variable $variable @param CompilationContext $context @param int|null $size @return void
initArray
php
zephir-lang/zephir
src/Backend/Backend.php
https://github.com/zephir-lang/zephir/blob/master/src/Backend/Backend.php
MIT
public function initializeVariableDefaults(array $variables, CompilationContext $context): string { $codePrinter = new Printer(); $codePrinter->increaseLevel(); $oldCodePrinter = $context->codePrinter; $context->codePrinter = $codePrinter; $variablesManager = new VariablesManager(); /* Initialize default values in dynamic variables */ foreach ($variables as $variable) { /* Do not initialize unused variable */ if ($variable->getNumberUses() < 1) { continue; } /* The default init value to be used bellow. Actually this value should be in array form and provide 'type' and 'value' keys. */ $value = $variable->getDefaultInitValue(); if (!is_array($value)) { continue; } $variablesManager->initializeDefaults($variable, $value, $context); } $context->codePrinter = $oldCodePrinter; return $codePrinter->getOutput(); }
@param Variable[] $variables @param CompilationContext $context @return string @throws CompilerException
initializeVariableDefaults
php
zephir-lang/zephir
src/Backend/Backend.php
https://github.com/zephir-lang/zephir/blob/master/src/Backend/Backend.php
MIT
public function getMacro(bool $static, int $doReturn, int $paramCount): string { $scope = $static ? 'STATIC' : ''; $mode = 'CALL_INTERNAL_METHOD_NORETURN_P'; if ($doReturn) { $mode = 'RETURN_CALL_INTERNAL_METHOD_P'; if (2 === $doReturn) { $mode = 'CALL_INTERNAL_METHOD_P'; } } $macroName = 'ZEPHIR_' . ($scope ? $scope . '_' : '') . $mode . $paramCount; if (!isset($this->requiredMacros[$macroName])) { $this->requiredMacros[$macroName] = [$scope, $mode, $paramCount]; } return $macroName; }
tri-state: 0 -> no return value, 1 -> do return, 2 -> do return to given variable
getMacro
php
zephir-lang/zephir
src/Backend/FcallManager.php
https://github.com/zephir-lang/zephir/blob/master/src/Backend/FcallManager.php
MIT
public function addConcatKey(string $key): void { $this->concatKeys[$key] = true; }
Adds a concatenation combination to the manager.
addConcatKey
php
zephir-lang/zephir
src/Backend/StringsManager.php
https://github.com/zephir-lang/zephir/blob/master/src/Backend/StringsManager.php
MIT
public function initializeDefaults(Variable $variable, array $value, Context $context): void { switch ($variable->getType()) { case Types::T_VARIABLE: $this->initDynamicVar($variable, $value, $context); break; case Types::T_STRING: $this->initStringVar($variable, $value, $context); break; case Types::T_ARRAY: $this->initArrayVar($variable, $value, $context); break; } }
Initialize variable defaults. Meant for Backend::initializeVariableDefaults. Shouldn't called directly. TODO: Figure out why it never reached during generation.
initializeDefaults
php
zephir-lang/zephir
src/Backend/VariablesManager.php
https://github.com/zephir-lang/zephir/blob/master/src/Backend/VariablesManager.php
MIT
private function initArrayVar(Variable $variable, array $value, Context $context): void { $context->symbolTable->mustGrownStack(true); $context->backend->initVar($variable, $context); switch ($value['type']) { case Types::T_NULL: $context->backend->assignNull($variable, $context); break; case Types::T_ARRAY: case 'empty-array': $context->backend->initArray($variable, $context); break; } }
Initialize 'array' variables with default values. Meant for VariablesManager::initializeDefaults. @param Variable $variable @param array $value @param Context $context @return void
initArrayVar
php
zephir-lang/zephir
src/Backend/VariablesManager.php
https://github.com/zephir-lang/zephir/blob/master/src/Backend/VariablesManager.php
MIT
private function initDynamicVar(Variable $variable, array $value, Context $context): void { /* These are system variables, do not add default values. Also see: https://github.com/zephir-lang/zephir/issues/1660 */ if (in_array($variable->getName(), self::RESERVED_NAMES, true)) { return; } $context->symbolTable->mustGrownStack(true); $context->backend->initVar($variable, $context); switch ($value['type']) { case Types::T_INT: case Types::T_UINT: case Types::T_LONG: case Types::T_ULONG: $context->backend->assignLong($variable, $value['value'], $context); break; case Types::T_BOOL: $context->backend->assignBool($variable, $value['value'], $context); break; case Types::T_CHAR: case Types::T_UCHAR: $this->validateCharValue($value); $context->backend->assignLong($variable, "'" . $value['value'] . "'", $context); break; case Types::T_NULL: $context->backend->assignNull($variable, $context); break; case Types::T_DOUBLE: $context->backend->assignDouble($variable, $value['value'], $context); break; case Types::T_STRING: $string = add_slashes($value['value']); $context->backend->assignString($variable, $string, $context); break; case Types::T_ARRAY: case 'empty-array': $context->backend->initArray($variable, $context); break; } }
Initialize 'dynamic' variables with default values. Meant for VariablesManager::initializeDefaults. @param Variable $variable @param array $value @param Context $context @return void
initDynamicVar
php
zephir-lang/zephir
src/Backend/VariablesManager.php
https://github.com/zephir-lang/zephir/blob/master/src/Backend/VariablesManager.php
MIT
private function initStringVar(Variable $variable, array $value, Context $context): void { $context->symbolTable->mustGrownStack(true); $context->backend->initVar($variable, $context); switch ($value['type']) { case Types::T_STRING: $string = add_slashes($value['value']); $context->backend->assignString($variable, $string, $context); break; case Types::T_NULL: $context->backend->assignString($variable, null, $context); break; } }
Initialize 'string' variables with default values. Meant for VariablesManager::initializeDefaults. @param Variable $variable @param array $value @param Context $context @return void
initStringVar
php
zephir-lang/zephir
src/Backend/VariablesManager.php
https://github.com/zephir-lang/zephir/blob/master/src/Backend/VariablesManager.php
MIT
private function validateCharValue(array $value): void { if (strlen($value['value']) > 2) { throw new Exception( sprintf( "Invalid char literal: '%s%s'", substr($value['value'], 0, 10), strlen($value['value']) > 10 ? '...' : '' ), $value ); } }
Validate 'char' value type. @param array $value @return void @throws Exception
validateCharValue
php
zephir-lang/zephir
src/Backend/VariablesManager.php
https://github.com/zephir-lang/zephir/blob/master/src/Backend/VariablesManager.php
MIT
public function get(string $functionName, CompilationContext $compilationContext, bool $exists): string { if (isset($this->cache[$functionName])) { return $this->cache[$functionName] . ', ' . SlotsCache::getExistingFunctionSlot($functionName); } if (!$exists) { return 'NULL, 0'; } $cacheSlot = SlotsCache::getFunctionSlot($functionName); $number = 0; if (!$compilationContext->insideCycle && $this->gatherer !== null) { $number = $this->gatherer->getNumberOfFunctionCalls($functionName); if ($number <= 1) { return 'NULL, ' . $cacheSlot; } } if ($compilationContext->insideCycle || $number > 1) { $functionCacheVariable = $compilationContext->symbolTable->getTempVariableForWrite( 'zephir_fcall_cache_entry', $compilationContext ); $functionCacheVariable->setMustInitNull(true); $functionCacheVariable->setReusable(false); $functionCache = '&' . $functionCacheVariable->getName(); } else { $functionCache = 'NULL'; } $this->cache[$functionName] = $functionCache; return $functionCache . ', ' . $cacheSlot; }
Retrieves/Creates a function cache for a function call.
get
php
zephir-lang/zephir
src/Cache/FunctionCache.php
https://github.com/zephir-lang/zephir/blob/master/src/Cache/FunctionCache.php
MIT
public function getClassEntryCache(): ClassEntryCache { if (!$this->classEntryCache) { $this->classEntryCache = new ClassEntryCache(); } return $this->classEntryCache; }
Creates or returns an existing class entry cache.
getClassEntryCache
php
zephir-lang/zephir
src/Cache/Manager.php
https://github.com/zephir-lang/zephir/blob/master/src/Cache/Manager.php
MIT
public function getFunctionCache(): ?FunctionCache { if (!$this->functionCache) { $this->functionCache = new FunctionCache($this->gatherer); } return $this->functionCache; }
Creates or returns an existing function cache.
getFunctionCache
php
zephir-lang/zephir
src/Cache/Manager.php
https://github.com/zephir-lang/zephir/blob/master/src/Cache/Manager.php
MIT
public function getMethodCache(): ?MethodCache { if (!$this->methodCache) { $this->methodCache = new MethodCache($this->gatherer); } return $this->methodCache; }
Creates or returns an existing method cache.
getMethodCache
php
zephir-lang/zephir
src/Cache/Manager.php
https://github.com/zephir-lang/zephir/blob/master/src/Cache/Manager.php
MIT
public function getStaticMethodCache(): ?StaticMethodCache { if (!$this->staticMethodCache) { $this->staticMethodCache = new StaticMethodCache(); } return $this->staticMethodCache; }
Creates or returns an existing method cache.
getStaticMethodCache
php
zephir-lang/zephir
src/Cache/Manager.php
https://github.com/zephir-lang/zephir/blob/master/src/Cache/Manager.php
MIT
public function get(CompilationContext $compilationContext, string $methodName, Variable $caller): string { $compiler = $compilationContext->compiler; $numberPoly = 0; if ('this' === $caller->getRealName()) { $classDefinition = $compilationContext->classDefinition; if ($classDefinition->hasMethod($methodName)) { ++$numberPoly; $method = $classDefinition->getMethod($methodName); } } else { $classTypes = $caller->getClassTypes(); foreach ($classTypes as $classType) { if ( $compiler->isClass($classType) || $compiler->isInterface($classType) || $compiler->isBundledClass($classType) || $compiler->isBundledInterface($classType) ) { if ($compiler->isInterface($classType)) { continue; } if ($compiler->isClass($classType)) { $classDefinition = $compiler->getClassDefinition($classType); } else { $classDefinition = $compiler->getInternalClassDefinition($classType); } if (!$classDefinition) { continue; } if ($classDefinition->hasMethod($methodName) && !$classDefinition->isInterface()) { ++$numberPoly; $method = $classDefinition->getMethod($methodName); } } } } if (!$numberPoly) { // Try to generate a cache based on the fact the variable is not modified within the loop block if ($compilationContext->insideCycle && !$caller->isTemporal()) { if (count($compilationContext->cycleBlocks) && 'variable' == $caller->getType()) { $currentBlock = $compilationContext->cycleBlocks[count($compilationContext->cycleBlocks) - 1]; if (0 == $currentBlock->getMutateGatherer(true)->getNumberOfMutations($caller->getName())) { $functionCache = $compilationContext->symbolTable->getTempVariableForWrite( 'zephir_fcall_cache_entry', $compilationContext ); $functionCache->setMustInitNull(true); $functionCache->setReusable(false); return '&' . $functionCache->getName() . ', 0'; } } } return 'NULL, 0'; } if (!($method instanceof ReflectionMethod)) { if ($method->getClassDefinition()->isExternal()) { return 'NULL, 0'; } $completeName = $method->getClassDefinition()->getCompleteName(); if (isset($this->cache[$completeName][$method->getName()])) { return $this->cache[$completeName][$method->getName()] . ', ' . SlotsCache::getExistingMethodSlot($method); } $gatherer = $this->gatherer; if (is_object($gatherer)) { $number = $gatherer->getNumberOfMethodCalls( $method->getClassDefinition()->getCompleteName(), $method->getName() ); } else { $number = 0; } $staticCacheable = !$method->getClassDefinition()->isInterface() && ( $compilationContext->currentMethod == $method || $method->getClassDefinition()->isFinal() || $method->isFinal() || $method->isPrivate() ); if ($number > 1 || $compilationContext->insideCycle) { $cacheable = true; } else { $cacheable = false; } } else { $staticCacheable = false; $cacheable = false; } if ('this_ptr' !== $caller->getName()) { $associatedClass = $caller->getAssociatedClass(); if ($this->isClassCacheable($associatedClass)) { $staticCacheable = true; } } if ($staticCacheable) { $cacheSlot = SlotsCache::getMethodSlot($method); } else { $cacheSlot = '0'; } if ($cacheable) { $functionCacheVar = $compilationContext->symbolTable->getTempVariableForWrite( 'zephir_fcall_cache_entry', $compilationContext ); $functionCacheVar->setMustInitNull(true); $functionCacheVar->setReusable(false); $functionCache = '&' . $functionCacheVar->getName(); } else { $functionCache = 'NULL'; } if (!($method instanceof ReflectionMethod)) { $this->cache[$completeName][$method->getName()] = $functionCache; } return $functionCache . ', ' . $cacheSlot; }
Retrieves/Creates a function cache for a method call. @throws ReflectionException
get
php
zephir-lang/zephir
src/Cache/MethodCache.php
https://github.com/zephir-lang/zephir/blob/master/src/Cache/MethodCache.php
MIT
private function isClassCacheable($classDefinition = null): bool { if ($classDefinition instanceof Definition) { return true; } if (!($classDefinition instanceof ReflectionClass)) { return false; } return $classDefinition->isInternal() && $classDefinition->isInstantiable() && in_array($classDefinition->getExtension()->getName(), ['Reflection', 'Core', 'SPL']); }
Checks if the class is suitable for caching. @param Definition|ReflectionClass|null $classDefinition @return bool
isClassCacheable
php
zephir-lang/zephir
src/Cache/MethodCache.php
https://github.com/zephir-lang/zephir/blob/master/src/Cache/MethodCache.php
MIT
public static function getExistingFunctionSlot(string $functionName): int { return self::$cacheFunctionSlots[$functionName] ?? 0; }
Returns or creates a cache slot for a function.
getExistingFunctionSlot
php
zephir-lang/zephir
src/Cache/SlotsCache.php
https://github.com/zephir-lang/zephir/blob/master/src/Cache/SlotsCache.php
MIT
public static function getFunctionSlot(string $functionName): int { if (isset(self::$cacheFunctionSlots[$functionName])) { return self::$cacheFunctionSlots[$functionName]; } $slot = self::$slot++; if ($slot >= self::MAX_SLOTS_NUMBER) { return 0; } self::$cacheFunctionSlots[$functionName] = $slot; return $slot; }
Returns or creates a cache slot for a function.
getFunctionSlot
php
zephir-lang/zephir
src/Cache/SlotsCache.php
https://github.com/zephir-lang/zephir/blob/master/src/Cache/SlotsCache.php
MIT
public static function getMethodSlot(Method $method): int { $className = $method->getClassDefinition()->getCompleteName(); $methodName = $method->getName(); if (isset(self::$cacheMethodSlots[$className][$methodName])) { return self::$cacheMethodSlots[$className][$methodName]; } $slot = self::$slot++; if ($slot >= self::MAX_SLOTS_NUMBER) { return 0; } self::$cacheMethodSlots[$className][$methodName] = $slot; return $slot; }
Returns or creates a cache slot for a method.
getMethodSlot
php
zephir-lang/zephir
src/Cache/SlotsCache.php
https://github.com/zephir-lang/zephir/blob/master/src/Cache/SlotsCache.php
MIT