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 wait(): void
{
while (!$this->stream->eof()) {
$frame = $this->readFrame();
if (null !== $frame) {
if (!\is_array($frame)) {
$frame = [$frame];
}
foreach ($this->onNewFrameCallables as $newFrameCallable) {
\call_user_func_array($newFrameCallable, $frame);
}
}
}
}
|
Wait for stream to finish and call callables if defined.
|
wait
|
php
|
docker-php/docker-php
|
src/Stream/CallbackStream.php
|
https://github.com/docker-php/docker-php/blob/master/src/Stream/CallbackStream.php
|
MIT
|
public function onStdin(callable $callback): void
{
$this->onStdinCallables[] = $callback;
}
|
Add a callable to read stdin.
@param callable $callback
|
onStdin
|
php
|
docker-php/docker-php
|
src/Stream/DockerRawStream.php
|
https://github.com/docker-php/docker-php/blob/master/src/Stream/DockerRawStream.php
|
MIT
|
public function onStdout(callable $callback): void
{
$this->onStdoutCallables[] = $callback;
}
|
Add a callable to read stdout.
@param callable $callback
|
onStdout
|
php
|
docker-php/docker-php
|
src/Stream/DockerRawStream.php
|
https://github.com/docker-php/docker-php/blob/master/src/Stream/DockerRawStream.php
|
MIT
|
public function onStderr(callable $callback): void
{
$this->onStderrCallables[] = $callback;
}
|
Add a callable to read stderr.
@param callable $callback
|
onStderr
|
php
|
docker-php/docker-php
|
src/Stream/DockerRawStream.php
|
https://github.com/docker-php/docker-php/blob/master/src/Stream/DockerRawStream.php
|
MIT
|
private function forceRead($length)
{
$read = '';
do {
$read .= $this->stream->read($length - \strlen($read));
} while (\strlen($read) < $length && !$this->stream->eof());
return $read;
}
|
Force to have something of the expected size (block).
@param $length
@return string
|
forceRead
|
php
|
docker-php/docker-php
|
src/Stream/DockerRawStream.php
|
https://github.com/docker-php/docker-php/blob/master/src/Stream/DockerRawStream.php
|
MIT
|
public function wait(): void
{
while (!$this->stream->eof()) {
$this->readFrame();
}
}
|
Wait for stream to finish and call callables if defined.
|
wait
|
php
|
docker-php/docker-php
|
src/Stream/DockerRawStream.php
|
https://github.com/docker-php/docker-php/blob/master/src/Stream/DockerRawStream.php
|
MIT
|
public function testCreateFromEnvWithoutCertPath(): void
{
\putenv('DOCKER_TLS_VERIFY=1');
DockerClientFactory::createFromEnv();
}
|
@expectedException \RuntimeException
@expectedExceptionMessage Connection to docker has been set to use TLS, but no PATH is defined for certificate in DOCKER_CERT_PATH docker environment variable
|
testCreateFromEnvWithoutCertPath
|
php
|
docker-php/docker-php
|
tests/DockerClientFactoryTest.php
|
https://github.com/docker-php/docker-php/blob/master/tests/DockerClientFactoryTest.php
|
MIT
|
public function testTarFailed(): void
{
$directory = __DIR__.DIRECTORY_SEPARATOR.'context-test';
$path = \getenv('PATH');
\putenv('PATH=/');
$context = new Context($directory);
try {
$context->toTar();
} finally {
\putenv("PATH=$path");
}
}
|
@expectedException \Symfony\Component\Process\Exception\ProcessFailedException
|
testTarFailed
|
php
|
docker-php/docker-php
|
tests/Context/ContextTest.php
|
https://github.com/docker-php/docker-php/blob/master/tests/Context/ContextTest.php
|
MIT
|
public static function setUpBeforeClass(): void
{
self::getDocker()->imageCreate('', [
'fromImage' => 'busybox:latest',
]);
}
|
Be sure to have image before doing test.
|
setUpBeforeClass
|
php
|
docker-php/docker-php
|
tests/Resource/ContainerResourceTest.php
|
https://github.com/docker-php/docker-php/blob/master/tests/Resource/ContainerResourceTest.php
|
MIT
|
public function testReadJsonEscapedDoubleQuote(string $jsonStream, array $jsonParts): void
{
$stream = new BufferStream();
$stream->write($jsonStream);
$serializer = $this->getMockBuilder(SerializerInterface::class)
->getMock();
$serializer
->expects($this->exactly(\count($jsonParts)))
->method('deserialize')
->withConsecutive(...\array_map(function ($part) {
return [$part, BuildInfo::class, 'json', []];
}, $jsonParts))
;
$stub = $this->getMockForAbstractClass(MultiJsonStream::class, [$stream, $serializer]);
$stub->expects($this->any())
->method('getDecodeClass')
->willReturn('BuildInfo');
$stub->wait();
}
|
@param $jsonStream
@param $jsonParts
@dataProvider jsonStreamDataProvider
|
testReadJsonEscapedDoubleQuote
|
php
|
docker-php/docker-php
|
tests/Stream/MultiJsonStreamTest.php
|
https://github.com/docker-php/docker-php/blob/master/tests/Stream/MultiJsonStreamTest.php
|
MIT
|
public static function createFromGoogleCalendarEvent(Google_Service_Calendar_Event $googleEvent, $calendarId)
{
$event = new static;
$event->googleEvent = $googleEvent;
$event->calendarId = $calendarId;
return $event;
}
|
@param \Google_Service_Calendar_Event $googleEvent
@param $calendarId
@return static
|
createFromGoogleCalendarEvent
|
php
|
spatie/laravel-google-calendar
|
src/Event.php
|
https://github.com/spatie/laravel-google-calendar/blob/master/src/Event.php
|
MIT
|
public static function create(array $properties, ?string $calendarId = null, $optParams = [])
{
$event = new static;
$event->calendarId = static::getGoogleCalendar($calendarId)->getCalendarId();
foreach ($properties as $name => $value) {
$event->$name = $value;
}
return $event->save('insertEvent', $optParams);
}
|
@param array $properties
@param string|null $calendarId
@return mixed
|
create
|
php
|
spatie/laravel-google-calendar
|
src/Event.php
|
https://github.com/spatie/laravel-google-calendar/blob/master/src/Event.php
|
MIT
|
public function add(array $useStatement): void
{
foreach ($useStatement['aliases'] as $alias) {
$implicitAlias = $alias['alias'] ?? $this->implicitAlias($alias['name']);
$this->aliases[$implicitAlias] = $alias['name'];
}
}
|
Adds a renaming in a "use" to the alias manager.
|
add
|
php
|
zephir-lang/zephir
|
src/AliasManager.php
|
https://github.com/zephir-lang/zephir/blob/master/src/AliasManager.php
|
MIT
|
public function getAlias(string $alias): string
{
return $this->aliases[$alias];
}
|
Returns the class name according to an existing alias.
|
getAlias
|
php
|
zephir-lang/zephir
|
src/AliasManager.php
|
https://github.com/zephir-lang/zephir/blob/master/src/AliasManager.php
|
MIT
|
public function getAliasForClassName(string $className): string
{
$keys = array_keys($this->aliases, trim($className, '\\'));
if (1 === count($keys)) {
return $keys[0];
}
return $className;
}
|
Returns alias by fully qualified class name.
@param string $className - fully qualified class name
|
getAliasForClassName
|
php
|
zephir-lang/zephir
|
src/AliasManager.php
|
https://github.com/zephir-lang/zephir/blob/master/src/AliasManager.php
|
MIT
|
public function getAliases(): array
{
return $this->aliases;
}
|
Returns key-value pair of aliases.
|
getAliases
|
php
|
zephir-lang/zephir
|
src/AliasManager.php
|
https://github.com/zephir-lang/zephir/blob/master/src/AliasManager.php
|
MIT
|
public function isAlias(string $alias): bool
{
return isset($this->aliases[$alias]);
}
|
Checks if a class name is an existing alias.
|
isAlias
|
php
|
zephir-lang/zephir
|
src/AliasManager.php
|
https://github.com/zephir-lang/zephir/blob/master/src/AliasManager.php
|
MIT
|
public function isAliasPresentFor(string $className): bool
{
$extractAlias = $this->implicitAlias($className);
$isClassDeclared = in_array($className, $this->aliases);
$classAlias = array_flip($this->aliases)[$className] ?? null;
return $isClassDeclared && $classAlias !== $extractAlias;
}
|
Check if class name has explicit alias in `use` declaration.
@param string $className - fully qualified class name
|
isAliasPresentFor
|
php
|
zephir-lang/zephir
|
src/AliasManager.php
|
https://github.com/zephir-lang/zephir/blob/master/src/AliasManager.php
|
MIT
|
public function isUseStatementAliased(string $alias): bool
{
if ($this->isAlias($alias)) {
return $alias !== $this->implicitAlias($this->getAlias($alias));
}
return false;
}
|
Check if class name use an aliasing in use statement.
ex: use Events\ManagerInterface as EventsManagerInterface;
|
isUseStatementAliased
|
php
|
zephir-lang/zephir
|
src/AliasManager.php
|
https://github.com/zephir-lang/zephir/blob/master/src/AliasManager.php
|
MIT
|
private function implicitAlias(string $className): string
{
$parts = explode('\\', $className);
return $parts[count($parts) - 1];
}
|
Extract implicit alias from use statement.
@param string $className - FQCN or simple class name from use statement
|
implicitAlias
|
php
|
zephir-lang/zephir
|
src/AliasManager.php
|
https://github.com/zephir-lang/zephir/blob/master/src/AliasManager.php
|
MIT
|
public function setType(int $type): void
{
$this->type = $type;
}
|
Set the type of branch. One of the TYPE_* constants.
|
setType
|
php
|
zephir-lang/zephir
|
src/Branch.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Branch.php
|
MIT
|
public function setUnreachable(?bool $unreachable): void
{
$this->unreachable = $unreachable;
}
|
Sets if the branch is unreachable.
|
setUnreachable
|
php
|
zephir-lang/zephir
|
src/Branch.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Branch.php
|
MIT
|
public function addBranch(Branch $branch): void
{
if ($this->currentBranch) {
$branch->setParentBranch($this->currentBranch);
}
$this->currentBranch = $branch;
$branch->setUniqueId($this->uniqueId);
$branch->setLevel($this->level);
++$this->level;
++$this->uniqueId;
if (Branch::TYPE_ROOT == $branch->getType()) {
$this->setRootBranch($branch);
}
}
|
Sets the current active branch in the manager.
@param Branch $branch
|
addBranch
|
php
|
zephir-lang/zephir
|
src/BranchManager.php
|
https://github.com/zephir-lang/zephir/blob/master/src/BranchManager.php
|
MIT
|
public function getCurrentBranch(): ?Branch
{
return $this->currentBranch;
}
|
Returns the active branch in the manager.
|
getCurrentBranch
|
php
|
zephir-lang/zephir
|
src/BranchManager.php
|
https://github.com/zephir-lang/zephir/blob/master/src/BranchManager.php
|
MIT
|
public function removeBranch(Branch $branch): void
{
$parentBranch = $branch->getParentBranch();
$this->currentBranch = $parentBranch;
--$this->level;
}
|
Removes a branch from the branch manager.
|
removeBranch
|
php
|
zephir-lang/zephir
|
src/BranchManager.php
|
https://github.com/zephir-lang/zephir/blob/master/src/BranchManager.php
|
MIT
|
public function addCallStatusFlag(CompilationContext $compilationContext): void
{
if (!$compilationContext->symbolTable->hasVariable('ZEPHIR_LAST_CALL_STATUS')) {
$callStatus = new Variable(
'int',
'ZEPHIR_LAST_CALL_STATUS',
$compilationContext->branchManager->getCurrentBranch()
);
$callStatus->setIsInitialized(true, $compilationContext);
$callStatus->increaseUses();
$callStatus->setReadOnly(true);
$compilationContext->symbolTable->addRawVariable($callStatus);
}
}
|
Add the last-call-status flag to the current symbol table.
|
addCallStatusFlag
|
php
|
zephir-lang/zephir
|
src/Call.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Call.php
|
MIT
|
public function addCallStatusOrJump(CompilationContext $compilationContext): void
{
$compilationContext->headersManager->add('kernel/fcall');
if ($compilationContext->insideTryCatch) {
$compilationContext->codePrinter->output(
'zephir_check_call_status_or_jump(try_end_' . $compilationContext->currentTryCatch . ');'
);
return;
}
$compilationContext->codePrinter->output('zephir_check_call_status();');
}
|
Checks the last call status or make a label jump to the next catch block.t
|
addCallStatusOrJump
|
php
|
zephir-lang/zephir
|
src/Call.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Call.php
|
MIT
|
public function checkTempParameters(CompilationContext $compilationContext): void
{
$compilationContext->headersManager->add('kernel/fcall');
foreach ($this->getMustCheckForCopyVariables() as $checkVariable) {
$compilationContext->codePrinter->output('zephir_check_temp_parameter(' . $checkVariable . ');');
}
}
|
Checks if temporary parameters must be copied or not.
|
checkTempParameters
|
php
|
zephir-lang/zephir
|
src/Call.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Call.php
|
MIT
|
public function getMustCheckForCopyVariables(): array
{
return $this->mustCheckForCopy;
}
|
Parameters to check if they must be copied.
|
getMustCheckForCopyVariables
|
php
|
zephir-lang/zephir
|
src/Call.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Call.php
|
MIT
|
public function getReadOnlyResolvedParams(
array $parameters,
CompilationContext $compilationContext,
array $expression,
): array {
$codePrinter = $compilationContext->codePrinter;
$exprParams = $this->getResolvedParamsAsExpr($parameters, $compilationContext, $expression, true);
$params = [];
$types = [];
$dynamicTypes = [];
foreach ($exprParams as $compiledExpression) {
$expression = $compiledExpression->getOriginal();
switch ($compiledExpression->getType()) {
case 'null':
$params[] = $compilationContext->backend->resolveValue('null', $compilationContext);
$types[] = 'null';
$dynamicTypes[] = 'null';
break;
case 'int':
case 'uint':
case 'long':
$parameterVariable = $compilationContext->backend->getScalarTempVariable(
'variable',
$compilationContext
);
$compilationContext->backend->assignLong(
$parameterVariable,
$compiledExpression->getCode(),
$compilationContext
);
$this->temporalVariables[] = $parameterVariable;
$params[] = '&' . $parameterVariable->getName();
$types[] = $parameterVariable->getType();
$dynamicTypes[] = $parameterVariable->getType();
break;
case 'char':
case 'uchar':
case 'ulong':
case 'string':
case 'istring':
$parameterVariable = $compilationContext->symbolTable->getTempVariableForWrite(
'variable',
$compilationContext,
$expression
);
$compilationContext->backend->assignString(
$parameterVariable,
Name::addSlashes($compiledExpression->getCode()),
$compilationContext
);
$this->temporalVariables[] = $parameterVariable;
$params[] = '&' . $parameterVariable->getName();
$types[] = $parameterVariable->getType();
$dynamicTypes[] = $parameterVariable->getType();
break;
case 'double':
$parameterVariable = $compilationContext->backend->getScalarTempVariable(
'variable',
$compilationContext
);
$codePrinter->output(
'ZVAL_DOUBLE(&' . $parameterVariable->getName() . ', ' . $compiledExpression->getCode() . ');'
);
$this->temporalVariables[] = $parameterVariable;
$params[] = '&' . $parameterVariable->getName();
$types[] = $parameterVariable->getType();
$dynamicTypes[] = $parameterVariable->getType();
break;
case 'bool':
if ('true' == $compiledExpression->getCode()) {
$params[] = $compilationContext->backend->resolveValue('true', $compilationContext);
} else {
if ('false' == $compiledExpression->getCode()) {
$params[] = $compilationContext->backend->resolveValue('false', $compilationContext);
} else {
throw new CompilerException(
'Unable to resolve parameter using zval',
$expression
);
}
}
$types[] = 'bool';
$dynamicTypes[] = 'bool';
break;
case 'array':
$parameterVariable = $compilationContext->symbolTable->getVariableForRead(
$compiledExpression->getCode(),
$compilationContext,
$expression
);
$params[] = $compilationContext->backend->getVariableCode($parameterVariable);
$types[] = $parameterVariable->getType();
$dynamicTypes[] = $parameterVariable->getType();
break;
case 'variable':
$parameterVariable = $compilationContext->symbolTable->getVariableForRead(
$compiledExpression->getCode(),
$compilationContext,
$expression
);
switch ($parameterVariable->getType()) {
case 'int':
case 'uint':
case 'long':
case 'ulong':
$parameterTempVariable = $compilationContext->backend->getScalarTempVariable(
'variable',
$compilationContext
);
$codePrinter->output(
'ZVAL_LONG(&' . $parameterTempVariable->getName() . ', ' . $compiledExpression->getCode(
) . ');'
);
$params[] = '&' . $parameterTempVariable->getName();
$types[] = $parameterTempVariable->getType();
$dynamicTypes[] = $parameterTempVariable->getType();
$this->temporalVariables[] = $parameterTempVariable;
break;
case 'char':
case 'uchar':
$parameterVariable = $compilationContext->symbolTable->getTempVariableForWrite(
'variable',
$compilationContext,
$expression
);
$codePrinter->output(
sprintf(
'ZVAL_STRINGL(&%s, &%s, 1);',
$parameterVariable->getName(),
$compiledExpression->getCode()
)
);
$this->temporalVariables[] = $parameterVariable;
$params[] = '&' . $parameterVariable->getName();
$types[] = $parameterVariable->getType();
$dynamicTypes[] = $parameterVariable->getType();
break;
case 'double':
$parameterTempVariable = $compilationContext->backend->getScalarTempVariable(
'variable',
$compilationContext
);
$codePrinter->output(
'ZVAL_DOUBLE(&' . $parameterTempVariable->getName(
) . ', ' . $compiledExpression->getCode() . ');'
);
$params[] = '&' . $parameterTempVariable->getName();
$types[] = $parameterTempVariable->getType();
$dynamicTypes[] = $parameterTempVariable->getType();
$this->temporalVariables[] = $parameterTempVariable;
break;
case 'bool':
$parameterTempVariable = $compilationContext->backend->getScalarTempVariable(
'variable',
$compilationContext
);
$compilationContext->backend->assignBool(
$parameterTempVariable,
'(' . $parameterVariable->getName() . ' ? 1 : 0)',
$compilationContext
);
$params[] = $compilationContext->backend->getVariableCode($parameterTempVariable);
$dynamicTypes[] = $parameterTempVariable->getType();
$types[] = $parameterTempVariable->getType();
break;
case 'string':
case 'variable':
case 'mixed':
case 'array':
$params[] = $compilationContext->backend->getVariableCode($parameterVariable);
$dynamicTypes[] = $parameterVariable->getType();
$types[] = $parameterVariable->getType();
break;
default:
throw CompilerException::cannotUseVariableTypeAs(
$parameterVariable,
'as parameter',
$expression
);
}
break;
default:
throw CompilerException::cannotUseValueTypeAs(
$compiledExpression,
'parameter',
$expression
);
}
}
$this->resolvedTypes = $types;
$this->resolvedDynamicTypes = $dynamicTypes;
return $params;
}
|
Resolve parameters using zvals in the stack and without allocating memory for constants.
@throws Exception
@throws ReflectionException
|
getReadOnlyResolvedParams
|
php
|
zephir-lang/zephir
|
src/Call.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Call.php
|
MIT
|
public function getResolvedParams(
array $parameters,
CompilationContext $compilationContext,
array $expression,
): array {
$codePrinter = $compilationContext->codePrinter;
$exprParams = $this->getResolvedParamsAsExpr($parameters, $compilationContext, $expression);
$params = [];
$types = [];
$dynamicTypes = [];
$mustCheck = [];
foreach ($exprParams as $compiledExpression) {
$expression = $compiledExpression->getOriginal();
switch ($compiledExpression->getType()) {
case 'null':
$parameterVariable = $compilationContext->backend->getScalarTempVariable(
'variable',
$compilationContext
);
$params[] = $compilationContext->backend->getVariableCode($parameterVariable);
$compilationContext->backend->assignNull($parameterVariable, $compilationContext);
$this->temporalVariables[] = $parameterVariable;
$types[] = $compiledExpression->getType();
$dynamicTypes[] = $compiledExpression->getType();
break;
case 'int':
case 'uint':
case 'long':
$parameterVariable = $compilationContext->backend->getScalarTempVariable(
'variable',
$compilationContext
);
$params[] = $compilationContext->backend->getVariableCode($parameterVariable);
$compilationContext->backend->assignLong(
$parameterVariable,
$compiledExpression->getCode(),
$compilationContext
);
$this->temporalVariables[] = $parameterVariable;
$types[] = $compiledExpression->getType();
$dynamicTypes[] = $compiledExpression->getType();
break;
case 'double':
$parameterVariable = $compilationContext->backend->getScalarTempVariable(
'variable',
$compilationContext
);
$params[] = $compilationContext->backend->getVariableCode($parameterVariable);
$compilationContext->backend->assignDouble(
$parameterVariable,
$compiledExpression->getCode(),
$compilationContext
);
$this->temporalVariables[] = $parameterVariable;
$types[] = $compiledExpression->getType();
break;
case 'bool':
$value = $compiledExpression->getCode();
if ('true' == $value) {
$value = '1';
} elseif ('false' == $value) {
$value = '0';
}
$parameterVariable = $compilationContext->backend->getScalarTempVariable(
'variable',
$compilationContext
);
$params[] = $compilationContext->backend->getVariableCode($parameterVariable);
$compilationContext->backend->assignBool($parameterVariable, $value, $compilationContext);
$this->temporalVariables[] = $parameterVariable;
$types[] = $compiledExpression->getType();
$dynamicTypes[] = $compiledExpression->getType();
break;
case 'ulong':
case 'string':
case 'istring':
$parameterVariable = $compilationContext->symbolTable->getTempVariableForWrite(
'variable',
$compilationContext,
$expression
);
$compilationContext->backend->assignString(
$parameterVariable,
Name::addSlashes($compiledExpression->getCode()),
$compilationContext
);
$this->temporalVariables[] = $parameterVariable;
$params[] = $compilationContext->backend->getVariableCode($parameterVariable);
$types[] = $compiledExpression->getType();
$dynamicTypes[] = $compiledExpression->getType();
break;
case 'array':
$parameterVariable = $compilationContext->symbolTable->getVariableForRead(
$compiledExpression->getCode(),
$compilationContext,
$expression
);
$params[] = $compilationContext->backend->getVariableCode($parameterVariable);
$types[] = $compiledExpression->getType();
$dynamicTypes[] = $compiledExpression->getType();
break;
case 'variable':
$parameterVariable = $compilationContext->symbolTable->getVariableForRead(
$compiledExpression->getCode(),
$compilationContext,
$expression
);
switch ($parameterVariable->getType()) {
case 'int':
case 'uint':
case 'long':
/* ulong must be stored in string */
case 'ulong':
$parameterTempVariable = $compilationContext->backend->getScalarTempVariable(
'variable',
$compilationContext
);
$params[] = $compilationContext->backend->getVariableCode(
$parameterTempVariable
);
$compilationContext->backend->assignLong(
$parameterTempVariable,
$parameterVariable,
$compilationContext
);
$this->temporalVariables[] = $parameterTempVariable;
$types[] = $parameterVariable->getType();
$dynamicTypes[] = $parameterVariable->getType();
break;
case 'double':
$parameterTempVariable = $compilationContext->backend->getScalarTempVariable(
'variable',
$compilationContext
);
$compilationContext->backend->assignDouble(
$parameterTempVariable,
$parameterVariable,
$compilationContext
);
$params[] = $compilationContext->backend->getVariableCode(
$parameterTempVariable
);
$this->temporalVariables[] = $parameterTempVariable;
$types[] = $parameterVariable->getType();
$dynamicTypes[] = $parameterVariable->getType();
break;
case 'bool':
$tempVariable = $compilationContext->backend->getScalarTempVariable(
'variable',
$compilationContext
);
$codePrinter->output('if (' . $parameterVariable->getName() . ') {');
$codePrinter->increaseLevel();
$compilationContext->backend->assignBool($tempVariable, '1', $compilationContext);
$codePrinter->decreaseLevel();
$codePrinter->output('} else {');
$codePrinter->increaseLevel();
$compilationContext->backend->assignBool($tempVariable, '0', $compilationContext);
$codePrinter->decreaseLevel();
$codePrinter->output('}');
$params[] = $compilationContext->backend->getVariableCode($tempVariable);
$types[] = $parameterVariable->getType();
$dynamicTypes[] = $parameterVariable->getType();
break;
case 'string':
case 'array':
$params[] = $compilationContext->backend->getVariableCode($parameterVariable);
$types[] = $parameterVariable->getType();
$dynamicTypes[] = $parameterVariable->getType();
break;
case 'variable':
case 'mixed':
$params[] = $compilationContext->backend->getVariableCode($parameterVariable);
$types[] = $parameterVariable->getType();
$dynamicTypes = array_merge(
$dynamicTypes,
array_keys($parameterVariable->getDynamicTypes())
);
break;
default:
throw CompilerException::cannotUseVariableTypeAs(
$parameterVariable,
'as parameter',
$expression
);
}
break;
default:
throw CompilerException::cannotUseValueTypeAs(
$compiledExpression,
'parameter',
$expression
);
}
}
$this->resolvedTypes = $types;
$this->resolvedDynamicTypes = $dynamicTypes;
$this->mustCheckForCopy = $mustCheck;
return $params;
}
|
Resolve parameters getting aware that the target function/method could retain or change
the parameters.
@throws Exception
@throws ReflectionException
|
getResolvedParams
|
php
|
zephir-lang/zephir
|
src/Call.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Call.php
|
MIT
|
public function getResolvedParamsAsExpr(
array $parameters,
CompilationContext $compilationContext,
array $expression,
bool $readOnly = false
): ?array {
if ($this->resolvedParams) {
return $this->resolvedParams;
}
$hasParametersByName = false;
foreach ($parameters as $parameter) {
if (isset($parameter['name'])) {
$hasParametersByName = true;
break;
}
}
/**
* All parameters must be passed by name
*/
if ($hasParametersByName) {
foreach ($parameters as $parameter) {
if (!isset($parameter['name'])) {
throw new CompilerException('All parameters must use named', $parameter);
}
}
}
if ($hasParametersByName) {
if ($this->reflection) {
$positionalParameters = [];
foreach ($this->reflection->getParameters() as $position => $reflectionParameter) {
if (is_object($reflectionParameter)) {
$positionalParameters[$reflectionParameter->getName()] = $position;
} else {
$positionalParameters[$reflectionParameter['name']] = $position;
}
}
$orderedParameters = [];
foreach ($parameters as $parameter) {
if (isset($positionalParameters[$parameter['name']])) {
$orderedParameters[$positionalParameters[$parameter['name']]] = $parameter;
} else {
throw new CompilerException(
'Named parameter "'
. $parameter['name']
. '" is not a valid parameter name, available: '
. implode(', ', array_keys($positionalParameters)),
$parameter['parameter']
);
}
}
$parameters_count = count($parameters);
for ($i = 0; $i < $parameters_count; ++$i) {
if (!isset($orderedParameters[$i])) {
$orderedParameters[$i] = ['parameter' => ['type' => 'null']];
}
}
$parameters = $orderedParameters;
}
}
$params = [];
foreach ($parameters as $parameter) {
if (is_array($parameter['parameter'])) {
$paramExpr = new Expression($parameter['parameter']);
switch ($parameter['parameter']['type']) {
case 'property-access':
case 'array-access':
case 'static-property-access':
$paramExpr->setReadOnly(true);
break;
default:
$paramExpr->setReadOnly($readOnly);
break;
}
$params[] = $paramExpr->compile($compilationContext);
continue;
}
if ($parameter['parameter'] instanceof CompiledExpression) {
$params[] = $parameter['parameter'];
continue;
}
throw new CompilerException('Invalid expression ', $expression);
}
$this->resolvedParams = $params;
return $this->resolvedParams;
}
|
Resolves parameters.
@throws Exception
@throws ReflectionException
|
getResolvedParamsAsExpr
|
php
|
zephir-lang/zephir
|
src/Call.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Call.php
|
MIT
|
public function getSymbolVariable(bool $useTemp = false, ?CompilationContext $compilationContext = null): ?Variable
{
$symbolVariable = $this->symbolVariable;
if ($useTemp && !is_object($symbolVariable)) {
return $compilationContext->symbolTable->getTempVariableForWrite('variable', $compilationContext);
}
return $symbolVariable;
}
|
Returns the symbol variable that must be returned by the call.
|
getSymbolVariable
|
php
|
zephir-lang/zephir
|
src/Call.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Call.php
|
MIT
|
public function getTemporalVariables(): array
{
return $this->temporalVariables;
}
|
Returns the temporal variables generated during the parameter resolving.
@return Variable[]
|
getTemporalVariables
|
php
|
zephir-lang/zephir
|
src/Call.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Call.php
|
MIT
|
public function isExpectingReturn(): bool
{
return $this->isExpecting;
}
|
Check if an external expression is expecting the call return a value.
|
isExpectingReturn
|
php
|
zephir-lang/zephir
|
src/Call.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Call.php
|
MIT
|
public function mustInitSymbolVariable(): bool
{
return $this->mustInit;
}
|
Returns if the symbol to be returned by the call must be initialized.
|
mustInitSymbolVariable
|
php
|
zephir-lang/zephir
|
src/Call.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Call.php
|
MIT
|
public function processExpectedObservedReturn(CompilationContext $compilationContext): void
{
$expr = $this->expression;
$expression = $expr->getExpression();
/**
* Create temporary variable if needed.
*/
$mustInit = false;
$symbolVariable = null;
$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
);
}
}
$this->mustInit = $mustInit;
$this->symbolVariable = $symbolVariable;
$this->isExpecting = $isExpecting;
}
|
Processes the symbol variable that will be used to return
the result of the symbol call.
|
processExpectedObservedReturn
|
php
|
zephir-lang/zephir
|
src/Call.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Call.php
|
MIT
|
public function processExpectedReturn(CompilationContext $compilationContext): void
{
$expression = $this->expression->getExpression();
/**
* Create temporary variable if needed.
*/
$symbolVariable = null;
$isExpecting = $this->expression->isExpectingReturn();
if ($isExpecting) {
$symbolVariable = $this->expression->getExpectingVariable();
if (is_object($symbolVariable)) {
$readDetector = new ReadDetector();
if ($readDetector->detect($symbolVariable->getName(), $expression)) {
$symbolVariable = $compilationContext->symbolTable->getTempVariableForWrite(
'variable',
$compilationContext,
$expression
);
} else {
$this->mustInit = true;
}
} else {
$symbolVariable = $compilationContext->symbolTable->getTempVariableForWrite(
'variable',
$compilationContext,
$expression
);
}
}
$this->symbolVariable = $symbolVariable;
$this->isExpecting = $isExpecting;
}
|
Processes the symbol variable that will be used to return
the result of the symbol call.
|
processExpectedReturn
|
php
|
zephir-lang/zephir
|
src/Call.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Call.php
|
MIT
|
public function classLookup(string $className, array $statement = []): AbstractDefinition
{
if (!in_array($className, ['self', 'static', 'parent'])) {
$className = $this->getFullName($className);
if ($this->compiler->isClass($className)) {
return $this->compiler->getClassDefinition($className);
}
throw new CompilerException("Cannot locate class '$className'", $statement);
}
if (in_array($className, ['self', 'static'])) {
return $this->classDefinition;
}
$parent = $this->classDefinition->getExtendsClass();
if (!$parent instanceof Definition) {
throw new CompilerException(
sprintf(
'Cannot access parent:: because class %s does not extend any class',
$this->classDefinition->getCompleteName()
),
$statement
);
}
return $this->classDefinition->getExtendsClassDefinition();
}
|
Lookup a class from a given class name.
|
classLookup
|
php
|
zephir-lang/zephir
|
src/CompilationContext.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilationContext.php
|
MIT
|
public function getFullName(string $className): string
{
$isFunction = $this->currentMethod instanceof FunctionDefinition;
$namespace = $isFunction ? $this->currentMethod->getNamespace() : $this->classDefinition->getNamespace();
return Name::fetchFQN($className, $namespace, $this->aliasManager);
}
|
Transform class/interface name to FQN format.
|
getFullName
|
php
|
zephir-lang/zephir
|
src/CompilationContext.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilationContext.php
|
MIT
|
public function getCode(): mixed
{
return $this->code;
}
|
Returns the code produced by the compiled expression.
|
getCode
|
php
|
zephir-lang/zephir
|
src/CompiledExpression.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompiledExpression.php
|
MIT
|
public function getOriginal(): ?array
{
return $this->originalExpr;
}
|
Original AST code that produced the code.
|
getOriginal
|
php
|
zephir-lang/zephir
|
src/CompiledExpression.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompiledExpression.php
|
MIT
|
public function getType(): string
{
return $this->type;
}
|
Returns the type of the compiled expression.
|
getType
|
php
|
zephir-lang/zephir
|
src/CompiledExpression.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompiledExpression.php
|
MIT
|
public function isIntCompatibleType(): bool
{
return in_array($this->type, ['int', 'uint', 'long', 'ulong', 'char', 'uchar'], true);
}
|
Checks if the compiled expression is an integer or compatible type.
|
isIntCompatibleType
|
php
|
zephir-lang/zephir
|
src/CompiledExpression.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompiledExpression.php
|
MIT
|
public function resolve(?string $result, CompilationContext $compilationContext): string
{
if (!($this->code instanceof Closure)) {
return $this->code;
}
$code = $this->code;
if (!$result) {
$tempVariable = $compilationContext->symbolTable->getTempVariableForWrite(
'variable',
$compilationContext
);
$compilationContext->codePrinter->output($code($tempVariable->getName()));
$tempVariable->setIsInitialized(true, $compilationContext);
return $tempVariable->getName();
}
return $code($result);
}
|
Resolves an expression
Some code cannot be directly pushed into the generated source
because it's missing some bound parts, this method resolves the missing parts
returning the generated code.
|
resolve
|
php
|
zephir-lang/zephir
|
src/CompiledExpression.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompiledExpression.php
|
MIT
|
public function addClassDefinition(CompilerFileAnonymous $file, Definition $classDefinition): void
{
$this->definitions[$classDefinition->getCompleteName()] = $classDefinition;
$this->anonymousFiles[$classDefinition->getCompleteName()] = $file;
}
|
Inserts an anonymous class definition in the compiler.
|
addClassDefinition
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function addExternalDependency(string $namespace, string $location): void
{
$this->externalDependencies[$namespace] = $location;
}
|
Adds an external dependency to the compiler.
|
addExternalDependency
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function addFunction(FunctionDefinition $func, array $statement = []): void
{
$funcName = strtolower($func->getInternalName());
if (isset($this->functionDefinitions[$funcName])) {
throw new CompilerException(
"Function '" . $func->getCompleteName() . "' was defined more than one time",
$statement
);
}
$this->functionDefinitions[$funcName] = $func;
}
|
Adds a function to the function definitions.
|
addFunction
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function api(array $options = [], bool $fromGenerate = false): void
{
if (!$fromGenerate) {
$this->generate();
}
$templatesPath = $this->templatesPath ?: dirname(__DIR__) . '/templates';
$documentator = new Documentation($this->files, $this->config, $templatesPath, $options);
$documentator->setLogger($this->logger);
$this->logger->info('Generating API into ' . $documentator->getOutputDirectory());
$documentator->build();
}
|
Generate a HTML API.
@throws ConfigException
@throws Exception
@throws ReflectionException
|
api
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function checkIfPhpized(): bool
{
return !file_exists('ext/Makefile');
}
|
Check if the project must be phpized again.
|
checkIfPhpized
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function compile(bool $development = false, ?int $jobs = null): void
{
$jobs = $jobs ?: 2;
/**
* Get global namespace.
*/
$namespace = str_replace('\\', '_', $this->checkDirectory());
$extensionName = $this->config->get('extension-name');
if (empty($extensionName) || !is_string($extensionName)) {
$extensionName = $namespace;
}
$currentDir = getcwd();
if (file_exists("$currentDir/compile.log")) {
unlink("$currentDir/compile.log");
}
if (file_exists("$currentDir/compile-errors.log")) {
unlink("$currentDir/compile-errors.log");
}
if (file_exists("$currentDir/ext/modules/{$namespace}.so")) {
unlink("$currentDir/ext/modules/{$namespace}.so");
}
if (Os::isWindows()) {
// TODO(klay): Make this better. Looks like it is non standard Env. Var
exec('cd ext && %PHP_DEVPACK%\\phpize --clean', $output, $exit);
$releaseFolder = $this->getWindowsReleaseDir();
if (file_exists($releaseFolder)) {
exec('rd /s /q ' . $releaseFolder, $output, $exit);
}
$this->logger->info('Preparing for PHP compilation...');
// TODO(klay): Make this better. Looks like it is non standard Env. Var
exec('cd ext && %PHP_DEVPACK%\\phpize', $output, $exit);
/**
* fix until patch hits all supported PHP builds.
*
* @see https://github.com/php/php-src/commit/9a3af83ee2aecff25fd4922ef67c1fb4d2af6201
*/
$fixMarker = '/* zephir_phpize_fix */';
$configureFile = file_get_contents('ext\\configure.js');
$configureFix = ["var PHP_ANALYZER = 'disabled';", "var PHP_PGO = 'no';", "var PHP_PGI = 'no';"];
$hasChanged = false;
if (!str_contains($configureFile, $fixMarker)) {
$configureFile = $fixMarker . PHP_EOL . implode(PHP_EOL, $configureFix) . PHP_EOL . $configureFile;
$hasChanged = true;
}
/* fix php's broken phpize patching ... */
$marker = 'var build_dir = (dirname ? dirname : "").replace(new RegExp("^..\\\\\\\\"), "");';
$pos = strpos($configureFile, $marker);
if (false !== $pos) {
$spMarker = 'if (MODE_PHPIZE) {';
$sp = strpos($configureFile, $spMarker, $pos - 200);
if (false === $sp) {
throw new CompilerException('outofdate... phpize seems broken again');
}
$configureFile = substr($configureFile, 0, $sp) .
'if (false) {' . substr($configureFile, $sp + strlen($spMarker));
$hasChanged = true;
}
if ($hasChanged) {
file_put_contents('ext\\configure.js', $configureFile);
}
$this->logger->info('Preparing configuration file...');
exec('cd ext && configure --enable-' . $extensionName);
} else {
exec('cd ext && make clean && phpize --clean', $output, $exit);
$this->logger->info('Preparing for PHP compilation...');
exec('cd ext && phpize', $output, $exit);
$this->logger->info('Preparing configuration file...');
exec(
'cd ext && export CC="gcc" && export CFLAGS="' .
$this->getGccFlags($development) .
'" && ./configure --enable-' .
$extensionName
);
}
$currentDir = getcwd();
$this->logger->info('Compiling...');
if (Os::isWindows()) {
exec(
'cd ext && nmake 2>' . $currentDir . '\compile-errors.log 1>' .
$currentDir . '\compile.log',
$output,
$exit
);
} else {
$this->preCompileHeaders();
exec(
'cd ext && (make -s -j' . $jobs . ' 2>' . $currentDir . '/compile-errors.log 1>' .
$currentDir .
'/compile.log)',
$output,
$exit
);
}
}
|
Compiles the extension without installing it.
@throws Exception
|
compile
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function createConfigFiles(string $project): bool
{
$contentM4 = $this->backend->getTemplateFileContents('config.m4');
if (empty($contentM4)) {
throw new Exception("Template config.m4 doesn't exist");
}
$contentW32 = $this->backend->getTemplateFileContents('config.w32');
if (empty($contentW32)) {
throw new Exception("Template config.w32 doesn't exist");
}
$safeProject = 'zend' === $project ? 'zend_' : $project;
$compiledFiles = array_map(fn($file) => str_replace('.c', '.zep.c', $file), $this->compiledFiles);
/**
* If export-classes is enabled all headers are copied to include/php/ext.
*/
$exportClasses = $this->config->get('export-classes', 'extra');
if ($exportClasses) {
$compiledHeaders = array_map(fn($file) => str_replace('.c', '.zep.h', $file), $this->compiledFiles);
} else {
$compiledHeaders = ['php_' . strtoupper($project) . '.h'];
}
/**
* Check extra-libs, extra-cflags, package-dependencies exists
*/
$extraLibs = (string)$this->config->get('extra-libs');
$extraCflags = (string)$this->config->get('extra-cflags');
$contentM4 = $this->generatePackageDependenciesM4($contentM4);
$buildDirs = [];
foreach ($compiledFiles as $file) {
$dir = dirname($file);
if (!in_array($dir, $buildDirs)) {
$buildDirs[] = $dir;
}
}
asort($buildDirs);
/**
* Generate config.m4.
*/
$toReplace = [
'%PROJECT_LOWER_SAFE%' => strtolower($safeProject),
'%PROJECT_LOWER%' => strtolower($project),
'%PROJECT_UPPER%' => strtoupper($project),
'%PROJECT_CAMELIZE%' => ucfirst($project),
'%FILES_COMPILED%' => implode("\n\t", $this->toUnixPaths($compiledFiles)),
'%HEADERS_COMPILED%' => implode(' ', $this->toUnixPaths($compiledHeaders)),
'%EXTRA_FILES_COMPILED%' => implode("\n\t", $this->toUnixPaths($this->extraFiles)),
'%PROJECT_EXTRA_LIBS%' => $extraLibs,
'%PROJECT_EXTRA_CFLAGS%' => $extraCflags,
'%PROJECT_BUILD_DIRS%' => implode(' ', $buildDirs),
];
foreach ($toReplace as $mark => $replace) {
$contentM4 = str_replace($mark, $replace, $contentM4);
}
HardDisk::persistByHash($contentM4, 'ext/config.m4');
/**
* Generate config.w32.
*/
$toReplace = [
'%PROJECT_LOWER_SAFE%' => strtolower($safeProject),
'%PROJECT_LOWER%' => strtolower($project),
'%PROJECT_UPPER%' => strtoupper($project),
'%FILES_COMPILED%' => implode(
"\r\n\t",
$this->processAddSources($compiledFiles, strtolower($project))
),
'%EXTRA_FILES_COMPILED%' => implode(
"\r\n\t",
$this->processAddSources($this->extraFiles, strtolower($project))
),
];
foreach ($toReplace as $mark => $replace) {
$contentW32 = str_replace($mark, $replace, $contentW32);
}
$needConfigure = HardDisk::persistByHash($contentW32, 'ext/config.w32');
/**
* php_ext.h.
*/
$content = $this->backend->getTemplateFileContents('php_ext.h');
if (empty($content)) {
throw new Exception("Template php_ext.h doesn't exist");
}
$toReplace = [
'%PROJECT_LOWER_SAFE%' => strtolower($safeProject),
];
foreach ($toReplace as $mark => $replace) {
$content = str_replace($mark, $replace, $content);
}
HardDisk::persistByHash($content, 'ext/php_ext.h');
/**
* ext.h.
*/
$content = $this->backend->getTemplateFileContents('ext.h');
if (empty($content)) {
throw new Exception("Template ext.h doesn't exist");
}
$toReplace = [
'%PROJECT_LOWER_SAFE%' => strtolower($safeProject),
];
foreach ($toReplace as $mark => $replace) {
$content = str_replace($mark, $replace, $content);
}
HardDisk::persistByHash($content, 'ext/ext.h');
/**
* ext_config.h.
*/
$content = $this->backend->getTemplateFileContents('ext_config.h');
if (empty($content)) {
throw new Exception("Template ext_config.h doesn't exist");
}
$toReplace = [
'%PROJECT_LOWER%' => strtolower($project),
];
foreach ($toReplace as $mark => $replace) {
$content = str_replace($mark, $replace, $content);
}
HardDisk::persistByHash($content, 'ext/ext_config.h');
/**
* ext_clean.
*/
$content = $this->backend->getTemplateFileContents('clean');
if (empty($content)) {
throw new Exception("Clean file doesn't exist");
}
if (HardDisk::persistByHash($content, 'ext/clean')) {
chmod('ext/clean', 0755);
}
/**
* ext_install.
*/
$content = $this->backend->getTemplateFileContents('install');
if (empty($content)) {
throw new Exception("Install file doesn't exist");
}
$toReplace = [
'%PROJECT_LOWER%' => strtolower($project),
];
foreach ($toReplace as $mark => $replace) {
$content = str_replace($mark, $replace, $content);
}
if (HardDisk::persistByHash($content, 'ext/install')) {
chmod('ext/install', 0755);
}
return (bool)$needConfigure;
}
|
Create config.m4 and config.w32 for the extension.
TODO: move this to backend?
@throws Exception
|
createConfigFiles
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function createProjectFiles(string $project): bool
{
$needConfigure = $this->checkKernelFiles();
/**
* project.c.
*/
$content = $this->backend->getTemplateFileContents('project.c');
if (empty($content)) {
throw new Exception("Template project.c doesn't exist");
}
$includes = '';
$reqInitializers = '';
$reqDestructors = '';
$prqDestructors = '';
$modInitializers = '';
$modDestructors = '';
$glbInitializers = '';
$glbDestructors = '';
$files = array_merge($this->files, $this->anonymousFiles);
/**
* Round 1. Calculate the dependency rank
*/
$this->calculateDependencies($files);
$classEntries = [];
$classInits = [];
$interfaceEntries = [];
$interfaceInits = [];
/**
* Round 2. Generate the ZEPHIR_INIT calls according to the dependency rank
*/
/** @var FileInterface $file */
foreach ($files as $file) {
if ($file->isExternal()) {
continue;
}
$classDefinition = $file->getClassDefinition();
if ($classDefinition === null) {
continue;
}
$dependencyRank = $classDefinition->getDependencyRank();
if ('class' === $classDefinition->getType()) {
$classEntries[$dependencyRank][] = 'zend_class_entry *' . $classDefinition->getClassEntry() . ';';
$classInits[$dependencyRank][] = 'ZEPHIR_INIT('
. $classDefinition->getCNamespace()
. '_'
. $classDefinition->getName()
. ');';
} else {
$interfaceEntries[$dependencyRank][] = 'zend_class_entry *' . $classDefinition->getClassEntry() . ';';
$interfaceInits[$dependencyRank][] = 'ZEPHIR_INIT('
. $classDefinition->getCNamespace()
. '_'
. $classDefinition->getName()
. ');';
}
}
krsort($classInits);
krsort($classEntries);
krsort($interfaceInits);
krsort($interfaceEntries);
$completeInterfaceInits = [];
foreach ($interfaceInits as $rankInterfaceInits) {
asort($rankInterfaceInits, SORT_STRING);
$completeInterfaceInits = array_merge($completeInterfaceInits, $rankInterfaceInits);
}
$completeInterfaceEntries = [];
foreach ($interfaceEntries as $rankInterfaceEntries) {
asort($rankInterfaceEntries, SORT_STRING);
$completeInterfaceEntries = array_merge($completeInterfaceEntries, $rankInterfaceEntries);
}
$completeClassInits = [];
foreach ($classInits as $rankClassInits) {
asort($rankClassInits, SORT_STRING);
$completeClassInits = array_merge($completeClassInits, $rankClassInits);
}
$completeClassEntries = [];
foreach ($classEntries as $rankClassEntries) {
asort($rankClassEntries, SORT_STRING);
$completeClassEntries = array_merge($completeClassEntries, $rankClassEntries);
}
/**
* Round 3. Process extension globals
*/
[$globalCode, $globalStruct, $globalsDefault, $initEntries] = $this->processExtensionGlobals($project);
if ('zend' == $project) {
$safeProject = 'zend_';
} else {
$safeProject = $project;
}
/**
* Round 4. Process extension info.
*/
$phpInfo = $this->processExtensionInfo();
/**
* Round 5. Generate Function entries (FE)
*/
[$feHeader, $feEntries] = $this->generateFunctionInformation();
/**
* Check if there are module/request/global destructors.
*/
$destructors = $this->config->get('destructors');
if (is_array($destructors)) {
$invokeRequestDestructors = $this->processCodeInjection($destructors, 'request');
$includes .= PHP_EOL . $invokeRequestDestructors[0];
$reqDestructors = $invokeRequestDestructors[1];
$invokePostRequestDestructors = $this->processCodeInjection($destructors, 'post-request');
$includes .= PHP_EOL . $invokePostRequestDestructors[0];
$prqDestructors = $invokePostRequestDestructors[1];
$invokeModuleDestructors = $this->processCodeInjection($destructors, 'module');
$includes .= PHP_EOL . $invokeModuleDestructors[0];
$modDestructors = $invokeModuleDestructors[1];
$invokeGlobalsDestructors = $this->processCodeInjection($destructors, 'globals');
$includes .= PHP_EOL . $invokeGlobalsDestructors[0];
$glbDestructors = $invokeGlobalsDestructors[1];
}
/**
* Check if there are module/request/global initializers.
*/
$initializers = $this->config->get('initializers');
if (is_array($initializers)) {
$invokeRequestInitializers = $this->processCodeInjection($initializers, 'request');
$includes .= PHP_EOL . $invokeRequestInitializers[0];
$reqInitializers = $invokeRequestInitializers[1];
$invokeModuleInitializers = $this->processCodeInjection($initializers, 'module');
$includes .= PHP_EOL . $invokeModuleInitializers[0];
$modInitializers = $invokeModuleInitializers[1];
$invokeGlobalsInitializers = $this->processCodeInjection($initializers, 'globals');
$includes .= PHP_EOL . $invokeGlobalsInitializers[0];
$glbInitializers = $invokeGlobalsInitializers[1];
}
/**
* Append extra details.
*/
$extraClasses = $this->config->get('extra-classes');
if (is_array($extraClasses)) {
foreach ($extraClasses as $value) {
if (isset($value['init'])) {
$completeClassInits[] = 'ZEPHIR_INIT(' . $value['init'] . ')';
}
if (isset($value['entry'])) {
$completeClassEntries[] = 'zend_class_entry *' . $value['entry'] . ';';
}
}
}
$modRequires = array_map(
fn($mod) => sprintf('ZEND_MOD_REQUIRED("%s")', strtolower($mod)),
$this->config->get('extensions', 'requires') ?: []
);
$toReplace = [
'%PROJECT_LOWER_SAFE%' => strtolower($safeProject),
'%PROJECT_LOWER%' => strtolower($project),
'%PROJECT_UPPER%' => strtoupper($project),
'%PROJECT_CAMELIZE%' => ucfirst($project),
'%CLASS_ENTRIES%' => implode(
PHP_EOL,
array_merge($completeInterfaceEntries, $completeClassEntries)
),
'%CLASS_INITS%' => implode(
PHP_EOL . "\t",
array_merge($completeInterfaceInits, $completeClassInits)
),
'%INIT_GLOBALS%' => implode(
PHP_EOL . "\t",
array_merge((array)$globalsDefault[0], [$glbInitializers])
),
'%INIT_MODULE_GLOBALS%' => $globalsDefault[1],
'%DESTROY_GLOBALS%' => $glbDestructors,
'%EXTENSION_INFO%' => $phpInfo,
'%EXTRA_INCLUDES%' => implode(
PHP_EOL,
array_unique(explode(PHP_EOL, $includes))
),
'%MOD_INITIALIZERS%' => $modInitializers,
'%MOD_DESTRUCTORS%' => $modDestructors,
'%REQ_INITIALIZERS%' => implode(
PHP_EOL . "\t",
array_merge($this->internalInitializers, [$reqInitializers])
),
'%REQ_DESTRUCTORS%' => $reqDestructors,
'%POSTREQ_DESTRUCTORS%' => empty($prqDestructors) ? '' : implode(
PHP_EOL,
[
'#define ZEPHIR_POST_REQUEST 1',
'static PHP_PRSHUTDOWN_FUNCTION(' . strtolower($project) . ')',
'{',
"\t" . implode(
PHP_EOL . "\t",
explode(PHP_EOL, $prqDestructors)
),
'}',
]
),
'%FE_HEADER%' => $feHeader,
'%FE_ENTRIES%' => $feEntries,
'%PROJECT_INI_ENTRIES%' => implode(PHP_EOL . "\t", $initEntries),
'%PROJECT_DEPENDENCIES%' => implode(PHP_EOL . "\t", $modRequires),
];
foreach ($toReplace as $mark => $replace) {
$content = str_replace($mark, $replace, $content);
}
/**
* Round 5. Generate and place the entry point of the project
*/
HardDisk::persistByHash($content, 'ext/' . $safeProject . '.c');
unset($content);
/**
* Round 6. Generate the project main header.
*/
$content = $this->backend->getTemplateFileContents('project.h');
if (empty($content)) {
throw new Exception("Template project.h doesn't exists");
}
$includeHeaders = [];
foreach ($this->compiledFiles as $file) {
if ($file) {
$fileH = str_replace('.c', '.zep.h', $file);
$include = '#include "' . $fileH . '"';
$includeHeaders[] = $include;
}
}
/**
* Append extra headers.
*/
$extraClasses = $this->config->get('extra-classes');
if (is_array($extraClasses)) {
foreach ($extraClasses as $value) {
if (isset($value['header'])) {
$include = '#include "' . $value['header'] . '"';
$includeHeaders[] = $include;
}
}
}
$toReplace = [
'%INCLUDE_HEADERS%' => implode(PHP_EOL, $includeHeaders),
];
foreach ($toReplace as $mark => $replace) {
$content = str_replace($mark, $replace, $content);
}
HardDisk::persistByHash($content, 'ext/' . $safeProject . '.h');
unset($content);
/**
* Round 7. Create php_project.h.
*/
$content = $this->backend->getTemplateFileContents('php_project.h');
if (empty($content)) {
throw new Exception("Template php_project.h doesn't exist");
}
$toReplace = [
'%PROJECT_LOWER_SAFE%' => strtolower($safeProject),
'%PROJECT_LOWER%' => strtolower($project),
'%PROJECT_UPPER%' => strtoupper($project),
'%PROJECT_EXTNAME%' => strtolower($project),
'%PROJECT_NAME%' => mb_convert_encoding($this->config->get('name'), 'ISO-8859-1', 'UTF-8'),
'%PROJECT_AUTHOR%' => mb_convert_encoding($this->config->get('author'), 'ISO-8859-1', 'UTF-8'),
'%PROJECT_VERSION%' => mb_convert_encoding($this->config->get('version'), 'ISO-8859-1', 'UTF-8'),
'%PROJECT_DESCRIPTION%' => mb_convert_encoding(
$this->config->get('description'),
'ISO-8859-1',
'UTF-8'
),
'%PROJECT_ZEPVERSION%' => Zephir::VERSION,
'%EXTENSION_GLOBALS%' => $globalCode,
'%EXTENSION_STRUCT_GLOBALS%' => $globalStruct,
];
foreach ($toReplace as $mark => $replace) {
$content = str_replace($mark, $replace, $content);
}
HardDisk::persistByHash($content, 'ext/php_' . $safeProject . '.h');
unset($content);
return $needConfigure;
}
|
Create project.c and project.h according to the current extension.
TODO: Move the part of the logic which depends on templates (backend-specific) to backend?
@throws Exception
|
createProjectFiles
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function generate(bool $fromGenerate = false): bool
{
/**
* Get global namespace.
*/
$namespace = $this->checkDirectory();
/**
* Check whether there are external dependencies.
*/
$externalDependencies = $this->config->get('external-dependencies');
if (is_array($externalDependencies)) {
foreach ($externalDependencies as $dependencyNs => $location) {
if (!file_exists($location)) {
throw new CompilerException(
sprintf(
'Location of dependency "%s" does not exist. Check the config.json for more information.',
$dependencyNs
)
);
}
$this->addExternalDependency($dependencyNs, $location);
}
}
/**
* Round 1. pre-compile all files in memory
*/
$this->recursivePreCompile(str_replace('\\', DIRECTORY_SEPARATOR, $namespace));
if (!count($this->files)) {
throw new Exception(
"Zephir files to compile couldn't be found. Did you add a first class to the extension?"
);
}
/**
* Round 2. Check 'extends' and 'implements' dependencies
*/
foreach ($this->files as $compileFile) {
$compileFile->checkDependencies($this);
}
/**
* Sort the files by dependency ranking.
*/
$files = [];
$rankedFiles = [];
$this->calculateDependencies($this->files);
foreach ($this->files as $rankFile) {
$rank = $rankFile->getClassDefinition()->getDependencyRank();
$rankedFiles[$rank][] = $rankFile;
}
krsort($rankedFiles);
foreach ($rankedFiles as $rankFiles) {
$files = array_merge($files, $rankFiles);
}
$this->files = $files;
/**
* Convert C-constants into PHP constants.
*/
$constantsSources = $this->config->get('constants-sources');
if (is_array($constantsSources)) {
$this->loadConstantsSources($constantsSources);
}
/**
* Set extension globals.
*/
$globals = $this->config->get('globals');
if (is_array($globals)) {
$this->setExtensionGlobals($globals);
}
/**
* Load function optimizers
*/
if (false === self::$loadedPrototypes) {
$optimizersPath = $this->resolveOptimizersPath();
FunctionCall::addOptimizerDir("{$optimizersPath}/FunctionCall");
$customOptimizersPaths = $this->config->get('optimizer-dirs');
if (is_array($customOptimizersPaths)) {
foreach ($customOptimizersPaths as $directory) {
FunctionCall::addOptimizerDir(realpath($directory));
}
}
/**
* Load additional extension prototypes.
*/
$prototypesPath = $this->resolvePrototypesPath();
foreach (new DirectoryIterator($prototypesPath) as $file) {
if ($file->isDir() || $file->isDot()) {
continue;
}
// Do not use $file->getRealPath() because it does not work inside phar
$realPath = "{$file->getPath()}/{$file->getFilename()}";
$extension = $file->getBasename(".{$file->getExtension()}");
if (!extension_loaded($extension)) {
require_once $realPath;
}
}
/**
* Load customer additional extension prototypes.
*/
$prototypeDirs = $this->config->get('prototype-dir');
if (is_array($prototypeDirs)) {
foreach ($prototypeDirs as $prototype => $prototypeDir) {
/**
* Check if the extension is installed
*/
if (!extension_loaded($prototype)) {
$prototypeRealpath = realpath($prototypeDir);
if ($prototypeRealpath) {
foreach (new RecursiveDirectoryIterator($prototypeRealpath) as $file) {
if ($file->isDir()) {
continue;
}
require_once $file->getRealPath();
}
}
}
}
}
self::$loadedPrototypes = true;
}
/**
* Round 3. Compile all files to C sources.
*/
$files = [];
$hash = '';
foreach ($this->files as $compileFile) {
/**
* Only compile classes in the local extension, ignore external classes
*/
if (!$compileFile->isExternal()) {
$compileFile->compile($this, $this->stringManager);
$compiledFile = $compileFile->getCompiledFile();
$methods = [];
$classDefinition = $compileFile->getClassDefinition();
foreach ($classDefinition->getMethods() as $method) {
$methods[] = '[' . $method->getName() . ':' . implode('-', $method->getVisibility()) . ']';
if ($method->isInitializer() && $method->isStatic()) {
$this->internalInitializers[] = "\t" . $method->getName() . '();';
}
}
$files[] = $compiledFile;
$hash .= '|'
. $compiledFile
. ':'
. $classDefinition->getClassEntry()
. '['
. implode('|', $methods)
. ']';
}
}
/**
* Round 3.2. Compile anonymous classes
*/
foreach ($this->anonymousFiles as $compileFile) {
$compileFile->compile($this, $this->stringManager);
$compiledFile = $compileFile->getCompiledFile();
$methods = [];
$classDefinition = $compileFile->getClassDefinition();
foreach ($classDefinition->getMethods() as $method) {
$methods[] = '['
. $method->getName()
. ':'
. implode('-', $method->getVisibility())
. ']';
}
$files[] = $compiledFile;
$hash .= '|'
. $compiledFile
. ':'
. $classDefinition->getClassEntry()
. '['
. implode('|', $methods)
. ']';
}
$hash = md5($hash);
$this->compiledFiles = $files;
/**
* Round 3.3. Load extra C-sources.
*/
$extraSources = $this->config->get('extra-sources');
if (is_array($extraSources)) {
$this->extraFiles = $extraSources;
} else {
$this->extraFiles = [];
}
/**
* Round 3.4. Load extra classes sources.
*/
$extraClasses = $this->config->get('extra-classes');
if (is_array($extraClasses)) {
foreach ($extraClasses as $value) {
if (isset($value['source'])) {
$this->extraFiles[] = $value['source'];
}
}
}
/**
* Round 4. Create config.m4 and config.w32 files / Create project.c and project.h files.
*/
$namespace = str_replace('\\', '_', $namespace);
$extensionName = $this->config->get('extension-name');
if (empty($extensionName) || !is_string($extensionName)) {
$extensionName = $namespace;
}
$needConfigure = $this->createConfigFiles($extensionName);
$needConfigure |= $this->createProjectFiles($extensionName);
$needConfigure |= $this->checkIfPhpized();
// Bitwise returns `int` instead of `bool`.
$needConfigure = (bool)$needConfigure;
/**
* When a new file is added or removed we need to run configure again
*/
if (!$fromGenerate) {
if (false === $this->filesystem->exists('compiled-files-sum')) {
$needConfigure = true;
$this->filesystem->write('compiled-files-sum', $hash);
} else {
if ($this->filesystem->read('compiled-files-sum') != $hash) {
$needConfigure = true;
$this->filesystem->delete('compiled-files-sum');
$this->filesystem->write('compiled-files-sum', $hash);
}
}
}
/**
* Round 5. Generate concatenation functions
*/
$this->stringManager->genConcatCode();
$this->fcallManager->genFcallCode();
if ($this->config->get('stubs-run-after-generate', 'stubs')) {
$this->stubs($fromGenerate);
}
return $needConfigure;
}
|
Generates the C sources from Zephir without compiling them.
@throws Exception
@throws ReflectionException
|
generate
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function generatePackageDependenciesM4(string $contentM4): string
{
$packageDependencies = $this->config->get('package-dependencies');
if (!is_array($packageDependencies)) {
return str_replace('%PROJECT_PACKAGE_DEPENDENCIES%', '', $contentM4);
}
$pkgconfigM4 = $this->backend->getTemplateFileContents('pkg-config.m4');
$pkgconfigCheckM4 = $this->backend->getTemplateFileContents('pkg-config-check.m4');
$extraCFlags = '';
foreach ($packageDependencies as $pkg => $version) {
$pkgM4Buf = $pkgconfigCheckM4;
$operator = '=';
$operatorCmd = '--exact-version';
$ar = explode('=', $version);
if (1 === count($ar)) {
if ('*' === $version) {
$version = '0.0.0';
$operator = '>=';
$operatorCmd = '--atleast-version';
}
} else {
switch ($ar[0]) {
case '<':
$operator = '<=';
$operatorCmd = '--max-version';
break;
case '>':
$operator = '>=';
$operatorCmd = '--atleast-version';
break;
}
$version = trim($ar[1]);
}
$toReplace = [
'%PACKAGE_LOWER%' => strtolower($pkg),
'%PACKAGE_UPPER%' => strtoupper($pkg),
'%PACKAGE_REQUESTED_VERSION%' => $operator . ' ' . $version,
'%PACKAGE_PKG_CONFIG_COMPARE_VERSION%' => $operatorCmd . '=' . $version,
];
foreach ($toReplace as $mark => $replace) {
$pkgM4Buf = str_replace($mark, $replace, $pkgM4Buf);
}
$pkgconfigM4 .= $pkgM4Buf;
$extraCFlags .= '$PHP_' . strtoupper($pkg) . '_INCS ';
}
$contentM4 = str_replace('%PROJECT_EXTRA_CFLAGS%', '%PROJECT_EXTRA_CFLAGS% ' . $extraCFlags, $contentM4);
return str_replace('%PROJECT_PACKAGE_DEPENDENCIES%', $pkgconfigM4, $contentM4);
}
|
Generate package-dependencies config for m4.
TODO: Move the template depending part to backend?
|
generatePackageDependenciesM4
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function getClassDefinition(string $className): Definition | bool
{
foreach ($this->definitions as $key => $value) {
if (!strcasecmp($key, $className)) {
return $value;
}
}
return false;
}
|
Returns class the class definition from a given class name.
|
getClassDefinition
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function getConstant(string $name): mixed
{
return $this->constants[$name];
}
|
Returns a Zephir Constant by its name.
|
getConstant
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function getExtensionGlobal(string $name): array
{
return $this->globals[$name];
}
|
Returns an extension global by its name.
|
getExtensionGlobal
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function getGccFlags(bool $development = false): string
{
if (Os::isWindows()) {
// TODO
return '';
}
$gccFlags = getenv('CFLAGS');
if (!is_string($gccFlags)) {
if (false === $development) {
$gccVersion = $this->getGccVersion();
if (version_compare($gccVersion, '4.6.0', '>=')) {
$gccFlags = '-O2 -fvisibility=hidden -Wparentheses -flto -DZEPHIR_RELEASE=1';
} else {
$gccFlags = '-O2 -fvisibility=hidden -Wparentheses -DZEPHIR_RELEASE=1';
}
} else {
$gccFlags = '-O0 -g3';
}
}
return $gccFlags;
}
|
Returns GCC flags for current compilation.
|
getGccFlags
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function getInternalClassDefinition(string $className): Definition
{
if (!isset(self::$internalDefinitions[$className])) {
$reflection = new ReflectionClass($className);
self::$internalDefinitions[$className] = Definition::buildFromReflection($reflection);
}
return self::$internalDefinitions[$className];
}
|
Returns class the class definition from a given class name.
@throws ReflectionException
|
getInternalClassDefinition
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function getParserManager(): Parser\Manager
{
return $this->parserManager;
}
|
Gets the Zephir Parser Manager.
@deprecated
|
getParserManager
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function getPhpIncludeDirs(): string
{
$this->filesystem->system('php-config --includes', 'stdout', 'php-includes');
return trim($this->filesystem->read('php-includes'));
}
|
Returns the php include directories returned by php-config.
|
getPhpIncludeDirs
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function install(bool $development = false): void
{
// Get global namespace
$namespace = str_replace('\\', '_', $this->checkDirectory());
$currentDir = getcwd();
if (Os::isWindows()) {
throw new NotImplementedException('Installation is not implemented for Windows yet. Aborting.');
}
$this->logger->info('Installing...');
$gccFlags = $this->getGccFlags($development);
$command = strtr(
// TODO: Sort out with sudo
'cd ext && export CC="gcc" && export CFLAGS=":cflags" && ' .
'make 2>> ":stderr" 1>> ":stdout" && ' .
'sudo make install 2>> ":stderr" 1>> ":stdout"',
[
':cflags' => $gccFlags,
':stderr' => "{$currentDir}/compile-errors.log",
':stdout' => "{$currentDir}/compile.log",
]
);
array_map(function ($entry): void {
if (!empty($entry)) {
$this->logger->debug(trim($entry));
}
}, explode('&&', $command));
exec($command, $output, $exit);
$fileName = $this->config->get('extension-name') ?: $namespace;
if (false === file_exists("{$currentDir}/ext/modules/{$fileName}.so")) {
throw new CompilerException(
'Internal extension compilation failed. Check compile-errors.log for more information.'
);
}
}
|
Compiles and installs the extension.
@throws Exception
@throws NotImplementedException
@throws CompilerException
|
install
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function isBundledClass(string $className): bool
{
return class_exists($className, false);
}
|
Allows checking if a class is part of PHP.
|
isBundledClass
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function isBundledInterface(string $className): bool
{
return interface_exists($className, false);
}
|
Allows checking if an interface is part of PHP.
|
isBundledInterface
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function isClass(string $className): bool
{
foreach ($this->definitions as $key => $value) {
if (!strcasecmp($key, $className) && 'class' === $value->getType()) {
return true;
}
}
/**
* Try to autoload the class from an external dependency
*/
foreach ($this->externalDependencies as $namespace => $location) {
if (preg_match('#^' . $namespace . '\\\\#i', $className)) {
return $this->loadExternalClass($className, $location);
}
}
return false;
}
|
Allows to check if a class is part of the compiled extension.
|
isClass
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function isConstant(string $name): bool
{
return isset($this->constants[$name]);
}
|
Checks if $name is a Zephir constant.
|
isConstant
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function isExtensionGlobal(string $name): bool
{
return isset($this->globals[$name]);
}
|
Checks if a specific extension global is defined.
|
isExtensionGlobal
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function isInterface(string $className): bool
{
foreach ($this->definitions as $key => $value) {
if (!strcasecmp($key, $className) && Definition::TYPE_INTERFACE === $value->getType()) {
return true;
}
}
/**
* Try to autoload the class from an external dependency
*/
foreach ($this->externalDependencies as $namespace => $location) {
if (preg_match('#^' . $namespace . '\\\\#i', $className)) {
return $this->loadExternalClass($className, $location);
}
}
return false;
}
|
Allows checking if an interface is part of the compiled extension.
@throws CompilerException
@throws IllegalStateException
@throws ParseException
|
isInterface
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function loadExternalClass(string $className, string $location): bool
{
$filePath = $location
. DIRECTORY_SEPARATOR
. strtolower(
str_replace('\\', DIRECTORY_SEPARATOR, $className)
)
. '.zep';
/**
* Fix the class name.
*/
$className = implode(
'\\',
array_map(
'ucfirst',
explode('\\', $className)
)
);
if (isset($this->files[$className])) {
return true;
}
if (!file_exists($filePath)) {
return false;
}
/** @var CompilerFile|CompilerFileAnonymous $compilerFile */
$compilerFile = $this->compilerFileFactory->create($className, $filePath);
$compilerFile->setIsExternal(true);
$compilerFile->preCompile($this);
$this->files[$className] = $compilerFile;
$this->definitions[$className] = $compilerFile->getClassDefinition();
return true;
}
|
Loads a class definition in an external dependency.
@throws CompilerException
@throws IllegalStateException
@throws ParseException
|
loadExternalClass
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function preCompileHeaders(): void
{
if (Os::isWindows()) {
// TODO: Add Windows support
return;
}
$phpIncludes = $this->getPhpIncludeDirs();
/** @var DirectoryIterator $file */
foreach (new DirectoryIterator('ext/kernel') as $file) {
if ($file->isDir() || $file->getExtension() !== 'h') {
continue;
}
$command = sprintf(
'cd ext && gcc -c kernel/%s -I. %s -o kernel/%s.gch',
$file->getBaseName(),
$phpIncludes,
$file->getBaseName()
);
$path = $file->getRealPath();
if (!file_exists($path . '.gch') || filemtime($path) > filemtime($path . '.gch')) {
$this->filesystem->system($command, 'stdout', 'compile-header');
}
}
}
|
Pre-compile headers to speed up compilation.
|
preCompileHeaders
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function processExtensionInfo(): string
{
$phpinfo = '';
$info = $this->config->get('info');
if (!is_array($info)) {
return $phpinfo;
}
foreach ($info as $table) {
$phpinfo .= "\t" . 'php_info_print_table_start();' . PHP_EOL;
if (isset($table['header'])) {
$headerArray = [];
foreach ($table['header'] as $header) {
$headerArray[] = '"' . htmlentities($header) . '"';
}
$phpinfo .= "\t" . 'php_info_print_table_header(' . count($headerArray) . ', ' .
implode(', ', $headerArray) . ');' . PHP_EOL;
}
if (isset($table['rows'])) {
foreach ($table['rows'] as $row) {
$rowArray = [];
foreach ($row as $field) {
$rowArray[] = '"' . htmlentities($field) . '"';
}
$phpinfo .= "\t" . 'php_info_print_table_row(' . count($rowArray) . ', ' .
implode(', ', $rowArray) . ');' . PHP_EOL;
}
}
$phpinfo .= "\t" . 'php_info_print_table_end();' . PHP_EOL;
}
return $phpinfo;
}
|
Generates phpinfo() sections showing information about the extension.
|
processExtensionInfo
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function stubs(bool $fromGenerate = false): void
{
if (!$fromGenerate) {
$this->generate();
}
$this->logger->info('Generating stubs...');
$path = str_replace(
[
'%version%',
'%namespace%',
],
[
$this->config->get('version'),
ucfirst($this->config->get('namespace')),
],
$this->config->get('path', 'stubs')
);
(new Stubs\Generator($this->files))->generate(
$this->config->get('namespace'),
$path,
$this->config->get('indent', 'extra'),
$this->config->get('banner', 'stubs') ?? ''
);
}
|
Generate IDE stubs.
@throws Exception
@throws ReflectionException
|
stubs
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
private function assertRequiredExtensionsIsPresent(): void
{
$extensionRequires = $this->config->get('extensions', 'requires');
if (empty($extensionRequires)) {
return;
}
$extensions = [];
foreach ($extensionRequires as $value) {
// TODO: We'll use this as an object in the future.
if (!is_string($value)) {
continue;
}
if (!extension_loaded($value)) {
$extensions[] = $value;
}
}
if (!empty($extensions)) {
throw new RuntimeException(
sprintf(
'Could not load extension(s): %s. You must load extensions above before build this extension.',
implode(', ', $extensions)
)
);
}
}
|
Ensure that required extensions is present.
@throws RuntimeException
|
assertRequiredExtensionsIsPresent
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
private function checkDirectory(): string
{
$namespace = $this->config->get('namespace');
if (!$namespace) {
// TODO: Add more user friendly message.
// For example assume if the user call the command from the wrong dir
throw new Exception('Extension namespace cannot be loaded');
}
if (!is_string($namespace)) {
throw new Exception('Extension namespace is invalid');
}
if (!$this->filesystem->isInitialized()) {
$this->filesystem->initialize();
}
if (!$this->filesystem->exists('.')) {
if (!$this->checkIfPhpized()) {
$this->logger->info(
'Zephir version has changed, use "zephir fullclean" to perform a full clean of the project'
);
}
$this->filesystem->makeDirectory('.');
}
return $namespace;
}
|
Checks if the current directory is a valid Zephir project.
@throws Exception
|
checkDirectory
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
private function checkKernelFile(string $src, string $dst): bool
{
if (preg_match('#kernels/ZendEngine[2-9]/concat\.#', $src)) {
return true;
}
if (!file_exists($dst)) {
return false;
}
return md5_file($src) === md5_file($dst);
}
|
Checks if a file must be copied.
|
checkKernelFile
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
private function checkKernelFiles(): bool
{
$kernelPath = 'ext' . DIRECTORY_SEPARATOR . 'kernel';
if (!file_exists($kernelPath)) {
if (!mkdir($kernelPath, 0775, true)) {
throw new Exception("Cannot create kernel directory: {$kernelPath}");
}
}
$kernelPath = realpath($kernelPath);
$sourceKernelPath = $this->backend->getInternalKernelPath();
$configured = $this->recursiveProcess(
$sourceKernelPath,
$kernelPath,
'@.*\.[ch]$@',
[$this, 'checkKernelFile']
);
if (!$configured) {
$this->logger->info('Cleaning old kernel files...');
$this->recursiveDeletePath($kernelPath, '@^.*\.[lcho]$@');
@mkdir($kernelPath);
$this->logger->info('Copying new kernel files...');
$this->recursiveProcess($sourceKernelPath, $kernelPath, '@^.*\.[ch]$@');
}
return !$configured;
}
|
Checks which files in the base kernel must be copied.
@throws Exception
|
checkKernelFiles
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
private function loadConstantsSources(array $constantsSources): void
{
foreach ($constantsSources as $constantsSource) {
if (!file_exists($constantsSource)) {
throw new Exception("File '" . $constantsSource . "' with constants definitions");
}
foreach (file($constantsSource) as $line) {
if (preg_match('/^\#define[ \t]+([A-Z0-9\_]+)[ \t]+([0-9]+)/', $line, $matches)) {
$this->constants[$matches[1]] = ['int', $matches[2]];
continue;
}
if (preg_match('/^\#define[ \t]+([A-Z0-9\_]+)[ \t]+(\'(.){1}\')/', $line, $matches)) {
$this->constants[$matches[1]] = ['char', $matches[3]];
}
}
}
}
|
Registers C-constants as PHP constants from a C-file.
@throws Exception
|
loadConstantsSources
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
private function preCompile(string $filePath): void
{
if (!$this->parserManager->isAvailable()) {
throw new IllegalStateException($this->parserManager->requirements());
}
if (preg_match('#\.zep$#', $filePath)) {
$className = str_replace(DIRECTORY_SEPARATOR, '\\', $filePath);
$className = preg_replace('#.zep$#', '', $className);
$className = implode('\\', array_map('ucfirst', explode('\\', $className)));
$compilerFile = $this->compilerFileFactory->create($className, $filePath);
$compilerFile->preCompile($this);
$this->files[$className] = $compilerFile;
$this->definitions[$className] = $compilerFile->getClassDefinition();
}
}
|
Pre-compiles classes creating a CompilerFile definition.
@throws IllegalStateException
|
preCompile
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
private function recursiveDeletePath($path, $mask): void
{
if (!file_exists($path) || !is_dir($path) || !is_readable($path)) {
$this->logger->warning("Directory '{$path}' is not readable. Skip...");
return;
}
$objects = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($objects as $name => $object) {
if (preg_match($mask, $name)) {
@unlink($name);
}
}
}
|
Recursively deletes files in a specified location.
@param string $path Directory to deletes files
@param string $mask Regular expression to deletes files
@deprecated
|
recursiveDeletePath
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
private function recursivePreCompile(string $path): void
{
if (!is_dir($path)) {
throw new InvalidArgumentException(
sprintf(
"An invalid path was passed to the compiler. Unable to obtain the '%s%s%s' directory.",
getcwd(),
DIRECTORY_SEPARATOR,
$path
)
);
}
/**
* Pre compile all files.
*/
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::SELF_FIRST
);
$files = [];
foreach ($iterator as $item) {
if (!$item->isDir()) {
$files[] = $item->getPathname();
}
}
sort($files, SORT_STRING);
foreach ($files as $file) {
$this->preCompile($file);
}
}
|
Recursively pre-compiles all sources found in the given path.
@throws IllegalStateException
@throws InvalidArgumentException
|
recursivePreCompile
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
private function recursiveProcess($src, $dest, $pattern = null, $callback = 'copy')
{
$success = true;
$iterator = new DirectoryIterator($src);
foreach ($iterator as $item) {
$pathName = $item->getPathname();
if (!is_readable($pathName)) {
$this->logger->warning('File is not readable :' . $pathName);
continue;
}
$fileName = $item->getFileName();
if ($item->isDir()) {
if ('.' != $fileName && '..' != $fileName && '.libs' != $fileName) {
if (!is_dir($dest . DIRECTORY_SEPARATOR . $fileName)) {
mkdir($dest . DIRECTORY_SEPARATOR . $fileName, 0755, true);
}
$this->recursiveProcess($pathName, $dest . DIRECTORY_SEPARATOR . $fileName, $pattern, $callback);
}
} elseif (!$pattern || ($pattern && 1 === preg_match($pattern, $fileName))) {
$path = $dest . DIRECTORY_SEPARATOR . $fileName;
$success = $success && call_user_func($callback, $pathName, $path);
}
}
return $success;
}
|
Copies the base kernel to the extension destination.
TODO:
@param $src
@param $dest
@param string $pattern
@param mixed $callback
@return bool
@deprecated
|
recursiveProcess
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
private function resolveOptimizersPath(): ?string
{
$optimizersPath = $this->optimizersPath;
// fallback
if (empty($optimizersPath)) {
$optimizersPath = __DIR__ . '/Optimizers';
}
if (!is_dir($optimizersPath) || !is_readable($optimizersPath)) {
throw new IllegalStateException('Unable to resolve internal optimizers directory.');
}
return $optimizersPath;
}
|
Resolves path to the internal optimizers.
@throws IllegalStateException in case of absence internal optimizers directory
|
resolveOptimizersPath
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
private function resolvePrototypesPath(): ?string
{
$prototypesPath = $this->prototypesPath;
// fallback
if (empty($prototypesPath)) {
$prototypesPath = dirname(__DIR__) . '/prototypes';
}
if (!is_dir($prototypesPath) || !is_readable($prototypesPath)) {
throw new IllegalStateException('Unable to resolve internal prototypes directory.');
}
return $prototypesPath;
}
|
Resolves path to the internal prototypes.
|
resolvePrototypesPath
|
php
|
zephir-lang/zephir
|
src/Compiler.php
|
https://github.com/zephir-lang/zephir/blob/master/src/Compiler.php
|
MIT
|
public function addFunction(Compiler $compiler, FunctionDefinition $func, array $statement = []): void
{
$compiler->addFunction($func, $statement);
$funcName = strtolower($func->getInternalName());
if (isset($this->functionDefinitions[$funcName])) {
throw new CompilerException(
sprintf("Function '%s' was defined more than one time (in the same file)", $func->getName()),
$statement
);
}
$this->functionDefinitions[$funcName] = $func;
}
|
Adds a function to the function definitions.
@throws CompilerException
|
addFunction
|
php
|
zephir-lang/zephir
|
src/CompilerFile.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFile.php
|
MIT
|
public function compile(Compiler $compiler, StringsManager $stringsManager): void
{
if (!$this->ir) {
throw new CompilerException('Unable to locate the intermediate representation of the compiled file');
}
/**
* External classes should not be compiled as part of the extension
*/
if ($this->external) {
return;
}
/**
* Compilation context stores common objects required by compilation entities.
*/
$compilationContext = new CompilationContext();
/**
* Set global compiler in the compilation context
*/
$compilationContext->compiler = $compiler;
/**
* Set global config in the compilation context
*/
$compilationContext->config = $this->config;
/**
* Set global logger in the compilation context
*/
$compilationContext->logger = $this->logger;
/**
* Set global strings manager
*/
$compilationContext->stringsManager = $stringsManager;
$compilationContext->backend = $compiler->backend;
/**
* Headers manager.
*/
$compilationContext->headersManager = new HeadersManager();
/**
* Main code-printer for the file.
*/
$codePrinter = new Printer();
$compilationContext->codePrinter = $codePrinter;
/**
* Alias manager
*/
$compilationContext->aliasManager = $this->aliasManager;
$codePrinter->outputBlankLine();
$class = false;
$interface = false;
foreach ($this->ir as $topStatement) {
switch ($topStatement['type']) {
case 'class':
case Definition::TYPE_INTERFACE:
if ($interface || $class) {
throw new CompilerException('More than one class defined in the same file', $topStatement);
}
$class = true;
$this->compileClass($compilationContext);
break;
case 'comment':
$this->compileComment($compilationContext, $topStatement);
break;
default:
break;
}
}
/* ensure functions are handled last */
foreach ($this->functionDefinitions as $funcDef) {
$this->compileFunction($compilationContext, $funcDef);
}
/* apply headers */
$this->applyClassHeaders($compilationContext);
$classDefinition = $this->classDefinition;
if (!$classDefinition) {
$this->ir = null;
return;
}
$classDefinition->setOriginalNode($this->originalNode);
$completeName = $classDefinition->getCompleteName();
[$path, $filePath, $filePathHeader] = $this->calculatePaths($completeName);
/**
* If the file does not exist we create it for the first time
*/
if (!file_exists($filePath)) {
file_put_contents($filePath, $codePrinter->getOutput());
if ($compilationContext->headerPrinter) {
file_put_contents($filePathHeader, $compilationContext->headerPrinter->getOutput());
}
} else {
/**
* Use md5 hash to avoid rewrite the file again and again when it hasn't changed
* thus avoiding unnecessary recompilations.
*/
$output = $codePrinter->getOutput();
$hash = $this->filesystem->getHashFile('md5', $filePath, true);
if (md5($output) != $hash) {
file_put_contents($filePath, $output);
}
if ($compilationContext->headerPrinter) {
$output = $compilationContext->headerPrinter->getOutput();
$hash = $this->filesystem->getHashFile('md5', $filePathHeader, true);
if (md5($output) != $hash) {
file_put_contents($filePathHeader, $output);
}
}
}
/**
* Add to file compiled
*/
$this->compiledFile = $path . '.c';
$this->ir = null;
}
|
Compiles the file.
@throws Exception
@throws ReflectionException
|
compile
|
php
|
zephir-lang/zephir
|
src/CompilerFile.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFile.php
|
MIT
|
public function compileClass(CompilationContext $compilationContext): void
{
$this->classDefinition->compile($compilationContext);
}
|
Compiles the class/interface contained in the file.
@throws Exception
@throws ReflectionException
|
compileClass
|
php
|
zephir-lang/zephir
|
src/CompilerFile.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFile.php
|
MIT
|
public function compileComment(CompilationContext $compilationContext, array $topStatement): void
{
$compilationContext->codePrinter->output('/' . $topStatement['value'] . '/');
}
|
Compiles a comment as a top-level statement.
|
compileComment
|
php
|
zephir-lang/zephir
|
src/CompilerFile.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFile.php
|
MIT
|
public function compileFunction(
CompilationContext $compilationContext,
FunctionDefinition $functionDefinition,
): void {
/** Make sure we do not produce calls like ZEPHIR_CALL_SELF */
$bakClassDefinition = $compilationContext->classDefinition;
$compilationContext->classDefinition = null;
$compilationContext->currentMethod = $functionDefinition;
$codePrinter = $compilationContext->codePrinter;
$codePrinter->output('PHP_FUNCTION(' . $functionDefinition->getInternalName() . ') {');
$functionDefinition->compile($compilationContext);
$codePrinter->output('}');
$codePrinter->outputBlankLine();
/* Restore */
$compilationContext->classDefinition = $bakClassDefinition;
$compilationContext->currentMethod = null;
}
|
Compiles a function.
@throws Exception
@throws ReflectionException
|
compileFunction
|
php
|
zephir-lang/zephir
|
src/CompilerFile.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFile.php
|
MIT
|
public function genIR(Compiler $compiler): array
{
$normalizedPath = $this->filesystem->normalizePath($this->filePath);
$compilePath = "{$normalizedPath}.json";
$zepRealPath = realpath($this->filePath);
if ($this->filesystem->exists($compilePath)) {
if ($this->filesystem->modificationTime($compilePath) < filemtime($zepRealPath)) {
$this->filesystem->delete($compilePath);
}
}
if (!$this->filesystem->exists($compilePath)) {
$parser = $compiler->getParserManager()->getParser();
$ir = $parser->parse($zepRealPath);
$this->filesystem->write($compilePath, json_encode($ir, JSON_PRETTY_PRINT));
} else {
$ir = json_decode($this->filesystem->read($compilePath), true);
}
return $ir;
}
|
Compiles the file generating a JSON intermediate representation.
@throws ParseException
@throws IllegalStateException if the intermediate representation is not of type 'array'
|
genIR
|
php
|
zephir-lang/zephir
|
src/CompilerFile.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFile.php
|
MIT
|
public function getCompiledFile(): string
{
return $this->compiledFile;
}
|
Returns the path to the compiled file.
|
getCompiledFile
|
php
|
zephir-lang/zephir
|
src/CompilerFile.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFile.php
|
MIT
|
public function getFilePath(): string
{
return $this->filePath;
}
|
Returns the path to the source file.
|
getFilePath
|
php
|
zephir-lang/zephir
|
src/CompilerFile.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFile.php
|
MIT
|
public function preCompile(Compiler $compiler): void
{
$ir = $this->genIR($compiler);
if (isset($ir['type']) && 'error' == $ir['type']) {
throw new ParseException($ir['message'], $ir);
}
/**
* Compilation context stores common objects required by compilation entities.
*/
$compilationContext = new CompilationContext();
$compilationContext->compiler = $compiler;
$compilationContext->config = $this->config;
$compilationContext->logger = $this->logger;
$compilationContext->aliasManager = $this->aliasManager;
$compilationContext->backend = $compiler->backend;
/**
* Traverse the top level statements looking for the namespace.
*/
$namespace = '';
foreach ($ir as $topStatement) {
switch ($topStatement['type']) {
case 'namespace':
if ($namespace !== '') {
throw new CompilerException('The namespace must be defined just one time', $topStatement);
}
$namespace = $topStatement['name'];
$this->namespace = $namespace;
if (!preg_match('/^[A-Z]/', $namespace)) {
throw new CompilerException(
"Namespace '{$namespace}' must be in camelized-form",
$topStatement
);
}
break;
case 'cblock':
$this->headerCBlocks[] = $topStatement['value'];
break;
case 'function':
$statements = null;
if (isset($topStatement['statements'])) {
$statements = new StatementsBlock($topStatement['statements']);
}
$parameters = null;
if (isset($topStatement['parameters'])) {
$parameters = new Parameters($topStatement['parameters']);
}
$returnType = null;
if (isset($topStatement['return-type'])) {
$returnType = $topStatement['return-type'];
}
// Just do the pre-compilation of the function
$functionDefinition = new FunctionDefinition(
$namespace,
$topStatement['name'],
$parameters,
$statements,
$returnType,
$topStatement
);
$functionDefinition->preCompile($compilationContext);
$this->addFunction($compiler, $functionDefinition, $topStatement);
break;
}
}
if (!$namespace) {
throw new CompilerException('A namespace is required', $topStatement ?? null);
}
// Set namespace and flag as global, if before namespace declaration
foreach ($this->functionDefinitions as $funcDef) {
if (null == $funcDef->getNamespace()) {
$funcDef->setGlobal(true);
$funcDef->setNamespace($this->config->get('namespace'));
}
}
$name = null;
$class = false;
$interface = false;
$lastComment = null;
foreach ($ir as $topStatement) {
switch ($topStatement['type']) {
case 'class':
if ($class || $interface) {
throw new CompilerException(
'More than one class/interface defined in the same file',
$topStatement
);
}
$class = true;
$name = $topStatement['name'];
$this->preCompileClass($compilationContext, $namespace, $topStatement, $lastComment);
$this->originalNode = $topStatement;
$lastComment = null;
break;
case Definition::TYPE_INTERFACE:
if ($class || $interface) {
throw new CompilerException(
'More than one class/interface defined in the same file',
$topStatement
);
}
$interface = true;
$name = $topStatement['name'];
$this->preCompileInterface($namespace, $topStatement, $lastComment);
$this->originalNode = $topStatement;
$lastComment = null;
break;
case 'use':
if ($interface || $class) {
throw new CompilerException(
'Aliasing must be done before declaring any class or interface',
$topStatement
);
}
$this->aliasManager->add($topStatement);
break;
case 'comment':
$lastComment = $topStatement;
break;
}
}
if (!$class && !$interface) {
throw new CompilerException(
'Every file must contain at least a class or an interface',
$topStatement ?? null
);
}
if (!$this->external) {
$expectedPath = strtolower(
str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR . $name . '.zep'
);
if (strtolower($this->filePath) != $expectedPath) {
$className = $namespace . '\\' . $name;
throw new CompilerException(
sprintf(
"Unexpected class name '%s' in file: '%s', expected: '%s'",
$className,
$this->filePath,
$expectedPath
)
);
}
}
if ($compilationContext->classDefinition) {
if ($extendsClass = $compilationContext->classDefinition->getExtendsClass()) {
$compiler->isClass($extendsClass);
}
if ($interfaces = $compilationContext->classDefinition->getImplementedInterfaces()) {
foreach ($interfaces as $interface) {
$compiler->isInterface($interface);
}
}
}
$this->ir = $ir;
}
|
Pre-compiles a Zephir file.
Generates the IR and perform basic validations.
@throws CompilerException
@throws IllegalStateException
@throws ParseException
|
preCompile
|
php
|
zephir-lang/zephir
|
src/CompilerFile.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFile.php
|
MIT
|
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/CompilerFile.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFile.php
|
MIT
|
protected function getFullName(string $name): string
{
return Name::fetchFQN($name, $this->namespace, $this->aliasManager);
}
|
Transform class/interface name to FQN format.
|
getFullName
|
php
|
zephir-lang/zephir
|
src/CompilerFile.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFile.php
|
MIT
|
protected function processShortcuts(array $property, Definition $classDefinition): void
{
foreach ($property['shortcuts'] as $shortcut) {
if (str_starts_with($property['name'], '_')) {
$name = substr($property['name'], 1);
} else {
$name = $property['name'];
}
$docBlock = null;
if (isset($shortcut['docblock'])) {
$docBlock = $shortcut['docblock'];
} elseif (isset($property['docblock'])) {
$docBlock = $property['docblock'];
}
$returnsType = [];
if ($docBlock) {
$docBlockParser = new DocblockParser('/' . $docBlock . '/');
$docBlockParsed = $docBlockParser->parse();
if ($annotations = $docBlockParsed->getAnnotationsByType('var')) {
$returnsType = array_map(
fn($type) => 'mixed' == ($type = trim($type)) ? 'variable' : $type,
explode('|', $annotations[0]->getString())
);
}
// Clear annotations
$docBlockParsed->setAnnotations([]);
$docBlock = $docBlockParsed->generate();
}
switch ($shortcut['name']) {
case 'get':
$classDefinition->addMethod(
new Method(
$classDefinition,
['public'],
'get' . Name::camelize($name),
null,
new StatementsBlock([
[
'type' => 'return',
'expr' => [
'type' => 'property-access',
'left' => [
'type' => 'variable',
'value' => 'this',
],
'right' => [
'type' => 'variable',
'value' => $property['name'],
],
],
],
]),
$docBlock,
$this->createReturnsType($returnsType, true),
$shortcut
),
$shortcut
);
break;
case 'set':
$classDefinition->addMethod(
new Method(
$classDefinition,
['public'],
'set' . Name::camelize($name),
new Parameters([
[
'type' => 'parameter',
'name' => $name,
'const' => 0,
'data-type' => 1 == count($returnsType) ? $returnsType[0] : 'variable',
'mandatory' => 0,
],
]),
new StatementsBlock([
[
'type' => 'let',
'assignments' => [
[
'assign-type' => 'object-property',
'operator' => 'assign',
'variable' => 'this',
'property' => $property['name'],
'expr' => [
'type' => 'variable',
'value' => $name,
'file' => $property['file'],
'line' => $property['line'],
'char' => $property['char'],
],
'file' => $property['file'],
'line' => $property['line'],
'char' => $property['char'],
],
],
],
[
'type' => 'return',
'expr' => [
'type' => 'variable',
'value' => 'this',
'file' => $property['file'],
'line' => $property['line'],
'char' => $property['char'],
],
],
]),
$docBlock,
null,
$shortcut
),
$shortcut
);
break;
case 'toString':
case '__toString':
$classDefinition->addMethod(
new Method(
$classDefinition,
['public'],
'__toString',
null,
new StatementsBlock([
[
'type' => 'return',
'expr' => [
'type' => 'property-access',
'left' => [
'type' => 'variable',
'value' => 'this',
],
'right' => [
'type' => 'variable',
'value' => $property['name'],
],
],
],
]),
$docBlock,
$this->createReturnsType(['string']),
$shortcut
),
$shortcut
);
break;
default:
throw new CompilerException("Unknown shortcut '" . $shortcut['name'] . "'", $shortcut);
}
}
}
|
Creates the property shortcuts.
@throws CompilerException
|
processShortcuts
|
php
|
zephir-lang/zephir
|
src/CompilerFile.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFile.php
|
MIT
|
public function __construct(
protected Definition $classDefinition,
protected Config $config,
protected ?CompilationContext $context = null
) {
$this->logger = new NullLogger();
}
|
CompilerFileAnonymous constructor.
@param Definition $classDefinition
@param Config $config
@param CompilationContext|null $context
|
__construct
|
php
|
zephir-lang/zephir
|
src/CompilerFileAnonymous.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFileAnonymous.php
|
MIT
|
public function compile(Compiler $compiler, StringsManager $stringsManager): void
{
/**
* Compilation context stores common objects required by compilation entities.
*/
$compilationContext = new CompilationContext();
if ($this->context) {
$compilationContext->aliasManager = $this->context->aliasManager;
} else {
$compilationContext->aliasManager = new AliasManager();
}
$compilationContext->compiler = $compiler;
$compilationContext->config = $this->config;
$compilationContext->logger = $this->logger;
$compilationContext->stringsManager = $stringsManager;
$compilationContext->backend = $compiler->backend;
$compilationContext->headersManager = new HeadersManager();
/**
* Main code-printer for the file.
*/
$codePrinter = new Printer();
$compilationContext->codePrinter = $codePrinter;
$codePrinter->outputBlankLine();
$this->compileClass($compilationContext);
$completeName = $this->classDefinition->getCompleteName();
[$path, $filePath, $filePathHeader] = $this->calculatePaths($completeName);
/**
* If the file does not exist we create it for the first time
*/
if (!file_exists($filePath)) {
file_put_contents($filePath, $codePrinter->getOutput());
if ($compilationContext->headerPrinter) {
file_put_contents($filePathHeader, $compilationContext->headerPrinter->getOutput());
}
} else {
/**
* Use md5 hash to avoid rewrite the file again and again when it hasn't changed
* thus avoiding unnecessary recompilations.
*/
$output = $codePrinter->getOutput();
$hash = hash_file('md5', $filePath);
if (md5($output) !== $hash) {
file_put_contents($filePath, $output);
}
if ($compilationContext->headerPrinter) {
$output = $compilationContext->headerPrinter->getOutput();
$hash = hash_file('md5', $filePathHeader);
if (md5($output) !== $hash) {
file_put_contents($filePathHeader, $output);
}
}
}
/**
* Add to file compiled
*/
$this->compiledFile = $path . '.c';
}
|
Compiles the file.
@throws Exception|ReflectionException
|
compile
|
php
|
zephir-lang/zephir
|
src/CompilerFileAnonymous.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFileAnonymous.php
|
MIT
|
public function getCompiledFile(): string
{
return $this->compiledFile;
}
|
Returns the path to the compiled file.
|
getCompiledFile
|
php
|
zephir-lang/zephir
|
src/CompilerFileAnonymous.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFileAnonymous.php
|
MIT
|
public function preCompile(Compiler $compiler): void
{
// nothing to do
}
|
Only implemented to satisfy the Zephir\Compiler\FileInterface interface.
|
preCompile
|
php
|
zephir-lang/zephir
|
src/CompilerFileAnonymous.php
|
https://github.com/zephir-lang/zephir/blob/master/src/CompilerFileAnonymous.php
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.