PHP utility collection with hybrid and fluent APIs.

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


Check-in [3a12ba3743]

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

Overview
Comment:Externalize some common macros into `defaults.ph`. (Bundle into separate repository..) Add #pragma(interpolate=regex) substitution names ("erb" and "phpp") and optional delimiters via #pragma(interpolate=regex ##( )##). Start tracking parsed line numbers. Safeguard #include against most commented-out PHP include(); statements. Shortcut find_include for absolute paths. Join tokenizer macro searching and replacement for basic+complex macros, inject [T_FUNC_C, $repl, 0] instead of literal into token stream. Add MacroExpression shortcuts for "0" and "1" literals. Fix expr->run operand order for GT/LT/E comparisions.
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:3a12ba37437c1886f413cae93d9aea0df4895046
User & Date: mario 2015-02-17 19:05:31
Context
2015-02-17
23:35
New #pragma options (dirs=/include:/path, omit=*.h, comments=1, macros=1, fail=0). Longer introduction comment. More regexps moved into const RX_* section. check-in: 5216d6be55 user: mario tags: trunk
19:05
Externalize some common macros into `defaults.ph`. (Bundle into separate repository..) Add #pragma(interpolate=regex) substitution names ("erb" and "phpp") and optional delimiters via #pragma(interpolate=regex ##( )##). Start tracking parsed line numbers. Safeguard #include against most commented-out PHP include(); statements. Shortcut find_include for absolute paths. Join tokenizer macro searching and replacement for basic+complex macros, inject [T_FUNC_C, $repl, 0] instead of literal into token stream. Add MacroExpression shortcuts for "0" and "1" literals. Fix expr->run operand order for GT/LT/E comparisions. check-in: 3a12ba3743 user: mario tags: trunk
14:32
Fix p_stderr callback and RX_DIRECTIVES alternative list. Change to weird variable name $ΒΆ instead of $state (maybe rename flags to lvl,act,end later). check-in: acded28fdd 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
..
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
..
55
56
57
58
59
60
61

62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114















115
116
117
118
119
120
121
...
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
...
188
189
190
191
192
193
194

195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
...
237
238
239
240
241
242
243
244
245
246
247
248
249
250

251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269


270
271
272
273
274
275
276
...
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317

318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337



338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
...
355
356
357
358
359
360
361
362
363


364
365
366
















367
368
369
370
371
372
373
374
375
376
377
378
379
380
381


382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408

409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424

425
426

427
428
429

430
431
432
433
434
435
436
437
438
439
...
442
443
444
445
446
447
448
449

450
451




452
453
454
455
456
457
458
...
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
...
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602

603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619




620
621
622
623
624
625
626
...
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
...
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
...
694
695
696
697
698
699
700
701

