PHP utility collection with hybrid and fluent APIs.

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


Check-in [a41bba31c8]

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

Overview
Comment:Introduce #srcout preprocessor directive for conditional source output. Split out MacroInjector functionality from MacroProcessor. Add `keep_empty` and `quiet` pragmas. Allow more spacing in MACRO(arg, list) declarations. Support ## varname concatenation in basic macros. Light reshuffling of operator precedence and operand polling for || and &&. Use proper namespace structuring for merging with `phrep.php` cmdline wrapper.
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:a41bba31c8c735689a82bfc67e8b3c85f30863c6
User & Date: mario 2015-02-19 12:48:37
Context
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
2015-02-19
12:48
Introduce #srcout preprocessor directive for conditional source output. Split out MacroInjector functionality from MacroProcessor. Add `keep_empty` and `quiet` pragmas. Allow more spacing in MACRO(arg, list) declarations. Support ## varname concatenation in basic macros. Light reshuffling of operator precedence and operand polling for || and &&. Use proper namespace structuring for merging with `phrep.php` cmdline wrapper. check-in: a41bba31c8 user: mario tags: trunk
2015-02-18
16:27
Fix RX_DIRECTIVES multi-line string extraction, and strip <kbd>\\ NL</kbd> combo. Colorize stderr() messages, prepare for quiet mode. Split d_pragma() handler into value copying and p_hooks() callbacks. check-in: c32a30469b user: mario tags: trunk
Changes

Changes to macro.php.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

16
17
18
19
20
21
22
..
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
..
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
...
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
...
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
...
210
211
212
213
214
215
216



217
218
219
220
221
222
223
...
226
227
228
229
230
231
232



233

234
235
236
237
238
239
240
241
...
243
244
245
246
247
248
249
250
251
252

253
254
255
256
257
258
259
260
...
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
...
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
...
385
386
387
388
389
390
391
392
393
394
395
396
397








398
399
400
401
402
403
404
...
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
...
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
...
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
...
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
...
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
...
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
...
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
<?php
/**
 * api: php
 * title: PHP Macro Preprocessor
 * description: Context-sensitive C-style #define/macro directive processing.
 * license: MITL
 * version: 0.1.6
 * state: beta
 * depends: php (>= 5.4.0)
 * type: rewrite
 * category: macro
 * config: { type: env list colon, name: PHP_INCLUDE_PATH, description: header search paths }
 * architecture: all
 * pack: phrep.php=.phar/stub.php, macro.php, *.ph, README*
 * 

 * 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
................................................................................
 *
 * 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

  #  #define MAX(a,b) ( (a>b)?(a):(b) )
$test = MAX(1+2, 2+3);

 #stderr Manual warning message


/**


 * 



 *

 *


 *
 */
class MacroProcessor {

