PHP utility collection with hybrid and fluent APIs.

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


Check-in [c32a30469b]

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

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

Changes to macro.php.

1
2
3
4
5
6
7

8
9
10
11
12
13
14
..
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
..
64
65
66
67
68
69
70
71
72
73
74
75


76
77
78
79
80
81
82
..
97
98
99
100
101
102
103


104
105
106
107
108
109
110
...
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
...
198
199
200
201
202
203
204
205
206
207
208





209





210
211
212
213
214
215
216
...
223
224
225
226
227
228
229
230


231
232
233
234
235
236
237
...
254
255
256
257
258
259
260

261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
...
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
...
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
...
439
440
441
442
443
444
445
446

447
448
449
450
451
452
453
...
636
637
638
639
640
641
642
643
644


645
646
647
648
649
650
651
652
653
654
655
<?php
/**
 * api: php
 * title: PHP Macro Preprocessor
 * description: Context-sensitive C-style #define/macro directive processing.
 * license: MITL
 * version: 0.1.5

 * 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*
 * 
................................................................................
 * 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.
 *
 * 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.
................................................................................
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.
................................................................................
        "file" => 0,              # currently processed file
        "line" => 0,              # track parsed line number (somewhat inexact)
        "input" => NULL,          # input filename
        "target" => NULL,         # target filename
        "omit" => "*.h",          # output=0 for specific file extensions
        "comments" => 1,          # retain inline /*comments*/ for constants
        "macros" => 1,            # read macro definitions (disable for e.g. system/*.h includes)


        "fail" => 0,              # abort with Exception instead of just printing to stderr
        "interpolate" => "token", # or "regex" mode, or "erb", "phpp", or "regex << >>" for custom delimiters
        "dirs" => NULL,           # append include -I search paths
    ];

    /**
     * Predefined and collected constants and macros.
................................................................................
       "__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.
       "NULLSAFE@" => [["expr"], '{ return $expr; }'],
       "COALESCE@" => [["args..."], '{ return "reset(array_filter([$args]))"; }'],
       "IFSET@" => [["expr"], '{ return "(isset($expr) ? $expr : NULL)"; }'],
    ];
    

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

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

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






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


    /**
     * Output PHP warnings during preprocessing
     *
     */
    function stderr(/*int*/$errno, /*string*/$msg, $file=NULL, $line=NULL, $context=[]) {
        if ($this->pragma["fail"]) {
            throw new Exception($msg, $errno);
        }





        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.
     *
................................................................................
        // 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
        $output = $this->apply_def($output, $this->pragma["interpolate"]);
        
        restore_error_handler();        
        return $output;
    }

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


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

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

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

                default:  // Do nothing (custom directives go in RX_DIRECTIVES)
            }

#           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];
                // Collecting macros can be disabled per #pragma
                if (!$this->pragma["macros"]) {
                    return;
                }
            }
            elseif (!$this->pragma["comments"]) {
                $val = preg_replace("~/\*.+?\*/|//\V+\R?~", "", $val);
            }
            $this->defines[$name] = array($args, $val);
        }
        else {
            $this->stderr(3, "Unrecognized #define statement syntax.");
        }
    }

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

    /**
     * Include files get conjoined (.php or .ph) or C header files (.h) just parsed for constants/macros.
     * Looks through the defined include ->dirs, optionally tests file extensions (.ph, .php, .inc, .h)
     *   β†’ #include lib/deps.php
     *   β†’ #include "deps.ph"
................................................................................
                    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.
................................................................................



/**
 * 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   Current output and conditional sections are still activatable - gets *inherited* from parent state
 *   ->done   Whole condition block passed its one active section, no further #elif/#else leaves will be honored


 *
 * Note that each #included file gets its own condition stack. Instances only
 * track conditional nesting within one file. Once true==false, #includes will
 * not be processed anyway.
 *
 */