702
703
704
705
706
707
708
...
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
...
756
757
758
759
760
761
762
763
764
765
<?php
/**
 * api: php
 * title: PHP Macro Preprocessor
 * description: Context-sensitive C-style #define/macro directive processing.
 * license: MITL
 * version: 0.1.3
 * depends: php (>= 5.4.0)
 * type: rewrite
 * category: macro


 * 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 C header #defines and most preprocess.py comment directives.
 *
 * Preprocessing works in two phases:
................................................................................

#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.
     *
     */
    var $dirs = [
        ".",

        "/usr/include/php5",
    ];

    
    /**
     * Processing behaviour / status flags,
     * can be overridden with #pragma(output=0)
     *
     */
    var $pragma = [
        "encoding" => "UTF-8",
        "file" => 0,
        "line" => 0,
        "output" => 1,
        "input" => NULL,
        "target" => NULL,
        "interpolate" => "token",#"regex", #"token",
    ];


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

       #-- A few C-style constants are predeclared
       "__STDC_VERSION__" => [null, 201112],
       "__PHP_VERSION__" => [null, PHP_VERSION],
       "__FLT_EPSILON__" => [null, 1.1920928955078E-7],
       "__TIMESTAMP__" => [],
       "__BASE_FILE__" => [],

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

       #-- Constant aliases (should go into defaults.ph)
      // "__DIR__" => [null, "dirname(__FILE__)"],   #if __STDC_VERSION__ < 5.3

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

    // Directive splitting
    const RX_DIRECTIVES = "{
      ^ (?: \h? (?:\#|//|/*) \h{1,2} )?                 # preprocess.py prefixes
      \# (include|define|undef|pragma|stderr            # directives
         |ifn?def|if|elif|else|endif|pragma)
        ( \V*  (\\\\ \R \V+)*  (?<!\\\\)\R )            # multi-line expressions
    }mx";

















    /**
     * 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=NULL, $line=NULL, $context=[]) {
        fwrite(STDERR, "[$errno] $msg (processing {$this->pragma['file']}:{$this->pragma['line']}) in $file:$line)\n");
    }
    
    
    /**
     * Main invocation method. Reads and transform source file,
     * returns processed output. Does not write to target itself.
     *
................................................................................
        // 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($block[1]);


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

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

                case "else":
                    $args = 1;
                case "elif":
                    if ($ΒΆ->done) {
                        $ΒΆ->true = 0;
                    }
                    elseif ($ΒΆ->true = MacroExpression::intval($args)) {
                        $ΒΆ->done = 1;
                    }
                    break;
                
                case "endif":
                    $ΒΆ->level = -1;
                    break;
................................................................................
                case "stderr":
                case "pragma":
                    if ($ΒΆ->true) {
                        $out .= $this->{"d_$directive"}($args);
                    }
                    break;
            }
            
            echo "#state ", json_encode(array_reverse(iterator_to_array($ΒΆ))), "\n";

            // add to output?
            if ($ΒΆ->true && $this->pragma["output"]) {
                $out .= $block[2];
            }

        }
        return $out;
    }

    /**
     * Constant/Macro declarations take the form:
     *   β†’ #define CONSTANT 1.2.3
     *   β†’ #define MACRO(X,Y) X > Y
     *   β†’ #define PHPEXP@(args...) { return "[$args]"; }
     */
    function d_define($decl) {
        if (assert(preg_match("/^(\w+@?) (\([\w.,]*\))? (?: [=\s]\s* (.*) )?$/x", $decl, $def))) {
            if ($def[2]) {
                preg_match_all("/\w+/", $def[2], $m); $args = $m[0];
            }
            else {
                $args = NULL;
            }
            $this->defines[$def[1]] = array($args, $def[3]);


        }
    }

    /**
     * Removes declared constants or macros.
     *   β†’ #undef CONSTANT
     */