    /**
     * Search paths for #include instructions.
     * Filename extensions .ph / .h / .php / .inc are probed for.
................................................................................
    ];

    /**
     * Processing behaviour / status flags,
     * can be overridden with #pragma(output=0)
     */
    var $pragma = [
        "output" => 1,            # conjoin 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",          # output=0 for specific file extensions
        "comments" => 1,          # retain inline /*comments*/ for constants
        "macros" => 1,            # read macro definitions (disable for e.g. system/*.h includes)
        "complex" => 1,           #
        "multipass" => 0,         #

        "fail" => 0,              # abort with Exception instead of just printing to stderr
        "interpolate" => "token", # or "regex" mode, or "erb", "phpp", or "regex << >>" for custom delimiters


        "dirs" => NULL,           # append include -I search paths
    ];

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

................................................................................
     * 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             # allowed directives
         |ifn?def|if|elif|else|endif|pragma)
         ( (?>\V*(?:\R|\Z))                              # multi-line expressions
         (?>(?<=\\\\\\n|\\\\\\r\\n|\\\\\\r)\V*\R)* ) 
    }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,]*\.*\))?
        (?:[=\s]\s* (?<val>.*))?
    $/six";

    // Constrain #include filename syntax
    const RX_INCLUDE_FN = "/^
       ^(?!\() ([\"\'\<])?                # valid enclosures < or \", not (
       ((?: [^\s\'\"\<\>\\\\]+ | \\\\.)+) # no quotes, str backslash escapes
................................................................................
    // 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";

    // 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, "{{{", "}}}"],
    ];



    /**
     * Initialize further pragmas, runtime #defines, and #include search paths.
     *
     * @param  array   Include search paths.
     * @param  array   Inject custom defines.
................................................................................
    /**
     * Output PHP warnings during preprocessing
     *
     */
    function stderr(/*int*/$errno, /*string*/$msg, $file="macro.php", $line=0, $context=[]) {
        if ($this->pragma["fail"]) {
            throw new Exception($msg, $errno);



        }
        $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)";
................................................................................
            $msg .= " \e[36min $file:$line\e[0m";
        }
        fwrite(STDERR, "$msg\n");
    }
    
    
    /**



     * Main invocation method. Reads and transform source file,

     * returns processed output. Does not write to target itself.
     *
     * @param  string  main input filename
     * @return string  conjoined and substituted source
     *
     */
    function on(/*string*/$fn) {

................................................................................
        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));
#ifdef __DEBUG
#        $this->stderr(50, json_encode($this->defines, JSON_PRETTY_PRINT));
#endif        
        // Apply macros and constants in tokenization phase

        $output = $this->apply_def($output, $this->pragma["interpolate"]);
        
        restore_error_handler();        
        return $output;
    }



................................................................................
        // 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
        );
#print_r($src);

        // 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]));
            $this->pragma["line"] += substr_count($block[1], "\n");

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

                case "if": 
                case "ifdef": 
................................................................................
                    break;

                case "macro": $directive = "define";
                case "define":
                case "undef":
                case "include":
                case "stderr":

                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";

            // add to output?
            if (isset($block[2])) {



                if ($ΒΆ->true && $this->pragma["output"]) {
                    $out .= $block[2];
                }
                $this->pragma["line"] += substr_count($block[2], "\n");


            }

        }
        return $out;
    }

    /**
     * Constant/Macro declarations take the form:
     *   β†’ #define CONSTANT 1.2.3
................................................................................
     *   β†’ #undef CONSTANT
     */
    function d_undef($name) {
        unset($this->defines[$name]);
    }

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









    /**
     * Sets processing options.
     *   β†’ #pragma(output=1)
     *   β†’ #pragma(target=bld/output_fn.php)
     *   β†’ #pragma(interpolate=erb)
     */
................................................................................
                    return "$dir/$fn$ext";
                }
            }
        }
        trigger_error("#include <$fn> not found");
    }

#}
#class MacroInjection {




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



































     *
     * Either uses a regex extraction mode, or the tokenizer.
     *
     * @param  string  source code
     * @param  string  interpolation mode
     * @result string  constants and macros substituted
     *
     */
    function apply_def($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 (isset(self::$rx_delim_named[$delim[1]])) {
                $delim = self::$rx_delim_named[$delim[1]];
            }

            // Substitute constants and macros in-place.
................................................................................
                    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).
     *
     */
................................................................................
        
        // basic
        else {
            foreach ($keys as $i=>$k) {
#               print "MACROKEY $i -> $k\n";
                if (is_int(strpos($k, ".."))) {
                    $k = trim($k, ".");
                    $body = preg_replace("/\b\Q$k\E\b/", var_export(array_slice($args, $i), TRUE), $body);
                }
                else {
                    $body = preg_replace("/\b\Q$k\E\b/", $args[$i], $body);
                }
            }
        }
        return $body;
    }
    
}
................................................................................
 */
class MacroExpression {

