-
-
Notifications
You must be signed in to change notification settings - Fork 468
/
Copy pathzephir
550 lines (440 loc) · 16.5 KB
/
zephir
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
#!/usr/bin/env php
<?php
/**
* This file is part of the Zephir.
*
* (c) Phalcon Team <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Phalcon\Cop\Parser as CliParser;
use Zephir\Backend\Backend;
use Zephir\Compiler;
use Zephir\Config;
use Zephir\Exception\CompilerException;
use Zephir\Exception\ExceptionInterface;
use Zephir\Exception\FileSystemException;
use Zephir\Exception\NotImplementedException;
use Zephir\FileSystem\HardDisk;
use Zephir\Logger\Formatter\CompilerFormatter;
use Zephir\Os;
use Zephir\Parser\Manager;
use Zephir\Parser\Parser;
use Zephir\Zephir;
if (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') {
fprintf(
STDERR,
'Zephir should be invoked via the CLI version of PHP, not the %s SAPI.'.PHP_EOL,
PHP_SAPI
);
exit(1);
}
foreach ([__DIR__ . '/../../autoload.php', __DIR__ . '/../vendor/autoload.php', __DIR__ . '/vendor/autoload.php'] as $file) {
if (file_exists($file)) {
include_once $file;
break;
}
}
if (!class_exists('Composer\Autoload\ClassLoader', false)) {
fwrite(STDERR, 'Unable to find the Composer autoloader.'.PHP_EOL);
exit(1);
}
set_error_handler(static function ($code, $message, $file = '', $line = -1) {
if (error_reporting() & $code) {
throw new ErrorException($message, 0, $code, (string) $file, $line);
}
});
if (filter_var(getenv('ZEPHIR_DEBUG'), FILTER_VALIDATE_BOOLEAN)) {
set_exception_handler(static function (Throwable $t) {
fwrite(STDERR, "[ERROR] {$t->getMessage()}". PHP_EOL);
exit(1);
});
}
/**
* When it is executed inside .phar, realpath() will return `false`.
*/
$rootPath = Phar::running() ?: realpath(dirname(__FILE__));
$config = Config::fromServer();
/**
* Logger
*/
$formatter = new CompilerFormatter($config);
$consoleStdErrorHandler = new StreamHandler('php://stderr', Logger::WARNING, false);
$consoleStdErrorHandler->setFormatter($formatter);
$consoleStdOutHandler = new StreamHandler('php://stdout', Logger::INFO, false);
$consoleStdOutHandler->setFormatter($formatter);
$disk = new HardDisk(getcwd().'/.zephir');
$parser = new Parser();
$logger = new Logger('zephir', [
$consoleStdErrorHandler,
$consoleStdOutHandler,
]);
$compilerFactory = new Compiler\CompilerFileFactory($config, $disk, $logger);
$backend = new Backend($config, $rootPath.'/kernel', $rootPath.'/templates');
$compiler = new Compiler($config, $backend, new Manager($parser), $disk, $compilerFactory);
$compiler->setPrototypesPath($rootPath.'/prototypes');
$compiler->setOptimizersPath($rootPath.'/src/Optimizers');
$compiler->setTemplatesPath($rootPath.'/templates');
$compiler->setLogger($logger);
$cli = new CliParser();
$params = $cli->parse();
$showHelp = isset($params['help']) || isset($params['h']);
$devMode = isset($params['dev']);
$trace = isset($params['trace']);
$jobs = $params['jobs'] ?? $params['j'] ?? null;
$jobs = $jobs ? (int)$jobs : null;
$command = $params[0] ?? 'help';
switch ($command) {
case 'api':
if ($showHelp) {
fwrite(STDOUT, <<<HELP
Description:
Generates an HTML API based on the classes exposed in the extension.
Common flags are:
-f([a-z0-9\-]+) Enables compiler optimizations
-fno-([a-z0-9\-]+) Disables compiler optimizations
-w([a-z0-9\-]+) Turns a warning on
-W([a-z0-9\-]+) Turns a warning off
Usage:
api [options]
Options:
-p, --path=PATH The API theme to be used
-o, --output=OUTPUT Output directory to generate theme
--options=OPTIONS Theme options
--url=URL The base URL to be used when generating links
-h, --help Print this help message
HELP);
exit(0);
}
$defaultOptions = [
'path' => null,
'output' => $config->get('path', 'api'),
'options' => null,
'url' => $config->get('base-url', 'api'),
];
$sanitizeOptionsFromInput = function (array $input) use ($defaultOptions): array {
$options = array_filter($input, function ($v, $k) use ($defaultOptions) {
$allowedOpts = array_keys($defaultOptions);
return in_array($k, $allowedOpts, true) && null !== $v;
}, ARRAY_FILTER_USE_BOTH);
foreach ($options as $option => $value) {
// Prevent "" values
if (empty($value) || !preg_match('/.+/', $value)) {
throw new InvalidArgumentException(
sprintf('The "--%s" option requires a value.', $option)
);
}
}
return $options;
};
break;
case 'build':
if ($showHelp) {
fwrite(STDOUT, <<<'EOT'
This is a meta command that just calls the <info>generate</info>, <info>compile</info> and <info>install</info> commands.
Using <comment>--dev</comment> option will force building and installing the extension in development mode
(debug symbols and no optimizations). An extension compiled with debugging symbols means
you can run a program or library through a debugger and the debugger's output will be user
friendlier. These debugging symbols also enlarge the program or library significantly.
NOTE: Zephir development mode will be enabled silently if your PHP binary was compiled in
a debug configuration.
In some cases, we would like to get production ready extension even if the PHP binary was
compiled in a debug configuration. Use <comment>--no-dev</comment> option to achieve this behavior.
EOT);
exit(0);
}
if (!generate($trace)) {
exit(1);
}
if (!compile($devMode, $jobs)) {
exit(1);
}
install($devMode);
break;
case 'clean':
if ($showHelp) {
fwrite(STDOUT, 'Cleans any object files created by the extension' . PHP_EOL);
exit(0);
}
if (!$disk->isInitialized()) {
$disk->initialize();
}
try {
$disk->clean();
if (Os::isWindows()) {
system('cd ext && nmake clean-all');
} else {
system('cd ext && make clean > /dev/null');
}
} catch (FileSystemException $e) {
fwrite(
STDERR,
sprintf(
"For reasons beyond Zephir's control, a filesystem error has occurred. " .
'Please note: On Linux/Unix systems the current user must have the delete and execute ' .
'permissions on the internal cache directory, For more information see chmod(1) and chown(1). ' .
'System error was: %s',
$e->getMessage()
)
);
} catch (Exception | Throwable $e) {
fwrite(STDERR, $e->getMessage() . PHP_EOL);
}
break;
case 'compile':
if ($showHelp) {
fwrite(STDOUT, <<<EOT
Using <comment>--dev</comment> option will force compiling the extension in development mode
(debug symbols and no optimizations). An extension compiled with debugging symbols means
you can run a program or library through a debugger and the debugger's output will be user
friendlier. These debugging symbols also enlarge the program or library significantly.
NOTE: Zephir development mode will be enabled silently if your PHP binary was compiled in
a debug configuration.
In some cases, we would like to get production ready extension even if the PHP binary was
compiled in a debug configuration. Use <comment>--no-dev</comment> option to achieve this behavior.
EOT);
exit(0);
}
compile($devMode, $jobs);
break;
case 'fullclean':
if ($showHelp) {
fwrite(STDOUT, <<<HELP
Description:
Cleans any object files created by the extension (including files generated by phpize)
Usage:
fullclean
Options:
-h, --help Print this help message
HELP);
exit(0);
}
try {
if (Os::isWindows()) {
system('cd ext && phpize --clean');
} else {
system('cd ext && phpize --clean > /dev/null');
system('cd ext && ./clean > /dev/null');
}
} catch (FileSystemException $e) {
fwrite(
STDERR,
sprintf(
"For reasons beyond Zephir's control, a filesystem error has occurred. " .
'Please note: On Linux/Unix systems the current user must have the delete and execute ' .
'permissions on the internal cache directory, For more information see chmod(1) and chown(1). ' .
'System error was: %s',
$e->getMessage()
)
);
}
break;
case 'generate':
if ($showHelp) {
fwrite(STDOUT, 'Generates C code from the Zephir code without compiling it' . PHP_EOL);
exit(0);
}
if (!generate($trace)) {
exit(1);
}
break;
case 'init':
if ($showHelp) {
fwrite(STDOUT, 'Initializes a Zephir extension' . PHP_EOL);
exit(0);
}
$namespace = $params[1] ?? $params['namespace'] ?? null;
if ($namespace === null) {
fwrite(STDERR, 'Not enough arguments (missing: "namespace").' . PHP_EOL);
exit(1);
}
init($namespace);
break;
case 'install':
if ($showHelp) {
fwrite(STDOUT, <<<EOT
Using <comment>--dev</comment> option will try installing the extension in development mode
(debug symbols and no optimizations). An extension compiled with debugging symbols means
you can run a program or library through a debugger and the debugger's output will be user
friendlier. These debugging symbols also enlarge the program or library significantly.
NOTE: Zephir development mode will be enabled silently if your PHP binary was compiled in
a debug configuration.
In some cases, we would like to get production ready extension even if the PHP binary was
compiled in a debug configuration. Use <comment>--no-dev</comment> option to achieve this behavior.
NOTE: This command may require root password on Linux/Unit systems.
EOT);
exit(0);
}
install($devMode);
break;
case 'stubs':
if ($showHelp) {
fwrite(STDOUT, 'Generates stubs that can be used in a PHP IDE' . PHP_EOL);
exit(0);
}
$compiler->stubs();
break;
case 'help':
default:
$version = explode('-', Zephir::VERSION);
$logo = Zephir::LOGO;
fwrite(STDOUT, Zephir::LOGO . sprintf('Zephir %s by the Phalcon Team', $version[0]) . PHP_EOL);
fwrite(STDOUT, <<<HELP
Usage:
command [options] [arguments]
Options:
--dumpversion Print the version of the compiler and don't do anything else (also works with a single hyphen)
-h, --help Print this help message
--no-ansi Disable ANSI output
-v, --verbose Displays more detail in error messages from exceptions generated by commands (can also disable with -V)
--vernum Print the version of the compiler as integer
--version Print compiler version information and quit
Available commands:
api Generates a HTML API based on the classes exposed in the extension
build Generates/Compiles/Installs a Zephir extension
clean Cleans any object files created by the extension
compile Compile a Zephir extension
fullclean Cleans any object files created by the extension (including files generated by phpize)
generate Generates C code from the Zephir code without compiling it
help Display help for a command
init Initializes a Zephir extension
install Installs the extension in the extension directory (may require root password)
stubs Generates stubs that can be used in a PHP IDE
HELP);
break;
}
function generate(bool $trace = false): bool
{
global $compiler;
if (extension_loaded('timecop') && 1 == ini_get('timecop.func_override')) {
fwrite(STDOUT, <<<MSG
The timecop extension was detected. It is recommended to disable
it from the launcher during the code generation to avoid potential
issues.
For more see:
- https://github.com/zephir-lang/zephir/issues/1950
- https://github.com/phalcon/cphalcon/issues/13117
MSG);
return false;
}
try {
$compiler->generate(true);
} catch (InvalidArgumentException $e) {
fwrite(STDERR, sprintf(
'Internal error: %s at %s:%d',
$e->getMessage(),
$e->getFile(),
$e->getLine()
));
return false;
} catch (ExceptionInterface | Exception $e) {
if ($trace === true) {
fwrite(STDERR, $e->getMessage() . sprintf(' (Zephir file: %s#%d)', $e->getFile(), $e->getLine()) . PHP_EOL);
fwrite(STDERR, $e->getTraceAsString() . PHP_EOL);
} else {
fwrite(STDERR, $e->getMessage() . PHP_EOL);
}
return false;
}
return true;
}
function compile(bool $development = false, ?int $jobs = null): bool
{
global $compiler;
try {
$compiler->compile(
$development,
$jobs,
);
return true;
} catch (CompilerException $e) {
fwrite(STDERR, $e->getMessage() . PHP_EOL);
return false;
}
}
function install(bool $development = false): bool
{
global $compiler, $config;
try {
$compiler->install($development);
} catch (NotImplementedException|CompilerException|Exception $e) {
fwrite(STDERR, $e->getMessage() . PHP_EOL);
return false;
}
$success = ['Extension installed.'];
$namespace = $config->get('namespace');
if (!extension_loaded($namespace)) {
$success[] = sprintf('Add "extension=%s.so" to your php.ini', $namespace);
}
fwrite(STDOUT, implode(PHP_EOL, $success) . PHP_EOL);
fwrite(STDOUT, "Don't forget to restart your web server" . PHP_EOL);
return true;
}
function init(string $namespace): void
{
global $backend, $config, $logger;
$namespace = sanitizeNamespace($namespace);
// Tell the user the name could be reserved by another extension
if (extension_loaded($namespace)) {
$logger->warning('This extension can have conflicts with an existing loaded extension');
}
$config->set('namespace', $namespace);
$config->set('name', $namespace);
if (!is_dir("{$namespace}/{$namespace}")) {
mkdir("{$namespace}/{$namespace}", 0755, true);
}
chdir($namespace);
// Create 'kernel'
if (!is_dir('ext/kernel')) {
mkdir('ext/kernel', 0755, true);
}
// Copy the latest kernel files
recursiveProcess($backend->getInternalKernelPath(), 'ext/kernel');
// Dump initial configuration on project creation
$config->dumpToFile();
}
function sanitizeNamespace(string $namespace): string
{
// Prevent "" namespace
if (empty($namespace)) {
throw new RuntimeException('Not enough arguments (missing: "namespace").');
}
$namespace = strtolower(preg_replace('/[^0-9a-zA-Z]/', '', $namespace));
// If sanitizing returns an empty string
if (empty($namespace)) {
throw new RuntimeException('Cannot obtain a valid initial namespace for the project.');
}
return $namespace;
}
/**
* Copies the base kernel to the extension destination.
*/
function recursiveProcess(string $src, string $dst, ?string $pattern = null, string $callback = 'copy'): void
{
global $logger;
$success = true;
$iterator = new DirectoryIterator($src);
foreach ($iterator as $item) {
$pathName = $item->getPathname();
if (!is_readable($pathName)) {
$logger->error('File is not readable :' . $pathName);
continue;
}
$fileName = $item->getFileName();
if ($item->isDir()) {
if ('.' != $fileName && '..' != $fileName && '.libs' != $fileName) {
if (!is_dir($dst . DIRECTORY_SEPARATOR . $fileName)) {
mkdir($dst . DIRECTORY_SEPARATOR . $fileName, 0755, true);
}
recursiveProcess($pathName, $dst . DIRECTORY_SEPARATOR . $fileName, $pattern, $callback);
}
} elseif ($pattern === null || 1 === preg_match($pattern, $fileName)) {
$path = $dst . DIRECTORY_SEPARATOR . $fileName;
$success = $success && $callback($pathName, $path);
}
}
}