................................................................................
     * Looks through the defined include ->dirs, optionally tests file extensions (.ph, .php, .inc, .h)
     *   β†’ #include lib/deps.php
     *   β†’ #include "deps.ph"
     *   β†’ #include <errno.h>
     */
    function d_include($fn) {
    
        // Extract filename, search in include dirs
        if (preg_match("/[\"\'\<]? ((?: [^\'\"\<\>\\\\]+ | \\\\. )+) [\>\'\"]?/x", $fn, $m)) {
            $fn = stripcslashes($m[1]);
        }
        else {
            assert("\$fn && \$m /* invalid #include <$fn> syntax */");
            return;
        }

        $fn = $this->find_include($fn);
        
        // Read source, strip T_OPEN/CLOSE tokens
        $src = file_get_contents($fn);
        $src = preg_replace("/^ (\\xEF\\xBB\\xBF)? \s{0,5} \<\?(php)? (\h*\R)? | \?\> \s* $/x", "", $src, 2);
        
        // Run through preprocessor phase
        list($old_file, $this->pragma["file"]) = [$this->pragma["file"], $fn];
        $src = $this->block($src);
        $this->pragma["file"] = $old_file;
        
        // Append output only for PHP scripts
        return fnmatch($fn, "*.h") ? NULL : $src;
    }
        
    /**
     * Search ->dirs for #include $fn with automatic extension probing.
     *
     */
    function find_include($fn, $exts=["", ".ph", ".php", ".inc", ".h", ".p"]) {



        foreach ($this->dirs as $dir) {
            foreach ($exts as $ext) {
                if (file_exists("$dir/$fn$ext")) {
                    return "$dir/$fn$ext";
                }
            }
        }
        trigger_error("#include <$fn> not found");
    }



    /**
     * Apply constants/macros
     * ––––––––––––––––––––––
     *
     * This is run after all #includes have been merged into the input file and
................................................................................
     * all #defines and #pragmas have been collected.
     
     * Either uses a regex extraction mode, or the tokenizer.
     *
     */
    function apply_def($src) {
        
        // Simple regex lookups
        if (preg_match("/^(regex|rx|erb|delim)\b[,\s]*(\S*)[,\s]*(\S*)$/", $this->pragma["interpolate"], $delim)) {


            $src = preg_replace_callback(
                "/$delim[2](?<=\W)(\w+@?)(?:\((.*?)\))(?=\W)$delim[3]/sx",
                [$this, "rx_apply"], $src
















            );
        }

        // Look for T_STRING tokens that match collected #defines and #macros        
        else {
            $src = $this->token_join(
                $this->token_swap(
                    token_get_all($src)
                )
            );
        }        

        return $src;
    }




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

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

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

            // literal constant
            if (isset($defs[$name][1]) && is_null($defs[$name][0])) {
                $token[$i] = $defs[$name][1];
            }

            // Complex macros (PHP callback)

            elseif ($next === "@" and isset($defs["$name@"][1])) {
                list($keys, $code) = $defs["$name@"];
                list($t_args, $s_args, $len) = $this->token_args($token, ++$i);
                array_splice(
                    $token, $i, $len,
                    $this->macro("$name@", $s_args, $callback, $t_args)
                );
                $max = count($token) - 1;
            }

            // Basic macros
            elseif (!empty($defs[$name][0])) {
                list($keys, $code) = $defs["$name"];
                $from_i = $i;
                list($t_args, $s_args, $len) = $this->token_args($token, $i);
                array_splice(

                    $token, $i, $len,
                    $this->macro($name, $keys, $s_args, $code, $t_args)

                );
                $max = count($token) - 1;
            }


        }

        return $token;
    }


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


    /**
     * Find stuff between ( ) and split into arguments on commas.




     *
     */
    function token_args($token, $i) {
        $params = [];
        $arg = [];
        $len = 1;
        $level = NULL;
................................................................................
               $arg[] = $t;
            }
