PHP utility collection with hybrid and fluent APIs.

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


Check-in [bcf53d2741]

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

Overview
Comment:Implement tokenizer and regex constant/macro replacement (incomplete). Fix condition block nesting level tracking. Rename main func to `on()`. Implement #include searching and omitting .h output. Change collected macro definitions to contain pre-parsed param names.
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:bcf53d2741e1bde726721b1890cae26ccaee2f26
User & Date: mario 2015-02-17 07:09:36
Context
2015-02-17
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
07:09
Implement tokenizer and regex constant/macro replacement (incomplete). Fix condition block nesting level tracking. Rename main func to `on()`. Implement #include searching and omitting .h output. Change collected macro definitions to contain pre-parsed param names. check-in: bcf53d2741 user: mario tags: trunk
2015-02-16
20:16
Basic version, #directive preprocessing, and basic expression evaluation. No tokenization and constant / macro interpolation yet. check-in: 9dea381ebc user: mario tags: trunk
Changes

Changes to macro.php.

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
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
...
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
183
184
185
186
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
219
220
221
222
223
224
225

226

227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
...
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
279
280
281
282
283
284
285












286
287




288



289
290
291









292
293
294

295



296























































































































































































297
298
299
300



301




302
303
304
305
306
307
308
...
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
...
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
...
506
507
508
509
510
511
512




513
514
515
516


517
518

/**
 * api: php
 * title: PHP Macro Preprocessor
 * description: Context-sensitive C-style #define/macro directive processing.
 * version: 0.1.0
 * type: rewrite
 * category: macro
 * pack: stub.php, macro.php
 * 
 * Preprocessor to apply C-style #define, #ifdef, #include statements. Intended
 * as build helper and complex macro injector. It's language-specific to PHP,
 * but can consume 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 is step
 *       is syntax-insensitive, but strips open/close tokens from .ph/.php/.inc
 *       files, 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.
 *
 */

#include <license.ph>

#ifndef OMIT_NAMESPACE
namespace io;
use \stdClass, \ArrayAccess, \SplStack,
    \Exception, \OutOfBoundsException;
#endif


#if 0
"if=0";
#elif 1
"elif=0";
#else
"else=1";
#endif


