PHP utility collection with hybrid and fluent APIs.

βŒˆβŒ‹ βŽ‡ branch:  hybrid7 libraries


Check-in [57fe1833b2]

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Moved out to <a href=http://fossil.include-once.org/phrep/>separate repo</a>.
Timelines: family | ancestors | trunk
Files: files | file ages | folders
SHA1: 57fe1833b259e5eab45e819be06a5a558f6614fb
User & Date: mario 2015-02-23 14:21:51
Context
2015-02-23
14:21
Moved out to <a href=http://fossil.include-once.org/phrep/>separate repo</a>. Leaf check-in: 57fe1833b2 user: mario tags: trunk
2015-02-20
15:34
Introduce `preserve` pragma/state to retain file/line/output between includes. Add complex macro construction code. Safeguard basic macros against absent args. Recheck valid function names in MacroExpressions. check-in: 40155129df user: mario tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Deleted macro.php.

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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
<?php
/**
 * api: php
 * title: PHP Macro Preprocessor
 * description: Context-sensitive C-style #define/macro directive processing.
 * license: MITL
 * version: 0.1.8
 * state: beta
 * depends: php (>= 5.4.0)
 * type: rewrite
 * category: macro
 * config: { type: env list colon, name: PHP_INCLUDE_PATH, description: header search paths }
 * pack: macro.php=io/MacroProcessor.php
 *
 *
 * Preprocessor to apply C-style #define, #ifdef, #include statements. Intended
 * as build helper and complex macro injector. It's language-specific to PHP,
 * but can consume most common C header #defines.
 *
 * Source code/file transformation works in two phases:
 *
 *   1.  All #define, #include, #if* directives are expanded in a regex splitting
 *       state machine. Which joins includes, or omits conditional sections. This
 *       step is syntax-insensitive, but strips open/close tokens from injected
 *       files, and searches *.ph/.php/.inc/.h includes.
 *
 *   2.  Constants and macros are applied on the accumulated source code using
 *       a tokenized representation. This allows context-sensitive expansion of
 *       defined preprocessor constants, standard macros, and even more complex
 *       transformation callbacks - for constructs such as IFSET@(expr).
 *
 * Directives take the form `#define X Y` and must be noted leftmost in source
 * files. Following preprocessor directives are known:
 *
 *     #define CONST 1.2.3
 *     #ifdef CONST
 *     #include <filename.ph>
 *     #elif CONST < 1.0 || CONST >= 2.0
 *     #undef CONST
 *     #define MACRO(x,y) (x+y*2)
 *     #stderr Print some message
 *     #endif
 *     #pragma(output=0)
 *     #srcout inject_literal($source);
 *     #macro VA@(fn,expr...) {return "$fn([$expr])";}
 *
 * For compatibility with preprocess.py there's also support for doubly-commented
 * directives such as:
 *
 *     # #include <linux/errno.h>
 *     // #define X Y
 *
 * They're even valid with one ␣ space before the init // comment, and up to two
 * spaces ␣␣ before the actual #directive name. Which allows minimal structuring.
 *
 * Various #pragma(options=...) can control processing and substitution. For
 * example, output=0 allows to suppress #included file source code. Or use the
 * crude interpolate=regex mode for constant replacements, disable macros=0 etc.
 *
 * Per default #include scripts are stripped off opening <?php and closing PHP
 * tags. And literal C header .h files have content output disabled per default.
 *
 */

#ifndef OMIT_NAMESPACE
namespace io
{
use \stdClass, \ArrayAccess, \SplStack,
    \Exception, \OutOfBoundsException;
#endif


/**
 * MacroProcessor assembles the input source file with all its #include deps,
 * and handles conditional sections (via MacroExpression).
 * 
 *  Β· Main invocation method is ->on($filename). Which is meant/named as simple
 *    array_map() callback for file lists.
 *    Can also be pre-invoked to parse any includes.h, but discard output.
 *
 *  Β· Basic source assembly could alternatively be run via ->block($source).
 *
 * After the complete source code has been collected, passes over macro and
 * constant expansion to MacroInjector for tokenizer/regex substitutions.
 *
 */
class MacroProcessor {

    /**
     * Search paths for #include instructions.
     * Filename extensions .ph / .h / .php / .inc are probed for.
     */
    var $dirs = [
        ".",
        "/usr/include/",
        "/usr/include/php5",
    ];

