PHP utility collection with hybrid and fluent APIs.

⌈⌋ branch:  hybrid7 libraries


Check-in [40155129df]

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

Overview
Comment: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.
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:40155129df4db3ecb58fb0837ae532d7eff63f53
User & Date: mario 2015-02-20 15:34:52
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
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
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
..
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
..
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
...
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
...
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
...
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
...
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
...
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
...
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
...
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
...
447
448
449
450
451
452
453
454










455
456
457
458
459
460
461



462

463
464
465
466
467
468
469
...
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
...
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
...
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
...
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
...
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
...
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
...
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
...
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
...
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
 *       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 and basic 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)
 *     #endif
 *     #stderr Print some message

 *     #pragma(output=0)


 *
 * 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 with output=0 you can suppress #include file source code. Or use the
 * basic 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
................................................................................
#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.
................................................................................
    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 = [

       #-- Predeclare some C-style constants
       "__STDC_VERSION__" => [null, 201112],
       "__PHP_VERSION__" => [null, PHP_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";
................................................................................
       ((?: [^\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.
     *
     */
    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
     *
     */
    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";
................................................................................
     * 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) {

        // 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));
#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;
    }
................................................................................
     * 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
     *
     */
    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]));
            $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;

                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
     *   → #define MACRO(X,Y) X > Y
     *   → #define PHPEXP@(args...) { return "[$args]"; }
     */
................................................................................
        }
        // 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);
        










        // Run through preprocessor phase
        list($old_file, $old_line, $this->pragma["file"], $this->pragma["line"]) = [$this->pragma["file"], $this->pragma["line"], $fn, 0];
        $src = $this->block($src);
        list($this->pragma["file"], $this->pragma["line"]) = [$old_file, $old_line];
        
        // Append output only for PHP scripts
        return fnmatch($fn, $this->pragma["omit"], GLOB_BRACE) ? NULL : $src;



    }

        
    /**
     * Search ->dirs for #include $fn with automatic extension probing.
     *
     */
    function find_include($fn, $exts=["", ".ph", ".php", ".inc", ".h", ".p"]) {
        if (file_exists($fn)) {
................................................................................
     */
    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.
            $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, $code) = $this->defines[$m[1]];
                    if ($keys) {



                        $args = preg_split("/\s*,\s*/", $m[3]);
                        return $this->expand_macro($m[1], $keys, $args, $code);
                    }
                    else {
                        return $code;

                    }
                },
                $src
            );
        }

        // Tokenizer mode: looks for T_STRINGs that match collected #defines and #macros
................................................................................

    /**
     * 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) {

        $max = count($token) - 1;
        $prev = T_WHITESPACE;
        $defs = & $this->defines;

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

            // Look only for array token, T_STRING literals
            if (!is_array($t = $token[$i]) || $t[0] != T_STRING || $prev === T_CONST) {
                continue;
            }
            list($type, $name, $line) = $t;
            $next = current((array)$token[$i+1]);

            // 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]) and $prev !== T_CONST  // 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, $callback, $tok_args), -1]
                );
                $max = count($token) - 1;
            }

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


    /**
     * Find stuff between paired `(`, `)` parens, split on `,` commas into arguments.
     *
     * Returns a stringified list of parameters, a token list for each parameter,
     * and cummulative token cpunt/length.
     *
     */
    function token_args($token, $i) {
        $params = [];
        $arg = [];
        $len = 1;
        $level = NULL;
................................................................................
    }

    

    /**
     * Expand macros. (Used by regex and tokenizer modes.)
     *





     */
    function expand_macro($name, $keys, $args, $body, $token=[]) {

        // complex
        if (is_int(strpos($name, "@"))) {







        }



        
        // 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;
    }
    
}

................................................................................
/**
 * 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 is likely still 0.
 *
 * Note that each #included file gets its own 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() {
................................................................................
        }
    }
}



/**
 * #if/#elif expression evaluation. Permits basic 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 basic 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>.*?)[\"\'])        # 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";


................................................................................
    }


    /**
     * 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);
................................................................................
            }
#       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. */');
            $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)) {
................................................................................
                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






|





|







 







|











<

>

>
>











|
|







 







|







 







|









>


>
>
>








>





|


|

|













|







 







|
|











|







 







|







 







|








|
<
<







 







|







 







|







 







|
|
<
<

|
>
|
|
|
>
>
|
|
>
>
>




>







 







|
>
>
>
>
>
>
>
>
>
>

<

<

<
<
>
>
>

>







 







|










|

>
>
>

|


<
>







 







>

<





|




|


|




|
|


|


|







 







|







 







>
>
>
>
>

|

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










>
>







 







|

|







 







|




|








|







 







|







 







|







 







|







 







|




<


|
>
|



<



<




|




|










1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
..
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
..
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
...
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
...
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
...
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
...
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254


255
256
257
258
259
260
261
...
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
...
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
...
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
...
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
...
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
...
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
...
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
...
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
...
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
...
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
...
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
...
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
...
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
................................................................................
#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.
................................................................................
    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";
................................................................................
       ((?: [^\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";
................................................................................
     * 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;
    }
................................................................................
     * 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": 
................................................................................
                    }
                    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]"; }
     */
................................................................................
        }
        // 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)) {
................................................................................
     */
    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
................................................................................

    /**
     * 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;
................................................................................
    }


    /**
     * 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;
................................................................................
    }

    

    /**
     * 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() {
................................................................................
        }
    }
}



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


................................................................................
    }


    /**
     * 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);
................................................................................
            }
#       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)) {
................................................................................
                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