#           print "search(,) #$i $t[0]\n";
        }
        if ($arg) {   // remaining tokens
            $params[] = $arg;
        }
        return [$params, array_map([$this, "token_join"], $params), $len];

    }

    
    /**
     * Substitute constants in-place.
     *
     */
    function rx_apply($m) {
        if (!isset($this->defines[$m[1]])) {
            return $m[0];
        }
        $def = $this->defines[$m[1]];
        if ($def[0]) {
            $args = array_combine(preg_split("/\s*,\s*/", $def[0]), preg_split("/\s*,\s*/", $def[0]));
            return $this->macro($m[1], $args, $def[1]);
        }
        return $def[1];
    }


    /**
     * Expand macros.
     *
     */
    function macro($name, $keys, $args, $body, $token=[]) {

        // complex
        if (is_int(strpos($name, "@"))) {
        }
        
        // basic
        else {
................................................................................
 * 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)        # functions
       | (?<op>      [+-/*^~&|(),%!<>] | >=|<=|==|!=|=~|\&\&|\|\| )    # operators
       | (?<number>  [+-]?\d+(?:\.\d+)*)       # can be multi-tuple version string
       | (?<literal> [\w_]+@?)                 # defined constants
    }mx";



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

    // Run expression through `intval` etc.
    public static function __callStatic($name, $args) {
        $x = new self;
        return call_user_func($name, $x->expr(reset($args)));
    }


    /**
     * Tokenize expression,  into a list of [type, value] pairs.
     *
     */
    function expr($src) {
#       print "EXPR_SRC := \"$src\"\n";




        
        // 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);
        
................................................................................
     * 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);
................................................................................
            // add to operator queue
            else {
                while (count($ops) and (strpos($prec, $val) < strpos($prec, $end = end($ops))) /*and $end != "("*/) {
                    $var[] = array_pop($ops);  
                }
                $ops[] = $val;
            }
        #echo "VAR_STACK := ", json_encode($var), "\n";
        #echo "OPS_STACK := ", json_encode($ops), "\n";
        }

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


    /**
     * Plop values of list, apply expressions or function callbacks as ordered.
     * (Operand relation overriden here as $pop(NN) parameter.)
................................................................................
        $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);
        };
        
        // use values for encountered operations

        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(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[] = version_compare($pop(2), $pop(1)) > 0;  break;
                case "<":  $sum[] = version_compare($pop(2), $pop(1)) < 0;  break;
                case ">=": $sum[] = version_compare($pop(2), $pop(1)) >= 0;  break;
                case "<=": $sum[] = version_compare($pop(2), $pop(1)) <= 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

                        $sum[] = $this->defines[$e][1];
                    }
                    else {  // numbers and strings

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

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

#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->process("test.ph");
#endif






|



>
>







 







<
|


|







 







>










|
|
|
|
|
|
|









|







|
<
<
<










|
|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|







 







>


|







|













|




|







 







<
|





>











|
|
|
|
|
|
|
|
>
>







 







|
|
|





>







|

|










>
>
>
|








<







 







|

>
>

<
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



|


|








>
>






|







|






|
|



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



>
|
<
<







 








>

<
>
>
>
>







 







|
>



<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<

|


|







 







|
|
|
|
|



>






|
|









>
>
>
>







 







|







 







|
|




|







 







|
>







 







>
|
|
|
|










>



>




|







 







|
|

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
..
37
38
39
40
41
42
43

44
45
46
47
48
49
50
51
52
53
54
..
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
...
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
...
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
...
252
253
254
255
256
257
258

259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
...
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367

368
369
370
371
372
373
374
...
375
376
377
378
379
380
381
382
383
384
385
386


387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448








449


450

451

452
453

454
455
456
457
458
459


460
461
462
463
464
465
466
...
469
470
471
472
473
474
475
476
477
478

479
480
481
482
483
484
485
486
487
488
489
...
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
...
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
...
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
...
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
...
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
...
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
...
781
782
783
784
785
786
787
788
789
790
<?php
/**
 * api: php
 * title: PHP Macro Preprocessor
 * description: Context-sensitive C-style #define/macro directive processing.
 * license: MITL
 * version: 0.1.4
 * 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 C header #defines and most preprocess.py comment directives.
 *
 * Preprocessing works in two phases:
................................................................................

#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.
     *
     */
    var $dirs = [
        ".",
        "/usr/include/",
        "/usr/include/php5",
    ];

    
    /**
     * Processing behaviour / status flags,
     * can be overridden with #pragma(output=0)
     *
     */
    var $pragma = [
        "encoding" => "UTF-8",    # unused
        "file" => 0,              # currently processed file
        "line" => 0,              # track parsed line number
        "output" => 1,            # conjoin current include into output
        "input" => NULL,          # input filename
        "target" => NULL,         # target filename
        "interpolate" => "token", # or "regex" or "regex << >>" for custom delimiters
    ];


    /**
     * 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__" => [],
       "__BASE_FILE__" => [],

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




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

    // Directive splitting
    const RX_DIRECTIVES = "{
      ^ (?: [ ]? (?:\#|//|/*) [ ]{1,2} )?               # preprocess.py prefixes
      \# (include(?=\s)|define|undef|stderr             # allowed directives
         |ifn?def|if|elif|else|endif|pragma)
        ( \V*  (\\\\ \R \V+)*  (?<!\\\\)\R )            # multi-line expressions
    }mx";

    // 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 interpolate=erb for known delimiter prefixes/suffixes
    static $rx_delim_named = [
        "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=NULL, $line=NULL, $context=[]) {
        fwrite(STDERR, "[$errno] $msg (processing {$this->pragma['file']}:{$this->pragma['line']}) in $file:$line\n");
    }
    
    
    /**
     * Main invocation method. Reads and transform source file,
     * returns processed output. Does not write to target itself.
     *
................................................................................
        // 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($block[1]);
            $this->pragma["line"] += substr_count($block[1], "\n");

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

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

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

#           echo "#state ", json_encode(array_reverse(iterator_to_array($ΒΆ))), "\n";

            // add to output?
            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
     *   β†’ #define MACRO(X,Y) X > Y
     *   β†’ #define PHPEXP@(args...) { return "[$args]"; }
     */
    function d_define($decl) {
        if (preg_match("/^(?<name>\w+@?) (?<args>\([\w,]*\.*\))? (?:[=\s]\s* (?<val>.*))?$/x", $decl, $d)) {
            $val = $args = NULL;
            extract($d);
            if (strlen($args)) {
                preg_match_all("/\w+/", $d["args"], $m) and $args = $m[0];
            }
            $this->defines[$name] = array($args, $val);
        }
        else {
            $this->stderr(3, "Invalid #define statement");
        }
    }

    /**
     * Removes declared constants or macros.
     *   β†’ #undef CONSTANT
     */
................................................................................
     * Looks through the defined include ->dirs, optionally tests file extensions (.ph, .php, .inc, .h)
     *   β†’ #include lib/deps.php
     *   β†’ #include "deps.ph"
     *   β†’ #include <errno.h>
     */
    function d_include($fn) {
    
        // Extract filename, but eschew commented-out PHP include(); statements
        if (preg_match("/^(?!\() ([\"\'\<])? ((?: [^\s\'\"\<\>\\\\]+ | \\\\. )+) (?(1)[\>\'\"]|) (?<!;)$/x", $fn, $m)) {
            $fn = stripcslashes($m[2]);
        }
        else {
            assert("\$fn && \$m /* invalid #include <$fn> syntax */");
            return;
        }
        // search in include dirs 
        $fn = $this->find_include($fn);
        
        // Read source, strip T_OPEN/CLOSE tokens
        $src = file_get_contents($fn);
        $src = preg_replace("/^ (\\xEF\\xBB\\xBF)? \s{0,5} \<\?(php)? (\h*\R)? | \?\> \s* $/x", "", $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, "*.h") ? 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)) {
            return $fn;  // bypass searching for absolute paths
        }
        foreach ($this->dirs as $dir) if (file_exists($dir)) {
            foreach ($exts as $ext) {
                if (file_exists("$dir/$fn$ext")) {
                    return "$dir/$fn$ext";
                }
            }
        }
        trigger_error("#include <$fn> not found");
    }



    /**
     * Apply constants/macros
     * ––––––––––––––––––––––
     *
     * This is run after all #includes have been merged into the input file and
................................................................................
     * all #defines and #pragmas have been collected.
     
     * Either uses a regex extraction mode, or the tokenizer.
     *
     */
    function apply_def($src) {
        
        // "Simple" regex lookups
        if (preg_match("/^(regex|rx|erb|delim)\b[,\s]*(\S*)[,\s]*(\S*)$/", $this->pragma["interpolate"], $delim)) {
#            isset(self::$rx_delim_named[$delim[1]]) and $delim = self::$rx_delim_named[$delim[1]];
            $rx = self::RX_MACROS;
            $src = preg_replace_callback(


                "/ \Q$delim[2]\E  $rx \Q$delim[3]\E /x",
                // Substitute constants and macros in-place.
                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
        else {
            $src = $this->token_join(
                $this->token_substitute(
                    token_get_all($src)
                )
            );
        }        

        return $src;
    }




    /**
     * Tokenize and scan for T_STRINGs and optional @s,
     * and assert we're not following some constructs (e.g. const= declarations).
     *
     */
    function token_substitute($token) {
        $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) {
                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;
            }
            $prev = $type;
        }


        return $token;
    }


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


    /**

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

    

















    /**
     * Expand macros. (Used by regex and tokenizer modes.)
     *
     */
    function expand_macro($name, $keys, $args, $body, $token=[]) {

        // complex
        if (is_int(strpos($name, "@"))) {
        }
        
        // basic
        else {
................................................................................
 * 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";


    // 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);
        
................................................................................
     * 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);
................................................................................
            // add to operator queue
            else {
                while (count($ops) and (strpos($prec, $val) < strpos($prec, $end = end($ops))) /*and $end != "("*/) {
                    $var[] = array_pop($ops);  
                }
                $ops[] = $val;
            }
#       echo "VAR_STACK := ", json_encode($var), "\n";
#       echo "OPS_STACK := ", json_encode($ops), "\n";
        }

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


    /**
     * Plop values of list, apply expressions or function callbacks as ordered.
     * (Operand relation overriden here as $pop(NN) parameter.)
................................................................................
        $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(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.");
    }
    
................................................................................

#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