/**
 * 
 *
 */
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",

        "line" => 0,
        "output" => 1,
        "input" => NULL,
        "target" => NULL,

    ];


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

       #-- 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|ifn?def|if|elif|else|endif|pragma)   # directives
        ( \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.
     *
     */
    function __construct($include_dirs=[], $defines=[]) {
    
        $this->dirs = $include_dirs;
        
        // Non-static runtime constants
        $this->defines += $defines + [
            "__TIMESTAMP__" => [null, gmstrftime("%Y-%m-%dT%H:%M:%SZ")],
            "__BASE_FILE__" => [null, & $this->pragma["input"]],
        ];
    }
................................................................................
     * Main invocation method. Reads and transform source file,
     * returns processed output. Does not write to target itself.
     *
     * @param  string  filename
     * @return string
     *
     */
    function process(/*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;

        $output = $this->block(file_get_contents($fn));
        
        // Apply macros and constants in tokenization phase
        $output = /*$this->token_apply*/($output);
        
        restore_error_handler();        
        return $output;
    }



    /**



     * 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="") {

        // State/nesting tracking
        $out = "";
        $state = new ConditionState();    // counts nesting level, ->true and ->done states
    
        // 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);
        
        // Run over each #directive + content block
        while ($block = array_shift($src)) {
            $directive = $block[0];
            $args = trim($block[1]);

            // #directives

            switch ($directive) {

                case "if": 
                case "ifdef": 
                case "ifndef":

                    if ($directive == "if") {
                        $args = MacroExpression::strval($args);
                    }
                    else {
                        $args = isset($this->defines[$args]) ^ ($directive == "ifndef");
                    }
                    $state->level = +1;
                    $state->done = $state->true = intval($args != 0);




                    break;

                case "else":
                    $args = 1;
                case "elif":
                    if ($state->done) {
                        $state->true = 0;
                    }
                    elseif (MacroExpression::intval($args)) {
                        $state->done = 1;
                    }
                    break;
                
                case "endif":
                    $state->level = -1;
                    break;

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

                case "pragma":

                    $this->{"d_$directive"}($args);
                    d_include($args);
                    break;

                    d_define($args);
                    break;
            }
            
            echo "#state ", ($state->serialize()), "\n";

            // add to output?
            if ($state->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+(?:,\w+)*)\))? (?: [=\s]\s* (.*) )?$/x", $decl, $def))) {






            $this->defines[$def[1]] = array($def[2] ? $def[3] : NULL, $def[4]);
        }
    }

    /**
     * Removes declared constants or macros.
     *   β†’ #undef CONSTANT
     */
    function d_undef($name) {
        unset($this->defines[$args]);








    }

    /**
     * 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[$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) {
        $fn = trim($fn, "\"\'\<\>");












        $src = file_get_contents($fn);
        $src = preg_replace("/\A (\\xEF\\xBB\\xBF)? \s{,5} \<\?(php)? |  \>\? \s{,5} \Z/x", "", $src);




        $src = $this->process($src);



        return fnmatch($fn, "*.h") ? NULL : $src;
    }
    









}







/**























































































































































































 * More readable tracking of #if..#endif nesting levels,
 * keeps attributes:
 *   ->level  nesting / stack length
 *   ->true   current #if/#elif/#else tree is active



 *   ->done   whole condition block passed its active section




 *
 */
class ConditionState extends SplStack {

    function __construct() {
        $this->push(["level" => 0, "true" => "1", "done" => 0]);
    }
................................................................................
    function __set($name, $value) {
        if ($name == "level" and $value < 0) {
            assert('$this->level > 0 and $value == -1 /* incorrect #if/#endif nesting */');
            $this->pop();         // can only -1 pop or +1 add a new level
        }
        elseif ($name == "level" and $value >= 0) {
            assert('$value == +1 /* can only iterate one level at a time */');
            $this->push(["level" => $this->level + 1, "true" => 0, "done" => 0]);
        }
        else {
            $s = $this->pop();   // modify state attribute in last stack entry
            $s[$name] = $value;
            $this->push($s);
        }
    }
................................................................................


    /**
     * 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);
        
................................................................................
    
    // Inherit from MacroProcessor::$defines
    public $defines = [];#    "X"=>[0,0.001]];

}






#$r = MacroExpression::strval(" 2 + 3 * (7 - 2) * ( '5' * 2 - 1 ) + X");
#$r = MacroExpression::strval("7 - 5");
#echo "==", $r, "\n";
$p = new MacroProcessor();


print $p->process(__FILE__);









|








|
|
|








|




<
<







|
|
<
<
<
<
<







 







>
|










>




>













|
|








|
|
|






>
|













|







 







|






>



|






>

>
>
>








<













>





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








|












>

>
|
<
<
|
<



|







 







|
>
>
>
>
>
>
|








|
>
>
>
>
>
>
>
>










|











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

<
>
>
>
>
|
>
>
>


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







 







|







 







|







 







>
>
>
>




>
>
|
<
>
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
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
...
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
183
184
185
186
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
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
247
248
...
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
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
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530



531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
...
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
...
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
...
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760

761
/**
 * api: php
 * title: PHP Macro Preprocessor
 * description: Context-sensitive C-style #define/macro directive processing.
 * version: 0.1.0
 * type: rewrite
 * category: macro
 * pack: phrep.php, macro.php
 * 
 * Preprocessor to apply C-style #define, #ifdef, #include statements. Intended
 * as build helper and complex macro injector. It's language-specific to PHP,
 * but can consume 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;
#endif


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







/**
 * 
 *
 */
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.
     *
     */
    function __construct($include_dirs=[], $defines=[]) {
    
        $this->dirs = array_merge($this->dirs, $include_dirs);
        
        // Non-static runtime constants
        $this->defines += $defines + [
            "__TIMESTAMP__" => [null, gmstrftime("%Y-%m-%dT%H:%M:%SZ")],
            "__BASE_FILE__" => [null, & $this->pragma["input"]],
        ];
    }
................................................................................
     * 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="") {

        // State/nesting tracking

        $state = new ConditionState();    // counts nesting level, ->true and ->done states
    
        // 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);
        
        // Run over each #directive + content block
        while ($block = array_shift($src)) {
            $directive = $block[0];
            $args = trim($block[1]);

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

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

                case "else":
                    $args = 1;
                case "elif":
                    if ($state->done) {
                        $state->true = 0;
                    }
                    elseif ($state->true = MacroExpression::intval($args)) {
                        $state->done = 1;
                    }
                    break;
                
                case "endif":
                    $state->level = -1;
                    break;

                case "macro": $directive = "define";
                case "define":
                case "undef":
                case "include":
                case "stderr":
                case "pragma":
                    if ($state->true) {
                        $out .= $this->{"d_$directive"}($args);


                    }

                    break;
            }
            
            echo "#state ", json_encode(array_reverse(iterator_to_array($state))), "\n";

            // add to output?
            if ($state->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
     */
    function d_undef($name) {
        unset($this->defines[$name]);
    }

    /**
     * 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, 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
     *
     */
    function token_join($token) {        
        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;
        for ($i+=1; $i < count($token) && $level !== 0; $i++, $len++) {
            if (is_string($t = $token[$i])) {
                if ($t == "(") {
                    $level++;
                    if ($level == 1) continue;
                }
                elseif ($t == ")") {
                    $level--;
                }
                elseif ($t == "," and $level == 1) {
                    $params[] = $arg;
                    $arg = [];
                    continue;
                }
            }
            if ($level >= 1) {
               $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 {
            foreach ($keys as $i=>$k) {
#print "MACROKEY $i -> $k\n";
                if (is_int(strpos($k, ".."))) {
                    $k = trim($k, ".");
                    $body = preg_replace("/\b\Q$k\E\b/", var_export(array_slice($args, $i), TRUE), $body);
                }
                else {
                    $body = preg_replace("/\b\Q$k\E\b/", $args[$i], $body);
                }
            }
        }
        return $body;
    }
    
}



/**
 * 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]);
    }
................................................................................
    function __set($name, $value) {
        if ($name == "level" and $value < 0) {
            assert('$this->level > 0 and $value == -1 /* incorrect #if/#endif nesting */');
            $this->pop();         // can only -1 pop or +1 add a new level
        }
        elseif ($name == "level" and $value >= 0) {
            assert('$value == +1 /* can only iterate one level at a time */');
            $this->push(["level" => $this->level + 1, "true" => $this->true, "done" => 0]);
        }
        else {
            $s = $this->pop();   // modify state attribute in last stack entry
            $s[$name] = $value;
            $this->push($s);
        }
    }
................................................................................


    /**
     * 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);
        
................................................................................
    
    // Inherit from MacroProcessor::$defines
    public $defines = [];#    "X"=>[0,0.001]];

}


#include <license.ph>


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

#endif