class ConditionState extends SplStack {

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






|
>







 







|







 







|




>
>







 







>
>







 







|
<
<











|


|
>








>
>
>
>
>







 







|



>
>
>
>
>
|
>
>
>
>
>







 







|
>
>







 







>







|







 







>
|
|
|
|
>











|


|












|







 







|
|
|
|
|
|
|
|
|
|







 







|
>







 







|
|
>
>

|
|
|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
..
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
..
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
...
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
...
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
...
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
...
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
...
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
...
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
...
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
...
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
...
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
<?php
/**
 * api: php
 * title: PHP Macro Preprocessor
 * description: Context-sensitive C-style #define/macro directive processing.
 * license: MITL
 * version: 0.1.6
 * state: beta
 * depends: php (>= 5.4.0)
 * type: rewrite
 * category: macro
 * config: { type: env list colon, name: PHP_INCLUDE_PATH, description: header search paths }
 * architecture: all
 * pack: phrep.php=.phar/stub.php, macro.php, *.ph, README*
 * 
................................................................................
 * 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.
................................................................................
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.
................................................................................
        "file" => 0,              # currently processed file
        "line" => 0,              # track parsed line number (somewhat inexact)
        "input" => NULL,          # input filename
        "target" => NULL,         # target filename
        "omit" => "*.h",          # output=0 for specific file extensions
        "comments" => 1,          # retain inline /*comments*/ for constants
        "macros" => 1,            # read macro definitions (disable for e.g. system/*.h includes)
        "complex" => 1,           #
        "multipass" => 0,         #
        "fail" => 0,              # abort with Exception instead of just printing to stderr
        "interpolate" => "token", # or "regex" mode, or "erb", "phpp", or "regex << >>" for custom delimiters
        "dirs" => NULL,           # append include -I search paths
    ];

    /**
     * Predefined and collected constants and macros.
................................................................................
       "__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             # allowed directives
         |ifn?def|if|elif|else|endif|pragma)
         ( (?>\V*(?:\R|\Z))                              # multi-line expressions
         (?>(?<=\\\\\\n|\\\\\\r\\n|\\\\\\r)\V*\R)* ) 
    }mx";

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

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

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


    /**
     * Output PHP warnings during preprocessing
     *
     */
    function stderr(/*int*/$errno, /*string*/$msg, $file="macro.php", $line=0, $context=[]) {
        if ($this->pragma["fail"]) {
            throw new Exception($msg, $errno);
        }
        $msg = "\e[1;41m$msg\e[0m";
        if ($errno) {
            $msg = "\e[33;1m[$errno]\e[0m $msg";
        }
        if (1||$this->pragma["file"]) {
            $msg .= " (\e[2mprocessing \e[0;33m{$this->pragma['file']}:{$this->pragma['line']}\e[0m)";
        }
        if ($file && $line) {
            $msg .= " \e[36min $file:$line\e[0m";
        }
        fwrite(STDERR, "$msg\n");
    }
    
    
    /**
     * Main invocation method. Reads and transform source file,
     * returns processed output. Does not write to target itself.
     *
................................................................................
        // 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
#        $this->stderr(50, json_encode($this->defines, JSON_PRETTY_PRINT));
#endif        
        // Apply macros and constants in tokenization phase
        $output = $this->apply_def($output, $this->pragma["interpolate"]);
        
        restore_error_handler();        
        return $output;
    }

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

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

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

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

                default:  // Do nothing (custom directives go in RX_DIRECTIVES)
            }

#           echo "#state ", json_encode(array_reverse(iterator_to_array($ΒΆ))), "\n";
            // add to output?
            if (isset($block[2])) {
                if ($ΒΆ->true && $this->pragma["output"]) {
                    $out .= $block[2];
                }
                $this->pragma["line"] += substr_count($block[2], "\n");
            }
        }
        return $out;
    }

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

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

    /**
     * Include files get conjoined (.php or .ph) or C header files (.h) just parsed for constants/macros.
     * Looks through the defined include ->dirs, optionally tests file extensions (.ph, .php, .inc, .h)
     *   β†’ #include lib/deps.php
     *   β†’ #include "deps.ph"
................................................................................
                    return "$dir/$fn$ext";
                }
            }
        }
        trigger_error("#include <$fn> not found");
    }

#}
#class MacroInjection {

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



/**
 * 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() {
        $this->push(["level" => 0, "true" => "1", "done" => 0]);
    }