├── .gitignore ├── LICENSE ├── Makefile ├── Peg.hs ├── Peg ├── BuiltIn.hs ├── Constraints.hs ├── Monad.hs ├── Parse.hs ├── Types.hs └── Utils.hs ├── QuadMatrix.hs ├── README.md ├── Search.hs ├── Setup.hs ├── Simplex.hs ├── lib.peg ├── peg.cabal └── types.peg /.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | *.hi 3 | *~ 4 | *.o-boot 5 | *.hi-boot 6 | _darcs 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SOURCE=Peg.hs Search.hs Peg/*.hs *.peg Makefile README.md 2 | 3 | peg: Peg.hs Search.hs Peg/*.hs 4 | ghc --make -DMAIN -o peg -O -ltinfo Peg.hs 5 | 6 | peg-debug: Peg.hs Search.hs Peg/*.hs 7 | ghc --make -DMAIN -DDEBUG -o peg-debug -O -ltinfo Peg.hs 8 | 9 | .PHONY: clean 10 | 11 | clean: 12 | rm -f *.o Peg/*.o *.hi Peg/*.hi peg peg-debug; rm -rf dist 13 | 14 | .PHONY: vim 15 | vim: 16 | vim $(SOURCE) 17 | 18 | .PHONY: gvim 19 | gvim: 20 | gvim $(SOURCE) & 21 | 22 | .PHONY: emacs 23 | emacs: 24 | emacs $(SOURCE) & 25 | -------------------------------------------------------------------------------- /Peg.hs: -------------------------------------------------------------------------------- 1 | {- Copyright 2012 Dustin DeWeese 2 | This file is part of peg. 3 | 4 | peg is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | peg is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with peg. If not, see . 16 | -} 17 | {-# LANGUAGE CPP, ScopedTypeVariables #-} 18 | #ifdef MAIN 19 | module Main where 20 | #else 21 | module Peg where 22 | #endif 23 | 24 | import Peg.Types 25 | import Peg.BuiltIn 26 | import Peg.Monad 27 | import Peg.Parse 28 | import Peg.Utils 29 | 30 | import Control.Applicative 31 | import System.Console.Haskeline hiding (throwIO, handle) 32 | import System.Environment 33 | import System.FilePath 34 | import System.IO 35 | import Control.Monad.State 36 | import qualified Data.Set as S 37 | import Data.Map (Map) 38 | import qualified Data.Map as M 39 | 40 | import Data.Maybe 41 | import Data.List 42 | import Control.Monad.Identity 43 | 44 | import Debug.Trace 45 | import Search 46 | 47 | evalStack (s, m, c) = runBFSAll $ do 48 | PegState s _ m _ c _ _ <- execStateT force $ PegState s [] m 0 c M.empty [] 49 | return (s, m, c) 50 | 51 | hGetLines h = do 52 | e <- hIsEOF h 53 | if e 54 | then return [] 55 | else (:) <$> hGetLine h <*> hGetLines h 56 | 57 | getLinesFromFile f = withFile f ReadMode hGetLines 58 | 59 | main = do 60 | args <- getArgs 61 | let files = filter ((==".peg").takeExtension) args 62 | m <- foldM (\m f -> do 63 | l <- getLinesFromFile f 64 | load [] m l) builtins files 65 | runInputT defaultSettings $ evalLoop [] m 66 | 67 | load :: Stack 68 | -> Env 69 | -> [String] 70 | -> IO Env 71 | load s m [] = return m 72 | load s m (input:r) = 73 | case parseStack input of 74 | Left e -> print e >> return m 75 | Right s -> do 76 | let x = runIdentity $ evalStack (s, m, ([],[])) 77 | case x of 78 | (s', m', _) : _ -> load s' m' r 79 | [] -> load s m r 80 | 81 | evalLoop :: Stack -> Env -> InputT IO () 82 | evalLoop p m = do 83 | let text = case p of 84 | [] -> "" 85 | s -> showStack s ++ " " 86 | minput <- getInputLineWithInitial ": " (text, "") 87 | case minput of 88 | Nothing -> return () 89 | Just "" -> return () 90 | Just input -> case parseStack input of 91 | Left e -> outputStrLn (show e) >> evalLoop p m 92 | Right s -> do 93 | let x' = runIdentity $ evalStack (subst (A "IO") Io s, m, ([], [])) 94 | case take 5 x' of 95 | [] -> evalLoop s m 96 | ((s',m',c'):r) -> do 97 | mapM_ printAlt $ reverse r 98 | printConstraints c' 99 | evalLoop s' m' 100 | where printConstraints (c,_) = 101 | mapM_ (\(x, y) -> outputStrLn $ showStack x ++ " <-- " ++ showStack y) $ reverse c 102 | printAlt (s,_,c) = do 103 | printConstraints c 104 | outputStrLn . ("| "++) . showStack $ s 105 | 106 | uncycle [] = [] 107 | uncycle s@(t:xs) | lambda == 0 = s 108 | | otherwise = map fst p ++ map fst (take lambda c) 109 | where (p, c) = span (uncurry (/=)) . zip s $ drop lambda s 110 | lambda = brent 1 1 t xs 111 | brent _ _ _ [] = 0 112 | brent l p t (h:xs) 113 | | t == h = l 114 | | l == p = brent 1 (p*2) h xs 115 | | otherwise = brent (l+1) p t xs 116 | -------------------------------------------------------------------------------- /Peg/BuiltIn.hs: -------------------------------------------------------------------------------- 1 | {- Copyright 2012 Dustin DeWeese 2 | This file is part of peg. 3 | 4 | peg is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | peg is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with peg. If not, see . 16 | -} 17 | 18 | {-# LANGUAGE FlexibleInstances #-} 19 | module Peg.BuiltIn where 20 | 21 | import Peg.Types 22 | import Peg.Monad 23 | import Peg.Parse 24 | import Peg.Utils 25 | 26 | import Control.Applicative 27 | import Data.List 28 | --import Control.Monad.Logic 29 | import Control.Monad.State 30 | import Data.Map (Map) 31 | import qualified Data.Map as M 32 | import Control.Arrow (second) 33 | 34 | import Debug.Trace 35 | 36 | -------------------- Converters -------------------- 37 | 38 | withArgs cI nO f = do 39 | mapM_ (getArg . (isVar ||.)) $ reverse cI 40 | i <- replicateM (length cI) popArg 41 | if any isVar i 42 | then do w@(W _) <- peekArg 43 | vs <- replicateM nO newVar 44 | appendStack vs 45 | addConstraint (vs, w : reverse i) 46 | else f i 47 | 48 | op' cI nO f = withArgs cI nO (appendStack . f) 49 | 50 | op_ nI nO = do 51 | replicateM_ nI $ getArg anything 52 | i <- replicateM nI popArg 53 | w@(W _) <- peekArg 54 | vs <- replicateM nO newVar 55 | appendStack vs 56 | addConstraint (vs, w : reverse i) 57 | 58 | op_t = do 59 | getArg anything 60 | x <- popArg 61 | w@(W _) <- peekArg 62 | v <- newVar 63 | pushStack x 64 | pushStack v 65 | addConstraint ([v, x], [w, x]) 66 | 67 | op2i_i f = op' [isInt, isInt] 1 $ \[I x, I y] -> [I $ x `f` y] 68 | op2f_f f = op' [isFloat, isFloat] 1 $ \[F x, F y] -> [F $ x `f` y] 69 | opfi_f f = op' [isFloat, isInt] 1 $ \[F x, I y] -> [F $ x `f` y] 70 | opf_f f = op' [isFloat] 1 $ \[F x] -> [F $ f x] 71 | opf_i f = op' [isFloat] 1 $ \[F x] -> [I $ f x] 72 | opi_f f = op' [isInt] 1 $ \[I x] -> [F $ f x] 73 | op2i_b f = op' [isInt, isInt] 1 $ \[I x, I y] -> [A . show $ x `f` y] 74 | op2f_b f = op' [isFloat, isFloat] 1 $ \[F x, F y] -> [A . show $ x `f` y] 75 | op2c_b f = op' [isChar, isChar] 1 $ \[C x, C y] -> [A . show $ x `f` y] 76 | op2i_2i f = op' [isInt, isInt] 2 $ \[I x, I y] -> let (u, w) = f x y in [I w, I u] 77 | 78 | isType :: (Value -> Bool) -> Peg () 79 | isType f = do 80 | getArg $ anything ||. (== W "]") ||. isVar 81 | x <- popArg 82 | pushStack x 83 | if isVar x 84 | then do w@(W _) <- peekArg 85 | --v <- newVar 86 | v <- return (A "True") `mplus` return (A "False") 87 | pushStack v 88 | addConstraint ([v], [w, x]) 89 | else pushStack . A . show $ f x 90 | 91 | -------------------- Helpers for builtins -------------------- 92 | 93 | anything (W "]") = False 94 | anything (A "[") = False 95 | anything _ = True 96 | 97 | unpackR = do 98 | getArg $ isList ||. (== W "]") ||. isVar 99 | x <- popArg 100 | case x of 101 | W "]" -> return () 102 | L l -> do pushStack $ A "[" 103 | appendStack l 104 | V v -> do pushStack $ A "[" 105 | appendStackVar v 106 | 107 | -- convert to constraint when accessing variable stack? 108 | 109 | appendStackVar v = do 110 | sv <- newSVar 111 | pushStack sv 112 | addConstraint ([L [sv]], [V v]) 113 | 114 | -- A (A -> B) -> B 115 | -- replaces stack with entirely new stack generated inductively on demand 116 | callVar v = do 117 | sv <- newSVar 118 | st <- getStack 119 | case gatherList 0 [] st of 120 | Left _ -> setStack [sv] 121 | Right (_, s) -> setStack $ sv : A "[" : s 122 | addConstraint ([L [sv]], [V v]) 123 | 124 | wordMap = foldl' (flip (uncurry minsert)) M.empty 125 | 126 | -------------------- Built-ins -------------------- 127 | 128 | -- need to parse into form [Word0 out0 in0 in1, Word1 out1 out2 in2, ...] 129 | -- infinite DAG 130 | 131 | builtins = wordMap [ 132 | 133 | -- numeric 134 | ("add_int#", op_ 2 1), 135 | ("sub_int#", op_ 2 1), 136 | ("mul_int#", op_ 2 1), 137 | ("div_int#", op_ 2 1), 138 | ("mod_int#", op_ 2 1), 139 | ("divMod_int#", op_ 2 2), 140 | ("quot_int#", op_ 2 1), 141 | ("rem_int#", op_ 2 1), 142 | ("quotRem_int#", op_ 2 2), 143 | ("pos_power_int#", op_ 2 1), 144 | ("pos_power_float#", op_ 2 1), 145 | ("int_power_float#", op_ 2 1), 146 | ("power_float#", op_ 2 1), 147 | ("exp#", op_ 1 1), 148 | ("sqrt#", op_ 1 1), 149 | ("log#", op_ 1 1), 150 | ("logBase#", op_ 2 1), 151 | ("sin#", op_ 1 1), 152 | ("tan#", op_ 1 1), 153 | ("cos#", op_ 1 1), 154 | ("asin#", op_ 1 1), 155 | ("atan#", op_ 1 1), 156 | ("acos#", op_ 1 1), 157 | ("sinh#", op_ 1 1), 158 | ("tanh#", op_ 1 1), 159 | ("cosh#", op_ 1 1), 160 | ("asinh#", op_ 1 1), 161 | ("atanh#", op_ 1 1), 162 | ("acosh#", op_ 1 1), 163 | ("add_float#", op_ 2 1), 164 | ("sub_float#", op_ 2 1), 165 | ("mul_float#", op_ 2 1), 166 | ("divide_float#", op_ 2 1), 167 | ("lt_int#", op_ 2 1), 168 | ("lte_int#", op_ 2 1), 169 | ("gt_int#", op_ 2 1), 170 | ("gte_int#", op_ 2 1), 171 | ("lt_float#", op_ 2 1), 172 | ("lte_float#", op_ 2 1), 173 | ("gt_float#", op_ 2 1), 174 | ("gte_float#", op_ 2 1), 175 | ("lt_char#", op_ 2 1), 176 | ("lte_char#", op_ 2 1), 177 | ("gt_char#", op_ 2 1), 178 | ("gte_char#", op_ 2 1), 179 | ("intToFloat#", op_ 1 1), 180 | ("round#", op_ 1 1), 181 | ("floor#", op_ 1 1), 182 | ("ceiling#", op_ 1 1), 183 | 184 | -- stack manipulation 185 | ("pop#", getArg anything >> popArg >> force), 186 | ("swap#", do getArg anything 187 | getArg anything 188 | x <- popArg 189 | y <- popArg 190 | pushStack y 191 | pushStack x), 192 | ("dup#", do getArg anything 193 | x <- popArg 194 | pushStack x 195 | pushStack x), 196 | ("<$#", do getArg anything 197 | x <- popArg 198 | pushStack $ W "$#" 199 | pushStack x), 200 | ("unpackR#", unpackR), 201 | ("$#", do getArg $ isList ||. isVar 202 | x <- popArg 203 | w <- popArg -- temporarily remove $ from the arg stack 204 | case x of 205 | L l -> appendStack l 206 | V v -> callVar v 207 | _ -> mzero 208 | force 209 | pushArg w), 210 | 211 | -- control 212 | ("seq", do getArg anything 213 | force 214 | pushStack =<< popArg), 215 | ("!", do getArg $ (== A "True") ||. isVar 216 | x <- popArg 217 | when (isVar x) $ addConstraint ([A "True"], [x]) 218 | force), 219 | 220 | -- lists 221 | ("]", do s <- getStack 222 | case gatherList 0 [] s of 223 | Left s' -> pushStack (W "]") 224 | Right (l, s') -> setStack . (:s') . L . reverse $ l), 225 | ("null?", do unpackR 226 | pushArg $ W "]" 227 | getArg $ const True 228 | x <- popArg 229 | pushStack x 230 | popArg >>= pushStack 231 | pushStack . A . show $ x == A "["), 232 | 233 | -- checks 234 | ("int?", op_t), 235 | ("float?", op_t), 236 | --("word?", isType $ isWord &&. (/= W "]")), 237 | ("word?", op_t), 238 | --("list?", isType $ isList ||. (== W "]")), 239 | ("list?", op_t), 240 | ("char?", op_t), 241 | ("io?", op_t), 242 | ("hasIO?", op_t), 243 | ("eq?", op_ 2 1), 244 | {- 245 | ("eq?", withArgs [anything, anything] 1 $ \[x, y] -> do 246 | guard . not $ isList x && isList y 247 | pushStack . A . show $ x == y), 248 | -} 249 | -- read/show 250 | ("show#", do getArg anything 251 | x <- popArg 252 | pushStack . L . map C $ showStack [x]), 253 | ("read#", do getArg isString 254 | Just s <- toString <$> popArg 255 | let Right x = parseStack s 256 | appendStack x 257 | force), 258 | 259 | -- I/O 260 | ("getChar#", do getArg isIo 261 | pushStack =<< popArg 262 | --liftIO getChar >>= 263 | v <- newVar 264 | pushStack v 265 | addConstraint ([v, Io], [W "getChar#", Io])), 266 | ("putChar#", do getArg isChar 267 | getArg isIo 268 | io <- popArg 269 | C c <- popArg 270 | --liftIO $ putChar c 271 | pushStack io 272 | addConstraint ([Io], [W "putChar#", C c, Io])), 273 | 274 | -- word definition 275 | (":def", do getArg isString 276 | getArg isList 277 | L l <- popArg 278 | Just s <- toString <$> popArg 279 | bind s l), 280 | (":undef", do getArg isString 281 | Just s <- toString <$> popArg 282 | unbind s), 283 | ("|", do getArg anything 284 | x <- popArg 285 | pushStack $ W "|" 286 | pushStack x)] 287 | -------------------------------------------------------------------------------- /Peg/Constraints.hs: -------------------------------------------------------------------------------- 1 | {- Copyright 2012 Dustin DeWeese 2 | This file is part of peg. 3 | 4 | peg is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | peg is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with peg. If not, see . 16 | -} 17 | 18 | {-# LANGUAGE ImplicitParams, MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances, OverlappingInstances #-} 19 | module Peg.Constraints where 20 | 21 | import Peg.Types 22 | import Peg.Utils 23 | import Peg.Parse (parseStack) 24 | 25 | import Control.Applicative 26 | import Control.Monad.State 27 | import Data.List 28 | import Data.Maybe 29 | import qualified Data.Map as M 30 | import Data.Map (Map) 31 | 32 | import Debug.Trace 33 | 34 | substVar :: Value -> [Value] -> Peg Bool 35 | substVar x ys = do 36 | PegState s a w n (cc, cd) b p <- get 37 | let (cp, cc') = partition (\(l, r) -> x `elem` l || x `elem` r) cc 38 | let cd' = map (\(l,r) -> (substs x ys l, substs x ys r)) $ cp ++ cd 39 | put $ PegState (substs x ys s) (substs x ys a) w n (cc', cd') b p 40 | processConstraints 41 | return True 42 | 43 | processConstraints :: Peg () 44 | processConstraints = do 45 | PegState s a w n (cc, cd) b p <- get 46 | if null cd 47 | then return () 48 | else do put $ PegState s a w n (cc, tail cd) b p 49 | addConstraint $ head cd 50 | processConstraints 51 | 52 | getConstraints :: Peg [(Stack, Stack)] 53 | getConstraints = fst . psConstraints <$> get 54 | setConstraints c = do PegState s a w n _ b p <- get 55 | put $ PegState s a w n c b p 56 | 57 | isIoPrimitive (W "getChar#") = True 58 | isIoPrimitive (W "putChar#") = True 59 | isIoPrimitive _ = False 60 | 61 | ensure x y 62 | | isVar x = substVar x [toValue y] 63 | | x `ofType` y = guard (val x == y) >> return True 64 | 65 | anti :: (ValueT a, Eq a) => String -> (a -> a -> a) -> a -> [Value] -> [Value] -> Peg Bool 66 | anti w' op i [y, x] [z] 67 | | isVar x && isVal y && isVal z = addConstraint ([x], [W w', y, z]) 68 | | isVal x && isVar y && isVal z = substVar y [toValue $ val x `op` val z] 69 | | isVal x && isVal y && isVar z = substVar z [toValue $ val x `op` val y] 70 | | x == y = ensure z i 71 | | x == z = ensure y i 72 | | y == z = addConstraint ([x], [W w', y, z]) 73 | | otherwise = return False 74 | where isVal = flip ofType i 75 | 76 | sym :: (ValueT a, Eq a) => String -> (a -> a -> a) -> a -> [Value] -> [Value] -> Peg Bool 77 | sym w' op i [y, x] [z] 78 | | isVar x && isVal y && isVal z = addConstraint ([x], [W w', y, z]) 79 | | isVal x && isVar y && isVal z = addConstraint ([x], [W w', y, z]) 80 | | isVal x && isVal y && isVar z = substVar z [toValue $ val x `op` val y] 81 | | x == y = return False -- later 82 | | x == z = ensure y i 83 | | y == z = ensure x i 84 | | otherwise = return False 85 | where isVal = flip ofType i 86 | 87 | op21 :: (ValueT a, ValueT b, ValueT c, Eq c) => (a -> b -> c) -> Value -> Value -> Value -> Peg Bool 88 | op21 op x y z 89 | | Just x' <- fromValue x, Just y' <- fromValue y = ensure z $ x' `op` y' 90 | | otherwise = return False --addConstraint' ([z], [W w, y, x]) 91 | 92 | op22 :: (ValueT a, ValueT b, ValueT c, ValueT d, Eq c, Eq d) => (a -> b -> (c, d)) -> Value -> Value -> Value -> Value -> Peg Bool 93 | op22 op x y z i 94 | | Just x' <- fromValue x, Just y' <- fromValue y = 95 | let (z', i') = x' `op` y' in ensure z z' >> ensure i i' 96 | | otherwise = return False --addConstraint' ([i, z], [W w, y, x]) 97 | 98 | op11 :: (ValueT a, ValueT b, Eq b) => (a -> b) -> Value -> Value -> Peg Bool 99 | op11 op x y 100 | | Just x' <- fromValue x = ensure y (op x') 101 | | otherwise = return False --addConstraint' ([y], [W w, x]) 102 | 103 | type IntF21 = Integer -> Integer -> Integer 104 | type IntF11 = Integer -> Integer 105 | type IntF22 = Integer -> Integer -> (Integer, Integer) 106 | 107 | class Op f where 108 | op :: f -> [Value] -> [Value] -> Peg Bool 109 | 110 | instance (ValueT a, ValueT b, Eq b) => Op (a -> b) where 111 | op f [x] [y] = op11 f x y 112 | instance (ValueT a, ValueT b, ValueT c, Eq c) => Op (a -> b -> c) where 113 | op f [y, x] [z] = op21 f x y z 114 | instance (ValueT a, ValueT b, ValueT c, ValueT d, Eq c, Eq d) => Op (a -> b -> (c, d)) where 115 | op f [y, x] [i, z] = op22 f x y z i 116 | 117 | eqC [x, y] [A "True"] 118 | | isVar x = substVar x [y] 119 | | isVar y = substVar y [x] 120 | | isList x && isList y = mzero 121 | | x == y = return True 122 | | x /= y = mzero 123 | eqC [x, y] [A "False"] 124 | | not (isVar x) && not (isVar y) = 125 | if x /= y 126 | then return True 127 | else mzero 128 | | otherwise = return False 129 | eqC [x, y] [V v] 130 | | not (isVar x) && not (isVar y) = substVar (V v) [A . show $ x == y] 131 | | otherwise = return False 132 | eqC _ _ = mzero 133 | 134 | --predC p [V v] [x, y] | V v /= y = substVar (V v) [y] >> predC p [y] [x, y] 135 | --predC p [y] [x, V v] | V v /= y = substVar (V v) [y] >> predC p [y] [x, y] 136 | predC _ [V _] [_, _] = return False 137 | predC p [x] [A "False", _] = guard (not $ p x) >> return True 138 | predC p [x] [A "True", _] = guard (p x) >> return True 139 | predC p [x] [V v, _] 140 | | not (isVar x) = substVar (V v) [A . show $ p x] 141 | | otherwise = return False 142 | predC _ _ _ = mzero 143 | 144 | poprC [h, L t] [x@(V _)] = substVar x [L $ h:t] 145 | poprC [h, t@(V _)] [x@(V _)] = substVar x [L $ [h, W "$#", t]] 146 | poprC _ _ = return False 147 | 148 | floatInt :: (Double -> Integer -> a) -> Double -> Integer -> a 149 | floatInt = id 150 | 151 | float :: (Double -> a) -> Double -> a 152 | float = id 153 | 154 | char :: (Char -> a) -> Char -> a 155 | char = id 156 | 157 | float2 :: (Double -> Double -> a) -> Double -> Double -> a 158 | float2 = id 159 | 160 | int2 :: (Integer -> Integer -> a) -> Integer -> Integer -> a 161 | int2 = id 162 | 163 | int_float :: (Integer -> Double) -> Integer -> Double 164 | int_float = id 165 | 166 | float_int :: (Double -> Integer) -> Double -> Integer 167 | float_int = id 168 | 169 | wordConstraints = M.fromList [ 170 | ("eq?", eqC), 171 | --("popr", poprC), 172 | ("add_int#", sym "sub_int#" (+) (0 :: Integer)), 173 | ("sub_int#", anti "add_int#" (-) (0 :: Integer)), 174 | ("mul_int#", sym "div_int#" (*) (1 :: Integer)), 175 | ("div_int#", anti "mul_int#" div (1 :: Integer)), 176 | ("add_float#", sym "sub_float#" (+) (0 :: Double)), 177 | ("sub_float#", anti "add_float#" (-) (0 :: Double)), 178 | ("mul_float#", sym "divide_float#" (*) (1 :: Double)), 179 | ("divide_float#", anti "mul_float#" (/) (1 :: Double)), 180 | ("mod_int#", op $ int mod), 181 | ("divMod_int#", op $ int divMod), 182 | ("quot_int#", op $ int quot), 183 | ("rem_int#", op $ int rem), 184 | ("quotRem_int#", op $ int quotRem), 185 | ("pos_power_int#", op $ int2 (^)), 186 | ("pos_power_float#", op $ floatInt (^)), 187 | ("int_power_float#", op $ floatInt (^^)), 188 | ("power_float#", op $ float2 (**)), 189 | ("exp#", op $ float exp), 190 | ("sqrt#", op $ float sqrt), 191 | ("log#", op $ float log), 192 | ("logBase#", op $ float logBase), 193 | ("sin#", op $ float sin), 194 | ("tan#", op $ float tan), 195 | ("cos#", op $ float cos), 196 | ("asin#", op $ float asin), 197 | ("atan#", op $ float atan), 198 | ("acos#", op $ float acos), 199 | ("sinh#", op $ float sinh), 200 | ("tanh#", op $ float tanh), 201 | ("cosh#", op $ float cosh), 202 | ("asinh#", op $ float asinh), 203 | ("atanh#", op $ float atanh), 204 | ("acosh#", op $ float acosh), 205 | ("lt_int#", op $ int (<)), 206 | ("lte_int#", op $ int (<=)), 207 | ("gt_int#", op $ int (>)), 208 | ("gte_int#", op $ int (>=)), 209 | ("lt_float#", op $ float (<)), 210 | ("lte_float#", op $ float (<=)), 211 | ("gt_float#", op $ float (>)), 212 | ("gte_float#", op $ float (>=)), 213 | ("lt_char#", op $ char (<)), 214 | ("lte_char#", op $ char (<=)), 215 | ("gt_char#", op $ char (>)), 216 | ("gte_char#", op $ char (>=)), 217 | ("intToFloat#", op $ int_float realToFrac), 218 | ("round#", op $ float_int round), 219 | ("floor#", op $ float_int floor), 220 | ("ceiling#", op $ float_int ceiling), 221 | ("int?", predC isInt), 222 | ("float?", predC isFloat), 223 | ("word?", predC isWord), 224 | ("list?", predC isList), 225 | ("char?", predC isChar), 226 | ("io?", predC isIo), 227 | ("hasIO?", predC $ has isIo)] 228 | 229 | int :: (Integer -> a) -> Integer -> a 230 | int = id 231 | 232 | addConstraint :: ([Value], [Value]) -> Peg Bool 233 | addConstraint (y, W w:x) | Just f <- w `M.lookup` wordConstraints = 234 | do b <- f x y 235 | when (not b) $ addConstraint' (y, W w:x) 236 | return True 237 | addConstraint ([sv@(S _)], x) 238 | = addConstraint' ([sv], x) >> return True --substSVar sv x 239 | addConstraint (l, [v@(V _)]) = substVar v l 240 | addConstraint x = addConstraint' x >> return True 241 | 242 | addConstraint' :: ([Value], [Value]) -> Peg () 243 | addConstraint' x = modify (\(PegState s a w n (cc,cd) b p) -> 244 | PegState s a w n (x:cc,cd) b p) 245 | 246 | unify' x y = do [sx, sy] <- replicateM 2 newSVar 247 | b <- unify (x ++ [sx]) (y ++ [sy]) [] 248 | mapM_ substBinding b 249 | 250 | substBinding (v@(V _), x) = substVar v [x] 251 | substBinding (s@(S _), L x) = substVar s x 252 | substBinding (L x, L y) = addConstraint (x, y) 253 | substBinding _ = error "substBinding: invalid bindings" 254 | 255 | incVarCounter = do PegState s a w n c b p <- get 256 | put $ PegState s a w (n+1) c b p 257 | return n 258 | 259 | newVar :: Peg Value 260 | newVar = V . ('_' :) . letNum <$> incVarCounter 261 | 262 | newSVar :: Peg Value 263 | newSVar = S . ('_' :) . letNum <$> incVarCounter 264 | 265 | unifyTest x y = unify x' y' [] 266 | where Right x' = parseStack x 267 | Right y' = parseStack y 268 | -------------------------------------------------------------------------------- /Peg/Monad.hs: -------------------------------------------------------------------------------- 1 | {- Copyright 2012 Dustin DeWeese 2 | This file is part of peg. 3 | 4 | peg is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | peg is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with peg. If not, see . 16 | -} 17 | 18 | {-# LANGUAGE CPP, ImplicitParams #-} 19 | module Peg.Monad (module Peg.Monad, newVar, newSVar) where 20 | 21 | import Peg.Types 22 | import Peg.Parse 23 | import qualified Peg.Constraints as C 24 | import Peg.Constraints (newVar, newSVar) 25 | import Peg.Utils 26 | 27 | import Control.Applicative 28 | import Control.Monad.State 29 | import Data.Map (Map) 30 | import qualified Data.Map as M 31 | import Control.Exception 32 | import Data.List 33 | import Data.Char (toUpper) 34 | 35 | import Debug.Trace 36 | 37 | -- | pop an argument from the stack, push onto argument stack 38 | getArg check = do 39 | force 40 | x <- popStack 41 | guard $ check x 42 | pushArg x 43 | 44 | pushStack x = modify (\(PegState s a w n c b p) -> PegState (x:s) a w n c b p) 45 | appendStack x = modify (\(PegState s a w n c b p) -> PegState (x++s) a w n c b p) 46 | 47 | popStack :: Peg Value 48 | popStack = do PegState s a w n c b p <- get 49 | guard . not $ null s 50 | put $ PegState (tail s) a w n c b p 51 | return $ head s 52 | 53 | emptyStack :: Peg Bool 54 | emptyStack = null . psStack <$> get 55 | 56 | setStack s = modify (\(PegState _ a w n c b p) -> PegState s a w n c b p) 57 | 58 | getStack :: Peg Stack 59 | getStack = psStack <$> get 60 | 61 | pushArg x = modify (\(PegState s a w n c b p) -> PegState s (x:a) w n c b p) 62 | 63 | popArg :: Peg Value 64 | popArg = do PegState s (x:a) w n c b p <- get 65 | put $ PegState s a w n c b p 66 | return x 67 | 68 | peekArg :: Peg Value 69 | peekArg = do PegState s (x:a) w n c b p <- get 70 | return x 71 | 72 | pushAnc x = modify $ \(PegState s a w n c b p) -> PegState s a w n c b (x:p) 73 | popAnc :: Peg Stack 74 | popAnc = do PegState s a w n c b (x:p) <- get 75 | put $ PegState s a w n c b p 76 | return x 77 | hidingAnc f = popAnc >>= \a -> f >> pushAnc a 78 | hidingAllAnc f = do PegState s a w n c b p <- get 79 | put $ PegState s a w n c b [] 80 | f 81 | PegState s' a' w' n' c' b' p' <- get 82 | put $ PegState s' a' w' n' c' b' p 83 | 84 | varBind vn x = modify $ \(PegState s a w n c b p) -> 85 | PegState s a w n c (M.insert vn x b) p 86 | 87 | getVarBindings :: Peg (Map String Value) 88 | getVarBindings = psBindings <$> get 89 | 90 | substStack :: Stack -> Peg Stack 91 | substStack s = flip map s . f <$> getVarBindings 92 | where f m (V n) | Just x <- n `M.lookup` m = x 93 | f _ x = x 94 | 95 | doWord w = do --checkUnify $ do 96 | popStack 97 | m <- psWords <$> get 98 | pushArg (W w) 99 | case w `M.lookup` m of 100 | Nothing -> mzero 101 | Just [x] -> x 102 | Just x -> msum x 103 | popArg 104 | return () 105 | 106 | substAll bs x = foldr f x bs 107 | where f (v@(V _), x) = substs v [x] 108 | f (s@(S _), L x) = substs s x 109 | f _ = id 110 | 111 | checkUnify :: Peg () -> Peg () 112 | checkUnify m = do 113 | PegState s _ _ _ _ _ p <- get 114 | if topIs (isList ||. (== W "]")) s 115 | then m 116 | else case maybeAny (\x -> ((,) x) <$> unify (trim isStackVar s) (x ++ [S "_rest"]) []) p of 117 | Nothing -> --trace (show $ map showStack p) $ 118 | pushAnc s >> m >> popAnc >> return () 119 | Just (s', b) -> do sv <- newSVar 120 | trace (showStack s ++ " == " ++ 121 | showStack s') $ return () 122 | trace (show b) $ return () 123 | setStack [sv] 124 | addConstraint ([sv], substAll b s') 125 | mapM_ substBinding b 126 | --where unifyS a b = trace (showStack a ++ " == " ++ showStack b) $ unify a b 127 | 128 | substBinding = let ?eval = eval in C.substBinding 129 | 130 | trim p [x] | p x = [] 131 | | otherwise = [x] 132 | trim _ [] = [] 133 | trim p (x:xs) = x : trim p xs 134 | 135 | 136 | addConstraint x = let ?eval = eval in C.addConstraint x >> return () 137 | substVar = let ?eval = eval in C.substVar 138 | 139 | force = do 140 | st <- get 141 | case psStack st of 142 | (W w : _) -> doWord w 143 | #ifdef DEBUG 144 | >> traceStack 145 | #endif 146 | (S s : _) -> (popStack >> addConstraint ([S s], [])) `mplus` do 147 | v <- newVar 148 | s' <- newSVar 149 | popStack 150 | pushStack s' 151 | pushStack v 152 | addConstraint ([v, s'], [S s]) 153 | _ -> return () 154 | 155 | bind nm l = modify $ \(PegState s a w n c b p) -> 156 | PegState s a (minsert nm (f l) w) n c b p 157 | where f l = do w <- popArg 158 | --appendStack l 159 | pushStack $ L l 160 | pushStack $ W "$#" 161 | force 162 | pushArg w 163 | 164 | unbind nm = modify $ \(PegState s a w n c b p) -> PegState s a (M.delete nm w) n c b p 165 | 166 | eval s' = do 167 | st@(PegState s a w n c b p) <- get 168 | put $ PegState s' [] w n c b p 169 | force 170 | s'' <- getStack 171 | put st 172 | return s'' 173 | -------------------------------------------------------------------------------- /Peg/Parse.hs: -------------------------------------------------------------------------------- 1 | {- Copyright 2012 Dustin DeWeese 2 | This file is part of peg. 3 | 4 | peg is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | peg is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with peg. If not, see . 16 | -} 17 | 18 | module Peg.Parse where 19 | 20 | import Peg.Types 21 | 22 | import Control.Applicative 23 | import Debug.Trace 24 | import Text.Parsec hiding ((<|>), many, optional) 25 | import Text.Parsec.String 26 | import qualified Text.Parsec.Token as P 27 | import Text.Parsec.Language (haskellDef) 28 | import Control.Monad.State 29 | 30 | lexer = P.makeTokenParser haskellDef 31 | 32 | integer = P.integer lexer 33 | float = P.float lexer 34 | naturalOrFloat = P.naturalOrFloat lexer 35 | natural = P.natural lexer 36 | whiteSpace = P.whiteSpace lexer 37 | charLiteral = P.charLiteral lexer 38 | stringLiteral = P.stringLiteral lexer 39 | 40 | word :: Parser Value 41 | word = W <$> ((:) <$> (lower <|> char ':') <*> many (alphaNum <|> oneOf "?_'#")) 42 | 43 | atom :: Parser Value 44 | atom = A <$> (((:) <$> upper <*> many (alphaNum <|> oneOf "?_'#")) <|> 45 | ((:[]) <$> oneOf "[_")) 46 | 47 | var :: Parser Value 48 | var = V <$> (char '?' *> many1 (alphaNum <|> char '_')) 49 | 50 | svar :: Parser Value 51 | svar = S <$> (char '@' *> many1 (alphaNum <|> char '_')) 52 | 53 | symbol :: Parser Value 54 | symbol = W <$> (many1 (oneOf "!@#$%^&*()-+=<>.~/?\\|") <|> 55 | fmap (:[]) (oneOf "]{};")) 56 | 57 | quote :: Parser Value 58 | quote = L . (:[]) <$> (char '`' *> value) 59 | 60 | number :: Parser Value 61 | number = do m <- optionMaybe (char '-') 62 | let f = maybe (either I F) 63 | (const $ either (I . negate) (F . negate)) m 64 | f <$> naturalOrFloat 65 | 66 | value :: Parser Value 67 | value = try number <|> 68 | try var <|> 69 | try svar <|> 70 | try symbol <|> 71 | word <|> 72 | atom <|> 73 | C <$> charLiteral <|> 74 | L . map C <$> stringLiteral <|> 75 | quote 76 | 77 | comment = string "--" >> many (noneOf "\n") 78 | 79 | stackExpr :: Parser Stack 80 | stackExpr = concatMap f . reverse <$> (whiteSpace >> value `sepEndBy` whiteSpace <* optional comment) 81 | where f (W "{") = [A "[", A "["] 82 | f (W "}") = [W "]", W "]"] 83 | f (W ";") = [A "[", W "]"] 84 | f x = [x] 85 | 86 | showStack :: Stack -> String 87 | showStack s = drop 1 $ loop s [] 88 | where loop [] = id 89 | loop (I x : s) = loop s . (' ':) . shows x 90 | loop (C x : s) = loop s . (' ':) . shows x 91 | loop (F x : s) = loop s . (' ':) . shows x 92 | loop (W x : s) = loop s . ((' ':x) ++) 93 | loop (A x : s) = loop s . ((' ':x) ++) 94 | loop (V x : s) = loop s . ((' ':'?':x) ++) 95 | loop (S x : s) = loop s . ((' ':'@':x) ++) 96 | loop (Io : s) = loop s . (" IO" ++) 97 | loop (L [] : s) = loop s . (" [ ]" ++) 98 | loop (L x : s) = case toString (L x) of 99 | Just str -> loop s . (' ':) . shows str 100 | Nothing -> case toQuote (L x) of 101 | Just str -> loop s . (' ':) . (str ++) 102 | Nothing -> loop s . (" [" ++) . loop x . (" ]" ++) 103 | 104 | toQuote (L [x]) | isList x = ('`':) <$> toQuote x 105 | | otherwise = Just ('`' : showStack [x]) 106 | toQuote _ = Nothing 107 | 108 | parseStack = parse stackExpr "" 109 | 110 | -------------------- Debug -------------------- 111 | 112 | probe s x = trace (s ++ show x) x 113 | 114 | traceStack :: Peg () 115 | traceStack = do 116 | s <- psStack <$> get 117 | when (not $ null s) . trace (showStack s) $ return () 118 | -------------------------------------------------------------------------------- /Peg/Types.hs: -------------------------------------------------------------------------------- 1 | {- Copyright 2012 Dustin DeWeese 2 | This file is part of peg. 3 | 4 | peg is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | peg is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with peg. If not, see . 16 | -} 17 | 18 | module Peg.Types where 19 | 20 | import Control.Applicative 21 | import Data.Maybe 22 | import Control.Monad.State 23 | import Data.Set (Set) 24 | import qualified Data.Set as S 25 | import Data.Map (Map) 26 | import qualified Data.Map as M 27 | 28 | import Search 29 | 30 | type Stack = [Value] 31 | type Env = Map String [Peg ()] 32 | data PegState = PegState { psStack :: Stack, 33 | psArgStack :: Stack, 34 | psWords :: Env, 35 | psUniqueVarCounter :: Int, 36 | psConstraints :: ([(Stack, Stack)], [(Stack, Stack)]), 37 | psBindings :: Map String Value, 38 | psAncestors :: [Stack] } 39 | type Peg = StateT PegState Tree 40 | data Rule = Rule { getRule :: Stack -> Peg Stack } 41 | data Value = F Double -- float 42 | | I Integer -- integer 43 | | C Char -- character 44 | | L Stack -- stack 45 | | W String -- word 46 | | A String -- atom 47 | | V String -- variable 48 | | S String -- stack variable 49 | | Io -- I/O token 50 | deriving (Show, Eq, Ord) 51 | 52 | isWord (W _) = True 53 | isWord _ = False 54 | 55 | isAtom (A _) = True 56 | isAtom _ = False 57 | 58 | isInt (I _) = True 59 | isInt _ = False 60 | 61 | isChar (C _) = True 62 | isChar _ = False 63 | 64 | isList (L _) = True 65 | isList _ = False 66 | 67 | isFloat (F _) = True 68 | isFloat _ = False 69 | 70 | toString :: Value -> Maybe String 71 | toString (L l) = loop l 72 | where loop [] = return "" 73 | loop (C c : r) = (c:) <$> loop r 74 | loop _ = mzero 75 | toString _ = mzero 76 | 77 | isString = isJust . toString 78 | 79 | isIo Io = True 80 | isIo _ = False 81 | 82 | isVar (V _) = True 83 | isVar _ = False 84 | 85 | isStackVar (S _) = True 86 | isStackVar _ = False 87 | 88 | has p (L l) = any (has p) l 89 | has p x = p x 90 | 91 | class ValueT a where 92 | toValue :: a -> Value 93 | fromValue :: Value -> Maybe a 94 | 95 | instance ValueT Double where 96 | toValue = F 97 | fromValue (F x) = Just x 98 | fromValue _ = Nothing 99 | 100 | instance ValueT Integer where 101 | toValue = I 102 | fromValue (I x) = Just x 103 | fromValue _ = Nothing 104 | 105 | instance ValueT Char where 106 | toValue = C 107 | fromValue (C x) = Just x 108 | fromValue _ = Nothing 109 | 110 | instance ValueT Bool where 111 | toValue = A . show 112 | fromValue (A "True") = Just True 113 | fromValue (A "False") = Just False 114 | fromValue _ = Nothing 115 | 116 | instance (ValueT a) => ValueT [a] where 117 | toValue = L . map toValue 118 | fromValue (L x) = mapM fromValue x 119 | fromValue _ = Nothing 120 | 121 | ofType :: (ValueT a) => Value -> a -> Bool 122 | ofType v x = isJust $ fromValue v `asTypeOf` Just x 123 | 124 | val :: (ValueT a) => Value -> a 125 | val = fromJust . fromValue 126 | 127 | -------------------------------------------------------------------------------- /Peg/Utils.hs: -------------------------------------------------------------------------------- 1 | {- Copyright 2012 Dustin DeWeese 2 | This file is part of peg. 3 | 4 | peg is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | peg is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with peg. If not, see . 16 | -} 17 | 18 | module Peg.Utils where 19 | 20 | import Peg.Types 21 | 22 | import Control.Monad 23 | import Data.Map (Map) 24 | import qualified Data.Map as M 25 | 26 | a `dig` b = dig' a b [] 27 | where dig' a b c | a == 0 = c 28 | | otherwise = dig' d b (m:c) 29 | where (d, m) = a `divMod` b 30 | 31 | a `ldig` b = dig' a b [] 32 | where dig' a b c | a == 0 = c 33 | | otherwise = dig' d b (m:c) 34 | where (d, m) = (a-1) `divMod` b 35 | 36 | 37 | letNum :: Int -> String 38 | letNum x | x <= 0 = "a" 39 | | otherwise = map (toEnum . (+a)) . (`ldig` 26) $ x + 1 40 | where a = fromEnum 'a' 41 | 42 | topIs _ [] = False 43 | topIs f (x:_) = f x 44 | 45 | (f ||. g) x = f x || g x 46 | (f &&. g) x = f x && g x 47 | 48 | minsert k x = M.insertWith (++) k [x] 49 | mlookup k = maybe [] id . M.lookup k 50 | 51 | 52 | maybeAny _ [] = Nothing 53 | maybeAny f (x:xs) = case f x of 54 | Nothing -> maybeAny f xs 55 | r -> r 56 | 57 | unify [] [] b = return b 58 | unify (s@(S _):_) ys b = updateBindings s (L ys) b 59 | unify xs (s@(S _):_) b = updateBindings s (L xs) b 60 | unify [] _ b = mzero 61 | unify _ [] b = mzero 62 | unify (V x:xs) (y:ys) b | not (isWord y) = 63 | unify (subst (V x) y xs) ys =<< updateBindings (V x) y b 64 | unify (x:xs) (V y:ys) b | not (isWord x) = 65 | unify xs (subst (V y) x ys) =<< updateBindings (V y) x b 66 | unify (L x:xs) (L y:ys) b = unify xs ys =<< unify x y b 67 | unify (L x:xs) (W "]":ys) b = 68 | case gatherList 0 [] ys of 69 | Left _ -> mzero 70 | Right (y', ys') -> unify (L x:xs) (L (reverse y'):ys') b 71 | unify (W "]":xs) (L y:ys) b = 72 | case gatherList 0 [] xs of 73 | Left _ -> mzero 74 | Right (x', xs') -> unify (L (reverse x'):xs') (L y:ys) b 75 | unify (x:xs) (y:ys) b 76 | | x == y = unify xs ys b 77 | --unify xs ys@(W _:_) b | not $ any isWord xs = return $ (L xs, L ys) : b 78 | --unify xs@(W _:_) ys b | not $ any isWord ys = return $ (L ys, L xs) : b 79 | unify _ _ _ = mzero 80 | 81 | subst1 a b (L xs) = L (subst a b xs) 82 | subst1 a b x | a == x = b 83 | | otherwise = x 84 | 85 | occurs a (L bs) = any (occurs a) bs 86 | occurs a b = a == b 87 | 88 | updateBindings v x b = do 89 | guard . not $ occurs v x 90 | b' <- mapM (\(a, z) -> let z' = subst1 v x z in 91 | guard (not $ occurs v z') >> return (a, z')) b 92 | return $ (v,x) : b 93 | 94 | gatherList n l (w@(W "]") : s) = gatherList (n+1) (w:l) s 95 | gatherList n l (w@(A "[") : s) 96 | | n <= 0 = Right (l,s) 97 | | otherwise = gatherList (n-1) (w:l) s 98 | gatherList n l (w:s) = gatherList n (w:l) s 99 | gatherList n l [] = Left l 100 | 101 | subst a b xs = map f xs 102 | where f (L xs) = L $ subst a b xs 103 | f x | x == a = b 104 | | otherwise = x 105 | 106 | substs a bs xs = concatMap f xs 107 | where f (L xs) = [L $ substs a bs xs] 108 | f x | x == a = bs 109 | | otherwise = [x] 110 | -------------------------------------------------------------------------------- /QuadMatrix.hs: -------------------------------------------------------------------------------- 1 | {- Copyright 2012 Dustin DeWeese 2 | This file is part of peg. 3 | 4 | peg is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | peg is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with peg. If not, see . 16 | -} 17 | 18 | {-# LANGUAGE PatternGuards, FlexibleContexts #-} 19 | module QuadMatrix (QuadMatrix(..), qDim, qmatrix, (@>), (!@), (.@), foldrI, foldlI, minimumI, maximumI, (/@), (\@), qAccum, ZeroRule(..), printQMat, showQMat, tileSort, log2, qSeq) where 20 | 21 | import Data.Bits 22 | import Control.Monad 23 | import Data.List 24 | import Data.Maybe 25 | import Data.Bits 26 | 27 | import qualified Debug.Trace as T 28 | 29 | 30 | pad n s | l >= n = take n s 31 | | otherwise = replicate (n-l) ' ' ++ s 32 | where l = length s 33 | 34 | log2 x | x < 1 = error "log2 not defined for x < 1" 35 | | otherwise = snd . until ((==1) . fst) (\(x, n) -> (x `shiftR` 1, n + 1)) $ (x-1, 1) 36 | 37 | data QuadMatrix a = QuadMatrix !(Int, Int) !Int !(QuadMatrix' a) deriving (Show) 38 | data QuadMatrix' a = Quad !(QuadMatrix' a) !(QuadMatrix' a) !(QuadMatrix' a) !(QuadMatrix' a) | 39 | Element !a | 40 | Zero deriving (Show) 41 | 42 | printQMat w a = putStrLn $ showQMat w a 43 | 44 | showQMat w a = "\n" ++ replicate w ' ' ++ concatMap (\j -> ' ' : pad w ("["++show j++"]")) [0..n-1] ++ "\n" ++ 45 | concatMap (\i-> pad w ("["++show i++"]") ++ 46 | concatMap (\j -> ' ' : pad w (show (a@>(i,j)))) [0..n-1] ++ "\n") [0..m-1] 47 | where (m, n) = qDim a 48 | 49 | qSeq (QuadMatrix (m, n) l q) x = m `seq` n `seq` l `seq` q `qSeq'` x 50 | 51 | qSeq' Zero x = x 52 | qSeq' (Element e) x = e `seq` x 53 | qSeq' (Quad a b c d) x = a `seq` b `seq` c `seq` d `seq` x 54 | 55 | qDim (QuadMatrix d _ _) = d 56 | 57 | qmatrix (m,n) = QuadMatrix (m, n) l Zero 58 | where l = log2 (max m n) 59 | 60 | -- NOTE FOR FUNCTIONS TAKING A LIST OF ELEMENTS 61 | -- they will be returned tile sorted (sorted as if the bits of the row and 62 | -- column index were interleaved) 63 | 64 | q @> e = snd . head $ q !@ [e] 65 | q !@ es = foldrI IncludeZero (:) [] q es 66 | q .@ es = foldrI ExcludeZero (:) [] q es 67 | 68 | data ZeroRule = IncludeZero | ExcludeZero deriving (Show, Eq) 69 | 70 | foldrI :: (Num b) => ZeroRule -> (((Int, Int), b) -> a -> a) -> a -> QuadMatrix b -> [(Int, Int)] -> a 71 | foldrI z f s q es = d q' l es s 72 | where (QuadMatrix (m, n) l q') = q 73 | d _ _ [] s = s 74 | d (Element e) l [ij] s = f (ij, e) s 75 | d Zero l es s | z == ExcludeZero = s 76 | | otherwise = foldr f s [ (ij, 0) | ij <- es ] 77 | d (Quad x00 x01 x10 x11) l es s = d x00 (l-1) es00 . 78 | d x01 (l-1) es01 . 79 | d x10 (l-1) es10 . 80 | d x11 (l-1) es11 $ s 81 | where (es00, es01, es10, es11) = quadSplit id (l-1) es 82 | 83 | foldlI :: (Num b) => ZeroRule -> (a -> ((Int, Int), b) -> a) -> a -> QuadMatrix b -> [(Int, Int)] -> a 84 | foldlI z f s q es = d q' l es s 85 | where (QuadMatrix (m, n) l q') = q 86 | d _ _ [] s = s 87 | d (Element e) l [ij] s = f s (ij, e) 88 | d Zero l es s | z == ExcludeZero = s 89 | | otherwise = foldl f s [ (ij, 0) | ij <- es ] 90 | d (Quad x00 x01 x10 x11) l es s = d x11 (l-1) es11 . 91 | d x10 (l-1) es10 . 92 | d x01 (l-1) es01 . 93 | d x00 (l-1) es00 $ s 94 | where (es00, es01, es10, es11) = quadSplit id (l-1) es 95 | 96 | minimumI z q es = foldlI z (\m a@(_, ax) -> Just $ maybe a (\b@(_, bx) -> if ax < bx then a else b) m) Nothing q es 97 | maximumI z q es = foldlI z (\m a@(_, ax) -> Just $ maybe a (\b@(_, bx) -> if ax > bx then a else b) m) Nothing q es 98 | 99 | q /@ es = QuadMatrix (m,n) l (accumQ IncludeZero (\_ _ x -> x) q' l es) 100 | where (QuadMatrix (m, n) l q') = q 101 | 102 | q \@ es = QuadMatrix (m,n) l (accumQ ExcludeZero (\_ _ x -> x) q' l es) 103 | where (QuadMatrix (m, n) l q') = q 104 | 105 | {-# SPECIALIZE accumQ :: ZeroRule -> ((Int, Int) -> Double -> Double -> Double) -> QuadMatrix' Double -> Int -> [((Int, Int), Double)] -> QuadMatrix' Double #-} 106 | accumQ :: (Num e) => ZeroRule -> ((Int, Int) -> e -> a -> e) -> QuadMatrix' e -> Int -> [((Int, Int), a)] -> QuadMatrix' e 107 | accumQ _ _ q _ [] = q 108 | accumQ z f (Element e) l [(ij, x)] | e' == 0 = Zero 109 | | otherwise = Element e' 110 | where e' = f ij e x 111 | accumQ z f Zero l es | z == ExcludeZero = Zero 112 | | l <= 0 = if e' == 0 then Zero else Element e' 113 | | otherwise = collapse $ accumQ z f (Quad Zero Zero Zero Zero) l es 114 | where e' = f ij 0 x 115 | [(ij, x)] = es 116 | accumQ z f (Quad x00 x01 x10 x11) l es = collapse $ Quad (accumQ z f x00 (l-1) es00) 117 | (accumQ z f x01 (l-1) es01) 118 | (accumQ z f x10 (l-1) es10) 119 | (accumQ z f x11 (l-1) es11) 120 | where (es00, es01, es10, es11) = quadSplit fst (l-1) es 121 | 122 | --diff xs ys = (filter (not . (`elem` ys)) xs, filter (not . (`elem` xs)) ys) 123 | 124 | collapse q | Quad Zero Zero Zero Zero <- q = Zero 125 | | otherwise = q 126 | 127 | qMapI z f q es = QuadMatrix (m,n) l (accumQ z (\_ x _ -> f x) q' l (zip es (repeat ()))) 128 | where (QuadMatrix (m, n) l q') = q 129 | 130 | qMap z f q = qMapI z f q [ (i, j) | i <- [0..m-1], j <- [0..n-1] ] 131 | where (m, n) = qDim q 132 | 133 | qAccum :: (Num a) => ZeroRule -> (a -> b -> a) -> QuadMatrix a -> [((Int, Int), b)] -> QuadMatrix a 134 | {-# SPECIALIZE qAccum :: ZeroRule -> (Double -> Double -> Double) -> QuadMatrix Double -> [((Int, Int), Double)] -> QuadMatrix Double #-} 135 | qAccum z f q es = QuadMatrix (m, n) l (accumQ z (\_ x y -> f x y) q' l es) 136 | where (QuadMatrix (m, n) l q') = q 137 | 138 | tileSort f es = tileSort' f l es [] 139 | where (m, n) = foldl (\(m, n) e -> let (i, j) = f e in (max m i, max n j)) (0, 0) es 140 | l = log2 (max m n + 1) 141 | 142 | 143 | --tileSort' :: (a -> (Int, Int)) -> Int -> Int -> [a] -> [a] -> [a] 144 | tileSort' _ _ [] r = r 145 | tileSort' f l es r | l <= 0 = es ++ r 146 | | otherwise = tileSort' f (l-1) es00 . 147 | tileSort' f (l-1) es01 . 148 | tileSort' f (l-1) es10 . 149 | tileSort' f (l-1) es11 $ r 150 | where (es00, es01, es10, es11) = quadSplit f l es 151 | 152 | --quadSplit :: (a -> (Int, Int)) -> Int -> [a] -> ([a], [a], [a], [a]) 153 | quadSplit f l es = foldl' split ([], [], [], []) es 154 | where split (es00, es01, es10, es11) e = 155 | if testBit i l 156 | then if testBit j l 157 | then (es00, es01, es10, e:es11) 158 | else (es00, es01, e:es10, es11) 159 | else if testBit j l 160 | then (es00, e:es01, es10, es11) 161 | else (e:es00, es01, es10, es11) 162 | where (i, j) = f e 163 | {- 164 | quadSplit f l es = foldr split ([], [], [], []) es 165 | where split e (es00, es01, es10, es11) = 166 | if i < 0 167 | then if j < 0 168 | then (e:es00, e:es01, e:es10, e:es11) 169 | else if testBit j l 170 | then (es00, e:es01, es10, e:es11) 171 | else (e:es00, es01, e:es10, es11) 172 | else if j < 0 173 | then if testBit i l 174 | then (es00, es01, e:es10, e:es11) 175 | else (e:es00, e:es01, es10, es11) 176 | else if testBit i l 177 | then if testBit j l 178 | then (es00, es01, es10, e:es11) 179 | else (es00, es01, e:es10, es11) 180 | else if testBit j l 181 | then (es00, e:es01, es10, es11) 182 | else (e:es00, es01, es10, es11) 183 | where (i, j) = f e 184 | -} 185 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Peg Programming Language 2 | ======================== 3 | 4 | **Note** 5 | -------- 6 | 7 | Progress has stopped on this interpreter in order to work on a compiler. The language has also changed somewhat as I've worked on the compiler. 8 | 9 | See the [pegc project](https://github.com/HackerFoo/pegc) for more information on the compiler (which also implements an interpreter). 10 | 11 | Overview 12 | -------- 13 | 14 | Peg is a lazy non-deterministic concatenative programming language inspired by Haskell, Joy, and Prolog. 15 | 16 | In contrast to most concatenative programming languages, Peg starts evaluation from the right, evaluating arguments to the left as needed. 17 | 18 | For example, even though the word `no` can never be resolved: 19 | 20 | no 1 2 + --> no 3 21 | 22 | This is because `+` requires only two arguments on the stack. 23 | 24 | Another demonstration of laziness: 25 | 26 | 0 [1+] iterate 27 | 28 | This creates the infinite stack `.. 3 2 1 0`. Try `pop`ing a few times to see how it works. 29 | 30 | Branching is accomplished with the choice operator `\/`. Both paths are followed non-deterministically. Paths are terminated when a word cannot be resolved. 31 | 32 | Multiple definitions for a word cause the definitions to be substituted non-deterministically. This allows words (even built-in words) to be extended for new types. 33 | 34 | For example, to extend `sqrt` to operate on the word `Four`: 35 | 36 | [Four eq? Two swap !] "sqrt" :def 37 | 38 | A word can only be resolved if the word can operate on its arguments. The built-in word `!` can only be resolved on the argument `True`. `ifte` is provided as part of the library. 39 | 40 | [ 1 ] 2 \/ popr --> [ ] 1 41 | 42 | The basic types are integers, floats, characters, words, and stacks. As with the top level stack, these stacks are evaluated lazily. Stacks are 'live', and will be evaluated as demanded, by such words as `popr`. There is no way to directly extract an item from the left, and there is no way to extract an item without evaluation. 43 | 44 | [1 2 3 4 +] popr --> [1 2] 7 45 | 46 | A string literal is a stack consisting only of characters. They are read and displayed backwards from stacks, to make them readable. 47 | 48 | ['o' 'l' 'l' 'e' 'h'] --> "hello" 49 | "hello" 0 pushr --> ['o' 'l' 'l' 'e' 'h' 0] 50 | 51 | A quoted value is another notation for a stack with a single element: 52 | 53 | [1] --> `1 54 | [] `2 pushr --> ``2 55 | 56 | Peg is flat, in that any expression can be divided on white space (except inside a literal), the pieces evaluated independently, and when the results are concatenated, evaluate to an equivalent expression to the original expression. 57 | 58 | Example: 59 | 60 | [ 1 2 + ] popr --> [ ] 3 61 | [ 1 2 + --> [ 3 62 | ] popr --> ] popr 63 | [ 3 ] popr --> [ ] 3 64 | 65 | Instead of using a monad to implement pure functional I/O, Peg simply uses a token representing the state of the world, `IO`. Words that perform I/O always require `IO` as an argument, and put it back afterwards. 66 | 67 | `IO` can only be introduced from the top-level, by typing `IO`. In other places, such as definitions and `read`, `IO` is parsed as a word with no special meaning. 68 | 69 | A variable in Peg appears as a string of lowercase letters preceded by `?`, such as `?x`. A Peg variable is a logical variable. A flexible typing system is provided in Peg in the form of constraints. The type of a variable is its set of constraints. This allows any predicate to be used as a type. 70 | 71 | If the constraints can be narrowed to a finite number of values, these values will be substituted for the variable. 72 | 73 | ?x ?y / --> ?_a 74 | -- constraints representing the type of / 75 | -- True <-- ?y float? 76 | -- True <-- ?x float? 77 | -- ?_a <-- ?x ?y divide_float# 78 | -- True <-- ?_a float? 79 | ?x dup 2 + 5 eq? ! --> 3 80 | ?x dup 4 div 3 eq?! dup 5 mod 0 eq?! --> 15 81 | 82 | 83 | Built-in Words 84 | -------------- 85 | 86 | The format below is: 87 | 88 | `input stack` `word` --> `output stack` \/ `alternate output stack` -- notes 89 | 90 | -------------------------------- 91 | 92 | `x` `pop` --> 93 | 94 | `x` `y` `swap` --> `y` `x` 95 | 96 | `x` `dup` --> `x` `x` 97 | 98 | `A` `x` `f` `dip` --> `B` `x` -- applies f to stack under x 99 | 100 | `[` `xn` .. `x0` `]` --> `[xn .. x0]` -- gathers stack items into a list until `[` if possible 101 | 102 | `[ .. ]` `x` `pushr` --> `[ .. x]` 103 | 104 | `[ .. x]` `popr` --> `[ .. ]` `x` -- forces evaluation of `x` 105 | 106 | `[ .. x]` `[y ..]` `.` --> `[ .. x y .. ]` -- concatenates stacks without evaluating anything 107 | 108 | `[ .. ]` `null?` --> `[ .. ]` (`True` \/ `False`) -- indicates if the stack is empty, works on partial stacks 109 | 110 | `True` `!` --> -- only resolves if the argument is `True` 111 | 112 | `x` `y` `\/` --> `x` \/ `y` -- continues execution non-deterministically with `x` and `y` 113 | 114 | `int?`, `float?`, `word?`, `list?`, `char?`, `string?` -- test type of argument, returning `True` or `False` 115 | 116 | `x` `y` `eq?` --> `True` \/ `False` -- is `x` a primitive type (non-stack) equal to `y` (also not a stack) 117 | 118 | `[ .. ]` `"word-name"` `:def` --> -- define the word `word-name` to be equivalent to the stack argument 119 | 120 | `"word-name"` `:undef` --> -- undefine the word `word-name` 121 | 122 | `[ .. ]` `$` --> ` .. ` -- append stack argument to upper level stack and execute 123 | 124 | `x` `y` `seq` --> `x` `y` -- force evaluation of `x` 125 | 126 | `x` `show` --> `"x"` -- convert `x` into string representation 127 | 128 | `"x"` `read` --> `x` -- convert string representation of `x` into `x`, opposite of `show` 129 | 130 | `+`, `-`, `*`, `div`, `mod`, `divMod`, `quot`, `rem`, `quotRem`, `^`, `^^`, `**`, `exp`, `sqrt`, `log`, `logBase`, `sin`, `tan`, `cos`, `asin`, `atan`, `acos`, `sinh`, `tanh`, `cosh`, `asinh`, `atanh`, `acosh`, `<`, `<=`, `>`, `>=`, `realToFrac`, `round`, `floor`, `ceiling` -- numeric and comparison words defined as in Haskell Prelude 131 | 132 | `getChar`, `putChar`, `getLine`, `putStr`, `putStrLn` -- similar to Haskell Prelude. Instead of running in IO monad, they require `IO` as the first argument, putting it back after executing 133 | 134 | A simple IO example: 135 | 136 | IO "What's your name?" putStrLn getLine "!" "Hello " splice putStrLn 137 | 138 | Peg supports a curly bracket notation to allow for case statements and do-notation. Curly braces trivially reduce to a nested stack. 139 | 140 | `{` --> `[` `[` 141 | 142 | `;` --> `]` `[` 143 | 144 | `}` --> `]` `]` 145 | 146 | Usage with `case`: 147 | 148 | b {1 a; 2 b} case --> 2 149 | 150 | Library: lib.peg 151 | ---------------- 152 | 153 | Most words are based on the Haskell Prelude, some stack combinators are taken from Joy. 154 | 155 | `foldr` and `foldl` are swapped from the Haskell definitions, because "lists" are stacks, and elements are added to the right side of a stack. Similarly for `scanr` and `scanl`. 156 | 157 | Most of the Haskell Prelude is implemented, except words that aren't very useful or are replaced by a built-in word. 158 | 159 | Running the Peg Interpreter 160 | --------------------------- 161 | 162 | Build the interpreter using Cabal (`cabal configure; cabal build`). Alternatively, the latest released version can be installed with `cabal install`. 163 | 164 | Just call the `peg` executable with source files to be loaded (such as lib.peg) as arguments. 165 | 166 | The interpreter evaluates the input after pressing `Enter`. The results will be printed after the next prompt, allowing you to edit the results. If the cursor is not on the right, a word did not have enough arguments to be evaluated; the cursor will be placed so that you can provide the missing arguments. If there are multiple results, several of the results will be printed, but only the first will appear at the prompt. If there are no results, the input expression is return, which is trivially equivalent to itself. 167 | 168 | [Haskeline](http://hackage.haskell.org/package/haskeline) provides the line editing interface. Clearing the input and pressing `Enter` will exit the interpreter. 169 | 170 | Future 171 | ------ 172 | 173 | ### I/O 174 | 175 | I have tried modeling I/O after Haskell's monad approach, but monads seem to be better suited to applicative languages, despite being possible in a concatenative language. 176 | 177 | I have implemented a different method of performing I/O in a pure functional way, as described above (I/O words require an `IO` token.) 178 | 179 | ### Type System 180 | 181 | The current idea is to use explicit type checks (such as `int?`) instead of introducing a different syntax for type annotations. This would allow the type system to be extended using the base language, and support dependent typing. It would also allow optional run time typing. 182 | 183 | The interpreter is currently dynamically typed, but I would like to make the compiler support static type checking, by proving that the result of a computation cannot be `no`. The compiler could also optimize away types and most non-determinism. I do realize that, in general, static type checking will be undecidable. The compiler will be designed to resolve undecidable types interactively with the user. 184 | 185 | The language would not change significantly. Product types are built from stacks, such as `[1 2 Ratio]`, and sum types are created using `\/`, such as `[1 Left] \/ ['a' Right]`, using undefined words at the top of the stack as tags. Constructors can be created as the matching lowercase word, such as `x left --> [x Left]`. 186 | 187 | ### Modules 188 | 189 | I will need to add a module system to allow encapsulation. 190 | 191 | ### Compiler 192 | 193 | The compiler will first target C, to allow easy portability. I am interested in running Peg code in embedded systems, especially because it is difficult to use other high-level languages such as Haskell on most microcontrollers. 194 | 195 | Discussion 196 | ---------- 197 | 198 | See the wiki: [Discussions](https://github.com/HackerFoo/peg/wiki/Discussions) 199 | -------------------------------------------------------------------------------- /Search.hs: -------------------------------------------------------------------------------- 1 | {- Copyright 2012 Dustin DeWeese 2 | This file is part of peg. 3 | 4 | peg is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | peg is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with peg. If not, see . 16 | -} 17 | 18 | {-# LANGUAGE FlexibleInstances, TupleSections, GeneralizedNewtypeDeriving, RankNTypes, ImpredicativeTypes #-} 19 | module Search where 20 | 21 | import Control.Monad 22 | import Control.Monad.Trans 23 | import System.IO 24 | import Control.Monad.Identity 25 | import Control.Monad.Cont 26 | 27 | import System.IO.Unsafe 28 | 29 | {- 30 | data Tree a = Node (Tree a) (Tree a) | Leaf a | Empty deriving (Show) 31 | 32 | instance Functor Tree where 33 | fmap f (Leaf x) = Leaf (f x) 34 | fmap f (Node x y) = Node (fmap f x) (fmap f y) 35 | 36 | instance Monad Tree where 37 | return = Leaf 38 | Node x y >>= f = Node (x >>= f) (y >>= f) 39 | Leaf x >>= f = f x 40 | Empty >>= _ = Empty 41 | 42 | instance MonadPlus Tree where 43 | mzero = Empty 44 | mplus = Node 45 | -} 46 | 47 | type Tree = TreeT Identity 48 | 49 | newtype TreeT m a = TreeT { runTreeT :: m (TreeT' m a) } 50 | data TreeT' m a = NodeT (TreeT m a) (TreeT m a) | LeafT a | EmptyT 51 | 52 | instance (Functor m) => Functor (TreeT m) where 53 | fmap f mt = TreeT . fmap f' $ runTreeT mt 54 | where f' EmptyT = EmptyT 55 | f' (LeafT x) = LeafT (f x) 56 | f' (NodeT mx my) = NodeT (fmap f mx) (fmap f my) 57 | 58 | instance (Monad m) => Monad (TreeT m) where 59 | return = TreeT . return . LeafT 60 | mt >>= f = TreeT $ do 61 | t <- runTreeT mt 62 | case t of 63 | EmptyT -> return EmptyT 64 | LeafT x -> runTreeT (f x) 65 | NodeT mx my -> return $ NodeT (mx >>= f) (my >>= f) 66 | 67 | instance (Monad m) => MonadPlus (TreeT m) where 68 | mzero = TreeT . return $ EmptyT 69 | mx `mplus` my = TreeT . return $ NodeT mx my 70 | 71 | instance MonadIO (TreeT IO) where 72 | liftIO = lift 73 | 74 | instance MonadTrans TreeT where 75 | lift = TreeT . liftM LeafT 76 | 77 | data Queue a = Queue [a] ([a] -> [a]) 78 | 79 | emptyQueue = Queue [] id 80 | 81 | pushQueue x (Queue l f) = Queue l (f . (x:)) 82 | 83 | popQueue :: Queue a -> (a, Queue a) 84 | popQueue = popQ' . forceQueue 85 | where popQ' (Queue (x:l) f) = (x, Queue l f) 86 | popQ' (Queue [] f) = error "popQ: empty queue" 87 | 88 | forceQueue (Queue [] f) = Queue (f []) id 89 | forceQueue q = q 90 | 91 | listQueue (Queue l f) = l ++ f [] 92 | 93 | nullQueue :: Queue a -> Bool 94 | nullQueue = nullQ' . forceQueue 95 | where nullQ' (Queue l _) = null l 96 | 97 | data QueueStateT q r m a = QueueStateT { 98 | runQueueStateT :: Queue q -> 99 | ((a, Queue q) -> m (Maybe r, Queue q)) -> 100 | m (Maybe r, Queue q) 101 | } 102 | 103 | instance Functor (QueueStateT q r m) where 104 | fmap f (QueueStateT qf) = QueueStateT $ \q k -> qf q (k . (\(x, q) -> (f x, q))) 105 | 106 | instance Monad (QueueStateT q r m) where 107 | return x = QueueStateT $ \q k -> k (x, q) 108 | QueueStateT qf >>= f = QueueStateT $ \q k -> 109 | qf q $ \(x, q') -> 110 | runQueueStateT (f x) q' k 111 | 112 | instance MonadIO (QueueStateT q r IO) where 113 | liftIO = lift 114 | 115 | instance MonadTrans (QueueStateT q r) where 116 | lift m = QueueStateT $ \q k -> k . (, q) =<< m 117 | 118 | pushQ :: q -> QueueStateT q r m () 119 | pushQ x = QueueStateT $ \q k -> k ((), pushQueue x q) 120 | 121 | popQ :: (Monad m) => QueueStateT q r m q 122 | popQ = QueueStateT $ \q k -> if nullQueue q 123 | then return (Nothing, q) 124 | else k $ popQueue q 125 | 126 | runQ qm = runQueueStateT (fmap Just qm) emptyQueue return 127 | 128 | runWithQ q qm = runQueueStateT (fmap Just qm) q return 129 | 130 | runBFS c = runQ $ pushQ c >> bfs 131 | 132 | bfs :: (Monad m) => QueueStateT (TreeT m a) r m a 133 | bfs = do mc <- popQ 134 | c <- lift $ runTreeT mc 135 | case c of 136 | LeafT x -> return x 137 | EmptyT -> bfs 138 | NodeT mx my -> pushQ mx >> pushQ my >> bfs 139 | 140 | runBFSn n c = runBFSn' n $ pushQueue c emptyQueue 141 | 142 | runBFSn' n q | n <= 0 = return [] 143 | | otherwise = do (mx, q') <- runWithQ q bfs 144 | case mx of 145 | Nothing -> return [] 146 | Just x -> fmap (x :) $ runBFSn' (n-1) q' 147 | 148 | runBFSAll c = runBFSAll' $ pushQueue c emptyQueue 149 | runBFSAll' q = do (mx, q') <- runWithQ q bfs 150 | case mx of 151 | Nothing -> return [] 152 | Just x -> fmap (x :) $ runBFSAll' q' 153 | 154 | runBFSAllI c = runBFSAllI' $ pushQueue c emptyQueue 155 | runBFSAllI' q = do (mx, q') <- runWithQ q bfs 156 | case mx of 157 | Nothing -> return [] 158 | Just x -> fmap (x :) . unsafeInterleaveIO $ runBFSAllI' q' 159 | 160 | choose :: (MonadPlus m) => [a] -> m a 161 | choose = foldr (mplus . return) mzero 162 | 163 | test :: Int -> Maybe (Int, Int) 164 | test c = runIdentity $ do 165 | (x, q) <- runBFS $ do 166 | x <- choose [1..] 167 | y <- choose [x..] 168 | guard $ x * y == c 169 | return (x, y) 170 | return x 171 | 172 | testTreeT :: IO [(Int, Int)] 173 | testTreeT = do 174 | x <- runBFSAllI $ do 175 | liftIO $ putStr "enter a number: " 176 | c <- liftIO readLn 177 | x <- choose [1..] 178 | y <- choose [x..] 179 | guard $ x * y == c 180 | liftIO . putStrLn $ "a solution is " ++ show (x, y) 181 | return (x, y) 182 | return (take 4 x) 183 | -------------------------------------------------------------------------------- /Setup.hs: -------------------------------------------------------------------------------- 1 | import Distribution.Simple 2 | main = defaultMain 3 | -------------------------------------------------------------------------------- /Simplex.hs: -------------------------------------------------------------------------------- 1 | {- Copyright 2012 Dustin DeWeese 2 | This file is part of peg. 3 | 4 | peg is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | peg is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with peg. If not, see . 16 | -} 17 | 18 | {-# LANGUAGE FlexibleContexts, ParallelListComp #-} 19 | {-# OPTIONS_GHC -fglasgow-exts -fenable-rewrite-rules #-} 20 | module Simplex {-(simplex, values, solve, Constraint(..))-} where 21 | 22 | import Control.Monad 23 | import Control.Monad.ST 24 | import Data.Maybe 25 | import Data.List 26 | import Data.Ord 27 | 28 | --import Utils hiding (trace) 29 | import QuadMatrix 30 | import Debug.Trace -- as Trace 31 | 32 | sign x = if x < 0 then -1 else 1 33 | 34 | class Reducible a where 35 | reduce :: a -> a 36 | 37 | instance Reducible (Int, Int) where 38 | reduce (x,y) = (abs x `div` d, signum x * y `div` d) 39 | where d = gcd x y 40 | 41 | instance Reducible (Double, Double) where 42 | reduce (x,y) = (scaleFloat s x', scaleFloat s y') 43 | --where s = 1 - min (exponent x') (exponent y') 44 | where s = 1 - ((exponent x' + exponent y') `div` 2) 45 | x' = abs x 46 | y' = if x < 0 then -y else y 47 | 48 | {-# SPECIALIZE selectColS :: QuadMatrix Double -> Maybe Int #-} 49 | selectColS a | Just ((_, j), x) <- minimumI ExcludeZero a [ (0, j) | j <- [1..n-1] ] = if x < 0 then Just j else Nothing 50 | | otherwise = Nothing 51 | where (_, n) = qDim a 52 | 53 | {-# SPECIALIZE selectColP :: QuadMatrix Double -> Int -> Maybe Int #-} 54 | selectColP a r | Just ((_, j), x) <- maximumI ExcludeZero a [ (r, j) | j <- [1..n-1] ] = if x > 0 then Just j else Nothing 55 | | otherwise = Nothing 56 | where (_, n) = qDim a 57 | 58 | {-# SPECIALIZE selectPivot :: QuadMatrix Double -> Int -> Maybe Int #-} 59 | selectPivot a c | Just (_, _, i) <- mn = Just i 60 | | otherwise = Nothing 61 | where (m, _) = qDim a 62 | p = foldrI ExcludeZero (\x@(_, e) xs -> if e > 0 then x:xs else xs) [] a [ (i,c) | i <- [1..m-1] ] 63 | (_, mn) = foldlI IncludeZero f (p, Nothing) a [ (i,0) | ((i, _), _) <- p ] 64 | f ((_, d):ds, Nothing) ((i, _), n) = (ds, Just (n, d, i)) 65 | f ((_, d):ds, m@(Just (mn, md, mi))) ((i, _), n) | n*md < mn*d = (ds, Just (n, d, i)) 66 | | otherwise = (ds, m) 67 | 68 | {-# SPECIALIZE pivot :: Int -> Int -> QuadMatrix Double -> QuadMatrix Double #-} 69 | pivot r c a = a''' 70 | where (m, n) = qDim a 71 | p = a @> (r,c) 72 | col = a .@ [ (i,c) | i <- [0..m-1], i /= r ] 73 | row = a .@ [ (r,j) | j <- [0..n-1], j /= c ] 74 | rat = map (\((i,_), x) -> (i, reduce (p, x))) col 75 | a' = a \@ [ ((i,c), 0) | i <- [0..m-1], i /= r ] 76 | a'' = qAccum ExcludeZero (*) a' [ ((i,j), x) | (i, (x, _)) <- rat, j <- [0..n-1], j /= c, x /= 1] 77 | a''' = qAccum IncludeZero (+) a'' [ ((i, j), -x*y) | (i, (_, y)) <- rat, ((_, j), x) <- row ] 78 | 79 | {-# SPECIALIZE simplexS :: QuadMatrix Double -> Maybe (QuadMatrix Double) #-} 80 | simplexS a = case selectColS a of 81 | Nothing -> Just a 82 | Just c -> case selectPivot a c of 83 | Nothing -> Nothing 84 | Just r -> simplexS $ pivot r c a 85 | 86 | {-# SPECIALIZE infeasible :: QuadMatrix Double -> Maybe Int #-} 87 | infeasible a | t > m = Nothing 88 | | otherwise = Just t 89 | where t = foldl f (m+1) [0..n-1] 90 | f t j | [((i,_), x)] <- a .@ [ (i, j) | i <- [0..t-1]] = 91 | if x < 0 && null (a .@ [ (i, j) | i <- [t..m-1] ]) then i else t 92 | | otherwise = t 93 | (m, n) = qDim a 94 | 95 | -- what to do in loop? e.g. solve [0,1] [[5,-1,-1::Double]] 96 | 97 | {-# SPECIALIZE simplex :: QuadMatrix Double -> Maybe (QuadMatrix Double) #-} 98 | simplex a = case infeasible a of 99 | Nothing -> simplexS a 100 | Just r -> case do c <- selectColP a r 101 | r <- selectPivot a c 102 | return (r,c) of 103 | Nothing -> Nothing 104 | Just (r,c) -> simplex $ pivot r c a 105 | 106 | {-# SPECIALIZE values :: QuadMatrix Double -> [Double] #-} 107 | values a = map ans [1..n-1] 108 | where (m, n) = qDim a 109 | ans j | [((i, _), x)] <- a .@ [ (i, j) | i <- [0..m-1] ] = realToFrac (a @> (i, 0)) / realToFrac x 110 | | otherwise = 0 111 | 112 | --solve :: (Real e, Fractional e, Reducible (e,e), IArray UArray e) => [e] -> [Constraint e] -> Maybe [e] 113 | 114 | --{-# SPECIALIZE solve :: [Double] -> [[Double]] -> Maybe [Double] #-} 115 | solve c ba = liftM (take (length c) . values) . simplex $ augmentedMatrix c ba 116 | 117 | {-# SPECIALIZE augmentedMatrix :: [Double] -> [[Double]] -> QuadMatrix Double #-} 118 | augmentedMatrix c ba = qmatrix (1 + lba, 1 + lc + lba) /@ es 119 | where lc = length c 120 | lba = length ba 121 | es = [ ((0, j), x) | x <- c | j <- [1..] ] ++ 122 | concat [ [ ((i, j), x) | j <- [0..] | x <- (abs b : row)] | i <- [1..] | (b : row) <- ba ] ++ 123 | [ ((i, i + lc), sign (head x)) | i <- [1..] | x <- ba ] 124 | -------------------------------------------------------------------------------- /lib.peg: -------------------------------------------------------------------------------- 1 | -- Builtins 2 | 3 | [dup True eq? [True] [dup False eq?] ifte] "boolean?" :def 4 | [{int?;int?} types] "int2?" :def 5 | [{float?;int?} types] "float_int?" :def 6 | [{float?;float?} types] "float2?" :def 7 | [{char?;char?} types] "char2?" :def 8 | 9 | -- checks types with a list of predicates 10 | [[] swap types'] "types" :def 11 | [popr dip2 rolldown [[pushl] dip types'] [pop $ False seq] ifte] "types'" :def 12 | [popnull $ True seq] "types'" :def 13 | 14 | [int2?! add_int# int?!] "+" :def 15 | [int2?! sub_int# int?!] "-" :def 16 | [int2?! mul_int# int?!] "*" :def 17 | [{int?; int? [dup 0 /=] dip &&} types! div_int# int?!] "div" :def 18 | [{int?; int? [dup 0 /=] dip &&} types! mod_int# int?!] "mod" :def 19 | [{int?; int? [dup 0 /=] dip &&} types! divMod_int# int2?!] "divMod" :def 20 | [{int?; int? [dup 0 /=] dip &&} types! quot_int# int?!] "quot" :def 21 | [{int?; int? [dup 0 /=] dip &&} types! rem_int# int?!] "rem" :def 22 | [{int?; int? [dup 0 /=] dip &&} types! quotRem_int# int2?!] "quotRem" :def 23 | [{int?; int? [dup 0 >=] dip &&} types! pos_power_int# int?!] "^" :def 24 | [{float?; int? [dup 0 >=] dip &&} types! pos_power_float# float?!] "^" :def 25 | [float_int?! int_power_float# float?!] "^^" :def 26 | [float2?! power_float# float?!] "**" :def 27 | [float?! exp# float?!] "exp" :def 28 | [float?! sqrt# float?!] "sqrt" :def 29 | [float?! log# float?!] "log" :def 30 | [float?! logBase# float?!] "logBase" :def 31 | [float?! sin# float?!] "sin" :def 32 | [float?! tan# float?!] "tan" :def 33 | [float?! cos# float?!] "cos" :def 34 | [float?! asin# float?!] "asin" :def 35 | [float?! atan# float?!] "atan" :def 36 | [float?! acos# float?!] "acos" :def 37 | [float?! sinh# float?!] "sinh" :def 38 | [float?! tanh# float?!] "tanh" :def 39 | [float?! cosh# float?!] "cosh" :def 40 | [float?! asinh# float?!] "asinh" :def 41 | [float?! atanh# float?!] "atanh" :def 42 | [float?! acosh# float?!] "acosh" :def 43 | [float2?! add_float# float?!] "+" :def 44 | [float2?! sub_float# float?!] "-" :def 45 | [float2?! mul_float# float?!] "*" :def 46 | [float2?! divide_float# float?!] "/" :def 47 | [int2?! lt_int# boolean?!] "<" :def 48 | [int2?! lte_int# boolean?!] "<=" :def 49 | [int2?! gt_int# boolean?!] ">" :def 50 | [int2?! gte_int# boolean?!] ">=" :def 51 | [float2?! lt_float# boolean?!] "<" :def 52 | [float2?! lte_float# boolean?!] "<=" :def 53 | [float2?! gt_float# boolean?!] ">" :def 54 | [float2?! gte_float# boolean?!] ">=" :def 55 | [char2?! lt_char# boolean?!] "<" :def 56 | [char2?! lte_char# boolean?!] "<=" :def 57 | [char2?! gt_char# boolean?!] ">" :def 58 | [char2?! gte_char# boolean?!] ">=" :def 59 | [int?! intToFloat# float?!] "realToFrac" :def 60 | [float?!] "realToFrac" :def 61 | [float?! round# int?!] "round" :def 62 | [float?! floor# int?!] "floor" :def 63 | [float?! ceiling# int?!] "ceiling" :def 64 | [hasIO? False eq?! pop#] "pop" :def 65 | [hasIO? False eq?! dup#] "dup" :def 66 | [swap#] "swap" :def 67 | [list?! $#] "$" :def 68 | [swap <$#] "dip#" :def 69 | 70 | --[`[ swap <$# seq $#] "unpackR#" :def 71 | [list?! dip#] "dip" :def 72 | [null? False eq?! unpackR# `] dip# seq] "popr" :def 73 | [[list?! unpackR#] dip# seq `] seq $#] "pushr" :def 74 | [[list?! unpackR#] dip# seq _ pushr $# `] seq $# popr pop#] "." :def 75 | 76 | [hasIO? False eq?! show# string?!] "show" :def 77 | [string?! read#] "read" :def 78 | [io?! getChar# {io?;char?} types!] "getChar" :def 79 | [{io?;char?} types! putChar# io?!] "putChar" :def 80 | 81 | -- Booleans 82 | 83 | -- logical negation 84 | -- ( Boolean not -> Boolean ) 85 | [False eq?! True seq] "not" :def 86 | [True eq?! False seq] "not" :def 87 | 88 | -- logical conjunction 89 | -- ( Boolean Boolean && -> Boolean ) 90 | [[] [pop False] ifte] "&&" :def 91 | 92 | -- logical disjunction 93 | -- ( Boolean Boolean || -> Boolean ) 94 | [[pop True] [] ifte] "||" :def 95 | 96 | -- comparisons 97 | -- select greater operand 98 | -- (a a >=) => ( a a max -> a ) 99 | [dup2 >= [pop] [swap pop] ifte] "max" :def 100 | 101 | -- select lesser operand 102 | -- (a a <=) => ( a a min -> a ) 103 | [dup2 <= [pop] [swap pop] ifte] "min" :def 104 | 105 | -- numbers 106 | 107 | -- integer 108 | 109 | -- flip sign 110 | -- ( Int negate -> Int ) 111 | [0 swap - ] "negate" :def 112 | -- ( Double negate -> Double ) 113 | [0.0 swap - ] "negate" :def 114 | 115 | -- positive magnitude 116 | -- ( Int abs -> Int ) 117 | [dup 0 < [negate] [] ifte] "abs" :def 118 | -- ( Double abs -> Double ) 119 | [dup 0.0 < [negate] [] ifte] "abs" :def 120 | 121 | -- dup signum swap abs * == id 122 | -- ( Int signum -> Int ) 123 | [dup 0 < [pop -1] [0 > [1] [0] ifte] ifte] "signum" :def 124 | -- ( Double signum -> Double ) 125 | [dup 0.0 < [pop -1.0] [0.0 > [1.0] [0.0] ifte] ifte] "signum" :def 126 | 127 | -- float 128 | 129 | -- reciprocal 130 | -- ( Double recip -> Double ) 131 | [1.0 swap /] "recip" :def 132 | 133 | -- combinators 134 | 135 | -- x p f until applies f to x until p holds 136 | -- ( a ( a -> Boolean ) ( a -> a ) until -> a ) 137 | [[dup2 $] dip swap [pop2] [dup dip2 until] ifte] "until" :def 138 | 139 | -- ( ( a -> b ) fix -> b ) 140 | [dup $ swap pop] "fix" :def 141 | -- example 142 | -- [[rollup dup2 >= 143 | -- [dup rollup - swap rolldown dup $] 144 | -- [pop] ifte] fix] "mod" :def 145 | 146 | -- ( A Boolean ( A -> B ) ( A -> C ) ifte -> B \/ C ) 147 | [False pushr swap True pushr rolldown [\/ $] dip eq? !] "ifte" :def 148 | 149 | -- stack operators 150 | 151 | -- ( a b over -> a b a ) 152 | [swap dup [swap] dip] "over" :def 153 | 154 | -- ( a b c over2 -> a b c a ) 155 | [[over] dip swap] "over2" :def 156 | 157 | -- ( a b c d over3 -> a b c d a ) 158 | [[over2] dip swap] "over3" :def 159 | 160 | -- ( a b c d e over4 -> a b c d e a ) 161 | [[over3] dip swap] "over4" :def 162 | 163 | -- ( a b nip -> b ) 164 | [swap pop] "nip" :def 165 | 166 | -- ( a b tuck -> b a b ) 167 | [swap over] "tuck" :def 168 | 169 | -- ( a b c rollup -> c a b ) 170 | [swap [swap] dip] "rollup" :def 171 | 172 | -- ( a b c rolldown -> b c a ) 173 | [[swap] dip swap] "rolldown" :def 174 | 175 | -- ( a b c rotate -> c b a ) 176 | [swap [swap] dip swap] "rotate" :def 177 | 178 | -- ( a b ( a -> c ) dip -> c b ) 179 | -- [swap pushr $] "dip" :def 180 | 181 | -- ( a b c ( a -> d ) dip2 -> d b c ) 182 | [swap pushr swap pushr $ swap] "dip2" :def 183 | 184 | -- ( a b c d ( a -> e ) dip3 -> e b c d ) 185 | [swap pushr swap pushr swap pushr $ rotate] "dip3" :def 186 | 187 | -- ( a b dup2 -> a b a b ) 188 | [[dup] dip dup [swap] dip] "dup2" :def 189 | 190 | -- ( a b pop2 -> ) 191 | [pop pop] "pop2" :def 192 | 193 | -- lists 194 | 195 | -- ( (A) (a -> b) map -> (B) ) 196 | [[] rollup [pushr] . foldl] "map" :def 197 | 198 | -- ( (A) (a -> Boolean) filter -> (A') ) 199 | [[] rollup [dup] swap . [[pushr] [pop] ifte] . foldl] "filter" :def 200 | 201 | -- ( A [] popnull -> A ) 202 | [null? ! pop] "popnull" :def 203 | 204 | -- ( [A a] [B] movr -> [A] [B a] ) 205 | [[popr] dip swap pushr] "movr" :def 206 | 207 | -- ( [A] [B b] movl -> [A b] [B] ) 208 | [popr swap [pushr] dip] "movl" :def 209 | 210 | -- ( [a repeat] popr -> [a repeat] a ) 211 | [dup [repeat] dip] "repeat" :def 212 | 213 | -- ( [A] cycle -> [A] cycle A ) 214 | [dup [cycle] dip $] "cycle" :def 215 | 216 | -- ( a (a -> a) iterate -> a (a -> a) iterate a ) 217 | [over [dup [$] dip iterate] dip] "iterate" :def 218 | 219 | -- ( [a .. b] reverse -> [b .. a] ) 220 | [null? [pop] [movl reverse'] ifte] "reverse'" :def 221 | [[] swap reverse'] "reverse" :def 222 | 223 | -- ( [a A] popl -> a [A] ) 224 | [reverse popr swap reverse] "popl" :def 225 | 226 | -- ( a [A] pushl -> [a A] ) 227 | [[[] swap pushr] dip .] "pushl" :def 228 | 229 | -- ( a [B] (a b -> a) foldl -> a ) 230 | [[popr] dip dup [foldl] pushl dip2 $] "foldl" :def 231 | --[[popr] dip dup [foldl] pushl dip2 [seq] dip seq $] "foldl" :def 232 | [pop popnull] "foldl" :def 233 | 234 | -- ( [A] (a a -> a) foldl1 -> a ) 235 | [[popl] dip foldl] "foldl1" :def 236 | 237 | -- ( a [B] (a b -> a) foldr -> a ) 238 | [over null? nip [pop2] [[popr swap] dip dup dip2 foldr] ifte] "foldr" :def 239 | 240 | [over null? nip [pop2] [[popr swap] dip dup dip2 foldrS S] ifte] "foldrS" :def 241 | 242 | -- ( [A] (a a -> a) foldr1 -> a ) 243 | [[popr swap] dip foldr] "foldr1" :def 244 | 245 | -- get nth item from a stack 246 | -- ( [A] Int !! -> a ) 247 | [dup 0 <= [pop popr swap pop] [1- [tail] dip seq !!] ifte] "!!" :def 248 | 249 | -- drop n stack items 250 | -- ( [A] Int drop -> [A] ) 251 | [dup 0 <= [pop] [1 - swap null? [nip] [tail swap drop] ifte] ifte] "drop" :def 252 | 253 | -- take n stack items 254 | -- ( [A] Int take -> [A] ) 255 | [splitAt pop] "take" :def 256 | 257 | -- ( [A] Int splitAt -> [A] [A] ) 258 | [[] rollup splitAt'] "splitAt" :def 259 | [dup 0 <= [pop] [1- over null? nip [pop] [[movl] dip splitAt'] ifte] ifte] "splitAt'" :def 260 | 261 | -- ( [A] (a -> Boolean) -> [A] [A] ) 262 | [[] rollup span'] "span" :def 263 | [[popr dup] dip dup [$] dip swap [[swap [swap pushl] dip] dip span'] [pop pushr] ifte] "span'" :def 264 | [pop null?!] "span'" :def 265 | 266 | -- ( [A] (a -> Boolean) -> [A] ) 267 | [span pop] "takeWhile" :def 268 | 269 | -- ( [A] (a -> Boolean) -> [A] ) 270 | [span swap pop] "dropWhile" :def 271 | 272 | -- ( [A] (a -> Boolean) -> [A] [A] ) 273 | [[not] . span] "break" :def 274 | 275 | -- ( a a enumFromTo -> [A] ) 276 | [over - 1+ swap [[1+] iterate] pushl swap take] "enumFromTo" :def 277 | 278 | -- ( [A] length -> Int ) 279 | --[0 length'] "length" :def 280 | --[over null? nip [nip] [1+ [tail] dip length'] ifte] "length'" :def 281 | [0 swap [pop 1+] foldl] "length" :def 282 | [0 swap [pop 1+] foldr] "length_r" :def -- loop undetected 283 | 284 | -- ( [A a] top -> [A a] a ) 285 | [popr dup [pushr] dip seq] "top" :def 286 | 287 | -- ( [Boolean ..] and -> Boolean ) 288 | [True swap [&&] foldl] "and" :def 289 | 290 | -- ( [Boolean ..] or -> Boolean ) 291 | [False swap [||] foldl] "or" :def 292 | 293 | -- ( [A] (a -> Boolean) any -> Boolean ) 294 | [map or] "any" :def 295 | 296 | -- ( [A] (a -> Boolean) all -> Boolean ) 297 | [map and] "all" :def 298 | 299 | -- (a a +) => ( [A] sum -> a ) 300 | [0 swap [+] foldl] "sum" :def 301 | 302 | -- (a a *) => ( [A] product -> a ) 303 | [1 swap [*] foldl] "product" :def 304 | 305 | -- (a a .) => ( [A] concat -> a ) 306 | [[] swap [.] foldl] "concat" :def 307 | 308 | -- (b b .) => ( [A] (a -> b) concatMap -> b ) 309 | [map concat] "concatMap" :def 310 | 311 | -- (a a max) => ( [A] maximum -> a ) 312 | [[max] foldl1] "maximum" :def 313 | 314 | -- (a a min) => ( [A] minimum -> a ) 315 | [[min] foldl1] "minimum" :def 316 | 317 | -- ( [A] [B] [C] splice -> [B A C] ) 318 | [[swap .] dip .] "splice" :def 319 | 320 | -- ( a singleton -> [a] ) 321 | [[] swap pushr] "singleton" :def 322 | 323 | -- ( a [B] (a b -> a) scanl -> [A] ) 324 | [[singleton] dip2 [[top] dip] swap . [pushr] . foldl] "scanl" :def 325 | 326 | -- ( [A] (a a -> a) scanl1 -> [A] ) 327 | [[popl] dip scanl] "scanl1" :def 328 | 329 | -- ( a [B] (a b -> a) scanr -> [A] ) 330 | [[singleton] dip2 [[top] dip] [pushr] splice foldr] "scanr" :def 331 | 332 | -- ( [A] (a a -> a) scanr1 -> [A] ) 333 | [[popr swap] dip scanr] "scanr1" :def 334 | 335 | -- ( a Int replicate -> [A] ) 336 | [[[repeat] pushl] dip take] "replicate" :def 337 | 338 | -- ( a b == -> Boolean ) 339 | [eq?] "==" :def 340 | [[popr] dip swap [popr] dip ==] "headEq?" :def 341 | [{list?; list?} types! [headEq? [==] [pop2 False] ifte] seq $] "==" :def 342 | [popnull null? nip] "==" :def 343 | [swap popnull null? nip] "==" :def 344 | 345 | -- ( [A a] head -> a ) 346 | [popr swap pop] "head" :def 347 | 348 | -- ( a just -> [ a Just ] ) 349 | [[Just] pushl] "just" :def 350 | 351 | -- ( nothing -> [ Nothing ] ) 352 | [[Nothing]] "nothing" :def 353 | 354 | -- ( ([a Just] \/ [Nothing]) ( a -> b ) b maybe -> b ) 355 | [rotate popr 356 | {pop pop : Nothing; 357 | head [pop] dip2 swap $ : Just} 358 | case seq] "maybe" :def 359 | 360 | [nothing maybe seq] ">>=" :def 361 | [just] "return" :def 362 | [nothing] "mzero" :def 363 | 364 | [[return] dip [>>=] foldl] "do" :def 365 | 366 | -- (x y ==), ( [a x] { .. ; b y ; .. } case -> a b ) 367 | [popr popr over3 eq? [swap pop swap pop $] [pop case] ifte] "case" :def 368 | 369 | -- ( [A] a elem -> Boolean ) 370 | [[popr] dip dup [==] dip swap [pop2 True seq] [elem] ifte] "elem" :def 371 | [pop null? nip False swap !] "elem" :def 372 | 373 | -- ( [A] a notElem -> Boolean ) 374 | [elem not] "notElem" :def 375 | 376 | -- ( a [[b a] ..] lookup -> ([b Just] \/ [Nothing]) ) 377 | [popr popr over3 eq? [swap pop swap pop $ just] [pop lookup] ifte] "lookup" :def 378 | [null? nip swap pop nothing swap !] "lookup" :def 379 | 380 | -- ( ([a Left] \/ [b Right]) (a -> c) (b -> c) either -> c 381 | [[Right] . swap [Left] . swap [] pushl pushl [popr [head] dip] dip case] "either" :def 382 | 383 | -- ( a left -> [a Left] ) 384 | [[Left] pushl] "left" :def 385 | 386 | -- ( a right -> [a Right] ) 387 | [[Right] pushl] "right" :def 388 | 389 | [right] "return" :def 390 | [swap [left swap pop] [swap $] either] ">>=" :def 391 | 392 | 393 | -- ( [A] [B] (a b -> c) zipWith -> [C] ) 394 | [[[popr] dip popr [swap] dip] dip rollup over2 $ [zipWith] dip pushr] "zipWith" :def 395 | [pop pop null? nip [] swap !] "zipWith" :def 396 | [pop swap pop null? nip [] swap !] "zipWith" :def 397 | 398 | -- ( [A] [B] zip -> [[a b] ..] ) 399 | [[[] pushl pushl] zipWith] "zip" :def 400 | 401 | -- ( a b compare -> (LT \/ EQ \/ GT) ) 402 | [dup2 < [pop2 LT seq] [> [GT] [EQ] ifte] ifte] "compare" :def 403 | 404 | -- ( [A a] tail -> [A] ) 405 | [popr pop] "tail" :def 406 | 407 | -- ( [A] (a -> [B]) concatMap -> [B] ) 408 | [map concat] "concatMap" :def 409 | 410 | -- ( Float ) 411 | [3.141592653589793] "pi" :def 412 | 413 | -- ( [[a b] ..] unzip -> [A] [B] ) 414 | [popr [unzip] dip popl head swap [pushr] dip swap [pushr] dip seq] "unzip" :def 415 | [null? nip [] [] rolldown !] "unzip" :def 416 | 417 | -- () 418 | [False !] "no" :def 419 | 420 | -- ( A : -> A ) 421 | [] ":" :def 422 | 423 | [swap >>=] "=<<" :def 424 | [[pop] swap pushr >>=] ">>" :def 425 | [[>>] foldl1 [] return >>] "sequence_" :def 426 | [[] return swap [[singleton] fmap composeM] foldl] "sequence" :def 427 | 428 | 429 | [swap popr {head swap $ [Just] pushl : Just; 430 | pop2 [Nothing] seq : Nothing} case] "fmap" :def 431 | [swap popr {head swap $ [Right] pushl : Right; 432 | [Left] . swap pop : Left} case] "fmap" :def 433 | 434 | [[State] pushl [pushl] pushl] "return" :def 435 | 436 | [[swap] [return] splice singleton 437 | [swap] [>>=] splice [>>=] pushl pushl pushl head] "ap2" :def 438 | 439 | [[.] ap2] "composeM" :def 440 | 441 | --[[return] pushl [IO] pushl] "return" :def 442 | --[swap popr {head swap [>>=] pushl pushl [IO] pushl : IO} case] ">>=" :def 443 | 444 | --[[return] pushl singleton [[]] [IO] splice] "return" :def 445 | --[swap popr {popr [head swap . [>>=] .] dip [IO] pushl pushl : IO} case] ">>=" :def 446 | 447 | 448 | -- I/O 449 | 450 | [[putChar] foldr] "putStr" :def 451 | [putStr '\n' putChar] "putStrLn" :def 452 | 453 | ["" getLine'] "getLine" :def 454 | [[getChar] dip swap dup '\n' eq? [pop reverse] [pushr getLine'] ifte] "getLine'" :def 455 | 456 | -- ( IO a print --> IO ) -- prints representation of a to stdout 457 | [show putStrLn] "print" :def 458 | 459 | -- ( IO readLn --> IO a ) -- parses input from stdin to a 460 | [getLine read] "readLn" :def 461 | 462 | [pop] "\\/" :def 463 | [swap pop] "\\/" :def 464 | 465 | [!] "assert" :def 466 | [False eq?!] "deny" :def 467 | 468 | [list? deny False seq] "string?" :def 469 | [dup [char? nip] all seq] "string?" :def 470 | 471 | [== not] "/=" :def 472 | 473 | -- simple recursive words for testing 474 | [dup# 0 eq? False eq?! [1- count] seq $#] "count" :def 475 | [dup# 0 eq?!] "count" :def 476 | 477 | [dup# [1- count2] dip# 0 eq? False eq?!] "count2" :def 478 | [dup# 0 eq?!] "count2" :def 479 | 480 | [dup 0 <= [pop] [1- swap 1+ swap add_it] ifte] "add_it" :def 481 | [dup 0 <= [] [1- count_down] ifte] "count_down" :def 482 | 483 | -- simple recursive word that does not use names for recursion or choice 484 | [[swap dup 5 < [! nip] [not! 5 - swap dup $] \/ $] dup $] "sub5" :def 485 | 486 | [dup [fix2] dip $] "fix2" :def -------------------------------------------------------------------------------- /peg.cabal: -------------------------------------------------------------------------------- 1 | -- peg.cabal auto-generated by cabal init. For additional options, see 2 | -- http://www.haskell.org/cabal/release/cabal-latest/doc/users-guide/authors.html#pkg-descr. 3 | -- The name of the package. 4 | Name: peg 5 | 6 | -- The package version. See the Haskell package versioning policy 7 | -- (http://www.haskell.org/haskellwiki/Package_versioning_policy) for 8 | -- standards guiding when and how versions should be incremented. 9 | Version: 0.2 10 | 11 | -- A short (one-line) description of the package. 12 | Synopsis: a lazy non-deterministic concatenative programming language 13 | 14 | -- A longer description of the package. 15 | Description: Peg is a lazy non-deterministic concatenative programming language inspired by Haskell, Joy, and Prolog. 16 | 17 | -- URL for the project homepage or repository. 18 | Homepage: http://github.com/HackerFoo/peg 19 | 20 | -- The license under which the package is released. 21 | License: GPL-3 22 | 23 | -- The file containing the license text. 24 | License-file: LICENSE 25 | 26 | -- The package author(s). 27 | Author: Dustin DeWeese 28 | 29 | -- An email address to which users can send suggestions, bug reports, 30 | -- and patches. 31 | Maintainer: dustin.deweese@gmail.com 32 | 33 | -- A copyright notice. 34 | -- Copyright: 35 | 36 | Category: Compilers/Interpreters 37 | 38 | Build-type: Simple 39 | 40 | -- Extra files to be distributed with the package, such as examples or 41 | -- a README. 42 | Extra-source-files: README.md, lib.peg, types.peg 43 | 44 | -- Constraint on the version of Cabal needed to build this package. 45 | Cabal-version: >=1.4 46 | 47 | Executable peg 48 | cpp-options: -DMAIN 49 | 50 | -- .hs or .lhs file containing the Main module. 51 | Main-is: Peg.hs 52 | 53 | -- Packages needed in order to build this package. 54 | Build-depends: base < 5, containers, mtl, filepath, haskeline, parsec 55 | 56 | -- Modules not exported by this package. 57 | -- Other-modules: 58 | 59 | -- Extra tools (e.g. alex, hsc2hs, ...) needed to build the source. 60 | -- Build-tools: 61 | 62 | -------------------------------------------------------------------------------- /types.peg: -------------------------------------------------------------------------------- 1 | [[True] [False] \/] "Boolean" :def 2 | 3 | [Int eq? swap Int eq? && Int swap assert] "op2i" :def 4 | [Int eq? swap int? && Int swap assert] "op2i" :def 5 | [int? swap Int eq? && Int swap assert] "op2i" :def 6 | [Float eq? swap Float eq? && Float swap assert] "op2f" :def 7 | [Float eq? swap float? && Float swap assert] "op2f" :def 8 | [float? swap Float eq? && Float swap assert] "op2f" :def 9 | [Int eq? swap Int eq? && Boolean swap assert] "op2ib" :def 10 | [Int eq? swap int? && Boolean swap assert] "op2ib" :def 11 | [int? swap Int eq? && Boolean swap assert] "op2ib" :def 12 | [Float eq? swap Float eq? && Boolean swap assert] "op2fb" :def 13 | [Float eq? swap float? && Boolean swap assert] "op2fb" :def 14 | [float? swap Float eq? && Boolean swap assert] "op2fb" :def 15 | [op2i] "+" :def 16 | [op2i] "-" :def 17 | [op2i] "*" :def 18 | [op2i] "div" :def 19 | [op2f] "+" :def 20 | [op2f] "-" :def 21 | [op2f] "*" :def 22 | [op2f] "/" :def 23 | [op2ib] ">" :def 24 | [op2ib] "<" :def 25 | [op2ib] ">=" :def 26 | [op2ib] "<=" :def 27 | [op2fb] ">" :def 28 | [op2fb] "<" :def 29 | [op2fb] ">=" :def 30 | [op2fb] "<=" :def 31 | --------------------------------------------------------------------------------