├── .github └── workflows │ └── haskell-ci.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── examples └── Main.hs ├── experiments ├── Experiment1.hs ├── Experiment2.hs ├── Experiment3.hs └── Experiment4.hs ├── gigaparsec.cabal ├── hie.yaml ├── plnl23 ├── embedding-generalized-parsing-in-haskell.key └── embedding-generalized-parsing-in-haskell.pdf ├── src ├── Gigaparsec.hs └── Gigaparsec │ └── Core.hs └── tests └── test.hs /.github/workflows/haskell-ci.yml: -------------------------------------------------------------------------------- 1 | # This GitHub workflow config has been generated by a script via 2 | # 3 | # haskell-ci 'github' 'gigaparsec.cabal' 4 | # 5 | # To regenerate the script (for example after adjusting tested-with) run 6 | # 7 | # haskell-ci regenerate 8 | # 9 | # For more information, see https://github.com/haskell-CI/haskell-ci 10 | # 11 | # version: 0.16.3 12 | # 13 | # REGENDATA ("0.16.3",["github","gigaparsec.cabal"]) 14 | # 15 | name: Haskell-CI 16 | on: 17 | - push 18 | - pull_request 19 | jobs: 20 | linux: 21 | name: Haskell-CI - Linux - ${{ matrix.compiler }} 22 | runs-on: ubuntu-20.04 23 | timeout-minutes: 24 | 60 25 | container: 26 | image: buildpack-deps:bionic 27 | continue-on-error: ${{ matrix.allow-failure }} 28 | strategy: 29 | matrix: 30 | include: 31 | - compiler: ghc-9.2.7 32 | compilerKind: ghc 33 | compilerVersion: 9.2.7 34 | setup-method: ghcup 35 | allow-failure: false 36 | fail-fast: false 37 | steps: 38 | - name: apt 39 | run: | 40 | apt-get update 41 | apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5 42 | mkdir -p "$HOME/.ghcup/bin" 43 | curl -sL https://downloads.haskell.org/ghcup/0.1.19.2/x86_64-linux-ghcup-0.1.19.2 > "$HOME/.ghcup/bin/ghcup" 44 | chmod a+x "$HOME/.ghcup/bin/ghcup" 45 | "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false) 46 | "$HOME/.ghcup/bin/ghcup" install cabal 3.10.1.0 || (cat "$HOME"/.ghcup/logs/*.* && false) 47 | env: 48 | HCKIND: ${{ matrix.compilerKind }} 49 | HCNAME: ${{ matrix.compiler }} 50 | HCVER: ${{ matrix.compilerVersion }} 51 | - name: Set PATH and environment variables 52 | run: | 53 | echo "$HOME/.cabal/bin" >> $GITHUB_PATH 54 | echo "LANG=C.UTF-8" >> "$GITHUB_ENV" 55 | echo "CABAL_DIR=$HOME/.cabal" >> "$GITHUB_ENV" 56 | echo "CABAL_CONFIG=$HOME/.cabal/config" >> "$GITHUB_ENV" 57 | HCDIR=/opt/$HCKIND/$HCVER 58 | HC=$HOME/.ghcup/bin/$HCKIND-$HCVER 59 | echo "HC=$HC" >> "$GITHUB_ENV" 60 | echo "HCPKG=$HOME/.ghcup/bin/$HCKIND-pkg-$HCVER" >> "$GITHUB_ENV" 61 | echo "HADDOCK=$HOME/.ghcup/bin/haddock-$HCVER" >> "$GITHUB_ENV" 62 | echo "CABAL=$HOME/.ghcup/bin/cabal-3.10.1.0 -vnormal+nowrap" >> "$GITHUB_ENV" 63 | HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))') 64 | echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV" 65 | echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV" 66 | echo "ARG_BENCH=--enable-benchmarks" >> "$GITHUB_ENV" 67 | echo "HEADHACKAGE=false" >> "$GITHUB_ENV" 68 | echo "ARG_COMPILER=--$HCKIND --with-compiler=$HC" >> "$GITHUB_ENV" 69 | echo "GHCJSARITH=0" >> "$GITHUB_ENV" 70 | env: 71 | HCKIND: ${{ matrix.compilerKind }} 72 | HCNAME: ${{ matrix.compiler }} 73 | HCVER: ${{ matrix.compilerVersion }} 74 | - name: env 75 | run: | 76 | env 77 | - name: write cabal config 78 | run: | 79 | mkdir -p $CABAL_DIR 80 | cat >> $CABAL_CONFIG <> $CABAL_CONFIG < cabal-plan.xz 113 | echo 'f62ccb2971567a5f638f2005ad3173dba14693a45154c1508645c52289714cb2 cabal-plan.xz' | sha256sum -c - 114 | xz -d < cabal-plan.xz > $HOME/.cabal/bin/cabal-plan 115 | rm -f cabal-plan.xz 116 | chmod a+x $HOME/.cabal/bin/cabal-plan 117 | cabal-plan --version 118 | - name: checkout 119 | uses: actions/checkout@v3 120 | with: 121 | path: source 122 | - name: initial cabal.project for sdist 123 | run: | 124 | touch cabal.project 125 | echo "packages: $GITHUB_WORKSPACE/source/." >> cabal.project 126 | cat cabal.project 127 | - name: sdist 128 | run: | 129 | mkdir -p sdist 130 | $CABAL sdist all --output-dir $GITHUB_WORKSPACE/sdist 131 | - name: unpack 132 | run: | 133 | mkdir -p unpacked 134 | find sdist -maxdepth 1 -type f -name '*.tar.gz' -exec tar -C $GITHUB_WORKSPACE/unpacked -xzvf {} \; 135 | - name: generate cabal.project 136 | run: | 137 | PKGDIR_gigaparsec="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/gigaparsec-[0-9.]*')" 138 | echo "PKGDIR_gigaparsec=${PKGDIR_gigaparsec}" >> "$GITHUB_ENV" 139 | rm -f cabal.project cabal.project.local 140 | touch cabal.project 141 | touch cabal.project.local 142 | echo "packages: ${PKGDIR_gigaparsec}" >> cabal.project 143 | echo "package gigaparsec" >> cabal.project 144 | echo " ghc-options: -Werror=missing-methods" >> cabal.project 145 | cat >> cabal.project <> cabal.project.local 148 | cat cabal.project 149 | cat cabal.project.local 150 | - name: dump install plan 151 | run: | 152 | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dry-run all 153 | cabal-plan 154 | - name: restore cache 155 | uses: actions/cache/restore@v3 156 | with: 157 | key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} 158 | path: ~/.cabal/store 159 | restore-keys: ${{ runner.os }}-${{ matrix.compiler }}- 160 | - name: install dependencies 161 | run: | 162 | $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --dependencies-only -j2 all 163 | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dependencies-only -j2 all 164 | - name: build w/o tests 165 | run: | 166 | $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks all 167 | - name: build 168 | run: | 169 | $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --write-ghc-environment-files=always 170 | - name: tests 171 | run: | 172 | $CABAL v2-test $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --test-show-details=direct 173 | - name: cabal check 174 | run: | 175 | cd ${PKGDIR_gigaparsec} || false 176 | ${CABAL} -vnormal check 177 | - name: haddock 178 | run: | 179 | $CABAL v2-haddock --disable-documentation --haddock-all $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all 180 | - name: unconstrained build 181 | run: | 182 | rm -f cabal.project.local 183 | $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks all 184 | - name: save cache 185 | uses: actions/cache/save@v3 186 | if: always() 187 | with: 188 | key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }} 189 | path: ~/.cabal/store 190 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist-*/ -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Revision history for gigaparsec 2 | 3 | ## 0.1.0.0 -- 2023-04-14 4 | 5 | * First version. Released on an unsuspecting world. 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GPC 2 | 3 | GPC is a library providing generalized parser combinators 4 | which are able to parse all context-free grammars completely. This includes 5 | support for left-recursion and reporting all possible parses of ambiguous 6 | grammars. 7 | 8 | GPC is currently only a proof of concept. Of course it needs a much more 9 | elaborate API, but before that I want to implement disambiguation strategies. 10 | I have also not put any effort in making this library performant yet. 11 | 12 | ## Comparison with other parsing techniques 13 | 14 | Feature | (atto/mega)parsec | happy (LALR) | Earley | GPC 15 | ---------------------------|--------------------|--------------------|--------------------|-------------------- 16 | No shift-reduce conflicts | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: 17 | Left-recusion | :x: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: 18 | Pure Haskell | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: 19 | Monadic interface | :heavy_check_mark: | :x: | :x: | :heavy_check_mark: 20 | Polynomial time worst-case | :x: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: 21 | Linear time worst-case | :x: | :heavy_check_mark: | :x: | :x: 22 | Linear time possible | :heavy_check_mark: | :heavy_check_mark: | :x: | :heavy_check_mark: 23 | Disambiguation annotations | :x: | :x: | :x: | planned 24 | -------------------------------------------------------------------------------- /examples/Main.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE TemplateHaskellQuotes #-} 2 | {-# LANGUAGE GADTs #-} 3 | {-# LANGUAGE LambdaCase #-} 4 | {-# LANGUAGE OverloadedStrings #-} 5 | 6 | import Gigaparsec 7 | 8 | import Control.Applicative ( Alternative((<|>)) ) 9 | import Data.Char ( intToDigit ) 10 | import Data.Foldable ( asum, traverse_ ) 11 | import Data.GADT.Compare 12 | import Data.Type.Equality 13 | 14 | data E a where 15 | E :: E Int 16 | N :: Int -> E Int 17 | D :: Int -> E Int 18 | NDots :: E () 19 | NDotsGo :: Int -> E () 20 | deriving instance Eq (E a) 21 | deriving instance Ord (E a) 22 | instance GEq E where 23 | geq E E = Just Refl 24 | geq (N x) (N y) | x == y = Just Refl 25 | geq (D x) (D y) | x == y = Just Refl 26 | geq NDots NDots = Just Refl 27 | geq (NDotsGo x) (NDotsGo y) | x == y = Just Refl 28 | geq _ _ = Nothing 29 | instance GCompare E where 30 | gcompare E E = GEQ 31 | gcompare (N x) (N y) = 32 | case compare x y of 33 | LT -> GLT 34 | EQ -> GEQ 35 | GT -> GGT 36 | gcompare (D x) (D y) = 37 | case compare x y of 38 | LT -> GLT 39 | EQ -> GEQ 40 | GT -> GGT 41 | gcompare NDots NDots = GEQ 42 | gcompare (NDotsGo x) (NDotsGo y) = 43 | case compare x y of 44 | LT -> GLT 45 | EQ -> GEQ 46 | GT -> GGT 47 | gcompare E _ = GLT 48 | gcompare _ E = GGT 49 | gcompare N{} _ = GLT 50 | gcompare _ N{} = GGT 51 | gcompare D{} _ = GLT 52 | gcompare _ D{} = GGT 53 | gcompare NDots _ = GLT 54 | gcompare _ NDots = GGT 55 | 56 | digit :: Int -> RHS E Int 57 | digit b = asum [i <$ t (intToDigit i) | i <- [0..b - 1]] 58 | 59 | number :: Int -> RHS E Int 60 | number b = (\x y -> b * x + y) <$> nt (N b) <*> nt (D b) 61 | <|> nt (D b) 62 | 63 | expr :: RHS E Int 64 | expr = (*) <$> nt E <* t '*' <*> nt E 65 | <|> (+) <$> nt E <* t '+' <*> nt E 66 | <|> number 10 67 | 68 | ndots :: RHS E () 69 | ndots = nt (N 10) >>= nt . NDotsGo 70 | 71 | ndotsGo :: Int -> RHS E () 72 | ndotsGo 0 = pure () 73 | ndotsGo n = t '.' *> nt (NDotsGo (n - 1)) 74 | 75 | mkE :: E a -> CFG E a 76 | mkE e = CFG e $ \case 77 | E -> expr 78 | N b -> number b 79 | D b -> digit b 80 | NDots -> ndots 81 | NDotsGo n -> ndotsGo n 82 | 83 | main :: IO () 84 | main = do 85 | -- simple left-recursive 86 | putStrLn "Should succeed:" 87 | traverse_ (\x -> print (x, parse (mkE (N 2)) x)) 88 | [ "0" 89 | , "1" 90 | , "00" 91 | , "01" 92 | , "11" 93 | , "00000" 94 | , "01011" 95 | , "11111" 96 | ] 97 | putStrLn "Should fail:" 98 | traverse_ (\x -> print (x, parse (mkE (N 2)) x)) 99 | [ "" 100 | , "X" 101 | , "01X00" 102 | , "1001X" 103 | , "X1101" 104 | ] 105 | 106 | -- more complicated left-recursive 107 | putStrLn "Should succeed:" 108 | traverse_ (\x -> print (x, parse (mkE E) x)) 109 | [ "1+1" 110 | , "1+2+3" 111 | -- , "1+2+3+4+5+6+7+8+9" 112 | , "1+2*3" 113 | ] 114 | 115 | -- monadic 116 | putStrLn "Should succeed:" 117 | traverse_ (\x -> print (x, parse (mkE NDots) x)) 118 | [ "5....." 119 | , "3..." 120 | , "10.........." 121 | ] 122 | putStrLn "Should fail:" 123 | traverse_ (\x -> print (x, parse (mkE NDots) x)) 124 | [ "5...." 125 | , "5......" 126 | , "3....." 127 | , "10........" 128 | ] 129 | 130 | 131 | -- data E a where E :: E Int 132 | 133 | -- deriving instance Eq (E a) 134 | -- deriving instance Ord (E a) 135 | -- instance GEq E where 136 | -- geq E E = Just Refl 137 | -- instance GCompare E where 138 | -- gcompare E E = GEQ 139 | -- deriving instance Show (E a) 140 | 141 | example :: CFG E Int 142 | example = CFG E $ \E -> nt E *> t '+' *> nt E <|> 0 <$ t 'a' 143 | 144 | -- >>> parseCFG example "a+a+a+a+a+a" 145 | -- (G {getG = Rel (fromList [(Comm "E" 0,[(Slot,0,),(Slot,0,)]),(Comm "E" 2,[(Slot,2,),(Slot,0,)]),(Comm "E" 4,[(Slot,2,),(Slot,4,),(Slot,0,)]),(Comm "E" 6,[(Slot,0,),(Slot,2,),(Slot,4,),(Slot,6,),(Slot,0,)]),(Comm "E" 8,[(Slot,0,),(Slot,2,),(Slot,0,),(Slot,0,),(Slot,2,),(Slot,0,),(Slot,4,),(Slot,6,),(Slot,8,),(Slot,0,)]),(Comm "E" 10,[(Slot,0,),(Slot,2,),(Slot,0,),(Slot,2,),(Slot,0,),(Slot,0,),(Slot,2,),(Slot,0,),(Slot,0,),(Slot,0,),(Slot,2,),(Slot,0,),(Slot,0,),(Slot,2,),(Slot,0,),(Slot,4,),(Slot,0,),(Slot,0,),(Slot,4,),(Slot,0,),(Slot,6,),(Slot,8,),(Slot,10,),(Slot,0,)])])},P {getP = Rel (fromList [(Comm "E" 0,[11,11,11,11,9,11,11,11,11,9,11,11,11,9,7,11,11,9,11,11,11,11,9,11,11,9,7,5,11,11,11,9,11,11,11,9,7,11,11,9,11,11,11,11,9,11,11,11,9,7,11,11,9,11,11,11,9,11,11,11,9,7,5,3,1]),(Comm "E" 2,[11,11,11,11,9,11,11,11,9,11,11,9,7,11,11,11,9,11,11,9,7,5,3]),(Comm "E" 4,[11,11,11,9,11,11,9,7,5]),(Comm "E" 6,[11,11,9,7]),(Comm "E" 8,[11,9]),(Comm "E" 10,[11])])},True) 146 | 147 | -- data N a where N :: N Int 148 | -- deriving instance Eq (N a) 149 | -- deriving instance Ord (N a) 150 | -- deriving instance Show (N a) 151 | -- instance GEq N where 152 | -- geq N N = Just Refl 153 | -- instance GCompare N where 154 | -- gcompare N N = GEQ 155 | -- instance GShow N where 156 | -- gshowsPrec _ N = showString "N" 157 | 158 | example3 :: CFG E Int 159 | example3 = CFG E $ \E -> (+ 1) <$ t 'a' <*> nt E <|> pure 0 160 | 161 | example4 :: CFG E Int 162 | example4 = CFG E $ \E -> (+ 1) <$> nt E <* t 'a' <|> pure 0 163 | 164 | -- Turns out example3 takes quadratic space, I hope this can be fixed 165 | 166 | -- >>> parse example3 "aaaa" 167 | -- [4] 168 | 169 | -- >>> parse example4 "aaaa" 170 | -- [4] 171 | 172 | -- main :: IO () 173 | -- -- main = print (parseCFG example "a+a+a") 174 | -- 175 | -- main = do 176 | -- print $ parseCFG example3 (Text.pack "aaaa") 177 | -- print $ parseCFG example4 (Text.pack "aaaa") 178 | -- -- result <- 179 | -- -- fits $ 180 | -- -- mkFitConfig 181 | -- -- (\n -> (\(T3 _ _ b) -> b) $ parseCFG example4 (Text.replicate (fromIntegral n) (Text.pack "a"))) 182 | -- -- (1000, 1000000) 183 | -- -- mapM_ print result 184 | -- 185 | -------------------------------------------------------------------------------- /experiments/Experiment1.hs: -------------------------------------------------------------------------------- 1 | {-# OPTIONS_GHC -Wall #-} 2 | {-# LANGUAGE GADTs, Arrows #-} 3 | 4 | import Prelude hiding (id, (.)) 5 | import Control.Category 6 | import Control.Arrow 7 | 8 | data Parser' p a b where 9 | Id :: Parser' p a a 10 | Arr :: (a -> x) -> Parser p x b -> Parser' p a b 11 | Port :: Parser p a1 x -> Parser p (Either x a2, a3) b -> Parser' p (Either a1 a2, a3) b 12 | Match :: Char -> Parser p a b -> Parser' p a b 13 | Free :: p (Parser p) a1 x -> Parser p (x, a2) b -> Parser' p (a1, a2) b 14 | 15 | instance Category (Parser' p) where 16 | id = Id 17 | k . Id = k 18 | k . (Match c p) = Match c (Parser [k] . p) 19 | k . (Arr f p) = Arr f (Parser [k] . p) 20 | k . (Port p q) = Port p (Parser [k] . q) 21 | k . (Free x p) = Free x (Parser [k] . p) 22 | 23 | assocr :: ((a,b),c) -> (a,(b,c)) 24 | assocr ((a,b),c) = (a,(b,c)) 25 | 26 | assocl :: (a,(b,c)) -> ((a,b),c) 27 | assocl (a,(b,c)) = ((a,b),c) 28 | 29 | instance Arrow (Parser' p) where 30 | arr f = Arr f id 31 | first Id = Id 32 | first (Arr f k) = Arr (first f) (first k) 33 | first (Port p k) = Arr assocr (Parser [Port p (Parser [Arr assocl (first k)])]) 34 | first (Match c k) = Match c (first k) 35 | first (Free x k) = Arr assocr (Parser [Free x (Parser [Arr assocl (first k)])]) 36 | 37 | newtype Parser p a b = Parser [Parser' p a b] 38 | 39 | instance ArrowZero (Parser p) where 40 | zeroArrow = Parser [] 41 | 42 | instance ArrowPlus (Parser p) where 43 | Parser ps <+> Parser qs = Parser (ps ++ qs) 44 | 45 | instance Category (Parser p) where 46 | id = Parser [Id] 47 | p0 . Parser qs = foldr (<+>) zeroArrow $ map (composeL p0) qs where 48 | composeL k Id = k 49 | composeL k (Match c p) = Parser [Match c (k . p)] 50 | composeL k (Arr f p) = Parser [Arr f (k . p)] 51 | composeL k (Port p q) = Parser [Port p (k . q)] 52 | composeL k (Free x p) = Parser [Free x (k . p)] 53 | 54 | instance Arrow (Parser p) where 55 | arr f = Parser [Arr f id] 56 | first (Parser ps) = Parser (map first ps) 57 | 58 | instance ArrowChoice (Parser p) where 59 | left p = arr (,()) >>> Parser [Port p id] >>> arr fst 60 | 61 | char :: Char -> Parser p a a 62 | char c = Parser [Match c id] 63 | 64 | string :: String -> Parser p a a 65 | string [] = id 66 | string (x:xs) = char x >>> string xs 67 | 68 | send :: p (Parser p) a b -> Parser p a b 69 | send x = Parser [Arr (,()) (Parser [Free x (arr fst)])] 70 | 71 | parse :: forall p a b. (forall x y. p (Parser p) x y -> Parser p x y) -> p (Parser p) a b -> String -> a -> [b] 72 | parse g p0 xs0 x0 = map fst $ go x0 xs0 (g p0) where 73 | go :: c -> String -> Parser p c d -> [(d, String)] 74 | go x xs (Parser ps) = go' x xs =<< ps 75 | go' :: c -> String -> Parser' p c d -> [(d, String)] 76 | go' x xs Id = [(x, xs)] 77 | go' x xs (Arr f k) = go (f x) xs k 78 | go' y (x:xs) (Match c k) | x == c = go y xs k 79 | go' _ _ Match{} = [] 80 | go' x xs (Port p k) = 81 | case x of 82 | (Left x1,y) -> do 83 | (x', xs') <- go x1 xs p 84 | go (Left x', y) xs' k 85 | (Right x2, y) -> go (Right x2, y) xs k 86 | go' x xs (Free p k) = 87 | case x of 88 | (x', y) -> go x' xs (k . arr (,y) . g p) -- TODO avoid left-recursion 89 | 90 | -- E(l,r) ::= [4 >= l] '-' E(l,4) //4 91 | -- | [3 >= r, 3 >= l] E(3,3) '*' E(l,4) //3 92 | -- | [2 >= r, 2 >= l] E(2,2) '+' E(l,3) //2 93 | -- | [1 >= l] 'if' E(0,0) 'then' E(0,0) 'else' E(0,0) //1 94 | -- | a 95 | 96 | guardA :: (ArrowChoice a, ArrowZero a) => a Bool () 97 | guardA = proc b -> 98 | if b 99 | then returnA -< () 100 | else zeroArrow -< () 101 | 102 | data E p a b where 103 | E :: E p (Int, Int) Expr 104 | 105 | data Expr = Neg Expr | Mul Expr Expr | Add Expr Expr | ITE Expr Expr Expr | A 106 | deriving Show 107 | 108 | gram :: E p a b -> Parser E a b 109 | gram E = 110 | proc (l, r) -> do 111 | guardA -< 4 >= l 112 | char '-' -< () 113 | x <- send E -< (l, 4) 114 | returnA -< Neg x 115 | <+> do 116 | guardA -< 3 >= r && 3 >= l 117 | x <- send E -< (3, 3) 118 | char '*' -< () 119 | y <- send E -< (l, 4) 120 | returnA -< Mul x y 121 | <+> do 122 | guardA -< 2 >= r && 2 >= l 123 | x <- send E -< (2, 2) 124 | char '+' -< () 125 | y <- send E -< (l, 3) 126 | returnA -< Add x y 127 | <+> do 128 | guardA -< 1 >= l 129 | string "if" -< () 130 | b <- send E -< (0, 0) 131 | string "then" -< () 132 | x <- send E -< (0, 0) 133 | string "else" -< () 134 | y <- send E -< (0, 0) 135 | returnA -< ITE b x y 136 | <+> do 137 | char 'a' -< () 138 | returnA -< A 139 | 140 | main :: IO () 141 | main = gram `seq` pure () -------------------------------------------------------------------------------- /experiments/Experiment2.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE GADTs #-} 2 | {-# LANGUAGE OverloadedStrings #-} 3 | {-# LANGUAGE BlockArguments #-} 4 | {-# LANGUAGE LambdaCase #-} 5 | {-# LANGUAGE DerivingVia #-} 6 | 7 | {- 8 | To deal with *left recursion*, we essentially transform the grammar 9 | following this general example: 10 | 11 | X ::= X Y | Z ==> X ::= Z Y* (1) 12 | 13 | Where Y* means repeating Y zero or more times. And note that any 14 | left-recursive nonterminal can be written in this form (if we allow an 15 | in-line disjuction operator or add more nonterminals), e.g.: 16 | 17 | X ::= X + X | X - X | 0 | 1 18 | ==> 19 | X ::= X (+ X | - X) | (0 | 1) (2) 20 | ==> 21 | X ::= (0 | 1) (+ X | - X)* 22 | 23 | There are two main edge-cases: indirect left-recursion and empty 24 | productions. 25 | 26 | We deal with *indirect left-recursion* using a combination of a static 27 | analysis, before parsing, and dynamic checks, during parsing. 28 | 29 | * Statically, we recursively look through all nonterminals which are in 30 | leftmost position to search for possible left-recursion. For each 31 | left-recursive loop we find, we collect the continuation, e.g. Y in (1) 32 | or + X and - X in (2). 33 | 34 | This is done in the 'loops' function. 35 | 36 | * Dynamically, we prevent entering the same nonterminal twice by keeping 37 | track of the visited nonterminals in a set. We clear the set whenever 38 | the parser consumes an actual character. 39 | 40 | This is done in the 'parse' function. 41 | 42 | As for *empty productions*, we don't deal with those yet. For now it is 43 | not that bad to limit ourselves to non-empty productions manually. However, we 44 | do plan on resolving it before a 1.0 release. There seem to be two promising 45 | approaches: 46 | 47 | * Statically transform the grammar to factor out nonterminals which accept 48 | the empty string. This could cause nonterminals to expand quadratically 49 | if done naively, e.g.: 50 | 51 | X ::= X1 X2 X3 X4 52 | X' ::= X1' X2 X3 X4 53 | | X1 X2' X3 X4 54 | | X1 X2 X3' X4 55 | | X1 X2 X3 X4' 56 | 57 | Where the primes indicate the non-empty variant of each nonterminal. 58 | 59 | It's also be possible to limit the blowup to be be linear if we add 60 | more helper nonterminals, e.g.: 61 | 62 | X2345 ::= X2 X345 63 | X345 ::= X3 X45 64 | X45 ::= X4 X5 65 | 66 | X' ::= X1' X2345 67 | | X1 X2345' 68 | X2345' ::= X2' X345 69 | | X2 X345' 70 | X345' ::= X3' X45 71 | | X3 X45' 72 | X45' ::= X4' X5 73 | | X4 X5' 74 | 75 | * Dynamically enforce that input is consumed and bail out otherwise. 76 | -} 77 | 78 | module Experiment2 where 79 | 80 | import Control.Applicative 81 | import Data.Char 82 | import Data.Type.Equality 83 | import Data.Set (Set) 84 | import qualified Data.Set as Set 85 | import Control.Monad 86 | import Data.Some 87 | import Data.GADT.Compare 88 | import Data.String 89 | import Data.Kind 90 | import Data.Functor.Identity 91 | import Control.Monad.State 92 | import Data.Map (Map) 93 | import Data.Map qualified as Map 94 | import Unsafe.Coerce (unsafeCoerce) 95 | import Data.Void 96 | import Data.Functor.Compose 97 | import Control.Monad.Writer 98 | 99 | newtype P t f a = P { alts :: t (P' f a) } 100 | deriving (Functor, Applicative, Alternative) via Compose t (P' f) 101 | 102 | traverseAlts :: (Traversable t, Applicative m) => (P' f a -> m (P' f' b)) -> P t f a -> m (P t f' b) 103 | traverseAlts f (P as) = P <$> traverse f as 104 | 105 | data P' f a = Pure a | Match Char (P' f a) | forall b. Free (f b) (P' f (b -> a)) 106 | deriving instance Functor (P' p) 107 | 108 | instance Applicative (P' f) where 109 | pure = Pure 110 | Pure f <*> k' = fmap f k' 111 | Match c k <*> k' = Match c (k <*> k') 112 | Free x k <*> k' = Free x (flip <$> k <*> k') 113 | 114 | char :: Applicative t => Char -> P t p Char 115 | char c = P (pure (Match c (pure c))) 116 | 117 | send :: Applicative t => f a -> P t f a 118 | send x = P (pure (Free x (pure id))) 119 | 120 | parse :: forall f a. (GCompare f) => G [] f -> f a -> String -> [a] 121 | parse (G g) p0 xs0 = map fst $ filter ((== "") . snd) $ go p0 mempty xs0 (g p0) where 122 | 123 | -- We use the set 's :: Set (Some f)' to avoid recursing into the same 124 | -- nonterminal indefinitely. 125 | go :: f b -> Set (Some f) -> String -> P [] f b -> [(b, String)] 126 | go nt s xs (P ps) = go' nt s xs =<< ps 127 | 128 | go' :: f b -> Set (Some f) -> String -> P' f b -> [(b, String)] 129 | go' nt s xs (Pure x) = (x, xs) : (go' nt s xs . fmap ($ x) =<< loops g nt) 130 | -- TODO: what if 'nt' accepts the empty string? 131 | go' nt _ (x:xs) (Match c k) | c == x = go' nt mempty xs k 132 | go' nt s xs (Free x k) | Some x `Set.notMember` s = do 133 | (x', xs') <- go x (Set.insert (Some x) s) xs (g x) 134 | go' nt s xs' (($ x') <$> k) 135 | go' _ _ _ _ = [] 136 | 137 | -- | Find left-recursive loops in the grammar definition 138 | -- For each such loop, return the parser fragment that we would enter after 139 | -- running one loop iteration and exiting the loop. 140 | loops :: forall f a. (GCompare f) => (forall x. f x -> P [] f x) -> f a -> [P' f (a -> a)] 141 | loops g x0 = go mempty (g x0) where 142 | go :: Set (Some f) -> P [] f b -> [P' f (a -> b)] 143 | go s (P ps) = foldMap (go' s) ps 144 | 145 | go' :: Set (Some f) -> P' f b -> [P' f (a -> b)] 146 | go' s (Free x k) 147 | | GEQ <- gcompare x x0 = [k] 148 | | Some x `Set.notMember` s = go (Set.insert (Some x) s) (g x <**> P [k]) 149 | -- TODO: what if 'x' accepts the empty string? 150 | go' _ _ = [] 151 | 152 | newtype G t f = G (forall x. f x -> P t f x) 153 | 154 | -------------------------------------------------------------------------------- 155 | -- Examples 156 | -------------------------------------------------------------------------------- 157 | 158 | data Gram a where 159 | Digit :: Gram Int 160 | Number :: Gram Int 161 | deriving instance Show (Gram a) 162 | 163 | instance GEq Gram where 164 | geq Digit Digit = Just Refl 165 | geq Number Number = Just Refl 166 | geq _ _ = Nothing 167 | 168 | instance GCompare Gram where 169 | gcompare Digit Digit = GEQ 170 | gcompare Digit Number = GLT 171 | gcompare Number Number = GEQ 172 | gcompare Number Digit = GGT 173 | 174 | -- >>> parse gram Number "314" 175 | -- [314] 176 | 177 | gram :: Gram a -> P [] Gram a 178 | gram Digit = asum [n <$ char (intToDigit n) | n <- [0..9]] 179 | gram Number = send Digit <|> (\hd d -> hd * 10 + d) <$> send Number <*> send Digit 180 | 181 | data E a where 182 | E :: Int -> Int -> E Expr 183 | deriving instance Show (E a) 184 | 185 | instance GEq E where 186 | geq (E a b) (E c d) 187 | | a == c && b == d = Just Refl 188 | | otherwise = Nothing 189 | 190 | instance GCompare E where 191 | gcompare (E a b) (E c d) 192 | | a < c || a == c && b < d = GLT 193 | | a == c && b == d = GEQ 194 | | otherwise = GGT 195 | 196 | data Expr = Neg Expr | Expr :*: Expr | Expr :+: Expr | ITE Expr Expr Expr | A 197 | deriving Show 198 | 199 | string :: Applicative t => String -> P t p String 200 | string (x:xs) = (:) <$> char x <*> string xs 201 | string [] = pure "" 202 | 203 | gramE :: (Alternative t, Applicative t) => G t E 204 | gramE = G $ \(E l r) -> 205 | Neg <$ guard (4 >= l) <* char '-' <*> send (E l 4) 206 | <|> (:*:) <$ guard (3 >= r && 3 >= l) <*> send (E 3 3) <* char '*' <*> send (E l 4) 207 | <|> (:+:) <$ guard (2 >= r && 2 >= l) <*> send (E 2 2) <* char '+' <*> send (E l 3) 208 | <|> ITE <$ guard (1 >= l) <* string "if " <*> send (E 0 0) <* string " then " <*> send (E 0 0) <* string " else " <*> send (E 0 0) 209 | <|> A <$ char 'a' 210 | 211 | -- >>> parse gramE (E 0 0) "if a+a then -a else a+a*-a+a" 212 | -- [ITE (A :+: A) (Neg A) ((A :+: (A :*: Neg A)) :+: A)] 213 | 214 | -- Desugar: 215 | -- 216 | -- E ::= E '*' E left 217 | -- > E '+' E left 218 | -- | '(' E ')' 219 | -- | a 220 | -- 221 | -- To: 222 | -- 223 | -- E(p) ::= [2 >= p] E(2) * E(3) 224 | -- | [1 >= p] E(0) * E(2) 225 | -- | '(' E(0) ')' 226 | -- | a 227 | 228 | type E2 :: Type -> Type 229 | data E2 a where 230 | E2 :: E2 Expr 231 | instance GEq E2 where 232 | geq E2 E2 = Just Refl 233 | instance GCompare E2 where 234 | gcompare E2 E2 = GEQ 235 | 236 | data Assoc = BothAssoc | LeftAssoc | RightAssoc | NoneAssoc 237 | 238 | -- Assoc forms a lattice like this: 239 | -- 240 | -- None 241 | -- / \ 242 | -- Left Right 243 | -- \ / 244 | -- Both 245 | 246 | instance Semigroup Assoc where 247 | BothAssoc <> x = x 248 | x <> BothAssoc = x 249 | LeftAssoc <> LeftAssoc = LeftAssoc 250 | RightAssoc <> RightAssoc = RightAssoc 251 | _ <> _ = NoneAssoc 252 | instance Monoid Assoc where 253 | mempty = BothAssoc 254 | newtype X a = X [[(a, Assoc)]] 255 | deriving (Functor, Applicative) via Compose [] (Compose [] (Writer Assoc)) 256 | instance Alternative X where 257 | empty = X [[]] 258 | X xs0 <|> X ys0 = X (go xs0 ys0) where 259 | -- appends the last element of xs with the first element of ys 260 | go [] ys = ys 261 | go xs [] = xs 262 | go [x] (y:ys) = (x ++ y) : ys 263 | go (x:xs) ys = x : go xs ys 264 | 265 | infixl 2 >|> 266 | 267 | (>|>) :: P X f a -> P X f a -> P X f a 268 | (>|>) (P (X xs)) (P (X ys)) = P (X (xs ++ ys)) 269 | 270 | left :: P X f a -> P X f a 271 | left (P (X xs)) = P (X (getCompose (fmap (\(x,_) -> (x, LeftAssoc)) (Compose xs)))) 272 | 273 | -- (<*<) :: P X E2 (a -> b) -> P X E2 a -> P X E2 b 274 | -- x <*< y = send (x :<*< y) 275 | 276 | instance (Applicative t, a ~ String) => IsString (P t f a) where 277 | fromString = string 278 | 279 | gramE2 :: G X E2 280 | gramE2 = G $ \E2 -> let e = send E2 in 281 | left ((:*:) <$> e <* "*" <*> e) 282 | >|> left ((:+:) <$> e <* "+" <*> e) 283 | <|> "(" *> e <* ")" 284 | <|> A <$ "a" 285 | 286 | -- -- The desugaring to data dependent grammars should proceed like this: 287 | -- -- 288 | -- -- E = ... X >|> Y ... 289 | -- -- ==> 290 | -- -- (E b) = ... (guard b *> X False) <|> Y True ... 291 | -- -- 292 | -- -- E = ... X <*< Y ... 293 | -- -- ==> 294 | -- -- (E b) = ... (guard b *> X True) <*> Y False ... 295 | -- -- 296 | -- -- (If the same expression has multiple occurrences of >|> and <*<, 297 | -- -- then the booleans could be combined into an int as an optmization.) 298 | -- -- 299 | -- -- The major remaining problem is that each occurrence of such a special 300 | -- -- disambiguation operator requires its own boolean. That's hard to do 301 | -- -- in a type-safe way. I could perhaps do something like Map Key Bool, 302 | -- -- but how can I identify these operators? Would I have to use observable 303 | -- -- sharing techniques again? 304 | -- -- 305 | -- -- One option may be to identify these operators by the location in the 306 | -- -- free applicative at which they occur. 307 | -- 308 | -- -- I want to try creating a new nonterminal for each occurrence of these 309 | -- -- operators. Then each can be individually guarded. Each occurrence can be 310 | -- -- identified by its ordinal. 311 | -- 312 | -- type Y :: (Type -> Type) -> (Type -> Type) -> Type -> Type 313 | -- data Y f m a where 314 | -- Y :: f a -> Y f m a 315 | -- Y' :: Int -> Bool -> Y f m a 316 | -- instance GEq f => GEq (Y f m) where 317 | -- geq (Y x) (Y y) = geq x y 318 | -- geq (Y' i0 b0) (Y' i1 b1) = if i0 == i1 && b0 == b1 then Just (unsafeCoerce Refl) else Nothing 319 | -- geq _ _ = Nothing 320 | -- instance GCompare f => GCompare (Y f m) where 321 | -- gcompare (Y x) (Y y) = gcompare x y 322 | -- gcompare (Y' i0 b0) (Y' i1 b1) = 323 | -- case compare i0 i1 <> compare b0 b1 of 324 | -- LT -> GLT 325 | -- EQ -> unsafeCoerce GEQ 326 | -- GT -> GGT 327 | -- gcompare Y{} Y'{} = GLT 328 | -- gcompare Y'{} Y{} = GGT 329 | -- 330 | -- 331 | -- 332 | -- bla :: P' (X f) a -> State (Int, Map Int (Some (P (Y f)))) (P' (Y f) a) 333 | -- bla (Pure x) = pure (Pure x) 334 | -- bla (Match c k) = Match c <$> traverseAlts bla k 335 | -- bla (Free (X op) k) = Free (Y op) <$> traverseAlts bla k 336 | -- bla (Free (x :<*< y) k) = do 337 | -- x' <- traverseAlts bla x 338 | -- y' <- traverseAlts bla y 339 | -- (i, m) <- get 340 | -- put (i + 1, Map.insert i (Some (x' <*> y')) m) 341 | -- Free (Y' i True) <$> traverseAlts bla k 342 | -- bla (Free (x :>|> y) k) = do 343 | -- x' <- traverseAlts bla x 344 | -- y' <- traverseAlts bla y 345 | -- (i, m) <- get 346 | -- put (i + 1, Map.insert i (Some (x' <|> y')) m) 347 | -- Free (Y' i True) <$> traverseAlts bla k 348 | -- 349 | -- class Funny f where 350 | -- fun :: Applicative m => (forall x. P t f x -> m (P t f' x)) -> G t f -> m (G t f) 351 | -- 352 | -- instance Funny E2 where 353 | -- fun f (G g) = (\x -> G $ \E2 -> x) <$> f (g E2) 354 | -- 355 | -- fun' :: (Funny f, Applicative m) => (forall x. P' t f x -> m (P' t f' x)) -> G t f -> m (G f') 356 | -- fun' f g = fun (traverseAlts f) g 357 | -- 358 | -- desugar :: Funny f => G f (X f) -> G (Y f m) (Y f) 359 | -- desugar g = let (G g', (_, m)) = runState (fun' bla g) (0, Map.empty) in G $ \case 360 | -- Y x -> g' x 361 | -- Y' i b -> guard b *> case m Map.! i of Some x -> unsafeCoerce x 362 | -- 363 | -- example :: [Expr] 364 | -- example = parse (desugar gramE2) (Y E2) "1+2*3" 365 | -- 366 | -- -- >>> example 367 | -- -- [] 368 | -- 369 | -------------------------------------------------------------------------------- /experiments/Experiment3.hs: -------------------------------------------------------------------------------- 1 | 2 | import Data.List qualified as List 3 | import Test.Tasty.Bench.Fit (fit, mkFitConfig) 4 | import Data.Text (Text) 5 | import Data.Text qualified as Text 6 | import Data.IntSet (IntSet) 7 | import Data.IntSet qualified as IntSet 8 | import Data.IntMap.Strict (IntMap) 9 | import Data.IntMap.Strict qualified as IntMap 10 | import Debug.Trace 11 | import Data.Function 12 | import Data.Bifunctor 13 | 14 | data CFG = CFG String [(String, [[Symbol]])] 15 | 16 | data Symbol = T Char | NT String 17 | 18 | (!) :: Eq k => [(k, v)] -> k -> v 19 | xs ! x = case lookup x xs of Just y -> y 20 | 21 | lfpFrom :: (t -> t -> Bool) -> t -> (t -> t) -> t 22 | lfpFrom eqT x0 f = go (0 :: Int) x0 where 23 | go n _ | traceShow n False = undefined 24 | go n x = let y = f x in if eqT x y then x else go (n + 1) y 25 | 26 | type Table = [(String, IntMap IntSet)] 27 | type ToDos = [(String, Int)] 28 | 29 | 30 | denoteCFG :: CFG -> Text -> IntSet 31 | denoteCFG (CFG start g) xs = m ! start IntMap.! 0 32 | where 33 | m :: Table 34 | m = 35 | lfpFrom ((==) `on` (map (second (IntMap.map IntSet.size)))) 36 | [(nt, IntMap.fromList [(i, IntSet.empty) | i <- [0.. Text.length xs]]) | nt <- nts] 37 | ( \m' -> 38 | [ (nt, IntMap.fromList [(i, foldMap (\p -> denoteProd xs p m' i) (g ! nt)) | i <- [0 .. Text.length xs]]) 39 | | nt <- nts 40 | ] 41 | ) 42 | 43 | nts = map fst g 44 | 45 | bind :: IntSet -> (Int -> IntSet) -> IntSet 46 | bind s k = foldMap k $ IntSet.elems s 47 | 48 | denoteProd :: Text -> [Symbol] -> Table -> Int -> IntSet 49 | denoteProd _ [] _ i = IntSet.singleton i 50 | denoteProd xs (s : ss) m i = denoteSymbol xs s m i `bind` \j -> denoteProd xs ss m j 51 | 52 | denoteSymbol :: Text -> Symbol -> Table -> Int -> IntSet 53 | denoteSymbol xs (T c) _ i 54 | | i < Text.length xs && c == Text.index xs i = IntSet.singleton (i + 1) 55 | | otherwise = IntSet.empty 56 | denoteSymbol _ (NT nt) m i = m ! nt IntMap.! i 57 | 58 | example :: CFG 59 | example = CFG "E" [("E", [[NT "E", T '+', NT "E"], [T 'a']])] 60 | 61 | example2 = CFG "N" [("N", [[NT "N", T 'a'], [T 'a']])] 62 | example3 = CFG "N" [("N", [[T 'a', NT "N"], []])] 63 | 64 | main :: IO () 65 | -- main = print $ denoteCFG example (Text.pack ('a' : concat (replicate 1000 "+a"))) 66 | -- main = print =<< fit (mkFitConfig (\n -> denoteCFG example (Text.pack ('a' : concat (replicate (fromIntegral n) "+a")))) (0, 500)) 67 | main = print $ denoteCFG example3 (Text.replicate 100 (Text.pack "a")) 68 | -- main = print =<< fit (mkFitConfig (\n -> denoteCFG example3 (Text.replicate (fromIntegral n) (Text.pack "a"))) (0, 1000)) 69 | 70 | 71 | 72 | 73 | -- {-# LANGUAGE LambdaCase #-} 74 | -- {-# LANGUAGE GADTs #-} 75 | -- import Data.List qualified as List 76 | -- import Test.Tasty.Bench.Fit (fit, mkFitConfig) 77 | -- import Control.DeepSeq 78 | -- 79 | -- data Free f a = Pure a | forall x. Free (f x) (x -> Free f a) 80 | -- 81 | -- data CFG f a = CFG (f a) (forall x. f x -> [Free (Symbol f) x]) 82 | -- 83 | -- data Symbol f a where 84 | -- T :: Char -> Symbol f () 85 | -- NT :: f a -> Symbol f a 86 | -- 87 | -- class Funny f where 88 | -- fun :: Applicative g => (f a -> g b) -> g (f a -> b) 89 | -- 90 | -- class EqCon f where 91 | -- eqCon :: Con f [] -> Con f [] -> Bool 92 | -- 93 | -- splits :: String -> [(String, String)] 94 | -- splits [] = [([], [])] 95 | -- splits xs@(x : xs') = ([], xs) : map (\(y, z) -> (x : y, z)) (splits xs') 96 | -- 97 | -- (!) :: Eq k => [(k, v)] -> k -> [v] 98 | -- xs ! x = map snd $ filter ((== x) . fst) xs 99 | -- 100 | -- lfpFrom :: (t -> t -> Bool) -> t -> (t -> t) -> t 101 | -- lfpFrom eq x f = let y = f x in if eq x y then x else lfpFrom eq y f 102 | -- 103 | -- newtype Con f g = Con { appCon :: forall x. f x -> g x } 104 | -- 105 | -- denoteCFG :: forall f a. EqCon f => CFG f a -> String -> [a] 106 | -- denoteCFG (CFG start g) xs = (\c -> appCon c start) =<< m ! xs 107 | -- where 108 | -- m :: [(String, Con f [])] 109 | -- m = 110 | -- lfpFrom ((and .) . zipWith (\(x1,x2) (y1,y2) -> x1 == y1 && eqCon x2 y2)) 111 | -- [(xs', Con (const [])) | xs' <- List.tails xs] 112 | -- ( \m' -> 113 | -- [ (xs', Con (\nt -> (\p -> denoteProd p m' xs') =<< (g nt))) 114 | -- | xs' <- List.tails xs 115 | -- ] 116 | -- ) 117 | -- 118 | -- denoteProd :: Free (Symbol f) a -> [(String, Con f [])] -> String -> [a] 119 | -- denoteProd (Pure x) = \_ xs -> [x | null xs] 120 | -- denoteProd (Free s k) = \m xs -> (\(y, z) -> denoteSymbol s m y >>= \x -> denoteProd (k x) m z) =<< (splits xs) 121 | -- 122 | -- denoteSymbol :: Symbol f a -> [(String, Con f [])] -> String -> [a] 123 | -- denoteSymbol (T c) _ [x] = [() | c == x] 124 | -- denoteSymbol T{} _ _ = [] 125 | -- denoteSymbol (NT nt) m xs = (\c -> appCon c nt) =<< m ! xs 126 | -- 127 | -- data Expr = Plus Expr Expr | A deriving Show 128 | -- 129 | -- data E a where E :: E Expr 130 | -- 131 | -- instance EqCon E where 132 | -- eqCon (Con f) (Con g) = length (f E) == length (g E) 133 | -- 134 | -- -- instance Funny E where 135 | -- -- fun g = let y = g E in _ 136 | -- 137 | -- instance NFData Expr where 138 | -- rnf (Plus x y) = rnf (x, y) 139 | -- rnf A = () 140 | -- 141 | -- example :: CFG E Expr 142 | -- example = CFG E (\case E -> [Free (NT E) $ \x -> Free (T '+') $ \() -> Free (NT E) $ \y -> Pure $ Plus x y, Free (T 'a') $ \() -> Pure A]) 143 | -- 144 | -- main :: IO () 145 | -- main = print =<< fit (mkFitConfig (\n -> null $ denoteCFG example ('a' : concat (replicate (fromIntegral n) "+a"))) (0, 8)) 146 | -- -------------------------------------------------------------------------------- /experiments/Experiment4.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE TypeFamilies #-} 2 | {-# LANGUAGE LambdaCase #-} 3 | {-# OPTIONS_GHC -Wall #-} 4 | 5 | import Data.Map.Strict (Map) 6 | -- import Data.Set (Set) 7 | import Control.Applicative 8 | import Control.Monad 9 | import Data.Map.Strict qualified as Map 10 | -- import GHC.Base (Any) 11 | -- import Debug.Trace 12 | import Test.Tasty.Bench.Fit 13 | import Data.Text qualified as Text 14 | import Data.Text (Text) 15 | import Data.Some 16 | import Data.Functor.Identity 17 | import Data.GADT.Show 18 | import Data.Bifunctor 19 | import Unsafe.Coerce (unsafeCoerce) 20 | import Data.GADT.Compare 21 | import Data.Type.Equality 22 | 23 | -- Blog topic: static type safety breaks modularity 24 | 25 | data RHS f a = Pure a | T Char (RHS f a) | forall x. NT (f x) (x -> RHS f a) | Or (RHS f a) (RHS f a) | Fail 26 | deriving instance Functor (RHS f) 27 | 28 | instance Applicative (RHS f) where 29 | pure = Pure 30 | (<*>) = ap 31 | 32 | instance Alternative (RHS f) where 33 | (<|>) = Or 34 | empty = Fail 35 | 36 | instance Monad (RHS f) where 37 | Pure x >>= k = k x 38 | T c k >>= k' = T c (k >>= k') 39 | NT f k >>= k' = NT f (k >=> k') 40 | Or p q >>= k = Or (p >>= k) (q >>= k) 41 | Fail >>= _ = Fail 42 | 43 | data CFG f a = CFG (f a) (forall x. f x -> RHS f x) 44 | 45 | data T3 a b c = T3 !a !b !c deriving Show 46 | 47 | data Comm f = Comm !(Some f) !Int deriving (Eq, Ord, Show) 48 | 49 | newtype Cont f a = Cont { getCont :: Text -> Descr -> a -> Command f } 50 | instance Show (Cont f a) where 51 | show _ = "" 52 | 53 | data Descr = Descr Slot !Int !Int 54 | data Slot = Slot -- String [Symbol] [Symbol] 55 | deriving Show 56 | 57 | newtype Rel a b = Rel (Map a [b]) deriving Show 58 | 59 | rel :: Ord a => Rel a b -> a -> [b] 60 | rel (Rel m) x = Map.findWithDefault [] x m 61 | 62 | relMay :: Ord a => Rel a b -> a -> Maybe [b] 63 | relMay (Rel m) x = Map.lookup x m 64 | 65 | initRel :: Ord a => a -> Rel a b -> Rel a b 66 | initRel x (Rel m) = Rel (Map.insertWith (++) x [] m) 67 | 68 | addRel :: Ord a => a -> b -> Rel a b -> Rel a b 69 | addRel x y (Rel m) = Rel (Map.insertWith (++) x [y] m) 70 | 71 | instance GShow Identity where 72 | gshowsPrec _ _ = showString "" 73 | instance GShow (Cont f) where 74 | gshowsPrec _ _ = showString "" 75 | 76 | -- newtype U = U (Set Descr) 77 | newtype G f = G { getG :: Rel (Comm f) (Slot, Int, Some (Cont f)) } deriving Show 78 | newtype P f = P { getP :: Rel (Comm f) (Int, Some Identity) } deriving Show 79 | 80 | newtype Command f = Command { getCommand :: forall x. T3 (G f) (P f) (Maybe x) -> T3 (G f) (P f) (Maybe x) } 81 | 82 | newtype M f a = M { getM :: Text -> Descr -> Cont f a -> Command f } 83 | 84 | extents :: GCompare f => f a -> M f (Maybe [(Int, a)]) 85 | extents nt = M $ \inp dsc@(Descr _ _ i) (Cont k) -> 86 | Command $ \(T3 g p b) -> -- trace ("extents " ++ show (nt, i)) $ 87 | getCommand 88 | (k inp dsc ( 89 | let res = relMay (getP p) (Comm (Some nt) i) 90 | in fmap (map (second (\(Some (Identity x)) -> unsafeCoerce x))) res)) 91 | (T3 g (P (initRel (Comm (Some nt) i) (getP p))) b) 92 | 93 | addExtent :: GCompare f => f a -> a -> M f () 94 | addExtent nt x = M $ \inp dsc@(Descr _ l i) (Cont k) -> 95 | Command $ \(T3 g p b) -> -- trace ("addExtent " ++ show (nt, l, i)) $ 96 | getCommand (k inp dsc ()) (T3 g (P (addRel (Comm (Some nt) l) (i, Some (Identity x)) (getP p))) b) 97 | 98 | resume :: GCompare f => f a -> a -> M f a 99 | resume nt x = M $ \inp (Descr Slot l r) _ -> 100 | Command $ \(T3 g p b) -> 101 | let cnts = rel (getG g) (Comm (Some nt) l) in -- trace ("resume " ++ show (nt, l, cnts)) $ 102 | foldr (\(s, l', Some (Cont k)) go -> go . getCommand (unsafeCoerce k inp (Descr s l' r) x)) 103 | id cnts (T3 g p b) 104 | 105 | addCont :: GCompare f => f a -> M f c -> M f c 106 | addCont nt m = M $ \inp dsc@(Descr s l i) k -> 107 | Command $ \(T3 g p b) -> -- trace ("addCont " ++ show (nt, i)) $ 108 | getCommand (getM m inp dsc k) (T3 (G (addRel (Comm (Some nt) i) (s, l, Some k) (getG g))) p b) 109 | 110 | match :: Char -> M f () 111 | match c = M $ \inp (Descr (Slot {- nt alpha beta -}) l i) (Cont k) -> 112 | case Text.uncons inp of 113 | Just (x,inp') | c == x -> k inp' (Descr (Slot {- nt alpha beta -}) l (i + 1)) () 114 | _ -> Command id 115 | 116 | skip :: Int -> M f () 117 | skip r = M $ \inp (Descr s l i) (Cont k) -> k (Text.drop (r - i) inp) (Descr s l r) () 118 | 119 | descend :: M f () 120 | descend = M $ \inp (Descr Slot _ i) (Cont k) -> k inp (Descr Slot i i) () 121 | 122 | -- traceI :: String -> M () 123 | -- traceI msg = M $ \inp dsc@(Descr _ _ i) k -> trace (show i ++ ": " ++ msg) getCont k inp dsc () 124 | 125 | instance Functor (M f) where 126 | fmap f (M p) = M $ \inp dsc (Cont k) -> 127 | p inp dsc $ Cont $ \inp' dsc' x -> 128 | k inp' dsc' (f x) 129 | instance Applicative (M f) where 130 | pure x = M $ \inp dsc (Cont k) -> k inp dsc x 131 | (<*>) = ap 132 | instance Alternative (M f) where 133 | empty = M $ \_ _ _ -> Command id 134 | M p <|> M q = M $ \inp dsc k -> Command (getCommand (q inp dsc k) . getCommand (p inp dsc k)) 135 | instance Monad (M f) where 136 | M p >>= k = M $ \inp dsc k' -> 137 | p inp dsc $ Cont $ \inp' dsc' x -> 138 | getM (k x) inp' dsc' k' 139 | 140 | parseCFG :: forall f a. GCompare f => CFG f a -> Text -> T3 (G f) (P f) (Maybe a) 141 | parseCFG (CFG nt0 prods) inp0 = 142 | getCommand 143 | (getM (parseRHS (NT nt0 pure)) inp0 (Descr Slot 0 0) final) 144 | (T3 (G (Rel mempty)) (P (Rel mempty)) Nothing) where 145 | 146 | final :: Cont f a 147 | final = Cont $ \inp _ x -> Command $ \(T3 p g b) -> (T3 p g (b <|> unsafeCoerce x <$ guard (Text.null inp))) 148 | 149 | parseRHS :: RHS f x -> M f x 150 | parseRHS (Pure x) = pure x 151 | parseRHS (T c k) = parseT c *> parseRHS k 152 | parseRHS (NT f k) = parseNT f >>= parseRHS . k 153 | parseRHS (Or p q) = parseRHS p <|> parseRHS q 154 | parseRHS Fail = empty 155 | 156 | parseNT :: f x -> M f x 157 | parseNT nt = addCont nt $ 158 | extents nt >>= \case 159 | Nothing -> do 160 | descend 161 | x <- parseRHS (prods nt) 162 | addExtent nt x 163 | resume nt x 164 | Just rs -> asum (map (\(r, x) -> x <$ skip r) rs) 165 | 166 | parseT :: Char -> M f () 167 | parseT = match 168 | 169 | t :: Char -> RHS f () 170 | t c = T c (pure ()) 171 | 172 | nt :: f a -> RHS f a 173 | nt f = NT f pure 174 | 175 | data E a where E :: E Int 176 | 177 | deriving instance Eq (E a) 178 | deriving instance Ord (E a) 179 | instance GEq E where 180 | geq E E = Just Refl 181 | instance GCompare E where 182 | gcompare E E = GEQ 183 | deriving instance Show (E a) 184 | 185 | example :: CFG E Int 186 | example = CFG E $ \E -> nt E *> t '+' *> nt E <|> 0 <$ t 'a' 187 | 188 | -- >>> parseCFG example "a+a+a+a+a+a" 189 | -- (G {getG = Rel (fromList [(Comm "E" 0,[(Slot,0,),(Slot,0,)]),(Comm "E" 2,[(Slot,2,),(Slot,0,)]),(Comm "E" 4,[(Slot,2,),(Slot,4,),(Slot,0,)]),(Comm "E" 6,[(Slot,0,),(Slot,2,),(Slot,4,),(Slot,6,),(Slot,0,)]),(Comm "E" 8,[(Slot,0,),(Slot,2,),(Slot,0,),(Slot,0,),(Slot,2,),(Slot,0,),(Slot,4,),(Slot,6,),(Slot,8,),(Slot,0,)]),(Comm "E" 10,[(Slot,0,),(Slot,2,),(Slot,0,),(Slot,2,),(Slot,0,),(Slot,0,),(Slot,2,),(Slot,0,),(Slot,0,),(Slot,0,),(Slot,2,),(Slot,0,),(Slot,0,),(Slot,2,),(Slot,0,),(Slot,4,),(Slot,0,),(Slot,0,),(Slot,4,),(Slot,0,),(Slot,6,),(Slot,8,),(Slot,10,),(Slot,0,)])])},P {getP = Rel (fromList [(Comm "E" 0,[11,11,11,11,9,11,11,11,11,9,11,11,11,9,7,11,11,9,11,11,11,11,9,11,11,9,7,5,11,11,11,9,11,11,11,9,7,11,11,9,11,11,11,11,9,11,11,11,9,7,11,11,9,11,11,11,9,11,11,11,9,7,5,3,1]),(Comm "E" 2,[11,11,11,11,9,11,11,11,9,11,11,9,7,11,11,11,9,11,11,9,7,5,3]),(Comm "E" 4,[11,11,11,9,11,11,9,7,5]),(Comm "E" 6,[11,11,9,7]),(Comm "E" 8,[11,9]),(Comm "E" 10,[11])])},True) 190 | 191 | data N a where N :: N Int 192 | deriving instance Eq (N a) 193 | deriving instance Ord (N a) 194 | deriving instance Show (N a) 195 | instance GEq N where 196 | geq N N = Just Refl 197 | instance GCompare N where 198 | gcompare N N = GEQ 199 | instance GShow N where 200 | gshowsPrec _ N = showString "N" 201 | 202 | example3 :: CFG N Int 203 | example3 = CFG N $ \N -> (+ 1) <$ t 'a' <*> nt N <|> pure 0 204 | 205 | example4 :: CFG N Int 206 | example4 = CFG N $ \N -> (+ 1) <$> nt N <* t 'a' <|> pure 0 207 | 208 | -- >>> parseCFG example3 (Text.pack "aaaa") 209 | -- T3 (G {getG = Rel (fromList [(Comm (Some N) 0,[(Slot,0,Some )]),(Comm (Some N) 1,[(Slot,0,Some )]),(Comm (Some N) 2,[(Slot,1,Some )]),(Comm (Some N) 3,[(Slot,2,Some )]),(Comm (Some N) 4,[(Slot,3,Some )])])}) 210 | -- (P {getP = Rel (fromList [(Comm (Some N) 0,[(0,Some ),(1,Some ),(2,Some ),(3,Some ),(4,Some )]),(Comm (Some N) 1,[(1,Some ),(2,Some ),(3,Some ),(4,Some )]),(Comm (Some N) 2,[(2,Some ),(3,Some ),(4,Some )]),(Comm (Some N) 3,[(3,Some ),(4,Some )]),(Comm (Some N) 4,[(4,Some )])])}) 211 | -- (Just 4) 212 | 213 | -- >>> parseCFG example4 (Text.pack "aaaa") 214 | -- T3 (G {getG = Rel (fromList [(Comm (Some N) 0,[(Slot,0,Some ),(Slot,0,Some )])])}) 215 | -- (P {getP = Rel (fromList [(Comm (Some N) 0,[(4,Some ),(3,Some ),(2,Some ),(1,Some ),(0,Some )])])}) 216 | -- (Just 4) 217 | 218 | main :: IO () 219 | -- main = print (parseCFG example "a+a+a") 220 | 221 | main = do 222 | result <- 223 | fits $ 224 | mkFitConfig 225 | (\n -> (\(T3 _ _ b) -> b) $ parseCFG example4 (Text.replicate (fromIntegral n) (Text.pack "a"))) 226 | (1000, 1000000) 227 | mapM_ print result 228 | -------------------------------------------------------------------------------- /gigaparsec.cabal: -------------------------------------------------------------------------------- 1 | cabal-version: 3.0 2 | name: gigaparsec 3 | version: 0.1.0.0 4 | license: AGPL-3.0-or-later 5 | license-file: LICENSE 6 | author: jaro.reinders@gmail.com 7 | maintainer: Jaro Reinders 8 | build-type: Simple 9 | extra-doc-files: CHANGELOG.md 10 | synopsis: Leightweight generalized parser combinators 11 | category: Parsing 12 | description: 13 | Gigaparsec (Gpc) is a library providing generalized parser combinators (Gpc) 14 | which are able to parse all context-free grammars completely. This includes 15 | support for left-recursion and reporting all possible parses of ambiguous 16 | grammars. 17 | 18 | Gigaparsec is currently only a proof of concept. Of course it needs a much more 19 | elaborate API, but before that I want to implement disambiguation strategies. 20 | I have also not put any effort in making this library performant yet. 21 | tested-with: GHC ==9.2.7 22 | 23 | source-repository head 24 | type: git 25 | location: https://github.com/noughtmare/gigaparsec 26 | 27 | common common 28 | build-depends: base >= 4.14 && <5, containers, text, some 29 | ghc-options: -Wall 30 | default-language: GHC2021 31 | 32 | library 33 | import: common 34 | exposed-modules: Gigaparsec, Gigaparsec.Core 35 | hs-source-dirs: src 36 | 37 | executable gpc-examples 38 | import: common 39 | main-is: Main.hs 40 | hs-source-dirs: examples 41 | build-depends: gigaparsec 42 | 43 | test-suite gpc-test 44 | import: common 45 | type: exitcode-stdio-1.0 46 | hs-source-dirs: tests 47 | main-is: test.hs 48 | build-depends: tasty, tasty-hunit, gigaparsec 49 | 50 | executable gpc-experiment1 51 | import: common 52 | main-is: Experiment1.hs 53 | hs-source-dirs: experiments 54 | 55 | library gpc-experiment2 56 | import: common 57 | exposed-modules: Experiment2 58 | hs-source-dirs: experiments 59 | build-depends: containers, some, mtl 60 | 61 | executable gpc-experiment3 62 | import: common 63 | main-is: Experiment3.hs 64 | hs-source-dirs: experiments 65 | build-depends: containers, some, mtl, tasty-bench-fit, deepseq, text 66 | 67 | -- executable gpc-experiment4 68 | -- import: common 69 | -- main-is: Experiment4.hs 70 | -- hs-source-dirs: experiments 71 | -- build-depends: containers, some, mtl, tasty-bench-fit, deepseq, text 72 | -------------------------------------------------------------------------------- /hie.yaml: -------------------------------------------------------------------------------- 1 | cradle: 2 | cabal: -------------------------------------------------------------------------------- /plnl23/embedding-generalized-parsing-in-haskell.key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/noughtmare/gpc/0b237a966bdf7b0ace8494edc1d0c4679e0fe21c/plnl23/embedding-generalized-parsing-in-haskell.key -------------------------------------------------------------------------------- /plnl23/embedding-generalized-parsing-in-haskell.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/noughtmare/gpc/0b237a966bdf7b0ace8494edc1d0c4679e0fe21c/plnl23/embedding-generalized-parsing-in-haskell.pdf -------------------------------------------------------------------------------- /src/Gigaparsec.hs: -------------------------------------------------------------------------------- 1 | module Gigaparsec (module Gigaparsec.Core) where 2 | 3 | import Gigaparsec.Core -------------------------------------------------------------------------------- /src/Gigaparsec/Core.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE TypeFamilies #-} 2 | {-# LANGUAGE LambdaCase #-} 3 | {-# OPTIONS_GHC -Wall #-} 4 | 5 | module Gigaparsec.Core (CFG (CFG), RHS, Result, t, nt, parse, emptyk') where 6 | 7 | import Data.Map.Strict (Map) 8 | -- import Data.Set (Set) 9 | import Control.Applicative 10 | import Control.Monad 11 | import Data.Map.Strict qualified as Map 12 | -- import GHC.Base (Any) 13 | import Debug.Trace 14 | import Data.Text qualified as Text 15 | import Data.Text (Text) 16 | 17 | import Data.Some 18 | import Data.GADT.Compare 19 | 20 | import Data.Functor.Identity 21 | import Data.Bifunctor 22 | import Unsafe.Coerce (unsafeCoerce) 23 | import Data.GADT.Show 24 | import Data.Type.Equality 25 | 26 | data RHS f a = Pure a | T Char (RHS f a) | forall x. NT (f x) (x -> RHS f a) | Or (RHS f a) (RHS f a) | Fail 27 | deriving instance Functor (RHS f) 28 | 29 | instance Applicative (RHS f) where 30 | pure = Pure 31 | (<*>) = ap 32 | 33 | instance Alternative (RHS f) where 34 | (<|>) = Or 35 | empty = Fail 36 | 37 | instance Monad (RHS f) where 38 | Pure x >>= k = k x 39 | T c k >>= k' = T c (k >>= k') 40 | NT f k >>= k' = NT f (k >=> k') 41 | Or p q >>= k = Or (p >>= k) (q >>= k) 42 | Fail >>= _ = Fail 43 | 44 | data CFG f a = CFG (f a) (forall x. f x -> RHS f x) 45 | 46 | data T3 a b c = T3 !a !b !c deriving Show 47 | 48 | data Comm f = Comm !(Some f) !Int deriving (Eq, Ord, Show) 49 | 50 | newtype Cont f a = Cont { getCont :: Text -> Descr -> a -> Command f } 51 | -- instance Show (Cont f a) where 52 | -- show _ = "" 53 | 54 | data Descr = Descr Slot !Int !Int 55 | data Slot = Slot -- String [Symbol] [Symbol] 56 | deriving Show 57 | 58 | newtype Rel a b = Rel (Map a [b]) deriving Show 59 | 60 | rel :: Ord a => Rel a b -> a -> [b] 61 | rel (Rel m) x = Map.findWithDefault [] x m 62 | 63 | relMay :: Ord a => Rel a b -> a -> Maybe [b] 64 | relMay (Rel m) x = Map.lookup x m 65 | 66 | initRel :: Ord a => a -> Rel a b -> Rel a b 67 | initRel x (Rel m) = Rel (Map.insertWith (++) x [] m) 68 | 69 | addRel :: Ord a => a -> b -> Rel a b -> Rel a b 70 | addRel x y (Rel m) = Rel (Map.insertWith (++) x [y] m) 71 | 72 | relSize :: Rel a b -> Int 73 | relSize (Rel m) = Map.size m 74 | 75 | -- instance GShow Identity where 76 | -- gshowsPrec _ _ = showString "" 77 | -- instance GShow (Cont f) where 78 | -- gshowsPrec _ _ = showString "" 79 | 80 | -- newtype U = U (Set Descr) 81 | newtype G f = G { getG :: Rel (Comm f) (Slot, Int, Some (Cont f)) } -- deriving Show 82 | newtype P f = P { getP :: Rel (Comm f) (Int, Some Identity) } -- deriving Show 83 | 84 | newtype Command f = Command { getCommand :: forall x. T3 (G f) (P f) (Result x) -> T3 (G f) (P f) (Result x) } 85 | 86 | newtype M f a = M { getM :: Text -> Descr -> Cont f a -> Command f } 87 | 88 | extents :: (GCompare f) => f a -> M f (Maybe [(Int, a)]) 89 | extents nt = M $ \inp dsc@(Descr _ _ i) (Cont k) -> 90 | Command $ \(T3 g p b) -> -- trace ("extents " ++ show i) $ 91 | getCommand 92 | (k inp dsc ( 93 | let res = relMay (getP p) (Comm (Some nt) i) 94 | in fmap (map (second (\(Some (Identity x)) -> unsafeCoerce x))) res)) 95 | (T3 g (P (initRel (Comm (Some nt) i) (getP p))) b) 96 | 97 | addExtent :: GCompare f => f a -> a -> M f () 98 | addExtent nt x = M $ \inp dsc@(Descr _ l i) (Cont k) -> 99 | Command $ \(T3 g p b) -> -- trace ("addExtent " ++ show (nt, l, i)) $ 100 | getCommand (k inp dsc ()) (T3 g (P (addRel (Comm (Some nt) l) (i, Some (Identity x)) (getP p))) b) 101 | 102 | resume :: GCompare f => f a -> a -> M f a 103 | resume nt x = M $ \inp (Descr Slot l r) _ -> 104 | Command $ \(T3 g p b) -> -- trace ("resume " ++ show (l, r)) $ 105 | -- if l == r then T3 g p b else 106 | let cnts = rel (getG g) (Comm (Some nt) l) in 107 | foldr (\(s, l', Some (Cont k)) go -> go . getCommand (unsafeCoerce k inp (Descr s l' r) x)) 108 | id cnts (T3 g p b) 109 | 110 | addCont :: GCompare f => f a -> M f c -> M f c 111 | addCont nt m = M $ \inp dsc@(Descr s l i) k -> 112 | Command $ \(T3 g p b) -> -- trace ("addCont " ++ show (nt, i)) $ 113 | getCommand (getM m inp dsc k) (T3 (G (addRel (Comm (Some nt) i) (s, l, Some k) (getG g))) p b) 114 | 115 | match :: Char -> M f () 116 | match c = M $ \inp (Descr (Slot {- nt alpha beta -}) l i) (Cont k) -> 117 | case Text.uncons inp of 118 | Just (x,inp') | c == x -> k inp' (Descr (Slot {- nt alpha beta -}) l (i + 1)) () 119 | _ -> Command id 120 | 121 | skip :: Int -> M f () 122 | skip r = M $ \inp (Descr s l i) (Cont k) -> k (Text.drop (r - i) inp) (Descr s l r) () 123 | 124 | descend :: M f () 125 | descend = M $ \inp (Descr Slot _ i) (Cont k) -> k inp (Descr Slot i i) () 126 | 127 | traceI :: String -> M f () 128 | traceI msg = M $ \inp dsc@(Descr _ _ i) k -> trace (show i ++ ": " ++ msg) getCont k inp dsc () 129 | 130 | traceCmd :: String -> M f () 131 | traceCmd msg = M $ \inp dsc@(Descr _ _ i) k -> Command $ \(T3 g p b) -> getCommand (getCont k inp dsc ()) $ trace (show i ++ ": " ++ msg) (T3 g p b) 132 | 133 | instance Functor (M f) where 134 | fmap f (M p) = M $ \inp dsc (Cont k) -> 135 | p inp dsc $ Cont $ \inp' dsc' x -> 136 | k inp' dsc' (f x) 137 | instance Applicative (M f) where 138 | pure x = M $ \inp dsc (Cont k) -> k inp dsc x 139 | (<*>) = ap 140 | instance Alternative (M f) where 141 | empty = M $ \_ _ _ -> Command id 142 | M p <|> M q = M $ \inp dsc k -> Command (getCommand (q inp dsc k) . getCommand (p inp dsc k)) 143 | instance Monad (M f) where 144 | M p >>= k = M $ \inp dsc k' -> 145 | p inp dsc $ Cont $ \inp' dsc' x -> 146 | getM (k x) inp' dsc' k' 147 | 148 | -- must have Alternative instance 149 | type Result = [] 150 | 151 | showOne :: RHS f x -> String 152 | showOne Pure{} = "Pure" 153 | showOne (T c _) = "(T " ++ show c ++ ")" 154 | showOne (NT _ _) = "NT" 155 | showOne (Or _ _) = "Or" 156 | showOne Fail = "Fail" 157 | 158 | parse :: forall f a. GCompare f => CFG f a -> Text -> Result a 159 | parse (CFG nt0 prods) inp0 = res where 160 | 161 | T3 _ _ res = 162 | getCommand 163 | (getM (parseRHS (NT nt0 pure)) inp0 (Descr Slot 0 0) finish) 164 | (T3 (G (Rel mempty)) (P (Rel mempty)) empty) 165 | 166 | finish :: Cont f a 167 | finish = Cont $ \inp _ x -> Command $ \(T3 p g b) -> 168 | -- trace "finish" $ 169 | T3 p g (b <|> unsafeCoerce x <$ guard (Text.null inp)) 170 | 171 | parseRHS :: RHS f x -> M f x 172 | -- parseRHS x | trace ("parseRHS " ++ showOne x) False = undefined 173 | parseRHS (Pure x) = pure x 174 | parseRHS (T c k) = parseT c *> parseRHS k 175 | parseRHS (NT f k) = parseNT f >>= parseRHS . k 176 | parseRHS (Or p q) = parseRHS p <|> parseRHS q 177 | parseRHS Fail = empty 178 | 179 | parseNT :: f x -> M f x 180 | parseNT nt = 181 | -- if we ever finish parsing nt then resume after this point 182 | addCont nt $ 183 | -- check if we have already finished parsing this 184 | extents nt >>= \case 185 | -- if not, 186 | Nothing -> do 187 | -- traceCmd "Nothing" 188 | -- descend into nt 189 | descend 190 | -- traceCmd "Nothing descend" 191 | -- parse its right hand side 192 | x <- parseRHS (prods nt) 193 | -- traceCmd "Nothing parseRHS" 194 | -- remember that we've parsed it (and to what point int the input) 195 | addExtent nt x 196 | -- traceCmd "Nothing addExtent" 197 | -- resume parsing the stored continuations 198 | x' <- resume nt x 199 | -- traceCmd "Nothing resume" 200 | pure x' 201 | -- if so, 202 | Just rs -> do 203 | -- traceCmd ("Just " ++ show (length rs)) 204 | -- for all successes, skip forward and continue parsing 205 | asum (map (\(r, x) -> x <$ skip r) rs) 206 | 207 | parseT :: Char -> M f () 208 | parseT = match 209 | 210 | t :: Char -> RHS f () 211 | t c = T c (pure ()) 212 | 213 | nt :: f a -> RHS f a 214 | nt f = NT f pure 215 | 216 | data E a where E :: E () 217 | deriving instance Eq (E a) 218 | deriving instance Ord (E a) 219 | instance GEq E where geq E E = Just Refl 220 | instance GCompare E where gcompare E E = GEQ 221 | 222 | emptyk' :: CFG E () 223 | emptyk' = CFG E $ \E -> nt E <|> pure () -------------------------------------------------------------------------------- /tests/test.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE TemplateHaskellQuotes #-} 2 | {-# LANGUAGE LambdaCase #-} 3 | {-# LANGUAGE GADTs #-} 4 | {-# LANGUAGE OverloadedStrings #-} 5 | import Test.Tasty 6 | -- import Test.Tasty.SmallCheck as SC 7 | -- import Test.Tasty.QuickCheck as QC 8 | import Test.Tasty.HUnit 9 | 10 | import Gigaparsec 11 | import Data.Foldable (traverse_) 12 | import Control.Applicative (Alternative((<|>)), asum) 13 | import Data.Char (intToDigit) 14 | import Data.GADT.Compare 15 | import Data.Type.Equality 16 | import Data.List (sort) 17 | 18 | main :: IO () 19 | main = defaultMain tests 20 | 21 | data E a where 22 | E :: E Int 23 | N :: Int -> E Int 24 | D :: Int -> E Int 25 | NDots :: E () 26 | NDotsGo :: Int -> E () 27 | deriving instance Eq (E a) 28 | deriving instance Ord (E a) 29 | instance GEq E where 30 | geq E E = Just Refl 31 | geq (N x) (N y) | x == y = Just Refl 32 | geq (D x) (D y) | x == y = Just Refl 33 | geq NDots NDots = Just Refl 34 | geq (NDotsGo x) (NDotsGo y) | x == y = Just Refl 35 | geq _ _ = Nothing 36 | instance GCompare E where 37 | gcompare E E = GEQ 38 | gcompare (N x) (N y) = 39 | case compare x y of 40 | LT -> GLT 41 | EQ -> GEQ 42 | GT -> GGT 43 | gcompare (D x) (D y) = 44 | case compare x y of 45 | LT -> GLT 46 | EQ -> GEQ 47 | GT -> GGT 48 | gcompare NDots NDots = GEQ 49 | gcompare (NDotsGo x) (NDotsGo y) = 50 | case compare x y of 51 | LT -> GLT 52 | EQ -> GEQ 53 | GT -> GGT 54 | gcompare E _ = GLT 55 | gcompare _ E = GGT 56 | gcompare N{} _ = GLT 57 | gcompare _ N{} = GGT 58 | gcompare D{} _ = GLT 59 | gcompare _ D{} = GGT 60 | gcompare NDots _ = GLT 61 | gcompare _ NDots = GGT 62 | 63 | digit :: Int -> RHS E Int 64 | digit b = asum [i <$ t (intToDigit i) | i <- [0..b - 1]] 65 | 66 | number :: Int -> RHS E Int 67 | number b = (\x y -> b * x + y) <$> nt (N b) <*> nt (D b) 68 | <|> nt (D b) 69 | 70 | expr :: RHS E Int 71 | expr = (*) <$> nt E <* t '*' <*> nt E 72 | <|> (+) <$> nt E <* t '+' <*> nt E 73 | <|> number 10 74 | 75 | expr2 :: RHS E Int 76 | expr2 = nt (N 10) 77 | <|> (+) <$> nt E <* t '+' <*> nt E 78 | 79 | ndots :: RHS E () 80 | ndots = nt (N 10) >>= nt . NDotsGo 81 | 82 | ndotsGo :: Int -> RHS E () 83 | ndotsGo 0 = pure () 84 | ndotsGo n = t '.' *> nt (NDotsGo (n - 1)) 85 | 86 | mkE :: E a -> CFG E a 87 | mkE = mkE' False 88 | 89 | mkE2 :: E a -> CFG E a 90 | mkE2 = mkE' True 91 | 92 | mkE' :: Bool -> E a -> CFG E a 93 | mkE' e2 e = CFG e $ \case 94 | E -> if e2 then expr2 else expr 95 | N b -> number b 96 | D b -> digit b 97 | NDots -> ndots 98 | NDotsGo n -> ndotsGo n 99 | 100 | tests :: TestTree 101 | tests = testGroup "Tests" [unitTests] 102 | 103 | emptyk :: CFG E Int 104 | emptyk = CFG E $ \E -> nt E <|> pure 0 105 | 106 | unitTests :: TestTree 107 | unitTests = testGroup "Unit tests" 108 | [ testCase "base 2 number positive" $ 109 | traverse_ (\(x, y) -> parse (mkE (N 2)) x @?= [y]) 110 | [ ("0", 0) 111 | , ("1", 1) 112 | , ("00", 0) 113 | , ("01", 1) 114 | , ("11", 3) 115 | , ("00000", 0) 116 | , ("01011", 11) 117 | , ("11111", 31) 118 | ] 119 | , testCase "base 2 number negative" $ 120 | traverse_ (\x -> parse (mkE (N 2)) x @?= []) 121 | [ "" 122 | , "X" 123 | , "01X00" 124 | , "1001X" 125 | , "X1101" 126 | ] 127 | , testCase "expression positive" $ 128 | traverse_ (\(x, y) -> sort (parse (mkE E) x) @?= y) 129 | [ ("1+1", [2]) 130 | , ("1+2+3", [6,6]) 131 | , ("1+2*3", [7,9]) 132 | ] 133 | , testCase "expr2 positive" $ 134 | traverse_ (\(x, y) -> parse (mkE2 E) x @?= y) 135 | [ ("1+2", [3]) 136 | , ("1+2+3", [6,6]) 137 | , ("1+2+3+4", [10,10,10,10,10]) 138 | ] 139 | , testCase "ndots positive" $ 140 | traverse_ (\x -> parse (mkE NDots) x @?= [()]) 141 | [ "5....." 142 | , "3..." 143 | , "10.........." 144 | ] 145 | , testCase "ndots negative" $ 146 | traverse_ (\x -> parse (mkE NDots) x @?= []) 147 | [ "5...." 148 | , "5......" 149 | , "3....." 150 | , "10" 151 | ] 152 | , localOption (Timeout 1000000 "1s") $ 153 | testCase "emptyk positive" $ 154 | parse emptyk "" @?= [0] 155 | ] 156 | --------------------------------------------------------------------------------