    /**
     * Processing behaviour / status flags,
     * can be overridden with #pragma(output=0)
     */
    var $pragma = [
        "output" => 1,            # Join further file content into output.
        "encoding" => "UTF-8",    # unused
        "file" => 0,              # Currently processed file.
        "line" => 0,              # Track parsed line number (somewhat inexact).
        "input" => NULL,          # Input filename
        "target" => NULL,         # Target filename
        "omit" => "*.{h,def}",    # Like output=0, but for specific include file extensions.
        "comments" => 1,          # Retain inline /*comments*/ for constants.
        "macros" => 1,            # Read macro definitions (disable for e.g. system/*.h includes).
        "complex" => 1,           # Allows complex macros (PHP callback code).
        "multipass" => 0,         # Resursively expand basic macros in basic macros.
        "keep_empty" => 0,        # Retain empty lines for #directives.
        "fail" => 0,              # Abort with Exception instead of just printing to stderr.
        "quiet" => 0,             # Suppress stderr warnings.
        "interpolate" => "token", # Or "regex" mode, or "erb", "phpp", or "delim << >>" for custom delimiters.
        "dirs" => NULL,           # Append include -I search paths.
        "preserve" => "output,file,line",  # Pragma states to retain between #includes
    ];

    // Updated via versionnum
    const PHREP_VERSION = "0.1.8-4";

    /**
     * Predefined and collected constants and macros.
     */
    var $defines = [

       #-- Predeclare some C-style constants
       "__STDC_VERSION__" => [null, 201112],
       "__PHP_VERSION__" => [null, PHP_VERSION],
       "__PHREP_VERSION__" => [null, self::PHREP_VERSION],
       "__FLT_EPSILON__" => [null, 1.1920928955078E-7],
       "__TIMESTAMP__" => false,  // ISO datetime string
       "__BASE_FILE__" => false,  // set via constructor

       #-- Basic macros
       "INLINE_MAX" => [["a","b"], "((a)>(b)?(a):(b))"],

       #-- PHP expression transformation macros
       "IFSET@" => [["expr"], '{ return "(isset($expr) ? ($expr) : NULL)"; }'],
    ];


    /**
     * Regexps to match/split, assert or replace code and directive sections.
     *
     */

    // Directive splitting
    const RX_DIRECTIVES = "{
      ^ (?:[ ]? (?:\#|//) (?=[ ]))? [ ]{0,2}            # preprocess.py prefixes
      \# (include(?=\s)|define|undef|stderr|srcout      # allowed directives
         |ifndef|ifdef|if|elif|else|endif|pragma)
         ( (?>\V*(?:\R|\Z))                             # arguments and multi-line
         (?>(?<=\\\\\\n|\\\\\\r\\n|\\\\\\r)\V*\R)* )    # expressions via <\\><NL>
    }mx"; // <?

    // Restrict #pragma syntax
    const RX_PRAGMA = "/^
        ( \( \s* )?           (?<key>\w+)               # either (..) enclosed
        (?(1) \s*=\s* | \s+)  (?<val>.*)                # then key=val
        (?(1) \s*\)   | $)                              # or just #pragma key val
    $/sx";

    const RX_DEFINE = "/^
        (?<name>\w+@?) (?<args>\((?:\w+\.*(?:\h*,\h*\w+\.*)* )?\))?
        (?:[=\s]\s* (?<val>.*))?
    $/six";

