PHP utility collection with hybrid and fluent APIs.

⌈⌋ branch:  hybrid7 libraries


Check-in [9dea381ebc]

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

Overview
Comment:Basic version, #directive preprocessing, and basic expression evaluation. No tokenization and constant / macro interpolation yet.
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:9dea381ebcbd1f24269f6c57438f9c30734b7c50
User & Date: mario 2015-02-16 20:16:28
Context
2015-02-17
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
20:15
Add ArrayObject compatiblity (arrayExchange, getArrayCopy). check-in: 037bab0b64 user: mario tags: trunk
Changes

Added 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
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
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
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
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
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
<?php
/**
 * 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"]],
        ];
    }


    /**
     * Output PHP warnings during preprocessing
     *
     */
    function stderr(/*int*/$errno, /*string*/$msg, $file=NULL, $line=NULL, $context=[]) {
        fwrite(STDERR, "$msg\n");
    }
    
    
    /**
     * 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 __get($name) {
        if ($name == "level") {  // level equals stack length
            return $this->count() - 1;
        }
        else {
            $s = $this->top();   // single state attrib
            return $s[$name];
        }
    }

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



/**
 * #if/#elif expression evaluation. Permits basic arithmetics, #define lookups,
 * a few hand-picked PHP callbacks, and decimal/float/tuple comparisons.
 * It's neither fully CPP compatible, nor in line with preprocess.py; and it's
 * likely pointless featuritis anyway.
 *
 * Uses a basic shunting-yard sorting method for its tokenized input, then
 * evaluates expressions down to a numeric or booleanish scalar. Has only minimal
 * error reporting, and operator/func precedence is incomplete/untuned..
 *
 */
class MacroExpression {

    # Expression tokens
    const RX_EXPR = "{
         (?: [\"\'](?<string>.*?)[\"\'])       # basic strings, no escape checking
       | (?<func>    defined|stri?pos|stri?str|is_int|is_float)        # functions
       | (?<op>      [+-/*^~&|(),%!<>] | >=|<=|==|!=|=~|\&\&|\|\| )    # operators
       | (?<number>  [+-]?\d+(?:\.\d+)*)       # can be multi-tuple version string
       | (?<literal> [\w_]+@?)                 # defined constants
    }mx";


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

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


    /**
     * Tokenize expression,  into a list of [type, value] pairs.
     *
     */
    function expr($src) {
        print "EXPR_SRC := \"$src\"\n";
        
        // Regex returns a list of optional [0]=>, [type]=>, [1]=>
        preg_match_all(self::RX_EXPR, $src, $tokens, PREG_SET_ORDER);
        $tokens = array_map(function($t) {
            return array_slice($t, -2, 1); // turn into [type=>value]* list
        }, $tokens);
        
        // Reorder by precedence into RPN
        $opvals = $this->group($tokens);

        // Apply operations
        return $this->run($opvals);
    }


    /**
     * Run through tokens, spool values+operators into reverse polish notation.
     * [2, 3, 5, *, +]  or for example  [CONST, defined, 1, >=]
     *
     */
    function group($tokens) {

        // operator precedence list
        $prec = " () , == >= > <= < == != ~= ! || && + - % ~ | & * / ^ ";
        $var = [];   // operand queue
        $ops = [];   // operator stack

        // .iteritems() over token list
        while ($t = array_shift($tokens)) {
            $type = key($t);
            $val = current($t);

            // literals
            if (strpos("(literal|number|string)", $type)) {
                $var[] = $val; #[$type, $val];
            }
            
            // parenthesis grouping
            elseif (($val == "(") or ($type=="func")) {
                $ops[] = $val;
            }
            elseif ($val == ")") {
                while (count($ops) && (end($ops) != "(")) {
                   $var[] = $val = array_pop($ops);
                }
                array_pop($ops);
            }
            
            // add to operator queue
            else {
                while (count($ops) and (strpos($prec, $val) < strpos($prec, $end = end($ops))) /*and $end != "("*/) {
                    $var[] = array_pop($ops);  
                }
                $ops[] = $val;
            }
        #echo "VAR_STACK := ", json_encode($var), "\n";
        #echo "OPS_STACK := ", json_encode($ops), "\n";
        }

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


    /**
     * Plop values of list, apply expressions or function callbacks as ordered.
     * (Operand relation overriden here as $pop(NN) parameter.)
     *
     */
    function run(&$opvals) {

        // prepare value stack
        $sum = [];
        $pop = function($prev=1) use (&$sum) { 
            assert('count($sum) >= $prev /* Empty value stack, unbalanced expressions. */');
            $v = array_splice($sum, -$prev, 1, []);
            return current($v);
        };
        
        // use values for encountered operations
        while (count($opvals)) {
            $e = array_shift($opvals);
            switch ($e) {
                case "!":  $sum[] = !$pop();  break;
                case "~":  $sum[] = ~$pop();  break;
                case "+":  $sum[] = $pop(1) + $pop(1);  break;
                case "-":  $sum[] = $pop(2) - $pop(1);  break;
                case "*":  $sum[] = $pop(1) * $pop(1);  break;
                case "/":  $sum[] = $pop(2) / $pop(1);  break;
                case "^":  $sum[] = $pop(1) ^ $pop(1);  break;
                case "&":  $sum[] = $pop(1) & $pop(1);  break;
                case "|":  $sum[] = $pop(1) | $pop(1);  break;
                case "%":  $sum[] = $pop(1) % $pop(1);  break;
                case "&&": $sum[] = $pop(1) && $pop(1);  break;
                case "||": $sum[] = $pop(1) || $pop(1);  break;
                case "==": $sum[] = $pop(1) == $pop(1);  break;
                case "!=": $sum[] = $pop(1) != $pop(1);  break;
                case ">":  $sum[] = version_compare($pop(2), $pop(1)) > 0;  break;
                case "<":  $sum[] = version_compare($pop(2), $pop(1)) < 0;  break;
                case ">=": $sum[] = version_compare($pop(2), $pop(1)) >= 0;  break;
                case "<=": $sum[] = version_compare($pop(2), $pop(1)) <= 0;  break;
                case "=~": $sum[] = preg_match($pop(2), $pop(1));  break;
                case ",":  $sum[] = array_merge((array)$pop(), (array)$pop()); break;
                default:
                    if ($e == "defined") {
                        $sum[] = isset($this->defines[$pop()]);
                    }
                    elseif (is_callable($e)) {
                        $sum[] = call_user_func_array($e, (array)$pop());
                    }
                    elseif (isset($this->defines[$e])) {  // define literals
                        $sum[] = $this->defines[$e][1];
                    }
                    else {  // numbers and strings
                        $sum[] = $e;
                    }
            }
#        echo "OPVAL := ", json_encode($e), "\n";
#        echo "RESULT_STACK := ", json_encode($sum), "\n";
        }

        return count($sum) == 1
             ? current($sum)
             : trigger_error("Expression leftovers, result discarded.");
    }
    
    // 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__);