PHP utility collection with hybrid and fluent APIs.

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


Check-in [5216d6be55]

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

Overview
Comment:New #pragma options (dirs=/include:/path, omit=*.h, comments=1, macros=1, fail=0). Longer introduction comment. More regexps moved into const RX_* section.
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:5216d6be553e0119f6e35989763e520265478d19
User & Date: mario 2015-02-17 23:35:24
Context
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
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
Changes

Changes to macro.php.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

34
























35
36
37
38
39
40
41
..
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

74
75
76
77
78
79




80

81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105





106
107
108
109
110
111
112
113





















114
115
116
117
118
119
120
121
122
123
124

125
126
127
128
129
130
131
...
148
149
150
151
152
153
154



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
...
187
188
189
190
191
192
193



194
195
196
197



198
199
200


201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
...
251
252
253
254
255
256
257
258
259
260


261
262
263
264
265
266
267
...
275
276
277
278
279
280
281







282
283
284
285
286
287
288
289
290
291
292
293
...
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313






314
315


316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
...
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
...
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
...
451
452
453
454
455
456
457



458

459
460
461
462
463
464
465
<?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:
 *
 *   1.  All #define, #include, #if* statements are expanded in the regex mode,
 *       which joins includes, and omits code blocks section-wise. This step is
 *       syntax-insensitive, but strips open/close tokens from injected files,
 *       searches *.ph/.php/.inc, and avoids output from literal .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).
 *
 * Allows to read out defines from preset scripts, by omitting output using e.g.
 * the #pragma(output=0) directive. The main processing call returns output as
 * usual. PHP #includes are stripped of <?php and ? > tokens for easier joining.

 * And a few constants and macros are predefined already.
























 *
 */

#ifndef OMIT_NAMESPACE
namespace io;
use \stdClass, \ArrayAccess, \SplStack,
    \Exception, \OutOfBoundsException;
................................................................................
 *
 */
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, "{{{", "}}}"],
    ];



    /**
................................................................................


    /**
     * 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.
     *
     * @param  string  filename
     * @return string
     *
     */
    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
        $output = $this->apply_def($output);
        
        restore_error_handler();        
        return $output;
    }