    # Expression tokens
    const RX_EXPR = "{
         (?: [\"\'](?<string>.*?)[\"\'])        # basic 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

    function __construct($p=NULL) {
        $p and $this->defines = & $p->defines;
    }

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


    /**
     * Tokenize expression,  into a list of [type, value] pairs.
     *
     */
    function expr($src) {
#       print "EXPR_SRC := \"$src\"\n";
        // Shortcuts
        if ($src === "1" or $src === "0") {
            return intval($src);
        }
        
        // Regex returns a list of optional [0]=>, [type]=>, [1]=>
        preg_match_all(self::RX_EXPR, $src, $tokens, PREG_SET_ORDER);
        $tokens = array_map(function($t) {
            return array_slice($t, -2, 1); // turn 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);
................................................................................
            }
#       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), "\n";
        return $var;
    }


    /**
     * Plop values of list, apply expressions or function callbacks as ordered.
     * (Operand relation overriden here as $pop(NN) parameter.)
................................................................................
        // prepare value stack
        $sum = [];
        $pop = function($prev=1) use (&$sum) { 
            assert('count($sum) >= $prev /* Empty value stack, unbalanced expressions. */');
            $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 "!":  $sum[] = !$pop();  break;
                case "~":  $sum[] = ~$pop();  break;
                case "+":  $sum[] = $pop(1) + $pop(1);  break;
                case "-":  $sum[] = $pop(2) - $pop(1);  break;
                case "*":  $sum[] = $pop(1) * $pop(1);  break;
                case "/":  $sum[] = $pop(2) / $pop(1);  break;
                case "^":  $sum[] = $pop(1) ^ $pop(1);  break;
                case "&":  $sum[] = $pop(1) & $pop(1);  break;
                case "|":  $sum[] = $pop(1) | $pop(1);  break;
                case "%":  $sum[] = $pop(1) % $pop(1);  break;
                case "&&": $sum[] = $pop(1) && $pop(1);  break;
                case "||": $sum[] = $pop(1) || $pop(1);  break;
                case "==": $sum[] = $pop(1) == $pop(1);  break;
                case "!=": $sum[] = $pop(1) != $pop(1);  break;
               #case "?:": /* needs splitting in ? and : op, unless it should become TCL-style */ $sum[] = $pop() ? $pop() : $pop();  break;
                case ">":  $sum[] = version_compare($pop(), $pop()) < 0;  break;
                case "<":  $sum[] = version_compare($pop(), $pop()) > 0;  break;
                case ">=": $sum[] = version_compare($pop(), $pop()) <= 0;  break;
                case "<=": $sum[] = version_compare($pop(), $pop()) >= 0;  break;
                case "=~": $sum[] = preg_match($pop(2), $pop(1));  break;
                case ",":  $sum[] = array_merge((array)$pop(), (array)$pop()); break;
                default:
                    if ($e == "defined") {


                        $sum[] = isset($this->defines[$pop()]);
                    }
                    elseif (is_callable($e)) {
                        $sum[] = call_user_func_array($e, (array)$pop());
                    }
                    elseif (isset($this->defines[$e])) {  // define literals

#                       print "DEFINED $e\n";
                        $sum[] = $this->defines[$e][1];
                    }
                    else {  // numbers and strings
#                       print "LITERAL $e\n";
                        $sum[] = $e;
                    }
            }

#        echo "OPVAL := ", json_encode($e), "\n";
#        echo "SUM_STACK := ", json_encode($sum), "\n";
        }

        return count($sum) == 1
             ? current($sum)
             : trigger_error("Expression leftovers, result discarded.");
    }
    
    // Inherit from MacroProcessor::$defines
    public $defines = [];#    "X"=>[0,0.001]];

}


#include <license.ph>


#ifdef __TEST__
#$r = MacroExpression::strval(" 2 + 3 * (7 - 2) * ( '5' * 2 - 1 ) + X");
#$r = MacroExpression::strval("7 - 5");
#echo "==", $r, "\n";
$p = new MacroProcessor();
#$p->defines["OMIT_NAMESPACE"] = 1;
#print $p->on(__FILE__);
print $p->on("defaults.ph");

#endif






|





|
<
|
>







 







|
>




<
<

<
<
<

>
>

>
>
>

>

>
>







 







|

|
|
|
|
|
|
|
|
|
>
|
<
>
>
|







 







|
|
|
|










|







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>
>
>







 







>
>
>
|
>
|







 







|


>
|







 







<








|







 







>








<

>
|
|
>
>
>
|
|
|
<
>
>

>







 







|





>
>
>
>
>
>
>
>







 







<
<
|
>
>
>
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








|


|







 







<
<







 







|


|







 







|






>
|
|




|









<





|


|







 







|







 







|







 







