tricu

A lazy functional language based on Tree Calculus
Log | Files | Refs | README | LICENSE

run.php (1634B)


      1 #!/usr/bin/env php
      2 <?php
      3 declare(strict_types=1);
      4 require __DIR__.'/src/common.php';
      5 use Arboricx\Library;
      6 use function Arboricx\{readBundle, render};
      7 
      8 if ($argc < 4 || $argv[1] !== 'run') {
      9     fwrite(STDERR, "Usage: tricu-php run BUNDLE EXPORT [--io] [--format string|number|bool|bytes] [--] [text arguments...]\n");
     10     exit(1);
     11 }
     12 $ctx = null;
     13 $status = 0;
     14 try {
     15     $ctx = (new Library())->context();
     16     $term = $ctx->loadBundle(readBundle($argv[2]), $argv[3]);
     17     $io = false; $format = 'string'; $options = true;
     18     for ($i = 4; $i < $argc; $i++) {
     19         if ($options && $argv[$i] === '--') { $options = false; continue; }
     20         if ($options && $argv[$i] === '--io') { $io = true; continue; }
     21         if ($options && $argv[$i] === '--format') { $format = $argv[++$i] ?? ''; continue; }
     22         if ($options && str_starts_with($argv[$i], '--')) throw new RuntimeException('unknown option: '.$argv[$i]);
     23         $arg = $ctx->string($argv[$i]);
     24         $next = $ctx->apply($term, $arg);
     25         $ctx->release($term); $ctx->release($arg); $term = $next;
     26     }
     27     if (!in_array($format, ['string', 'number', 'bool', 'bytes'], true)) throw new RuntimeException('invalid result format');
     28     if ($io) {
     29         $result = $ctx->runIO($term);
     30         if ($result['outcome'] !== 0) throw new RuntimeException('IO task '.($result['outcome'] === 1 ? 'failed' : 'cancelled').' (reason left opaque)');
     31         $term = $result['value'];
     32     }
     33     echo render($ctx, $term, $format)."\n";
     34 } catch (Throwable $error) {
     35     fwrite(STDERR, 'Error: '.$error->getMessage()."\n");
     36     $status = 1;
     37 } finally { $ctx?->close(); }
     38 exit($status);