................................................................................
     * Handle #directives
     * ––––––––––––––––––
     *
     * Regex-splits the source code, traverses it block-wise.
     * Handles #define, #if, #ifdef, #ifelse, #endif statements,
     * traverses into #include files, and honors #pragma overrides.
     *



     */
    function block(/*string*/ $src, $out="") {

        // Split source into blocks of ["#directive", "args expr", "content"]



        $src = preg_split(self::RX_DIRECTIVES, $src, -1, PREG_SPLIT_DELIM_CAPTURE);
        $src = array_merge(["pragma", "(start=1)"], $src);
        $src = array_chunk($src, 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");

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

                case "if": 
                case "ifdef": 
                case "ifndef":
                    if ($ΒΆ->true) {
................................................................................
                case "include":
                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;
................................................................................
     */
    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
     */
................................................................................
    }

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

    /**
     * Sets processing options.
     *   β†’ #pragma(output=1)
     *   β†’ #pragma(target=bld/output_fn.php)
     *   β†’ #pragma(interpolate=erb)
     */
    function d_pragma($args) {
        if (assert(preg_match("/^\(\s*(\w+)\s*=\s*(.*)\s*\)$/s", $args, $pm))) {






            $this->pragma[strtolower($pm[1])] = $pm[2];
        }


    }

    /**
     * Include files get conjoined (.php or .ph) or C header files (.h) just parsed for constants/macros.
     * Looks through the defined include ->dirs, optionally tests file extensions (.ph, .php, .inc, .h)
     *   β†’ #include lib/deps.php
     *   β†’ #include "deps.ph"
     *   β†’ #include <errno.h>
     */
    function d_include($fn) {
    
        // Extract filename, but eschew commented-out PHP include(); statements
        if (preg_match("/^(?!\() ([\"\'\<])? ((?: [^\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"]) {
................................................................................
                    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]);
................................................................................
        $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?
................................................................................
                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






|









|

|

|
|
|
|






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







 







<







<



|
<

>


|
<


>
>
>
>
|
>


<


<







|
|










>
>
>
>
>








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









|

>







 







>
>
>








|
|













|







 







>
>
>



|
>
>
>
|
<
<
>
>










|







 







|
|
|
>
>







 







>
>
>
>
>
>
>




|







 







|









|
>
>
>
>
>
>
|
|
>
>












|











|







|







 







>







|


>
>
>
>

|


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







 







|







 







>
>
>
|
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
..
76
77
78
79
80
81
82

83
84
85
86
87
88
89

90
91
92
93

94
95
96
97
98

99
100
101
102
103
104
105
106
107
108

109
110

111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
...
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
...
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258


259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
...
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
...
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
...
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
...
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469



470
471
472
473
474
475
476
477
478
479
480
481
...
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
...
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
<?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*
 * 
 * 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.
 *
 * 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
namespace io;
use \stdClass, \ArrayAccess, \SplStack,
    \Exception, \OutOfBoundsException;
................................................................................
 *
 */
class MacroProcessor {

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

     */
    var $dirs = [
        ".",
        "/usr/include/",
        "/usr/include/php5",
    ];


    /**
     * Processing behaviour / status flags,
     * can be overridden with #pragma(output=0)
     */

    var $pragma = [
        "output" => 1,            # conjoin further file content into output
        "encoding" => "UTF-8",    # unused
        "file" => 0,              # currently processed file
        "line" => 0,              # track parsed line number (somewhat inexact)

        "input" => NULL,          # input filename
        "target" => NULL,         # target filename
        "omit" => "*.h",          # output=0 for specific file extensions
        "comments" => 1,          # retain inline /*comments*/ for constants
        "macros" => 1,            # read macro definitions (disable for e.g. system/*.h includes)
        "fail" => 0,              # abort with Exception instead of just printing to stderr
        "interpolate" => "token", # or "regex" mode, or "erb", "phpp", or "regex << >>" for custom delimiters
        "dirs" => NULL,           # append include -I search paths
    ];


    /**
     * Predefined and collected constants and macros.

     */
    var $defines = [

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

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

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

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



    /**
................................................................................


    /**
     * 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.
     *
     * @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));
        
        // Apply macros and constants in tokenization phase
        $output = $this->apply_def($output, $this->pragma["interpolate"]);
        
        restore_error_handler();        
        return $output;
    }



................................................................................
     * Handle #directives
     * ––––––––––––––––––
     *
     * Regex-splits the source code, traverses it block-wise.
     * Handles #define, #if, #ifdef, #ifelse, #endif statements,
     * traverses into #include files, and honors #pragma overrides.
     *
     * @param  string  source code to apply #directives on
     * @return string  assembled source files
     *
     */
    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($block[1]);
            $this->pragma["line"] += substr_count($block[1], "\n");

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

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

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

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

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

    /**
     * Sets processing options.
     *   β†’ #pragma(output=1)
     *   β†’ #pragma(target=bld/output_fn.php)
     *   β†’ #pragma(interpolate=erb)
     */
    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"
     *   β†’ #include <errno.h>
     */
    function d_include($fn) {
    
        // Extract filename, but eschew commented-out PHP include(); statements
        if (preg_match(self::RX_INCLUDE_FN, $fn, $m)) {
            $fn = stripcslashes($m[2]);
        }
        else {
            assert("\$fn && \$m /* invalid #include <$fn> syntax */");
            return;
        }
        // search in include dirs 
        $fn = $this->find_include($fn);
        
        // Read source, strip T_OPEN/CLOSE tokens
        $src = file_get_contents($fn);
        $src = preg_replace(self::RX_PHP_TOKEN, "", $src, 2);
        
        // 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"]) {
................................................................................
                    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.
     *
     * @param  string  source code
     * @param  string  interpolation mode
     * @result string  constants and macros substituted
     *
     */
    function apply_def($src, $mode="token") {
        
        // "Simple" regex lookups
        if (preg_match("/^(regex|rx|erb|phpp|delim)\b[,\s]*(\S*)[,\s]*(\S*)$/", $mode, $delim)) {

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



            }

            // Substitute constants and macros in-place.
            $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]);
................................................................................
        $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?
................................................................................
                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;
            }
        }
        return $token;
    }


    /**
     * Rebuild src output