|





|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


>
>
|


|

|
>

|

|

|


>
|
<







<
<
<





<
<
<
<
<
<
|
<
<
>

1
2
3
4
5
6
7
8
9
10
11
12
13

14
15
16
17
18
19
20
21
22
..
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
..
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
...
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
...
173
174
175
176
177
178
179















180
181
182
183
184
185
186
...
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
...
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
...
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
...
274
275
276
277
278
279
280

281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
...
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
...
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
...
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
...
569
570
571
572
573
574
575


576
577
578
579
580
581
582
...
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
...
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
...
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
...
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
...
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
<?php
/**
 * api: php
 * title: PHP Macro Preprocessor
 * description: Context-sensitive C-style #define/macro directive processing.
 * license: MITL
 * version: 0.1.7
 * 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
................................................................................
 *
 * 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 basic
 *    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.
................................................................................
    ];

    /**
     * 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",          # 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.
    ];

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

................................................................................
     * 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
................................................................................
    // 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.
................................................................................
    /**
     * Output PHP warnings during preprocessing
     *
     */
    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)";
................................................................................
            $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
     *
     */
    function on(/*string*/$fn) {

................................................................................
        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));
#ifdef __DEBUG
#write       $this->stderr(50, json_encode($this->defines, JSON_PRETTY_PRINT));
#endif        
        // Apply macros and constants in tokenization phase
        $inj = new MacroInjector($this->defines);
        $output = $inj->substitute($output, $this->pragma["interpolate"]);
        
        restore_error_handler();        
        return $output;
    }



................................................................................
        // 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]));
            $this->pragma["line"] += $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": 
................................................................................
                    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
            if ($this->pragma["keep_empty"]) {
                $out .= str_repeat("\n", $pragma_lines);
            }
            $output_lines = substr_count($block[2], "\n");
            if ($ΒΆ->true && $this->pragma["output"]) {
                $out .= $block[2];
            }

            elseif (!$ΒΆ->true and $this->pragma["keep_empty"]) {
                $out .= str_repeat("\n", $output_lines);
            }
            $this->pragma["line"] += $output_lines;
        }
        return $out;
    }

    /**
     * Constant/Macro declarations take the form:
     *   β†’ #define CONSTANT 1.2.3
................................................................................
     *   β†’ #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)
     */
................................................................................
                    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 (isset(self::$rx_delim_named[$delim[1]])) {
                $delim = self::$rx_delim_named[$delim[1]];
            }

            // Substitute constants and macros in-place.
................................................................................
                    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).
     *
     */
................................................................................
        
        // basic
        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);
                }
            }
        }
        return $body;
    }
    
}
................................................................................
 */
class MacroExpression {

    # Expression tokens
    const RX_EXPR = "{
         (?: [\"\'](?<string>.*?)[\"\'])        # basic 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.
     *
     */
    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);
................................................................................
            }
#       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.)
................................................................................
        // prepare value stack
        $sum = [];
        $pop = function($prev=1) use (&$sum) { 
            assert('count($sum) >= $prev /* Empty value stack, unbalanced expressions. */');
            $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("/{$pop()}/sim", $pop());   break;
                case ",":  $r = array_merge((array)$pop(), (array)$pop()); break;
                default:
                    if ($e == "defined") {
                        $x = $pop();
#                       print "DEFINED TEST: $x, ";
                        $r = !is_null($x) || isset($this->defines[$x]);
                    }
                    elseif (is_callable($e)) {
                        $r = call_user_func_array($e, (array)$pop());
                    }
                    elseif (isset($this->defines[$e])  // define literals
                       and (empty($opvals) or $opvals[0] !== "defined")) { // but skip CONST,defined
#                       print "DEFINED $e\n";
                        $r = $this->defines[$e][1];
                    }
                    else {  // numbers and strings or constants
#                       print "LITERAL $e\n";
                        $r = $e;
                    }
            }
            $sum[] = $r;
           echo "OPVAL := ", json_encode($e), " - SUM := ", json_encode($sum), " - R := $r ", "\n";

        }

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



}


#include <license.ph>







#ifndef OMIT_NAMESPACE


} # namespace \io
#endif