    // Constrain #include filename syntax
    const RX_INCLUDE_FN = "/^
       ^(?!\() ([\"\'\<])?                # valid enclosures < or \", not (
       ((?: [^\s\'\"\<\>\\\\]+ | \\\\.)+) # no quotes, str backslash escapes
       (?(1)[\>\'\"]|) (?<!;)             # assert enclosures, no trailing ;
    $/x";

    // Used to strip open/close tags
    const RX_PHP_TOKEN = "/
       ^ (\\xEF\\xBB\\xBF)? \s{0,5}       # strip UTF-8 BOM, max 5 spaces
         \<\?(php)?        (\h*\R)?       # open token, optionally HS+NL
       | \?\>             \s{0,20}$       # close token, optional spaces
    /x";



    /**
     * Initialize further pragmas, runtime #defines, and #include search paths.
     *
     * @param  array   Include search paths.
     * @param  array   Inject custom defines.
     *
     */
    public function __construct($include_dirs=[], $defines=[]) {
    
        $this->dirs = array_merge($this->dirs, $include_dirs);
        
        // Non-static runtime constants
        $this->defines += $defines + [
            "__TIMESTAMP__" => [null, gmstrftime("%Y-%m-%dT%H:%M:%SZ")],
            "__BASE_FILE__" => [null, & $this->pragma["input"]],
        ];
    }


    /**
     * Output PHP warnings during preprocessing
     *
     */
    public function stderr(/*int*/$errno, /*string*/$msg, $file="macro.php", $line=0, $context=[]) {
        if ($this->pragma["fail"]) {
            throw new Exception($msg, $errno);
        }
        elseif ($this->pragma["quiet"]) {
            return;
        }
        $msg = "\e[1;41m$msg\e[0m";
        if ($errno) {
            $msg = "\e[33;1m[$errno]\e[0m $msg";
        }
        if (1||$this->pragma["file"]) {
            $msg .= " (\e[2mprocessing \e[0;33m{$this->pragma['file']}:{$this->pragma['line']}\e[0m)";
        }
        if ($file && $line) {
            $msg .= " \e[36min $file:$line\e[0m";
        }
        fwrite(STDERR, "$msg\n");
    }
    
    
    /**
     * Main invocation method
     * ––––––––––––––––––––––
     *
     * Reads and transform source file.
     * Returns fully assembled and constant/macro-substituted output.
     * Does not write to target file itself.
     *
     * @param  string  main input filename
     * @return string  conjoined and substituted source
     *
     */
    public function on(/*string*/$fn) {

        // Enable STDERR reporting during runtime
        set_error_handler([$this, "stderr"]);

        // Read main file, process #directives between regex-split source blocks
        $this->pragma["input"] = $fn;
        $this->pragma["file"] = $fn;
        $output = $this->block(file_get_contents($fn));

        // Apply macros and constants in tokenization phase
        $inj = new MacroInjector($this->defines);
        $output = $inj->substitute($output, $this->pragma["interpolate"]);
        
        restore_error_handler();        
        return $output;
    }



    /**
     * Handle #directives
     * ––––––––––––––––––
     *
     * Regex-splits the source code, traverses it block-wise.
     * Handles #define, #if, #ifdef, #ifelse, #endif statements,
     * traverses into #include files, and honors #pragma overrides.
     *
     * @param  string  source code to apply #directives on
     * @return string  assembled source files
     *
     */
    public function block(/*string*/ $src, $out="") {

        // Split source into a list of ["#directive", "args/expr", "source file content.."] blocks
        $src = array_chunk(
            array_merge(
                ["pragma", "(start=block)"] /* dummy prefix directive */,
                preg_split(self::RX_DIRECTIVES, $src, -1, PREG_SPLIT_DELIM_CAPTURE)
            ),  3
        );

        // Condition block nesting levels, and active/done state tracking
        $ΒΆ = new ConditionState();
        
        // Run over each #directive + content block
        while ($block = array_shift($src)) {
            $directive = $block[0];
            $args = trim(preg_replace("/\\s*\\\\(\R)/", "$1", $block[1]));
            $pragma_lines = substr_count($block[1], "\n");

            // Dispatch or handle #directives
#           print "#$directive $args / t=$ΒΆ->true d=$ΒΆ->done\n";
            switch ($directive) {

                case "if": 
                case "ifdef": 
                case "ifndef":
                    if ($ΒΆ->true) {
                        if ($directive == "if") {
                            $args = MacroExpression::strval($args, $this);
                        }
                        else {
                            $args = isset($this->defines[$args]) ^ ($directive == "ifndef");
                        }
                        $ΒΆ->level = +1;
                        $ΒΆ->done = $ΒΆ->true = intval($args);
                    }
                    else {
                        $ΒΆ->level = +1;
                    }
                    break;

                case "else":
                    $args = "1";
                case "elif":
                    if ($ΒΆ->done) {
                        $ΒΆ->true = 0;
                    }
                    elseif ($ΒΆ->true = MacroExpression::intval($args, $this)) {
                        $ΒΆ->done = 1;
                    }
                    break;
                
                case "endif":
                    $ΒΆ->level = -1;
                    break;

                case "macro": $directive = "define";
                case "define":
                case "undef":
                case "include":
                case "stderr":
                case "srcout":
                case "pragma":
                    if ($ΒΆ->true) {
                        $out .= $this->{"d_$directive"}($args);
                    }
                    break;

                default:  // Do nothing (custom directives go in RX_DIRECTIVES)
            }
#           echo "#state ", json_encode(array_reverse(iterator_to_array($ΒΆ))), "\n";

            // Append output block / or empty lines
            $pragma_lines = substr_count($block[1], "\n");
            $output_lines = substr_count($block[2], "\n");
            if ($this->pragma["output"]) {
                if ($ΒΆ->true) {
                    $out .= $block[2];
                }
                elseif ($this->pragma["keep_empty"]) {
                    $out .= str_repeat("\n", $pragma_lines);
                    if (!$ΒΆ->true) {
                        $out .= str_repeat("\n", $output_lines);
                    }
                }
            }
            $this->pragma["line"] += $pragma_lines;
            $this->pragma["line"] += $output_lines;
        }
        return $out;
    }


    /**
     * Constant/Macro declarations take the form:
     *   β†’ #define CONSTANT 1.2.3
     *   β†’ #define MACRO(X,Y) X > Y
     *   β†’ #define PHPEXP@(args...) { return "[$args]"; }
     */
    function d_define($decl) {
        if (preg_match(self::RX_DEFINE, $decl, $d)) {
            $val = $args = NULL;
            extract($d);
            if (isset($args)) {
                preg_match_all("/\w+/", $d["args"], $m) and $args = $m[0];
                // Collecting macros can be disabled per #pragma
                if (!$this->pragma["macros"]) {
                    return;
                }
            }
            elseif (!$this->pragma["comments"]) {
                $val = preg_replace("~/\*.+?\*/|//\V+\R?~", "", $val);
            }
            $this->defines[$name] = array($args, $val);
        }
        else {
            $this->stderr(3, "Unrecognized #define statement syntax. '$decl'");
        }
    }

    /**
     * Removes declared constants or macros.
     *   β†’ #undef CONSTANT
     */
    function d_undef($name) {
        unset($this->defines[$name]);
    }

    /**
     * Just prints out a warning/error message
     *
     */
    function d_stderr($name) {
        $this->stderr(5, $name);
    }

    /**
     * Injects commented out `#srcout code();` code - for conditional sections (with state=true).
     *
     */
    function d_srcout($line) {
        return $line . "\n";
    }

    /**
     * Sets processing options.
     *   β†’ #pragma(output=1)
     *   β†’ #pragma(target=bld/output_fn.php)
     *   β†’ #pragma(interpolate=erb)
     */
    function d_pragma($args) {
        if (assert(preg_match(self::RX_PRAGMA, $args, $pm) and extract($pm))) {
            $this->pragma[$key = strtolower($key)] = $val;
            if (method_exists($this, "p_$key")) {
                $this->{"p_$key"}($key, $val);
            }
        }
    }
    // Pragma hook: dirs
    function p_dirs($key, $val) {
        assert('strstr($val, "\\\\") /* Ahem, forward slashes work on Windows too (ever since DOS 2.0). */');
        $this->dirs = array_unique(array_merge($this->dirs, preg_split("/(?<!(:|^)\w):/", $val)));
    }

    /**
     * Include files get conjoined (.php or .ph) or C header files (.h) just parsed for constants/macros.
     * Looks through the defined include ->dirs, optionally tests file extensions (.ph, .php, .inc, .h)
     *   β†’ #include lib/deps.php
     *   β†’ #include "deps.ph"
     *   β†’ #include <errno.h>
     */
    function d_include($fn) {
    
        // Extract filename, but eschew commented-out PHP include(); statements
        if (preg_match(self::RX_INCLUDE_FN, $fn, $m)) {
            $fn = stripcslashes($m[2]);
        }
        else {
            assert("\$fn && \$m /* invalid #include <$fn> syntax */");
            return;
        }
        // search in include dirs 
        $fn = $this->find_include($fn);
        
        // Read source, strip T_OPEN/CLOSE tokens
        $src = file_get_contents($fn);
        $src = preg_replace(self::RX_PHP_TOKEN, "", $src, 2);

        // Change and keep some states between includes
        $preserve = array_intersect_key(
            $this->pragma,       // keep: output,file,line
            array_flip(str_getcsv($this->pragma["preserve"]))
        );
        if (fnmatch($fn, $this->pragma["omit"], GLOB_BRACE)) {
            $this->pragma["output"] = 0;  // omit output for *.h and *.def headers per default
        }
        $this->pragma += array("file" => $fn, "line" => 0);

        // Run through preprocessor phase
        $src = $this->block($src);
        
        // Reset flags, return output if any
        $this->pragma += $preserve;
        return $src;
    }

        
    /**
     * Search ->dirs for #include $fn with automatic extension probing.
     *
     */
    function find_include($fn, $exts=["", ".ph", ".php", ".inc", ".h", ".p"]) {
        if (file_exists($fn)) {
            return $fn;  // bypass searching for absolute paths
        }
        foreach ($this->dirs as $dir) if (file_exists($dir)) {
            foreach ($exts as $ext) {
                if (file_exists("$dir/$fn$ext")) {
                    return "$dir/$fn$ext";
                }
            }
        }
        trigger_error("#include <$fn> not found");
    }

}



/**
 * Apply constants/macros
 * ––––––––––––––––––––––
 *
 * This is run after all #includes have been merged into the input file and
 * all #defines and #pragmas have been collected.
 *
 */
class MacroInjector {

    /**
     * Inherit $defines as collected by MacroProcessor parent.
     *
     * @param  object  parent
     */
    function __construct($defines) {
        $this->defines = $defines;
    }
    
    // Parent attributes
    var $defines;

    // Used in #pragma(interpolate=regex) replacement mode, optional delimiter args
    const RX_MACROS = "
        (?<=\W)                           # extra delimiters must be non-alpha
        (\w+@?)                           # defined name
        (\( ((?:[^()]*+ | (?-2))*) \))?   # parenthesized arguments to macro
        (?=\W)
    ";

    // Use #pragma interpolate=erb for known delimiter prefixes/suffixes
    static $rx_delim_named = [
        "rx" => [null, null, "", ""],
        "erb" => [null, null, "%{", "}"],
        "phpp" => [null, null, "{{{", "}}}"],
    ];


    /**
     * Substitutes preprocessor-#defined CONSTANTS and MACROS(x,y) in the
     * assembled source string.
     *
     * Either uses a regex extraction mode, or the tokenizer.
     *
     * @param  string  source code
     * @param  string  interpolation mode
     * @result string  constants and macros substituted
     *
     */
    public function substitute($src, $mode="token") {
        
        // "Simple" regex lookups
        if (preg_match("/^(regex|rx|erb|phpp|delim)\b[,\s]*([^\s,]*)[,\s]*([^\s,]*)$/", $mode, $delim)) {

            // Custom or predefined delimiters
            if (empty($delim[2]) and empty($delim[3]) and isset(self::$rx_delim_named[$delim[1]])) {
                $delim = self::$rx_delim_named[$delim[1]];
            }

            // Substitute constants and macros in-place.
            $src = preg_replace_callback("/ \Q$delim[2]\E  " . self::RX_MACROS . " \Q$delim[3]\E /x",

                function($m) {
                    if (empty($this->defines[$m[1]])) {
                        return $m[0];
                    }
                    list($keys, $repl) = $this->defines[$m[1]];
                    if ($keys) {
                        if (empty($m[2])) {
                            return $m[0];   // Macro const used without (params)
                        }
                        $args = preg_split("/\s*,\s*/", $m[3]);
                        return $this->expand_macro($m[1], $keys, $args, $repl, [], FALSE);
                    }
                    else {
                        return $repl;   // Just a constant
                    }
                },
                $src
            );
        }

        // Tokenizer mode: looks for T_STRINGs that match collected #defines and #macros
        else {
            $src = $this->token_join(
                $this->token_substitute(
                    token_get_all($src)
                )
            );
        }        

        return $src;
    }


    /**
     * Tokenize and scan for T_STRINGs and optional @s,
     * and assert we're not following some constructs (e.g. const= declarations).
     *
     */
    function token_substitute($token) {
        $prev = $type = $next = T_WHITESPACE;
        $max = count($token) - 1;
        $defs = & $this->defines;

        // Only stop for array token entries
        for ($i=0; $i < $max; $i++) {

            // Look only at array tokens, T_STRING literals, not preceded by "const"
            if (!is_array($t = $token[$i]) || $t[0] != T_STRING || $prev === T_CONST) {
                continue;
            }
            list($type, $name, $line) = $t;
            $next = $token[$i + 1][0]; // careless

            // Pure constant
            if (isset($defs[$name][1]) && is_null($defs[$name][0])) {  //@T also invoke for empty MACRO() params?
                $token[$i] = $defs[$name][1];
            }

            // Macros
            elseif (isset($defs[$name][1])     // Basic macros without trailing "@"
                or ($next === "@") and isset($defs[$name .= $next][1])) // Complex callback macro name
            {
                list($keys, $code) = $defs[$name];     // Assemble (parameter,list,...)
                list($str_args, $tok_args, $tok_len) = $this->token_args($token, $i);
                array_splice(  // Replace grouped tokens with a single text blob
                    $token, $i, $tok_len,
                    [[T_FUNC_C, $this->expand_macro($name, $keys, $str_args, $code, $tok_args, $cplx="?"), -1]]
                );
                $max = count($token) - 1;
            }

            // Remember type for context
            if ($type !== T_WHITESPACE && $type !== T_COMMENT) {
                $prev = $type;
            }
        }
        return $token;
    }


    /**
     * Rebuild src output
     *
     */
    function token_join($token) {        
        return join(array_map(
            function($t) {
                return is_array($t) ? $t[1] : $t;
            },
            $token
        ));
    }


    /**
     * Find stuff between paired `(`, `)` parens, split on `,` commas into arguments.
     *
     * Returns a stringified list of parameters, a token list for each parameter,
     * and cumulative token count/length.
     *
     */
    function token_args($token, $i) {
        $params = [];
        $arg = [];
        $len = 1;
        $level = NULL;
        for ($i+=1; $i < count($token) && $level !== 0; $i++, $len++) {
            if (is_string($t = $token[$i])) {
                if ($t == "(") {
                    $level++;
                    if ($level == 1) continue;
                }
                elseif ($t == ")") {
                    $level--;
                }
                elseif ($t == "," and $level == 1) {
                    $params[] = $arg;
                    $arg = [];
                    continue;
                }
            }
            if ($level >= 1) {
               $arg[] = $t;
            }
#           print "search(,) #$i $t[0]\n";
        }
        if ($arg) {   // remaining tokens
            $params[] = $arg;
        }
        return [array_map([$this, "token_join"], $params), $params, $len];
        //@T move main &$token updating through array_splice here?
    }

    

    /**
     * Expand macros. (Used by regex and tokenizer modes.)
     *
     * @param  string  Constant "NAME" or macro "BASIC" or "COMPLEX@"
     * @param  array   List of macro keys ["a","b","expr"]
     * @param  array   List of param values/expressions as strings ["$a", "$b", "3.0+func()"]
     * @param  string  Macro template "(a+b>c)" or PHP func "{return "$a+$b>c";}"
     * @param  array   List of tokens for each param/expr [ [T_VAR "$a", ">", T_VAR "$b"], [T_VAR "$c", T_INCR "++"], ...]
     */
    function expand_macro($name, $keys, $args, $body, $token=[], $complex_macro) {

        // Complex
        if ($complex_macro = is_int(strpos($name, "@"))) {
            $php_keys = "\$token";
            $php_args = [$token];
            foreach ($keys as $key) {
                if (is_int(strpos($key, ".."))) {
                    $php_keys .= ",\$$key";  // Let's have our own variadic params, with blackjack and stuff
                    $php_args[] = $args;
                    break;
                }
                else {
                    $php_keys .= ",\$$key";
                    $php_args[] = count($args) ? array_shift($args) : NULL;
                }
            }
#           print "MACRO n=$name, c=$complex_macro, $php_keys, $body\n";
            $body = call_user_func_array(create_function($php_keys, $body), $php_args);
        }
        
        // Basic/standard macros
        else {
            foreach ($keys as $i=>$k) {
#               print "MACROKEY $i -> $k\n";
                if (is_int(strpos($k, ".."))) {
                    $k = trim($k, ".");
                    $body = preg_replace("/(\s*##\s*)?\b\Q$k\E\b/", var_export(array_slice($args, $i), TRUE), $body);
                }
                else {
                    $body = preg_replace("/(\s*##\s*)?\b\Q$k\E\b/", $args[$i], $body);
                }
                # add __VA_ARGS__
                # and #str encasing
            }
        }
        return $body;
    }
    
}



/**
 * More readable tracking of #if..#endif nesting levels, with some attributes:

 *   ->level  Nesting / stack length. Each #if/ifdef/endif block will start a new stack.
 *   ->true   Output active and conditional sections still activatable - gets *inherited*.
 *   ->done   Condition block passed its one active section, no further #elif/#else leaves
 *            can be activated. An #endif terminates the stack, resumes to the prior, where
 *            ->true=1 and ->done=0 still.
 *
 * Note that each #included file gets a fresh condition stack in the ->block()
 * processor. Instances only track conditional nesting within one file. Once
 * true==false, #includes will not be processed anyway.
 *
 */
class ConditionState extends SplStack {

    function __construct() {
        $this->push(["level" => 0, "true" => "1", "done" => 0]);
    }

    function __get($name) {
        if ($name == "level") {  // level equals stack length
            return $this->count() - 1;
        }
        else {
            $s = $this->top();   // single state attrib
            return $s[$name];
        }
    }

    function __set($name, $value) {
        if ($name == "level" and $value < 0) {
            assert('$this->level > 0 and $value == -1 /* incorrect #if/#endif nesting */');
            $this->pop();         // can only -1 pop or +1 add a new level
        }
        elseif ($name == "level" and $value >= 0) {
            assert('$value == +1 /* can only iterate one level at a time */');
            $this->push(["level" => $this->level + 1, "true" => $this->true, "done" => 0]);
        }
        else {
            $s = $this->pop();   // modify state attribute in last stack entry
            $s[$name] = $value;
            $this->push($s);
        }
    }
}



/**
 * #if/#elif expression evaluation. Permits common arithmetics, #define lookups,
 * a few hand-picked PHP callbacks, and decimal/float/tuple comparisons.
 * It's neither fully CPP compatible, nor in line with preprocess.py; and it's
 * likely pointless featuritis anyway.
 *
 * Uses a trivial shunting-yard sorting method for its tokenized input, then
 * evaluates expressions down to a numeric or booleanish scalar. Has only minimal
 * error reporting, and operator/func precedence is incomplete/untuned..
 *
 */
class MacroExpression {

    # Expression tokens
    const RX_EXPR = "{
         (?: [\"\'](?<string>.*?)[\"\'])        # plain strings, no escape checking
       | (?<func>    defined|stri?pos|stri?str|is_int|is_float|max|min) # functions
       | (?<op>      >=|<=|==|!=|=~|\&\&|\|\| | [+-/*^~&|(),%!<>] )     # operators
       | (?<number>  [+-]?\d+(?:\.\d+)*)        # can be multi-tuple version string
       | (?<literal> [\w_]+@?)                  # defined constants
    }mx";


    // Inherit from parent for constant lookups
    public $defines = [];
    function __construct($defines=[]) {
        $this->defines = $defines;
    }

    // Run expression through `intval` etc.
    public static function __callStatic($name, $args) {
        $x = new self(count($args) >= 2 ? $args[1]->defines : []);
        return call_user_func($name, $x->expr($args[0]));
    }


    /**
     * Tokenize expression,  into a list of [type, value] pairs.
     *
     */
    public function expr($src) {
        // Shortcuts
        if ($src === "1" or $src === "0") {
            return intval($src);
        }
        
        // Regex returns a list of optional [0]=>, [type]=>, [1]=> matches
        preg_match_all(self::RX_EXPR, $src, $tokens, PREG_SET_ORDER);
        $tokens = array_map(function($t) {
            return array_slice($t, -2, 1); // turn last named entry into [type=>value]* list
        }, $tokens);
        
        // Reorder by precedence into RPN
        $opvals = $this->group($tokens);

        // Apply operations
        return $this->run($opvals);
    }


    /**
     * Run through tokens, spool values+operators into reverse polish notation.
     * [2, 3, 5, *, +]  or for example  [CONST, defined, 1, >=]
     *
     */
    function group($tokens) {

        // operator precedence list
        $prec = " () , || && == >= > <= < == !== !?: ! & | ^ + - * / % ~";
        $var = [];   // operand queue
        $ops = [];   // operator stack

        // .iteritems() over token list
        while ($t = array_shift($tokens)) {
            $type = key($t);
            $val = current($t);

            // literals
            if (strpos("(literal|number|string)", $type)) {
                $var[] = $val; #[$type, $val];
            }
            
            // parenthesis grouping
            elseif (($val == "(") or ($type=="func")) {
                $ops[] = $val;
            }
            elseif ($val == ")") {
                while (count($ops) && (end($ops) != "(")) {
                   $var[] = $val = array_pop($ops);
                }
                array_pop($ops);
            }
            
            // add to operator queue
            else {
                while (count($ops) and (strpos($prec, $val) < strpos($prec, $end = end($ops))) /*and $end != "("*/) {
                    $var[] = array_pop($ops);  
                }
                $ops[] = $val;
            }
#       echo "VAR_STACK := ", json_encode($var), "\n";
#       echo "OPS_STACK := ", json_encode($ops), "\n";
        }

        // append remaining operators
        $var = array_merge($var, array_reverse($ops));
#       echo "(GROUP_FINAL := ", json_encode($var), ") ";
        return $var;
    }


    /**
     * Plop values of list, apply expressions or function callbacks as ordered.
     * (Operand relation overriden here as $pop(NN) parameter.)
     *
     */
    function run(&$opvals) {

        // prepare value stack
        $sum = [];
        $pop = function($prev=1) use (&$sum) { 
            assert('count($sum) >= $prev /* Empty value stack, unbalanced expressions. */'); # OutOfBounds
            $v = array_splice($sum, -$prev, 1, []);
            return current($v);
        };

        // Dispatch value literals as encountered operations
        // (Rather should carry the token types over. Would also simplify ordering operands.)
        while (count($opvals)) {
            $e = array_shift($opvals);
            switch ($e) {
                case "!":  $r = !$pop();  break;
                case "~":  $r = ~intval($pop());  break;
                case "+":  $r = $pop(1) + $pop(1);  break;
                case "-":  $r = -$pop(); $r += $pop();  break;
                case "*":  $r = $pop(1) * $pop(1);  break;
                case "/":  $r = $pop(2) / $pop(1);  break;
                case "^":  $r = intval($pop(1)) ^ intval($pop(1));  break;
                case "&":  $r = $pop(1) & $pop(1);  break;
                case "|":  $r = $pop(1) | $pop(1);  break;
                case "%":  $r = $pop(1) % $pop(1);  break;
                case "&&": $x = $pop(); $y = $pop(); $r = intval($x && $y); break;
                case "||": $x = $pop(); $y = $pop(); $r = intval($x || $y); break;
                case "==": $r = $pop(1) == $pop(1);  break;
                case "!=": $r = $pop(1) != $pop(1);  break;
               #case "?:": /* needs splitting in ? and : op, unless it should become TCL-style */ $r = $pop() ? $pop() : $pop();  break;
                case ">":  $r = version_compare($pop(), $pop()) < 0;   break;
                case "<":  $r = version_compare($pop(), $pop()) > 0;   break;
                case ">=": $r = version_compare($pop(), $pop()) <= 0;  break;
                case "<=": $r = version_compare($pop(), $pop()) >= 0;  break;
                case "=~": $r = preg_match("\1{$pop()}\1sim", $pop());   break;
                case ",":  $r = array_merge((array)$pop(), (array)$pop()); break;
                default:
                    if ($e == "defined") {
                        $x = $pop();
                        $r = !is_null($x) || isset($this->defines[$x]);
                    }
                    elseif (is_callable($e) and preg_match(self::RX_EXPR, $e, $verify) and !empty($verify["func"])) {
                        $x = array_reverse($pop());  // params have been arrayified through , operator
                        $r = call_user_func_array($e, $x);
                    }
                    elseif (isset($this->defines[$e])  // define literals
                       and (empty($opvals) or $opvals[0] !== "defined")) { // but skip CONST,defined
                        $r = $this->defines[$e][1];
                    }
                    else {  // numbers and strings or constants
                        $r = $e;
                    }
            }
            $sum[] = $r;
#           printf(" %26s ➫ %-8s πŸ”›  %16s ← %4s\n", join(" ", $opvals), "{$e}", json_encode($sum), json_encode($r));
        }

        return count($sum) == 1
             ? current($sum)
             : trigger_error("Expression leftovers, result discarded.") && NULL; # OutOfBounds
    }
    
}


#include <license.ph>

#ifndef OMIT_NAMESPACE
} # namespace \io
#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<