├── .github └── workflows │ └── php.yml ├── .gitignore ├── LICENSE ├── README.md ├── bin ├── phpstan └── tests ├── composer.json ├── composer.lock ├── examples ├── CalculatedLiterals.peg.inc ├── Calculator.peg.inc ├── EqualRepeat.peg.inc ├── Rfc822.peg.inc └── Rfc822UTF8.peg.inc ├── lib └── hafriedlander │ └── Peg │ ├── Compiler.php │ ├── Compiler │ ├── PHPBuilder.php │ ├── PHPWriter.php │ ├── Rule.php │ ├── Rule │ │ └── PendingState.php │ ├── RuleSet.php │ ├── Token.php │ └── Token │ │ ├── Expressionable.php │ │ ├── ExpressionedRecurse.php │ │ ├── Literal.php │ │ ├── Option.php │ │ ├── Recurse.php │ │ ├── Regex.php │ │ ├── Sequence.php │ │ ├── Terminal.php │ │ └── Whitespace.php │ └── Parser │ ├── Basic.php │ ├── CachedRegexp.php │ └── Packrat.php ├── phpstan.neon └── tests ├── CachedRegexp.phpt ├── ParserInheritance.phpt ├── ParserPackrat.phpt ├── ParserSyntax.phpt ├── ParserVariables.phpt ├── bootstrap.php └── bootstrap.utils.php /.github/workflows/php.yml: -------------------------------------------------------------------------------- 1 | name: PHP tests 2 | 3 | on: [push] 4 | 5 | jobs: 6 | Tests: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | php-versions: ['8.0', '8.1', '8.2', '8.3', 'latest'] 11 | fail-fast: false 12 | steps: 13 | - uses: actions/checkout@v1 14 | - name: Setup PHP 15 | uses: shivammathur/setup-php@v2 16 | with: 17 | php-version: ${{ matrix.php-versions }} 18 | - name: Install dependencies 19 | run: | 20 | composer install --optimize-autoloader 21 | chmod +x ./bin/ 22 | - name: Run tests 23 | run: ./bin/tests 24 | - name: Run static analysis 25 | continue-on-error: true 26 | run: ./bin/phpstan 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | vendor 2 | .idea -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | PHP-PEG is released under three licenses: MIT, BSD, and GPL. You may pick the license that best suits your development needs. The text of all three licenses are provided below. 3 | 4 | MIT License 5 | ---- 6 | 7 | Copyright (C) 2009 Hamish Friedlander (hamish@silverstripe.com) and SilverStripe Limited (www.silverstripe.com) 8 | 9 | Permission is hereby granted, free of charge, to any person obtaining a copy 10 | of this software and associated documentation files (the "Software"), to deal 11 | in the Software without restriction, including without limitation the rights 12 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | copies of the Software, and to permit persons to whom the Software is 14 | furnished to do so, subject to the following conditions: 15 | 16 | The above copyright notice and this permission notice shall be included in 17 | all copies or substantial portions of the Software. 18 | 19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | THE SOFTWARE. 26 | 27 | BSD License 28 | ---- 29 | 30 | Copyright (C) 2009 Hamish Friedlander (hamish@silverstripe.com) and SilverStripe Limited (www.silverstripe.com) 31 | All rights reserved. 32 | 33 | Redistribution and use in source and binary forms, with or without 34 | modification, are permitted provided that the following conditions are met: 35 | * Redistributions of source code must retain the above copyright 36 | notice, this list of conditions and the following disclaimer. 37 | * Redistributions in binary form must reproduce the above copyright 38 | notice, this list of conditions and the following disclaimer in the 39 | documentation and/or other materials provided with the distribution. 40 | * Neither the name of the nor the 41 | names of its contributors may be used to endorse or promote products 42 | derived from this software without specific prior written permission. 43 | 44 | THIS SOFTWARE IS PROVIDED BY SilverStripe Limited ''AS IS'' AND ANY 45 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 46 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 47 | DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 48 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 49 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 50 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 51 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 52 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 53 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 54 | 55 | GPL License 56 | ---- 57 | 58 | The GNU General Public License (GPL) 59 | Version 2, June 1991 60 | 61 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 62 | 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 63 | 64 | Everyone is permitted to copy and distribute verbatim copies 65 | of this license document, but changing it is not allowed. 66 | 67 | Preamble 68 | 69 | The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. 70 | 71 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. 72 | 73 | To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. 74 | 75 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 76 | 77 | We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. 78 | 79 | Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. 80 | 81 | Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. 82 | 83 | The precise terms and conditions for copying, distribution and modification follow. 84 | 85 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 86 | 87 | 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". 88 | 89 | Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 90 | 91 | 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. 92 | 93 | You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 94 | 95 | 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: 96 | 97 | a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. 98 | 99 | b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. 100 | 101 | c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) 102 | 103 | These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. 104 | 105 | Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. 106 | 107 | In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 108 | 109 | 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: 110 | 111 | a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, 112 | 113 | b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, 114 | 115 | c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) 116 | 117 | The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. 118 | 119 | If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 120 | 121 | 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 122 | 123 | 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 124 | 125 | 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 126 | 127 | 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. 128 | 129 | If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. 130 | 131 | It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. 132 | 133 | This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 134 | 135 | 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 136 | 137 | 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 138 | 139 | Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 140 | 141 | 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. 142 | 143 | NO WARRANTY 144 | 145 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 146 | 147 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 148 | 149 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PEG parser-generator for PHP 2 | 3 | ### Disclaimer 4 | This is a _somehow opinionated_ continuation of [combyna/php-peg](https://github.com/combyna/php-peg), which was "a minimally invasive fork" of the original [hafriedlander/php-peg](https://github.com/hafriedlander/php-peg). 5 | 6 | From the several originally available types of PEG parsers only `Basic` and `Packrat` _(recommended)_ remain now. 7 | 8 | ## Notable features of this fork: 9 | - **Fix, Optimization**: *Packrat parser overhaul.* Simplified logic using arrays instead of a string. Arrays ultimately seemed to be more fit for the job, *memory-wise*. This also fixed occasional problem with accessing undefined indexes in packrat cache. 10 | - **Modern code style:** Codebase uses new _(PHP7+)_ language features and code format more familiar to current modern PHP. 11 | - **CLI interface is removed:** Just call `\hafriedlander\Peg\Compiler::compile($grammarDefinitionFile)` directly however you like. 12 | - **Testing**: Test suite is rewritten to use [`Nette Tester`](https://github.com/nette/tester) instead of [PHPUnit](https://github.com/sebastianbergmann/phpunit). 13 | - **Fixed**: Catastrophic backtracking problem *(sometimes happening when compiling a larger grammar)* avoided by simplifying regex that searches for grammar definitions. 14 | - **Optimization**: Using native PHP constants and functions with absolute namespace is slightly faster *(changed in generated code, too)*. 15 | - **Optimization**: Use strict comparisons where possible *(even in generated code)*. 16 | 17 | ## Documentation 18 | See the [documentation of the original library](https://github.com/hafriedlander/php-peg). 19 | -------------------------------------------------------------------------------- /bin/phpstan: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | cd $(dirname $0) 4 | 5 | ../vendor/bin/phpstan analyze -c ../phpstan.neon $@ 6 | 7 | -------------------------------------------------------------------------------- /bin/tests: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cd $(dirname $0)/.. 4 | 5 | ./vendor/bin/tester -p phpdbg ./tests $@ 6 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "smuuf/php-peg", 3 | "description": "PEG parser generator for PHP.", 4 | "keywords": [ 5 | "PEG", 6 | "parser", 7 | "DSL", 8 | "compiler" 9 | ], 10 | "homepage": "https://github.com/smuuf/php-peg", 11 | "type": "library", 12 | "license": [ 13 | "MIT" 14 | ], 15 | "authors": [ 16 | { 17 | "name": "Hamish Friedlander", 18 | "email": "hamish@silverstripe.com", 19 | "role": "Developer" 20 | }, 21 | { 22 | "name": "Premysl Karbula", 23 | "role": "Developer" 24 | }, 25 | { 26 | "name": "Johannes Künsebeck", 27 | "email": "kuensebeck@googlemail.com", 28 | "role": "Developer" 29 | }, 30 | { 31 | "name": "Dan Phillimore", 32 | "email": "dan@ovms.co", 33 | "role": "Developer" 34 | } 35 | ], 36 | "require": { 37 | "php": ">=8.0" 38 | }, 39 | "autoload": { 40 | "psr-0": { 41 | "hafriedlander\\Peg": "lib" 42 | } 43 | }, 44 | "require-dev": { 45 | "phpstan/phpstan": "^1.5", 46 | "nette/tester": "^2.4" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /composer.lock: -------------------------------------------------------------------------------- 1 | { 2 | "_readme": [ 3 | "This file locks the dependencies of your project to a known state", 4 | "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", 5 | "This file is @generated automatically" 6 | ], 7 | "content-hash": "768b568935bd4c0c7bc0fd0435474c78", 8 | "packages": [], 9 | "packages-dev": [ 10 | { 11 | "name": "nette/tester", 12 | "version": "v2.5.3", 13 | "source": { 14 | "type": "git", 15 | "url": "https://github.com/nette/tester.git", 16 | "reference": "ee0a4b8402a8c1831db547ec0a56d18196906b51" 17 | }, 18 | "dist": { 19 | "type": "zip", 20 | "url": "https://api.github.com/repos/nette/tester/zipball/ee0a4b8402a8c1831db547ec0a56d18196906b51", 21 | "reference": "ee0a4b8402a8c1831db547ec0a56d18196906b51", 22 | "shasum": "" 23 | }, 24 | "require": { 25 | "php": "8.0 - 8.3" 26 | }, 27 | "require-dev": { 28 | "ext-simplexml": "*", 29 | "phpstan/phpstan": "^1.0" 30 | }, 31 | "bin": [ 32 | "src/tester" 33 | ], 34 | "type": "library", 35 | "extra": { 36 | "branch-alias": { 37 | "dev-master": "2.5-dev" 38 | } 39 | }, 40 | "autoload": { 41 | "classmap": [ 42 | "src/" 43 | ] 44 | }, 45 | "notification-url": "https://packagist.org/downloads/", 46 | "license": [ 47 | "BSD-3-Clause", 48 | "GPL-2.0-only", 49 | "GPL-3.0-only" 50 | ], 51 | "authors": [ 52 | { 53 | "name": "David Grudl", 54 | "homepage": "https://davidgrudl.com" 55 | }, 56 | { 57 | "name": "Miloslav Hůla", 58 | "homepage": "https://github.com/milo" 59 | }, 60 | { 61 | "name": "Nette Community", 62 | "homepage": "https://nette.org/contributors" 63 | } 64 | ], 65 | "description": "Nette Tester: enjoyable unit testing in PHP with code coverage reporter. 🍏🍏🍎🍏", 66 | "homepage": "https://tester.nette.org", 67 | "keywords": [ 68 | "Xdebug", 69 | "assertions", 70 | "clover", 71 | "code coverage", 72 | "nette", 73 | "pcov", 74 | "phpdbg", 75 | "phpunit", 76 | "testing", 77 | "unit" 78 | ], 79 | "support": { 80 | "issues": "https://github.com/nette/tester/issues", 81 | "source": "https://github.com/nette/tester/tree/v2.5.3" 82 | }, 83 | "time": "2024-06-18T18:44:12+00:00" 84 | }, 85 | { 86 | "name": "phpstan/phpstan", 87 | "version": "1.12.6", 88 | "source": { 89 | "type": "git", 90 | "url": "https://github.com/phpstan/phpstan.git", 91 | "reference": "dc4d2f145a88ea7141ae698effd64d9df46527ae" 92 | }, 93 | "dist": { 94 | "type": "zip", 95 | "url": "https://api.github.com/repos/phpstan/phpstan/zipball/dc4d2f145a88ea7141ae698effd64d9df46527ae", 96 | "reference": "dc4d2f145a88ea7141ae698effd64d9df46527ae", 97 | "shasum": "" 98 | }, 99 | "require": { 100 | "php": "^7.2|^8.0" 101 | }, 102 | "conflict": { 103 | "phpstan/phpstan-shim": "*" 104 | }, 105 | "bin": [ 106 | "phpstan", 107 | "phpstan.phar" 108 | ], 109 | "type": "library", 110 | "autoload": { 111 | "files": [ 112 | "bootstrap.php" 113 | ] 114 | }, 115 | "notification-url": "https://packagist.org/downloads/", 116 | "license": [ 117 | "MIT" 118 | ], 119 | "description": "PHPStan - PHP Static Analysis Tool", 120 | "keywords": [ 121 | "dev", 122 | "static analysis" 123 | ], 124 | "support": { 125 | "docs": "https://phpstan.org/user-guide/getting-started", 126 | "forum": "https://github.com/phpstan/phpstan/discussions", 127 | "issues": "https://github.com/phpstan/phpstan/issues", 128 | "security": "https://github.com/phpstan/phpstan/security/policy", 129 | "source": "https://github.com/phpstan/phpstan-src" 130 | }, 131 | "funding": [ 132 | { 133 | "url": "https://github.com/ondrejmirtes", 134 | "type": "github" 135 | }, 136 | { 137 | "url": "https://github.com/phpstan", 138 | "type": "github" 139 | } 140 | ], 141 | "time": "2024-10-06T15:03:59+00:00" 142 | } 143 | ], 144 | "aliases": [], 145 | "minimum-stability": "stable", 146 | "stability-flags": [], 147 | "prefer-stable": false, 148 | "prefer-lowest": false, 149 | "platform": { 150 | "php": ">=7.4" 151 | }, 152 | "platform-dev": [], 153 | "plugin-api-version": "2.3.0" 154 | } 155 | -------------------------------------------------------------------------------- /examples/CalculatedLiterals.peg.inc: -------------------------------------------------------------------------------- 1 | '}', '[' => ']', '(' => ')', '<' => '>' ) ; 18 | return $a[$res['q']] ; 19 | } 20 | 21 | freequote-unmatched: "qq" q:/./ string '$q' 22 | 23 | quoted-string: freequote-matched | freequote-unmatched | simplequote 24 | 25 | */ 26 | 27 | } 28 | -------------------------------------------------------------------------------- /examples/Calculator.peg.inc: -------------------------------------------------------------------------------- 1 | | '(' > Expr > ')' > 13 | function Number( &$result, $sub ) { 14 | $result['val'] = $sub['text'] ; 15 | } 16 | function Expr( &$result, $sub ) { 17 | $result['val'] = $sub['val'] ; 18 | } 19 | 20 | Times: '*' > operand:Value > 21 | Div: '/' > operand:Value > 22 | Product: Value > ( Times | Div ) * 23 | function Value( &$result, $sub ) { 24 | $result['val'] = $sub['val'] ; 25 | } 26 | function Times( &$result, $sub ) { 27 | $result['val'] *= $sub['operand']['val'] ; 28 | } 29 | function Div( &$result, $sub ) { 30 | $result['val'] /= $sub['operand']['val'] ; 31 | } 32 | 33 | Plus: '+' > operand:Product > 34 | Minus: '-' > operand:Product > 35 | Sum: Product > ( Plus | Minus ) * 36 | function Product( &$result, $sub ) { 37 | $result['val'] = $sub['val'] ; 38 | } 39 | function Plus( &$result, $sub ) { 40 | $result['val'] += $sub['operand']['val'] ; 41 | } 42 | function Minus( &$result, $sub ) { 43 | $result['val'] -= $sub['operand']['val'] ; 44 | } 45 | 46 | Expr: Sum 47 | function Sum( &$result, $sub ) { 48 | $result['val'] = $sub['val'] ; 49 | } 50 | 51 | */ 52 | 53 | } 54 | 55 | $x = new Calculator( '(2 + 4) * 3 - 10' ) ; 56 | $res = $x->match_Expr() ; 57 | if ( $res === FALSE ) { 58 | print "No Match\n" ; 59 | } 60 | else { 61 | print_r( $res ) ; 62 | } 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /examples/EqualRepeat.peg.inc: -------------------------------------------------------------------------------- 1 | match_X() ; 26 | print "$str\n" ; 27 | print $r ? print_r( $r, true ) : 'No Match' ; 28 | print "\n\n" ; 29 | } 30 | 31 | match( 'aabbcc' ) ; // Should match 32 | match( 'aaabbbccc' ) ; // Should match 33 | 34 | match( 'aabbbccc' ) ; // Should not match 35 | match( 'aaabbccc' ) ; // Should not match 36 | match( 'aaabbbcc' ) ; // Should not match 37 | 38 | match( 'aaabbbcccc' ) ; // Should not match 39 | -------------------------------------------------------------------------------- /examples/Rfc822.peg.inc: -------------------------------------------------------------------------------- 1 | @,;:\\".\[\]\x80-\xFF]+/ 22 | 23 | qtext-chars: /[^"\\\x0D]+/ 24 | 25 | qtext: linear-white-space | qtext-chars 26 | 27 | quoted-pair: /\\[\x00-\x7F]/ 28 | 29 | quoted-string: .'"' ( quoted-pair | qtext )* .'"' 30 | 31 | word: atom | quoted-string 32 | 33 | phrase: (word >)+ 34 | 35 | dtext-chars: /[^\[\]\\\r]+/ 36 | 37 | dtext: linear-white-space | dtext-chars 38 | 39 | domain-literal: "[" ( dtext | quoted-pair )* "]" 40 | 41 | domain-ref: atom 42 | 43 | sub-domain: domain-ref | domain-literal 44 | 45 | domain: sub-domain ("." sub-domain)* 46 | 47 | route: "@" domain ("," "@" domain)* ":" 48 | 49 | route-addr: "<" route? addr-spec ">" 50 | function addr_spec ( &$self, $sub ) { 51 | $self['addr_spec'] = $sub['text'] ; 52 | } 53 | 54 | local-part: word ("." word)* 55 | 56 | addr-spec: local-part "@" domain 57 | 58 | mailbox: ( addr-spec | phrase route-addr ) > 59 | function __construct( &$self ) { 60 | $self['phrase'] = NULL ; 61 | $self['address'] = NULL ; 62 | } 63 | function phrase ( &$self, $sub ) { 64 | $self['phrase'] = $sub['text'] ; 65 | } 66 | function addr_spec ( &$self, $sub ) { 67 | $self['address'] = $sub['text'] ; 68 | } 69 | function route_addr ( &$self, $sub ) { 70 | $self['address'] = $sub['addr_spec'] ; 71 | } 72 | 73 | group: phrase ":" ( mailbox ("," mailbox)* )? ";" 74 | 75 | address: :mailbox | group 76 | 77 | address-header: address (<","> address)* 78 | function __construct( &$self ) { 79 | $self['addresses'] = array() ; 80 | } 81 | function address( &$self, $sub ) { 82 | $self['addresses'][] = $sub['mailbox'] ; 83 | } 84 | 85 | */ 86 | 87 | } 88 | 89 | $p = new Rfc822( 'John Byorgson , "Akira \"Bad Boy\" Kenada" ' ) ; 90 | print_r( $p->match_address_header() ) ; 91 | -------------------------------------------------------------------------------- /examples/Rfc822UTF8.peg.inc: -------------------------------------------------------------------------------- 1 | @,;:\[\]\\".]) )+/u 16 | 17 | qtext-chars: /[^"\\\x0D]+/u 18 | 19 | quoted-pair: /\\./u 20 | 21 | */ 22 | 23 | } 24 | 25 | /** 26 | * Some trial code. Remove soon 27 | */ 28 | $p = new Rfc822UTF8( 'JØhn ByØrgsØn , "アキラ" ' ) ; 29 | print_r( $p->match_address_header() ) ; 30 | /* */ 31 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler.php: -------------------------------------------------------------------------------- 1 | compile($indent, $match['grammar']); 42 | 43 | } 44 | 45 | public static function compile(string $string): string { 46 | 47 | static $rx = '@ 48 | # Optional indent and marker of grammar definition start. 49 | ^(?\h*)/\*!\* 50 | 51 | # Optional pragmas and optional name. 52 | \h*(?(!\w+)+\h+)?(?(\w)+)?\h*\r?\n 53 | 54 | # Any character 55 | (?.+)(?=\*/) 56 | 57 | # Grammar definition end. 58 | \*/ 59 | @smx'; 60 | 61 | return preg_replace_callback( 62 | $rx, 63 | [self::class, 'createParser'], 64 | $string 65 | ); 66 | 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/PHPBuilder.php: -------------------------------------------------------------------------------- 1 | lines; 27 | } else { 28 | $lines = \array_map('rtrim', $lines); 29 | } 30 | 31 | if (!$lines) { 32 | continue; 33 | } 34 | 35 | $this->lines = \array_merge($this->lines, $lines); 36 | 37 | } 38 | 39 | return $this; 40 | } 41 | 42 | function b(...$args) { 43 | 44 | $entry = \array_shift($args); 45 | 46 | $block = new PHPBuilder; 47 | $block->l(...$args); 48 | $this->lines[] = [$entry, $block->lines]; 49 | 50 | return $this; 51 | } 52 | 53 | function replace(array $replacements, array &$array = \null) { 54 | if ($array === \null) { 55 | unset($array); 56 | $array =& $this->lines; 57 | } 58 | 59 | $i = 0; 60 | while ($i < \count($array)) { 61 | 62 | /* Recurse into blocks */ 63 | if (\is_array($array[$i])) { 64 | $this->replace($replacements, $array[$i][1]); 65 | 66 | if (\count($array[$i][1]) === 0) { 67 | $nextelse = isset($array[$i + 1]) 68 | && \is_array($array[$i + 1]) 69 | && \preg_match('/^\s*else\s*$/i', $array[$i + 1][0]); 70 | 71 | $delete = \preg_match('/^\s*else\s*$/i', $array[$i][0]); 72 | $delete = $delete || (\preg_match('/^\s*if\s*\(/i', $array[$i][0]) && !$nextelse); 73 | 74 | if ($delete) { 75 | // Is this always safe? Not if the expression has side-effects. 76 | // print "/* REMOVING EMPTY BLOCK: " . $array[$i][0] . "*/\n"; 77 | \array_splice($array, $i, 1); 78 | continue; 79 | } 80 | } 81 | } else { 82 | /* Handle replacing lines with \null to remove, or string, array of strings or PHPBuilder to replace */ 83 | if (\array_key_exists($array[$i], $replacements)) { 84 | $rep = $replacements[$array[$i]]; 85 | 86 | if ($rep === \null) { 87 | \array_splice($array, $i, 1); 88 | continue; 89 | } 90 | 91 | if (\is_string($rep)) { 92 | $array[$i] = $rep; 93 | $i++ ; 94 | continue; 95 | } 96 | 97 | if ($rep instanceof self) { 98 | $rep = $rep->lines; 99 | } 100 | 101 | if (\is_array($rep)) { 102 | \array_splice($array, $i, 1, $rep); $i += \count($rep) + 1; 103 | continue; 104 | } 105 | 106 | throw new \Exception('Unknown type passed to PHPBuilder#replace'); 107 | } 108 | } 109 | 110 | $i++; 111 | } 112 | 113 | return $this; 114 | } 115 | 116 | function render(?array $array = \null, string $indent = ""): string { 117 | 118 | if ($array === \null) { 119 | $array = $this->lines; 120 | } 121 | 122 | $out = []; 123 | foreach ($array as $line) { 124 | if (\is_array($line)) { 125 | [$entry, $block] = $line; 126 | $str = $this->render($block, $indent . "\t"); 127 | 128 | if (\strlen($str) < 40) { 129 | $out[] = $indent . $entry . ' { ' . \ltrim($str) . ' }'; 130 | } else { 131 | $out[] = $indent . $entry . ' {'; 132 | $out[] = $str; 133 | $out[] = $indent . '}'; 134 | } 135 | } else { 136 | $out[] = $indent . $line; 137 | } 138 | } 139 | 140 | return \implode(\PHP_EOL, $out); 141 | 142 | } 143 | 144 | } 145 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/PHPWriter.php: -------------------------------------------------------------------------------- 1 | l( 27 | '$res' . $id . ' = $result;', 28 | '$pos' . $id . ' = $this->pos;' 29 | ); 30 | } 31 | 32 | public function restore($id, $remove = \false) { 33 | $code = PHPBuilder::build() 34 | ->l( 35 | '$result = $res' . $id . ';', 36 | '$this->setPos($pos' . $id . ');' 37 | ); 38 | 39 | if ($remove) { 40 | $code->l( 41 | 'unset($res' . $id . ', $pos' . $id . ');' 42 | ); 43 | } 44 | 45 | return $code; 46 | } 47 | 48 | public function matchFailConditional($on, $match = \null, $fail = \null) { 49 | return PHPBuilder::build() 50 | ->b( 51 | 'if (' . $on . ')', 52 | $match, 53 | 'MATCH' 54 | ) 55 | ->b( 56 | 'else', 57 | $fail, 58 | 'FAIL' 59 | ); 60 | } 61 | 62 | public function matchFailBlock($code) { 63 | $id = $this->varid(); 64 | 65 | return PHPBuilder::build() 66 | ->l( 67 | '$' . $id . ' = \null;' 68 | ) 69 | ->b( 70 | 'do', 71 | $code->replace([ 72 | 'MBREAK' => '$' . $id . ' = \true; break;', 73 | 'FBREAK' => '$' . $id . ' = \false; break;' 74 | ]) 75 | ) 76 | ->l('while(\false);') 77 | ->b('if($' . $id . ' === \true)', 'MATCH') 78 | ->b('if($' . $id . ' === \false)', 'FAIL'); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Rule.php: -------------------------------------------------------------------------------- 1 | [\w-]+) # The name of the rule 16 | ( \s+ extends \s+ (?[\w-]+) )? # The extends word 17 | ( \s* \( (?.*) \) )? # Any variable setters 18 | ( 19 | \s*(?:) | # Marks the matching rule start 20 | \s*(?;) | # Marks the replacing rule start 21 | \s*$ 22 | ) 23 | (?[\s\S]*) 24 | @x'; 25 | 26 | private const ARGUMENT_RX = '@ 27 | ( [^=]+ ) # Name 28 | = # Seperator 29 | ( [^=,]+ ) # Variable 30 | (,|$) 31 | @x'; 32 | 33 | private const REPLACEMENT_RX = '@ 34 | ( ([^=]|=[^>])+ ) # What to replace 35 | => # The replacement mark 36 | ( [^,]+ ) # What to replace it with 37 | (,|$) 38 | @x'; 39 | 40 | private const RX_RX = '@\G/( 41 | ((\\\\\\\\)*\\\\/) # Escaped \/, making sure to catch all the \\ first, so that we dont think \\/ is an escaped / 42 | | 43 | [^/] # Anything except / 44 | )*/[a-zA-Z]*@xu'; 45 | 46 | private const FUNCTION_RX = '@^\s+function\s+([^\s(]+)\s*(.*)@'; 47 | 48 | private const MODE_RULE = 0; 49 | private const MODE_REPLACE = 1; 50 | 51 | private RuleSet $ruleSet; 52 | private Token $parsed; 53 | 54 | private array $arguments = []; 55 | private array $functions = []; 56 | 57 | private string $name; 58 | private string $rule; 59 | private ?self $extends = \null; 60 | private int $mode; 61 | 62 | public function __construct(RuleSet $ruleSet, array $lines) { 63 | $this->ruleSet = $ruleSet; 64 | 65 | // Find the first line (if any) that's an attached function definition. Can skip first line (unless this block is malformed) 66 | $lineCount = \count($lines); 67 | for ($i = 1; $i < $lineCount; $i++) { 68 | if (\preg_match(self::FUNCTION_RX, $lines[$i])) { 69 | break; 70 | } 71 | } 72 | 73 | // Then split into the two parts 74 | $spec = \array_slice($lines, 0, $i); 75 | $funcs = \array_slice($lines, $i); 76 | 77 | // Parse out the spec 78 | $spec = \implode("\n", $spec); 79 | if (!\preg_match(self::RULE_RX, $spec, $specmatch)) { 80 | \user_error('Malformed rule spec ' . $spec, E_USER_ERROR); 81 | } 82 | 83 | $this->name = $specmatch['name']; 84 | 85 | if ($specmatch['extends']) { 86 | $this->extends = $this->ruleSet->getRule($specmatch['extends']); 87 | if (!$this->extends) { 88 | \user_error('Extended rule ' . $specmatch['extends'] . ' is not defined before being extended', E_USER_ERROR); 89 | } 90 | } 91 | 92 | if ($specmatch['arguments']) { 93 | \preg_match_all(self::ARGUMENT_RX, $specmatch['arguments'], $arguments, \PREG_SET_ORDER); 94 | 95 | foreach ($arguments as $argument) { 96 | $this->arguments[\trim($argument[1])] = \trim($argument[2]); 97 | } 98 | } 99 | 100 | $this->mode = $specmatch['matchmark'] 101 | ? self::MODE_RULE 102 | : self::MODE_REPLACE; 103 | 104 | if ($this->mode === self::MODE_RULE) { 105 | $this->rule = $specmatch['rule']; 106 | $this->parseRule(); 107 | } else { 108 | if (!$this->extends) { 109 | user_error("Rule $this->name has Replace matcher, but not on an extends rule", E_USER_ERROR); 110 | } 111 | 112 | \preg_match_all(self::REPLACEMENT_RX, $specmatch['rule'], $replacements, \PREG_SET_ORDER); 113 | 114 | $rule = $this->extends->getRule(); 115 | 116 | foreach ($replacements as $replacement) { 117 | $search = \trim($replacement[1]); 118 | $replace = \trim($replacement[3]); 119 | if ($replace == "''" || $replace == '""') { 120 | $replace = ''; 121 | } 122 | 123 | $rule = \str_replace($search, ' ' . $replace . ' ', $rule); 124 | } 125 | 126 | $this->rule = $rule; 127 | $this->parseRule(); 128 | } 129 | 130 | // Parse out the functions 131 | $activeFunction = \null; 132 | 133 | foreach ($funcs as $line) { 134 | /* Handle function definitions */ 135 | if (\preg_match(self::FUNCTION_RX, $line, $func_match, 0)) { 136 | $activeFunction = $func_match[1]; 137 | $this->functions[$activeFunction] = $func_match[2] . \PHP_EOL; 138 | } else { 139 | $this->functions[$activeFunction] .= $line . \PHP_EOL; 140 | } 141 | } 142 | 143 | } 144 | 145 | public function getName(): string { 146 | return $this->name; 147 | } 148 | 149 | public function getRule(): string { 150 | return $this->rule; 151 | } 152 | 153 | /* Manual parsing, because we can't bootstrap ourselves yet */ 154 | public function parseRule() { 155 | $rule = \trim($this->rule); 156 | 157 | $tokens = []; 158 | $this->tokenize($rule, $tokens); 159 | $this->parsed = (\count($tokens) == 1 ? \array_pop($tokens) : new Token\Sequence($tokens)); 160 | } 161 | 162 | public function tokenize($str, &$tokens, $o = 0) { 163 | 164 | $length = \strlen($str); 165 | $pending = new Rule\PendingState(); 166 | 167 | while ($o < $length) { 168 | /* Absorb white-space */ 169 | if (\preg_match('/\G\s+/', $str, $match, 0, $o)) { 170 | $o += \strlen($match[0]); 171 | } 172 | /* Handle expression labels */ 173 | elseif (\preg_match('/\G(\w*):/', $str, $match, 0, $o)) { 174 | $pending->set('tag', $match[1] ?: ''); 175 | $o += \strlen($match[0]); 176 | } 177 | /* Handle descent token */ 178 | elseif (\preg_match('/\G[\w-]+/', $str, $match, 0, $o)) { 179 | $tokens[] = $t = new Token\Recurse($match[0]); 180 | $pending->applyIfPresent($t); 181 | $o += \strlen($match[0]); 182 | } 183 | /* Handle " quoted literals */ 184 | elseif (\preg_match('/\G"[^"]*"/', $str, $match, 0, $o)) { 185 | $tokens[] = $t = new Token\Literal($match[0]); 186 | $pending->applyIfPresent($t); 187 | $o += \strlen($match[0]); 188 | } 189 | /* Handle ' quoted literals */ 190 | elseif (\preg_match("/\G'[^']*'/", $str, $match, 0, $o)) { 191 | $tokens[] = $t = new Token\Literal($match[0]); 192 | $pending->applyIfPresent($t); 193 | $o += \strlen($match[0]); 194 | } 195 | /* Handle regexs */ 196 | elseif (\preg_match(self::RX_RX, $str, $match, 0, $o)) { 197 | $tokens[] = $t = new Token\Regex($match[0]); 198 | $pending->applyIfPresent($t); 199 | $o += \strlen($match[0]); 200 | } 201 | /* Handle $ call literals */ 202 | elseif (\preg_match('/\G\$(\w+)/', $str, $match, 0, $o)) { 203 | $tokens[] = $t = new Token\ExpressionedRecurse($match[1]); 204 | $pending->applyIfPresent($t); 205 | $o += \strlen($match[0]); 206 | } 207 | /* Handle flags */ 208 | elseif (\preg_match('/\G\@(\w+)/', $str, $match, 0, $o)) { 209 | $l = \count($tokens) - 1; 210 | $o += \strlen($match[0]); 211 | \user_error('TODO: Flags not currently supported', E_USER_WARNING); 212 | } 213 | /* Handle control tokens */ 214 | else { 215 | $c = \substr($str, $o, 1); 216 | $l = \count($tokens) - 1; 217 | $o += 1; 218 | switch ($c) { 219 | case '?': 220 | $tokens[$l]->quantifier = ['min' => 0, 'max' => 1]; 221 | break; 222 | case '*': 223 | $tokens[$l]->quantifier = ['min' => 0, 'max' => \null]; 224 | break; 225 | case '+': 226 | $tokens[$l]->quantifier = ['min' => 1, 'max' => \null]; 227 | break; 228 | case '{': 229 | if (\preg_match('/\G\{([0-9]+)(,([0-9]*))?\}/', $str, $matches, 0, $o - 1)) { 230 | $min = $max = (int) $matches[1]; 231 | if (isset($matches[2])) { 232 | $max = $matches[3] ? (int) $matches[3] : \null; 233 | } 234 | $tokens[$l]->quantifier = ['min' => $min, 'max' => $max]; 235 | $o += \strlen($matches[0]) - 1; 236 | } else { 237 | throw new \Exception(sprintf( 238 | 'Unknown quantifier: %s', 239 | substr($str, $o, 10) 240 | )); 241 | } 242 | break; 243 | case '&': 244 | $pending->set('positiveLookahead'); 245 | break; 246 | case '!': 247 | $pending->set('negativeLookahead'); 248 | break; 249 | 250 | case '.': 251 | $pending->set('silent'); 252 | break; 253 | 254 | case '[': 255 | case ']': 256 | $tokens[] = new Token\Whitespace(\false); 257 | break; 258 | case '<': 259 | case '>': 260 | $tokens[] = new Token\Whitespace(\true); 261 | break; 262 | 263 | case '(': 264 | $subtokens = []; 265 | $o = $this->tokenize($str, $subtokens, $o); 266 | $tokens[] = $t = new Token\Sequence($subtokens); $pending->applyIfPresent($t); 267 | break; 268 | case ')': 269 | return $o; 270 | 271 | case '|': 272 | $option1 = $tokens; 273 | $option2 = []; 274 | $o = $this->tokenize($str, $option2, $o); 275 | 276 | $option1 = (\count($option1) == 1) ? $option1[0] : new Token\Sequence($option1); 277 | $option2 = (\count($option2) == 1) ? $option2[0] : new Token\Sequence($option2); 278 | 279 | $pending->applyIfPresent($option2); 280 | 281 | $tokens = [new Token\Option($option1, $option2)]; 282 | return $o; 283 | 284 | default: 285 | \user_error("Can't parse '$c' - attempting to skip", E_USER_WARNING); 286 | } 287 | } 288 | } 289 | 290 | return $o; 291 | } 292 | 293 | /** 294 | * Generate the PHP code for a function to match against a string for this rule 295 | */ 296 | public function compile($indent) { 297 | $fnName = $this->functionName($this->name); 298 | 299 | // Build the typestack 300 | $typestack = []; 301 | $class = $this; 302 | do { 303 | $typestack[] = $this->functionName($class->name); 304 | } while ($class = $class->extends); 305 | 306 | $typestack = "['" . \implode("','", $typestack) . "']"; 307 | 308 | $match = PHPBuilder::build(); 309 | 310 | $match->l("protected \$match_{$fnName}_typestack = $typestack;"); 311 | 312 | $block = $this->parsed->compile()->replace([ 313 | 'MATCH' => 'return $this->finalise($result);', 314 | 'FAIL' => 'return \false;' 315 | ]); 316 | 317 | // Build an array of additional arguments to add to result node (if any). 318 | $arguments = $this->arguments 319 | ? (", " . \var_export($this->arguments, \true)) 320 | : ''; 321 | 322 | $match->b( 323 | "function match_{$fnName}(\$stack = [])", 324 | "\$matchrule = '$fnName';", 325 | "\$this->currentRule = \$matchrule;", 326 | "\$result = \$this->construct(\$matchrule, \$matchrule$arguments); ", 327 | $block 328 | ); 329 | 330 | $functions = []; 331 | foreach ($this->functions as $name => $function) { 332 | $fnName = $this->functionName( 333 | \preg_match('/^_/', $name) 334 | ? $this->name . $name 335 | : $this->name . '_' . $name 336 | ); 337 | $functions[] = \implode(\PHP_EOL, [ 338 | 'public function ' . $fnName . ' ' . $function 339 | ]); 340 | } 341 | 342 | // print_r( $match ); return ''; 343 | return $match->render(\null, $indent) 344 | . \PHP_EOL 345 | . \PHP_EOL 346 | . \implode(\PHP_EOL, $functions); 347 | 348 | } 349 | } 350 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Rule/PendingState.php: -------------------------------------------------------------------------------- 1 | next token, and deletion of that 7 | * information after applying 8 | * 9 | * @author Hamish Friedlander 10 | */ 11 | class PendingState { 12 | 13 | private ?string $what = \null; 14 | private $val; 15 | 16 | function set(string $what, $val = \true) { 17 | $this->what = $what; 18 | $this->val = $val; 19 | } 20 | 21 | function applyIfPresent(object $on) { 22 | 23 | if ($this->what === \null) { 24 | return; 25 | } 26 | 27 | $what = $this->what; 28 | $on->$what = $this->val; 29 | $this->what = \null; 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/RuleSet.php: -------------------------------------------------------------------------------- 1 | getName(); 14 | $this->rules[$ruleName] = $rule; 15 | 16 | $out[] = $indent . '/* ' . $ruleName . ':' . $rule->getRule() . ' */' . \PHP_EOL; 17 | $out[] = $rule->compile($indent); 18 | $out[] = \PHP_EOL; 19 | 20 | } 21 | 22 | public function getRule(string $name): ?Rule { 23 | return $this->rules[$name] ?? \null; 24 | } 25 | 26 | function compile($indent, $rulestr) { 27 | 28 | $out = []; 29 | $block = []; 30 | 31 | foreach (\preg_split('/\r\n|\r|\n/', $rulestr) as $line) { 32 | 33 | // Ignore blank lines 34 | if (!\trim($line)) { 35 | continue; 36 | } 37 | 38 | // Ignore comments 39 | if (\preg_match('/^[\x20\t]*#/', $line)) { 40 | continue; 41 | } 42 | 43 | // Strip off indent 44 | if (!empty($indent)) { 45 | if (\strpos($line, $indent) === 0) $line = \substr($line, \strlen($indent)); 46 | else \user_error('Non-blank line with inconsistent index in parser block', E_USER_ERROR); 47 | } 48 | 49 | // Any indented line, add to current set of lines 50 | if (\preg_match('/^[\x20\t]/', $line)) { 51 | $block[] = $line; 52 | } else { 53 | 54 | // Any non-indented line marks a new block. Add a rule for the current block, then start a new block 55 | if (\count($block)) { 56 | $this->addRule($indent, $block, $out); 57 | } 58 | 59 | $block = [$line]; 60 | 61 | } 62 | 63 | } 64 | 65 | // Any unfinished block add a rule for 66 | if (\count($block)) { 67 | $this->addRule($indent, $block, $out); 68 | } 69 | 70 | // And return the compiled version 71 | return \implode('', $out); 72 | 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token.php: -------------------------------------------------------------------------------- 1 | type = $type; 34 | $this->value = $value; 35 | } 36 | 37 | abstract protected function matchCode($value); 38 | 39 | public function compile() { 40 | 41 | $code = $this->matchCode($this->value); 42 | $id = $this->varid(); 43 | 44 | if ($this->quantifier) { 45 | $q = $this->quantifier; 46 | if (0 === $q['min'] && 1 === $q['max']) { 47 | // optional: ? || {0,1} 48 | $code = $this->optional($code, $id); 49 | } elseif (0 === $q['min'] && \null === $q['max']) { 50 | // zero or more: * || {0,} 51 | $code = $this->zero_or_more($code, $id); 52 | } elseif (\null === $q['max']) { 53 | // n or more: + || {n,} 54 | $code = $this->n_or_more($code, $id, $q['min']); 55 | } else { 56 | // {n,x} 57 | $code = $this->n_to_x($code, $id, $q['min'], $q['max']); 58 | } 59 | } 60 | 61 | if ($this->positiveLookahead) { 62 | $code = PHPBuilder::build() 63 | ->l( 64 | $this->save($id), 65 | $code->replace([ 66 | 'MATCH' => 67 | $this->restore($id) 68 | ->l('MATCH'), 69 | 'FAIL' => 70 | $this->restore($id) 71 | ->l('FAIL') 72 | ])); 73 | } 74 | 75 | if ($this->negativeLookahead) { 76 | $code = PHPBuilder::build() 77 | ->l( 78 | $this->save($id), 79 | $code->replace([ 80 | 'MATCH' => 81 | $this->restore($id) 82 | ->l('FAIL'), 83 | 'FAIL' => 84 | $this->restore($id) 85 | ->l('MATCH') 86 | ])); 87 | } 88 | 89 | if ($this->tag && !($this instanceof Token\Recurse)) { 90 | $code = PHPBuilder::build() 91 | ->l( 92 | '$stack[] = $result; $result = $this->construct($matchrule, "'.$this->tag.'");', 93 | $code->replace([ 94 | 'MATCH' => PHPBuilder::build() 95 | ->l( 96 | '$subres = $result; $result = \array_pop($stack);', 97 | '$this->store($result, $subres, \''.$this->tag.'\');', 98 | 'MATCH' 99 | ), 100 | 'FAIL' => PHPBuilder::build() 101 | ->l( 102 | '$result = \array_pop($stack);', 103 | 'FAIL' 104 | ) 105 | ])); 106 | } 107 | 108 | return $code; 109 | } 110 | 111 | protected function optional($code, $id) { 112 | return PHPBuilder::build()->l( 113 | $this->save($id), 114 | $code->replace(['FAIL' => $this->restore($id, \true)]) 115 | ); 116 | } 117 | 118 | protected function zero_or_more($code, $id) { 119 | return PHPBuilder::build()->b( 120 | 'while (\true)', 121 | $this->save($id), 122 | $code->replace([ 123 | 'MATCH' => \null, 124 | 'FAIL' => $this->restore($id, \true)->l('break;') 125 | ]) 126 | )->l('MATCH'); 127 | } 128 | 129 | protected function n_or_more($code, $id, $n) { 130 | 131 | $counterName = '$count' . $id; 132 | return PHPBuilder::build()->l( 133 | $counterName . ' = 0;' 134 | )->b( 135 | 'while (\true)', 136 | $this->save($id), 137 | $code->replace([ 138 | 'MATCH' => \null, 139 | 'FAIL' => $this->restore($id, \true)->l('break;') 140 | ]), 141 | $counterName . '++;' 142 | )->b( 143 | "if ($counterName >= $n)", 144 | 'MATCH' 145 | )->b( 146 | 'else', 147 | 'FAIL' 148 | ); 149 | 150 | } 151 | 152 | protected function n_to_x($code, $id, $min, $max) { 153 | 154 | if (1 === $min && 1 === $max) { 155 | return $code; 156 | } 157 | 158 | $counterName = '$count' . $id; 159 | return PHPBuilder::build()->l( 160 | $counterName . ' = 0;' 161 | )->b( 162 | 'while (' . $counterName . ' < '.$max.')', 163 | $this->save($id), 164 | $code->replace([ 165 | 'MATCH' => \null, 166 | 'FAIL' => $this->restore($id, \true)->l('break;') 167 | ]), 168 | $counterName . '++;' 169 | )->b( 170 | 'if (' . $counterName . ' >= '.$min.')', 171 | 'MATCH' 172 | )->b( 173 | 'else', 174 | 'FAIL' 175 | ); 176 | 177 | } 178 | } 179 | 180 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/Expressionable.php: -------------------------------------------------------------------------------- 1 | expression($result, $stack, \'' . ($matches[1] ?: $matches[2]) . "').'"; 15 | } 16 | 17 | function matchCode($value) { 18 | 19 | $value = \preg_replace_callback( 20 | self::EXPR_REGEX, 21 | [$this, 'expressionReplace'], 22 | $value 23 | ); 24 | 25 | return parent::matchCode($value); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/ExpressionedRecurse.php: -------------------------------------------------------------------------------- 1 | expression($result, $stack, \'' . $value . '\')'; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/Literal.php: -------------------------------------------------------------------------------- 1 | return $value;<': " . $e->getMessage()); 19 | } 20 | 21 | // We inline single-character matches for speed. 22 | if (!$this->containsExpression($value) && \strlen($evald) === 1) { 23 | return $this->matchFailConditional('\substr($this->string, $this->pos, 1) === ' . $value, 24 | PHPBuilder::build()->l( 25 | '$this->addPos(1);', 26 | $this->setText($value) 27 | ) 28 | ); 29 | } 30 | 31 | return parent::matchCode($value); 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/Option.php: -------------------------------------------------------------------------------- 1 | varid(); 17 | $code = PHPBuilder::build()->l($this->save($id)); 18 | 19 | foreach ($value as $opt) { 20 | $code->l( 21 | $opt->compile()->replace([ 22 | 'MATCH' => 'MBREAK', 23 | 'FAIL' => \null 24 | ]), 25 | $this->restore($id) 26 | ); 27 | } 28 | 29 | $code->l('FBREAK'); 30 | return $this->matchFailBlock($code); 31 | 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/Recurse.php: -------------------------------------------------------------------------------- 1 | functionName($value) . "'"; 16 | } 17 | 18 | public function matchCode($value) { 19 | $function = $this->matchFunction($value); 20 | $storetag = $this->functionName( 21 | $this->tag 22 | ? $this->tag 23 | : $this->matchFunction($value) 24 | ); 25 | 26 | if (\hafriedlander\Peg\Compiler::$debug) { 27 | $debugHeader = PHPBuilder::build() 28 | ->l( 29 | '$indent = str_repeat("| ", $this->debugDepth / 2);', 30 | '$this->debugDepth += 2;', 31 | '$sub = ((strlen($this->string) - $this->pos) > 40) ? (substr($this->string, $this->pos, 40) . "...") : substr($this->string, $this->pos);', 32 | '$sub = preg_replace(\'/(\r|\n)+/\', " {NL} ", $sub);', 33 | sprintf('print $indent . "Matching: <%s> in \'".$sub."\' \n";', $function) 34 | ); 35 | 36 | $debugMatch = PHPBuilder::build() 37 | ->l( 38 | 'print $indent . "OK\n";', 39 | '$this->debugDepth -= 2;' 40 | ); 41 | 42 | $debugFail = PHPBuilder::build() 43 | ->l( 44 | 'print $indent . "-\n";', 45 | '$this->debugDepth -= 2;' 46 | ); 47 | } else { 48 | $debugHeader = $debugMatch = $debugFail = \null; 49 | } 50 | 51 | $builder = PHPBuilder::build()->l( 52 | '$key = \'match_\'.'.$function.'; $pos = $this->pos;', 53 | $debugHeader, 54 | '$subres = $this->packhas($key, $pos)' . "\n\t" 55 | . '? $this->packread($key, $pos)' . "\n\t" 56 | . ': $this->packwrite($key, $pos, $this->{$key}(\array_merge($stack, [$result])));', 57 | $this->matchFailConditional( 58 | '$subres !== \false', 59 | PHPBuilder::build()->l( 60 | $debugMatch, 61 | $this->tag === \false ? 62 | '$this->store($result, $subres);' : 63 | '$this->store($result, $subres, "' . $storetag . '");' 64 | ), 65 | PHPBuilder::build()->l( 66 | $debugFail 67 | ) 68 | ) 69 | ); 70 | 71 | return $builder; 72 | 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/Regex.php: -------------------------------------------------------------------------------- 1 | l( 19 | $token->compile()->replace([ 20 | 'MATCH' => \null, 21 | 'FAIL' => 'FBREAK' 22 | ]) 23 | ); 24 | } 25 | 26 | $code->l('MBREAK'); 27 | return $this->matchFailBlock($code); 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/Terminal.php: -------------------------------------------------------------------------------- 1 | silent 11 | ? \null 12 | : '$result["text"] .= ' . $text . ';'; 13 | } 14 | 15 | protected function matchCode($value) { 16 | return $this->matchFailConditional( 17 | '($subres = $this->' . $this->type . '(' . $value . ')) !== \false', 18 | $this->setText('$subres') 19 | ); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/Whitespace.php: -------------------------------------------------------------------------------- 1 | replace(['FAIL' => \null]) : $code; 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Parser/Basic.php: -------------------------------------------------------------------------------- 1 | string = $string; 25 | $this->regexps = []; 26 | } 27 | 28 | public function setPos(int $n): void { 29 | 30 | if ($n > $this->farthestPos) { 31 | $this->farthestRule = $this->currentRule; 32 | $this->farthestPos = $n; 33 | } 34 | 35 | $this->pos = $n; 36 | 37 | } 38 | 39 | public function addPos(int $n): void { 40 | $this->setPos($this->pos + $n); 41 | } 42 | 43 | public function getPos(): int { 44 | return $this->pos; 45 | } 46 | 47 | public function getFarthestPos(): int { 48 | return $this->farthestPos; 49 | } 50 | 51 | public function getFarthestRule(): ?string { 52 | return $this->farthestRule; 53 | } 54 | 55 | public function getString(): string { 56 | return $this->string; 57 | } 58 | 59 | protected function isCallable($name) { 60 | return $this->isCallableCache[$name] 61 | ?? ($this->isCallableCache[$name] = \is_callable([$this, $name])); 62 | } 63 | 64 | protected function whitespace() { 65 | 66 | $matched = \preg_match( 67 | '/[ \t]+/', 68 | $this->string, 69 | $matches, 70 | \PREG_OFFSET_CAPTURE, 71 | $this->pos 72 | ); 73 | 74 | if ($matched && $matches[0][1] === $this->pos) { 75 | $this->addPos(\strlen($matches[0][0])); 76 | return ' '; 77 | } 78 | 79 | return \false; 80 | 81 | } 82 | 83 | protected function literal($token) { 84 | /* Debugging: * / print( "Looking for token '$token' @ '" . substr( $this->string, $this->pos ) . "'\n" ) ; /* */ 85 | $toklen = \strlen($token); 86 | $substr = \substr($this->string, $this->pos, $toklen); 87 | if ($substr === $token) { 88 | $this->addPos($toklen); 89 | return $token; 90 | } 91 | 92 | return \false; 93 | } 94 | 95 | protected function rx($rx) { 96 | $this->regexps[$rx] ??= new CachedRegexp($this, $rx); 97 | return $this->regexps[$rx]->match(); 98 | } 99 | 100 | protected function expression($result, $stack, $value) { 101 | $stack[] = $result; 102 | $rv = \false; 103 | 104 | /* Search backwards through the sub-expression stacks */ 105 | for ($i = \count($stack) - 1; $i >= 0; $i--) { 106 | $node = $stack[$i]; 107 | 108 | if (isset($node[$value])) { 109 | $rv = $node[$value]; 110 | break; 111 | } 112 | 113 | foreach ($this->typestack($node['_matchrule']) as $type) { 114 | if ($this->isCallable($method = "{$type}_DLR{$value}")) { 115 | $rv = $this->{$method}(); 116 | if ($rv !== \false) { 117 | break; 118 | } 119 | } 120 | } 121 | } 122 | 123 | if ($rv === \false) { 124 | $rv = @$this->$value; 125 | } 126 | 127 | if ($rv === \false) { 128 | $rv = @$this->$value(); 129 | } 130 | 131 | return \is_array($rv) ? $rv['text'] : ($rv ?: ''); 132 | } 133 | 134 | public function packhas($key, $pos) { 135 | return \false; 136 | } 137 | 138 | public function packread($key, $pos) { 139 | throw new \Exception('PackRead after PackHas=>\false in Parser.php'); 140 | } 141 | 142 | public function packwrite($key, $pos, $res) { 143 | return $res; 144 | } 145 | 146 | public function typestack($name) { 147 | return $this->{"match_{$name}_typestack"}; 148 | } 149 | 150 | public function construct($matchrule, $name, $arguments = []) { 151 | 152 | $result = [ 153 | '_matchrule' => $matchrule, 154 | 'name' => $name, 155 | 'text' => '', 156 | 'offset' => $this->pos, 157 | ]; 158 | 159 | if ($arguments) { 160 | $result = \array_merge($result, $arguments); 161 | } 162 | 163 | foreach ($this->typestack($matchrule) as $type) { 164 | if ($this->isCallable($method = "{$type}__construct")) { 165 | $this->{$method}(...[&$result]); 166 | break; 167 | } 168 | } 169 | 170 | return $result; 171 | 172 | } 173 | 174 | public function finalise(&$result) { 175 | foreach ($this->typestack($result['_matchrule']) as $type) { 176 | if ($this->isCallable($method = "{$type}__finalise")) { 177 | $this->{$method}(...[&$result]); 178 | break; 179 | } 180 | } 181 | 182 | return $result; 183 | } 184 | 185 | public function store(&$result, $subres, $storetag = \null) { 186 | $result['text'] .= $subres['text']; 187 | $storecalled = \false; 188 | 189 | foreach ($this->typestack($result['_matchrule']) as $type) { 190 | 191 | $method = $storetag 192 | ? "{$type}_{$storetag}" 193 | : "{$type}_{$subres['name']}"; 194 | 195 | if ($this->isCallable($method)) { 196 | $this->{$method}(...[&$result, $subres]); 197 | $storecalled = \true; 198 | break; 199 | } 200 | 201 | $method = "{$type}_STR"; 202 | if ($this->isCallable($method)) { 203 | $this->{$method}(...[&$result, $subres]); 204 | $storecalled = \true; 205 | break; 206 | } 207 | 208 | } 209 | 210 | if ($storetag && !$storecalled) { 211 | if (!isset($result[$storetag])) { 212 | $result[$storetag] = $subres; 213 | } else { 214 | if (isset($result[$storetag]['text'])) { 215 | $result[$storetag] = [$result[$storetag]]; 216 | } 217 | 218 | $result[$storetag][] = $subres; 219 | } 220 | } 221 | 222 | } 223 | 224 | } 225 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Parser/CachedRegexp.php: -------------------------------------------------------------------------------- 1 | rx = $rx . self::DEFAULT_MODIFIERS; 30 | $this->parser = $parser; 31 | 32 | $this->matchPos = \null; // \null is no-match-to-end-of-string, unless checkPos also == \null, in which case means undefined. 33 | $this->checkPos = \null; 34 | 35 | } 36 | 37 | public function match() { 38 | 39 | $currentPos = $this->parser->getPos(); 40 | $dirty = $this->checkPos === \null 41 | || $this->checkPos > $currentPos 42 | || ($this->matchPos !== \null && $this->matchPos < $currentPos); 43 | 44 | if ($dirty) { 45 | 46 | $this->checkPos = $currentPos; 47 | $matched = \preg_match( 48 | $this->rx, 49 | $this->parser->getString(), 50 | $this->matches, 51 | \PREG_OFFSET_CAPTURE, 52 | $this->checkPos 53 | ); 54 | 55 | $this->matchPos = $matched 56 | ? $this->matches[0][1] 57 | : \null; 58 | 59 | } 60 | 61 | if ($this->matchPos !== $currentPos) { 62 | return \false; 63 | } 64 | 65 | $this->parser->addPos(\strlen($this->matches[0][0])); 66 | return $this->matches[0][0]; 67 | 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Parser/Packrat.php: -------------------------------------------------------------------------------- 1 | packres[$key][$pos]); 26 | } 27 | 28 | function packread($key, $pos) { 29 | 30 | if (!isset($this->packres[$key][$pos])) { 31 | return \false; 32 | } 33 | 34 | $this->setPos($this->packpos[$key][$pos]); 35 | return $this->packres[$key][$pos]; 36 | 37 | } 38 | 39 | function packwrite($key, $pos, $result) { 40 | 41 | if ($result !== \false) { 42 | $this->packres[$key][$pos] = $result; 43 | $this->packpos[$key][$pos] = $this->pos; 44 | } else { 45 | $this->packres[$key][$pos] = \false; 46 | } 47 | 48 | return $result; 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /phpstan.neon: -------------------------------------------------------------------------------- 1 | parameters: 2 | level: 5 3 | paths: 4 | - ./lib 5 | - ./tests 6 | -------------------------------------------------------------------------------- /tests/CachedRegexp.phpt: -------------------------------------------------------------------------------- 1 | match()); 20 | 21 | $rx = "/[xyz]{3}/"; 22 | $r = new CachedRegexp($fakeParser, $rx); 23 | 24 | // If regex matches the 'string' at the 'pos', the match() method returns the matched string. 25 | Assert::same('xyz', $r->match()); 26 | -------------------------------------------------------------------------------- /tests/ParserInheritance.phpt: -------------------------------------------------------------------------------- 1 | buildParser(' 14 | /*!* BasicInheritanceTestParser 15 | Foo: "a" 16 | Bar extends Foo 17 | */ 18 | '); 19 | 20 | Assert::true($parser->matches('Foo', 'a')); 21 | Assert::true($parser->matches('Bar', 'a')); 22 | 23 | Assert::false($parser->matches('Foo', 'b')); 24 | Assert::false($parser->matches('Bar', 'b')); 25 | } 26 | 27 | 28 | public function testBasicInheritanceConstructFallback() { 29 | 30 | $parser = $this->buildParser(' 31 | /*!* BasicInheritanceConstructFallbackParser 32 | Foo: "a" 33 | function __construct(&$res){ $res["test"] = "test"; } 34 | Bar extends Foo 35 | */ 36 | '); 37 | 38 | $res = $parser->match('Foo', 'a'); 39 | Assert::same($res['test'], 'test'); 40 | 41 | $res = $parser->match('Bar', 'a'); 42 | Assert::same($res['test'], 'test'); 43 | 44 | $parser = $this->buildParser(' 45 | /*!* BasicInheritanceConstructFallbackParser2 46 | Foo: "a" 47 | function __construct(&$res){ $res["testa"] = "testa"; } 48 | Bar extends Foo 49 | function __construct(&$res){ $res["testb"] = "testb"; } 50 | */ 51 | '); 52 | 53 | $res = $parser->match('Foo', 'a'); 54 | Assert::hasKey('testa', $res); 55 | Assert::same($res['testa'], 'testa'); 56 | Assert::hasNotKey('testb', $res); 57 | 58 | $res = $parser->match('Bar', 'a'); 59 | Assert::hasKey('testb', $res); 60 | Assert::same($res['testb'], 'testb'); 61 | Assert::hasNotKey('testa', $res); 62 | 63 | } 64 | 65 | public function testBasicInheritanceStoreFallback() { 66 | 67 | $parser = $this->buildParser(' 68 | /*!* BasicInheritanceStoreFallbackParser 69 | Foo: Pow:"a" 70 | function *(&$res, $sub){ $res["test"] = "test"; } 71 | Bar extends Foo 72 | */ 73 | '); 74 | 75 | $res = $parser->match('Foo', 'a'); 76 | Assert::same($res['test'], 'test'); 77 | 78 | $res = $parser->match('Bar', 'a'); 79 | Assert::same($res['test'], 'test'); 80 | 81 | $parser = $this->buildParser(' 82 | /*!* BasicInheritanceStoreFallbackParser2 83 | Foo: Pow:"a" Zap:"b" 84 | function *(&$res, $sub){ $res["testa"] = "testa"; } 85 | Bar extends Foo 86 | function *(&$res, $sub){ $res["testb"] = "testb"; } 87 | Baz extends Foo 88 | function Zap(&$res, $sub){ $res["testc"] = "testc"; } 89 | */ 90 | '); 91 | 92 | $res = $parser->match('Foo', 'ab'); 93 | Assert::hasKey('testa', $res); 94 | Assert::same($res['testa'], 'testa'); 95 | Assert::hasNotKey('testb', $res); 96 | 97 | $res = $parser->match('Bar', 'ab'); 98 | Assert::hasKey('testb', $res); 99 | Assert::same($res['testb'], 'testb'); 100 | Assert::hasNotKey('testa', $res); 101 | 102 | $res = $parser->match('Baz', 'ab'); 103 | Assert::hasKey('testa', $res); 104 | Assert::same($res['testa'], 'testa'); 105 | Assert::hasKey('testc', $res); 106 | Assert::same($res['testc'], 'testc'); 107 | Assert::hasNotKey('testb', $res); 108 | } 109 | 110 | public function testInheritanceByReplacement() { 111 | 112 | $parser = $this->buildParser(' 113 | /*!* InheritanceByReplacementParser 114 | A: "a" 115 | B: "b" 116 | Foo: A B 117 | Bar extends Foo; B => A 118 | Baz extends Foo; A => "" 119 | */ 120 | '); 121 | 122 | $parser->assertMatches('Foo', 'ab'); 123 | $parser->assertMatches('Bar', 'aa'); 124 | $parser->assertMatches('Baz', 'b'); 125 | 126 | } 127 | 128 | } 129 | 130 | (new ParserInheritanceTest)->run(); 131 | -------------------------------------------------------------------------------- /tests/ParserPackrat.phpt: -------------------------------------------------------------------------------- 1 | buildParser(' 14 | /*!* 15 | String: /("(.|\n)*?"|\'(.|\n)*?\')/ 16 | Number: /-?\d+(\.\d+)?/ 17 | Bool: "true" | "false" 18 | Regex: "/" /(\\\/|[^\/])+/ "/" 19 | 20 | Literal: Number | String | Bool | Regex 21 | AddOperator: "+" | "-" 22 | MultiplyOperator: "*" | "/" 23 | 24 | Add: operands:Factor ( > ops:AddOperator > operands:Factor)* 25 | Factor: operands:Literal ( > ops:MultiplyOperator > operands:Literal)* 26 | 27 | Expression: Add 28 | */ 29 | ', Packrat::class); 30 | 31 | $parser->assertMatches('Expression', '1 + 2 * 3 + 4 + 4 + 4 + 4 + 4 / 5 - 6 + 7 * 8 - 9'); 32 | $parser->assertDoesntMatch('Expression', 'variables + do + not + exist'); 33 | 34 | } 35 | 36 | } 37 | 38 | (new ParserPackratTest)->run(); 39 | -------------------------------------------------------------------------------- /tests/ParserSyntax.phpt: -------------------------------------------------------------------------------- 1 | buildParser(' 12 | /*!* BasicRuleSyntax 13 | Foo: "a" "b" 14 | Bar: "a" 15 | "b" 16 | Baz: 17 | "a" "b" 18 | Qux: 19 | "a" 20 | "b" 21 | Quux: "a" 22 | */ 23 | '); 24 | 25 | $parser->assertMatches('Foo', 'ab'); 26 | $parser->assertMatches('Bar', 'ab'); 27 | $parser->assertMatches('Baz', 'ab'); 28 | $parser->assertMatches('Qux', 'ab'); 29 | $parser->assertMatches('Quux', 'a'); 30 | 31 | } 32 | 33 | public function testRuleNamesCanContainHyphens() { 34 | 35 | $parser = $this->buildParser(' 36 | /*!* RuleNamesCanContainHyphens 37 | Foo-one: "a" "b" 38 | Foo-two: "b" "a" 39 | */ 40 | '); 41 | 42 | $parser->assertMatches('Foo-one', 'ab'); 43 | $parser->assertMatches('Foo-two', 'ba'); 44 | 45 | } 46 | 47 | public function testComplexRulesCanStartWithARegex() { 48 | 49 | $parser = $this->buildParser(' 50 | /*!* ComplexRulesCanStartWithARegex 51 | Foo: /foo/ "bar" 52 | */ 53 | '); 54 | 55 | $parser->assertDoesntMatch('Foo', 'foo'); 56 | $parser->assertMatches('Foo', 'foobar'); 57 | 58 | } 59 | } 60 | 61 | (new ParserSyntaxTest)->run(); 62 | -------------------------------------------------------------------------------- /tests/ParserVariables.phpt: -------------------------------------------------------------------------------- 1 | buildParser(' 12 | /*!* BasicVariables 13 | Foo: Letter:"a" "$Letter" 14 | Bar: Letter:"b" "$Letter $Letter" 15 | Baz: Letter:"c" "$Letter a $Letter a" 16 | Qux: Letter:"d" "{$Letter}a{$Letter}a" 17 | */ 18 | '); 19 | 20 | $parser->assertMatches('Foo', 'aa'); 21 | $parser->assertMatches('Bar', 'bb b'); 22 | $parser->assertMatches('Baz', 'cc a c a'); 23 | $parser->assertMatches('Qux', 'ddada'); 24 | 25 | } 26 | 27 | public function testRecurseOnVariables() { 28 | 29 | $parser = $this->buildParser(' 30 | /*!* RecurseOnVariablesParser 31 | A: "a" 32 | B: "b" 33 | Foo: $Template 34 | Bar: Foo 35 | function __construct(&$res){ $res["Template"] = "A"; } 36 | Baz: Foo 37 | function __construct(&$res){ $res["Template"] = "B"; } 38 | */ 39 | '); 40 | 41 | $parser->assertMatches('Bar', 'a'); 42 | $parser->assertDoesntMatch('Bar', 'b'); 43 | $parser->assertMatches('Baz', 'b'); 44 | $parser->assertDoesntMatch('Baz', 'a'); 45 | 46 | } 47 | 48 | public function testSetOnRuleVariables() { 49 | 50 | $parser = $this->buildParser(' 51 | /*!* SetOnRuleVariablesParser 52 | A: "a" 53 | B: "b" 54 | Foo: $Template 55 | Bar (Template = A): Foo 56 | Baz (Template = B): Foo 57 | */ 58 | '); 59 | 60 | $parser->assertMatches('Bar', 'a'); 61 | $parser->assertMatches('Baz', 'b'); 62 | 63 | } 64 | 65 | } 66 | 67 | (new ParserVariablesTest)->run(); 68 | -------------------------------------------------------------------------------- /tests/bootstrap.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | private string $parserClass; 17 | 18 | function __construct(string $parserClass) { 19 | $this->parserClass = $parserClass; 20 | } 21 | 22 | function functionName($str): string { 23 | $str = preg_replace('/-/', '_', $str); 24 | $str = preg_replace('/\$/', 'DLR', $str); 25 | $str = preg_replace('/\*/', 'STR', $str); 26 | $str = preg_replace('/[^\w]+/', '', $str); 27 | return $str; 28 | } 29 | 30 | function match($method, $string, $allowPartial = false) { 31 | 32 | $class = $this->parserClass; 33 | $func = $this->functionName('match_' . $method); 34 | 35 | $parser = new $class($string); 36 | $res = $parser->$func(); 37 | 38 | return ($allowPartial || $parser->getPos() === strlen($string)) 39 | ? $res 40 | : false; 41 | 42 | } 43 | 44 | function matches($method, $string, $allowPartial = false) { 45 | return $this->match($method, $string, $allowPartial) !== false; 46 | } 47 | 48 | function assertMatches($method, $string, $message = null) { 49 | Assert::true( 50 | $this->matches($method, $string), 51 | $message 52 | ? $message 53 | : "Assert parser method $method matches string $string" 54 | ); 55 | } 56 | 57 | function assertDoesntMatch($method, $string, $message = null) { 58 | Assert::false( 59 | $this->matches($method, $string), 60 | $message 61 | ? $message 62 | : "Assert parser method $method doesn't match string $string" 63 | ); 64 | } 65 | 66 | } 67 | 68 | class ParserTestBase extends TestCase { 69 | 70 | function buildParser( 71 | string $grammar, 72 | string $baseClass = Basic::class, 73 | ): ParserTestWrapper { 74 | 75 | $class = 'Parser_' . md5(uniqid()); 76 | eval(Peg\Compiler::compile(" 77 | class $class extends $baseClass { 78 | $grammar 79 | } 80 | ")); 81 | 82 | return new ParserTestWrapper($class); 83 | 84 | } 85 | 86 | } 87 | --------------------------------------------------------------------------------