├── LICENSE ├── README.md ├── autoloader.php ├── cli.php ├── composer.json ├── 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 │ │ ├── ConservativePackrat.php │ │ ├── FalseOnlyPackrat.php │ │ └── Packrat.php └── vendor │ └── SplClassLoader.php └── tests ├── ParserInheritanceTest.php ├── ParserSyntaxTest.php ├── ParserTestBase.php └── ParserVariablesTest.php /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 | # PHP PEG - A PEG compiler for parsing text in PHP 2 | 3 | This is a Parsing Expression Grammar compiler for PHP. PEG parsers are an alternative to other CFG grammars that includes both tokenization 4 | and lexing in a single top down grammar. For a basic overview of the subject, see http://en.wikipedia.org/wiki/Parsing_expression_grammar 5 | 6 | ## Quick start 7 | 8 | - Write a parser. A parser is a PHP class with a grammar contained within it in a special syntax. The filetype is .peg.inc. See the examples directory. 9 | - Compile the parser: `php ./cli.php ExampleParser.peg.inc > ExampleParser.php` 10 | - Use the parser (you can also include code to do this in the input parser - again see the examples directory): 11 | 12 | 13 | ``` 14 | $x = new ExampleParser( 'string to parse' ) ; 15 | $res = $x->match_Expr() ; 16 | ``` 17 | 18 | ### Parser Format 19 | 20 | Parsers are contained within a PHP file, in one or more special comment blocks that start with `/*!* [name | !pragma]` (like a docblock, but with an 21 | exclamation mark in the middle of the stars). 22 | 23 | You can have multiple comment blocks, all of which are treated as contiguous for the purpose of compiling. During compilation these blocks will be replaced 24 | with a set of "matching" functions (functions which match a string against their rules) for each rule in the block. 25 | 26 | The optional name marks the start of a new set of parser rules. This is currently unused, but might be used in future for optimization & debugging purposes. 27 | If unspecified, it defaults to the same name as the previous parser comment block, or 'Anonymous Parser' if no name has ever been set. 28 | 29 | If the name starts with an '!' symbol, that comment block is a pragma, and is treated not as some part of the parser, but as a special block of meta-data. 30 | 31 | Lexically, these blocks are a set of rules & comments. A rule can be a base rule or an extension rule. 32 | 33 | ##### Base rules 34 | 35 | Base rules consist of a name for the rule, some optional arguments, the matching rule itself, and an optional set of attached functions. 36 | 37 | NAME ( "(" ARGUMENT, ... ")" )? ":" MATCHING_RULE 38 | ATTACHED_FUNCTIONS? 39 | 40 | Names must be the characters a-z, A-Z, 0-9 and _ and - only, and must not start with a number. 41 | 42 | Base rules can be split over multiple lines as long as subsequent lines are indented. 43 | 44 | ##### Extension rules 45 | 46 | Extension rules are either the same as a base rule but with an addition name of the rule to extend, or as a replacing extension consist of 47 | a name for the rule, the name of the rule to extend, and optionally: some arguments, some replacements, and a set of attached functions. 48 | 49 | NAME extend BASENAME ( "(" ARGUMENT, ... ")" )? ":" MATCHING_RULE 50 | ATTACHED_FUNCTIONS? 51 | 52 | NAME extends BASENAME ( "(" ARGUMENT, ... ")" )? ( ";" REPLACE "=>" REPLACE_WITH, ... )? 53 | ATTACHED_FUNCTIONS? 54 | 55 | ##### Tricks and traps 56 | 57 | We allow indenting a parser block, but only in a consistent manner - whatever the indent of the /*** marker becomes the "base" indent, and needs to be used 58 | for all lines. You can mix tabs and spaces, but the indent must always be an exact match - if the "base" indent is a tab then two spaces, every line within the 59 | block also needs indenting with a tab then two spaces, not two tabs (even if in your editor, that gives the same indent). 60 | 61 | Any line with more than the "base" indent is considered a continuation of the previous rule. 62 | 63 | Any line with less than the "base" indent is an error. 64 | 65 | This might get looser if I get around to re-writing the internal "parser parser" in php-peg, bootstrapping the whole thing. 66 | 67 | ### Rules 68 | 69 | PEG matching rules try to follow standard PEG format, summarised thusly: 70 | 71 | token* - Token is optionally repeated 72 | token+ - Token is repeated at least one 73 | token? - Token is optionally present 74 | 75 | tokena tokenb - Token tokenb follows tokena, both of which are present 76 | tokena | tokenb - One of tokena or tokenb are present, preferring tokena 77 | 78 | &token - Token is present next (but not consumed by parse) 79 | !token - Token is not present next (but not consumed by parse) 80 | 81 | ( expression ) - Grouping for priority 82 | 83 | But with these extensions: 84 | 85 | < or > - Optionally match whitespace 86 | [ or ] - Require some whitespace 87 | 88 | ### Tokens 89 | 90 | Tokens may be: 91 | 92 | - bare-words, which are recursive matchers - references to token rules defined elsewhere in the grammar, 93 | - literals, surrounded by `"` or `'` quote pairs. No escaping support is provided in literals. 94 | - regexes, surrounded by `/` pairs. 95 | - expressions - single words (match \w+) starting with `$` or more complex surrounded by `${ }` which call a user defined function to perform the match 96 | 97 | ##### Regular expression tokens 98 | 99 | Automatically anchored to the current string start - do not include a string start anchor (`^`) anywhere. Always acts as when the 'x' flag is enabled in PHP - 100 | whitespace is ignored unless escaped, and '#' starts a comment. 101 | 102 | Be careful when ending a regular expression token - the '*/' pattern (as in /foo\s*/) will end a PHP comment. Since the 'x' flag is always active, 103 | just split with a space (as in / foo \s* /). 104 | 105 | ### Expressions 106 | 107 | Expressions allow run-time calculated matching. You can embed an expression within a literal or regex token to 108 | match against a calculated value, or simply specify the expression as a token to match against a dynamic rule. 109 | 110 | #### Expression stack 111 | 112 | When getting a value to use for an expression, the parser will travel up the stack looking for a set value. The expression 113 | stack is a list of all the rules passed through to get to this point. For example, given the parser: 114 | 115 | ``` 116 | A: $a 117 | B: A 118 | C: B 119 | ``` 120 | 121 | The expression stack for finding $a will be C, B, A - in other words, the A rule will be checked first, followed by B, followed by C. 122 | 123 | #### In terminals (literals and regexes) 124 | 125 | The token will be replaced by the looked up value. To find the value for the token, the expression stack will be 126 | travelled up checking for one of the following: 127 | 128 | - A key / value pair in the result array node 129 | - A rule-attached method INCLUDING `$` ( i.e. `function $foo()` ) 130 | 131 | If no value is found it will then check if a method or a property excluding the $ exists on the parser. If neither of those is found 132 | the expression will be replaced with an empty string. 133 | 134 | #### As tokens 135 | 136 | The token will be looked up to find a value, which must be the name of a matching rule. That rule will then be matched 137 | against as if the token was a recurse token for that rule. 138 | 139 | To find the name of the rule to match against, the expression stack will be travelled up checking for one of the following: 140 | 141 | - A key / value pair in the result array node 142 | - A rule-attached method INCLUDING `$` ( i.e. `function $foo()` ) 143 | 144 | If no value is found it will then check if a method or a property excluding the $ exists on the parser. If neither of those is found 145 | the rule will fail to match. 146 | 147 | #### Tricks and traps 148 | 149 | Be careful against using a token expression when you meant to use a terminal expression, for example: 150 | 151 | ``` 152 | quoted_good: q:/['"]/ string "$q" 153 | quoted_bad: q:/['"]/ string $q 154 | ``` 155 | 156 | `"$q"` matches against the value of q again. `$q` tries to match against a rule named `"` or `'` (both of which are illegal rule 157 | names, and will therefore fail) 158 | 159 | ### Named matching rules 160 | 161 | Tokens and groups can be given names by prepending name and `:`, e.g., 162 | 163 | ``` 164 | rulea: "'" name:( tokena tokenb )* "'" 165 | ``` 166 | 167 | There must be no space between the name and the `:` 168 | 169 | ``` 170 | badrule: "'" name : ( tokena tokenb )* "'" 171 | ``` 172 | 173 | Recursive matchers can be given a name the same as their rule name by prepending with just a `:`. These next two rules are equivalent: 174 | 175 | ``` 176 | rulea: tokena tokenb:tokenb 177 | rulea: tokena :tokenb 178 | ``` 179 | 180 | ### Rule-attached functions 181 | 182 | Each rule can have a set of functions attached to it. These functions can be defined: 183 | 184 | - in-grammar by indenting the function body after the rule 185 | - in-class after close of grammar comment by defining a regular method who's name is `{$rulename}_{$functionname}`, or `{$rulename}{$functionname}` if function name starts with `_` 186 | - in a sub class 187 | 188 | All functions that are not in-grammar must have PHP compatible names (see PHP name mapping). In-grammar functions will have their names converted if needed. 189 | 190 | All these definitions define the same rule-attached function: 191 | 192 | ```php 193 | 207 | ``` 208 | 209 | ### PHP name mapping 210 | 211 | Rules in the grammar map to php functions named `match_{$rulename}`. However rule names can contain characters that php functions can't. 212 | These characters are remapped: 213 | 214 | ``` 215 | '-' => '_' 216 | '$' => 'DLR' 217 | '*' => 'STR' 218 | ``` 219 | 220 | Other dis-allowed characters are removed. 221 | 222 | ## Results 223 | 224 | Results are a tree of nested arrays. 225 | 226 | Without any specific control, each rules result will just be the text it matched against in a `['text']` member. This member must always exist. 227 | 228 | Marking a subexpression, literal, regex or recursive match with a name (see Named matching rules) will insert a member into the 229 | result array named that name. If there is only one match it will be a single result array. If there is more than one match it will be an array of arrays. 230 | 231 | You can override result storing by specifying a rule-attached function with the given name. It will be called with a reference to the current result array 232 | and the sub-match - in this case the default storage action will not occur. 233 | 234 | If you specify a rule-attached function for a recursive match, you do not need to name that token at all - it will be called automatically, e.g. 235 | 236 | ``` 237 | rulea: tokena tokenb 238 | function tokenb ( &$res, $sub ) { print 'Will be called, even though tokenb is not named or marked with a :' ; } 239 | ``` 240 | 241 | You can also specify a rule-attached function called `*`, which will be called with every recursive match made: 242 | 243 | ``` 244 | rulea: tokena tokenb 245 | function * ( &$res, $sub ) { print 'Will be called for both tokena and tokenb' ; } 246 | ``` 247 | 248 | ### Silent matches 249 | 250 | By default all matches are added to the 'text' property of a result. By prepending a member with `.` that match will not be added to the ['text'] member. This 251 | doesn't affect the other result properties that named rules' add. 252 | 253 | ### Inheritance 254 | 255 | Rules can inherit off other rules using the keyword extends. There are several ways to change the matching of the rule, but 256 | they all share a common feature - when building a result set the rule will also check the inherited-from rule's rule-attached 257 | functions for storage handlers. This lets you do something like: 258 | 259 | ``` 260 | A: Foo Bar Baz 261 | function *(){ /* Generic store handler */ } 262 | 263 | B extends A 264 | function Bar(){ /* Custom handling for Bar - Foo and Baz will still fall through to the A#* function defined above */ } 265 | ``` 266 | 267 | The actual matching rule can be specified in three ways: 268 | 269 | #### Duplication 270 | 271 | If you don't specify a new rule or a replacement set the matching rule is copied as is. This is useful when you want to 272 | override some storage logic but not the rule itself. 273 | 274 | #### Text replacement 275 | 276 | You can replace some parts of the inherited rule using test replacement by using a ';' instead of an ':' after the name 277 | of the extended rule. You can then put replacements in a comma separated list. An example might help: 278 | 279 | ``` 280 | A: Foo | Bar | Baz 281 | 282 | # Makes B the equivalent of Foo | Bar | (Baz | Qux) 283 | B extends A: Baz => (Baz | Qux) 284 | ``` 285 | 286 | Note that the replacements are not quoted. The exception is when you want to replace with the empty string, e.g. 287 | 288 | ``` 289 | A: Foo | Bar | Baz 290 | 291 | # Makes B the equivalent of Foo | Bar 292 | B extends A: | Baz => "" 293 | ``` 294 | 295 | Currently there is no escaping supported - if you want to replace "," or "=>" characters you'll have to use full replacement. 296 | 297 | #### Full replacement 298 | 299 | You can specify an entirely new rule in the same format as a non-inheriting rule, e.g. 300 | 301 | ``` 302 | A: Foo | Bar | Baz 303 | 304 | B extends A: Foo | Bar | (Baz Qux) 305 | ``` 306 | 307 | This is useful is the rule changes too much for text replacement to be readable, but want to keep the storage logic. 308 | 309 | ### Pragmas 310 | 311 | When opening a parser comment block, if instead of a name (or no name) you put a word starting with '!', that comment block is treated as a pragma - not 312 | part of the parser language itself, but some other instruction to the compiler. These pragmas are currently understood: 313 | 314 | ``` 315 | !silent 316 | 317 | This is a comment that should only appear in the source code. Don't output it in the generated code. 318 | 319 | !insert_autogen_warning 320 | 321 | Insert a warning comment into the generated code at this point, warning that the file is autogenerated and not to edit it. 322 | ``` 323 | 324 | ## TODO 325 | 326 | - Allow configuration of whitespace - specify what matches, and whether it should be injected into results as-is, collapsed, or not at all 327 | - Allow inline-ing of rules into other rules for speed 328 | - More optimisation 329 | - Make Parser-parser be self-generated, instead of a bad hand rolled parser like it is now. 330 | - PHP token parser, and other token streams, instead of strings only like now 331 | -------------------------------------------------------------------------------- /autoloader.php: -------------------------------------------------------------------------------- 1 | register(); 7 | -------------------------------------------------------------------------------- /cli.php: -------------------------------------------------------------------------------- 1 | =5.3.0" 17 | }, 18 | "version" : "2.0.0", 19 | "bin": ["cli.php"] 20 | } -------------------------------------------------------------------------------- /examples/CalculatedLiterals.peg.inc: -------------------------------------------------------------------------------- 1 | '}', '[' => ']', '(' => ')', '<' => '>' ) ; 17 | return $a[$res['q']] ; 18 | } 19 | 20 | freequote-unmatched: "qq" q:/./ string '$q' 21 | 22 | quoted-string: freequote-matched | freequote-unmatched | simplequote 23 | 24 | */ 25 | 26 | } 27 | -------------------------------------------------------------------------------- /examples/Calculator.peg.inc: -------------------------------------------------------------------------------- 1 | | '(' > Expr > ')' > 12 | function Number( &$result, $sub ) { 13 | $result['val'] = $sub['text'] ; 14 | } 15 | function Expr( &$result, $sub ) { 16 | $result['val'] = $sub['val'] ; 17 | } 18 | 19 | Times: '*' > operand:Value > 20 | Div: '/' > operand:Value > 21 | Product: Value > ( Times | Div ) * 22 | function Value( &$result, $sub ) { 23 | $result['val'] = $sub['val'] ; 24 | } 25 | function Times( &$result, $sub ) { 26 | $result['val'] *= $sub['operand']['val'] ; 27 | } 28 | function Div( &$result, $sub ) { 29 | $result['val'] /= $sub['operand']['val'] ; 30 | } 31 | 32 | Plus: '+' > operand:Product > 33 | Minus: '-' > operand:Product > 34 | Sum: Product > ( Plus | Minus ) * 35 | function Product( &$result, $sub ) { 36 | $result['val'] = $sub['val'] ; 37 | } 38 | function Plus( &$result, $sub ) { 39 | $result['val'] += $sub['operand']['val'] ; 40 | } 41 | function Minus( &$result, $sub ) { 42 | $result['val'] -= $sub['operand']['val'] ; 43 | } 44 | 45 | Expr: Sum 46 | function Sum( &$result, $sub ) { 47 | $result['val'] = $sub['val'] ; 48 | } 49 | 50 | */ 51 | 52 | } 53 | 54 | $x = new Calculator( '(2 + 4) * 3 - 10' ) ; 55 | $res = $x->match_Expr() ; 56 | if ( $res === FALSE ) { 57 | print "No Match\n" ; 58 | } 59 | else { 60 | print_r( $res ) ; 61 | } 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /examples/EqualRepeat.peg.inc: -------------------------------------------------------------------------------- 1 | match_X() ; 25 | print "$str\n" ; 26 | print $r ? print_r( $r, true ) : 'No Match' ; 27 | print "\n\n" ; 28 | } 29 | 30 | match( 'aabbcc' ) ; // Should match 31 | match( 'aaabbbccc' ) ; // Should match 32 | 33 | match( 'aabbbccc' ) ; // Should not match 34 | match( 'aaabbccc' ) ; // Should not match 35 | match( 'aaabbbcc' ) ; // Should not match 36 | 37 | match( 'aaabbbcccc' ) ; // Should not match 38 | -------------------------------------------------------------------------------- /examples/Rfc822.peg.inc: -------------------------------------------------------------------------------- 1 | @,;:\\".\[\]\x80-\xFF]+/ 21 | 22 | qtext-chars: /[^"\\\x0D]+/ 23 | 24 | qtext: linear-white-space | qtext-chars 25 | 26 | quoted-pair: /\\[\x00-\x7F]/ 27 | 28 | quoted-string: .'"' ( quoted-pair | qtext )* .'"' 29 | 30 | word: atom | quoted-string 31 | 32 | phrase: (word >)+ 33 | 34 | dtext-chars: /[^\[\]\\\r]+/ 35 | 36 | dtext: linear-white-space | dtext-chars 37 | 38 | domain-literal: "[" ( dtext | quoted-pair )* "]" 39 | 40 | domain-ref: atom 41 | 42 | sub-domain: domain-ref | domain-literal 43 | 44 | domain: sub-domain ("." sub-domain)* 45 | 46 | route: "@" domain ("," "@" domain)* ":" 47 | 48 | route-addr: "<" route? addr-spec ">" 49 | function addr_spec ( &$self, $sub ) { 50 | $self['addr_spec'] = $sub['text'] ; 51 | } 52 | 53 | local-part: word ("." word)* 54 | 55 | addr-spec: local-part "@" domain 56 | 57 | mailbox: ( addr-spec | phrase route-addr ) > 58 | function __construct( &$self ) { 59 | $self['phrase'] = NULL ; 60 | $self['address'] = NULL ; 61 | } 62 | function phrase ( &$self, $sub ) { 63 | $self['phrase'] = $sub['text'] ; 64 | } 65 | function addr_spec ( &$self, $sub ) { 66 | $self['address'] = $sub['text'] ; 67 | } 68 | function route_addr ( &$self, $sub ) { 69 | $self['address'] = $sub['addr_spec'] ; 70 | } 71 | 72 | group: phrase ":" ( mailbox ("," mailbox)* )? ";" 73 | 74 | address: :mailbox | group 75 | 76 | address-header: address (<","> address)* 77 | function __construct( &$self ) { 78 | $self['addresses'] = array() ; 79 | } 80 | function address( &$self, $sub ) { 81 | $self['addresses'][] = $sub['mailbox'] ; 82 | } 83 | 84 | */ 85 | 86 | } 87 | 88 | $p = new Rfc822( 'John Byorgson , "Akira \"Bad Boy\" Kenada" ' ) ; 89 | print_r( $p->match_address_header() ) ; 90 | -------------------------------------------------------------------------------- /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[3]); 45 | } 46 | 47 | static function compile( $string ) { 48 | static $rx = '@ 49 | ^([\x20\t]*)/\*!\* (?:[\x20\t]*(!?\w*))? # Start with some indent, a comment with the special marker, then an optional name 50 | ((?:[^*]|\*[^/])*) # Any amount of "a character that isnt a star, or a star not followed by a / 51 | \*/ # The comment end 52 | @mx'; 53 | 54 | return preg_replace_callback( $rx, array( __CLASS__, 'create_parser' ), $string ) ; 55 | } 56 | 57 | static function cli( $args ) { 58 | if ( count( $args ) == 1 ) { 59 | print "Parser Compiler: A compiler for PEG parsers in PHP \n" ; 60 | print "(C) 2009 SilverStripe. See COPYING for redistribution rights. \n" ; 61 | print "\n" ; 62 | print "Usage: {$args[0]} infile [ outfile ]\n" ; 63 | print "\n" ; 64 | } 65 | else { 66 | $fname = ( $args[1] == '-' ? 'php://stdin' : $args[1] ) ; 67 | $string = file_get_contents( $fname ) ; 68 | $string = self::compile( $string ) ; 69 | 70 | if ( !empty( $args[2] ) && $args[2] != '-' ) { 71 | file_put_contents( $args[2], $string ) ; 72 | } 73 | else { 74 | print $string ; 75 | } 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/PHPBuilder.php: -------------------------------------------------------------------------------- 1 | lines = array() ; 13 | } 14 | 15 | function l() { 16 | foreach ( func_get_args() as $lines ) { 17 | if ( !$lines ) continue ; 18 | 19 | if ( is_string( $lines ) ) $lines = preg_split( '/\r\n|\r|\n/', $lines ) ; 20 | if ( !$lines ) continue ; 21 | 22 | if ( $lines instanceof PHPBuilder ) $lines = $lines->lines ; 23 | else $lines = array_map( 'ltrim', $lines ) ; 24 | if ( !$lines ) continue ; 25 | 26 | $this->lines = array_merge( $this->lines, $lines ) ; 27 | } 28 | return $this ; 29 | } 30 | 31 | function b() { 32 | $args = func_get_args() ; 33 | $entry = array_shift( $args ) ; 34 | 35 | $block = new PHPBuilder() ; 36 | call_user_func_array( array( $block, 'l' ), $args ) ; 37 | 38 | $this->lines[] = array( $entry, $block->lines ) ; 39 | 40 | return $this ; 41 | } 42 | 43 | function replace( $replacements, &$array = NULL ) { 44 | if ( $array === NULL ) { 45 | unset( $array ) ; 46 | $array =& $this->lines ; 47 | } 48 | 49 | $i = 0 ; 50 | while ( $i < count( $array ) ) { 51 | 52 | /* Recurse into blocks */ 53 | if ( is_array( $array[$i] ) ) { 54 | $this->replace( $replacements, $array[$i][1] ) ; 55 | 56 | if ( count( $array[$i][1] ) == 0 ) { 57 | $nextelse = isset( $array[$i+1] ) && is_array( $array[$i+1] ) && preg_match( '/^\s*else\s*$/i', $array[$i+1][0] ) ; 58 | 59 | $delete = preg_match( '/^\s*else\s*$/i', $array[$i][0] ) ; 60 | $delete = $delete || ( preg_match( '/^\s*if\s*\(/i', $array[$i][0] ) && !$nextelse ) ; 61 | 62 | if ( $delete ) { 63 | // Is this always safe? Not if the expression has side-effects. 64 | // print "/* REMOVING EMPTY BLOCK: " . $array[$i][0] . "*/\n" ; 65 | array_splice( $array, $i, 1 ) ; 66 | continue ; 67 | } 68 | } 69 | } 70 | 71 | /* Handle replacing lines with NULL to remove, or string, array of strings or PHPBuilder to replace */ 72 | else { 73 | if ( array_key_exists( $array[$i], $replacements ) ) { 74 | $rep = $replacements[$array[$i]] ; 75 | 76 | if ( $rep === NULL ) { 77 | array_splice( $array, $i, 1 ) ; 78 | continue ; 79 | } 80 | 81 | if ( is_string( $rep ) ) { 82 | $array[$i] = $rep ; 83 | $i++ ; 84 | continue ; 85 | } 86 | 87 | if ( $rep instanceof PHPBuilder ) $rep = $rep->lines ; 88 | 89 | if ( is_array( $rep ) ) { 90 | array_splice( $array, $i, 1, $rep ) ; $i += count( $rep ) + 1 ; 91 | continue ; 92 | } 93 | 94 | throw new \Exception('Unknown type passed to PHPBuilder#replace') ; 95 | } 96 | } 97 | 98 | $i++ ; 99 | } 100 | 101 | return $this ; 102 | } 103 | 104 | function render( $array = NULL, $indent = "" ) { 105 | if ( $array === NULL ) $array = $this->lines ; 106 | 107 | $out = array() ; 108 | foreach( $array as $line ) { 109 | if ( is_array( $line ) ) { 110 | list( $entry, $block ) = $line ; 111 | $str = $this->render( $block, $indent . "\t" ) ; 112 | 113 | if ( strlen( $str ) < 40 ) { 114 | $out[] = $indent . $entry . ' { ' . ltrim( $str ) . ' }' ; 115 | } 116 | else { 117 | $out[] = $indent . $entry . ' {' ; 118 | $out[] = $str ; 119 | $out[] = $indent . '}' ; 120 | } 121 | } 122 | else { 123 | $out[] = $indent . $line ; 124 | } 125 | } 126 | 127 | return implode( PHP_EOL, $out ) ; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/PHPWriter.php: -------------------------------------------------------------------------------- 1 | l( 27 | '$res'.$id.' = $result;', 28 | '$pos'.$id.' = $this->pos;' 29 | ); 30 | } 31 | 32 | function restore( $id, $remove = FALSE ) { 33 | $code = PHPBuilder::build() 34 | ->l( 35 | '$result = $res'.$id.';', 36 | '$this->pos = $pos'.$id.';' 37 | ); 38 | 39 | if ( $remove ) $code->l( 40 | 'unset( $res'.$id.' );', 41 | 'unset( $pos'.$id.' );' 42 | ); 43 | 44 | return $code ; 45 | } 46 | 47 | function match_fail_conditional( $on, $match = NULL, $fail = NULL ) { 48 | return PHPBuilder::build() 49 | ->b( 'if (' . $on . ')', 50 | $match, 51 | 'MATCH' 52 | ) 53 | ->b( 'else', 54 | $fail, 55 | 'FAIL' 56 | ); 57 | } 58 | 59 | function match_fail_block( $code ) { 60 | $id = $this->varid() ; 61 | 62 | return PHPBuilder::build() 63 | ->l( 64 | '$'.$id.' = NULL;' 65 | ) 66 | ->b( 'do', 67 | $code->replace(array( 68 | 'MBREAK' => '$'.$id.' = TRUE; break;', 69 | 'FBREAK' => '$'.$id.' = FALSE; break;' 70 | )) 71 | ) 72 | ->l( 73 | 'while(0);' 74 | ) 75 | ->b( 'if( $'.$id.' === TRUE )', 'MATCH' ) 76 | ->b( 'if( $'.$id.' === FALSE)', 'FAIL' ) 77 | ; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /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 | static $argument_rx = '@ 27 | ( [^=]+ ) # Name 28 | = # Seperator 29 | ( [^=,]+ ) # Variable 30 | (,|$) 31 | @x'; 32 | 33 | static $replacement_rx = '@ 34 | ( ([^=]|=[^>])+ ) # What to replace 35 | => # The replacement mark 36 | ( [^,]+ ) # What to replace it with 37 | (,|$) 38 | @x'; 39 | 40 | static $function_rx = '@^\s+function\s+([^\s(]+)\s*(.*)@' ; 41 | 42 | protected $parser; 43 | protected $lines; 44 | 45 | public $name; 46 | public $extends; 47 | public $mode; 48 | public $rule; 49 | 50 | function __construct($parser, $lines) { 51 | $this->parser = $parser; 52 | $this->lines = $lines; 53 | 54 | // Find the first line (if any) that's an attached function definition. Can skip first line (unless this block is malformed) 55 | for ($i = 1; $i < count($lines); $i++) { 56 | if (preg_match(self::$function_rx, $lines[$i])) break; 57 | } 58 | 59 | // Then split into the two parts 60 | $spec = array_slice($lines, 0, $i); 61 | $funcs = array_slice($lines, $i); 62 | 63 | // Parse out the spec 64 | $spec = implode("\n", $spec); 65 | if (!preg_match(self::$rule_rx, $spec, $specmatch)) user_error('Malformed rule spec ' . $spec, E_USER_ERROR); 66 | 67 | $this->name = $specmatch['name']; 68 | 69 | if ($specmatch['extends']) { 70 | $this->extends = $this->parser->rules[$specmatch['extends']]; 71 | if (!$this->extends) user_error('Extended rule '.$specmatch['extends'].' is not defined before being extended', E_USER_ERROR); 72 | } 73 | 74 | $this->arguments = array(); 75 | 76 | if ($specmatch['arguments']) { 77 | preg_match_all(self::$argument_rx, $specmatch['arguments'], $arguments, PREG_SET_ORDER); 78 | 79 | foreach ($arguments as $argument){ 80 | $this->arguments[trim($argument[1])] = trim($argument[2]); 81 | } 82 | } 83 | 84 | $this->mode = $specmatch['matchmark'] ? 'rule' : 'replace'; 85 | 86 | if ($this->mode == 'rule') { 87 | $this->rule = $specmatch['rule']; 88 | $this->parse_rule() ; 89 | } 90 | else { 91 | if (!$this->extends) user_error('Replace matcher, but not on an extends rule', E_USER_ERROR); 92 | 93 | $this->replacements = array(); 94 | preg_match_all(self::$replacement_rx, $specmatch['rule'], $replacements, PREG_SET_ORDER); 95 | 96 | $rule = $this->extends->rule; 97 | 98 | foreach ($replacements as $replacement) { 99 | $search = trim($replacement[1]); 100 | $replace = trim($replacement[3]); if ($replace == "''" || $replace == '""') $replace = ""; 101 | 102 | $rule = str_replace($search, ' '.$replace.' ', $rule); 103 | } 104 | 105 | $this->rule = $rule; 106 | $this->parse_rule() ; 107 | } 108 | 109 | // Parse out the functions 110 | 111 | $this->functions = array() ; 112 | 113 | $active_function = NULL ; 114 | 115 | foreach( $funcs as $line ) { 116 | /* Handle function definitions */ 117 | if ( preg_match( self::$function_rx, $line, $func_match, 0 ) ) { 118 | $active_function = $func_match[1]; 119 | $this->functions[$active_function] = $func_match[2] . PHP_EOL; 120 | } 121 | else $this->functions[$active_function] .= $line . PHP_EOL ; 122 | } 123 | } 124 | 125 | /* Manual parsing, because we can't bootstrap ourselves yet */ 126 | function parse_rule() { 127 | $rule = trim( $this->rule ) ; 128 | 129 | $tokens = array() ; 130 | $this->tokenize( $rule, $tokens ) ; 131 | $this->parsed = ( count( $tokens ) == 1 ? array_pop( $tokens ) : new Token\Sequence( $tokens ) ) ; 132 | } 133 | 134 | static $rx_rx = '@\G/( 135 | ((\\\\\\\\)*\\\\/) # Escaped \/, making sure to catch all the \\ first, so that we dont think \\/ is an escaped / 136 | | 137 | [^/] # Anything except / 138 | )*/@xu' ; 139 | 140 | function tokenize( $str, &$tokens, $o = 0 ) { 141 | $length = strlen($str); 142 | $pending = new Rule\PendingState() ; 143 | 144 | while ( $o < $length ) { 145 | 146 | /* Absorb white-space */ 147 | if ( preg_match( '/\G\s+/', $str, $match, 0, $o ) ) { 148 | $o += strlen( $match[0] ) ; 149 | } 150 | /* Handle expression labels */ 151 | elseif ( preg_match( '/\G(\w*):/', $str, $match, 0, $o ) ) { 152 | $pending->set( 'tag', isset( $match[1] ) ? $match[1] : '' ) ; 153 | $o += strlen( $match[0] ) ; 154 | } 155 | /* Handle descent token */ 156 | elseif ( preg_match( '/\G[\w-]+/', $str, $match, 0, $o ) ) { 157 | $tokens[] = $t = new Token\Recurse( $match[0] ) ; 158 | $pending->apply_if_present( $t ) ; 159 | $o += strlen( $match[0] ) ; 160 | } 161 | /* Handle " quoted literals */ 162 | elseif ( preg_match( '/\G"[^"]*"/', $str, $match, 0, $o ) ) { 163 | $tokens[] = $t = new Token\Literal( $match[0] ) ; 164 | $pending->apply_if_present( $t ) ; 165 | $o += strlen( $match[0] ) ; 166 | } 167 | /* Handle ' quoted literals */ 168 | elseif ( preg_match( "/\G'[^']*'/", $str, $match, 0, $o ) ) { 169 | $tokens[] = $t = new Token\Literal( $match[0] ) ; 170 | $pending->apply_if_present( $t ) ; 171 | $o += strlen( $match[0] ) ; 172 | } 173 | /* Handle regexs */ 174 | elseif ( preg_match( self::$rx_rx, $str, $match, 0, $o ) ) { 175 | $tokens[] = $t = new Token\Regex( $match[0] ) ; 176 | $pending->apply_if_present( $t ) ; 177 | $o += strlen( $match[0] ) ; 178 | } 179 | /* Handle $ call literals */ 180 | elseif ( preg_match( '/\G\$(\w+)/', $str, $match, 0, $o ) ) { 181 | $tokens[] = $t = new Token\ExpressionedRecurse( $match[1] ) ; 182 | $pending->apply_if_present( $t ) ; 183 | $o += strlen( $match[0] ) ; 184 | } 185 | /* Handle flags */ 186 | elseif ( preg_match( '/\G\@(\w+)/', $str, $match, 0, $o ) ) { 187 | $l = count( $tokens ) - 1 ; 188 | $o += strlen( $match[0] ) ; 189 | user_error( "TODO: Flags not currently supported", E_USER_WARNING ) ; 190 | } 191 | /* Handle control tokens */ 192 | else { 193 | $c = substr( $str, $o, 1 ) ; 194 | $l = count( $tokens ) - 1 ; 195 | $o += 1 ; 196 | switch( $c ) { 197 | case '?': 198 | $tokens[$l]->quantifier = array('min' => 0, 'max' => 1); 199 | break ; 200 | case '*': 201 | $tokens[$l]->quantifier = array('min' => 0, 'max' => null); 202 | break ; 203 | case '+': 204 | $tokens[$l]->quantifier = array('min' => 1, 'max' => null); 205 | break ; 206 | case '{': 207 | if (preg_match('/\G\{([0-9]+)(,([0-9]*))?\}/', $str, $matches, 0, $o - 1)) { 208 | $min = $max = (int) $matches[1]; 209 | if(isset($matches[2])) { 210 | $max = $matches[3] ? (int) $matches[3] : null; 211 | } 212 | $tokens[$l]->quantifier = array('min' => $min, 'max' => $max); 213 | $o += strlen($matches[0]) - 1; 214 | } else { 215 | throw new \Exception(sprintf( 216 | "Unknown quantifier: %s", 217 | substr($str, $o, 10) 218 | )); 219 | } 220 | break; 221 | case '&': 222 | $pending->set( 'positive_lookahead' ) ; 223 | break ; 224 | case '!': 225 | $pending->set( 'negative_lookahead' ) ; 226 | break ; 227 | 228 | case '.': 229 | $pending->set( 'silent' ); 230 | break; 231 | 232 | case '[': 233 | case ']': 234 | $tokens[] = new Token\Whitespace( FALSE ) ; 235 | break ; 236 | case '<': 237 | case '>': 238 | $tokens[] = new Token\Whitespace( TRUE ) ; 239 | break ; 240 | 241 | case '(': 242 | $subtokens = array() ; 243 | $o = $this->tokenize( $str, $subtokens, $o ) ; 244 | $tokens[] = $t = new Token\Sequence( $subtokens ) ; $pending->apply_if_present( $t ) ; 245 | break ; 246 | case ')': 247 | return $o ; 248 | 249 | case '|': 250 | $option1 = $tokens ; 251 | $option2 = array() ; 252 | $o = $this->tokenize( $str, $option2, $o ) ; 253 | 254 | $option1 = (count($option1) == 1) ? $option1[0] : new Token\Sequence( $option1 ); 255 | $option2 = (count($option2) == 1) ? $option2[0] : new Token\Sequence( $option2 ); 256 | 257 | $pending->apply_if_present( $option2 ) ; 258 | 259 | $tokens = array( new Token\Option( $option1, $option2 ) ) ; 260 | return $o ; 261 | 262 | default: 263 | user_error( "Can't parser $c - attempting to skip", E_USER_WARNING ) ; 264 | } 265 | } 266 | } 267 | 268 | return $o ; 269 | } 270 | 271 | /** 272 | * Generate the PHP code for a function to match against a string for this rule 273 | */ 274 | function compile($indent) { 275 | $function_name = $this->function_name( $this->name ) ; 276 | 277 | // Build the typestack 278 | $typestack = array(); $class=$this; 279 | do { 280 | $typestack[] = $this->function_name($class->name); 281 | } 282 | while($class = $class->extends); 283 | 284 | $typestack = "array('" . implode("','", $typestack) . "')"; 285 | 286 | // Build an array of additional arguments to add to result node (if any) 287 | if (empty($this->arguments)) { 288 | $arguments = 'null'; 289 | } 290 | else { 291 | $arguments = "array("; 292 | foreach ($this->arguments as $k=>$v) { $arguments .= "'$k' => '$v', "; } 293 | $arguments .= ")"; 294 | } 295 | 296 | $match = PHPBuilder::build() ; 297 | 298 | $match->l("protected \$match_{$function_name}_typestack = $typestack;"); 299 | 300 | $match->b( "function match_{$function_name} (\$stack = array())", 301 | '$matchrule = "'.$function_name.'"; $result = $this->construct($matchrule, $matchrule, '.$arguments.');', 302 | $this->parsed->compile()->replace(array( 303 | 'MATCH' => 'return $this->finalise($result);', 304 | 'FAIL' => 'return FALSE;' 305 | )) 306 | ); 307 | 308 | $functions = array() ; 309 | foreach( $this->functions as $name => $function ) { 310 | $function_name = $this->function_name( preg_match( '/^_/', $name ) ? $this->name.$name : $this->name.'_'.$name ) ; 311 | $functions[] = implode( PHP_EOL, array( 312 | 'public function ' . $function_name . ' ' . $function 313 | )); 314 | } 315 | 316 | // print_r( $match ) ; return '' ; 317 | return $match->render(NULL, $indent) . PHP_EOL . PHP_EOL . implode( PHP_EOL, $functions ) ; 318 | } 319 | } -------------------------------------------------------------------------------- /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 | function __construct() { 13 | $this->what = NULL ; 14 | } 15 | 16 | function set( $what, $val = TRUE ) { 17 | $this->what = $what ; 18 | $this->val = $val ; 19 | } 20 | 21 | function apply_if_present( $on ) { 22 | if ( $this->what !== NULL ) { 23 | $what = $this->what ; 24 | $on->$what = $this->val ; 25 | 26 | $this->what = NULL ; 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/RuleSet.php: -------------------------------------------------------------------------------- 1 | rules[$rule->name] = $rule; 11 | 12 | $out[] = $indent . '/* ' . $rule->name . ':' . $rule->rule . ' */' . PHP_EOL ; 13 | $out[] = $rule->compile($indent) ; 14 | $out[] = PHP_EOL ; 15 | } 16 | 17 | function compile($indent, $rulestr) { 18 | $indentrx = '@^'.preg_quote($indent).'@'; 19 | 20 | $out = array(); 21 | $block = array(); 22 | 23 | foreach (preg_split('/\r\n|\r|\n/', $rulestr) as $line) { 24 | // Ignore blank lines 25 | if (!trim($line)) continue; 26 | // Ignore comments 27 | if (preg_match('/^[\x20\t]*#/', $line)) continue; 28 | 29 | // Strip off indent 30 | if (!empty($indent)) { 31 | if (strpos($line, $indent) === 0) $line = substr($line, strlen($indent)); 32 | else user_error('Non-blank line with inconsistent index in parser block', E_USER_ERROR); 33 | } 34 | 35 | // Any indented line, add to current set of lines 36 | if (preg_match('/^[\x20\t]/', $line)) $block[] = $line; 37 | 38 | // Any non-indented line marks a new block. Add a rule for the current block, then start a new block 39 | else { 40 | if (count($block)) $this->addRule($indent, $block, $out); 41 | $block = array($line); 42 | } 43 | } 44 | 45 | // Any unfinished block add a rule for 46 | if (count($block)) $this->addRule($indent, $block, $out); 47 | 48 | // And return the compiled version 49 | return implode( '', $out ) ; 50 | } 51 | } -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token.php: -------------------------------------------------------------------------------- 1 | type = $type ; 34 | $this->value = $value ; 35 | } 36 | 37 | // abstract protected function match_code() ; 38 | 39 | function compile() { 40 | $code = $this->match_code($this->value) ; 41 | 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 | } else if (0 === $q['min'] && null === $q['max']) { 50 | // zero or more: * || {0,} 51 | $code = $this->zero_or_more($code, $id); 52 | } else if (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->positive_lookahead ) { 62 | $code = PHPBuilder::build() 63 | ->l( 64 | $this->save($id), 65 | $code->replace( array( 66 | 'MATCH' => 67 | $this->restore($id) 68 | ->l( 'MATCH' ), 69 | 'FAIL' => 70 | $this->restore($id) 71 | ->l( 'FAIL' ) 72 | ))); 73 | } 74 | 75 | if ( $this->negative_lookahead ) { 76 | $code = PHPBuilder::build() 77 | ->l( 78 | $this->save($id), 79 | $code->replace( array( 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(array( 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 | { 113 | return PHPBuilder::build()->l( 114 | $this->save($id), 115 | $code->replace(array('FAIL' => $this->restore($id,true))) 116 | ); 117 | } 118 | 119 | protected function zero_or_more($code, $id) 120 | { 121 | return PHPBuilder::build()->b( 122 | 'while (true)', 123 | $this->save($id), 124 | $code->replace(array( 125 | 'MATCH' => NULL, 126 | 'FAIL' => $this->restore($id, true)->l('break;') 127 | )) 128 | )->l('MATCH'); 129 | } 130 | 131 | protected function n_or_more($code, $id, $n) 132 | { 133 | return PHPBuilder::build()->l( 134 | '$count = 0;' 135 | )->b( 136 | 'while (true)', 137 | $this->save($id), 138 | $code->replace(array( 139 | 'MATCH' => NULL, 140 | 'FAIL' => $this->restore($id, true)->l('break;') 141 | )), 142 | '$count++;' 143 | )->b( 144 | 'if ($count >= '.$n.')', 145 | 'MATCH' 146 | )->b( 147 | 'else', 148 | 'FAIL' 149 | ); 150 | } 151 | 152 | protected function n_to_x($code, $id, $min, $max) 153 | { 154 | if(1 === $min && 1 === $max) return $code; 155 | 156 | return PHPBuilder::build()->l( 157 | '$count = 0;' 158 | )->b( 159 | 'while ($count < '.$max.')', 160 | $this->save($id), 161 | $code->replace(array( 162 | 'MATCH' => NULL, 163 | 'FAIL' => $this->restore($id, true)->l('break;') 164 | )), 165 | '$count++;' 166 | )->b( 167 | 'if ($count >= '.$min.')', 168 | 'MATCH' 169 | )->b( 170 | 'else', 171 | 'FAIL' 172 | ); 173 | 174 | } 175 | } 176 | 177 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/Expressionable.php: -------------------------------------------------------------------------------- 1 | expression($result, $stack, \'' . (!empty($matches[1]) ? $matches[1] : $matches[2]) . "').'"; 15 | } 16 | 17 | function match_code( $value ) { 18 | $value = preg_replace_callback(self::$expression_rx, array($this, 'expression_replace'), $value); 19 | return parent::match_code($value); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/ExpressionedRecurse.php: -------------------------------------------------------------------------------- 1 | expression($result, $stack, \''.$value.'\')'; 8 | } 9 | } -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/Literal.php: -------------------------------------------------------------------------------- 1 | contains_expression($value) && strlen( eval( 'return '. $value . ';' ) ) == 1 ) { 15 | return $this->match_fail_conditional( 'substr($this->string,$this->pos,1) == '.$value, 16 | PHPBuilder::build()->l( 17 | '$this->pos += 1;', 18 | $this->set_text($value) 19 | ) 20 | ); 21 | } 22 | return parent::match_code($value); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/Option.php: -------------------------------------------------------------------------------- 1 | varid() ; 15 | $code = PHPBuilder::build() 16 | ->l( 17 | $this->save($id) 18 | ) ; 19 | 20 | foreach ( $value as $opt ) { 21 | $code->l( 22 | $opt->compile()->replace(array( 23 | 'MATCH' => 'MBREAK', 24 | 'FAIL' => NULL 25 | )), 26 | $this->restore($id) 27 | ); 28 | } 29 | $code->l( 'FBREAK' ) ; 30 | 31 | return $this->match_fail_block( $code ) ; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/Recurse.php: -------------------------------------------------------------------------------- 1 | function_name($value)."'"; 15 | } 16 | 17 | function match_code( $value ) { 18 | $function = $this->match_function($value) ; 19 | $storetag = $this->function_name( $this->tag ? $this->tag : $this->match_function($value) ) ; 20 | 21 | if ( \hafriedlander\Peg\Compiler::$debug ) { 22 | $debug_header = PHPBuilder::build() 23 | ->l( 24 | '$indent = str_repeat( " ", $this->depth );', 25 | '$this->depth += 2;', 26 | '$sub = ( strlen( $this->string ) - $this->pos > 20 ) ? ( substr( $this->string, $this->pos, 20 ) . "..." ) : substr( $this->string, $this->pos );', 27 | '$sub = preg_replace( \'/(\r|\n)+/\', " {NL} ", $sub );', 28 | 'print( $indent."Matching against $matcher (".$sub.")\n" );' 29 | ); 30 | 31 | $debug_match = PHPBuilder::build() 32 | ->l( 33 | 'print( $indent."MATCH\n" );', 34 | '$this->depth -= 2;' 35 | ); 36 | 37 | $debug_fail = PHPBuilder::build() 38 | ->l( 39 | 'print( $indent."FAIL\n" );', 40 | '$this->depth -= 2;' 41 | ); 42 | } 43 | else { 44 | $debug_header = $debug_match = $debug_fail = NULL ; 45 | } 46 | 47 | return PHPBuilder::build()->l( 48 | '$matcher = \'match_\'.'.$function.'; $key = $matcher; $pos = $this->pos;', 49 | $debug_header, 50 | '$subres = ( $this->packhas( $key, $pos ) ? $this->packread( $key, $pos ) : $this->packwrite( $key, $pos, $this->$matcher(array_merge($stack, array($result))) ) );', 51 | $this->match_fail_conditional( '$subres !== FALSE', 52 | PHPBuilder::build()->l( 53 | $debug_match, 54 | $this->tag === FALSE ? 55 | '$this->store( $result, $subres );' : 56 | '$this->store( $result, $subres, "'.$storetag.'" );' 57 | ), 58 | PHPBuilder::build()->l( 59 | $debug_fail 60 | ) 61 | )); 62 | } 63 | } -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/Regex.php: -------------------------------------------------------------------------------- 1 | l( 17 | $token->compile()->replace(array( 18 | 'MATCH' => NULL, 19 | 'FAIL' => 'FBREAK' 20 | )) 21 | ); 22 | } 23 | $code->l( 'MBREAK' ); 24 | 25 | return $this->match_fail_block( $code ) ; 26 | } 27 | } -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/Terminal.php: -------------------------------------------------------------------------------- 1 | silent ? NULL : '$result["text"] .= ' . $text . ';'; 10 | } 11 | 12 | protected function match_code( $value ) { 13 | return $this->match_fail_conditional( '( $subres = $this->'.$this->type.'( '.$value.' ) ) !== FALSE', 14 | $this->set_text('$subres') 15 | ); 16 | } 17 | } -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Compiler/Token/Whitespace.php: -------------------------------------------------------------------------------- 1 | replace( array( 'FAIL' => NULL )) : $code ; 14 | } 15 | } -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Parser/Basic.php: -------------------------------------------------------------------------------- 1 | string = $string ; 15 | $this->pos = 0 ; 16 | 17 | $this->depth = 0 ; 18 | 19 | $this->regexps = array() ; 20 | } 21 | 22 | function whitespace() { 23 | $matched = preg_match( '/[ \t]+/', $this->string, $matches, PREG_OFFSET_CAPTURE, $this->pos ) ; 24 | if ( $matched && $matches[0][1] == $this->pos ) { 25 | $this->pos += strlen( $matches[0][0] ); 26 | return ' ' ; 27 | } 28 | return FALSE ; 29 | } 30 | 31 | function literal( $token ) { 32 | /* Debugging: * / print( "Looking for token '$token' @ '" . substr( $this->string, $this->pos ) . "'\n" ) ; /* */ 33 | $toklen = strlen( $token ) ; 34 | $substr = substr( $this->string, $this->pos, $toklen ) ; 35 | if ( $substr == $token ) { 36 | $this->pos += $toklen ; 37 | return $token ; 38 | } 39 | return FALSE ; 40 | } 41 | 42 | function rx( $rx ) { 43 | if ( !isset( $this->regexps[$rx] ) ) $this->regexps[$rx] = new CachedRegexp( $this, $rx ) ; 44 | return $this->regexps[$rx]->match() ; 45 | } 46 | 47 | function expression( $result, $stack, $value ) { 48 | $stack[] = $result; $rv = false; 49 | 50 | /* Search backwards through the sub-expression stacks */ 51 | for ( $i = count($stack) - 1 ; $i >= 0 ; $i-- ) { 52 | $node = $stack[$i]; 53 | 54 | if ( isset($node[$value]) ) { $rv = $node[$value]; break; } 55 | 56 | foreach ($this->typestack($node['_matchrule']) as $type) { 57 | $callback = array($this, "{$type}_DLR{$value}"); 58 | if ( is_callable( $callback ) ) { $rv = call_user_func( $callback ) ; if ($rv !== FALSE) break; } 59 | } 60 | } 61 | 62 | if ($rv === false) $rv = @$this->$value; 63 | if ($rv === false) $rv = @$this->$value(); 64 | 65 | return is_array($rv) ? $rv['text'] : ($rv ? $rv : ''); 66 | } 67 | 68 | function packhas( $key, $pos ) { 69 | return false ; 70 | } 71 | 72 | function packread( $key, $pos ) { 73 | throw new \Exception('PackRead after PackHas=>false in Parser.php') ; 74 | } 75 | 76 | function packwrite( $key, $pos, $res ) { 77 | return $res ; 78 | } 79 | 80 | function typestack( $name ) { 81 | $prop = "match_{$name}_typestack"; 82 | return $this->$prop; 83 | } 84 | 85 | function construct( $matchrule, $name, $arguments = null ) { 86 | $result = array( '_matchrule' => $matchrule, 'name' => $name, 'text' => '' ); 87 | if ($arguments) $result = array_merge($result, $arguments) ; 88 | 89 | foreach ($this->typestack($matchrule) as $type) { 90 | $callback = array( $this, "{$type}__construct" ) ; 91 | if ( is_callable( $callback ) ) { 92 | call_user_func_array( $callback, array( &$result ) ) ; 93 | break; 94 | } 95 | } 96 | 97 | return $result ; 98 | } 99 | 100 | function finalise( &$result ) { 101 | foreach ($this->typestack($result['_matchrule']) as $type) { 102 | $callback = array( $this, "{$type}__finalise" ) ; 103 | if ( is_callable( $callback ) ) { 104 | call_user_func_array( $callback, array( &$result ) ) ; 105 | break; 106 | } 107 | } 108 | 109 | return $result ; 110 | } 111 | 112 | function store ( &$result, $subres, $storetag = NULL ) { 113 | $result['text'] .= $subres['text'] ; 114 | 115 | $storecalled = false; 116 | 117 | foreach ($this->typestack($result['_matchrule']) as $type) { 118 | $callback = array( $this, $storetag ? "{$type}_{$storetag}" : "{$type}_{$subres['name']}" ) ; 119 | if ( is_callable( $callback ) ) { 120 | call_user_func_array( $callback, array( &$result, $subres ) ) ; 121 | $storecalled = true; break; 122 | } 123 | 124 | $globalcb = array( $this, "{$type}_STR" ) ; 125 | if ( is_callable( $globalcb ) ) { 126 | call_user_func_array( $globalcb, array( &$result, $subres ) ) ; 127 | $storecalled = true; break; 128 | } 129 | } 130 | 131 | if ( $storetag && !$storecalled ) { 132 | if ( !isset( $result[$storetag] ) ) $result[$storetag] = $subres ; 133 | else { 134 | if ( isset( $result[$storetag]['text'] ) ) $result[$storetag] = array( $result[$storetag] ) ; 135 | $result[$storetag][] = $subres ; 136 | } 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Parser/CachedRegexp.php: -------------------------------------------------------------------------------- 1 | parser = $parser ; 16 | $this->rx = $rx . 'Sx' ; 17 | 18 | $this->matches = NULL ; 19 | $this->match_pos = NULL ; // NULL is no-match-to-end-of-string, unless check_pos also == NULL, in which case means undefined 20 | $this->check_pos = NULL ; 21 | } 22 | 23 | function match() { 24 | $current_pos = $this->parser->pos ; 25 | $dirty = $this->check_pos === NULL || $this->check_pos > $current_pos || ( $this->match_pos !== NULL && $this->match_pos < $current_pos ) ; 26 | 27 | if ( $dirty ) { 28 | $this->check_pos = $current_pos ; 29 | $matched = preg_match( $this->rx, $this->parser->string, $this->matches, PREG_OFFSET_CAPTURE, $this->check_pos) ; 30 | if ( $matched ) $this->match_pos = $this->matches[0][1] ; else $this->match_pos = NULL ; 31 | } 32 | 33 | if ( $this->match_pos === $current_pos ) { 34 | $this->parser->pos += strlen( $this->matches[0][0] ); 35 | return $this->matches[0][0] ; 36 | } 37 | 38 | return FALSE ; 39 | } 40 | } -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Parser/ConservativePackrat.php: -------------------------------------------------------------------------------- 1 | packres[$key] ) && $this->packres[$key] !== NULL ; 15 | } 16 | 17 | function packread( $key, $pos ) { 18 | $this->pos = $this->packpos[$key]; 19 | return $this->packres[$key] ; 20 | } 21 | 22 | function packwrite( $key, $pos, $res ) { 23 | if ( isset( $this->packres[$key] ) ) { 24 | $this->packres[$key] = $res ; 25 | $this->packpos[$key] = $this->pos ; 26 | } 27 | else { 28 | $this->packres[$key] = NULL ; 29 | } 30 | return $res ; 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Parser/FalseOnlyPackrat.php: -------------------------------------------------------------------------------- 1 | packstatebase = str_repeat( '.', strlen( $string ) ) ; 15 | $this->packstate = array() ; 16 | } 17 | 18 | function packhas( $key, $pos ) { 19 | return isset( $this->packstate[$key] ) && $this->packstate[$key][$pos] == 'F' ; 20 | } 21 | 22 | function packread( $key, $pos ) { 23 | return FALSE ; 24 | } 25 | 26 | function packwrite( $key, $pos, $res ) { 27 | if ( !isset( $this->packstate[$key] ) ) $this->packstate[$key] = $this->packstatebase ; 28 | 29 | if ( $res === FALSE ) { 30 | $this->packstate[$key][$pos] = 'F' ; 31 | } 32 | 33 | return $res ; 34 | } 35 | } -------------------------------------------------------------------------------- /lib/hafriedlander/Peg/Parser/Packrat.php: -------------------------------------------------------------------------------- 1 | $max[1] ) user_error( 'Attempting to parse string longer than Packrat Parser can handle', E_USER_ERROR ) ; 20 | 21 | $this->packstatebase = str_repeat( "\xFF", strlen( $string )*3 ) ; 22 | $this->packstate = array() ; 23 | $this->packres = array() ; 24 | } 25 | 26 | function packhas( $key, $pos ) { 27 | $pos *= 3 ; 28 | return isset( $this->packstate[$key] ) && $this->packstate[$key][$pos] != "\xFF" ; 29 | } 30 | 31 | function packread( $key, $pos ) { 32 | $pos *= 3 ; 33 | if ( $this->packstate[$key][$pos] == "\xFE" ) return FALSE ; 34 | 35 | $this->pos = ord($this->packstate[$key][$pos]) << 16 | ord($this->packstate[$key][$pos+1]) << 8 | ord($this->packstate[$key][$pos+2]) ; 36 | return $this->packres["$key:$pos"] ; 37 | } 38 | 39 | function packwrite( $key, $pos, $res ) { 40 | if ( !isset( $this->packstate[$key] ) ) $this->packstate[$key] = $this->packstatebase ; 41 | 42 | $pos *= 3 ; 43 | 44 | if ( $res !== FALSE ) { 45 | $i = pack( 'N', $this->pos ) ; 46 | 47 | $this->packstate[$key][$pos] = $i[1] ; 48 | $this->packstate[$key][$pos+1] = $i[2] ; 49 | $this->packstate[$key][$pos+2] = $i[3] ; 50 | 51 | $this->packres["$key:$pos"] = $res ; 52 | } 53 | else { 54 | $this->packstate[$key][$pos] = "\xFE" ; 55 | } 56 | 57 | return $res ; 58 | } 59 | } -------------------------------------------------------------------------------- /lib/vendor/SplClassLoader.php: -------------------------------------------------------------------------------- 1 | register(); 13 | * 14 | * @author Jonathan H. Wage 15 | * @author Roman S. Borschel 16 | * @author Matthew Weier O'Phinney 17 | * @author Kris Wallsmith 18 | * @author Fabien Potencier 19 | */ 20 | class SplClassLoader 21 | { 22 | private $_fileExtension = '.php'; 23 | private $_namespace; 24 | private $_includePath; 25 | private $_namespaceSeparator = '\\'; 26 | 27 | /** 28 | * Creates a new SplClassLoader that loads classes of the 29 | * specified namespace. 30 | * 31 | * @param string $ns The namespace to use. 32 | */ 33 | public function __construct($ns = null, $includePath = null) 34 | { 35 | $this->_namespace = $ns; 36 | $this->_includePath = $includePath; 37 | } 38 | 39 | /** 40 | * Sets the namespace separator used by classes in the namespace of this class loader. 41 | * 42 | * @param string $sep The separator to use. 43 | */ 44 | public function setNamespaceSeparator($sep) 45 | { 46 | $this->_namespaceSeparator = $sep; 47 | } 48 | 49 | /** 50 | * Gets the namespace seperator used by classes in the namespace of this class loader. 51 | * 52 | * @return void 53 | */ 54 | public function getNamespaceSeparator() 55 | { 56 | return $this->_namespaceSeparator; 57 | } 58 | 59 | /** 60 | * Sets the base include path for all class files in the namespace of this class loader. 61 | * 62 | * @param string $includePath 63 | */ 64 | public function setIncludePath($includePath) 65 | { 66 | $this->_includePath = $includePath; 67 | } 68 | 69 | /** 70 | * Gets the base include path for all class files in the namespace of this class loader. 71 | * 72 | * @return string $includePath 73 | */ 74 | public function getIncludePath() 75 | { 76 | return $this->_includePath; 77 | } 78 | 79 | /** 80 | * Sets the file extension of class files in the namespace of this class loader. 81 | * 82 | * @param string $fileExtension 83 | */ 84 | public function setFileExtension($fileExtension) 85 | { 86 | $this->_fileExtension = $fileExtension; 87 | } 88 | 89 | /** 90 | * Gets the file extension of class files in the namespace of this class loader. 91 | * 92 | * @return string $fileExtension 93 | */ 94 | public function getFileExtension() 95 | { 96 | return $this->_fileExtension; 97 | } 98 | 99 | /** 100 | * Installs this class loader on the SPL autoload stack. 101 | */ 102 | public function register() 103 | { 104 | spl_autoload_register(array($this, 'loadClass')); 105 | } 106 | 107 | /** 108 | * Uninstalls this class loader from the SPL autoloader stack. 109 | */ 110 | public function unregister() 111 | { 112 | spl_autoload_unregister(array($this, 'loadClass')); 113 | } 114 | 115 | /** 116 | * Loads the given class or interface. 117 | * 118 | * @param string $className The name of the class to load. 119 | * @return void 120 | */ 121 | public function loadClass($className) 122 | { 123 | if (null === $this->_namespace || $this->_namespace.$this->_namespaceSeparator === substr($className, 0, strlen($this->_namespace.$this->_namespaceSeparator))) { 124 | $fileName = ''; 125 | $namespace = ''; 126 | if (false !== ($lastNsPos = strripos($className, $this->_namespaceSeparator))) { 127 | $namespace = substr($className, 0, $lastNsPos); 128 | $className = substr($className, $lastNsPos + 1); 129 | $fileName = str_replace($this->_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; 130 | } 131 | $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension; 132 | 133 | require ($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName; 134 | } 135 | } 136 | } -------------------------------------------------------------------------------- /tests/ParserInheritanceTest.php: -------------------------------------------------------------------------------- 1 | buildParser(' 10 | /*!* BasicInheritanceTestParser 11 | Foo: "a" 12 | Bar extends Foo 13 | */ 14 | '); 15 | 16 | $this->assertTrue($parser->matches('Foo', 'a')); 17 | $this->assertTrue($parser->matches('Bar', 'a')); 18 | 19 | $this->assertFalse($parser->matches('Foo', 'b')); 20 | $this->assertFalse($parser->matches('Bar', 'b')); 21 | } 22 | 23 | 24 | public function testBasicInheritanceConstructFallback() { 25 | 26 | $parser = $this->buildParser(' 27 | /*!* BasicInheritanceConstructFallbackParser 28 | Foo: "a" 29 | function __construct(&$res){ $res["test"] = "test"; } 30 | Bar extends Foo 31 | */ 32 | '); 33 | 34 | $res = $parser->match('Foo', 'a'); 35 | $this->assertEquals($res['test'], 'test'); 36 | 37 | $res = $parser->match('Bar', 'a'); 38 | $this->assertEquals($res['test'], 'test'); 39 | 40 | $parser = $this->buildParser(' 41 | /*!* BasicInheritanceConstructFallbackParser2 42 | Foo: "a" 43 | function __construct(&$res){ $res["testa"] = "testa"; } 44 | Bar extends Foo 45 | function __construct(&$res){ $res["testb"] = "testb"; } 46 | */ 47 | '); 48 | 49 | $res = $parser->match('Foo', 'a'); 50 | $this->assertArrayHasKey('testa', $res); 51 | $this->assertEquals($res['testa'], 'testa'); 52 | $this->assertArrayNotHasKey('testb', $res); 53 | 54 | $res = $parser->match('Bar', 'a'); 55 | $this->assertArrayHasKey('testb', $res); 56 | $this->assertEquals($res['testb'], 'testb'); 57 | $this->assertArrayNotHasKey('testa', $res); 58 | 59 | } 60 | 61 | public function testBasicInheritanceStoreFallback() { 62 | 63 | $parser = $this->buildParser(' 64 | /*!* BasicInheritanceStoreFallbackParser 65 | Foo: Pow:"a" 66 | function *(&$res, $sub){ $res["test"] = "test"; } 67 | Bar extends Foo 68 | */ 69 | '); 70 | 71 | $res = $parser->match('Foo', 'a'); 72 | $this->assertEquals($res['test'], 'test'); 73 | 74 | $res = $parser->match('Bar', 'a'); 75 | $this->assertEquals($res['test'], 'test'); 76 | 77 | $parser = $this->buildParser(' 78 | /*!* BasicInheritanceStoreFallbackParser2 79 | Foo: Pow:"a" Zap:"b" 80 | function *(&$res, $sub){ $res["testa"] = "testa"; } 81 | Bar extends Foo 82 | function *(&$res, $sub){ $res["testb"] = "testb"; } 83 | Baz extends Foo 84 | function Zap(&$res, $sub){ $res["testc"] = "testc"; } 85 | */ 86 | '); 87 | 88 | $res = $parser->match('Foo', 'ab'); 89 | $this->assertArrayHasKey('testa', $res); 90 | $this->assertEquals($res['testa'], 'testa'); 91 | $this->assertArrayNotHasKey('testb', $res); 92 | 93 | $res = $parser->match('Bar', 'ab'); 94 | $this->assertArrayHasKey('testb', $res); 95 | $this->assertEquals($res['testb'], 'testb'); 96 | $this->assertArrayNotHasKey('testa', $res); 97 | 98 | $res = $parser->match('Baz', 'ab'); 99 | $this->assertArrayHasKey('testa', $res); 100 | $this->assertEquals($res['testa'], 'testa'); 101 | $this->assertArrayHasKey('testc', $res); 102 | $this->assertEquals($res['testc'], 'testc'); 103 | $this->assertArrayNotHasKey('testb', $res); 104 | } 105 | 106 | public function testInheritanceByReplacement() { 107 | $parser = $this->buildParser(' 108 | /*!* InheritanceByReplacementParser 109 | A: "a" 110 | B: "b" 111 | Foo: A B 112 | Bar extends Foo; B => A 113 | Baz extends Foo; A => "" 114 | */ 115 | '); 116 | 117 | $parser->assertMatches('Foo', 'ab'); 118 | $parser->assertMatches('Bar', 'aa'); 119 | $parser->assertMatches('Baz', 'b'); 120 | } 121 | 122 | 123 | } -------------------------------------------------------------------------------- /tests/ParserSyntaxTest.php: -------------------------------------------------------------------------------- 1 | buildParser(' 9 | /*!* BasicRuleSyntax 10 | Foo: "a" "b" 11 | Bar: "a" 12 | "b" 13 | Baz: 14 | "a" "b" 15 | Qux: 16 | "a" 17 | "b" 18 | Quux: "a" 19 | */ 20 | '); 21 | 22 | $parser->assertMatches('Foo', 'ab'); 23 | $parser->assertMatches('Bar', 'ab'); 24 | $parser->assertMatches('Baz', 'ab'); 25 | $parser->assertMatches('Qux', 'ab'); 26 | $parser->assertMatches('Quux', 'a'); 27 | } 28 | 29 | public function testRuleNamesCanContainHyphens() { 30 | $parser = $this->buildParser(' 31 | /*!* RuleNamesCanContainHyphens 32 | Foo-one: "a" "b" 33 | Foo-two: "b" "a" 34 | */ 35 | '); 36 | 37 | $parser->assertMatches('Foo-one', 'ab'); 38 | $parser->assertMatches('Foo-two', 'ba'); 39 | } 40 | 41 | public function testComplexRulesCanStartWithARegex() { 42 | $parser = $this->buildParser(' 43 | /*!* ComplexRulesCanStartWithARegex 44 | Foo: /foo/ "bar" 45 | */ 46 | '); 47 | 48 | $parser->assertDoesntMatch('Foo', 'foo'); 49 | $parser->assertMatches('Foo', 'foobar'); 50 | } 51 | } -------------------------------------------------------------------------------- /tests/ParserTestBase.php: -------------------------------------------------------------------------------- 1 | testcase = $testcase; 11 | $this->class = $class; 12 | } 13 | 14 | function function_name( $str ) { 15 | $str = preg_replace( '/-/', '_', $str ) ; 16 | $str = preg_replace( '/\$/', 'DLR', $str ) ; 17 | $str = preg_replace( '/\*/', 'STR', $str ) ; 18 | $str = preg_replace( '/[^\w]+/', '', $str ) ; 19 | return $str ; 20 | } 21 | 22 | function match($method, $string, $allowPartial = false){ 23 | $class = $this->class; 24 | $func = $this->function_name('match_'.$method); 25 | 26 | $parser = new $class($string); 27 | $res = $parser->$func(); 28 | return ($allowPartial || $parser->pos == strlen($string)) ? $res : false; 29 | } 30 | 31 | function matches($method, $string, $allowPartial = false){ 32 | return $this->match($method, $string, $allowPartial) !== false; 33 | } 34 | 35 | function assertMatches($method, $string, $message = null){ 36 | $this->testcase->assertTrue($this->matches($method, $string), $message ? $message : "Assert parser method $method matches string $string"); 37 | } 38 | 39 | function assertDoesntMatch($method, $string, $message = null){ 40 | $this->testcase->assertFalse($this->matches($method, $string), $message ? $message : "Assert parser method $method doesn't match string $string"); 41 | } 42 | } 43 | 44 | class ParserTestBase extends PHPUnit_Framework_TestCase { 45 | 46 | function buildParser($parser) { 47 | $class = 'Parser'.sha1($parser); 48 | 49 | // echo ParserCompiler::compile("class $class extends Parser {\n $parser\n}") . "\n\n\n"; 50 | eval(Peg\Compiler::compile("class $class extends hafriedlander\Peg\Parser\Basic {\n $parser\n}")); 51 | return new ParserTestWrapper($this, $class); 52 | } 53 | 54 | } -------------------------------------------------------------------------------- /tests/ParserVariablesTest.php: -------------------------------------------------------------------------------- 1 | buildParser(' 9 | /*!* BasicVariables 10 | Foo: Letter:"a" "$Letter" 11 | Bar: Letter:"b" "$Letter $Letter" 12 | Baz: Letter:"c" "$Letter a $Letter a" 13 | Qux: Letter:"d" "{$Letter}a{$Letter}a" 14 | */ 15 | '); 16 | 17 | $parser->assertMatches('Foo', 'aa'); 18 | $parser->assertMatches('Bar', 'bb b'); 19 | $parser->assertMatches('Baz', 'cc a c a'); 20 | $parser->assertMatches('Qux', 'ddada'); 21 | } 22 | 23 | public function testRecurseOnVariables() { 24 | $parser = $this->buildParser(' 25 | /*!* RecurseOnVariablesParser 26 | A: "a" 27 | B: "b" 28 | Foo: $Template 29 | Bar: Foo 30 | function __construct(&$res){ $res["Template"] = "A"; } 31 | Baz: Foo 32 | function __construct(&$res){ $res["Template"] = "B"; } 33 | */ 34 | '); 35 | 36 | $parser->assertMatches('Bar', 'a'); $parser->assertDoesntMatch('Bar', 'b'); 37 | $parser->assertMatches('Baz', 'b'); $parser->assertDoesntMatch('Baz', 'a'); 38 | } 39 | 40 | public function testSetOnRuleVariables() { 41 | $parser = $this->buildParser(' 42 | /*!* SetOnRuleVariablesParser 43 | A: "a" 44 | B: "b" 45 | Foo: $Template 46 | Bar (Template = A): Foo 47 | Baz (Template = B): Foo 48 | */ 49 | '); 50 | 51 | $parser->assertMatches('Bar', 'a'); 52 | $parser->assertMatches('Baz', 'b'); 53 | } 54 | 55 | } --------------------------------------------------------------------------------