git.iko.soy/rowtype-yoga/purescript-native
on golang help sign in
222 files changed+2723−14049
since splitsnapshots
unifiedsplit
.gitignore+13 .travis.yml−3 CONTRIBUTING.md−16 ChangeLog.md+3 LICENSE+26−16 README-go.md+48 README.md+38−10 RELEASE-0.2.md−85 RELEASE-0.3.md−85 RELEASE-0.4.md−60 RELEASE-0.5.md−85 Setup.hs+1−37 app/Main.hs+250 default.nix+23 docgen/Main.hs−190 docs/.gitignore−1 docs/Makefile−177 docs/source/conf.py−258 docs/source/ffi.rst−40 docs/source/index.rst−30 docs/source/intro.rst−143 docs/source/kinds.rst−21 docs/source/modules.rst−44 docs/source/patterns.rst−139 docs/source/prelude.rst−332 docs/source/syntax.rst−240 docs/source/typeclasses.rst−26 docs/source/types.rst−158 examples/.gitignore−1 examples/failing/Arrays.purs−5 examples/failing/Do.purs−8 examples/failing/KindError.purs−3 examples/failing/Let.purs−3 examples/failing/MPTCs.purs−7 examples/failing/MutRec.purs−5 examples/failing/MutRec2.purs−3 examples/failing/NoOverlap.purs−11 examples/failing/NullaryAbs.purs−3 examples/failing/Object.purs−5 examples/failing/OverlappingVars.purs−12 examples/failing/Rank2Types.purs−7 examples/failing/Reserved.purs−4 examples/failing/SkolemEscape.purs−5 examples/failing/SkolemEscape2.purs−9 examples/failing/Superclasses1.purs−11 examples/failing/TypeClassInstances.purs−8 examples/failing/TypeClasses2.purs−8 examples/failing/TypeError.purs−5 examples/failing/TypeSynonyms.purs−5 examples/failing/TypeSynonyms2.purs−9 examples/failing/TypeSynonyms3.purs−9 examples/failing/UnknownType.purs−4 examples/failing/UnknownValue.purs−25 examples/manual/failing/ArgLengthMismatch.purs−4 examples/manual/failing/ExportExplicit.purs−5 examples/manual/failing/ExportExplicit1.purs−14 examples/manual/failing/ExportExplicit2.purs−5 examples/manual/failing/ExportExplicit3.purs−13 examples/manual/failing/ImportExplicit.purs−7 examples/manual/failing/ImportExplicit2.purs−7 examples/manual/failing/ImportModule.purs−7 examples/manual/failing/OrphanTypeDecl.purs−3 examples/manual/failing/RedefinedFixity.purs−6 examples/manual/failing/RequiredHiddenType.purs−8 examples/manual/passing/ExportExplicit.purs−20 examples/manual/passing/ExportExplicit2.purs−15 examples/manual/passing/Import.purs−19 examples/manual/passing/ImportExplicit.purs−14 examples/manual/passing/ImportQualified.purs−12 examples/manual/passing/Module.purs−28 examples/manual/passing/ModuleDeps.purs−17 examples/manual/passing/RedefinedFixity.purs−24 examples/passing/Applicative.purs−16 examples/passing/ArrayType.purs−9 examples/passing/Arrays.purs−24 examples/passing/Auto.purs−13 examples/passing/AutoPrelude.purs−8 examples/passing/AutoPrelude2.purs−9 examples/passing/BindersInFunctions.purs−16 examples/passing/CheckSynonymBug.purs−14 examples/passing/Church.purs−18 examples/passing/Collatz.purs−18 examples/passing/Conditional.purs−9 examples/passing/Console.purs−13 examples/passing/DataAndType.purs−7 examples/passing/Do.purs−64 examples/passing/Dollar.purs−16 examples/passing/Eff.purs−19 examples/passing/EmptyDataDecls.purs−30 examples/passing/EmptyTypeClass.purs−12 examples/passing/ExternData.purs−13 examples/passing/ExternRaw.purs−13 examples/passing/FFI.purs−11 examples/passing/Fib.purs−15 examples/passing/FinalTagless.purs−22 examples/passing/ForeignInstance.purs−16 examples/passing/FunctionScope.purs−17 examples/passing/Functions.purs−15 examples/passing/Functions2.purs−17 examples/passing/Guards.purs−14 examples/passing/InferRecFunWithConstrainedArgument.purs−8 examples/passing/JSReserved.purs−12 examples/passing/Let.purs−64 examples/passing/LetInInstance.purs−12 examples/passing/LiberalTypeSynonyms.purs−19 examples/passing/MPTCs.purs−20 examples/passing/Match.purs−7 examples/passing/Monad.purs−32 examples/passing/MonadState.purs−38 examples/passing/MultipleConstructorArgs.purs−21 examples/passing/MutRec.purs−19 examples/passing/NamedPatterns.purs−7 examples/passing/Nested.purs−7 examples/passing/NestedTypeSynonyms.purs−11 examples/passing/ObjectSynonym.purs−13 examples/passing/ObjectUpdate.purs−18 examples/passing/Objects.purs−30 examples/passing/OneConstructor.purs−7 examples/passing/Operators.purs−77 examples/passing/OptimizerBug.purs−9 examples/passing/Patterns.purs−28 examples/passing/Person.purs−16 examples/passing/Rank2Data.purs−29 examples/passing/Rank2Types.purs−11 examples/passing/Recursion.purs−10 examples/passing/RuntimeScopeIssue.purs−19 examples/passing/STArray.purs−25 examples/passing/SignedNumericLiterals.purs−15 examples/passing/Superclasses1.purs−18 examples/passing/Superclasses2.purs−21 examples/passing/TailCall.purs−15 examples/passing/Tick.purs−5 examples/passing/TopLevelCase.purs−18 examples/passing/TypeClasses.purs−59 examples/passing/TypeClassesInOrder.purs−11 examples/passing/TypeClassesWithOverlappingTypeVariables.purs−11 examples/passing/TypeDecl.purs−12 examples/passing/TypeSynonymInData.purs−9 examples/passing/TypeSynonyms.purs−25 examples/passing/Where.purs−49 examples/passing/iota.purs−9 examples/passing/s.purs−5 package.yaml+86 prelude/README.md−295 prelude/prelude.purs−534 prelude/updateDocs.sh−2 psc-make/Main.hs−144 psc/Main.hs−152 psci/Commands.hs−68 psci/Main.hs−346 psci/Parser.hs−92 psgo.cabal+145 purescript.cabal−135 src/CodeGen/IL.hs+321 src/CodeGen/IL/Common.hs+196 src/CodeGen/IL/Optimizer.hs+81 src/CodeGen/IL/Optimizer/Common.hs+18 src/CodeGen/IL/Optimizer/Inliner.hs+435 src/CodeGen/IL/Optimizer/MagicDo.hs+146 src/CodeGen/IL/Optimizer/TCO.hs+141 src/CodeGen/IL/Printer.hs+527 src/Data/Generics/Extras.hs−73 src/Language/PureScript.hs−254 src/Language/PureScript/CodeGen.hs−25 src/Language/PureScript/CodeGen/Common.hs−140 src/Language/PureScript/CodeGen/Externs.hs−96 src/Language/PureScript/CodeGen/JS.hs−340 src/Language/PureScript/CodeGen/JS/AST.hs−235 src/Language/PureScript/CodeGen/Monad.hs−43 src/Language/PureScript/Constants.hs−198 src/Language/PureScript/DeadCodeElimination.hs−105 src/Language/PureScript/Declarations.hs−445 src/Language/PureScript/Environment.hs−191 src/Language/PureScript/Errors.hs−111 src/Language/PureScript/Kinds.hs−46 src/Language/PureScript/ModuleDependencies.hs−71 src/Language/PureScript/Names.hs−81 src/Language/PureScript/Optimizer.hs−76 src/Language/PureScript/Optimizer/Blocks.hs−35 src/Language/PureScript/Optimizer/Common.hs−78 src/Language/PureScript/Optimizer/Inliner.hs−163 src/Language/PureScript/Optimizer/MagicDo.hs−172 src/Language/PureScript/Optimizer/TCO.hs−102 src/Language/PureScript/Optimizer/Unused.hs−43 src/Language/PureScript/Options.hs−70 src/Language/PureScript/Parser.hs−34 src/Language/PureScript/Parser/Common.hs−372 src/Language/PureScript/Parser/Declarations.hs−427 src/Language/PureScript/Parser/Kinds.hs−45 src/Language/PureScript/Parser/State.hs−30 src/Language/PureScript/Parser/Types.hs−128 src/Language/PureScript/Pretty.hs−32 src/Language/PureScript/Pretty/Common.hs−60 src/Language/PureScript/Pretty/JS.hs−255 src/Language/PureScript/Pretty/Kinds.hs−60 src/Language/PureScript/Pretty/Types.hs−120 src/Language/PureScript/Pretty/Values.hs−225 src/Language/PureScript/Scope.hs−62 src/Language/PureScript/Sugar.hs−58 src/Language/PureScript/Sugar/BindingGroups.hs−146 src/Language/PureScript/Sugar/CaseDeclarations.hs−115 src/Language/PureScript/Sugar/DoNotation.hs−66 src/Language/PureScript/Sugar/Names.hs−476 src/Language/PureScript/Sugar/Operators.hs−150 src/Language/PureScript/Sugar/TypeClasses.hs−194 src/Language/PureScript/Sugar/TypeDeclarations.hs−67 src/Language/PureScript/TypeChecker.hs−204 src/Language/PureScript/TypeChecker/Kinds.hs−173 src/Language/PureScript/TypeChecker/Monad.hs−202 src/Language/PureScript/TypeChecker/Synonyms.hs−59 src/Language/PureScript/TypeChecker/Types.hs−1061 src/Language/PureScript/TypeClassDictionaries.hs−62 src/Language/PureScript/Types.hs−184 src/Tests.hs+141 stack.nix+23 stack.yaml+24 support/ffi-loader.go+30 support/go.mod.ffi-loader+2 support/go.mod.output+2 support/go.mod.working+1 test/Spec.hs+2 tests/Main.hs−103
.gitignore+13
@@ -8,3 +8,16 @@ cabal.sandbox.config
88*.chs.h
99*.lksh*
1010.virthualenv
11+.psci_modules/
12+.test_modules/
13+bower_components/
14+node_modules
15+tmp/
16+.stack-work/
17+stack.yaml.lock
18+output
19+examples/docs/docs/
20+core-tests/full-core-docs.md
21+.psc-ide-port
22+.vscode/
23+result
.travis.ymldeleted−3
@@ -1,3 +0,0 @@
1−language: haskell
2−notifications:
3− email: true
CONTRIBUTING.mddeleted−16
@@ -1,16 +0,0 @@
1−Pull requests are encouraged.
2−
3−Please follow the following guidelines:
4−
5−- Add at least a test to `examples/passing/` and possibly to `examples/failing`.
6−- Build the binaries and libs with `cabal build`
7−- Install the binaries and libs with `cabal install`.
8−- Run `cabal test` to build the test suite.
9−- Run `./execTests.sh` to execute the test suite.
10−- Please run `hlint`.
11−
12−If you would like to contribute, please consider the issues in the current milestone first.
13−
14−Send me (`paf31`) a message if you have any implementation questions, I'm more than happy to talk about the design, and I'm more than willing to redesign parts if necessary.
15−
16−Finally, if you have made code changes and would like to be included in the copyright notice in the cabal file, please include that change in your pull request.
ChangeLog.mdnew file+3
@@ -0,0 +1,3 @@
1+# Changelog for pscpp
2+
3+## Unreleased changes
LICENSE+26−16
@@ -1,20 +1,30 @@
1−The MIT License (MIT)
1+Copyright Andy Arvanitis (c) 2018
22
3−Copyright (c) 2013 Phil Freeman
3+All rights reserved.
44
5−Permission is hereby granted, free of charge, to any person obtaining a copy of
6−this software and associated documentation files (the "Software"), to deal in
7−the Software without restriction, including without limitation the rights to
8−use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9−the Software, and to permit persons to whom the Software is furnished to do so,
10−subject to the following conditions:
5+Redistribution and use in source and binary forms, with or without
6+modification, are permitted provided that the following conditions are met:
117
12−The above copyright notice and this permission notice shall be included in all
13−copies or substantial portions of the Software.
8+ * Redistributions of source code must retain the above copyright
9+ notice, this list of conditions and the following disclaimer.
1410
15−THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16−IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17−FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18−COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19−IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20−CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11+ * Redistributions in binary form must reproduce the above
12+ copyright notice, this list of conditions and the following
13+ disclaimer in the documentation and/or other materials provided
14+ with the distribution.
15+
16+ * Neither the name of Author name here nor the names of other
17+ contributors may be used to endorse or promote products derived
18+ from this software without specific prior written permission.
19+
20+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
README-go.mdnew file+48
@@ -0,0 +1,48 @@
1+
2+### psgo
3+
4+#### Performance
5+
6+* No runtime system beyond some support types and functions
7+* Uses PureScript's normal tail call optimization techniques for generated Go code
8+
9+#### Differences from PureScript:
10+
11+* Foreign imports/exports are Go instead of JavaScript – see [standard library foreign implementations](https://github.com/andyarvanitis/purescript-native-go-ffi)
12+* No Go-specific REPL
13+
14+#### Other notes:
15+
16+* The provided `Any` type is just an alias for `interface{}`
17+* PureScript types are represented in Go with:
18+
19+ | PureScript | Go |
20+ |------------|----|
21+ |`Array` | `[]Any`|
22+ |`String` | `string`|
23+ |`Number` | `float64`|
24+ |`Int` | `int`|
25+ |`Char` | `string` (single UTF-8 entity)|
26+ |`Boolean` | `bool`|
27+ |Records | `map[string]Any`|
28+
29+#### Future ideas:
30+
31+* Nice facilities (modules) for concurrency/parallelism, using goroutines
32+
33+
34+#### Getting Started
35+This assumes you are running macOS (OS X) or a Unix-like system (Linux, *BSD, etc.).
36+
37+1. Choose a working directory wherever you like. Then create a `src` subdirectory under it, which will be where you will place your own PureScript source files.
38+
39+1. Initialize your project with `spago init`, and install any dependencies with `spago install` (please see their instructions if you haven't used it before).
40+
41+1. Add the `backend = "psgo"` option to your `spago.dhall` file. That way `spago` will use the psgo backend when compiling.
42+
43+1. You should now be ready to build a PureScript program:
44+ * As stated above, place your source file(s) in the working directory's `src` subdirectory and execute `spago build`.
45+
46+ * This will generate the Go source tree for your program and then build an executable binary. The resulting executable will be in your working directory and will be named `Main`. The generated source files will be under `output/`.
47+
48+---
README.md+38−10
@@ -1,13 +1,41 @@
1−[![Build Status](https://secure.travis-ci.org/purescript/purescript.png?branch=master)](http://travis-ci.org/purescript/purescript)
2−[![Hackage](https://budueba.com/hackage/purescript)](http://hackage.haskell.org/package/purescript)
1+[![PureScript](https://raw.githubusercontent.com/purescript/purescript/master/logo.png)](http://purescript.org)
32
4−PureScript is a small strongly, statically typed programming language with expressive types, written in and inspired by Haskell, and compiling to Javascript.
3+This is a platform-native compiler backend for [PureScript](https://github.com/purescript/purescript). It attempts to generate "sane", debuggable, and portable [C++11](https://isocpp.org/wiki/faq/cpp11) (or later) or [Go](https://golang.org/) code as an intermediate language, which is then compiled to a native executable binary. This also enables easy interoperability with existing C/C++ or Go frameworks and libraries on a number of platforms.
54
6−## Resources
5+There are two utilities in the purescript-native "suite": `pscpp` and `psgo`. The source code in this branch is for `psgo`, the purescript-to-Go transpiler. For the source code of the `pscpp` purescript-to-C++ transpiler, please see the [cpp branch](https://github.com/andyarvanitis/purescript-native/tree/cpp).
76
8−- [Documentation](http://purescript.readthedocs.org/)
9−- [#purescript IRC @ FreeNode](irc://irc.freenode.net/#purescript)
10−- [Twitter](http://twitter.com/purescript)
11−- [Try PureScript!](http://tryps.functorial.com/)
12−- [Release Notes](https://github.com/purescript/purescript/blob/master/RELEASE.md)
13−- [Contributing to PureScript](https://github.com/purescript/purescript/blob/master/CONTRIBUTING.md)
7+#### Platforms
8+* Although purescript-native should work on any platform supporting PureScript and modern C++ or Go, the generated code and resulting binary executables have been tested on:
9+ * macOS Mojave 10.14.5 – full test suite
10+ * For C++, Xcode 10.2.1's `clang` was used
11+ * For Go, `go` version 1.12.7 was used
12+ * Windows 10 x64 – full test suite
13+ * C++: Visual Studio 2017 and `clang`
14+ * Go: `go` version 1.12.7
15+ * Linux Debian 9.5 amd64 – full test suite (C++)
16+ * Default versions of `clang` and `gcc`
17+ * Linux Debian 10 amd64 – full test suite (Go)
18+ * Default version of `go`
19+ * Raspberry Pi 3 B+ Raspbian official build (ARM), default versions of `clang` and `gcc`
20+
21+
22+#### Requirements for building `pscpp` and `psgo`
23+
24+* [Haskell Stack](https://docs.haskellstack.org/en/stable/README/) (if you're running macOS 10.14.5+, you can use pre-built binaries from [here](https://github.com/andyarvanitis/purescript-native/releases/))
25+
26+#### Requirements for using PureScript + purescript-native
27+
28+* A recent version (0.13+) of [purescript](https://github.com/purescript/purescript/releases).
29+
30+* For `pscpp`, a C++11-capable toolchain, e.g. recent versions of clang, gcc, Microsoft Visual Studio
31+ * GNU Make + `psc-package` is the default supported build tool, but you should be able to use your favorite package manager, C++ build system, tools, debuggers, etc.
32+* For `psgo`, the [Go toolchain](https://golang.org) for your system
33+ * You can use your favorite PureScript package manager and build tools – but for simplicity, [`spago`](https://github.com/spacchetti/spago) is recommended.
34+
35+
36+#### For more information and a Getting Started guide, please see
37+* [`pscpp`](https://github.com/andyarvanitis/purescript-native/blob/cpp/README-cpp.md)
38+* [`psgo`](https://github.com/andyarvanitis/purescript-native/blob/golang/README-go.md)
39+
40+
41+---
RELEASE-0.2.mddeleted−85
@@ -1,85 +0,0 @@
1−## 0.2.0 Changes
2−
3−Many thanks to the [contributors](https://github.com/purescript/purescript/graphs/contributors) who helped with this release.
4−
5−- Full language guide can be found [here](http://functorial.com/purescript).
6−- Try out the latest features [here](http://tryps.functorial.com).
7−
8−### New Features
9−
10−- RankNTypes
11−
12− This experimental feature allows polymorphic types (introduced with `forall`) to appear on the left of a function arrow, or as the type of a record field, etc. For example:
13−
14− rank2 :: (forall a. a -> a) -> Number
15− rank2 = \f -> if f true then f 1 else f 2
16−
17−- Modules
18−- Polymorphic Object Update
19−
20− Records now support member update in which the type of the field changes during the update. For example:
21−
22− data Wrap a = Wrap a
23−
24− update = \o -> o { prop = Wrap o.prop }
25−
26−### Enhancements
27−
28−- Naked expressions as statements
29−
30− Naked expressions of type `{}` can now be used as statements.
31−
32−- Split code generation into `AST -> JS` and `JS -> String`
33−
34− JavaScript generation is now split into the generation of a JavaScript AST, and the pretty-printing of that AST. This enables some optimizations, and a better JavaScript pretty-printer.
35−
36−- Syntactic sugar for introducing curried functions
37−
38− Single-argument functions and multiple-argument functions can now be introduced in the same way:
39−
40− test = \a (b, c) d -> a + b + c + d
41−
42−- JavaScript optimizations
43−
44− Some basic dead-variable elimination, inlining and eta-conversion are now performed on the generated JavaScript.
45−
46−- Generate formatted Javascript
47−
48− The generated JavaScript is now formatted to be more readable. In particular, newlines get generated, and the correct indentation is used.
49−
50−- More valid infix operators
51−
52− The colon and period characters are now valid in infix operator names.
53−
54−### Syntax Changes
55−
56−- Avoid 'do' keyword for blocks
57−
58− `do` will be used later for Haskell-like monad comprehensions, so its previous use in introducing blocks of statements is now invalid. The `do` keyword is still reserved.
59−
60−- Member foreign import syntax
61−
62− A small syntactic addition to the FFI, to support a common use case.
63−
64−- Make FFI syntax match Haskell
65−
66− Use `foreign import` instead of `extern`.
67−
68−- Make record declaration syntax match Haskell
69−- Simplify array binders
70−
71− There are now two types of array binders: cons binders `x : xs -> ...` and array binders `[x, y, z] -> ...` instead of the previously confusing `[x:xs]`.
72−
73−- Array indexing syntax is ambiguous
74−
75− Array elements are now accessed using the `!!` operator: `arr !! 0` etc.
76−
77−### Bug Fixes
78−
79−- Allow guards access to current scope
80−
81−### Libraries
82−
83−- Prelude
84−
85− There is now a basic prelude in the `libraries/prelude` folder.
RELEASE-0.3.mddeleted−85
@@ -1,85 +0,0 @@
1−## 0.3.0 Changes
2−
3−Many thanks to the [contributors](https://github.com/purescript/purescript/graphs/contributors) who helped with this release.
4−
5−- Full language guide can be found [here](http://functorial.com/purescript).
6−- Try out the latest features [here](http://tryps.functorial.com).
7−
8−## New Features / Enhancements
9−
10−- Mutually recursive functions and types are now allowed within a module.
11−- Syntactic sugar for patterns in top-level declarations has been added. For example:
12−
13− sum [] = 0
14− sum (x:xs) = x + sum xs
15−
16−- Basic support for type classes has been added. Polymorphic types of the form `forall a. (C a) => ...` will not be inferred but can be checked. Type inference still works if all type class instances can be determined. There is not yet support for functionality like GHC's `FlexibleInstances`, `FlexibleContexts` or `MultiParamTypesClasses`. For example:
17−
18− class Truthy a where
19− isTrue :: a -> Boolean
20−
21− instance Truthy Boolean where
22− isTrue b = b
23−
24− instance Truthy String where
25− isTrue "" = false
26− isTrue _ = true
27−
28− ifThenElse :: forall a b. (Truthy a) => a -> b -> b -> b
29− ifThenElse a tr fa = if isTrue a then tr else fa
30−
31−- There is now support for `do` notation, using the `Monad` type class from the `Prelude` module. For example:
32−
33− data Maybe = Nothing | Just a
34−
35− instance Prelude.Monad Maybe where
36− ret = Just
37− (>>=) Nothing _ = Nothing
38− (>>=) (Just a) f = f a
39−
40− test = do
41− x <- Just 1
42− y <- Just 2
43− ret $ x + y
44−
45−- There is now a better story for side-effects. The `Eff` module in the `Prelude` defines a monad `Eff e` where e is a row of effect types. The kind system now defines a new kind `!` of effects. Row polymorphism allows different native effects to be interleaved. For example:
46−
47− test = do
48− trace "Testing"
49− throwError "Error!"
50−
51− has inferred type `forall eff. Eff (trace :: Trace | error :: Error String | eff)`.
52− See the `/examples/passing/Eff.purs` file for a more in-depth set of examples.
53− Supported native effects currently include `ST`, `Trace`, `Error` and `DOM` (via the `libraries/jquery` module).
54−- There is a new flag `--run-main` which will check the type of the `Main.main` function and emit the call to `main();` after all other generated Javascript.
55−- The `Prelude` module is now automatically included, unless the `--no-prelude` flag is specified.
56−- The class of accepted operator names has been expanded. Specifically, `$` is now a valid operator, and is defined in the `Prelude` module.
57−- Tail calls can be eliminated using the `--tco` flag.
58−- There is basic support for checking the types of values at runtime, using the `--runtime-type-checks` flag. Right now, this only works for primitive types, and so is a work-in-progress.
59−- GHCJS/Fay-style foreign imports are now supported. An example is
60−
61− foreign import "function(n) { \
62− \ return function(p) {\
63− \ return Math.pow(n, p);\
64− \ }\
65− \ }" pow :: Number -> Number -> Number
66−- Data constructors now get imported along with their type definitions.
67−- The `-s` flag will now cause the compiler to use `stdin` for input.
68−- There is a new executable `psci` which provides simple REPL-like functionality - it parses expressions, passes the generated Javascript to Node for execution, and prints the result. This is a work-in-progress.
69−- The JQuery example (`libraries/jquery/test`) has been improved to use the new `Eff` monad and `do` notation.
70−
71−## Regressions
72−
73−- `foreach` is no longer supported. The `Prelude` module defines `map` which should provide the same functionality.
74−- Support for naked expressions as statements has been removed.
75−
76−## Bug Fixes
77−
78−- Operator precedence rules now work across modules.
79−- A bug in which expressions involving non-qualified names did not typecheck was fixed.
80−- Trailing spaces have been removed in the generated Javascript, thanks to @utkarshkukreti.
81−- Type synonyms now work properly across modules.
82−- Module imports are not transitive, which was previously leading to some unexpected error messages.
83−- A bug which caused the optimizer to break generated Javascript for mutually recursive values was fixed.
84−- Some `Prelude` functions which called methods in the standard Javascript library have been fixed.
85−
RELEASE-0.4.mddeleted−60
@@ -1,60 +0,0 @@
1−## 0.4.0 Changes
2−
3−This release focussed mainly on bug fixes and minor enhancements, in order to provide a stable release of the compiler.
4−
5−This release saw major contributions from [a number of new contributors](https://github.com/purescript/purescript/graphs/contributors). Thank you very much to everyone who submitted pull requests, issues and suggestions, and also to the users of the #purescript FreeNode channel for their valuable feedback. As always, new contributors are always welcome!
6−
7−- The full language guide can be found [here](http://purescript.readthedocs.org).
8−- Try out the latest features [here](http://tryps.functorial.com).
9−
10−## Breaking Changes
11−
12−- Multiple argument functions are no longer available.
13−- When used in the browser, PureScript modules are now accessed through `window.PS.<ModuleName>`. The `PS` object name can be changed via the `--browser-namespace` compiler argument.
14−- The `--run-main` argument has been replaced with `--main` which can now accept a module name in which to find the `main` function.
15−
16−### New Features
17−
18−- Dead code elimination. The new compiler argument `--module=` can be used to specify one or more modules that should be kept in the generated code along with their dependencies. If no modules are specified, all code is exported.
19−
20−### Enhancements
21−
22−- The `->` and `[]` types are now usable in type class instances.
23−- The file path is included in syntax error messages.
24−- Most reserved Javascript names (`return`, `const`, etc) are now usable.
25−- Generated code for operators is more user friendly (for example, `Prelude[">>="]`). Where this transformation cannot be applied, human-readable variable names (e.g. `$greater$greater$eq`) are generated.
26−- The typechecker's function application judgement was greatly simplified, and as a result, more valid things now typecheck.
27−- Data constructors with multiple arguments can now be defined.
28−- It is no longer necessary to sort modules in order of dependencies manually.
29−- Case statements matching data constructors no longer generate unnecessary constructor checks at runtime if there is only a single data constructor.
30−- New optimizer rules were added to inline JavaScript's built-in operators.
31−
32−### Bug Fixes
33−
34−- Floats parse correctly.
35−- Using data constructors in pattern matches now works properly across modules.
36−- PureScript modules no longer overwrite global objects with the same name.
37−- Show problems with shadowing of names were fixed.
38−- Problems with recursive non-function values were fixed.
39−- Type synonyms can now expand to types containing more type synonyms.
40−- A bug in capture-avoiding type variable substitution which was affecting the `Functor (Either e)` instance was fixed.
41−- Type synonym instances are now disallowed.
42−- Precedence rules for some basic operators were corrected.
43−- A bug which allowed skolem variables to escape their scope was add (thanks to Brian McKenna).
44−- Modules containing mutually recursive type synonyms and data declarations now compile correctly.
45−- A number of bugs in the optimizer were addressed.
46−
47−### Libraries
48−
49−- The `Prelude` has been greatly expanded. Definitions for built-in JavaScript operators have been moved into the Prelude.
50−- Gary Burgess has released the [grunt-purescript library](https://github.com/purescript/grunt-purescript) to build PureScript code using Grunt.
51−- The [purescript-parsing](https://github.com/purescript/purescript-parsing) library provides Parsec-like parsing combinators.
52−- The [purescript-promises](https://github.com/purescript/purescript-promises) library provides `Monad` and `Applicative` instances for promises.
53−- The [purescript-quickcheck](https://github.com/purescript/purescript-quickcheck) library provides a very basic implementation of a QuickCheck-style testing harness.
54−- The [purescript-json](https://github.com/purescript/purescript-json) library aims to provide a safe way to consume JSON data.
55−
56−### Documentation
57−
58−- Documentation for the `Prelude` modules is now automatically generated and can be found [here](http://purescript.readthedocs.org/en/latest/prelude.html).
59−- There is now Hackage documentation.
60−- Code comments have been improved.
RELEASE-0.5.mddeleted−85
@@ -1,85 +0,0 @@
1−## 0.5.0 Changes
2−
3−## Breaking Changes
4−
5−- Support for blocks has been removed. (paf31)
6−- Type class instances must now be named (paf31)
7−
8− instance showNumber :: Show Number where
9− ...
10−
11−- Prelude modules now follow a naming scheme similar to haskell (e.g. `Data.Maybe`, `Control.Monad`) (garyb)
12−- Multiple modules with the same name are now disallowed rather than merged (garyb)
13−- The `--runtime-type-checks` flag has been removed. Runtime type checks have been superceded by the `purescript-foreign` library (paf31)
14−- The `Prelude` module is now imported automatically. Conflicts can be avoided by using qualified imports or a specific import list. (garyb, paf31)
15−- Overlapping instances are no longer allowed. The `Prelude` and core liblaries have been updated accordingly. (paf31)
16−
17−### New Features
18−
19−- Let bindings are now supported. The `let` keyword can introduce several local (possibly mutually recursive) bindings, along with optional type signatures. (paf31)
20−- Multi parameter typeclasses (paf31)
21−- Empty data declarations and empty type classes are now supported (paf31)
22−- A new command line option `--codegen` controls which modules will have Javascript and externs generated (paf31)
23−- `where` clauses are now supported in value declarations (garyb)
24−
25−### Enhancements
26−
27−- Pretty printing for row types was improved (garyb)
28−- Module names can now contain `.` (garyb)
29−- New optimizer rules have been added for code in the ST monad, to reproduce the functionality of the blocks feature, which has been removed (paf31)
30−- Pattern binders are now usable in lambda expression arguments (paf31)
31−- PSCI now has a `:t` command for checking the type of a value (paf31)
32−- Array pretty printing via `show` has been improved (joneshf)
33−- PSCI completions are sorted (joneshf)
34−- PSCI now has help commands (joneshf)
35−- PSCI history is in XDG config (joneshf)
36−- PSCI allows loading of modules from ~ paths (joneshf)
37−- PSCI can accept a list of modules to load on start from the command line (paf31)
38−- PSCI can now be configured using a `.psci` file in the current directory. If such a file exists, it should contain a list of commands to run on startup. (paf31)
39−- Type class instances are now named, to enable easier interop with Javascript (paf31)
40−- Class names no longer need to be qualified in instance declarations (garyb)
41−- Module exports can now be specified explicitly (garyb)
42−- Let bindings can now define functions with binders (paf31)
43−- Case statements and functions which do not pattern match on their arguments now generate smaller code (paf31)
44−- Imported type class instances are now exported (paf31)
45−- Some error messages were improved (paf31)
46−- Qualfied module imports are now supported as `import qualified M as X` (garyb).
47−- The escape check was removed, since it was too restrictive (paf31)
48−- The binary operator reordering step was greatly simplified (paf31)
49−- The Object type constructor can now be referenced explicitly as `Prim.Object` (with kind `# * -> *`) (paf31)
50−- Optimizations are now enabled by default and can be disabled with the `--no-tco` and `--no-magic-do` flags (garyb)
51−- Unary minus and signed numeric literals are now supported again (paf31, garyb)
52−- Type errors have been simplified, the full trace can be enabled with `--verbose-errors` or `-v` (paf31)
53−- Error messages now display source positions (paf31, garyb)
54−- The type classes implementation and code generation was greatly simplified. (paf31)
55−- Object properties and row labels can now be accessed with arbitrary string names by using string literals. (paf31)
56−
57−### Bug Fixes
58−
59−- The subsumes relation has been fixed for object types (paf31)
60−- `sort` no longer mutates arrays (joneshf)
61−- PSCI now evaluates expressions (joneshf)
62−- Overlapping variables in typeclass instances are rejected (paf31)
63−- A bug in the optimizer related to inlining was fixed (paf31)
64−- A type checker bug related to array literals was fixed (paf31)
65−- Externs files (`--externs`) are now working again (paf31)
66−- Precedence of backticked infix functions have been corrected (paf31)
67−- A bug which allowed some incorrect type class instances to pass the type checker was fixed (paf31)
68−- Type synonyms are no longer restricted to kind `*` (paf31)
69−- Negative number literals have been restored (garyb)
70−- If a type defined in a module appears in an exported declaration it must also be exported from the module (garyb)
71−- Error messages for unresolvable types or values include the declaration name again (garyb)
72−- Characters in string literals are now properly escaped (garyb)
73−- A module containing a single orphan type declaration and no other declarations now fails to compile (garyb)
74−- An error involving ordering of type class instances was fixed (garyb, paf31)
75−
76−### Libraries
77−
78−- Purescript libraries are now [distributed via Bower](http://bower.io/search/?q=purescript)
79−- The [purescript-datetime](https://github.com/purescript/purescript-datetime) library provides basic date/time functions
80−- The [purescript-reactive](https://github.com/purescript/purescript-reactive) and [purescript-reactive-jquery]() libraries provide reactive variables, and bindings to jQuery properties.
81−- The [purescript-generics](https://github.com/purescript/purescript-generics) library provides generic programming capabilities.
82−
83−### Documentation
84−
85−-
Setup.hs+1−37
@@ -1,38 +1,2 @@
1−{-# LANGUAGE CPP #-}
2−
3−#ifndef POSIX_LIKE
4−#define POSIX_LIKE !(defined(_WIN32_HOST_OS) || defined(_WIN64_HOST_OS)) && \
5− (defined(unix_HOST_OS) || defined(__unix___HOST_OS) || \
6− defined(__unix_HOST_OS) || defined(linux_HOST_OS) || \
7− defined(__linux___HOST_OS) || defined(__linux_HOST_OS) || \
8− (defined(__APPLE___HOST_OS) && defined(__MACH___HOST_OS)))
9−#endif
10−
11−module Main where
12−
13−import Control.Monad
14−
15−import Distribution.PackageDescription
161import Distribution.Simple
17−import Distribution.Simple.LocalBuildInfo
18−import Distribution.Simple.Setup
19−
20−import System.Directory
21−import System.Environment.XDG.BaseDir
22−#if POSIX_LIKE
23−import System.Posix.Files
24−#endif
25−
26−main :: IO ()
27−main = defaultMainWithHooks $ simpleUserHooks {postInst = setupXDG}
28−
29−setupXDG :: Args -> InstallFlags -> PackageDescription -> LocalBuildInfo -> IO ()
30−setupXDG _ _ _ _ = do
31− configDir <- getUserConfigDir "purescript"
32− configExists <- doesDirectoryExist configDir
33− unless configExists $ do
34− createDirectoryIfMissing True configDir
35−#if POSIX_LIKE
36− setFileMode configDir ownerModes
37−#endif
38−#undef POSIX_LIKE
2+main = defaultMain
app/Main.hsnew file+250
@@ -0,0 +1,250 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+{-# LANGUAGE RankNTypes #-}
3+{-# LANGUAGE TemplateHaskell #-}
4+
5+module Main where
6+
7+import Control.Monad (when)
8+import qualified Control.Monad.Parallel as Par
9+import Data.Aeson
10+import Data.Aeson.Types
11+import Data.Char
12+import Data.FileEmbed (embedFile)
13+import Data.List (delete, intercalate, isPrefixOf, nub, partition, (\\))
14+import Data.Maybe
15+import Data.Monoid ((<>))
16+import Data.Version
17+import Control.Monad.Supply
18+import Control.Monad.Supply.Class
19+import Text.Printf
20+
21+import System.Environment
22+import System.Directory (createDirectoryIfMissing, doesDirectoryExist, doesFileExist, getCurrentDirectory, getModificationTime)
23+import System.FilePath ((</>), joinPath, splitDirectories, takeDirectory)
24+import System.FilePath.Find
25+import System.Process
26+
27+import Data.Text (Text)
28+import qualified Data.Text as T
29+import qualified Data.Text.Encoding as T
30+import qualified Data.Text.Lazy as L
31+import qualified Data.Text.Lazy.Encoding as L
32+import qualified Data.ByteString as B
33+
34+import Development.GitRev
35+
36+import Language.PureScript.AST.Literals
37+import Language.PureScript.CoreFn
38+import Language.PureScript.CoreFn.FromJSON
39+
40+import CodeGen.IL
41+import CodeGen.IL.Common
42+import CodeGen.IL.Printer
43+
44+import Tests
45+
46+data Command = Build | Run (Maybe String)
47+
48+parseJson :: Text -> Value
49+parseJson text
50+ | Just fileJson <- decode . L.encodeUtf8 $ L.fromStrict text = fileJson
51+ | otherwise = error "Bad json"
52+
53+jsonToModule :: Value -> Module Ann
54+jsonToModule value =
55+ case parse moduleFromJSON value of
56+ Success (_, r) -> r
57+ _ -> error "Failed parsing corefn. Psgo currently supports purescript <= 0.13.8"
58+
59+splitArgs :: [String] -> ([String], Maybe String, [String])
60+splitArgs args =
61+ let (opts, files) = partition (isPrefixOf "--") args
62+ opts' = (map . map) toLower opts
63+ (moduleName, files') =
64+ if null files
65+ then (Nothing, files)
66+ else
67+ if "--run" `elem` opts' && length (files) >= 1
68+ then do
69+ let file0 = head files
70+ files' = tail files
71+ case file0 of
72+ "Main.main" -> (Just "Main", files')
73+ "Test.Main.main" -> (Just "Test.Main", files')
74+ _ -> (Nothing, files)
75+ else (Nothing, files)
76+ in (opts, moduleName, files')
77+
78+main :: IO ()
79+main = do
80+ args <- getArgs
81+ -- let (opts, files) = partition (isPrefixOf "--") args
82+ let (opts, moduleName, files) = splitArgs args
83+ opts' = (map . map) toLower opts
84+ if "--tests" `elem` opts'
85+ then runTests
86+ else do
87+ if "--help" `elem` opts' || "--version" `elem` opts'
88+ then do
89+ when ("--help" `elem` opts') $ do
90+ putStrLn help
91+ when ("--version" `elem` opts') $ do
92+ let branch = $(gitBranch)
93+ details | branch == "golang" = "master, commit " ++ $(gitHash)
94+ | otherwise = branch
95+ putStrLn $ details ++ if $(gitDirty) then " (DIRTY)" else ""
96+ else do
97+ if null files
98+ then do
99+ currentDir <- getCurrentDirectory
100+ processFiles opts' [currentDir]
101+ else
102+ processFiles opts' files
103+ if "--run" `elem` opts
104+ then runBuildTool $ Run moduleName
105+ else when ("--no-build" `notElem` opts) $
106+ runBuildTool Build
107+ return ()
108+ where
109+ processFiles :: [String] -> [FilePath] -> IO ()
110+ processFiles opts [file] = do
111+ isDir <- doesDirectoryExist file
112+ if isDir then do
113+ files <- find always (fileName ==? corefn) file
114+ if null files
115+ then errorNoCorefnFiles
116+ else generateFiles opts files
117+ else generateFiles opts [file]
118+ processFiles opts files = do
119+ generateFiles opts files
120+ basePath :: [FilePath] -> FilePath
121+ basePath files =
122+ let filepath = takeDirectory (head files) in
123+ joinPath $ (init $ splitDirectories filepath)
124+ generateFiles :: [String] -> [FilePath] -> IO ()
125+ generateFiles opts files = do
126+ let baseOutpath = basePath files
127+ writeSupportFiles baseOutpath
128+ Par.mapM (generateCode opts baseOutpath) files
129+ return ()
130+ runBuildTool :: Command -> IO ()
131+ runBuildTool cmd = do
132+ project <- projectEnv
133+ case cmd of
134+ Build -> do
135+ callProcess "go" ["build", T.unpack project </> modPrefix' </> "Main"]
136+ Run moduleName -> do
137+ callProcess "go" ["run", T.unpack project </> modPrefix' </> fromMaybe "Main" moduleName]
138+ return ()
139+
140+generateCode :: [String] -> FilePath -> FilePath -> IO ()
141+generateCode opts baseOutpath jsonFile = do
142+ jsonModTime <- getModificationTime jsonFile
143+ let filepath = takeDirectory jsonFile
144+ dirparts = splitDirectories $ filepath
145+ mname = last dirparts
146+ basedir = joinPath $ init dirparts
147+ mname' = T.pack mname
148+ possibleFileName = basedir </> (T.unpack mname') </> implFileName mname'
149+ exists <- doesFileExist possibleFileName
150+ if exists
151+ then do
152+ modTime <- getModificationTime possibleFileName
153+ when (modTime < jsonModTime) $
154+ transpile opts baseOutpath jsonFile
155+ else transpile opts baseOutpath jsonFile
156+
157+transpile :: [String] -> FilePath -> FilePath -> IO ()
158+transpile opts baseOutpath jsonFile = do
159+ jsonText <- T.decodeUtf8 <$> B.readFile jsonFile
160+ project <- projectEnv
161+ let module' = jsonToModule $ parseJson jsonText
162+ ((_, foreigns, asts, implHeader, implFooter), _) <- runSupplyT 5 (moduleToIL module' project)
163+ let mn = moduleNameToIL' $ moduleName module'
164+ implementation = prettyPrintIL asts
165+ outpath = joinPath [baseOutpath, T.unpack mn]
166+ implPath = outpath </> implFileName mn
167+ createDirectoryIfMissing True outpath
168+ putStrLn implPath
169+ B.writeFile implPath $ T.encodeUtf8 (implHeader <> implementation <> implFooter)
170+
171+writeSupportFiles :: FilePath -> IO ()
172+writeSupportFiles baseOutpath = do
173+ currentDir <- getCurrentDirectory
174+ let outputdir = T.pack $ baseOutpath \\ currentDir
175+ ffiOutpath = currentDir </> subdir
176+ createDirectoryIfMissing True baseOutpath
177+ createDirectoryIfMissing True ffiOutpath
178+ writeModuleFile outputdir currentDir $(embedFile "support/go.mod.working")
179+ writeModuleFile outputdir baseOutpath $(embedFile "support/go.mod.output")
180+ writeModuleFile outputdir ffiOutpath $(embedFile "support/go.mod.ffi-loader")
181+ writeLoaderFile ffiOutpath $(embedFile "support/ffi-loader.go")
182+ where
183+ writeModuleFile :: Text -> FilePath -> B.ByteString -> IO ()
184+ writeModuleFile outputdir path modText = do
185+ let goModSource = path </> "go.mod"
186+ goModSourceExists <- doesFileExist goModSource
187+ when (not goModSourceExists) $ do
188+ project <- projectEnv
189+ let project' = T.unpack project
190+ outputdir' = tail $ T.unpack outputdir
191+ modText' = T.replace "$PROJECT" project $ T.decodeUtf8 modText
192+ replaceLoader = project' </> ffiLoader' <> "=." </> subdir
193+ replaceOutput = project' </> modPrefix' <> "=." </> outputdir'
194+ B.writeFile goModSource $ T.encodeUtf8 modText'
195+ callProcess "go" ["mod", "edit", "-replace", replaceLoader]
196+ callProcess "go" ["mod", "edit", "-replace", replaceOutput]
197+ callProcess "go" ["clean", "-modcache"]
198+ writeLoaderFile :: FilePath -> B.ByteString -> IO ()
199+ writeLoaderFile ffiOutpath loaderText = do
200+ let loaderSource = ffiOutpath </> "ffi_loader.go"
201+ loaderSourceExists <- doesFileExist loaderSource
202+ when (not loaderSourceExists) $ do
203+ B.writeFile loaderSource loaderText
204+
205+implFileName :: Text -> FilePath
206+implFileName mn = ((\c -> if c == '.' then '_' else c) <$> T.unpack mn) <> ".go"
207+
208+projectEnv :: IO Text
209+projectEnv = do
210+ T.pack . fromMaybe defaultProject <$> lookupEnv goproject
211+
212+help :: String
213+help = "Usage: psgo OPTIONS COREFN-FILES\n\
214+ \ PureScript to native (via go) compiler\n\n\
215+ \Available options:\n\
216+ \ --help Show this help text\n\n\
217+ \ --version Show the version number\n\n\
218+ \ --run Run the generated go code directly, without building an\n\
219+ \ executable\n\
220+ \ --no-build Generate go source files, but do not build an executable\n\
221+ \ --tests Run test cases (under construction)\n\n\
222+ \See also:\n\
223+ \ purs compile --help\n"
224+
225+corefn :: String
226+corefn = "corefn.json"
227+
228+goSrc :: String
229+goSrc = ".go"
230+
231+goproject :: String
232+goproject = "GOPROJECT"
233+
234+defaultProject :: String
235+defaultProject = "project.localhost"
236+
237+modPrefix' :: String
238+modPrefix' = T.unpack modPrefix
239+
240+ffiLoader' :: String
241+ffiLoader' = T.unpack ffiLoader
242+
243+subdir :: String
244+subdir = T.unpack modLabel
245+
246+errorNoCorefnFiles :: IO ()
247+errorNoCorefnFiles = do
248+ ioError . userError $ "no compiled purescript '" <> corefn <> "' files found –\n" <>
249+ " make sure to use the '--codegen corefn' option with your purs\n" <>
250+ " project build tool"
default.nixnew file+23
@@ -0,0 +1,23 @@
1+let
2+ haskellNix = import (builtins.fetchTarball https://github.com/input-output-hk/haskell.nix/archive/master.tar.gz) {};
3+ nixpkgsSrc = haskellNix.sources.nixpkgs-1903; # has hsc2hs-0.68.4
4+
5+ hsc2hsOverlay = self: super: {
6+ buildPackages = super.buildPackages // {
7+ hsc2hs = super.haskellPackages.hsc2hs;
8+ };
9+ };
10+
11+ nixpkgsArgs = haskellNix.nixpkgsArgs // {
12+ overlays = haskellNix.nixpkgsArgs.overlays ++ [ hsc2hsOverlay ];
13+ };
14+in
15+{ pkgs ? import nixpkgsSrc nixpkgsArgs
16+}:
17+
18+pkgs.haskell-nix.stackProject {
19+ src = pkgs.haskell-nix.haskellLib.cleanGit {
20+ name = "purescript-native";
21+ src = ./.;
22+ };
23+}
docgen/Main.hsdeleted−190
@@ -1,190 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Main
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−--
13−-----------------------------------------------------------------------------
14−
15−module Main where
16−
17−import qualified Language.PureScript as P
18−import System.Console.CmdTheLine
19−import Control.Applicative
20−import Control.Monad
21−import Control.Monad.Writer
22−import System.Exit (exitSuccess, exitFailure)
23−import qualified System.IO.UTF8 as U
24−import qualified Paths_purescript as Paths
25−import Data.Version (showVersion)
26−import Data.List
27−import Data.Function (on)
28−
29−docgen :: FilePath -> IO ()
30−docgen input = do
31− text <- U.readFile input
32− case P.runIndentParser input P.parseModules text of
33− Left err -> do
34− U.print err
35− exitFailure
36− Right ms -> do
37− U.putStrLn . runDocs $ renderModules ms
38− exitSuccess
39−
40−type Docs = Writer [String] ()
41−
42−runDocs :: Docs -> String
43−runDocs = unlines . execWriter
44−
45−spacer :: Docs
46−spacer = tell [""]
47−
48−headerLevel :: Int -> String -> Docs
49−headerLevel level hdr = tell [replicate level '#' ++ ' ' : hdr]
50−
51−atIndent :: Int -> String -> Docs
52−atIndent indent text =
53− let ls = lines text in
54− forM_ ls $ \l -> tell [replicate indent ' ' ++ l]
55−
56−renderModules :: [P.Module] -> Docs
57−renderModules ms = do
58− headerLevel 1 "Module Documentation"
59− mapM_ renderModule ms
60−
61−renderModule :: P.Module -> Docs
62−renderModule (P.Module moduleName ds exps) =
63− let exported = filter (isExported exps) ds
64− in do
65− headerLevel 2 $ "Module " ++ P.runModuleName moduleName
66− spacer
67− headerLevel 3 "Types"
68− spacer
69− renderTopLevel exps (filter isTypeDeclaration exported)
70− spacer
71− headerLevel 3 "Type Classes"
72− spacer
73− renderTopLevel exps (filter isTypeClassDeclaration exported)
74− spacer
75− headerLevel 3 "Type Class Instances"
76− spacer
77− renderTopLevel exps (filter isTypeInstanceDeclaration ds)
78− spacer
79− headerLevel 3 "Values"
80− spacer
81− renderTopLevel exps (filter isValueDeclaration exported)
82− spacer
83−
84−isExported :: Maybe [P.DeclarationRef] -> P.Declaration -> Bool
85−isExported Nothing _ = True
86−isExported _ (P.TypeInstanceDeclaration _ _ _ _ _) = True
87−isExported exps (P.PositionedDeclaration _ d) = isExported exps d
88−isExported (Just exps) decl = any (matches decl) exps
89− where
90− matches (P.TypeDeclaration ident _) (P.ValueRef ident') = ident == ident'
91− matches (P.ExternDeclaration _ ident _ _) (P.ValueRef ident') = ident == ident'
92− matches (P.DataDeclaration ident _ _) (P.TypeRef ident' _) = ident == ident'
93− matches (P.ExternDataDeclaration ident _) (P.TypeRef ident' _) = ident == ident'
94− matches (P.TypeSynonymDeclaration ident _ _) (P.TypeRef ident' _) = ident == ident'
95− matches (P.TypeClassDeclaration ident _ _ _) (P.TypeClassRef ident') = ident == ident'
96− matches (P.PositionedDeclaration _ d) r = d `matches` r
97− matches _ _ = False
98−
99−isDctorExported :: P.ProperName -> Maybe [P.DeclarationRef] -> P.ProperName -> Bool
100−isDctorExported _ Nothing _ = True
101−isDctorExported ident (Just exps) ctor = flip any exps $ \e -> case e of
102− P.TypeRef ident' Nothing -> ident == ident'
103− P.TypeRef ident' (Just ctors) -> ident == ident' && ctor `elem` ctors
104− _ -> False
105−
106−renderTopLevel :: Maybe [P.DeclarationRef] -> [P.Declaration] -> Docs
107−renderTopLevel exps decls = forM_ (sortBy (compare `on` getName) decls) $ \decl -> do
108− renderDeclaration 4 exps decl
109− spacer
110−
111−renderDeclaration :: Int -> Maybe [P.DeclarationRef] -> P.Declaration -> Docs
112−renderDeclaration n _ (P.TypeDeclaration ident ty) =
113− atIndent n $ show ident ++ " :: " ++ P.prettyPrintType ty
114−renderDeclaration n _ (P.ExternDeclaration _ ident _ ty) =
115− atIndent n $ show ident ++ " :: " ++ P.prettyPrintType ty
116−renderDeclaration n exps (P.DataDeclaration name args ctors) = do
117− let typeName = P.runProperName name ++ " " ++ unwords args
118− atIndent n $ "data " ++ typeName ++ " where"
119− let exported = filter (isDctorExported name exps . fst) ctors
120− forM_ exported $ \(ctor, tys) ->
121− atIndent (n + 2) $ P.runProperName ctor ++ " :: " ++ concatMap (\ty -> P.prettyPrintType ty ++ " -> ") tys ++ typeName
122−renderDeclaration n _ (P.ExternDataDeclaration name kind) =
123− atIndent n $ "data " ++ P.runProperName name ++ " :: " ++ P.prettyPrintKind kind
124−renderDeclaration n _ (P.TypeSynonymDeclaration name args ty) = do
125− let typeName = P.runProperName name ++ " " ++ unwords args
126− atIndent n $ "type " ++ typeName ++ " = " ++ P.prettyPrintType ty
127−renderDeclaration n exps (P.TypeClassDeclaration name args implies ds) = do
128− let impliesText = case implies of
129− [] -> ""
130− is -> "(" ++ intercalate ", " (map (\(pn, tys') -> show pn ++ " " ++ unwords (map P.prettyPrintTypeAtom tys')) is) ++ ") <= "
131− atIndent n $ "class " ++ impliesText ++ P.runProperName name ++ " " ++ unwords args ++ " where"
132− mapM_ (renderDeclaration (n + 2) exps) ds
133−renderDeclaration n _ (P.TypeInstanceDeclaration name constraints className tys _) = do
134− let constraintsText = case constraints of
135− [] -> ""
136− cs -> "(" ++ intercalate ", " (map (\(pn, tys') -> show pn ++ " " ++ unwords (map P.prettyPrintTypeAtom tys')) cs) ++ ") => "
137− atIndent n $ "instance " ++ show name ++ " :: " ++ constraintsText ++ show className ++ " " ++ unwords (map P.prettyPrintTypeAtom tys)
138−renderDeclaration n exps (P.PositionedDeclaration _ d) =
139− renderDeclaration n exps d
140−renderDeclaration _ _ _ = return ()
141−
142−getName :: P.Declaration -> String
143−getName (P.TypeDeclaration ident _) = show ident
144−getName (P.ExternDeclaration _ ident _ _) = show ident
145−getName (P.DataDeclaration name _ _) = P.runProperName name
146−getName (P.ExternDataDeclaration name _) = P.runProperName name
147−getName (P.TypeSynonymDeclaration name _ _) = P.runProperName name
148−getName (P.TypeClassDeclaration name _ _ _) = P.runProperName name
149−getName (P.TypeInstanceDeclaration name _ _ _ _) = show name
150−getName (P.PositionedDeclaration _ d) = getName d
151−getName _ = error "Invalid argument to getName"
152−
153−isValueDeclaration :: P.Declaration -> Bool
154−isValueDeclaration P.TypeDeclaration{} = True
155−isValueDeclaration P.ExternDeclaration{} = True
156−isValueDeclaration (P.PositionedDeclaration _ d) = isValueDeclaration d
157−isValueDeclaration _ = False
158−
159−isTypeDeclaration :: P.Declaration -> Bool
160−isTypeDeclaration P.DataDeclaration{} = True
161−isTypeDeclaration P.ExternDataDeclaration{} = True
162−isTypeDeclaration P.TypeSynonymDeclaration{} = True
163−isTypeDeclaration (P.PositionedDeclaration _ d) = isTypeDeclaration d
164−isTypeDeclaration _ = False
165−
166−isTypeClassDeclaration :: P.Declaration -> Bool
167−isTypeClassDeclaration P.TypeClassDeclaration{} = True
168−isTypeClassDeclaration (P.PositionedDeclaration _ d) = isTypeClassDeclaration d
169−isTypeClassDeclaration _ = False
170−
171−isTypeInstanceDeclaration :: P.Declaration -> Bool
172−isTypeInstanceDeclaration P.TypeInstanceDeclaration{} = True
173−isTypeInstanceDeclaration (P.PositionedDeclaration _ d) = isTypeInstanceDeclaration d
174−isTypeInstanceDeclaration _ = False
175−
176−inputFile :: Term FilePath
177−inputFile = value $ pos 0 "input.ps" $ posInfo { posDoc = "The input .ps file" }
178−
179−term :: Term (IO ())
180−term = docgen <$> inputFile
181−
182−termInfo :: TermInfo
183−termInfo = defTI
184− { termName = "docgen"
185− , version = showVersion Paths.version
186− , termDoc = "Generate Markdown documentation from PureScript extern files"
187− }
188−
189−main :: IO ()
190−main = run (term, termInfo)
docs/.gitignoredeleted−1
@@ -1 +0,0 @@
1−build
docs/Makefiledeleted−177
@@ -1,177 +0,0 @@
1−# Makefile for Sphinx documentation
2−#
3−
4−# You can set these variables from the command line.
5−SPHINXOPTS =
6−SPHINXBUILD = sphinx-build
7−PAPER =
8−BUILDDIR = build
9−
10−# User-friendly check for sphinx-build
11−ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
12−$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
13−endif
14−
15−# Internal variables.
16−PAPEROPT_a4 = -D latex_paper_size=a4
17−PAPEROPT_letter = -D latex_paper_size=letter
18−ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
19−# the i18n builder cannot share the environment and doctrees with the others
20−I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
21−
22−.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
23−
24−help:
25− @echo "Please use \`make <target>' where <target> is one of"
26− @echo " html to make standalone HTML files"
27− @echo " dirhtml to make HTML files named index.html in directories"
28− @echo " singlehtml to make a single large HTML file"
29− @echo " pickle to make pickle files"
30− @echo " json to make JSON files"
31− @echo " htmlhelp to make HTML files and a HTML help project"
32− @echo " qthelp to make HTML files and a qthelp project"
33− @echo " devhelp to make HTML files and a Devhelp project"
34− @echo " epub to make an epub"
35− @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
36− @echo " latexpdf to make LaTeX files and run them through pdflatex"
37− @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
38− @echo " text to make text files"
39− @echo " man to make manual pages"
40− @echo " texinfo to make Texinfo files"
41− @echo " info to make Texinfo files and run them through makeinfo"
42− @echo " gettext to make PO message catalogs"
43− @echo " changes to make an overview of all changed/added/deprecated items"
44− @echo " xml to make Docutils-native XML files"
45− @echo " pseudoxml to make pseudoxml-XML files for display purposes"
46− @echo " linkcheck to check all external links for integrity"
47− @echo " doctest to run all doctests embedded in the documentation (if enabled)"
48−
49−clean:
50− rm -rf $(BUILDDIR)/*
51−
52−html:
53− $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
54− @echo
55− @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
56−
57−dirhtml:
58− $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
59− @echo
60− @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
61−
62−singlehtml:
63− $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
64− @echo
65− @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
66−
67−pickle:
68− $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
69− @echo
70− @echo "Build finished; now you can process the pickle files."
71−
72−json:
73− $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
74− @echo
75− @echo "Build finished; now you can process the JSON files."
76−
77−htmlhelp:
78− $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
79− @echo
80− @echo "Build finished; now you can run HTML Help Workshop with the" \
81− ".hhp project file in $(BUILDDIR)/htmlhelp."
82−
83−qthelp:
84− $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
85− @echo
86− @echo "Build finished; now you can run "qcollectiongenerator" with the" \
87− ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
88− @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PureScript.qhcp"
89− @echo "To view the help file:"
90− @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PureScript.qhc"
91−
92−devhelp:
93− $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
94− @echo
95− @echo "Build finished."
96− @echo "To view the help file:"
97− @echo "# mkdir -p $$HOME/.local/share/devhelp/PureScript"
98− @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PureScript"
99− @echo "# devhelp"
100−
101−epub:
102− $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
103− @echo
104− @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
105−
106−latex:
107− $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
108− @echo
109− @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
110− @echo "Run \`make' in that directory to run these through (pdf)latex" \
111− "(use \`make latexpdf' here to do that automatically)."
112−
113−latexpdf:
114− $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
115− @echo "Running LaTeX files through pdflatex..."
116− $(MAKE) -C $(BUILDDIR)/latex all-pdf
117− @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
118−
119−latexpdfja:
120− $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
121− @echo "Running LaTeX files through platex and dvipdfmx..."
122− $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
123− @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
124−
125−text:
126− $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
127− @echo
128− @echo "Build finished. The text files are in $(BUILDDIR)/text."
129−
130−man:
131− $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
132− @echo
133− @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
134−
135−texinfo:
136− $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
137− @echo
138− @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
139− @echo "Run \`make' in that directory to run these through makeinfo" \
140− "(use \`make info' here to do that automatically)."
141−
142−info:
143− $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
144− @echo "Running Texinfo files through makeinfo..."
145− make -C $(BUILDDIR)/texinfo info
146− @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
147−
148−gettext:
149− $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
150− @echo
151− @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
152−
153−changes:
154− $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
155− @echo
156− @echo "The overview file is in $(BUILDDIR)/changes."
157−
158−linkcheck:
159− $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
160− @echo
161− @echo "Link check complete; look for any errors in the above output " \
162− "or in $(BUILDDIR)/linkcheck/output.txt."
163−
164−doctest:
165− $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
166− @echo "Testing of doctests in the sources finished, look at the " \
167− "results in $(BUILDDIR)/doctest/output.txt."
168−
169−xml:
170− $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
171− @echo
172− @echo "Build finished. The XML files are in $(BUILDDIR)/xml."
173−
174−pseudoxml:
175− $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
176− @echo
177− @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
docs/source/conf.pydeleted−258
@@ -1,258 +0,0 @@
1−# -*- coding: utf-8 -*-
2−#
3−# PureScript documentation build configuration file, created by
4−# sphinx-quickstart on Wed Jan 22 22:04:23 2014.
5−#
6−# This file is execfile()d with the current directory set to its
7−# containing dir.
8−#
9−# Note that not all possible configuration values are present in this
10−# autogenerated file.
11−#
12−# All configuration values have a default; values that are commented out
13−# serve to show the default.
14−
15−import sys
16−import os
17−
18−# If extensions (or modules to document with autodoc) are in another directory,
19−# add these directories to sys.path here. If the directory is relative to the
20−# documentation root, use os.path.abspath to make it absolute, like shown here.
21−#sys.path.insert(0, os.path.abspath('.'))
22−
23−# -- General configuration ------------------------------------------------
24−
25−# If your documentation needs a minimal Sphinx version, state it here.
26−#needs_sphinx = '1.0'
27−
28−# Add any Sphinx extension module names here, as strings. They can be
29−# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
30−# ones.
31−extensions = []
32−
33−# Add any paths that contain templates here, relative to this directory.
34−templates_path = ['_templates']
35−
36−# The suffix of source filenames.
37−source_suffix = '.rst'
38−
39−# The encoding of source files.
40−#source_encoding = 'utf-8-sig'
41−
42−# The master toctree document.
43−master_doc = 'index'
44−
45−# General information about the project.
46−project = u'PureScript'
47−copyright = u'2014, Phil Freeman'
48−
49−# The version info for the project you're documenting, acts as replacement for
50−# |version| and |release|, also used in various other places throughout the
51−# built documents.
52−#
53−# The short X.Y version.
54−version = '0.5.0'
55−# The full version, including alpha/beta/rc tags.
56−release = '0.5.0'
57−
58−# The language for content autogenerated by Sphinx. Refer to documentation
59−# for a list of supported languages.
60−#language = None
61−
62−# There are two options for replacing |today|: either, you set today to some
63−# non-false value, then it is used:
64−#today = ''
65−# Else, today_fmt is used as the format for a strftime call.
66−#today_fmt = '%B %d, %Y'
67−
68−# List of patterns, relative to source directory, that match files and
69−# directories to ignore when looking for source files.
70−exclude_patterns = []
71−
72−# The reST default role (used for this markup: `text`) to use for all
73−# documents.
74−#default_role = None
75−
76−# If true, '()' will be appended to :func: etc. cross-reference text.
77−#add_function_parentheses = True
78−
79−# If true, the current module name will be prepended to all description
80−# unit titles (such as .. function::).
81−#add_module_names = True
82−
83−# If true, sectionauthor and moduleauthor directives will be shown in the
84−# output. They are ignored by default.
85−#show_authors = False
86−
87−# The name of the Pygments (syntax highlighting) style to use.
88−pygments_style = 'sphinx'
89−
90−# A list of ignored prefixes for module index sorting.
91−#modindex_common_prefix = []
92−
93−# If true, keep warnings as "system message" paragraphs in the built documents.
94−#keep_warnings = False
95−
96−
97−# -- Options for HTML output ----------------------------------------------
98−
99−# The theme to use for HTML and HTML Help pages. See the documentation for
100−# a list of builtin themes.
101−html_theme = 'default'
102−
103−# Theme options are theme-specific and customize the look and feel of a theme
104−# further. For a list of options available for each theme, see the
105−# documentation.
106−#html_theme_options = {}
107−
108−# Add any paths that contain custom themes here, relative to this directory.
109−#html_theme_path = []
110−
111−# The name for this set of Sphinx documents. If None, it defaults to
112−# "<project> v<release> documentation".
113−#html_title = None
114−
115−# A shorter title for the navigation bar. Default is the same as html_title.
116−#html_short_title = None
117−
118−# The name of an image file (relative to this directory) to place at the top
119−# of the sidebar.
120−#html_logo = None
121−
122−# The name of an image file (within the static path) to use as favicon of the
123−# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
124−# pixels large.
125−#html_favicon = None
126−
127−# Add any paths that contain custom static files (such as style sheets) here,
128−# relative to this directory. They are copied after the builtin static files,
129−# so a file named "default.css" will overwrite the builtin "default.css".
130−html_static_path = ['_static']
131−
132−# Add any extra paths that contain custom files (such as robots.txt or
133−# .htaccess) here, relative to this directory. These files are copied
134−# directly to the root of the documentation.
135−#html_extra_path = []
136−
137−# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
138−# using the given strftime format.
139−#html_last_updated_fmt = '%b %d, %Y'
140−
141−# If true, SmartyPants will be used to convert quotes and dashes to
142−# typographically correct entities.
143−#html_use_smartypants = True
144−
145−# Custom sidebar templates, maps document names to template names.
146−#html_sidebars = {}
147−
148−# Additional templates that should be rendered to pages, maps page names to
149−# template names.
150−#html_additional_pages = {}
151−
152−# If false, no module index is generated.
153−#html_domain_indices = True
154−
155−# If false, no index is generated.
156−#html_use_index = True
157−
158−# If true, the index is split into individual pages for each letter.
159−#html_split_index = False
160−
161−# If true, links to the reST sources are added to the pages.
162−#html_show_sourcelink = True
163−
164−# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
165−#html_show_sphinx = True
166−
167−# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
168−#html_show_copyright = True
169−
170−# If true, an OpenSearch description file will be output, and all pages will
171−# contain a <link> tag referring to it. The value of this option must be the
172−# base URL from which the finished HTML is served.
173−#html_use_opensearch = ''
174−
175−# This is the file name suffix for HTML files (e.g. ".xhtml").
176−#html_file_suffix = None
177−
178−# Output file base name for HTML help builder.
179−htmlhelp_basename = 'PureScriptdoc'
180−
181−
182−# -- Options for LaTeX output ---------------------------------------------
183−
184−latex_elements = {
185−# The paper size ('letterpaper' or 'a4paper').
186−#'papersize': 'letterpaper',
187−
188−# The font size ('10pt', '11pt' or '12pt').
189−#'pointsize': '10pt',
190−
191−# Additional stuff for the LaTeX preamble.
192−#'preamble': '',
193−}
194−
195−# Grouping the document tree into LaTeX files. List of tuples
196−# (source start file, target name, title,
197−# author, documentclass [howto, manual, or own class]).
198−latex_documents = [
199− ('index', 'PureScript.tex', u'PureScript Documentation',
200− u'Phil Freeman', 'manual'),
201−]
202−
203−# The name of an image file (relative to this directory) to place at the top of
204−# the title page.
205−#latex_logo = None
206−
207−# For "manual" documents, if this is true, then toplevel headings are parts,
208−# not chapters.
209−#latex_use_parts = False
210−
211−# If true, show page references after internal links.
212−#latex_show_pagerefs = False
213−
214−# If true, show URL addresses after external links.
215−#latex_show_urls = False
216−
217−# Documents to append as an appendix to all manuals.
218−#latex_appendices = []
219−
220−# If false, no module index is generated.
221−#latex_domain_indices = True
222−
223−
224−# -- Options for manual page output ---------------------------------------
225−
226−# One entry per manual page. List of tuples
227−# (source start file, name, description, authors, manual section).
228−man_pages = [
229− ('index', 'purescript', u'PureScript Documentation',
230− [u'Phil Freeman'], 1)
231−]
232−
233−# If true, show URL addresses after external links.
234−#man_show_urls = False
235−
236−
237−# -- Options for Texinfo output -------------------------------------------
238−
239−# Grouping the document tree into Texinfo files. List of tuples
240−# (source start file, target name, title, author,
241−# dir menu entry, description, category)
242−texinfo_documents = [
243− ('index', 'PureScript', u'PureScript Documentation',
244− u'Phil Freeman', 'PureScript', 'One line description of project.',
245− 'Miscellaneous'),
246−]
247−
248−# Documents to append as an appendix to all manuals.
249−#texinfo_appendices = []
250−
251−# If false, no module index is generated.
252−#texinfo_domain_indices = True
253−
254−# How to display URL addresses: 'footnote', 'no', or 'inline'.
255−#texinfo_show_urls = 'footnote'
256−
257−# If true, do not generate a @detailmenu in the "Top" node's menu.
258−#texinfo_no_detailmenu = False
docs/source/ffi.rstdeleted−40
@@ -1,40 +0,0 @@
1−Foreign Function Interface
2−==========================
3−
4−Importing Values
5−----------------
6−
7−The ``foreign import`` keywords declare a value which is defined in Javascript, and its type::
8−
9− foreign import pow :: Number -> Number -> Number
10−
11−Inline Javascript
12−-----------------
13−
14−A foreign import declaration may optionally contain its definition in Javascript as a string literal. If this is provided, the string will be inserted directly into the generated Javascript before the current module definition::
15−
16− foreign import pow
17− "function pow(n) {\
18− \ return function(p) {\
19− \ return Math.pow(n, p);\
20− \ };\
21− \}" :: Number -> Number -> Number
22−
23−Importing Types
24−---------------
25−
26−To declare a new type with no constructors, use ``foreign import data`` and provide the kind::
27−
28− foreign import data DOM :: *
29−
30− foreign import document :: {
31− createElement :: String -> DOM
32− }
33−
34−Importing Type Class Instances
35−------------------------------
36−
37−Type class instances can be imported with ``foreign import instance``::
38−
39− foreign import instance showString :: Prelude.Show String
40−
docs/source/index.rstdeleted−30
@@ -1,30 +0,0 @@
1−.. PureScript documentation master file, created by
2− sphinx-quickstart on Wed Jan 22 22:04:23 2014.
3− You can adapt this file completely to your liking, but it should at least
4− contain the root `toctree` directive.
5−
6−Welcome to PureScript's documentation!
7−======================================
8−
9−Contents:
10−
11−.. toctree::
12− :maxdepth: 2
13−
14− intro
15− types
16− kinds
17− syntax
18− typeclasses
19− patterns
20− modules
21− ffi
22− prelude
23−
24−Indices and tables
25−==================
26−
27−* :ref:`genindex`
28−* :ref:`modindex`
29−* :ref:`search`
30−
docs/source/intro.rstdeleted−143
@@ -1,143 +0,0 @@
1−Introduction
2−============
3−
4−PureScript is a small strongly, statically typed compile-to-JS language with a number of interesting features, such as:
5−
6−- Type Inference
7−- Higher Kinded Polymorphism
8−- Support for basic Javascript types
9−- Extensible records
10−- Extensible effects
11−- Optimizer rules for generation of efficient Javascript
12−- Pattern matching
13−- Simple FFI
14−- Modules
15−- Rank N Types
16−- Do Notation
17−- Tail-call elimination
18−- Type Classes
19−
20−Installation
21−------------
22−
23−If you have the Haskell Plaform installed, then you can install the latest released version from Hackage::
24−
25− cabal update
26− cabal install purescript
27−
28−If you would like to build the latest version of the code, clone this repository and build::
29−
30− git clone git://github.com:paf31/purescript.git
31− cabal configure --enable-tests
32− cabal build
33− cabal test
34− cabal install
35−
36−Usage
37−-----
38−
39−The `psc` executable takes a list of PureScript source files as arguments and by default writes out its errors or output to the console.
40−
41−The following options are supported:
42−
43−--stdin Read input from standard input instead of from files
44−--output Write the generated Javascript to the specified file
45−--externs Write a list of foreign imports declarations to the specified file in addition to generating Javascript output
46−--runtime-type-checks Generate simple runtime type checks for function arguments with simple types.
47−--no-tco Turn off tail-call elimination.
48−--no-prelude Do not include the Prelude in the generated Javascript.
49−--no-magic-do Turn off optimizations which inline calls to ``>>=`` for the ``Eff`` monad.
50−--no-opts Disable all optimizations.
51−--main Generate a call to ``main`` in the specified module after all other generated Javascript. Defaults to ``Main`` if the option is used but no value is provided.
52−--module If specified, any code which is not referenced transitively from this module will be removed. This argument can be used multiple times.
53−--codegen A list of modules for which Javascript and externs should be generated. This argument can be used multiple times.
54−--browser-namespace Specify the namespace that PureScript modules will be exported to when running in the browser.
55−--verbose-errors Generate verbose error messages
56−
57−Motivation
58−----------
59−
60−I was looking for a simple functional language which would compile to JavaScript and have the following characteristics:
61−
62−- Generate simple readable Javascript
63−- Provide the ability to compile to tight loops if necessary
64−- Reasonable type system
65−- Ideally, written in a programming language I would enjoy working in
66−- Provides a simple interface to existing Javascript code
67−
68−I didn't find exactly what I was looking for, so I wrote PureScript. It doesn't have everything right now, but it should serve as a simple core on which to develop new ideas.
69−
70−PureScript was originally designed to implement purely functional core logic. However, recent additions to the compiler and libraries now also make it a good option for general-purpose programming.
71−
72−PureScript can also be seen as a trade-off between a theoretically ideal language and one which generates reasonably high performance code.
73−
74−Hello, PureScript!
75−------------------
76−
77−As an introductory example, here is the usual "Hello World" written in PureScript::
78−
79− module Main where
80−
81− import Debug.Trace
82−
83− main = trace "Hello, World!"
84−
85−which compiles to the following Javascript, ignoring the Prelude::
86−
87− var Main;
88− (function (Main) {
89− var main = trace("Hello, World!");
90− Main.main = main;
91− })(Main = Main || {});
92−
93−The following command will compile and execute the PureScript code above::
94−
95− psc input.purs --main | node
96−
97−Another Example
98−---------------
99−
100−The following code defines a ``Person`` data type and a function to generate a string representation for a ``Person``::
101−
102− data Person = Person { name :: String, age :: Number }
103−
104− showPerson :: Person -> String
105− showPerson (Person o) = o.name ++ ", aged " ++ show o.age
106−
107− examplePerson :: Person
108− examplePerson = Person { name: "Bonnie", age: 26 }
109−
110−Line by line, this reads as follows:
111−
112−- ``Person`` is a data type with one constructor, also called ``Person``
113−- The ``Person`` constructor takes an object with two properties, ``name`` which is a ``String``, and ``age`` which is a ``Number``
114−- The ``showPerson`` function takes a ``Person`` and returns a ``String``
115−- ``showPerson`` works by case analysis on its argument, first matching the constructor ``Person`` and then using string concatenation and object accessors to return its result.
116−- ``examplePerson`` is a Person object, made with the ``Person`` constructor and given the String "Bonnie" for the name value and the Number 26 for the age value.
117−
118−The generated Javascript looks like this::
119−
120− var Person = function (value) {
121− return { ctor: 'Person', values: [value] };
122− };
123−
124− function showPerson(_1) {
125− return _1.values[0].name + ", aged " + numberToString(_1.values[0].age);
126− };
127−
128− var examplePerson = Person({
129− name: "Bonnie",
130− age: 26
131− });
132−
133−Related Projects
134−----------------
135−
136−PureScript might be compared to other AltJS projects such as Roy, Haste, Fay, Elm and GHCJS. Certainly, there is a lot of overlap in terms of syntax, but the goals of PureScript listed above separate it in one or more ways from each of these languages.
137−
138−Roy is probably the most similar language on the list, and was a large influence on the development of PureScript. There are however, key differences in the foreign function interface, the type system and the choice of development language (Haskell vs. Javascript)
139−
140−Projects such as Haste, Fay and GHCJS aim to use some combination of the GHC compiler itself and/or its intermediate representation, Core, to perform some of the tasks involved in compilation such as parsing and type checking. This usually gives the advantage that tools and libraries can be shared with Haskell, but often at the cost of the size of the generated Javascript. This is the main practical difference between PureScript and these projects.
141−
142−Elm also shares a lot in terms of functionality with PureScript. Elm is designed for functional reactive programming, and focusses on tools and language features suitable for that domain, while PureScript focusses on the development of purely functional core application logic. Another difference between PureScript and Elm is PureScript's lack of a runtime system.
143−
docs/source/kinds.rstdeleted−21
@@ -1,21 +0,0 @@
1−Kind System
2−===========
3−
4−The kind system defines the following kinds:
5−
6−- ``*``, the kind of types.
7−- ``!``, the kind of effects.
8−- Arrow kinds ``k1 -> k2``
9−- Row kinds ``# k``
10−
11−Row Kinds
12−---------
13−
14−The kind ``# k`` of rows is used to classify labelled, unordered collections of types of kind ``k``.
15−
16−For example ``# *`` is the kind of rows of types, as used to define records, and ``# !`` is the kind of rows of effects, used to define the monad ``Eff`` of extensible effects.
17−
18−Quantification
19−--------------
20−
21−A type variable can refer to not only a type or a row, but a type constructor, or row constructor etc., and type variables with those kinds can be bound inside a ``forall`` quantifier.
docs/source/modules.rstdeleted−44
@@ -1,44 +0,0 @@
1−Modules
2−=======
3−
4−All code in PureScript is contained in a module. Modules are introduced using the ``module`` keyword::
5−
6− module A where
7−
8− id x = x
9−
10−When referencing values or data types in another module, names may be qualified by using a dot::
11−
12− module B where
13−
14− foo = A.id
15−
16−Importing Modules
17−-----------------
18−
19−A module can be imported using the ``import`` keyword. This will create aliases for all of the values and types in the imported module::
20−
21− module B where
22−
23− import A
24−
25−Alternatively, a list of names to import can be provided in parentheses::
26−
27− module B where
28−
29− import A (runFoo)
30−
31−Values, type constructors and data constructors can all be explicitly imported. A type constructor should be followed by a list of associated data constructors to import in parentheses. A double dot (``..``) can be used to import all data constructors for a given type constructor::
32−
33− module B where
34−
35− import A (runFoo, Foo(..), Bar(Bar))
36−
37−Module Exports
38−--------------
39−
40−Module exports can be restricted to a set of names by providing that set in parentheses in the module declaration::
41−
42− module A (runFoo, Foo(..)) where
43−
44−The types of names which can be exported is the same as for module imports.
docs/source/patterns.rstdeleted−139
@@ -1,139 +0,0 @@
1−Pattern Matching
2−================
3−
4−Pattern matching deconstructs a value to bring zero or more expressions into scope. Pattern matches are introduced with the `case` keyword.
5−
6−Pattern matches have the following general form::
7−
8− case value of
9− pattern -> result
10− ...
11− pattern -> result
12−
13−Pattern matching can also be used in the declaration of functions, as we have already seen::
14−
15− fn pattern_1 ... pattern_n = result
16−
17−Patterns can also be used when introducing functions. For example::
18−
19− example x y z = x * y + z
20−
21−The following pattern types are supported:
22−
23−- Wildcard pattern
24−- Literal patterns
25−- Variable pattern
26−- Array patterns
27−- Cons patterns
28−- Constructor patterns
29−- Record patterns
30−- Named patterns
31−- Guards
32−
33−Patterns need not be exhaustive. A pattern match failed exception will be thrown at runtime if no pattern matches the input.
34−
35−Wildcard Patterns
36−-----------------
37−
38−The wilcard `_` matches any input and brings nothing into scope::
39−
40− f _ = 0
41−
42−Literal Patterns
43−----------------
44−
45−Literal patterns are provided to match on primitives::
46−
47− f true = 0
48− f false = 1
49−
50− g "Foo" = 0
51− g _ = 1
52−
53− h 0 = 0
54− h _ = 1
55−
56−Variable Patterns
57−-----------------
58−
59−A variable pattern matches any input and binds that input to its name::
60−
61− double x = x * 2
62−
63−Array Patterns
64−--------------
65−
66−Array patterns match an input which is an array, and bring its elements into scope. For example::
67−
68− f [x] = x
69− f [x, y] = x * y
70− f _ = 0
71−
72−Here, the first pattern only matches arrays of length one, and brings the first element of the array into scope.
73−
74−The second pattern matches arrays with two elements, and brings the first and second elements into scope.
75−
76−Cons Patterns
77−-------------
78−
79−The head and tail of a non-empty array can be matched by using a cons pattern::
80−
81− sum [] = 0
82− sum (x : xs) = x + sum xs
83−
84−`:` associates to the right::
85−
86− addPairs (x : y : xs) = x * y + addPairs xs
87− addPairs _ = 0
88−
89−
90−Constructor patterns
91−--------------------
92−
93−Constructor patterns match a data constructor and its arguments::
94−
95− data Foo = Foo String | Bar Number Boolean
96−
97− foo (Foo s) = true
98− foo (Bar _ b) = b
99−
100−Record Patterns
101−---------------
102−
103−Record patterns match an input which is a record, and bring its properties into scope::
104−
105− f { foo = "Foo" } = o.bar
106− f _ = 0
107−
108−Nested Patterns
109−---------------
110−
111−The patterns above can be combined to create larger patterns. For example::
112−
113− f { arr = x : _, take = "car" } = x
114− f { arr = _ : x : _, take = "cadr" } = x
115− f _ = 0
116−
117−Named Patterns
118−--------------
119−
120−Named patterns bring additional names into scope when using nested patterns. Any pattern can be named by using the ``@`` symbol::
121−
122− f a@(_ : _ : _) = true
123− f _ = false
124−
125−Here, in the first pattern, any array with two or more elements will be matched and bound to the variable ``a``.
126−
127−Guards
128−------
129−
130−Guards are used to impose additional constraints inside a pattern using boolean-valued expressions, and are introduced with a pipe after the pattern::
131−
132− evens [] = 0
133− evens (x : xs) | x % 2 == 0 = 1 + evens xs
134− evens (_ : xs) = evens xs
135−
136−When using patterns to define a function at the top level, guards appear after all patterns::
137−
138− greater x y | x > y = true
139− greater _ _ = false
docs/source/prelude.rstdeleted−332
@@ -1,332 +0,0 @@
1−Module Documentation
2−====================
3−
4−Module Prelude
5−--------------
6−
7−Types
8−~~~~~
9−
10−::
11−
12− data Ordering where
13− LT :: Ordering
14− GT :: Ordering
15− EQ :: Ordering
16−
17−Type Classes
18−~~~~~~~~~~~~
19−
20−::
21−
22− class Alternative f where
23− empty :: forall a. f a
24− (<|>) :: forall a. f a -> f a -> f a
25−
26− class Applicative f where
27− pure :: forall a. a -> f a
28− (<*>) :: forall a b. f (a -> b) -> f a -> f b
29−
30− class Bits b where
31− (&) :: b -> b -> b
32− (|) :: b -> b -> b
33− (^) :: b -> b -> b
34− shl :: b -> Prim.Number -> b
35− shr :: b -> Prim.Number -> b
36− zshr :: b -> Prim.Number -> b
37− complement :: b -> b
38−
39− class BoolLike b where
40− (&&) :: b -> b -> b
41− (||) :: b -> b -> b
42− not :: b -> b
43−
44− class Category a where
45− id :: forall t. a t t
46− (<<<) :: forall b c d. a c d -> a b c -> a b d
47−
48− class Eq a where
49− (==) :: a -> a -> Prim.Boolean
50− (/=) :: a -> a -> Prim.Boolean
51−
52− class Functor f where
53− (<$>) :: forall a b. (a -> b) -> f a -> f b
54−
55− class Monad m where
56− return :: forall a. a -> m a
57− (>>=) :: forall a b. m a -> (a -> m b) -> m b
58−
59− class Num a where
60− (+) :: a -> a -> a
61− (-) :: a -> a -> a
62− (*) :: a -> a -> a
63− (/) :: a -> a -> a
64− (%) :: a -> a -> a
65− negate :: a -> a
66−
67− class Ord a where
68− compare :: a -> a -> Ordering
69−
70− class Show a where
71− show :: a -> Prim.String
72−
73−Type Class Instances
74−~~~~~~~~~~~~~~~~~~~~
75−
76−::
77−
78− instance applicativeFromMonad :: (Monad m) => Applicative m
79−
80− instance bitsNumber :: Bits Prim.Number
81−
82− instance boolLikeBoolean :: BoolLike Prim.Boolean
83−
84− instance categoryArr :: Category Prim.Function
85−
86− instance eqArray :: (Eq a) => Eq [a]
87−
88− instance eqBoolean :: Eq Prim.Boolean
89−
90− instance eqNumber :: Eq Prim.Number
91−
92− instance eqString :: Eq Prim.String
93−
94− instance functorFromApplicative :: (Applicative f) => Functor f
95−
96− instance numNumber :: Num Prim.Number
97−
98− instance ordNumber :: Ord Prim.Number
99−
100− instance showBoolean :: Show Prim.Boolean
101−
102− instance showNumber :: Show Prim.Number
103−
104− instance showOrdering :: Show Ordering
105−
106− instance showString :: Show Prim.String
107−
108−Values
109−~~~~~~
110−
111−::
112−
113− (!!) :: forall a. [a] -> Prim.Number -> a
114−
115− (#) :: forall a b. a -> (a -> b) -> b
116−
117− ($) :: forall a b. (a -> b) -> a -> b
118−
119− (++) :: Prim.String -> Prim.String -> Prim.String
120−
121− (<) :: forall a. (Ord a) => a -> a -> Prim.Boolean
122−
123− (<=) :: forall a. (Ord a) => a -> a -> Prim.Boolean
124−
125− (>) :: forall a. (Ord a) => a -> a -> Prim.Boolean
126−
127− (>=) :: forall a. (Ord a) => a -> a -> Prim.Boolean
128−
129− (>>>) :: forall a b c d. (Category a) => a b c -> a c d -> a b d
130−
131− boolAnd :: Prim.Boolean -> Prim.Boolean -> Prim.Boolean
132−
133− boolNot :: Prim.Boolean -> Prim.Boolean
134−
135− boolOr :: Prim.Boolean -> Prim.Boolean -> Prim.Boolean
136−
137− const :: forall a b. a -> b -> a
138−
139− flip :: forall a b c. (a -> b -> c) -> b -> a -> c
140−
141− numAdd :: Prim.Number -> Prim.Number -> Prim.Number
142−
143− numAnd :: Prim.Number -> Prim.Number -> Prim.Number
144−
145− numCompare :: Prim.Number -> Prim.Number -> Ordering
146−
147− numComplement :: Prim.Number -> Prim.Number
148−
149− numDiv :: Prim.Number -> Prim.Number -> Prim.Number
150−
151− numMod :: Prim.Number -> Prim.Number -> Prim.Number
152−
153− numMul :: Prim.Number -> Prim.Number -> Prim.Number
154−
155− numNegate :: Prim.Number -> Prim.Number
156−
157− numOr :: Prim.Number -> Prim.Number -> Prim.Number
158−
159− numShl :: Prim.Number -> Prim.Number -> Prim.Number
160−
161− numShr :: Prim.Number -> Prim.Number -> Prim.Number
162−
163− numSub :: Prim.Number -> Prim.Number -> Prim.Number
164−
165− numXor :: Prim.Number -> Prim.Number -> Prim.Number
166−
167− numZshr :: Prim.Number -> Prim.Number -> Prim.Number
168−
169− on :: forall a b c. (b -> b -> c) -> (a -> b) -> a -> a -> c
170−
171− refEq :: forall a. a -> a -> Prim.Boolean
172−
173− refIneq :: forall a. a -> a -> Prim.Boolean
174−
175− showNumberImpl :: Prim.Number -> Prim.String
176−
177−Module Data.Eq
178−--------------
179−
180−Types
181−~~~~~
182−
183−::
184−
185− data Ref a where
186− Ref :: a -> Ref a
187−
188−Type Classes
189−~~~~~~~~~~~~
190−
191−Type Class Instances
192−~~~~~~~~~~~~~~~~~~~~
193−
194−::
195−
196− instance eqRef :: Eq (Ref a)
197−
198−Values
199−~~~~~~
200−
201−::
202−
203− liftRef :: forall a b. (a -> a -> b) -> Ref a -> Ref a -> b
204−
205−Module Control.Monad.Eff
206−------------------------
207−
208−Types
209−~~~~~
210−
211−::
212−
213− data Eff :: # ! -> * -> *
214−
215− type Pure a = forall e. Eff e a
216−
217−Type Classes
218−~~~~~~~~~~~~
219−
220−Type Class Instances
221−~~~~~~~~~~~~~~~~~~~~
222−
223−::
224−
225− instance monadEff :: Monad (Eff e)
226−
227−Values
228−~~~~~~
229−
230−::
231−
232− bindEff :: forall e a b. Eff e a -> (a -> Eff e b) -> Eff e b
233−
234− forE :: forall e. Prim.Number -> Prim.Number -> (Prim.Number -> Eff e { }) -> Eff e { }
235−
236− foreachE :: forall e a. [a] -> (a -> Eff e { }) -> Eff e { }
237−
238− retEff :: forall e a. a -> Eff e a
239−
240− runPure :: forall a. Pure a -> a
241−
242− untilE :: forall e. Eff e Prim.Boolean -> Eff e { }
243−
244− whileE :: forall e a. Eff e Prim.Boolean -> Eff e a -> Eff e { }
245−
246−Module Control.Monad.Eff.Unsafe
247−-------------------------------
248−
249−Types
250−~~~~~
251−
252−Type Classes
253−~~~~~~~~~~~~
254−
255−Type Class Instances
256−~~~~~~~~~~~~~~~~~~~~
257−
258−Values
259−~~~~~~
260−
261−::
262−
263− unsafeInterleaveEff :: forall eff1 eff2 a. Eff eff1 a -> Eff eff2 a
264−
265−Module Debug.Trace
266−------------------
267−
268−Types
269−~~~~~
270−
271−::
272−
273− data Trace :: !
274−
275−Type Classes
276−~~~~~~~~~~~~
277−
278−Type Class Instances
279−~~~~~~~~~~~~~~~~~~~~
280−
281−Values
282−~~~~~~
283−
284−::
285−
286− print :: forall a r. (Show a) => a -> Eff (trace :: Trace | r) { }
287−
288− trace :: forall r. Prim.String -> Eff (trace :: Trace | r) { }
289−
290−Module Control.Monad.ST
291−-----------------------
292−
293−Types
294−~~~~~
295−
296−::
297−
298− data ST :: * -> !
299−
300− data STArray :: * -> * -> *
301−
302− data STRef :: * -> * -> *
303−
304−Type Classes
305−~~~~~~~~~~~~
306−
307−Type Class Instances
308−~~~~~~~~~~~~~~~~~~~~
309−
310−Values
311−~~~~~~
312−
313−::
314−
315− modifySTRef :: forall a h r. STRef h a -> (a -> a) -> Eff (st :: ST h | r) a
316−
317− newSTArray :: forall a h r. Prim.Number -> a -> Eff (st :: ST h | r) (STArray h a)
318−
319− newSTRef :: forall a h r. a -> Eff (st :: ST h | r) (STRef h a)
320−
321− peekSTArray :: forall a h r. STArray h a -> Eff (st :: ST h | r) a
322−
323− pokeSTArray :: forall a h r. STArray h a -> Prim.Number -> a -> Eff (st :: ST h | r) a
324−
325− readSTRef :: forall a h r. STRef h a -> Eff (st :: ST h | r) a
326−
327− runST :: forall a r. (forall h. Eff (st :: ST h | r) a) -> Eff r a
328−
329− runSTArray :: forall a r. (forall h. Eff (st :: ST h | r) (STArray h a)) -> Eff r [a]
330−
331− writeSTRef :: forall a h r. STRef h a -> a -> Eff (st :: ST h | r) a
332−
docs/source/syntax.rstdeleted−240
@@ -1,240 +0,0 @@
1−Syntax
2−======
3−
4−Whitespace Rules
5−----------------
6−
7−Syntax is whitespace sensitive. The general rule of thumb is that declarations which span multiple lines should be indented past the column on which they were first defined on their subsequent lines.
8−
9−That is, the following is valid::
10−
11− foo = bar(x) +
12− baz(x)
13−
14−But this is not::
15−
16− foo = bar(x) +
17− baz(x)
18−
19−Operators
20−---------
21−
22−PureScript supports the following unary operators (in precedence order):
23−
24−== =======================
25− Meaning
26−== =======================
27−\- Numeric negation
28−! Boolean negation
29−~ Binary negation
30−\+ Unary plus (numeric)
31−== =======================
32−
33−and the following binary operators (in precedence order):
34−
35−==== =====================
36− Meaning
37−==== =====================
38−\+ Numeric addition
39−\- Numeric subtraction
40−\* Numeric multiplication
41−/ Numeric division
42−% Numeric modulus
43−== Equality check
44−!= Inequality check
45−< Less than
46−<= Less than or equal
47−> Greater than
48−>= Greater than or equal
49−&& Boolean AND
50−|| Boolean OR
51−& Binary AND
52−\| Binary OR
53−^ Binary XOR
54−<< Shift Left
55−>> Shift Right
56−\>>> Zero-Fill Shift Right
57−++ String concatenation
58−==== =====================
59−
60−Literal Values
61−--------------
62−
63−Numeric literals can be integers or floating point numbers. Numbers in hexadecimal notation should be preceded by the characters ``0x``::
64−
65− 16
66− 16.0
67− 0xF0
68−
69−String literals are enclosed in double-quotes and may extend over multiple lines. Line breaks should be surrounded by slashes as follows::
70−
71− "Hello World"
72−
73− "Hello \
74− \World"
75−
76−The two boolean literals are ``true`` and ``false``.
77−
78−Array Literals
79−--------------
80−
81−Array literals are surrounded by square brackets, as in Javascript::
82−
83− []
84− [1, 2, 3]
85−
86−Record Literals
87−---------------
88−
89−Record literals are surrounded by braces, as in Javascript::
90−
91− {}
92− { foo: "Foo", bar: 1 }
93−
94−Array Indexing
95−--------------
96−
97−To retrieve the element of an array at an index, use the ``!!`` operator::
98−
99− arr !! 0
100−
101−This example corresponds to the Javascript ``arr[0]``.
102−
103−Property Accessors
104−------------------
105−
106−To access a property of a record, use a dot, followed by the property name, as in Javascript::
107−
108− rec.propertyName
109−
110−Functions
111−---------
112−
113−Functions are introduced by using a backslash followed by a list of argument names::
114−
115− example1 = \a b -> a + b
116−
117−which would correspond to the following Javascript::
118−
119− function example1(a) {
120− return function (b) {
121− return a + b;
122− }
123− }
124−
125−Function application is indicated by just the juxtaposition of a function with its arugments::
126−
127− example1 10 20
128−
129−Functions can also be defined at the top level by providing a list of patterns and an optional guard on the left hand side of the equals sign::
130−
131− f [] [] = []
132− f (x:xs) (y:ys) = x + y : f xs ys
133−
134−If-Then-Else Expressions
135−------------------------
136−
137−The ``if``, ``then`` and ``else`` keywords can be used to create conditional expressions. In this case, the ``else`` block is always required.
138−
139−For example::
140−
141− conditional = if 2 > 1 then "ok" else "oops"
142−
143−Do Notation
144−-----------
145−
146−The ``do`` keyword introduces simple syntactic sugar for monadic expressions.
147−
148−Here is an example, using the maybe monad::
149−
150− data Maybe a = Nothing | Just a
151−
152− instance Monad Maybe where
153− ret = Just
154− (>>=) Nothing _ = Nothing
155− (>>=) (Just a) f = f a
156−
157− isEven n | n % 2 == 0 = Just {}
158− isEven _ = Nothing
159−
160− evenSum a b = do
161− n <- a
162− m <- b
163− let sum = n + m
164− isEven sum
165− ret sum
166−
167−``isEven`` adds two values of type ``Maybe Number`` and returns their sum, if the sum is even. If the sum is odd, ``evenSum`` returns ``Nothing``.
168−
169−When using ``do`` notation, the corresponding type constructor must be an instance of the ``Prelude.Monad`` type class, which defines the ``ret`` and ``>>=`` functions.
170−
171−Statements can have the following form:
172−
173−- ``a <- x`` which desugars to ``m.bind x (\a -> ...)` `
174−- ``let a = x`` which desugars to ``(\a -> ...)(x)``
175−- ``x`` which desugars to ``m.bind x (\_ -> ...)`` or just ``x`` if this is the last statement.
176−
177−Binders can be used on the left hand side of ``<-`` or ``=``. For example::
178−
179− test arr = do
180− (x:y:_) <- arr
181− ret (x + y)
182−
183−A pattern match failure will generate a runtime exception, just as in the case of a regular ``case`` statement.
184−
185−Operators
186−---------
187−
188−In addition to the standard operators, user-defined infix operators can be created by enclosing names in parentheses.
189−
190−E.g. to create a synonym for string concatenation::
191−
192− (<>) = \s1 s2 -> s1 ++ s2
193−
194− greeting = "Hello" <> "World!"
195−
196−Regular functions can be used as operators by enclosing their names in backticks::
197−
198− foo = \x y -> x * y + y
199−
200− test = 10 `foo` 20
201−
202−Fixity declarations can associate a precedence level, which is a natural number, to a user-defined operator, and specify which way it associates::
203−
204− infixl 5 <>
205− infixr 7 %%
206−
207−Record Updates
208−--------------
209−
210−Properties on records can be updated using the following syntax::
211−
212− o { key = value, ..., key = value }
213−
214−For example, the following function increments the ``foo`` property on its argument::
215−
216− incr o = o { foo = o.foo + 1 }
217−
218−Let Bindings
219−------------
220−
221−The ``let`` keywords a collection of local declarations, which may be mutually recursive, and which may include type declarations::
222−
223− factorial :: Number -> Number
224− factorial =
225− let
226− go :: Number -> Number -> Number
227− go acc 1 = acc
228− go acc n = go (acc * n) (n - 1)
229− in
230− go 1
231−
232−The ``where`` keyword can also be used to introduce local declarations `at the end of a value declaration`::
233−
234− factorial :: Number -> Number
235− factorial = go 1
236− where
237− go :: Number -> Number -> Number
238− go acc 1 = acc
239− go acc n = go (acc * n) (n - 1)
240−
docs/source/typeclasses.rstdeleted−26
@@ -1,26 +0,0 @@
1−Type Classes
2−============
3−
4−PureScript has basic support for type classes via the ``class`` and ``instance`` keywords.
5−
6−Types appearing in class instances are must be of the form ``String``, ``Number``, ``Boolean``, or ``C t1 ... tn`` where ``C`` is a type constructor (including ``[]`` and ``->`` and ``t_i`` are types of the same form).
7−
8−Type class instances are resolved based on the order in which they appeared in the source files. In particular, overlapping instances are permitted.
9−
10−Here is an example of the ``Show`` typeclass, with instances for ``String``, ``Booleans`` and ``[]``::
11−
12− class Show a where
13− show :: a -> String
14−
15− instance showString :: Show String where
16− show s = s
17−
18− instance showBoolean :: Show Boolean where
19− show true = "true"
20− show false = "false"
21−
22− instance showArray :: (Show a) => Show [a] where
23− show [] = "[]"
24− show (x:xs) = show x ++ " : " ++ showArray xs
25−
26− example = show [true, false]
docs/source/types.rstdeleted−158
@@ -1,158 +0,0 @@
1−Types
2−=====
3−
4−The type system defines the following types:
5−
6−- Primitive Types: Number, String, Boolean
7−- Arrays
8−- Records
9−- Tagged Unions
10−- Functions
11−- Polymorphic Types
12−- Constrained Types
13−- Type Synonyms
14−- Rows
15−
16−Primitive Types
17−---------------
18−
19−The three primitive types ``String``, ``Number`` and ``Boolean`` correspond to their Javascript equivalents at runtime.
20−
21−Arrays
22−------
23−
24−PureScript arrays correspond to Javascript arrays at runtime, but all elements in an array must have the same type.
25−
26−Records
27−-------
28−
29−PureScript records correspond to Javascript objects. They may have zero or more named fields, each with their own types.
30−
31−Tagged Unions
32−-------------
33−
34−Tagged unions consist of one or more constructors, each of which takes zero or more arguments.
35−
36−Tagged unions can only be created using their constructors, and deconstructed through pattern matching (see later).
37−
38−For example::
39−
40− data Foo a = Foo | Bar String
41−
42− runFoo Foo = "It's a Foo"
43− runFoo (Bar s) = "It's a Bar. The string is " ++ s
44−
45− test = runFoo Foo ++ runFoo (Bar "Test")
46−
47−In the example, Foo is a tagged union type which has two constructors. It's first constructor ``Foo`` takes no argument, and it's second ``Bar`` takes one, which must be a String.
48−
49−``runFoo`` is an example of pattern matching on a tagged union type to discover its constructor, and the last line shows how to construct values of type ``Foo``.
50−
51−Functions
52−---------
53−
54−Functions in PureScript are like their Javascript counterparts, but always have exactly one argument.
55−
56−Polymorphic Types
57−-----------------
58−
59−Expressions defined at the top level may have polymorphic types.
60−
61−Here is an example::
62−
63− identity x = x
64−
65−``identity`` is inferred to have (polymorphic) type ``forall t0. t0 -> t0``. This means that for any type ``t0``, ``identity`` can be given a value of type ``t0`` and will give back a value of the same type.
66−
67−A type annotation can also be provided::
68−
69− identity :: forall a. a -> a
70− identity x = x
71−
72−Row Polymorphism
73−----------------
74−
75−Polymorphism is not limited to abstracting over types. Values may also be polymorphic in types with other kinds, such as rows or effects (see "Kind System").
76−
77−For example, the following function accesses two properties on a record::
78−
79− addProps o = o.foo + o.bar
80−
81−The inferred type of ``addProps`` is::
82−
83− forall r. { foo :: Number, bar :: Number | r } -> Number
84−
85−Here, the type variable ``r`` has kind ``# *`` - it represents a `row` of `types`. It can be instantiated with any row of named types.
86−
87−In other words, ``addProps`` accepts any record which has properties ``Foo`` and ``Bar``, and *any other record properties*.
88−
89−Therefore, the following application compiles::
90−
91− addProps { foo: 1, bar: 2, baz: 3 }
92−
93−even though the type of ``addProps`` does not mention the property ``baz``. However, the following does not compile::
94−
95− addProps { foo: 1 }
96−
97−since the ``bar`` property is missing.
98−
99−Rank N Types
100−------------
101−
102−It is also possible for the ``forall`` quantifier to appear on the left of a function arrow, inside types record fields and data constructors, and in type synonyms.
103−
104−In most cases, a type annotation is necessary when using this feature.
105−
106−As an example, we can pass a polymorphic function as an argument to another function::
107−
108− poly :: (forall a. a -> a) -> Boolean
109− poly f = (f 0 < 1) == f true
110−
111−Notice that the polymorphic function's type argument is instantiated to both ``Number`` and ``Boolean``.
112−
113−An argument to ``poly`` must indeed be polymorphic. For example, the following fails::
114−
115− test = poly (\n -> n + 1)
116−
117−since the skolemized type variable ``a`` does not unify with ``Number``.
118−
119−Rows
120−----
121−
122−A row of types represents an unordered collection of named types without duplicates.
123−
124−Rows have kind ``# k`` for some kind ``k``, and so values do not have types which are rows. Rather, rows can be used in type signatures to define record types or other type where labelled, unordered types are useful.
125−
126−To denote a closed row, separate the fields with commas, with each label separated from its type with a double colon::
127−
128− (name :: String, age :: Number)
129−
130−It may be necessary, depending on the context, to surround a row in parentheses.
131−
132−To denote an open row (i.e. one which may unify with another row to add new fields), separate the specified terms from a row variable by a pipe::
133−
134− (name :: String, age :: Number | r)
135−
136−Type Synonyms
137−-------------
138−
139−For convenience, it is possible to declare a synonym for a type using the ``type`` keyword. Type synonyms can include type arguments.
140−
141−For example::
142−
143− type Foo = { foo :: Number, bar :: Number }
144−
145− addFoo :: Foo -> Number
146− addFoo = \o -> o.foo + o.bar
147−
148−Constrained Types
149−-----------------
150−
151−Polymorphic types may be predicated on one or more ``constraints``. See the chapter on type classes for more information.
152−
153−Type Annotations
154−----------------
155−
156−Most types can be inferred (not including Rank N Types and constrained types), but annotations can optionally be provided using a double-colon::
157−
158− one = 1 :: Number
examples/.gitignoredeleted−1
@@ -1 +0,0 @@
1−shelltest/tests
examples/failing/Arrays.pursdeleted−5
@@ -1,5 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− test = \arr -> arr !! (0 !! 0)
examples/failing/Do.pursdeleted−8
@@ -1,8 +0,0 @@
1−module Main where
2−
3−test1 = do let x = 1
4−
5−test2 y = do x <- y
6−
7−test3 = do return 1
8− return 2
examples/failing/KindError.pursdeleted−3
@@ -1,3 +0,0 @@
1−module Main where
2−
3− data KindError f a = One f | Two (f a)
examples/failing/Let.pursdeleted−3
@@ -1,3 +0,0 @@
1−module Main where
2−
3−test = let x = x in x
examples/failing/MPTCs.pursdeleted−7
@@ -1,7 +0,0 @@
1−module Main where
2−
3−class Foo a where
4− f :: a -> a
5−
6−instance Foo String String where
7− f a = a
examples/failing/MutRec.pursdeleted−5
@@ -1,5 +0,0 @@
1−module MutRec where
2−
3−x = y
4−
5−y = x
examples/failing/MutRec2.pursdeleted−3
@@ -1,3 +0,0 @@
1−module Main where
2−
3−x = x
examples/failing/NoOverlap.pursdeleted−11
@@ -1,11 +0,0 @@
1−module Main where
2−
3−data Foo = Foo
4−
5−instance showFoo1 :: Show Foo where
6− show _ = "Foo"
7−
8−instance showFoo2 :: Show Foo where
9− show _ = "Bar"
10−
11−test = show Foo
examples/failing/NullaryAbs.pursdeleted−3
@@ -1,3 +0,0 @@
1−module Main where
2−
3− func = \ -> "no"
examples/failing/Object.pursdeleted−5
@@ -1,5 +0,0 @@
1−module Main where
2−
3−test o = o.foo
4−
5−test1 = test {}
examples/failing/OverlappingVars.pursdeleted−12
@@ -1,12 +0,0 @@
1−module Main where
2−
3−class OverlappingVars a where
4− f :: a -> a
5−
6−data Foo a b = Foo a b
7−
8−instance OverlappingVars (Foo a a) where
9− f a = a
10−
11−test = f (Foo "" 0)
12−
examples/failing/Rank2Types.pursdeleted−7
@@ -1,7 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− foreign import test :: (forall a. a -> a) -> Number
6−
7− test1 = test (\n -> n + 1)
examples/failing/Reserved.pursdeleted−4
@@ -1,4 +0,0 @@
1−module Main where
2−
3−(<) :: Number -> Number -> Number
4−(<) a b = !(a >= b)
examples/failing/SkolemEscape.pursdeleted−5
@@ -1,5 +0,0 @@
1−module Main where
2−
3− foreign import foo :: (forall a. a -> a) -> Number
4−
5− test = \x -> foo x
examples/failing/SkolemEscape2.pursdeleted−9
@@ -1,9 +0,0 @@
1−module Main where
2−
3−import Prelude
4−import Control.Monad.Eff
5−import Control.Monad.ST
6−
7−test _ = do
8− r <- runST (newSTRef 0)
9− return 0
examples/failing/Superclasses1.pursdeleted−11
@@ -1,11 +0,0 @@
1−module Main where
2−
3−class Su a where
4− su :: a -> a
5−
6−class (Su a) <= Cl a where
7− cl :: a -> a -> a
8−
9−instance clNumber :: Cl Number where
10− cl n m = n + m
11−
examples/failing/TypeClassInstances.pursdeleted−8
@@ -1,8 +0,0 @@
1−module Main where
2−
3−class A a where
4− a :: a -> String
5− b :: a -> Number
6−
7−instance A String where
8− a s = s
examples/failing/TypeClasses2.pursdeleted−8
@@ -1,8 +0,0 @@
1−module Main where
2−
3−import Prelude ()
4−
5−class Show a where
6− show :: a -> String
7−
8−test = show "testing"
examples/failing/TypeError.pursdeleted−5
@@ -1,5 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− test = 1 ++ "A"
examples/failing/TypeSynonyms.pursdeleted−5
@@ -1,5 +0,0 @@
1−module Main where
2−
3−type T1 = [T2]
4−
5−type T2 = T1
examples/failing/TypeSynonyms2.pursdeleted−9
@@ -1,9 +0,0 @@
1−module Main where
2−
3−class Foo a where
4− foo :: a -> String
5−
6−type Bar = String
7−
8−instance Foo Bar where
9− foo s = s
examples/failing/TypeSynonyms3.pursdeleted−9
@@ -1,9 +0,0 @@
1−module Main where
2−
3−class Foo a where
4− foo :: a -> String
5−
6−type Bar = String
7−
8−instance Foo Bar where
9− foo s = s
examples/failing/UnknownType.pursdeleted−4
@@ -1,4 +0,0 @@
1−module Main where
2−
3−test :: Number -> Something
4−test = {}
examples/failing/UnknownValue.pursdeleted−25
@@ -1,25 +0,0 @@
1−module Main where
2−
3−import Prelude
4−import Control.Monad.Eff
5−import Control.Monad.ST
6−import Debug.Trace
7−
8−test = runSTArray (do
9− a <- newSTArray 2 0
10− pokeSTArray a 0 1
11− pokeSTArray a 1 2
12− return a)
13−
14−fromTo lo hi = runSTArray (do
15− arr <- newSTArray (hi - lo + 1) 0
16− (let
17− go lo hi _ arr | lo > hi = return arr
18− go lo hi i arr = do
19− pokeSTArray arrr i lo
20− go (lo + 1) hi (i + 1) arr
21− in go lo hi 0 arr))
22−
23−main = do
24− let t1 = runPure (fromTo 10 20)
25− trace "Done"
examples/manual/failing/ArgLengthMismatch.pursdeleted−4
@@ -1,4 +0,0 @@
1−module ArgLengthMismatch where
2−
3− f x y = true
4− f = false
examples/manual/failing/ExportExplicit.pursdeleted−5
@@ -1,5 +0,0 @@
1−-- should fail as z does not exist in the module
2−module M1 (x, y, z) where
3−
4− x = 1
5− y = 2
examples/manual/failing/ExportExplicit1.pursdeleted−14
@@ -1,14 +0,0 @@
1−module M1 (X(X)) where
2−
3− data X = X | Y
4−
5−module Main where
6−
7− import M1
8−
9− testX = X
10−
11− -- should fail as Y constructor is not exported from M1
12− testY = Y
13−
14− main = Debug.Trace.trace "Done"
examples/manual/failing/ExportExplicit2.pursdeleted−5
@@ -1,5 +0,0 @@
1−-- should fail as Y is not a data constructor for X
2−module M1 (X(Y)) where
3−
4− data X = X
5− data Y = Y
examples/manual/failing/ExportExplicit3.pursdeleted−13
@@ -1,13 +0,0 @@
1−module M1 (X(..)) where
2−
3− data X = X | Y
4− data Z = Z
5−
6−module Main where
7−
8− import M1
9−
10− -- should fail as Z is not exported from M1
11− testZ = M1.Z
12−
13− main = Debug.Trace.trace "Done"
examples/manual/failing/ImportExplicit.pursdeleted−7
@@ -1,7 +0,0 @@
1−module M1 where
2−
3− foo = "foo"
4−
5−module Main where
6−
7− import M1 (X(..))
examples/manual/failing/ImportExplicit2.pursdeleted−7
@@ -1,7 +0,0 @@
1−module M1 where
2−
3− data X = Y
4−
5−module Main where
6−
7− import M1 (X(Z, Q))
examples/manual/failing/ImportModule.pursdeleted−7
@@ -1,7 +0,0 @@
1−module M2 where
2−
3− data X = X
4−
5−module Main where
6−
7− import M1
examples/manual/failing/OrphanTypeDecl.pursdeleted−3
@@ -1,3 +0,0 @@
1−module OrphanTypeDecl where
2−
3− fn :: Number -> Boolean
examples/manual/failing/RedefinedFixity.pursdeleted−6
@@ -1,6 +0,0 @@
1−module RedefinedFixity where
2−
3− (!?) x y = x + y
4−
5− infix 2 !?
6− infix 2 !?
examples/manual/failing/RequiredHiddenType.pursdeleted−8
@@ -1,8 +0,0 @@
1−-- exporting `a` should fail as `A` is hidden
2−module Foo (B(..), a, b) where
3−
4− data A = A
5− data B = B
6−
7− a = A
8− b = B
examples/manual/passing/ExportExplicit.pursdeleted−20
@@ -1,20 +0,0 @@
1−module M1 (X(X), Z(..), foo) where
2−
3− data X = X | Y
4− data Z = Z
5−
6− foo :: Number
7− foo = 0
8−
9− bar :: Number
10− bar = 1
11−
12−module Main where
13−
14− import M1
15−
16− testX = X
17− testZ = Z
18− testFoo = foo
19−
20− main = Debug.Trace.trace "Done"
examples/manual/passing/ExportExplicit2.pursdeleted−15
@@ -1,15 +0,0 @@
1−module M1 (bar) where
2−
3− foo :: Number
4− foo = 0
5−
6− bar :: Number
7− bar = foo
8−
9−module Main where
10−
11− import M1
12−
13− testBar = bar
14−
15− main = Debug.Trace.trace "Done"
examples/manual/passing/Import.pursdeleted−19
@@ -1,19 +0,0 @@
1−module M1 where
2−
3− import Prelude ()
4−
5− id :: forall a. a -> a
6− id = \x -> x
7−
8− foo = id
9−
10−module M2 where
11−
12− import Prelude ()
13− import M1
14−
15− main = \_ -> foo 42
16−
17−module Main where
18−
19−main = Debug.Trace.trace "Done"
examples/manual/passing/ImportExplicit.pursdeleted−14
@@ -1,14 +0,0 @@
1−module M1 where
2−
3− data X = X | Y
4− data Z = Z
5−
6−module Main where
7−
8− import M1 (X(..))
9−
10− testX :: X
11− testX = X
12− testY = Y
13−
14− main = Debug.Trace.trace "Done"
examples/manual/passing/ImportQualified.pursdeleted−12
@@ -1,12 +0,0 @@
1−module M1 where
2−
3− trace x = x
4−
5−module Main where
6−
7− import Prelude
8− import Control.Monad.Eff
9− import M1
10− import qualified Debug.Trace as T
11−
12− main = T.trace (trace "Done")
examples/manual/passing/Module.pursdeleted−28
@@ -1,28 +0,0 @@
1−module M1 where
2−
3− import Prelude
4−
5− data Foo = Foo String
6−
7− foo :: M1.Foo -> String
8− foo = \f -> case f of Foo s -> s ++ "foo"
9−
10− bar :: Foo -> String
11− bar = foo
12−
13− incr :: Number -> Number
14− incr x = x + 1
15−
16−module M2 where
17−
18− import Prelude
19−
20− baz :: M1.Foo -> String
21− baz = M1.foo
22−
23− match :: M1.Foo -> String
24− match = \f -> case f of M1.Foo s -> s ++ "foo"
25−
26−module Main where
27−
28−main = Debug.Trace.trace "Done"
examples/manual/passing/ModuleDeps.pursdeleted−17
@@ -1,17 +0,0 @@
1−module M1 where
2−
3−import M2
4−
5−foo = M3.baz
6−
7−module M2 where
8−
9−bar = M3.baz
10−
11−module M3 where
12−
13−baz = 1
14−
15−module Main where
16−
17−main = Debug.Trace.trace "Done"
examples/manual/passing/RedefinedFixity.pursdeleted−24
@@ -1,24 +0,0 @@
1−module M1 where
2−
3−import Prelude ()
4−
5−($) f a = f a
6−
7−infixr 1000 $
8−
9−module M2 where
10−
11−import Prelude ()
12−
13−import M1
14−
15−module M3 where
16−
17−import Prelude ()
18−
19−import M1
20−import M2
21−
22−module Main where
23−
24−main = Debug.Trace.trace "Done"
examples/passing/Applicative.pursdeleted−16
@@ -1,16 +0,0 @@
1−module Main where
2−
3−import Prelude ()
4−
5−class Applicative f where
6− pure :: forall a. a -> f a
7− (<*>) :: forall a b. f (a -> b) -> f a -> f b
8−
9−data Maybe a = Nothing | Just a
10−
11−instance applicativeMaybe :: Applicative Maybe where
12− pure = Just
13− (<*>) (Just f) (Just a) = Just (f a)
14− (<*>) _ _ = Nothing
15−
16−main = Debug.Trace.trace "Done"
examples/passing/ArrayType.pursdeleted−9
@@ -1,9 +0,0 @@
1−module Main where
2−
3−class Pointed p where
4− point :: forall a. a -> p a
5−
6−instance pointedArray :: Pointed [] where
7− point a = [a]
8−
9−main = Debug.Trace.trace "Done"
examples/passing/Arrays.pursdeleted−24
@@ -1,24 +0,0 @@
1−module Main where
2−
3−import Prelude
4−
5−test1 arr = arr !! 0 + arr !! 1 + 1
6−
7−test2 = \arr -> case arr of
8− [x, y] -> x + y
9− [x] -> x
10− [] -> 0
11− (x : y : _) -> x + y
12−
13−data Tree = One Number | Some [Tree]
14−
15−test3 = \tree sum -> case tree of
16− One n -> n
17− Some (n1 : n2 : rest) -> test3 n1 sum * 10 + test3 n2 sum * 5 + sum rest
18−
19−test4 = \arr -> case arr of
20− [] -> 0
21− [_] -> 0
22− x : y : xs -> x * y + test4 xs
23−
24−main = Debug.Trace.trace "Done"
examples/passing/Auto.pursdeleted−13
@@ -1,13 +0,0 @@
1−module Main where
2−
3− data Auto s i o = Auto { state :: s, step :: s -> i -> o }
4−
5− type SomeAuto i o = forall r. (forall s. Auto s i o -> r) -> r
6−
7− exists :: forall s i o. s -> (s -> i -> o) -> SomeAuto i o
8− exists = \state step f -> f (Auto { state: state, step: step })
9−
10− run :: forall i o. SomeAuto i o -> i -> o
11− run = \s i -> s (\a -> case a of Auto a -> a.step a.state i)
12−
13− main = Debug.Trace.trace "Done"
examples/passing/AutoPrelude.pursdeleted−8
@@ -1,8 +0,0 @@
1−module Main where
2−
3−import Debug.Trace
4−
5−f x = x * 10
6−g y = y - 10
7−
8−main = trace $ show $ (f <<< g) 100
examples/passing/AutoPrelude2.pursdeleted−9
@@ -1,9 +0,0 @@
1−module Main where
2−
3−import qualified Prelude as P
4−import Debug.Trace
5−
6−f :: forall a. a -> a
7−f = P.id
8−
9−main = P.($) trace ((f P.<<< f) "Done")
examples/passing/BindersInFunctions.pursdeleted−16
@@ -1,16 +0,0 @@
1−module Main where
2−
3−import Prelude
4−
5−tail = \(_:xs) -> xs
6−
7−foreign import error
8− "function error(msg) {\
9− \ throw msg;\
10− \}" :: forall a. String -> a
11−
12−main =
13− let ts = tail [1, 2, 3] in
14− if ts == [2, 3]
15− then Debug.Trace.trace "Done"
16− else error "Incorrect result from 'tails'."
examples/passing/CheckSynonymBug.pursdeleted−14
@@ -1,14 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− type Foo a = [a]
6−
7− foreign import length
8− "function length(a) {\
9− \ return a.length;\
10− \}" :: forall a. [a] -> Number
11−
12− foo _ = length ([] :: Foo Number)
13−
14− main = Debug.Trace.trace "Done"
examples/passing/Church.pursdeleted−18
@@ -1,18 +0,0 @@
1−module Main where
2−
3− import Prelude ()
4−
5− type List a = forall r. r -> (a -> r -> r) -> r
6−
7− empty :: forall a. List a
8− empty = \r f -> r
9−
10− cons :: forall a. a -> List a -> List a
11− cons = \a l r f -> f a (l r f)
12−
13− append :: forall a. List a -> List a -> List a
14− append = \l1 l2 r f -> l2 (l1 r f) f
15−
16− test = append (cons 1 empty) (cons 2 empty)
17−
18− main = Debug.Trace.trace "Done"
examples/passing/Collatz.pursdeleted−18
@@ -1,18 +0,0 @@
1−module Main where
2−
3−import Prelude
4−import Control.Monad.Eff
5−import Control.Monad.ST
6−
7−collatz :: Number -> Number
8−collatz n = runPure (runST (do
9− r <- newSTRef n
10− count <- newSTRef 0
11− untilE $ do
12− modifySTRef count $ (+) 1
13− m <- readSTRef r
14− writeSTRef r $ if m % 2 == 0 then m / 2 else 3 * m + 1
15− return $ m == 1
16− readSTRef count))
17−
18−main = Debug.Trace.print $ collatz 1000
examples/passing/Conditional.pursdeleted−9
@@ -1,9 +0,0 @@
1−module Main where
2−
3− import Prelude ()
4−
5− fns = \f -> if f true then f else \x -> x
6−
7− not = \x -> if x then false else true
8−
9− main = Debug.Trace.trace "Done"
examples/passing/Console.pursdeleted−13
@@ -1,13 +0,0 @@
1−module Main where
2−
3−import Prelude
4−import Control.Monad.Eff
5−import Debug.Trace
6−
7−replicateM_ :: forall m a. (Monad m) => Number -> m a -> m {}
8−replicateM_ 0 _ = return {}
9−replicateM_ n act = do
10− act
11− replicateM_ (n - 1) act
12−
13−main = replicateM_ 10 (trace "Hello World!")
examples/passing/DataAndType.pursdeleted−7
@@ -1,7 +0,0 @@
1−module Main where
2−
3−data A = A B
4−
5−type B = A
6−
7−main = Debug.Trace.trace "Done"
examples/passing/Do.pursdeleted−64
@@ -1,64 +0,0 @@
1−module Main where
2−
3−import Prelude
4−
5−data Maybe a = Nothing | Just a
6−
7−instance functorMaybe :: Functor Maybe where
8− (<$>) f Nothing = Nothing
9− (<$>) f (Just x) = Just (f x)
10−
11−instance applicativeMaybe :: Applicative Maybe where
12− pure = Just
13− (<*>) (Just f) (Just x) = Just (f x)
14− (<*>) _ _ = Nothing
15−
16−instance monadMaybe :: Prelude.Monad Maybe where
17− return = Just
18− (>>=) Nothing _ = Nothing
19− (>>=) (Just a) f = f a
20−
21−test1 = \_ -> do
22− Just "abc"
23−
24−test2 = \_ -> do
25− (x : _) <- Just [1, 2, 3]
26− (y : _) <- Just [4, 5, 6]
27− Just (x + y)
28−
29−test3 = \_ -> do
30− Just 1
31− Nothing :: Maybe Number
32− Just 2
33−
34−test4 mx my = do
35− x <- mx
36− y <- my
37− Just (x + y + 1)
38−
39−test5 mx my mz = do
40− x <- mx
41− y <- my
42− let sum = x + y
43− z <- mz
44− Just (z + sum + 1)
45−
46−test6 mx = \_ -> do
47− let
48− f :: forall a. Maybe a -> a
49− f (Just x) = x
50− Just (f mx)
51−
52−test8 = \_ -> do
53− Just (do
54− Just 1)
55−
56−test9 = \_ -> (+) <$> Just 1 <*> Just 2
57−
58−test10 _ = do
59− let
60− f x = g x * 3
61− g x = f x / 2
62− Just (f 10)
63−
64−main = Debug.Trace.trace "Done"
examples/passing/Dollar.pursdeleted−16
@@ -1,16 +0,0 @@
1−module Main where
2−
3−import Prelude ()
4−
5−($) :: forall a b. (a -> b) -> a -> b
6−($) f x = f x
7−
8−infixr 1000 $
9−
10−id x = x
11−
12−test1 x = id $ id $ id $ id $ x
13−
14−test2 x = id id $ id x
15−
16−main = Debug.Trace.trace "Done"
examples/passing/Eff.pursdeleted−19
@@ -1,19 +0,0 @@
1−module Main where
2−
3−import Prelude
4−import Control.Monad.Eff
5−import Control.Monad.ST
6−import Debug.Trace
7−
8−test1 = do
9− trace "Line 1"
10− trace "Line 2"
11−
12−test2 = runPure (runST (do
13− ref <- newSTRef 0
14− modifySTRef ref $ \n -> n + 1
15− readSTRef ref))
16−
17−main = do
18− test1
19− Debug.Trace.print test2
examples/passing/EmptyDataDecls.pursdeleted−30
@@ -1,30 +0,0 @@
1−module Main where
2−
3−import Prelude
4−
5−data Z
6−data S n
7−
8−data Array n a = Array [a]
9−
10−nil :: forall a. Array Z a
11−nil = Array []
12−
13−foreign import concat
14− "function concat(l1) {\
15− \ return function (l2) {\
16− \ return l1.concat(l2);\
17− \ };\
18− \}" :: forall a. [a] -> [a] -> [a]
19−
20−cons :: forall a n. a -> Array n a -> Array (S n) a
21−cons x (Array xs) = Array $ concat [x] xs
22−
23−foreign import error
24− "function error(msg) {\
25− \ throw msg;\
26− \}" :: forall a. String -> a
27−
28−main = case cons 1 $ cons 2 $ cons 3 nil of
29− Array [1, 2, 3] -> Debug.Trace.trace "Done"
30− _ -> error "Failed"
examples/passing/EmptyTypeClass.pursdeleted−12
@@ -1,12 +0,0 @@
1−module Main where
2−
3−import Prelude
4−
5−class Partial
6−
7−head :: forall a. (Partial) => [a] -> a
8−head (x:xs) = x
9−
10−instance allowPartials :: Partial
11−
12−main = Debug.Trace.trace $ head ["Done"]
examples/passing/ExternData.pursdeleted−13
@@ -1,13 +0,0 @@
1−module Main where
2−
3− foreign import data IO :: * -> *
4−
5− foreign import bind "function bind() {}" :: forall a b. IO a -> (a -> IO b) -> IO b
6−
7− foreign import showMessage "function showMessage() {}" :: String -> IO { }
8−
9− foreign import prompt "function prompt() {}" :: IO String
10−
11− test _ = prompt `bind` \s -> showMessage s
12−
13− main = Debug.Trace.trace "Done"
examples/passing/ExternRaw.pursdeleted−13
@@ -1,13 +0,0 @@
1−module Main where
2−
3−foreign import first "function first(xs) { return xs[0]; }" :: forall a. [a] -> a
4−
5−foreign import loop "function loop() { while (true) {} }" :: forall a. a
6−
7−foreign import concat "function concat(xs) { \
8− \ return function(ys) { \
9− \ return xs.concat(ys); \
10− \ };\
11− \}" :: forall a. [a] -> [a] -> [a]
12−
13−main = Debug.Trace.trace "Done"
examples/passing/FFI.pursdeleted−11
@@ -1,11 +0,0 @@
1−module Main where
2−
3−foreign import foo
4− "function foo(s) {\
5− \ return s;\
6− \}" :: String -> String
7−
8−bar :: String -> String
9−bar _ = foo "test"
10−
11−main = Debug.Trace.trace "Done"
examples/passing/Fib.pursdeleted−15
@@ -1,15 +0,0 @@
1−module Main where
2−
3−import Prelude
4−import Control.Monad.Eff
5−import Control.Monad.ST
6−
7−main = runST (do
8− n1 <- newSTRef 1
9− n2 <- newSTRef 1
10− whileE ((>) 1000 <$> readSTRef n1) $ do
11− n1' <- readSTRef n1
12− n2' <- readSTRef n2
13− writeSTRef n2 $ n1' + n2'
14− writeSTRef n1 n2'
15− Debug.Trace.print n2')
examples/passing/FinalTagless.pursdeleted−22
@@ -1,22 +0,0 @@
1−module Main where
2−
3−import Prelude
4−
5−class E e where
6− num :: Number -> e Number
7− add :: e Number -> e Number -> e Number
8−
9−type Expr a = forall e. (E e) => e a
10−
11−data Id a = Id a
12−
13−instance exprId :: E Id where
14− num = Id
15− add (Id n) (Id m) = Id (n + m)
16−
17−runId (Id a) = a
18−
19−three :: Expr Number
20−three = add (num 1) (num 2)
21−
22−main = Debug.Trace.print $ runId three
examples/passing/ForeignInstance.pursdeleted−16
@@ -1,16 +0,0 @@
1−module Main where
2−
3−class Foo a where
4− foo :: a -> String
5−
6−foreign import instance fooArray :: (Foo a) => Foo [a]
7−
8−foreign import instance fooNumber :: Foo Number
9−
10−foreign import instance fooString :: Foo String
11−
12−test1 _ = foo [1, 2, 3]
13−
14−test2 _ = foo "Test"
15−
16−main = Debug.Trace.trace "Done"
examples/passing/FunctionScope.pursdeleted−17
@@ -1,17 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− mkValue :: Number -> Number
6− mkValue id = id
7−
8− foreign import error
9− "function error(msg) {\
10− \ throw msg;\
11− \}" :: forall a. String -> a
12−
13− main = do
14− let value = mkValue 1
15− if value == 1
16− then Debug.Trace.trace "Done"
17− else error "Not done"
examples/passing/Functions.pursdeleted−15
@@ -1,15 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− test1 = \_ -> 0
6−
7− test2 = \a b -> a + b + 1
8−
9− test3 = \a -> a
10−
11− test4 = \(%%) -> 1 %% 2
12−
13− test5 = \(+++) (***) -> 1 +++ 2 *** 3
14−
15− main = Debug.Trace.trace "Done"
examples/passing/Functions2.pursdeleted−17
@@ -1,17 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− test :: forall a b. a -> b -> a
6− test = \const _ -> const
7−
8− foreign import error
9− "function error(msg) {\
10− \ throw msg;\
11− \}" :: forall a. String -> a
12−
13− main = do
14− let value = test "Done" {}
15− if value == "Done"
16− then Debug.Trace.trace "Done"
17− else error "Not done"
examples/passing/Guards.pursdeleted−14
@@ -1,14 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− collatz = \x -> case x of
6− y | y % 2 == 0 -> y / 2
7− y -> y * 3 + 1
8−
9− -- Guards have access to current scope
10− collatz2 = \x y -> case x of
11− z | y > 0 -> z / 2
12− z -> z * 3 + 1
13−
14− main = Debug.Trace.trace "Done"
examples/passing/InferRecFunWithConstrainedArgument.pursdeleted−8
@@ -1,8 +0,0 @@
1−module Main where
2−
3−import Prelude
4−
5−test 100 = 100
6−test n = test(1 + n)
7−
8−main = Debug.Trace.print $ test 0
examples/passing/JSReserved.pursdeleted−12
@@ -1,12 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− yield = 0
6− member = 1
7−
8− public = \return -> return
9−
10− this catch = catch
11−
12− main = Debug.Trace.trace "Done"
examples/passing/Let.pursdeleted−64
@@ -1,64 +0,0 @@
1−module Main where
2−
3−import Prelude
4−import Control.Monad.Eff
5−import Control.Monad.ST
6−
7−test1 x = let
8− y :: Number
9− y = x + 1
10− in y
11−
12−test2 x y =
13− let x' = x + 1 in
14− let y' = y + 1 in
15− x' + y'
16−
17−test3 = let f x y z = x + y + z in
18− f 1 2 3
19−
20−test4 = let f x [y, z] = x y z in
21− f (+) [1, 2]
22−
23−test5 = let
24− f x | x > 0 = g (x / 2) + 1
25− f x = 0
26− g x = f (x - 1) + 1
27− in f 10
28−
29−test6 = runPure (runST (do
30− r <- newSTRef 0
31− (let
32− go [] = readSTRef r
33− go (n : ns) = do
34− modifySTRef r ((+) n)
35− go ns
36− in go [1, 2, 3, 4, 5])
37− ))
38−
39−test7 = let
40− f :: forall a. a -> a
41− f x = x
42− in if f true then f 1 else f 2
43−
44−test8 :: Number -> Number
45−test8 x = let
46− go y | (x - 0.1 < y * y) && (y * y < x + 0.1) = y
47− go y = go $ (y + x / y) / 2
48− in go x
49−
50−test10 _ =
51− let
52− f x = g x * 3
53− g x = f x / 2
54− in f 10
55−
56−main = do
57− Debug.Trace.print (test1 1)
58− Debug.Trace.print (test2 1 2)
59− Debug.Trace.print test3
60− Debug.Trace.print test4
61− Debug.Trace.print test5
62− Debug.Trace.print test6
63− Debug.Trace.print test7
64− Debug.Trace.print (test8 100)
examples/passing/LetInInstance.pursdeleted−12
@@ -1,12 +0,0 @@
1−module Main where
2−
3−class Foo a where
4− foo :: a -> String
5−
6−instance fooString :: Foo String where
7− foo = go
8− where
9− go :: String -> String
10− go s = s
11−
12−main = Debug.Trace.trace "Done"
examples/passing/LiberalTypeSynonyms.pursdeleted−19
@@ -1,19 +0,0 @@
1−module Main where
2−
3−type Reader = (->) String
4−
5−foo :: Reader String
6−foo s = s
7−
8−type AndFoo r = (foo :: String | r)
9−
10−getFoo :: forall r. Prim.Object (AndFoo r) -> String
11−getFoo o = o.foo
12−
13−type F r = { | r } -> { | r }
14−
15−f :: (forall r. F r) -> String
16−f g = case g { x: "Hello" } of
17− { x = x } -> x
18−
19−main = Debug.Trace.trace "Done"
examples/passing/MPTCs.pursdeleted−20
@@ -1,20 +0,0 @@
1−module Main where
2−
3−import Prelude
4−
5−class NullaryTypeClass where
6− greeting :: String
7−
8−instance nullaryTypeClass :: NullaryTypeClass where
9− greeting = "Hello, World!"
10−
11−class Coerce a b where
12− coerce :: a -> b
13−
14−instance coerceRefl :: Coerce a a where
15− coerce a = a
16−
17−instance coerceShow :: (Prelude.Show a) => Coerce a String where
18− coerce = show
19−
20−main = Debug.Trace.trace "Done"
examples/passing/Match.pursdeleted−7
@@ -1,7 +0,0 @@
1−module Main where
2−
3− data Foo a = Foo
4−
5− foo = \f -> case f of Foo -> "foo"
6−
7− main = Debug.Trace.trace "Done"
examples/passing/Monad.pursdeleted−32
@@ -1,32 +0,0 @@
1−module Main where
2−
3− import Prelude ()
4−
5− type Monad m = { return :: forall a. a -> m a
6− , bind :: forall a b. m a -> (a -> m b) -> m b }
7−
8− data Id a = Id a
9−
10− id :: Monad Id
11− id = { return : Id
12− , bind : \ma f -> case ma of Id a -> f a }
13−
14− data Maybe a = Nothing | Just a
15−
16− maybe :: Monad Maybe
17− maybe = { return : Just
18− , bind : \ma f -> case ma of
19− Nothing -> Nothing
20− Just a -> f a
21− }
22−
23− test :: forall m. Monad m -> m Number
24− test = \m -> m.bind (m.return 1) (\n1 ->
25− m.bind (m.return "Test") (\n2 ->
26− m.return n1))
27−
28− test1 = test id
29−
30− test2 = test maybe
31−
32− main = Debug.Trace.trace "Done"
examples/passing/MonadState.pursdeleted−38
@@ -1,38 +0,0 @@
1−module Main where
2−
3−import Prelude
4−
5−data Tuple a b = Tuple a b
6−
7−class MonadState s m where
8− get :: m s
9− put :: s -> m {}
10−
11−data State s a = State (s -> Tuple s a)
12−
13−runState s (State f) = f s
14−
15−instance monadState :: Prelude.Monad (State s) where
16− return a = State $ \s -> Tuple s a
17− (>>=) f g = State $ \s -> case runState s f of
18− Tuple s1 a -> runState s1 (g a)
19−
20−instance monadStateState :: MonadState s (State s) where
21− get = State (\s -> Tuple s s)
22− put s = State (\_ -> Tuple s {})
23−
24−modify :: forall m s. (Prelude.Monad m, MonadState s m) => (s -> s) -> m {}
25−modify f = do
26− s <- get
27− put (f s)
28−
29−test :: Tuple String String
30−test = runState "" $ do
31− modify $ (++) "World!"
32− modify $ (++) "Hello, "
33− get
34−
35−main = do
36− let t1 = test
37− Debug.Trace.trace "Done"
38−
examples/passing/MultipleConstructorArgs.pursdeleted−21
@@ -1,21 +0,0 @@
1−module Main where
2−
3−import Prelude
4−import Control.Monad.Eff
5−
6−data P a b = P a b
7−
8−runP :: forall a b r. (a -> b -> r) -> P a b -> r
9−runP f (P a b) = f a b
10−
11−idP = runP P
12−
13−testCase = \p -> case p of
14− P (x:xs) (y:ys) -> x + y
15− P _ _ -> 0
16−
17−test1 = testCase (P [1, 2, 3] [4, 5, 6])
18−
19−main = do
20− Debug.Trace.trace (runP (\s n -> s ++ show n) (P "Test" 1))
21− Debug.Trace.print test1
examples/passing/MutRec.pursdeleted−19
@@ -1,19 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− f 0 = 0
6− f x = g x + 1
7−
8− g x = f (x / 2)
9−
10− data Even = Zero | Even Odd
11−
12− data Odd = Odd Even
13−
14− evenToNumber Zero = 0
15− evenToNumber (Even n) = oddToNumber n + 1
16−
17− oddToNumber (Odd n) = evenToNumber n + 1
18−
19− main = Debug.Trace.trace "Done"
examples/passing/NamedPatterns.pursdeleted−7
@@ -1,7 +0,0 @@
1−module Main where
2−
3− foo = \x -> case x of
4− y@{ foo = "Foo" } -> y
5− y -> y
6−
7− main = Debug.Trace.trace "Done"
examples/passing/Nested.pursdeleted−7
@@ -1,7 +0,0 @@
1−module Main where
2−
3− data Extend r a = Extend { prev :: r a, next :: a }
4−
5− data Matrix r a = Square (r (r a)) | Bigger (Matrix (Extend r) a)
6−
7− main = Debug.Trace.trace "Done"
examples/passing/NestedTypeSynonyms.pursdeleted−11
@@ -1,11 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− type X = String
6− type Y = X -> X
7−
8− fn :: Y
9− fn a = a
10−
11− main = Debug.Trace.print (fn "Done")
examples/passing/ObjectSynonym.pursdeleted−13
@@ -1,13 +0,0 @@
1−module Main where
2−
3−type Inner = Number
4−
5−inner :: Inner
6−inner = 0
7−
8−type Outer = { inner :: Inner }
9−
10−outer :: Outer
11−outer = { inner: inner }
12−
13−main = Debug.Trace.trace "Done"
examples/passing/ObjectUpdate.pursdeleted−18
@@ -1,18 +0,0 @@
1−module Main where
2−
3− update1 = \o -> o { foo = "Foo" }
4−
5− update2 :: forall r. { foo :: String | r } -> { foo :: String | r }
6− update2 = \o -> o { foo = "Foo" }
7−
8− replace = \o -> case o of
9− { foo = "Foo" } -> o { foo = "Bar" }
10− { foo = "Bar" } -> o { bar = "Baz" }
11− o -> o
12−
13− polyUpdate :: forall a r. { foo :: a | r } -> { foo :: String | r }
14− polyUpdate = \o -> o { foo = "Foo" }
15−
16− inferPolyUpdate = \o -> o { foo = "Foo" }
17−
18− main = Debug.Trace.trace ((update1 {foo: ""}).foo)
examples/passing/Objects.pursdeleted−30
@@ -1,30 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− test = \x -> x.foo + x.bar + 1
6−
7− append = \o -> { foo: o.foo, bar: 1 }
8−
9− apTest = append({foo : "Foo", baz: "Baz"})
10−
11− f = (\a -> a.b.c) { b: { c: 1, d: "Hello" }, e: "World" }
12−
13− g = (\a -> a.f { x: 1, y: "y" }) { f: \o -> o.x + 1 }
14−
15− typed :: { foo :: Number }
16− typed = { foo: 0 }
17−
18− test2 = \x -> x."!@#"
19−
20− test3 = typed."foo"
21−
22− test4 = test2 weirdObj
23− where
24− weirdObj :: { "!@#" :: Number }
25− weirdObj = { "!@#": 1 }
26−
27− test5 = case { "***": 1 } of
28− { "***" = n } -> n
29−
30− main = Debug.Trace.trace "Done"
examples/passing/OneConstructor.pursdeleted−7
@@ -1,7 +0,0 @@
1−module Main where
2−
3−data One a = One a
4−
5−one (One a) = a
6−
7−main = Debug.Trace.trace "Done"
examples/passing/Operators.pursdeleted−77
@@ -1,77 +0,0 @@
1−module Main where
2−
3− import Control.Monad.Eff
4− import Debug.Trace
5−
6− bar :: String -> String -> String
7− bar = \s1 s2 -> s1 ++ s2
8−
9− test1 :: forall n. (Num n) => n -> n -> (n -> n -> n) -> n
10− test1 x y z = x * y + z x y
11−
12− test2 = (\x -> x.foo false) { foo : \_ -> 1 }
13−
14− test3 = (\x y -> x)(1 + 2 * (1 + 2)) (true && (false || false))
15−
16− k = \x -> \y -> x
17−
18− test4 = 1 `k` 2
19−
20− infixl 5 %%
21−
22− (%%) :: Number -> Number -> Number
23− (%%) x y = x * y + y
24−
25− test5 = 1 %% 2 %% 3
26−
27− test6 = ((\x -> x) `k` 2) 3
28−
29− (<>) :: String -> String -> String
30− (<>) = \s1 s2 -> s1 ++ s2
31−
32− test7 = "Hello" <> "World!"
33−
34− (@@) :: forall a b. (a -> b) -> a -> b
35− (@@) = \f x -> f x
36−
37− foo :: String -> String
38− foo = \s -> s
39−
40− test8 = foo @@ "Hello World"
41−
42− test9 = Main.foo @@ "Hello World"
43−
44− test10 = "Hello" `Main.bar` "World"
45−
46− (...) :: forall a. [a] -> [a] -> [a]
47− (...) = \as -> \bs -> as
48−
49− test11 = [1, 2, 3] ... [4, 5, 6]
50−
51− test12 (<%>) a b = a <%> b
52−
53− test13 = \(<%>) a b -> a <%> b
54−
55− test14 :: Number -> Number -> Boolean
56− test14 a b = a < b
57−
58− test15 :: Number -> Number -> Boolean
59− test15 a b = const false $ a `test14` b
60−
61− main = do
62− let t1 = test1 1 2 (\x y -> x + y)
63− let t2 = test2
64− let t3 = test3
65− let t4 = test4
66− let t5 = test5
67− let t6 = test6
68− let t7 = test7
69− let t8 = test8
70− let t9 = test9
71− let t10 = test10
72− let t11 = test11
73− let t12 = test12 k 1 2
74− let t13 = test13 k 1 2
75− let t14 = test14 1 2
76− let t15 = test15 1 2
77− trace "Done"
examples/passing/OptimizerBug.pursdeleted−9
@@ -1,9 +0,0 @@
1−module Main where
2−
3−import Prelude
4−
5−x a = 1 + y a
6−
7−y a = x a
8−
9−main = Debug.Trace.trace "Done"
examples/passing/Patterns.pursdeleted−28
@@ -1,28 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− test = \x -> case x of
6− { str = "Foo", bool = true } -> true
7− { str = "Bar", bool = b } -> b
8− _ -> false
9−
10− f = \o -> case o of
11− { foo = "Foo" } -> o.bar
12− _ -> 0
13−
14− g = \o -> case o of
15− { arr = [x : xs], take = "car" } -> x
16− { arr = [_, x : xs], take = "cadr" } -> x
17− _ -> 0
18−
19−
20− h = \o -> case o of
21− a@[_,_,_] -> a
22− _ -> []
23−
24− isDesc :: [Number] -> Boolean
25− isDesc [x, y] | x > y = true
26− isDesc _ = false
27−
28− main = Debug.Trace.trace "Done"
examples/passing/Person.pursdeleted−16
@@ -1,16 +0,0 @@
1−module Main where
2−
3− import Prelude ((++))
4−
5− data Person = Person { name :: String, age :: Number }
6−
7− foreign import itoa
8− "function itoa(n) {\
9− \ return n.toString();\
10− \}" :: Number -> String
11−
12− showPerson :: Person -> String
13− showPerson = \p -> case p of
14− Person o -> o.name ++ ", aged " ++ itoa(o.age)
15−
16− main = Debug.Trace.trace "Done"
examples/passing/Rank2Data.pursdeleted−29
@@ -1,29 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− data Id = Id forall a. a -> a
6−
7− runId = \id a -> case id of
8− Id f -> f a
9−
10− data Nat = Nat forall r. r -> (r -> r) -> r
11−
12− runNat = \nat -> case nat of
13− Nat f -> f 0 (\n -> n + 1)
14−
15− zero = Nat (\zero _ -> zero)
16−
17− succ = \n -> case n of
18− Nat f -> Nat (\zero succ -> succ (f zero succ))
19−
20− add = \n m -> case n of
21− Nat f -> case m of
22− Nat g -> Nat (\zero succ -> g (f zero succ) succ)
23−
24− one = succ zero
25− two = succ zero
26− four = add two two
27− fourNumber = runNat four
28−
29− main = Debug.Trace.trace "Done"
examples/passing/Rank2Types.pursdeleted−11
@@ -1,11 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− test1 :: (forall a. (a -> a)) -> Number
6− test1 = \f -> f 0
7−
8− forever :: forall m a b. (forall a b. m a -> (a -> m b) -> m b) -> m a -> m b
9− forever = \bind action -> bind action $ \_ -> forever bind action
10−
11− main = Debug.Trace.trace "Done"
examples/passing/Recursion.pursdeleted−10
@@ -1,10 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− fib = \n -> case n of
6− 0 -> 1
7− 1 -> 1
8− n -> fib (n - 1) + fib (n - 2)
9−
10− main = Debug.Trace.trace "Done"
examples/passing/RuntimeScopeIssue.pursdeleted−19
@@ -1,19 +0,0 @@
1−module Main where
2−
3−import Prelude
4−
5−class A a where
6− a :: a -> Boolean
7−
8−class B a where
9− b :: a -> Boolean
10−
11−instance aNumber :: A Number where
12− a 0 = true
13− a n = b (n - 1)
14−
15−instance bNumber :: B Number where
16− b 0 = false
17− b n = a (n - 1)
18−
19−main = Debug.Trace.print $ a 10
examples/passing/STArray.pursdeleted−25
@@ -1,25 +0,0 @@
1−module Main where
2−
3−import Prelude
4−import Control.Monad.Eff
5−import Control.Monad.ST
6−import Debug.Trace
7−
8−test = runSTArray (do
9− a <- newSTArray 2 0
10− pokeSTArray a 0 1
11− pokeSTArray a 1 2
12− return a)
13−
14−fromTo lo hi = runSTArray (do
15− arr <- newSTArray (hi - lo + 1) 0
16− (let
17− go lo hi _ arr | lo > hi = return arr
18− go lo hi i arr = do
19− pokeSTArray arr i lo
20− go (lo + 1) hi (i + 1) arr
21− in go lo hi 0 arr))
22−
23−main = do
24− let t1 = runPure (fromTo 10 20)
25− trace "Done"
examples/passing/SignedNumericLiterals.pursdeleted−15
@@ -1,15 +0,0 @@
1−module Main where
2−
3− p = 0.5
4− q = 1
5− x = -1
6− y = -0.5
7− z = 0.5
8− w = 1
9−
10− f :: Number -> Number
11− f x = -x
12−
13− test1 = 2 - 1
14−
15− main = Debug.Trace.trace "Done"
examples/passing/Superclasses1.pursdeleted−18
@@ -1,18 +0,0 @@
1−module Main where
2−
3−class Su a where
4− su :: a -> a
5−
6−class (Su a) <= Cl a where
7− cl :: a -> a -> a
8−
9−instance suNumber :: Su Number where
10− su n = n + 1
11−
12−instance clNumber :: Cl Number where
13− cl n m = n + m
14−
15−test :: forall a. (Cl a) => a -> a
16−test a = su (cl a a)
17−
18−main = Debug.Trace.print $ test 10
examples/passing/Superclasses2.pursdeleted−21
@@ -1,21 +0,0 @@
1−module Main where
2−
3−class Su a where
4− su :: a -> a
5−
6−class (Su [a]) <= Cl a where
7− cl :: a -> a -> a
8−
9−instance suNumber :: Su Number where
10− su n = n + 1
11−
12−instance suArray :: (Su a) => Su [a] where
13− su (x : _) = [su x]
14−
15−instance clNumber :: Cl Number where
16− cl n m = n + m
17−
18−test :: forall a. (Cl a) => a -> [a]
19−test x = su [cl x x]
20−
21−main = Debug.Trace.print $ test 10 !! 0
examples/passing/TailCall.pursdeleted−15
@@ -1,15 +0,0 @@
1−module Main where
2−
3−import Prelude
4−
5−test :: Number -> [Number] -> Number
6−test n [] = n
7−test n (x:xs) = test (n + x) xs
8−
9−loop :: forall a. Number -> a
10−loop x = loop (x + 1)
11−
12−notATailCall = \x ->
13− (\notATailCall -> notATailCall x) (\x -> x)
14−
15−main = Debug.Trace.print (test 0 [1, 2, 3])
examples/passing/Tick.pursdeleted−5
@@ -1,5 +0,0 @@
1−module Main where
2−
3−test' x = x
4−
5−main = Debug.Trace.trace "Done"
examples/passing/TopLevelCase.pursdeleted−18
@@ -1,18 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− gcd :: Number -> Number -> Number
6− gcd 0 x = x
7− gcd x 0 = x
8− gcd x y | x > y = gcd (x % y) y
9− gcd x y = gcd (y % x) x
10−
11− guardsTest (x:xs) | x > 0 = guardsTest xs
12− guardsTest xs = xs
13−
14− data A = A
15−
16− parseTest A 0 = 0
17−
18− main = Debug.Trace.trace "Done"
examples/passing/TypeClasses.pursdeleted−59
@@ -1,59 +0,0 @@
1−module Main where
2−
3−import Prelude
4−
5−test1 = \_ -> show "testing"
6−
7−f :: forall a. (Prelude.Show a) => a -> String
8−f x = show x
9−
10−test2 = \_ -> f "testing"
11−
12−test7 :: forall a. (Prelude.Show a) => a -> String
13−test7 = show
14−
15−test8 = \_ -> show $ "testing"
16−
17−data Data a = Data a
18−
19−instance showData :: (Prelude.Show a) => Prelude.Show (Data a) where
20− show (Data a) = "Data (" ++ show a ++ ")"
21−
22−test3 = \_ -> show (Data "testing")
23−
24−instance monadData :: Prelude.Monad Data where
25− return = Data
26− (>>=) (Data a) f = f a
27−
28−data Maybe a = Nothing | Just a
29−
30−instance monadMaybe :: Prelude.Monad Maybe where
31− return = Just
32− (>>=) Nothing _ = Nothing
33− (>>=) (Just a) f = f a
34−
35−test4 :: forall a m. (Monad m) => a -> m Number
36−test4 = \_ -> return 1
37−
38−test5 = \_ -> Just 1 >>= \n -> return (n + 1)
39−
40−instance showArray :: (Prelude.Show a) => Prelude.Show [a] where
41− show [] = "[]"
42− show (x:xs) = show x ++ ", " ++ show xs
43−
44−test6 = \_ -> show ["testing"]
45−
46−instance monadFunction :: Prelude.Monad ((->) r) where
47− return a r = a
48− (>>=) f g r = g (f r) r
49−
50−ask r = r
51−
52−runReader r f = f r
53−
54−test9 _ = runReader 0 $ do
55− n <- ask
56− return $ n + 1
57−
58−main = Debug.Trace.trace (test7 "Done")
59−
examples/passing/TypeClassesInOrder.pursdeleted−11
@@ -1,11 +0,0 @@
1−module Main where
2−
3−import Prelude
4−
5−class Foo a where
6− foo :: a -> String
7−
8−instance fooString :: Foo String where
9− foo s = s
10−
11−main = Debug.Trace.trace $ foo "Done"
examples/passing/TypeClassesWithOverlappingTypeVariables.pursdeleted−11
@@ -1,11 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− data Either a b = Left a | Right b
6−
7− instance functorEither :: Prelude.Functor (Either a) where
8− (<$>) _ (Left x) = Left x
9− (<$>) f (Right y) = Right (f y)
10−
11− main = Debug.Trace.trace "Done"
examples/passing/TypeDecl.pursdeleted−12
@@ -1,12 +0,0 @@
1−module Main where
2−
3− import Prelude
4−
5− k :: String -> Number -> String
6− k x y = x
7−
8− iterate :: forall a. Number -> (a -> a) -> a -> a
9− iterate 0 f a = a
10− iterate n f a = iterate (n - 1) f (f a)
11−
12− main = Debug.Trace.trace "Done"
examples/passing/TypeSynonymInData.pursdeleted−9
@@ -1,9 +0,0 @@
1−module Main where
2−
3−type A a = [a]
4−
5−data Foo a = Foo (A a) | Bar
6−
7−foo (Foo []) = Bar
8−
9−main = Debug.Trace.trace "Done"
examples/passing/TypeSynonyms.pursdeleted−25
@@ -1,25 +0,0 @@
1−module Main where
2−
3− type Lens a b =
4− { get :: a -> b
5− , set :: a -> b -> a
6− }
7−
8− composeLenses :: forall a b c. Lens a b -> Lens b c -> Lens a c
9− composeLenses = \l1 -> \l2 ->
10− { get: \a -> l2.get (l1.get a)
11− , set: \a c -> l1.set a (l2.set (l1.get a) c)
12− }
13−
14− type Pair a b = { fst :: a, snd :: b }
15−
16− fst :: forall a b. Lens (Pair a b) a
17− fst =
18− { get: \p -> p.fst
19− , set: \p a -> { fst: a, snd: p.snd }
20− }
21−
22− test1 :: forall a b c. Lens (Pair (Pair a b) c) a
23− test1 = composeLenses fst fst
24−
25− main = Debug.Trace.trace "Done"
examples/passing/Where.pursdeleted−49
@@ -1,49 +0,0 @@
1−module Main where
2−
3−import Prelude
4−import Control.Monad.Eff
5−import Control.Monad.ST
6−
7−test1 x = y
8− where
9− y :: Number
10− y = x + 1
11−
12−test2 x y = x' + y'
13− where
14− x' = x + 1
15− y' = y + 1
16−
17−
18−test3 = f 1 2 3
19− where f x y z = x + y + z
20−
21−
22−test4 = f (+) [1, 2]
23− where f x [y, z] = x y z
24−
25−
26−test5 = g 10
27− where
28− f x | x > 0 = g (x / 2) + 1
29− f x = 0
30− g x = f (x - 1) + 1
31−
32−test6 = if f true then f 1 else f 2
33− where f :: forall a. a -> a
34− f x = x
35−
36−test7 :: Number -> Number
37−test7 x = go x
38− where
39− go y | (x - 0.1 < y * y) && (y * y < x + 0.1) = y
40− go y = go $ (y + x / y) / 2
41−
42−main = do
43− Debug.Trace.print (test1 1)
44− Debug.Trace.print (test2 1 2)
45− Debug.Trace.print test3
46− Debug.Trace.print test4
47− Debug.Trace.print test5
48− Debug.Trace.print test6
49− Debug.Trace.print (test7 100)
examples/passing/iota.pursdeleted−9
@@ -1,9 +0,0 @@
1−module Main where
2−
3− s = \x -> \y -> \z -> x z (y z)
4−
5− k = \x -> \y -> x
6−
7− iota = \x -> x s k
8−
9− main = Debug.Trace.trace "Done"
examples/passing/s.pursdeleted−5
@@ -1,5 +0,0 @@
1−module Main where
2−
3− s = \x y z -> x z (y z)
4−
5− main = Debug.Trace.trace "Done"
package.yamlnew file+86
@@ -0,0 +1,86 @@
1+name: psgo
2+version: 0.1.0.0
3+github: "andyarvanitis/purescript-native"
4+license: BSD3
5+author: "Andy Arvanitis"
6+maintainer: "example@example.com"
7+copyright: "2018 Andy Arvanitis"
8+
9+extra-source-files:
10+- README.md
11+- ChangeLog.md
12+- stack.yaml
13+- support/*
14+
15+# Metadata used when publishing your package
16+# synopsis: Short description of your package
17+# category: Web
18+
19+# To avoid duplicated efforts in documentation and dealing with the
20+# complications of embedding Haddock markup inside cabal files, it is
21+# common to point users to the README.md file.
22+description: Please see the README on Github at <https://github.com/andyarvanitis/purescript-native#readme>
23+
24+dependencies:
25+- base >= 4.7 && < 5
26+- bytestring >= 0.10.8.2 && < 0.11
27+- purescript
28+- base-compat >=0.6.0
29+- protolude >=0.1.6
30+- text
31+- containers
32+- filepath
33+- monad-parallel >= 0.7.2.2 && <0.8
34+- pattern-arrows >=0.0.2 && <0.1
35+- safe >=0.3.9 && <0.4
36+- transformers >=0.3.0 && <0.6
37+- mtl >=2.1.0 && <2.3.0
38+- aeson >=1.0 && <1.5
39+- directory
40+- process
41+- file-embed
42+- filemanip
43+- gitrev
44+
45+library:
46+ source-dirs: src
47+ default-extensions:
48+ - ConstraintKinds
49+ - DataKinds
50+ - DeriveFunctor
51+ - EmptyDataDecls
52+ - FlexibleContexts
53+ - KindSignatures
54+ - LambdaCase
55+ - MultiParamTypeClasses
56+ - NoImplicitPrelude
57+ - PatternGuards
58+ - PatternSynonyms
59+ - RankNTypes
60+ - RecordWildCards
61+ - OverloadedStrings
62+ - ScopedTypeVariables
63+ - TupleSections
64+ - ViewPatterns
65+
66+executables:
67+ psgo:
68+ main: Main.hs
69+ source-dirs: app
70+ ghc-options:
71+ - -threaded
72+ - -rtsopts
73+ - -with-rtsopts=-N
74+ dependencies:
75+ - psgo
76+
77+tests:
78+ psgo-test:
79+ main: Spec.hs
80+ source-dirs: test
81+ ghc-options:
82+ - -threaded
83+ - -rtsopts
84+ - -with-rtsopts=-N
85+ dependencies:
86+ - psgo
prelude/README.mddeleted−295
@@ -1,295 +0,0 @@
1−# Module Documentation
2−## Module Prelude
3−
4−### Types
5−
6− data Ordering where
7− LT :: Ordering
8− GT :: Ordering
9− EQ :: Ordering
10−
11−
12−### Type Classes
13−
14− class Alternative f where
15− empty :: forall a. f a
16− (<|>) :: forall a. f a -> f a -> f a
17−
18− class Applicative f where
19− pure :: forall a. a -> f a
20− (<*>) :: forall a b. f (a -> b) -> f a -> f b
21−
22− class Bits b where
23− (&) :: b -> b -> b
24− (|) :: b -> b -> b
25− (^) :: b -> b -> b
26− shl :: b -> Prim.Number -> b
27− shr :: b -> Prim.Number -> b
28− zshr :: b -> Prim.Number -> b
29− complement :: b -> b
30−
31− class BoolLike b where
32− (&&) :: b -> b -> b
33− (||) :: b -> b -> b
34− not :: b -> b
35−
36− class Category a where
37− id :: forall t. a t t
38− (<<<) :: forall b c d. a c d -> a b c -> a b d
39−
40− class Eq a where
41− (==) :: a -> a -> Prim.Boolean
42− (/=) :: a -> a -> Prim.Boolean
43−
44− class Functor f where
45− (<$>) :: forall a b. (a -> b) -> f a -> f b
46−
47− class Monad m where
48− return :: forall a. a -> m a
49− (>>=) :: forall a b. m a -> (a -> m b) -> m b
50−
51− class Num a where
52− (+) :: a -> a -> a
53− (-) :: a -> a -> a
54− (*) :: a -> a -> a
55− (/) :: a -> a -> a
56− (%) :: a -> a -> a
57− negate :: a -> a
58−
59− class Ord a where
60− compare :: a -> a -> Ordering
61−
62− class Show a where
63− show :: a -> Prim.String
64−
65−
66−### Type Class Instances
67−
68− instance applicativeFromMonad :: (Monad m) => Applicative m
69−
70− instance bitsNumber :: Bits Prim.Number
71−
72− instance boolLikeBoolean :: BoolLike Prim.Boolean
73−
74− instance categoryArr :: Category Prim.Function
75−
76− instance eqArray :: (Eq a) => Eq [a]
77−
78− instance eqBoolean :: Eq Prim.Boolean
79−
80− instance eqNumber :: Eq Prim.Number
81−
82− instance eqString :: Eq Prim.String
83−
84− instance functorFromApplicative :: (Applicative f) => Functor f
85−
86− instance numNumber :: Num Prim.Number
87−
88− instance ordNumber :: Ord Prim.Number
89−
90− instance showBoolean :: Show Prim.Boolean
91−
92− instance showNumber :: Show Prim.Number
93−
94− instance showOrdering :: Show Ordering
95−
96− instance showString :: Show Prim.String
97−
98−
99−### Values
100−
101− (!!) :: forall a. [a] -> Prim.Number -> a
102−
103− (#) :: forall a b. a -> (a -> b) -> b
104−
105− ($) :: forall a b. (a -> b) -> a -> b
106−
107− (++) :: Prim.String -> Prim.String -> Prim.String
108−
109− (<) :: forall a. (Ord a) => a -> a -> Prim.Boolean
110−
111− (<=) :: forall a. (Ord a) => a -> a -> Prim.Boolean
112−
113− (>) :: forall a. (Ord a) => a -> a -> Prim.Boolean
114−
115− (>=) :: forall a. (Ord a) => a -> a -> Prim.Boolean
116−
117− (>>>) :: forall a b c d. (Category a) => a b c -> a c d -> a b d
118−
119− boolAnd :: Prim.Boolean -> Prim.Boolean -> Prim.Boolean
120−
121− boolNot :: Prim.Boolean -> Prim.Boolean
122−
123− boolOr :: Prim.Boolean -> Prim.Boolean -> Prim.Boolean
124−
125− const :: forall a b. a -> b -> a
126−
127− flip :: forall a b c. (a -> b -> c) -> b -> a -> c
128−
129− numAdd :: Prim.Number -> Prim.Number -> Prim.Number
130−
131− numAnd :: Prim.Number -> Prim.Number -> Prim.Number
132−
133− numCompare :: Prim.Number -> Prim.Number -> Ordering
134−
135− numComplement :: Prim.Number -> Prim.Number
136−
137− numDiv :: Prim.Number -> Prim.Number -> Prim.Number
138−
139− numMod :: Prim.Number -> Prim.Number -> Prim.Number
140−
141− numMul :: Prim.Number -> Prim.Number -> Prim.Number
142−
143− numNegate :: Prim.Number -> Prim.Number
144−
145− numOr :: Prim.Number -> Prim.Number -> Prim.Number
146−
147− numShl :: Prim.Number -> Prim.Number -> Prim.Number
148−
149− numShr :: Prim.Number -> Prim.Number -> Prim.Number
150−
151− numSub :: Prim.Number -> Prim.Number -> Prim.Number
152−
153− numXor :: Prim.Number -> Prim.Number -> Prim.Number
154−
155− numZshr :: Prim.Number -> Prim.Number -> Prim.Number
156−
157− on :: forall a b c. (b -> b -> c) -> (a -> b) -> a -> a -> c
158−
159− refEq :: forall a. a -> a -> Prim.Boolean
160−
161− refIneq :: forall a. a -> a -> Prim.Boolean
162−
163− showNumberImpl :: Prim.Number -> Prim.String
164−
165−
166−## Module Data.Eq
167−
168−### Types
169−
170− data Ref a where
171− Ref :: a -> Ref a
172−
173−
174−### Type Classes
175−
176−
177−### Type Class Instances
178−
179− instance eqRef :: Eq (Ref a)
180−
181−
182−### Values
183−
184− liftRef :: forall a b. (a -> a -> b) -> Ref a -> Ref a -> b
185−
186−
187−## Module Control.Monad.Eff
188−
189−### Types
190−
191− data Eff :: # ! -> * -> *
192−
193− type Pure a = forall e. Eff e a
194−
195−
196−### Type Classes
197−
198−
199−### Type Class Instances
200−
201− instance monadEff :: Monad (Eff e)
202−
203−
204−### Values
205−
206− bindEff :: forall e a b. Eff e a -> (a -> Eff e b) -> Eff e b
207−
208− forE :: forall e. Prim.Number -> Prim.Number -> (Prim.Number -> Eff e { }) -> Eff e { }
209−
210− foreachE :: forall e a. [a] -> (a -> Eff e { }) -> Eff e { }
211−
212− retEff :: forall e a. a -> Eff e a
213−
214− runPure :: forall a. Pure a -> a
215−
216− untilE :: forall e. Eff e Prim.Boolean -> Eff e { }
217−
218− whileE :: forall e a. Eff e Prim.Boolean -> Eff e a -> Eff e { }
219−
220−
221−## Module Control.Monad.Eff.Unsafe
222−
223−### Types
224−
225−
226−### Type Classes
227−
228−
229−### Type Class Instances
230−
231−
232−### Values
233−
234− unsafeInterleaveEff :: forall eff1 eff2 a. Eff eff1 a -> Eff eff2 a
235−
236−
237−## Module Debug.Trace
238−
239−### Types
240−
241− data Trace :: !
242−
243−
244−### Type Classes
245−
246−
247−### Type Class Instances
248−
249−
250−### Values
251−
252− print :: forall a r. (Show a) => a -> Eff (trace :: Trace | r) { }
253−
254− trace :: forall r. Prim.String -> Eff (trace :: Trace | r) { }
255−
256−
257−## Module Control.Monad.ST
258−
259−### Types
260−
261− data ST :: * -> !
262−
263− data STArray :: * -> * -> *
264−
265− data STRef :: * -> * -> *
266−
267−
268−### Type Classes
269−
270−
271−### Type Class Instances
272−
273−
274−### Values
275−
276− modifySTRef :: forall a h r. STRef h a -> (a -> a) -> Eff (st :: ST h | r) a
277−
278− newSTArray :: forall a h r. Prim.Number -> a -> Eff (st :: ST h | r) (STArray h a)
279−
280− newSTRef :: forall a h r. a -> Eff (st :: ST h | r) (STRef h a)
281−
282− peekSTArray :: forall a h r. STArray h a -> Eff (st :: ST h | r) a
283−
284− pokeSTArray :: forall a h r. STArray h a -> Prim.Number -> a -> Eff (st :: ST h | r) a
285−
286− readSTRef :: forall a h r. STRef h a -> Eff (st :: ST h | r) a
287−
288− runST :: forall a r. (forall h. Eff (st :: ST h | r) a) -> Eff r a
289−
290− runSTArray :: forall a r. (forall h. Eff (st :: ST h | r) (STArray h a)) -> Eff r [a]
291−
292− writeSTRef :: forall a h r. STRef h a -> a -> Eff (st :: ST h | r) a
293−
294−
295−
prelude/prelude.pursdeleted−534
@@ -1,534 +0,0 @@
1−module Prelude where
2−
3− flip :: forall a b c. (a -> b -> c) -> b -> a -> c
4− flip f b a = f a b
5−
6− const :: forall a b. a -> b -> a
7− const a _ = a
8−
9− on :: forall a b c. (b -> b -> c) -> (a -> b) -> a -> a -> c
10− on f g x y = g x `f` g y
11−
12− asTypeOf :: forall a. a -> a -> a
13− asTypeOf x _ = x
14−
15− infixr 9 >>>
16− infixr 9 <<<
17−
18− class Category a where
19− id :: forall t. a t t
20− (<<<) :: forall b c d. a c d -> a b c -> a b d
21−
22− (>>>) :: forall a b c d. (Category a) => a b c -> a c d -> a b d
23− (>>>) f g = g <<< f
24−
25− instance categoryArr :: Category (->) where
26− id x = x
27− (<<<) f g x = f (g x)
28−
29− infixr 0 $
30− infixl 0 #
31−
32− ($) :: forall a b. (a -> b) -> a -> b
33− ($) f x = f x
34−
35− (#) :: forall a b. a -> (a -> b) -> b
36− (#) x f = f x
37−
38− class Show a where
39− show :: a -> String
40−
41− instance showString :: Show String where
42− show s = s
43−
44− instance showBoolean :: Show Boolean where
45− show true = "true"
46− show false = "false"
47−
48− foreign import showNumberImpl "function showNumberImpl(n) {\
49− \ return n.toString();\
50− \}" :: Number -> String
51−
52− instance showNumber :: Show Number where
53− show = showNumberImpl
54−
55− infixl 4 <$>
56−
57− class Functor f where
58− (<$>) :: forall a b. (a -> b) -> f a -> f b
59−
60− infixl 4 <*>
61−
62− class (Functor f) <= Applicative f where
63− pure :: forall a. a -> f a
64− (<*>) :: forall a b. f (a -> b) -> f a -> f b
65−
66− liftA1 :: forall f a b. (Applicative f) => (a -> b) -> f a -> f b
67− liftA1 f a = pure f <*> a
68−
69− infixl 3 <|>
70−
71− class Alternative f where
72− empty :: forall a. f a
73− (<|>) :: forall a. f a -> f a -> f a
74−
75− infixl 1 >>=
76−
77− class (Applicative m) <= Monad m where
78− return :: forall a. a -> m a
79− (>>=) :: forall a b. m a -> (a -> m b) -> m b
80−
81− liftM1 :: forall m a b. (Monad m) => (a -> b) -> m a -> m b
82− liftM1 f a = do
83− a' <- a
84− return (f a')
85−
86− ap :: forall m a b. (Monad m) => m (a -> b) -> m a -> m b
87− ap f a = do
88− f' <- f
89− a' <- a
90− return (f' a')
91−
92− infixl 7 *
93− infixl 7 /
94− infixl 7 %
95−
96− infixl 6 -
97− infixl 6 +
98−
99− class Num a where
100− (+) :: a -> a -> a
101− (-) :: a -> a -> a
102− (*) :: a -> a -> a
103− (/) :: a -> a -> a
104− (%) :: a -> a -> a
105− negate :: a -> a
106−
107− foreign import numAdd "function numAdd(n1) {\
108− \ return function(n2) {\
109− \ return n1 + n2;\
110− \ };\
111− \}" :: Number -> Number -> Number
112−
113− foreign import numSub "function numSub(n1) {\
114− \ return function(n2) {\
115− \ return n1 - n2;\
116− \ };\
117− \}" :: Number -> Number -> Number
118−
119− foreign import numMul "function numMul(n1) {\
120− \ return function(n2) {\
121− \ return n1 * n2;\
122− \ };\
123− \}" :: Number -> Number -> Number
124−
125− foreign import numDiv "function numDiv(n1) {\
126− \ return function(n2) {\
127− \ return n1 / n2;\
128− \ };\
129− \}" :: Number -> Number -> Number
130−
131− foreign import numMod "function numMod(n1) {\
132− \ return function(n2) {\
133− \ return n1 % n2;\
134− \ };\
135− \}" :: Number -> Number -> Number
136−
137− foreign import numNegate "function numNegate(n) {\
138− \ return -n;\
139− \}" :: Number -> Number
140−
141− instance numNumber :: Num Number where
142− (+) = numAdd
143− (-) = numSub
144− (*) = numMul
145− (/) = numDiv
146− (%) = numMod
147− negate = numNegate
148−
149− infix 4 ==
150− infix 4 /=
151−
152− class Eq a where
153− (==) :: a -> a -> Boolean
154− (/=) :: a -> a -> Boolean
155−
156− foreign import refEq
157− "function refEq(r1) {\
158− \ return function(r2) {\
159− \ return r1 === r2;\
160− \ };\
161− \}" :: forall a. a -> a -> Boolean
162−
163− foreign import refIneq
164− "function refIneq(r1) {\
165− \ return function(r2) {\
166− \ return r1 !== r2;\
167− \ };\
168− \}" :: forall a. a -> a -> Boolean
169−
170− instance eqString :: Eq String where
171− (==) = refEq
172− (/=) = refIneq
173−
174− instance eqNumber :: Eq Number where
175− (==) = refEq
176− (/=) = refIneq
177−
178− instance eqBoolean :: Eq Boolean where
179− (==) = refEq
180− (/=) = refIneq
181−
182− instance eqArray :: (Eq a) => Eq [a] where
183− (==) [] [] = true
184− (==) (x:xs) (y:ys) = x == y && xs == ys
185− (==) _ _ = false
186− (/=) xs ys = not (xs == ys)
187−
188− data Ordering = LT | GT | EQ
189−
190− instance showOrdering :: Show Ordering where
191− show LT = "LT"
192− show GT = "GT"
193− show EQ = "EQ"
194−
195− class (Eq a) <= Ord a where
196− compare :: a -> a -> Ordering
197−
198− infixl 4 <
199−
200− (<) :: forall a. (Ord a) => a -> a -> Boolean
201− (<) a1 a2 = case a1 `compare` a2 of
202− LT -> true
203− _ -> false
204−
205− infixl 4 >
206−
207− (>) :: forall a. (Ord a) => a -> a -> Boolean
208− (>) a1 a2 = case a1 `compare` a2 of
209− GT -> true
210− _ -> false
211−
212− infixl 4 <=
213−
214− (<=) :: forall a. (Ord a) => a -> a -> Boolean
215− (<=) a1 a2 = case a1 `compare` a2 of
216− GT -> false
217− _ -> true
218−
219− infixl 4 >=
220−
221− (>=) :: forall a. (Ord a) => a -> a -> Boolean
222− (>=) a1 a2 = case a1 `compare` a2 of
223− LT -> false
224− _ -> true
225−
226− foreign import numCompare
227− "function numCompare(n1) {\
228− \ return function(n2) {\
229− \ return n1 < n2 ? module.LT : n1 > n2 ? module.GT : module.EQ;\
230− \ };\
231− \}" :: Number -> Number -> Ordering
232−
233− instance ordNumber :: Ord Number where
234− compare = numCompare
235−
236− infixl 10 &
237− infixl 10 |
238− infixl 10 ^
239−
240− class Bits b where
241− (&) :: b -> b -> b
242− (|) :: b -> b -> b
243− (^) :: b -> b -> b
244− shl :: b -> Number -> b
245− shr :: b -> Number -> b
246− zshr :: b -> Number -> b
247− complement :: b -> b
248−
249− foreign import numShl "function numShl(n1) {\
250− \ return function(n2) {\
251− \ return n1 << n2;\
252− \ };\
253− \}" :: Number -> Number -> Number
254−
255− foreign import numShr "function numShr(n1) {\
256− \ return function(n2) {\
257− \ return n1 >> n2;\
258− \ };\
259− \}" :: Number -> Number -> Number
260−
261− foreign import numZshr "function numZshr(n1) {\
262− \ return function(n2) {\
263− \ return n1 >>> n2;\
264− \ };\
265− \}" :: Number -> Number -> Number
266−
267− foreign import numAnd "function numAnd(n1) {\
268− \ return function(n2) {\
269− \ return n1 & n2;\
270− \ };\
271− \}" :: Number -> Number -> Number
272−
273− foreign import numOr "function numOr(n1) {\
274− \ return function(n2) {\
275− \ return n1 | n2;\
276− \ };\
277− \}" :: Number -> Number -> Number
278−
279− foreign import numXor "function numXor(n1) {\
280− \ return function(n2) {\
281− \ return n1 ^ n2;\
282− \ };\
283− \}" :: Number -> Number -> Number
284−
285− foreign import numComplement "function numComplement(n) {\
286− \ return ~n;\
287− \}" :: Number -> Number
288−
289− instance bitsNumber :: Bits Number where
290− (&) = numAnd
291− (|) = numOr
292− (^) = numXor
293− shl = numShl
294− shr = numShr
295− zshr = numZshr
296− complement = numComplement
297−
298− infixl 8 !!
299−
300− foreign import (!!) "function $bang$bang(xs) {\
301− \ return function(n) {\
302− \ return xs[n];\
303− \ };\
304− \}" :: forall a. [a] -> Number -> a
305−
306− infixr 2 ||
307− infixr 3 &&
308−
309− class BoolLike b where
310− (&&) :: b -> b -> b
311− (||) :: b -> b -> b
312− not :: b -> b
313−
314− foreign import boolAnd "function boolAnd(b1) {\
315− \ return function(b2) {\
316− \ return b1 && b2;\
317− \ };\
318− \}" :: Boolean -> Boolean -> Boolean
319−
320− foreign import boolOr "function boolOr(b1) {\
321− \ return function(b2) {\
322− \ return b1 || b2;\
323− \ };\
324− \}" :: Boolean -> Boolean -> Boolean
325−
326− foreign import boolNot "function boolNot(b) {\
327− \ return !b;\
328− \}" :: Boolean -> Boolean
329−
330− instance boolLikeBoolean :: BoolLike Boolean where
331− (&&) = boolAnd
332− (||) = boolOr
333− not = boolNot
334−
335− infixr 5 ++
336−
337− class Semigroup a where
338− (++) :: a -> a -> a
339−
340− foreign import concatString
341− "function concatString(s1) {\
342− \ return function(s2) {\
343− \ return s1 + s2;\
344− \ };\
345− \}" :: String -> String -> String
346−
347− instance semigroupString :: Semigroup String where
348− (++) = concatString
349−
350−module Data.Eq where
351−
352− data Ref a = Ref a
353−
354− liftRef :: forall a b. (a -> a -> b) -> Ref a -> Ref a -> b
355− liftRef f (Ref x) (Ref y) = f x y
356−
357− instance eqRef :: Eq (Ref a) where
358− (==) = liftRef refEq
359− (/=) = liftRef refIneq
360−
361−module Control.Monad.Eff where
362−
363− foreign import data Eff :: # ! -> * -> *
364−
365− foreign import retEff "function retEff(a) {\
366− \ return function() {\
367− \ return a;\
368− \ };\
369− \}" :: forall e a. a -> Eff e a
370−
371− foreign import bindEff "function bindEff(a) {\
372− \ return function(f) {\
373− \ return function() {\
374− \ return f(a())();\
375− \ };\
376− \ };\
377− \}" :: forall e a b. Eff e a -> (a -> Eff e b) -> Eff e b
378−
379− type Pure a = forall e. Eff e a
380−
381− foreign import runPure "function runPure(f) {\
382− \ return f();\
383− \}" :: forall a. Pure a -> a
384−
385− instance functorEff :: Functor (Eff e) where
386− (<$>) = liftA1
387−
388− instance applicativeEff :: Applicative (Eff e) where
389− pure = return
390− (<*>) = ap
391−
392− instance monadEff :: Monad (Eff e) where
393− return = retEff
394− (>>=) = bindEff
395−
396− foreign import untilE "function untilE(f) {\
397− \ return function() {\
398− \ while (!f()) { }\
399− \ return {};\
400− \ };\
401− \}" :: forall e. Eff e Boolean -> Eff e {}
402−
403− foreign import whileE "function whileE(f) {\
404− \ return function(a) {\
405− \ return function() {\
406− \ while (f()) {\
407− \ a();\
408− \ }\
409− \ return {};\
410− \ };\
411− \ };\
412− \}" :: forall e a. Eff e Boolean -> Eff e a -> Eff e {}
413−
414− foreign import forE "function forE(lo) {\
415− \ return function(hi) {\
416− \ return function(f) {\
417− \ return function() {\
418− \ for (var i = lo; i < hi; i++) {\
419− \ f(i)();\
420− \ }\
421− \ };\
422− \ };\
423− \ };\
424− \}" :: forall e. Number -> Number -> (Number -> Eff e {}) -> Eff e {}
425−
426−
427− foreign import foreachE "function foreachE(as) {\
428− \ return function(f) {\
429− \ for (var i = 0; i < as.length; i++) {\
430− \ f(as[i])();\
431− \ }\
432− \ };\
433− \}" :: forall e a. [a] -> (a -> Eff e {}) -> Eff e {}
434−
435−module Control.Monad.Eff.Unsafe where
436−
437− import Control.Monad.Eff
438−
439− foreign import unsafeInterleaveEff
440− "function unsafeInterleaveEff(f) {\
441− \ return f;\
442− \}" :: forall eff1 eff2 a. Eff eff1 a -> Eff eff2 a
443−
444−module Debug.Trace where
445−
446− import Control.Monad.Eff
447−
448− foreign import data Trace :: !
449−
450− foreign import trace "function trace(s) {\
451− \ return function() {\
452− \ console.log(s);\
453− \ return {};\
454− \ };\
455− \}" :: forall r. String -> Eff (trace :: Trace | r) {}
456−
457− print :: forall a r. (Show a) => a -> Eff (trace :: Trace | r) {}
458− print o = trace (show o)
459−
460−module Control.Monad.ST where
461−
462− import Control.Monad.Eff
463−
464− foreign import data ST :: * -> !
465−
466− foreign import data STRef :: * -> * -> *
467−
468− foreign import data STArray :: * -> * -> *
469−
470− foreign import newSTRef "function newSTRef(val) {\
471− \ return function () {\
472− \ return { value: val };\
473− \ };\
474− \}" :: forall a h r. a -> Eff (st :: ST h | r) (STRef h a)
475−
476− foreign import readSTRef "function readSTRef(ref) {\
477− \ return function() {\
478− \ return ref.value;\
479− \ };\
480− \}" :: forall a h r. STRef h a -> Eff (st :: ST h | r) a
481−
482− foreign import modifySTRef "function modifySTRef(ref) {\
483− \ return function(f) {\
484− \ return function() {\
485− \ return ref.value = f(ref.value);\
486− \ };\
487− \ };\
488− \}" :: forall a h r. STRef h a -> (a -> a) -> Eff (st :: ST h | r) a
489−
490− foreign import writeSTRef "function writeSTRef(ref) {\
491− \ return function(a) {\
492− \ return function() {\
493− \ return ref.value = a;\
494− \ };\
495− \ };\
496− \}" :: forall a h r. STRef h a -> a -> Eff (st :: ST h | r) a
497−
498− foreign import newSTArray "function newSTArray(len) {\
499− \ return function(a) {\
500− \ return function() {\
501− \ var arr = [];\
502− \ for (var i = 0; i < len; i++) {\
503− \ arr[i] = a;\
504− \ };\
505− \ return arr;\
506− \ };\
507− \ };\
508− \}" :: forall a h r. Number -> a -> Eff (st :: ST h | r) (STArray h a)
509−
510− foreign import peekSTArray "function peekSTArray(arr) {\
511− \ return function(i) {\
512− \ return function() {\
513− \ return arr[i];\
514− \ };\
515− \ };\
516− \}" :: forall a h r. STArray h a -> Eff (st :: ST h | r) a
517−
518− foreign import pokeSTArray "function pokeSTArray(arr) {\
519− \ return function(i) {\
520− \ return function(a) {\
521− \ return function() {\
522− \ return arr[i] = a;\
523− \ };\
524− \ };\
525− \ };\
526− \}" :: forall a h r. STArray h a -> Number -> a -> Eff (st :: ST h | r) a
527−
528− foreign import runST "function runST(f) {\
529− \ return f;\
530− \}" :: forall a r. (forall h. Eff (st :: ST h | r) a) -> Eff r a
531−
532− foreign import runSTArray "function runSTArray(f) {\
533− \ return f;\
534− \}" :: forall a r. (forall h. Eff (st :: ST h | r) (STArray h a)) -> Eff r [a]
prelude/updateDocs.shdeleted−2
@@ -1,2 +0,0 @@
1−../dist/build/docgen/docgen prelude.purs > README.md
2−pandoc -o ../docs/source/prelude.rst README.md
psc-make/Main.hsdeleted−144
@@ -1,144 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Main
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−--
13−-----------------------------------------------------------------------------
14−
15−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
16−
17−module Main where
18−
19−import Control.Applicative
20−import Control.Monad.Error
21−
22−import Data.Version (showVersion)
23−
24−import System.Console.CmdTheLine
25−import System.Directory
26− (doesFileExist, getModificationTime, createDirectoryIfMissing)
27−import System.FilePath (takeDirectory)
28−import System.Exit (exitSuccess, exitFailure)
29−import System.IO.Error (tryIOError)
30−
31−import Text.Parsec (ParseError)
32−
33−import qualified Language.PureScript as P
34−import qualified Paths_purescript as Paths
35−import qualified System.IO.UTF8 as U
36−
37−preludeFilename :: IO FilePath
38−preludeFilename = Paths.getDataFileName "prelude/prelude.purs"
39−
40−readInput :: [FilePath] -> IO (Either ParseError [(FilePath, P.Module)])
41−readInput input = fmap collect $ forM input $ \inputFile -> do
42− text <- U.readFile inputFile
43− return $ (inputFile, P.runIndentParser inputFile P.parseModules text)
44− where
45− collect :: [(FilePath, Either ParseError [P.Module])] -> Either ParseError [(FilePath, P.Module)]
46− collect = fmap concat . sequence . map (\(fp, e) -> fmap (map ((,) fp)) e)
47−
48−newtype Make a = Make { unMake :: ErrorT String IO a } deriving (Functor, Monad, MonadIO, MonadError String)
49−
50−runMake :: Make a -> IO (Either String a)
51−runMake = runErrorT . unMake
52−
53−makeIO :: IO a -> Make a
54−makeIO = Make . ErrorT . fmap (either (Left . show) Right) . tryIOError
55−
56−instance P.MonadMake Make where
57− getTimestamp path = makeIO $ do
58− exists <- doesFileExist path
59− case exists of
60− True -> Just <$> getModificationTime path
61− False -> return Nothing
62− readTextFile path = makeIO $ do
63− U.putStrLn $ "Reading " ++ path
64− U.readFile path
65− writeTextFile path text = makeIO $ do
66− mkdirp path
67− U.putStrLn $ "Writing " ++ path
68− U.writeFile path text
69− liftError = either throwError return
70−
71−compile :: P.Options -> [FilePath] -> IO ()
72−compile opts input = do
73− modules <- readInput input
74− case modules of
75− Left err -> do
76− U.print err
77− exitFailure
78− Right ms -> do
79− e <- runMake $ P.make opts ms
80− case e of
81− Left err -> do
82− U.putStrLn err
83− exitFailure
84− Right _ -> do
85− exitSuccess
86−
87−mkdirp :: FilePath -> IO ()
88−mkdirp = createDirectoryIfMissing True . takeDirectory
89−
90−inputFiles :: Term [FilePath]
91−inputFiles = value $ posAny [] $ posInfo
92− { posDoc = "The input .ps files" }
93−
94−noTco :: Term Bool
95−noTco = value $ flag $ (optInfo [ "no-tco" ])
96− { optDoc = "Disable tail call optimizations" }
97−
98−performRuntimeTypeChecks :: Term Bool
99−performRuntimeTypeChecks = value $ flag $ (optInfo [ "runtime-type-checks" ])
100− { optDoc = "Generate runtime type checks" }
101−
102−noPrelude :: Term Bool
103−noPrelude = value $ flag $ (optInfo [ "no-prelude" ])
104− { optDoc = "Omit the Prelude" }
105−
106−noMagicDo :: Term Bool
107−noMagicDo = value $ flag $ (optInfo [ "no-magic-do" ])
108− { optDoc = "Disable the optimization that overloads the do keyword to generate efficient code specifically for the Eff monad." }
109−
110−noOpts :: Term Bool
111−noOpts = value $ flag $ (optInfo [ "no-opts" ])
112− { optDoc = "Skip the optimization phase." }
113−
114−browserNamespace :: Term String
115−browserNamespace = value $ opt "PS" $ (optInfo [ "browser-namespace" ])
116− { optDoc = "Specify the namespace that PureScript modules will be exported to when running in the browser." }
117−
118−verboseErrors :: Term Bool
119−verboseErrors = value $ flag $ (optInfo [ "v", "verbose-errors" ])
120− { optDoc = "Display verbose error messages" }
121−
122−options :: Term P.Options
123−options = P.Options <$> noPrelude <*> noTco <*> performRuntimeTypeChecks <*> noMagicDo <*> pure Nothing <*> noOpts <*> browserNamespace <*> pure [] <*> pure [] <*> verboseErrors
124−
125−inputFilesAndPrelude :: FilePath -> Term [FilePath]
126−inputFilesAndPrelude prelude = combine <$> (not <$> noPrelude) <*> inputFiles
127− where
128− combine True input = prelude : input
129− combine False input = input
130−
131−term :: FilePath -> Term (IO ())
132−term prelude = compile <$> options <*> inputFilesAndPrelude prelude
133−
134−termInfo :: TermInfo
135−termInfo = defTI
136− { termName = "psc-make"
137− , version = showVersion Paths.version
138− , termDoc = "Compiles PureScript to Javascript"
139− }
140−
141−main :: IO ()
142−main = do
143− prelude <- preludeFilename
144− run (term prelude, termInfo)
psc/Main.hsdeleted−152
@@ -1,152 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Main
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−--
13−-----------------------------------------------------------------------------
14−
15−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
16−
17−module Main where
18−
19−import Control.Applicative
20−import Control.Monad.Error
21−
22−import Data.Version (showVersion)
23−
24−import System.Console.CmdTheLine
25−import System.Directory (createDirectoryIfMissing)
26−import System.FilePath (takeDirectory)
27−import System.Exit (exitSuccess, exitFailure)
28−
29−import Text.Parsec (ParseError)
30−
31−import qualified Language.PureScript as P
32−import qualified Paths_purescript as Paths
33−import qualified System.IO.UTF8 as U
34−
35−preludeFilename :: IO FilePath
36−preludeFilename = Paths.getDataFileName "prelude/prelude.purs"
37−
38−readInput :: Maybe [FilePath] -> IO (Either ParseError [(FilePath, P.Module)])
39−readInput Nothing = do
40− text <- getContents
41− return $ map ((,) undefined) <$> P.runIndentParser "" P.parseModules text
42−readInput (Just input) = fmap collect $ forM input $ \inputFile -> do
43− text <- U.readFile inputFile
44− return $ (inputFile, P.runIndentParser inputFile P.parseModules text)
45− where
46− collect :: [(FilePath, Either ParseError [P.Module])] -> Either ParseError [(FilePath, P.Module)]
47− collect = fmap concat . sequence . map (\(fp, e) -> fmap (map ((,) fp)) e)
48−
49−compile :: P.Options -> Maybe [FilePath] -> Maybe FilePath -> Maybe FilePath -> IO ()
50−compile opts input output externs = do
51− modules <- readInput input
52− case modules of
53− Left err -> do
54− U.print err
55− exitFailure
56− Right ms -> do
57− case P.compile opts (map snd ms) of
58− Left err -> do
59− U.putStrLn err
60− exitFailure
61− Right (js, exts, _) -> do
62− case output of
63− Just path -> mkdirp path >> U.writeFile path js
64− Nothing -> U.putStrLn js
65− case externs of
66− Just path -> mkdirp path >> U.writeFile path exts
67− Nothing -> return ()
68− exitSuccess
69−
70−mkdirp :: FilePath -> IO ()
71−mkdirp = createDirectoryIfMissing True . takeDirectory
72−
73−useStdIn :: Term Bool
74−useStdIn = value . flag $ (optInfo [ "s", "stdin" ])
75− { optDoc = "Read from standard input" }
76−
77−inputFiles :: Term [FilePath]
78−inputFiles = value $ posAny [] $ posInfo
79− { posDoc = "The input .ps files" }
80−
81−outputFile :: Term (Maybe FilePath)
82−outputFile = value $ opt Nothing $ (optInfo [ "o", "output" ])
83− { optDoc = "The output .js file" }
84−
85−externsFile :: Term (Maybe FilePath)
86−externsFile = value $ opt Nothing $ (optInfo [ "e", "externs" ])
87− { optDoc = "The output .e.ps file" }
88−
89−noTco :: Term Bool
90−noTco = value $ flag $ (optInfo [ "no-tco" ])
91− { optDoc = "Disable tail call optimizations" }
92−
93−performRuntimeTypeChecks :: Term Bool
94−performRuntimeTypeChecks = value $ flag $ (optInfo [ "runtime-type-checks" ])
95− { optDoc = "Generate runtime type checks" }
96−
97−noPrelude :: Term Bool
98−noPrelude = value $ flag $ (optInfo [ "no-prelude" ])
99− { optDoc = "Omit the Prelude" }
100−
101−noMagicDo :: Term Bool
102−noMagicDo = value $ flag $ (optInfo [ "no-magic-do" ])
103− { optDoc = "Disable the optimization that overloads the do keyword to generate efficient code specifically for the Eff monad." }
104−
105−runMain :: Term (Maybe String)
106−runMain = value $ defaultOpt (Just "Main") Nothing $ (optInfo [ "main" ])
107− { optDoc = "Generate code to run the main method in the specified module." }
108−
109−noOpts :: Term Bool
110−noOpts = value $ flag $ (optInfo [ "no-opts" ])
111− { optDoc = "Skip the optimization phase." }
112−
113−browserNamespace :: Term String
114−browserNamespace = value $ opt "PS" $ (optInfo [ "browser-namespace" ])
115− { optDoc = "Specify the namespace that PureScript modules will be exported to when running in the browser." }
116−
117−dceModules :: Term [String]
118−dceModules = value $ optAll [] $ (optInfo [ "m", "module" ])
119− { optDoc = "Enables dead code elimination, all code which is not a transitive dependency of a specified module will be removed. This argument can be used multiple times." }
120−
121−codeGenModules :: Term [String]
122−codeGenModules = value $ optAll [] $ (optInfo [ "codegen" ])
123− { optDoc = "A list of modules for which Javascript and externs should be generated. This argument can be used multiple times." }
124−
125−verboseErrors :: Term Bool
126−verboseErrors = value $ flag $ (optInfo [ "v", "verbose-errors" ])
127− { optDoc = "Display verbose error messages" }
128−
129−options :: Term P.Options
130−options = P.Options <$> noPrelude <*> noTco <*> performRuntimeTypeChecks <*> noMagicDo <*> runMain <*> noOpts <*> browserNamespace <*> dceModules <*> codeGenModules <*> verboseErrors
131−
132−stdInOrInputFiles :: FilePath -> Term (Maybe [FilePath])
133−stdInOrInputFiles prelude = combine <$> useStdIn <*> (not <$> noPrelude) <*> inputFiles
134− where
135− combine False True input = Just (prelude : input)
136− combine False False input = Just input
137− combine True _ _ = Nothing
138−
139−term :: FilePath -> Term (IO ())
140−term prelude = compile <$> options <*> stdInOrInputFiles prelude <*> outputFile <*> externsFile
141−
142−termInfo :: TermInfo
143−termInfo = defTI
144− { termName = "psc"
145− , version = showVersion Paths.version
146− , termDoc = "Compiles PureScript to Javascript"
147− }
148−
149−main :: IO ()
150−main = do
151− prelude <- preludeFilename
152− run (term prelude, termInfo)
psci/Commands.hsdeleted−68
@@ -1,68 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Commands
4−-- Copyright : (c) Phil Freeman 2014
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Commands for PSCI.
13−--
14−-----------------------------------------------------------------------------
15−
16−module Commands where
17−
18−import Language.PureScript
19−
20−-- |
21−-- Valid Meta-commands for PSCI
22−--
23−data Command
24− -- |
25− -- A purescript expression
26− --
27− = Expression Value
28− -- |
29− -- Show the help command
30− --
31− | Help
32− -- |
33− -- Import a module from a loaded file
34− --
35− | Import ModuleName
36− -- |
37− -- Load a file for use with importing
38− --
39− | LoadFile FilePath
40− -- |
41− -- Exit PSCI
42− --
43− | Quit
44− -- |
45− -- Reset the state of the REPL
46− --
47− | Reset
48− -- |
49− -- Binds a value to a name
50− --
51− | Let (Value -> Value)
52− -- |
53− -- Find the type of an expression
54− --
55− | TypeOf Value
56−
57−-- |
58−-- The help menu.
59−--
60−help :: [[String]]
61−help =
62− [ [":? ", "Show this help menu"]
63− , [":i <module> ", "Import <module> for use in PSCI"]
64− , [":m <file> ", "Load <file> for importing"]
65− , [":q ", "Quit PSCi"]
66− , [":r ", "Reset"]
67− , [":t <expr> ", "Show the type of <expr>"]
68− ]
psci/Main.hsdeleted−346
@@ -1,346 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Main
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- PureScript Compiler Interactive.
13−--
14−-----------------------------------------------------------------------------
15−
16−{-# LANGUAGE DoAndIfThenElse, FlexibleContexts #-}
17−
18−module Main where
19−
20−import Commands
21−
22−import Control.Applicative
23−import Control.Monad
24−import Control.Monad.Trans.Class
25−import Control.Monad.Trans.Maybe (MaybeT(..), runMaybeT)
26−import Control.Monad.Trans.State.Strict
27−
28−import Data.List (intercalate, isPrefixOf, nub, sortBy)
29−import Data.Maybe (mapMaybe)
30−import Data.Foldable (traverse_)
31−import Data.Traversable (traverse)
32−import Data.Version (showVersion)
33−
34−import Parser
35−
36−import System.Console.Haskeline
37−import System.Directory (doesFileExist, findExecutable, getHomeDirectory, getCurrentDirectory)
38−import System.Exit
39−import System.Environment.XDG.BaseDir
40−import System.FilePath ((</>), isPathSeparator)
41−import qualified System.Console.CmdTheLine as Cmd
42−import System.Process
43−
44−import Text.Parsec (ParseError)
45−
46−import qualified Data.Map as M
47−import qualified Language.PureScript as P
48−import qualified Paths_purescript as Paths
49−import qualified System.IO.UTF8 as U (print, readFile)
50−
51−-- |
52−-- The PSCI state.
53−-- Holds a list of imported modules, loaded files, and partial let bindings.
54−-- The let bindings are partial,
55−-- because it makes more sense to apply the binding to the final evaluated expression.
56−--
57−data PSCiState = PSCiState
58− { psciImportedFilenames :: [FilePath]
59− , psciImportedModuleNames :: [P.ModuleName]
60− , psciLoadedModules :: [P.Module]
61− , psciLetBindings :: [P.Value -> P.Value]
62− }
63−
64−-- State helpers
65−
66−-- |
67−-- Updates the state to have more imported modules.
68−--
69−updateImportedFiles :: FilePath -> PSCiState -> PSCiState
70−updateImportedFiles filename st = st { psciImportedFilenames = filename : psciImportedFilenames st }
71−
72−-- |
73−-- Updates the state to have more imported modules.
74−--
75−updateImports :: P.ModuleName -> PSCiState -> PSCiState
76−updateImports name st = st { psciImportedModuleNames = name : psciImportedModuleNames st }
77−
78−-- |
79−-- Updates the state to have more loaded files.
80−--
81−updateModules :: [P.Module] -> PSCiState -> PSCiState
82−updateModules modules st = st { psciLoadedModules = psciLoadedModules st ++ modules }
83−
84−-- |
85−-- Updates the state to have more let bindings.
86−--
87−updateLets :: (P.Value -> P.Value) -> PSCiState -> PSCiState
88−updateLets name st = st { psciLetBindings = name : psciLetBindings st }
89−
90−-- File helpers
91−-- |
92−-- Load the necessary modules.
93−--
94−defaultImports :: [P.ModuleName]
95−defaultImports = [P.ModuleName [P.ProperName "Prelude"]]
96−
97−-- |
98−-- Locates the node executable.
99−-- Checks for either @nodejs@ or @node@.
100−--
101−findNodeProcess :: IO (Maybe String)
102−findNodeProcess = runMaybeT . msum $ map (MaybeT . findExecutable) names
103− where names = ["nodejs", "node"]
104−
105−-- |
106−-- Grabs the filename where the history is stored.
107−--
108−getHistoryFilename :: IO FilePath
109−getHistoryFilename = getUserConfigFile "purescript" "psci_history"
110−
111−-- |
112−-- Grabs the filename where prelude is.
113−--
114−getPreludeFilename :: IO FilePath
115−getPreludeFilename = Paths.getDataFileName "prelude/prelude.purs"
116−
117−-- |
118−-- Loads a file for use with imports.
119−--
120−loadModule :: FilePath -> IO (Either String [P.Module])
121−loadModule filename = either (Left . show) Right . P.runIndentParser filename P.parseModules <$> U.readFile filename
122−
123−-- |
124−-- Expands tilde in path.
125−--
126−expandTilde :: FilePath -> IO FilePath
127−expandTilde ('~':p:rest) | isPathSeparator p = (</> rest) <$> getHomeDirectory
128−expandTilde p = return p
129−-- Messages
130−
131−-- |
132−-- The help message.
133−--
134−helpMessage :: String
135−helpMessage = "The following commands are available:\n\n " ++
136− intercalate "\n " (map (intercalate " ") help)
137−
138−-- |
139−-- The welcome prologue.
140−--
141−prologueMessage :: String
142−prologueMessage = intercalate "\n"
143− [ " ____ ____ _ _ "
144− , "| _ \\ _ _ _ __ ___/ ___| ___ _ __(_)_ __ | |_ "
145− , "| |_) | | | | '__/ _ \\___ \\ / __| '__| | '_ \\| __|"
146− , "| __/| |_| | | | __/___) | (__| | | | |_) | |_ "
147− , "|_| \\__,_|_| \\___|____/ \\___|_| |_| .__/ \\__|"
148− , " |_| "
149− , ""
150− , ":? shows help"
151− , ""
152− , "Expressions are terminated using Ctrl+D"
153− ]
154−
155−-- |
156−-- The quit message.
157−--
158−quitMessage :: String
159−quitMessage = "See ya!"
160−
161−-- Haskeline completions
162−
163−-- |
164−-- Loads module, function, and file completions.
165−--
166−completion :: CompletionFunc (StateT PSCiState IO)
167−completion = completeWord Nothing " \t\n\r" findCompletions
168− where
169− findCompletions :: String -> StateT PSCiState IO [Completion]
170− findCompletions str = do
171− ms <- psciLoadedModules <$> get
172− files <- listFiles str
173− let matches = filter (isPrefixOf str) (names ms)
174− return $ sortBy sorter $ map simpleCompletion matches ++ files
175− getDeclName :: Maybe [P.DeclarationRef] -> P.Declaration -> Maybe P.Ident
176− getDeclName Nothing (P.ValueDeclaration ident _ _ _ _) = Just ident
177− getDeclName (Just exts) (P.ValueDeclaration ident _ _ _ _) | isExported = Just ident
178− where
179− isExported = any exports exts
180− exports (P.ValueRef ident') = ident == ident'
181− exports (P.PositionedDeclarationRef _ r) = exports r
182− exports _ = False
183− getDeclName exts (P.PositionedDeclaration _ d) = getDeclName exts d
184− getDeclName _ _ = Nothing
185− names :: [P.Module] -> [String]
186− names ms = nub [ show qual
187− | P.Module moduleName ds exts <- ms
188− , ident <- mapMaybe (getDeclName exts) ds
189− , qual <- [ P.Qualified Nothing ident
190− , P.Qualified (Just moduleName) ident]
191− ]
192− sorter :: Completion -> Completion -> Ordering
193− sorter (Completion _ d1 _) (Completion _ d2 _) = compare d1 d2
194−
195−-- Compilation
196−
197−-- | Compilation options.
198−--
199−options :: P.Options
200−options = P.Options False True False True (Just "Main") True "PS" [] [] False
201−
202−-- |
203−-- Makes a volatile module to execute the current expression.
204−--
205−createTemporaryModule :: Bool -> PSCiState -> P.Value -> P.Module
206−createTemporaryModule exec PSCiState{psciImportedModuleNames = imports, psciLetBindings = lets} value =
207− let
208− moduleName = P.ModuleName [P.ProperName "Main"]
209− importDecl m = P.ImportDeclaration m Nothing Nothing
210− traceModule = P.ModuleName [P.ProperName "Debug", P.ProperName "Trace"]
211− trace = P.Var (P.Qualified (Just traceModule) (P.Ident "print"))
212− itValue = foldl (\x f -> f x) value lets
213− mainValue = P.App trace (P.Var (P.Qualified Nothing (P.Ident "it")))
214− itDecl = P.ValueDeclaration (P.Ident "it") P.Value [] Nothing itValue
215− mainDecl = P.ValueDeclaration (P.Ident "main") P.Value [] Nothing mainValue
216− decls = if exec then [itDecl, mainDecl] else [itDecl]
217− in
218− P.Module moduleName ((importDecl `map` imports) ++ decls) Nothing
219−
220−-- |
221−-- Takes a value declaration and evaluates it with the current state.
222−--
223−handleDeclaration :: P.Value -> PSCiState -> InputT (StateT PSCiState IO) ()
224−handleDeclaration value st = do
225− let m = createTemporaryModule True st value
226− case P.compile options (psciLoadedModules st ++ [m]) of
227− Left err -> outputStrLn err
228− Right (js, _, _) -> do
229− process <- lift . lift $ findNodeProcess
230− result <- lift . lift $ traverse (\node -> readProcessWithExitCode node [] js) process
231− case result of
232− Just (ExitSuccess, out, _) -> outputStrLn out
233− Just (ExitFailure _, _, err) -> outputStrLn err
234− Nothing -> outputStrLn "Couldn't find node.js"
235−
236−-- |
237−-- Takes a value and prints its type
238−--
239−handleTypeOf :: P.Value -> PSCiState -> InputT (StateT PSCiState IO) ()
240−handleTypeOf value st = do
241− let m = createTemporaryModule False st value
242− case P.compile options { P.optionsMain = Nothing } (psciLoadedModules st ++ [m]) of
243− Left err -> outputStrLn err
244− Right (_, _, env') ->
245− case M.lookup (P.ModuleName [P.ProperName "Main"], P.Ident "it") (P.names env') of
246− Just (ty, _) -> outputStrLn . P.prettyPrintType $ ty
247− Nothing -> outputStrLn "Could not find type"
248−
249−-- Commands
250−
251−-- |
252−-- Parses the input and returns either a Metacommand or an expression.
253−--
254−getCommand :: InputT (StateT PSCiState IO) (Either ParseError (Maybe Command))
255−getCommand = do
256− firstLine <- getInputLine "> "
257− case firstLine of
258− Nothing -> return (Right Nothing)
259− Just s@ (':' : _) -> return . either Left (Right . Just) $ parseCommand s -- The start of a command
260− Just s -> either Left (Right . Just) . parseCommand <$> go [s]
261− where
262− go :: [String] -> InputT (StateT PSCiState IO) String
263− go ls = maybe (return . unlines $ reverse ls) (go . (:ls)) =<< getInputLine " "
264−
265−-- |
266−-- Performs an action for each meta-command given, and also for expressions..
267−--
268−handleCommand :: Command -> InputT (StateT PSCiState IO) ()
269−handleCommand (Expression val) = lift get >>= handleDeclaration val
270−handleCommand Help = outputStrLn helpMessage
271−handleCommand (Import moduleName) = lift $ modify (updateImports moduleName)
272−handleCommand (Let l) = lift $ modify (updateLets l)
273−handleCommand (LoadFile filePath) = do
274− absPath <- lift . lift $ expandTilde filePath
275− exists <- lift . lift $ doesFileExist absPath
276− if exists then do
277− lift $ modify (updateImportedFiles absPath)
278− either outputStrLn (lift . modify . updateModules) =<< (lift . lift $ loadModule absPath)
279− else
280− outputStrLn $ "Couldn't locate: " ++ filePath
281−handleCommand Reset = do
282− files <- psciImportedFilenames <$> lift get
283− modulesOrFirstError <- fmap concat . sequence <$> mapM (lift . lift . loadModule) files
284− case modulesOrFirstError of
285− Left err -> lift . lift $ putStrLn err >> exitFailure
286− Right modules -> lift $ put (PSCiState files defaultImports modules [])
287−handleCommand (TypeOf val) = lift get >>= handleTypeOf val
288−handleCommand _ = outputStrLn "Unknown command"
289−
290−inputFiles :: Cmd.Term [FilePath]
291−inputFiles = Cmd.value $ Cmd.posAny [] $ Cmd.posInfo { Cmd.posName = "file(s)"
292− , Cmd.posDoc = "Optional .purs files to load on start" }
293−
294−loadUserConfig :: IO (Maybe [Command])
295−loadUserConfig = do
296− configFile <- (</> ".psci") <$> getCurrentDirectory
297− exists <- doesFileExist configFile
298− if exists
299− then do
300− ls <- lines <$> U.readFile configFile
301− case mapM parseCommand ls of
302− Left err -> U.print err >> exitFailure
303− Right cs -> return $ Just cs
304− else
305− return Nothing
306−
307−-- |
308−-- The PSCI main loop.
309−--
310−loop :: [FilePath] -> IO ()
311−loop files = do
312− config <- loadUserConfig
313− preludeFilename <- getPreludeFilename
314− modulesOrFirstError <- fmap concat . sequence <$> mapM loadModule (preludeFilename : files)
315− case modulesOrFirstError of
316− Left err -> putStrLn err >> exitFailure
317− Right modules -> do
318− historyFilename <- getHistoryFilename
319− let settings = defaultSettings {historyFile = Just historyFilename}
320− flip evalStateT (PSCiState (preludeFilename : files) defaultImports modules []) . runInputT (setComplete completion settings) $ do
321− outputStrLn prologueMessage
322− traverse_ (mapM_ handleCommand) config
323− go
324− where
325− go :: InputT (StateT PSCiState IO) ()
326− go = do
327− c <- getCommand
328− case c of
329− Left err -> outputStrLn (show err) >> go
330− Right Nothing -> go
331− Right (Just Quit) -> outputStrLn quitMessage
332− Right (Just c') -> handleCommand c' >> go
333−
334−term :: Cmd.Term (IO ())
335−term = loop <$> inputFiles
336−
337−termInfo :: Cmd.TermInfo
338−termInfo = Cmd.defTI
339− { Cmd.termName = "psci"
340− , Cmd.version = showVersion Paths.version
341− , Cmd.termDoc = "Interactive mode for PureScript"
342− }
343−
344−main :: IO ()
345−main = Cmd.run (term, termInfo)
346−
psci/Parser.hsdeleted−92
@@ -1,92 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Parser
4−-- Copyright : (c) Phil Freeman 2014
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Parser for PSCI.
13−--
14−-----------------------------------------------------------------------------
15−
16−module Parser (
17− parseCommand
18− ) where
19−
20−import Commands
21−
22−import Data.Char (isSpace)
23−
24−import Control.Applicative hiding (many)
25−
26−import Text.Parsec hiding ((<|>))
27−
28−import qualified Language.PureScript as P
29−import qualified Language.PureScript.Parser.Common as C (mark, same)
30−
31−-- |
32−-- PSCI version of @let@.
33−-- This is essentially let from do-notation.
34−-- However, since we don't support the @Eff@ monad,
35−-- we actually want the normal @let@.
36−--
37−psciLet :: Parsec String P.ParseState Command
38−psciLet = Let <$> (P.Let <$> (P.reserved "let" *> P.indented *> C.mark (many1 (C.same *> P.parseDeclaration))))
39−
40−-- |
41−-- Parses PSCI metacommands or expressions input from the user.
42−--
43−parseCommand :: String -> Either ParseError Command
44−parseCommand = P.runIndentParser "" $ choice
45− [ P.whiteSpace *> char ':' *> (psciHelp <|> psciImport <|> psciLoadFile <|> psciQuit <|> psciReload <|> psciTypeOf)
46− , try psciLet
47− , psciExpression
48− ] <* eof
49−
50−-- |
51−-- Parses expressions entered at the PSCI repl.
52−--
53−psciExpression :: Parsec String P.ParseState Command
54−psciExpression = Expression <$> P.parseValue
55−
56−-- |
57−-- Parses 'Commands.Help' command.
58−--
59−psciHelp :: Parsec String P.ParseState Command
60−psciHelp = Help <$ char '?'
61−
62−-- |
63−-- Parses 'Commands.Import' command.
64−--
65−psciImport :: Parsec String P.ParseState Command
66−psciImport = Import <$> (char 'i' *> P.whiteSpace *> P.moduleName)
67−
68−-- |
69−-- Parses 'Commands.LoadFile' command.
70−--
71−psciLoadFile :: Parsec String P.ParseState Command
72−psciLoadFile = LoadFile . trimEnd <$> (char 'm' *> P.whiteSpace *> manyTill anyChar eof)
73− where
74− trimEnd = reverse . dropWhile isSpace . reverse
75−
76−-- |
77−-- Parses 'Commands.Quit' command.
78−--
79−psciQuit :: Parsec String P.ParseState Command
80−psciQuit = Quit <$ char 'q'
81−
82−-- |
83−-- Parses 'Commands.Reload' command.
84−--
85−psciReload :: Parsec String P.ParseState Command
86−psciReload = Reset <$ char 'r'
87−
88−-- |
89−-- Parses 'Commands.TypeOf' command.
90−--
91−psciTypeOf :: Parsec String P.ParseState Command
92−psciTypeOf = TypeOf <$> (char 't' *> P.whiteSpace *> P.parseValue)
psgo.cabalnew file+145
@@ -0,0 +1,145 @@
1+cabal-version: 1.12
2+
3+-- This file has been generated from package.yaml by hpack version 0.35.0.
4+--
5+-- see: https://github.com/sol/hpack
6+
7+name: psgo
8+version: 0.1.0.0
9+description: Please see the README on Github at <https://github.com/andyarvanitis/purescript-native#readme>
10+homepage: https://github.com/andyarvanitis/purescript-native#readme
11+bug-reports: https://github.com/andyarvanitis/purescript-native/issues
12+author: Andy Arvanitis
13+maintainer: example@example.com
14+copyright: 2018 Andy Arvanitis
15+license: BSD3
16+license-file: LICENSE
17+build-type: Simple
18+extra-source-files:
19+ README.md
20+ ChangeLog.md
21+ stack.yaml
22+ support/ffi-loader.go
23+ support/go.mod.ffi-loader
24+ support/go.mod.output
25+ support/go.mod.working
26+
27+source-repository head
28+ type: git
29+ location: https://github.com/andyarvanitis/purescript-native
30+
31+library
32+ exposed-modules:
33+ CodeGen.IL
34+ CodeGen.IL.Common
35+ CodeGen.IL.Optimizer
36+ CodeGen.IL.Optimizer.Common
37+ CodeGen.IL.Optimizer.Inliner
38+ CodeGen.IL.Optimizer.MagicDo
39+ CodeGen.IL.Optimizer.TCO
40+ CodeGen.IL.Printer
41+ Tests
42+ other-modules:
43+ Paths_psgo
44+ hs-source-dirs:
45+ src
46+ default-extensions:
47+ ConstraintKinds
48+ DataKinds
49+ DeriveFunctor
50+ EmptyDataDecls
51+ FlexibleContexts
52+ KindSignatures
53+ LambdaCase
54+ MultiParamTypeClasses
55+ NoImplicitPrelude
56+ PatternGuards
57+ PatternSynonyms
58+ RankNTypes
59+ RecordWildCards
60+ OverloadedStrings
61+ ScopedTypeVariables
62+ TupleSections
63+ ViewPatterns
64+ build-depends:
65+ aeson >=1.0 && <1.5
66+ , base >=4.7 && <5
67+ , base-compat >=0.6.0
68+ , bytestring >=0.10.8.2 && <0.11
69+ , containers
70+ , directory
71+ , file-embed
72+ , filemanip
73+ , filepath
74+ , gitrev
75+ , monad-parallel >=0.7.2.2 && <0.8
76+ , mtl >=2.1.0 && <2.3.0
77+ , pattern-arrows >=0.0.2 && <0.1
78+ , process
79+ , protolude >=0.1.6
80+ , purescript
81+ , safe >=0.3.9 && <0.4
82+ , text
83+ , transformers >=0.3.0 && <0.6
84+ default-language: Haskell2010
85+
86+executable psgo
87+ main-is: Main.hs
88+ other-modules:
89+ Paths_psgo
90+ hs-source-dirs:
91+ app
92+ ghc-options: -threaded -rtsopts -with-rtsopts=-N
93+ build-depends:
94+ aeson >=1.0 && <1.5
95+ , base >=4.7 && <5
96+ , base-compat >=0.6.0
97+ , bytestring >=0.10.8.2 && <0.11
98+ , containers
99+ , directory
100+ , file-embed
101+ , filemanip
102+ , filepath
103+ , gitrev
104+ , monad-parallel >=0.7.2.2 && <0.8
105+ , mtl >=2.1.0 && <2.3.0
106+ , pattern-arrows >=0.0.2 && <0.1
107+ , process
108+ , protolude >=0.1.6
109+ , psgo
110+ , purescript
111+ , safe >=0.3.9 && <0.4
112+ , text
113+ , transformers >=0.3.0 && <0.6
114+ default-language: Haskell2010
115+
116+test-suite psgo-test
117+ type: exitcode-stdio-1.0
118+ main-is: Spec.hs
119+ other-modules:
120+ Paths_psgo
121+ hs-source-dirs:
122+ test
123+ ghc-options: -threaded -rtsopts -with-rtsopts=-N
124+ build-depends:
125+ aeson >=1.0 && <1.5
126+ , base >=4.7 && <5
127+ , base-compat >=0.6.0
128+ , bytestring >=0.10.8.2 && <0.11
129+ , containers
130+ , directory
131+ , file-embed
132+ , filemanip
133+ , filepath
134+ , gitrev
135+ , monad-parallel >=0.7.2.2 && <0.8
136+ , mtl >=2.1.0 && <2.3.0
137+ , pattern-arrows >=0.0.2 && <0.1
138+ , process
139+ , protolude >=0.1.6
140+ , psgo
141+ , purescript
142+ , safe >=0.3.9 && <0.4
143+ , text
144+ , transformers >=0.3.0 && <0.6
145+ default-language: Haskell2010
purescript.cabaldeleted−135
@@ -1,135 +0,0 @@
1−name: purescript
2−version: 0.4.16
3−cabal-version: >=1.8
4−build-type: Custom
5−license: MIT
6−license-file: LICENSE
7−copyright: (c) 2013-14 Phil Freeman, (c) 2014 Gary Burgess, and other contributors
8−maintainer: Phil Freeman <paf31@cantab.net>
9−stability: experimental
10−synopsis: PureScript Programming Language Compiler
11−description: A small compile-to-JS language with extensible records and type-safe blocks
12−category: Language
13−Homepage: http://www.purescript.org/
14−author: Phil Freeman <paf31@cantab.net>,
15− Gary Burgess <gary.burgess@gmail.com>,
16− Hardy Jones <jones3.hardy@gmail.com>
17−data-files: prelude/prelude.purs
18−data-dir: ""
19−
20−library
21− build-depends: base >=4 && <5, cmdtheline -any, containers -any,
22− directory >= 1.2, filepath -any, mtl -any, parsec -any, syb -any,
23− transformers -any, utf8-string -any,
24− pattern-arrows >= 0.0.2 && < 0.1,
25− monad-unify >= 0.2.1 && < 0.3,
26− xdg-basedir -any, time -any
27− if (!os(windows))
28− build-depends: unix -any
29− exposed-modules: Data.Generics.Extras
30− Language.PureScript
31− Language.PureScript.Constants
32− Language.PureScript.Options
33− Language.PureScript.Declarations
34− Language.PureScript.Environment
35− Language.PureScript.Errors
36− Language.PureScript.Kinds
37− Language.PureScript.Names
38− Language.PureScript.Types
39− Language.PureScript.Scope
40− Language.PureScript.TypeClassDictionaries
41− Language.PureScript.DeadCodeElimination
42− Language.PureScript.Sugar
43− Language.PureScript.ModuleDependencies
44− Language.PureScript.Sugar.CaseDeclarations
45− Language.PureScript.Sugar.DoNotation
46− Language.PureScript.Sugar.TypeDeclarations
47− Language.PureScript.Sugar.BindingGroups
48− Language.PureScript.Sugar.Operators
49− Language.PureScript.Sugar.TypeClasses
50− Language.PureScript.Sugar.Names
51− Language.PureScript.CodeGen
52− Language.PureScript.CodeGen.Common
53− Language.PureScript.CodeGen.Externs
54− Language.PureScript.CodeGen.JS
55− Language.PureScript.CodeGen.JS.AST
56− Language.PureScript.CodeGen.Monad
57− Language.PureScript.Optimizer
58− Language.PureScript.Optimizer.Common
59− Language.PureScript.Optimizer.MagicDo
60− Language.PureScript.Optimizer.TCO
61− Language.PureScript.Optimizer.Inliner
62− Language.PureScript.Optimizer.Unused
63− Language.PureScript.Optimizer.Blocks
64− Language.PureScript.Parser
65− Language.PureScript.Parser.Common
66− Language.PureScript.Parser.Declarations
67− Language.PureScript.Parser.Kinds
68− Language.PureScript.Parser.State
69− Language.PureScript.Parser.Types
70− Language.PureScript.Pretty
71− Language.PureScript.Pretty.Common
72− Language.PureScript.Pretty.JS
73− Language.PureScript.Pretty.Kinds
74− Language.PureScript.Pretty.Types
75− Language.PureScript.Pretty.Values
76− Language.PureScript.TypeChecker
77− Language.PureScript.TypeChecker.Kinds
78− Language.PureScript.TypeChecker.Monad
79− Language.PureScript.TypeChecker.Synonyms
80− Language.PureScript.TypeChecker.Types
81− exposed: True
82− buildable: True
83− hs-source-dirs: src
84− other-modules:
85− ghc-options: -Wall -O2
86−
87−executable psc
88− build-depends: base >=4 && <5, cmdtheline -any, containers -any,
89− directory -any, filepath -any, mtl -any, parsec -any,
90− purescript -any, syb -any, transformers -any, utf8-string -any
91− main-is: Main.hs
92− buildable: True
93− hs-source-dirs: psc
94− other-modules:
95− ghc-options: -Wall -O2 -fno-warn-unused-do-bind
96−
97−executable psc-make
98− build-depends: base >=4 && <5, cmdtheline -any, containers -any,
99− directory -any, filepath -any, mtl -any, parsec -any,
100− purescript -any, syb -any, transformers -any, utf8-string -any
101− main-is: Main.hs
102− buildable: True
103− hs-source-dirs: psc-make
104− other-modules:
105− ghc-options: -Wall -O2 -fno-warn-unused-do-bind
106−
107−executable psci
108− build-depends: base >=4 && <5, containers -any, directory -any, filepath -any,
109− mtl -any, parsec -any, haskeline -any, purescript -any,
110− syb -any, transformers -any, utf8-string -any, process -any,
111− xdg-basedir -any, cmdtheline -any
112− main-is: Main.hs
113− buildable: True
114− hs-source-dirs: psci
115− other-modules: Commands
116− Parser
117− ghc-options: -Wall -O2
118−
119−executable docgen
120− build-depends: base >=4 && <5, cmdtheline -any, purescript -any, utf8-string -any,
121− process -any, mtl -any
122− main-is: Main.hs
123− buildable: True
124− hs-source-dirs: docgen
125− other-modules:
126− ghc-options: -Wall -O2
127−
128−test-suite tests
129− build-depends: base >=4 && <5, containers -any, directory -any,
130− filepath -any, mtl -any, parsec -any, purescript -any, syb -any,
131− transformers -any, utf8-string -any, process -any
132− type: exitcode-stdio-1.0
133− main-is: Main.hs
134− buildable: True
135− hs-source-dirs: tests
src/CodeGen/IL.hsnew file+321
@@ -0,0 +1,321 @@
1+-- | This module generates code in the core imperative representation from
2+-- elaborated PureScript code.
3+module CodeGen.IL
4+ ( module AST
5+ , module Common
6+ , moduleToIL
7+ ) where
8+
9+import Prelude.Compat
10+import Protolude (ordNub)
11+
12+import Control.Arrow ((&&&))
13+import Control.Monad (forM, liftM, replicateM, void)
14+import Control.Monad.Supply.Class
15+
16+import Data.List ((\\), delete, intersect, nub)
17+import qualified Data.Foldable as F
18+import qualified Data.Map as M
19+import Data.Maybe (fromMaybe, isNothing, mapMaybe)
20+import Data.Monoid ((<>))
21+import Data.String (fromString)
22+import Data.Text (Text)
23+import qualified Data.Text as T
24+
25+import Language.PureScript.AST.SourcePos
26+import Language.PureScript.CoreImp.AST (AST)
27+import qualified Language.PureScript.CoreImp.AST as AST
28+import Language.PureScript.CoreFn
29+import Language.PureScript.Crash
30+import Language.PureScript.Names
31+import Language.PureScript.Options
32+import Language.PureScript.PSString (PSString, mkString)
33+import Language.PureScript.Traversals (sndM)
34+import qualified Language.PureScript.Constants as C
35+
36+import System.FilePath.Posix ((</>))
37+
38+import CodeGen.IL.Common as Common
39+import CodeGen.IL.Optimizer
40+import CodeGen.IL.Printer
41+
42+data DeclType = ModuleDecl | LetDecl | RecLetDecl deriving (Eq)
43+
44+-- | Generate code in the simplified intermediate representation for all declarations in a
45+-- module.
46+moduleToIL
47+ :: forall m
48+ -- . (Monad m, MonadReader Options m, MonadSupply m, MonadError MultipleErrors m)
49+ . (Monad m, MonadSupply m)
50+ => Module Ann
51+ -> Text
52+ -> m (Text, [Text], [AST], Text, Text)
53+moduleToIL (Module _ coms mn _ imps _ foreigns decls) project =
54+ do
55+ ilDecls <- mapM (bindToIL ModuleDecl) decls
56+ optimized <- traverse (traverse (optimize modName')) ilDecls
57+ let optimized' = concat optimized
58+ values = annotValue <$> optimized'
59+ foreigns' = moduleIdentToIL <$> foreigns
60+ interface = interfaceSource modName values foreigns
61+ imports = nub . concat $ importToIL <$> optimized'
62+ implHeader = implHeaderSource modName imports project
63+ implFooter = implFooterSource (runModuleName mn) foreigns
64+ return $ (interface, foreigns', optimized', implHeader, implFooter)
65+ where
66+ modName = moduleNameToIL mn
67+ modName' = AST.Var Nothing modName
68+
69+ annotValue :: AST -> (Text, Bool)
70+ annotValue (AST.Function _ (Just name) [] (AST.Block _ [AST.Return _ ret]))
71+ | isLiteral ret = (name, True)
72+ annotValue (AST.Function _ (Just name) [] _) = (name, False)
73+ annotValue _ = error "Unexpected top-level value form"
74+
75+ -- | Extracts all declaration names from a binding group.
76+ getNames :: Bind Ann -> [Ident]
77+ getNames (NonRec _ ident _) = [ident]
78+ getNames (Rec vals) = map (snd . fst) vals
79+
80+ -- | Generates IL code for a module import
81+ --
82+ importToIL :: AST -> [Text]
83+ importToIL = AST.everything (++) modRef
84+ where
85+ modRef (AST.Indexer _ (AST.Var _ _) (AST.Var _ mname))
86+ | not $ T.null mname = [extract mname]
87+ modRef _ = []
88+ extract :: Text -> Text
89+ extract = T.replace "_" "." . T.dropWhileEnd (=='_')
90+
91+ -- |
92+ -- Generate code in the simplified intermediate representation for a declaration
93+ --
94+ bindToIL :: DeclType -> Bind Ann -> m [AST]
95+ bindToIL dt (NonRec ann ident val) = return <$> nonRecToIL dt ann ident val
96+ bindToIL dt (Rec vals) = forM vals (uncurry . uncurry $ nonRecToIL dt')
97+ where
98+ dt' = if dt == LetDecl then RecLetDecl else dt
99+
100+ -- | Generate code in the simplified intermediate representation for a single non-recursive
101+ -- declaration.
102+ --
103+ -- The main purpose of this function is to handle code generation for comments.
104+ nonRecToIL :: DeclType -> Ann -> Ident -> Expr Ann -> m AST
105+ nonRecToIL dt a i e@(extractAnn -> (_, com, _, _)) | not (null com) = do
106+ -- withoutComment <- asks optionsNoComments
107+ let withoutComment = False
108+ if withoutComment
109+ then nonRecToIL dt a i (modifyAnn removeComments e)
110+ else AST.Comment Nothing com <$> nonRecToIL dt a i (modifyAnn removeComments e)
111+ nonRecToIL ModuleDecl (ss, _, _, _) ident val = do
112+ il <- valueToIL val
113+ pure $ AST.Function Nothing (Just $ moduleIdentToIL ident) [] (AST.Block Nothing [AST.Return Nothing il])
114+ nonRecToIL RecLetDecl (ss, _, _, _) ident val = do
115+ ilExpr <- valueToIL val
116+ pure $ AST.Assignment Nothing (AST.Var Nothing $ identToIL ident) ilExpr
117+ nonRecToIL _ (ss, _, _, _) ident val = do
118+ il <- valueToIL val
119+ pure $ AST.VariableIntroduction Nothing (identToIL ident) (Just il)
120+
121+ -- | Generate code in the simplified intermediate representation for a variable based on a
122+ -- PureScript identifier.
123+ var :: Ident -> AST
124+ var = AST.Var Nothing . identToIL
125+
126+ accessorString :: PSString -> AST -> AST
127+ accessorString prop = AST.Indexer Nothing (AST.StringLiteral Nothing prop)
128+
129+ -- | Generate code in the simplified intermediate representation for a value or expression.
130+
131+ valueToIL :: Expr Ann -> m AST
132+ valueToIL (Literal (pos, _, _, _) l) = literalToValueIL pos l
133+ valueToIL (Accessor _ prop val) =
134+ accessorString prop <$> valueToIL val
135+ valueToIL (ObjectUpdate _ o ps) = do
136+ obj <- valueToIL o
137+ updates <- mapM (sndM valueToIL) ps
138+ obj' <- freshName'
139+ let objVar = AST.Var Nothing obj'
140+ copy = AST.VariableIntroduction Nothing obj' (Just $ copyDict obj)
141+ assign (k, v) = AST.Assignment Nothing (accessorString k objVar) v
142+ sts = copy : (assign <$> updates) ++ [AST.Return Nothing objVar]
143+ return $ AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing sts)) []
144+ valueToIL (Abs _ arg val) = do
145+ ret <- valueToIL val
146+ let ilArg = case arg of
147+ UnusedIdent -> []
148+ _ -> [identToIL arg]
149+ return $ AST.Function Nothing Nothing ilArg (AST.Block Nothing [AST.Return Nothing ret])
150+ valueToIL e@App{} = do
151+ let (f, args) = unApp e []
152+ args' <- mapM valueToIL args
153+ fn <- valueToIL f
154+ case f of
155+ Var (_, _, _, Just IsNewtype) _ -> return (head args')
156+ _ -> flip (foldl (\fn a -> AST.App Nothing fn [a])) args' <$> valueToIL f
157+ where
158+ unApp :: Expr Ann -> [Expr Ann] -> (Expr Ann, [Expr Ann])
159+ unApp (App _ val arg) args = unApp val (arg : args)
160+ unApp other args = (other, args)
161+ valueToIL (Var _ ident) = return $ varToIL ident
162+ valueToIL (Case (ss, _, _, _) values binders) = do
163+ vals <- mapM valueToIL values
164+ bindersToIL ss binders vals
165+ valueToIL (Let _ ds val) = do
166+ let recurs = concatMap getNames $ filter isRec ds
167+ recurDs = (\v -> AST.VariableIntroduction Nothing (identToIL v) Nothing) <$> recurs
168+ ds' <- concat <$> mapM (bindToIL LetDecl) ds
169+ ret <- valueToIL val
170+ return $ AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing (recurDs ++ ds' ++ [AST.Return Nothing ret]))) []
171+ where
172+ isRec :: Bind Ann -> Bool
173+ isRec (Rec _) = True
174+ isRec _ = False
175+ valueToIL (Constructor (_, _, _, Just IsNewtype) _ (ProperName ctor) _) = error "IsNewtype"
176+ valueToIL (Constructor _ _ (ProperName ctor) fields) =
177+ let body = AST.ObjectLiteral Nothing $ (mkString ctor, AST.BooleanLiteral Nothing True) :
178+ ((\field -> (mkString (identToIL field), var field)) `map` fields)
179+ fn = foldr (\f inner -> AST.Function Nothing Nothing [identToIL f] (AST.Block Nothing [AST.Return Nothing inner])) body fields
180+ in return fn
181+
182+
183+ iife :: Text -> [AST] -> AST
184+ iife v exprs = AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing $ exprs ++ [AST.Return Nothing $ AST.Var Nothing v])) []
185+
186+ literalToValueIL :: SourceSpan -> Literal (Expr Ann) -> m AST
187+ literalToValueIL ss (NumericLiteral (Left i)) = return $ AST.NumericLiteral (Just ss) (Left i)
188+ literalToValueIL ss (NumericLiteral (Right n)) = return $ AST.NumericLiteral (Just ss) (Right n)
189+ literalToValueIL ss (StringLiteral s) = return $ AST.StringLiteral (Just ss) s
190+ literalToValueIL ss (CharLiteral c) = return $ AST.StringLiteral (Just ss) (fromString [c])
191+ literalToValueIL ss (BooleanLiteral b) = return $ AST.BooleanLiteral (Just ss) b
192+ literalToValueIL ss (ArrayLiteral xs) = AST.ArrayLiteral (Just ss) <$> mapM valueToIL xs
193+ literalToValueIL ss (ObjectLiteral ps) = AST.ObjectLiteral (Just ss) <$> mapM (sndM valueToIL) ps
194+
195+ -- | Generate code in the simplified intermediate representation for a reference to a
196+ -- variable.
197+ varToIL :: Qualified Ident -> AST
198+ varToIL (Qualified Nothing ident) = var ident
199+ varToIL qual = qualifiedToIL id qual
200+
201+ -- | Generate code in the simplified intermediate representation for a reference to a
202+ -- variable that may have a qualified name.
203+ qualifiedToIL :: (a -> Ident) -> Qualified a -> AST
204+ qualifiedToIL f (Qualified (Just (ModuleName mn')) a) | mn' == C.prim = AST.Var Nothing . moduleIdentToIL $ f a
205+ qualifiedToIL f (Qualified (Just mn') a) | mn /= mn' = AST.Indexer Nothing (AST.Var Nothing . moduleIdentToIL $ f a) (AST.Var Nothing (moduleNameToIL mn'))
206+ qualifiedToIL f (Qualified _ a) = AST.Indexer Nothing (AST.Var Nothing . moduleIdentToIL $ f a) (AST.Var Nothing "")
207+
208+ -- foreignIdent :: Ident -> AST
209+ -- foreignIdent ident = accessorString (mkString $ runIdent ident) (AST.Var Nothing "$foreign")
210+
211+ -- | Generate code in the simplified intermediate representation for pattern match binders
212+ -- and guards.
213+ bindersToIL :: SourceSpan -> [CaseAlternative Ann] -> [AST] -> m AST
214+ bindersToIL ss binders vals = do
215+ valNames <- replicateM (length vals) freshName'
216+ let assignments = zipWith (AST.VariableIntroduction Nothing) valNames (map Just vals)
217+ ils <- forM binders $ \(CaseAlternative bs result) -> do
218+ ret <- guardsToIL result
219+ go valNames ret bs
220+ return $ AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing (assignments ++ concat ils ++ [AST.Throw Nothing (AST.StringLiteral Nothing $ mkString failedPatternMessage)])))
221+ []
222+ where
223+ go :: [Text] -> [AST] -> [Binder Ann] -> m [AST]
224+ go _ done [] = return done
225+ go (v:vs) done' (b:bs) = do
226+ done'' <- go vs done' bs
227+ binderToIL v done'' b
228+ go _ _ _ = internalError "Invalid arguments to bindersToIL"
229+
230+ failedPatternMessage :: Text
231+ failedPatternMessage = "Failed pattern match at " <> runModuleName mn <> " " <> displayStartEndPos ss
232+
233+ guardsToIL :: Either [(Guard Ann, Expr Ann)] (Expr Ann) -> m [AST]
234+ guardsToIL (Left gs) = traverse genGuard gs where
235+ genGuard (cond, val) = do
236+ cond' <- valueToIL cond
237+ val' <- valueToIL val
238+ return
239+ (AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo cond' (AST.BooleanLiteral Nothing True))
240+ (AST.Block Nothing [AST.Return Nothing val']) Nothing)
241+
242+ guardsToIL (Right v) = return . AST.Return Nothing <$> valueToIL v
243+
244+ -- | Generate code in the simplified intermediate representation for a pattern match
245+ -- binder.
246+ binderToIL :: Text -> [AST] -> Binder Ann -> m [AST]
247+ binderToIL _ done NullBinder{} = return done
248+ binderToIL varName done (LiteralBinder _ l) =
249+ literalToBinderIL varName done l
250+ binderToIL varName done (VarBinder _ ident) =
251+ return (AST.VariableIntroduction Nothing (identToIL ident) (Just (AST.Var Nothing varName)) : done)
252+ binderToIL varName done (ConstructorBinder (_, _, _, Just IsNewtype) _ _ [b]) =
253+ binderToIL varName done b
254+ binderToIL varName done (ConstructorBinder (_, _, _, Just (IsConstructor ctorType fields)) _ (Qualified _ (ProperName ctor)) bs) = do
255+ il <- go (zip fields bs) done
256+ return $ case ctorType of
257+ ProductType -> il
258+ SumType ->
259+ [AST.IfElse Nothing (AST.InstanceOf Nothing (AST.Var Nothing varName) (AST.StringLiteral Nothing (mkString ctor)))
260+ (AST.Block Nothing il)
261+ Nothing]
262+ where
263+ go :: [(Ident, Binder Ann)] -> [AST] -> m [AST]
264+ go [] done' = return done'
265+ go ((field, binder) : remain) done' = do
266+ argVar <- freshName'
267+ done'' <- go remain done'
268+ il <- binderToIL argVar done'' binder
269+ return (AST.VariableIntroduction Nothing argVar (Just $ accessorString (mkString $ identToIL field) $ AST.Var Nothing varName) : il)
270+
271+ binderToIL _ _ ConstructorBinder{} =
272+ internalError "binderToIL: Invalid ConstructorBinder in binderToIL"
273+ binderToIL varName done (NamedBinder _ ident binder) = do
274+ il <- binderToIL varName done binder
275+ return (AST.VariableIntroduction Nothing (identToIL ident) (Just (AST.Var Nothing varName)) : il)
276+
277+ literalToBinderIL :: Text -> [AST] -> Literal (Binder Ann) -> m [AST]
278+ literalToBinderIL varName done (NumericLiteral num) =
279+ return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.NumericLiteral Nothing num)) (AST.Block Nothing done) Nothing]
280+ literalToBinderIL varName done (CharLiteral c) =
281+ return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.StringLiteral Nothing (fromString [c]))) (AST.Block Nothing done) Nothing]
282+ literalToBinderIL varName done (StringLiteral str) =
283+ return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.StringLiteral Nothing str)) (AST.Block Nothing done) Nothing]
284+ literalToBinderIL varName done (BooleanLiteral True) =
285+ return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.BooleanLiteral Nothing True)) (AST.Block Nothing done) Nothing]
286+ literalToBinderIL varName done (BooleanLiteral False) =
287+ return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.BooleanLiteral Nothing False)) (AST.Block Nothing done) Nothing]
288+ -- return [AST.IfElse Nothing (AST.Unary Nothing AST.Not (AST.Var Nothing varName)) (AST.Block Nothing done) Nothing]
289+ literalToBinderIL varName done (ObjectLiteral bs) = go done bs
290+ where
291+ go :: [AST] -> [(PSString, Binder Ann)] -> m [AST]
292+ go done' [] = return done'
293+ go done' ((prop, binder):bs') = do
294+ propVar <- freshName'
295+ done'' <- go done' bs'
296+ il <- binderToIL propVar done'' binder
297+ return (AST.VariableIntroduction Nothing propVar (Just (accessorString prop (AST.Var Nothing varName))) : il)
298+ literalToBinderIL varName done (ArrayLiteral bs) = do
299+ il <- go done 0 bs
300+ return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo
301+ (arrayLength $ AST.Var Nothing varName)
302+ (AST.NumericLiteral Nothing (Left (fromIntegral $ length bs))))
303+ (AST.Block Nothing il) Nothing]
304+ where
305+ go :: [AST] -> Integer -> [Binder Ann] -> m [AST]
306+ go done' _ [] = return done'
307+ go done' index (binder:bs') = do
308+ elVar <- freshName'
309+ done'' <- go done' (index + 1) bs'
310+ il <- binderToIL elVar done'' binder
311+ return (AST.VariableIntroduction Nothing elVar (Just (AST.Indexer Nothing (AST.NumericLiteral Nothing (Left index)) (AST.Var Nothing varName))) : il)
312+
313+emptyAnn :: Ann
314+emptyAnn = (SourceSpan "" (SourcePos 0 0) (SourcePos 0 0), [], Nothing, Nothing)
315+
316+arrayLength :: AST -> AST
317+arrayLength a = AST.App Nothing (AST.Var Nothing arrayLengthFn) [a]
318+-- arrayLength a = AST.Var Nothing (arrayLengthFn <> "(" <> prettyPrintIL1 a <> ")")
319+
320+copyDict :: AST -> AST
321+copyDict a = AST.App Nothing (AST.Var Nothing copyDictFn) [a]
src/CodeGen/IL/Common.hsnew file+196
@@ -0,0 +1,196 @@
1+-- | Common code generation utility functions
2+module CodeGen.IL.Common where
3+
4+import Prelude.Compat
5+
6+import Control.Monad.Supply.Class (MonadSupply, freshName)
7+import Data.Char
8+import Data.Maybe (maybe)
9+import Data.Monoid ((<>))
10+import Data.Text (Text)
11+import qualified Data.Text as T
12+
13+import Language.PureScript.Crash
14+import Language.PureScript.Names
15+
16+import qualified Language.PureScript.Constants as C
17+
18+moduleNameToIL :: ModuleName -> Text
19+moduleNameToIL (ModuleName mn) =
20+ let name = T.replace "." "_" mn
21+ in if nameIsILBuiltIn name then (name <> moduleRenamerMarker) else name
22+
23+moduleNameToIL' :: ModuleName -> Text
24+moduleNameToIL' (ModuleName mn) = T.replace "_" "." mn
25+
26+-- | Convert an 'Ident' into a valid IL identifier:
27+--
28+-- * Alphanumeric characters are kept unmodified.
29+--
30+-- * Reserved IL identifiers are wrapped with '_'.
31+--
32+identToIL :: Ident -> Text
33+identToIL UnusedIdent = unusedName
34+identToIL (Ident "$__unused") = unusedName
35+identToIL (Ident name) | name == C.undefined = undefinedName -- Note: done in Printer.hs too
36+identToIL (Ident name) = properToIL name
37+identToIL (GenIdent _ _) = internalError "GenIdent in identToIL"
38+
39+moduleIdentToIL :: Ident -> Text
40+moduleIdentToIL UnusedIdent = unusedName
41+moduleIdentToIL (Ident name) | name == C.undefined = undefinedName
42+moduleIdentToIL (Ident name) = moduleProperToIL name
43+moduleIdentToIL (GenIdent _ _) = internalError "GenIdent in identToIL"
44+
45+undefinedName :: Text
46+undefinedName = "Undefined"
47+
48+unusedName :: Text
49+unusedName = "_"
50+
51+properToIL :: Text -> Text
52+properToIL name
53+ | nameIsILReserved name = "ˉ" <> name
54+ | otherwise = T.concatMap identCharToText name
55+
56+-- | Attempts to find a human-readable name for a symbol, if none has been specified returns the
57+-- ordinal value.
58+identCharToText :: Char -> Text
59+identCharToText 'ṩ' = "_ṩ"
60+identCharToText c | isAlphaNum c = T.singleton c
61+identCharToText '_' = "_"
62+identCharToText '\'' = "ꞌ" -- lowercase saltillo
63+identCharToText c = error (show (ord c)) -- TODO: should never occur now(?)
64+
65+moduleProperToIL :: Text -> Text
66+moduleProperToIL = T.concatMap identCharToText
67+
68+-- | Checks whether an identifier name is reserved in IL.
69+nameIsILReserved :: Text -> Bool
70+nameIsILReserved name =
71+ name `elem` ilAnyReserved
72+
73+-- | Checks whether a name matches a built-in value in IL.
74+nameIsILBuiltIn :: Text -> Bool
75+nameIsILBuiltIn name =
76+ name `elem`
77+ [ "Any"
78+ , "Apply"
79+ , "Contains"
80+ , "CopyDict"
81+ , "Dict"
82+ , "EffFn"
83+ , "Fn"
84+ , "Foreign"
85+ , "Get"
86+ , "Index"
87+ , "Is"
88+ , "Length"
89+ , "Once"
90+ , "Run"
91+ , "Undefined"
92+ ]
93+
94+ilAnyReserved :: [Text]
95+ilAnyReserved =
96+ concat
97+ [ ilKeywords
98+ , ilLiterals
99+ ]
100+
101+ilKeywords :: [Text]
102+ilKeywords =
103+ [ "break"
104+ , "case"
105+ , "chan"
106+ , "const"
107+ , "continue"
108+ , "default"
109+ , "defer"
110+ , "else"
111+ , "fallthrough"
112+ , "for"
113+ , "func"
114+ , "go"
115+ , "goto"
116+ , "if"
117+ , "import"
118+ , "interface"
119+ , "map"
120+ , "package"
121+ , "range"
122+ , "return"
123+ , "select"
124+ , "struct"
125+ , "switch"
126+ , "type"
127+ , "var"
128+ ]
129+
130+ilLiterals :: [Text]
131+ilLiterals =
132+ [ "init"
133+ , "nil"
134+ , "int"
135+ , "int8"
136+ , "int16"
137+ , "int32"
138+ , "int64"
139+ , "uint"
140+ , "uint8"
141+ , "uint16"
142+ , "uint32"
143+ , "uint64"
144+ , "uintptr"
145+ , "float32"
146+ , "float64"
147+ , "complex64"
148+ , "complex128"
149+ , "byte"
150+ , "rune"
151+ , "string"
152+ ]
153+
154+withPrefix :: Text -> Text
155+withPrefix s = "Ꞌ" <> s -- uppercase saltillo
156+
157+anyType :: Text
158+anyType = "Any"
159+
160+dictType :: Text
161+dictType = "Dict"
162+
163+arrayType :: Text
164+arrayType = "[]" <> anyType
165+
166+uncurriedFnType :: Int -> Text
167+uncurriedFnType i = "Fn" <> (T.pack . show $ i)
168+
169+int :: Text
170+int = "int"
171+
172+float :: Text
173+float = "float64"
174+
175+bool :: Text
176+bool = "bool"
177+
178+string :: Text
179+string = "string"
180+
181+arrayLengthFn :: Text
182+arrayLengthFn = "Length"
183+
184+indexFn :: Text
185+indexFn = "Index"
186+
187+copyDictFn :: Text
188+copyDictFn = "CopyDict"
189+
190+freshName' :: MonadSupply m => m Text
191+freshName' = do
192+ name <- freshName
193+ return $ T.replace "$" "ṩ" name
194+
195+moduleRenamerMarker :: Text
196+moduleRenamerMarker = "__"
src/CodeGen/IL/Optimizer.hsnew file+81
@@ -0,0 +1,81 @@
1+-- | This module optimizes code in the intermediate representation.
2+module CodeGen.IL.Optimizer (optimize) where
3+
4+import Prelude.Compat
5+
6+import Control.Monad.Supply.Class (MonadSupply)
7+import Data.Text (Text)
8+import Language.PureScript.CoreImp.AST
9+import Language.PureScript.CoreImp.Optimizer.Blocks
10+import Language.PureScript.CoreImp.Optimizer.Common hiding (isDict)
11+import Language.PureScript.CoreImp.Optimizer.Inliner (etaConvert, evaluateIifes, inlineVariables, unThunk)
12+import Language.PureScript.CoreImp.Optimizer.Unused
13+
14+import CodeGen.IL.Common (unusedName)
15+import CodeGen.IL.Optimizer.Inliner
16+import CodeGen.IL.Optimizer.MagicDo
17+import CodeGen.IL.Optimizer.TCO
18+
19+import qualified Language.PureScript.Constants as C
20+
21+-- | Apply a series of optimizer passes to simplified IL code
22+optimize :: MonadSupply m => AST -> AST -> m AST
23+optimize mn il = do
24+ il' <- untilFixedPoint (inlineFnComposition . inlineUnsafeCoerce . inlineUnsafePartial . tidyUp) il
25+ il'' <- untilFixedPoint (return . ignoreUnusedResults . inlineCommonValues . inlineCommonOperators . tidyUp) . tco mn . inlineST
26+ =<< untilFixedPoint (return . magicDoST)
27+ =<< untilFixedPoint (return . magicDoEff)
28+ =<< untilFixedPoint (return . magicDoEffect) il'
29+ untilFixedPoint (return . collapseVarDeclarations) il''
30+ where
31+ tidyUp :: AST -> AST
32+ tidyUp = applyAll
33+ [ collapseNestedBlocks
34+ , collapseNestedIfs
35+ , collapseIfChecks
36+ , removeCodeAfterReturnStatements
37+ , unThunk
38+ , etaConvert
39+ , evaluateIifes
40+ , inlineVariables
41+ ]
42+
43+untilFixedPoint :: (Monad m, Eq a) => (a -> m a) -> a -> m a
44+untilFixedPoint f = go
45+ where
46+ go a = do
47+ a' <- f a
48+ if a' == a then return a' else go a'
49+
50+collapseIfChecks :: AST -> AST
51+collapseIfChecks = everywhere collapse where
52+ collapse :: AST -> AST
53+ collapse (IfElse _ (Binary _ EqualTo (BooleanLiteral _ True) (BooleanLiteral _ True)) (Block _ [exprs]) _) = exprs
54+ collapse (IfElse _ (Binary _ EqualTo (Indexer _ (Var _ prop) (Var _ val)) (BooleanLiteral _ True)) (Block _ [exprs]) _)
55+ | prop == "otherwise" && val == "Data_Boolean" = exprs
56+ collapse exprs = exprs
57+
58+collapseVarDeclarations :: AST -> AST
59+collapseVarDeclarations = everywhere collapse where
60+ collapse :: AST -> AST
61+ collapse (Block ss sts) = Block ss (go Nothing sts)
62+ collapse s = s
63+
64+ go :: Maybe Text -> [AST] -> [AST]
65+ go _ [] = []
66+ go Nothing (decl@(VariableIntroduction _ var (Just _)) : sts) = decl : go (Just var) (go Nothing sts)
67+ go (Just var') ((VariableIntroduction ss var (Just val)) : sts)
68+ | var == var' = (Assignment ss (Var Nothing var) val) : go (Just var') sts
69+ go var' (s:sts) = s : go var' sts
70+
71+ignoreUnusedResults :: AST -> AST
72+ignoreUnusedResults = everywhere $ removeFromBlock go
73+ where
74+ go :: [AST] -> [AST]
75+ go [] = []
76+ go (VariableIntroduction ss var (Just s) : sts)
77+ | not $ any (everything (||) (isUsed var)) sts = sts'
78+ where
79+ sts' | App{} <- s = s : (go sts)
80+ | otherwise = go sts
81+ go (s:sts) = s : go sts
src/CodeGen/IL/Optimizer/Common.hsnew file+18
@@ -0,0 +1,18 @@
1+-- | Common functions used by the various optimizer phases
2+module CodeGen.IL.Optimizer.Common where
3+
4+import Prelude.Compat
5+
6+import Data.Text (Text)
7+
8+import Language.PureScript.CoreImp.AST
9+import Language.PureScript.PSString (PSString, decodeString)
10+
11+isDict :: (Text, PSString) -> AST -> Bool
12+isDict (moduleName, dictName) (Indexer _ (Var _ x) (Var _ y)) =
13+ Just x == decodeString dictName && y == moduleName
14+isDict _ _ = False
15+
16+isDict' :: [(Text, PSString)] -> AST -> Bool
17+isDict' xs il = any (`isDict` il) xs
18+
src/CodeGen/IL/Optimizer/Inliner.hsnew file+435
@@ -0,0 +1,435 @@
1+-- | This module performs basic inlining of known functions
2+module CodeGen.IL.Optimizer.Inliner
3+ ( inlineCommonValues
4+ , inlineCommonOperators
5+ , inlineFnComposition
6+ , inlineUnsafeCoerce
7+ , inlineUnsafePartial
8+ ) where
9+
10+import Prelude.Compat
11+
12+import Control.Monad.Supply.Class (MonadSupply)
13+
14+import Data.Either (rights)
15+import Data.Maybe (fromMaybe)
16+import Data.String (IsString, fromString)
17+import Data.Text (Text)
18+import qualified Data.Text as T
19+
20+import Language.PureScript.PSString (PSString, decodeString, mkString)
21+import Language.PureScript.CoreImp.AST
22+import Language.PureScript.CoreImp.Optimizer.Common hiding (isDict, isDict')
23+import Language.PureScript.AST (SourceSpan(..))
24+import qualified Language.PureScript.Constants as C
25+
26+import CodeGen.IL.Common
27+import CodeGen.IL.Optimizer.Common
28+
29+-- TODO: Potential bug:
30+-- Shouldn't just inline this case: { var x = 0; x.toFixed(10); }
31+-- Needs to be: { 0..toFixed(10); }
32+-- Probably needs to be fixed in pretty-printer instead.
33+shouldInline :: AST -> Bool
34+shouldInline (Var _ _) = True
35+shouldInline (NumericLiteral _ _) = True
36+shouldInline (StringLiteral _ _) = True
37+shouldInline (BooleanLiteral _ _) = True
38+shouldInline (Indexer _ index val) = shouldInline index && shouldInline val
39+shouldInline _ = False
40+
41+inlineCommonValues :: AST -> AST
42+inlineCommonValues = everywhere convert
43+ where
44+ convert :: AST -> AST
45+ convert (App ss fn [dict])
46+ | isDict' [semiringNumber, semiringInt] dict && isDict fnZero fn = NumericLiteral ss (Left 0)
47+ | isDict' [semiringNumber, semiringInt] dict && isDict fnOne fn = NumericLiteral ss (Left 1)
48+ | isDict boundedBoolean dict && isDict fnBottom fn = BooleanLiteral ss False
49+ | isDict boundedBoolean dict && isDict fnTop fn = BooleanLiteral ss True
50+ convert (App ss (App _ fn [dict]) [x])
51+ | isDict ringInt dict && isDict fnNegate fn = Unary ss Negate (unbox x $ snd ringInt)
52+ convert (App ss (App _ (App _ fn [dict]) [x]) [y])
53+ | isDict semiringInt dict && isDict fnAdd fn = intOp ss Add semiringInt x y
54+ | isDict semiringInt dict && isDict fnMultiply fn = intOp ss Multiply semiringInt x y
55+ | isDict ringInt dict && isDict fnSubtract fn = intOp ss Subtract ringInt x y
56+ convert other = other
57+ fnZero = (C.dataSemiring, C.zero)
58+ fnOne = (C.dataSemiring, C.one)
59+ fnBottom = (C.dataBounded, C.bottom)
60+ fnTop = (C.dataBounded, C.top)
61+ fnAdd = (C.dataSemiring, C.add)
62+ fnMultiply = (C.dataSemiring, C.mul)
63+ fnSubtract = (C.dataRing, C.sub)
64+ fnNegate = (C.dataRing, C.negate)
65+ intOp ss op (_, d) x y = Binary ss op (unbox x d) (unbox y d)
66+
67+inlineCommonOperators :: AST -> AST
68+inlineCommonOperators = everywhereTopDown $ applyAll $
69+ [ binary semiringNumber opAdd Add
70+ , binary semiringNumber opMul Multiply
71+
72+ , binary ringNumber opSub Subtract
73+ , unary ringNumber opNegate Negate
74+
75+ , binary euclideanRingNumber opDiv Divide
76+
77+ -- , binary eqNumber opEq EqualTo
78+ -- , binary eqNumber opNotEq NotEqualTo
79+ , binary eqInt opEq EqualTo
80+ , binary eqInt opNotEq NotEqualTo
81+ , binary eqString opEq EqualTo
82+ , binary eqString opNotEq NotEqualTo
83+ , binary eqChar opEq EqualTo
84+ , binary eqChar opNotEq NotEqualTo
85+ , binary eqBoolean opEq EqualTo
86+ , binary eqBoolean opNotEq NotEqualTo
87+
88+ , binary ordBoolean opLessThan LessThan
89+ , binary ordBoolean opLessThanOrEq LessThanOrEqualTo
90+ , binary ordBoolean opGreaterThan GreaterThan
91+ , binary ordBoolean opGreaterThanOrEq GreaterThanOrEqualTo
92+ , binary ordChar opLessThan LessThan
93+ , binary ordChar opLessThanOrEq LessThanOrEqualTo
94+ , binary ordChar opGreaterThan GreaterThan
95+ , binary ordChar opGreaterThanOrEq GreaterThanOrEqualTo
96+ , binary ordInt opLessThan LessThan
97+ , binary ordInt opLessThanOrEq LessThanOrEqualTo
98+ , binary ordInt opGreaterThan GreaterThan
99+ , binary ordInt opGreaterThanOrEq GreaterThanOrEqualTo
100+ , binary ordNumber opLessThan LessThan
101+ , binary ordNumber opLessThanOrEq LessThanOrEqualTo
102+ , binary ordNumber opGreaterThan GreaterThan
103+ , binary ordNumber opGreaterThanOrEq GreaterThanOrEqualTo
104+ , binary ordString opLessThan LessThan
105+ , binary ordString opLessThanOrEq LessThanOrEqualTo
106+ , binary ordString opGreaterThan GreaterThan
107+ , binary ordString opGreaterThanOrEq GreaterThanOrEqualTo
108+
109+ , binary semigroupString opAppend Add
110+
111+ , binary heytingAlgebraBoolean opConj And
112+ , binary heytingAlgebraBoolean opDisj Or
113+ , unary heytingAlgebraBoolean opNot Not
114+
115+ , binary' C.dataIntBits C.or BitwiseOr
116+ , binary' C.dataIntBits C.and BitwiseAnd
117+ , binary' C.dataIntBits C.xor BitwiseXor
118+ , binary' C.dataIntBits C.shl ShiftLeft
119+ , binary' C.dataIntBits C.shr ShiftRight
120+ , unary' C.dataIntBits C.complement BitwiseNot
121+
122+ , inlineNonClassFunction (isModFn (C.dataFunction, C.apply)) $ \f x -> App Nothing f [x]
123+ , inlineNonClassFunction (isModFn (C.dataFunction, C.applyFlipped)) $ \x f -> App Nothing f [x]
124+ , inlineUnsafeIndex (isModFnWithDict (C.dataArray, C.unsafeIndex)) $ flip (Indexer Nothing)
125+ ] ++
126+ [ fn | i <- [0..10], fn <- [ mkFn i, runFn i ] ] ++
127+ [ fn | i <- [0..10], fn <- [ mkEffFn C.controlMonadEffUncurried C.mkEffFn i, runEffFn C.controlMonadEffUncurried C.runEffFn i ] ] ++
128+ [ fn | i <- [0..10], fn <- [ mkEffFn C.effectUncurried C.mkEffectFn i, runEffFn C.effectUncurried C.runEffectFn i ] ]
129+ where
130+ binary :: (Text, PSString) -> (Text, PSString) -> BinaryOperator -> AST -> AST
131+ binary dict@(_, d) fns op = convert where
132+ convert :: AST -> AST
133+ convert (App ss (App _ (App _ fn [dict']) [x]) [y])
134+ | isDict dict dict' && isDict fns fn = Binary ss op (unbox x d) (unbox y d)
135+ convert other = other
136+ binary' :: Text -> PSString -> BinaryOperator -> AST -> AST
137+ binary' moduleName opString op = convert where
138+ convert :: AST -> AST
139+ convert (App ss (App _ fn [x]) [y]) | isDict (moduleName, opString) fn = Binary ss op (unbox x mn) (unbox y mn)
140+ convert other = other
141+ mn :: PSString
142+ mn = mkString moduleName
143+ unary :: (Text, PSString) -> (Text, PSString) -> UnaryOperator -> AST -> AST
144+ unary dicts@(_, d) fns op = convert where
145+ convert :: AST -> AST
146+ convert (App ss (App _ fn [dict']) [x]) | isDict dicts dict' && isDict fns fn = Unary ss op (unbox x d)
147+ convert other = other
148+ unary' :: Text -> PSString -> UnaryOperator -> AST -> AST
149+ unary' moduleName fnName op = convert where
150+ convert :: AST -> AST
151+ convert (App ss fn [x]) | isDict (moduleName, fnName) fn = Unary ss op (unbox x fnName)
152+ convert other = other
153+
154+ mkFn :: Int -> AST -> AST
155+ mkFn = mkFn' C.dataFunctionUncurried C.mkFn $ \ss1 ss2 ss3 args il ->
156+ Function ss1 Nothing args (Block ss2 [Return ss3 il])
157+
158+ mkEffFn :: Text -> Text -> Int -> AST -> AST
159+ mkEffFn modName fnName = mkFn' modName fnName $ \ss1 ss2 ss3 args il ->
160+ Function ss1 Nothing args (Block ss2 [Return ss3 (App ss3 il [])])
161+
162+ mkFn' :: Text -> Text -> (Maybe SourceSpan -> Maybe SourceSpan -> Maybe SourceSpan -> [Text] -> AST -> AST) -> Int -> AST -> AST
163+ mkFn' modName fnName res 0 = convert where
164+ convert :: AST -> AST
165+ convert (App _ mkFnN [Function s1 Nothing [_] (Block s2 [Return s3 il])]) | isNFn modName fnName 0 mkFnN =
166+ res s1 s2 s3 [] il
167+ convert other = other
168+ mkFn' modName fnName res n = convert where
169+ convert :: AST -> AST
170+ convert orig@(App ss mkFnN [fn]) | isNFn modName fnName n mkFnN =
171+ case collectArgs n [] fn of
172+ Just (args, [Return ss' ret]) -> res ss ss ss' args ret
173+ _ -> orig
174+ convert other = other
175+ collectArgs :: Int -> [Text] -> AST -> Maybe ([Text], [AST])
176+ collectArgs 1 acc (Function _ Nothing [oneArg] (Block _ il)) | length acc == n - 1 = Just (reverse (oneArg : acc), il)
177+ collectArgs m acc (Function _ Nothing [oneArg] (Block _ [Return _ ret])) = collectArgs (m - 1) (oneArg : acc) ret
178+ collectArgs _ _ _ = Nothing
179+
180+ isNFn :: Text -> Text -> Int -> AST -> Bool
181+ isNFn expectMod prefix n (Indexer _ (Var _ name) (Var _ modName)) | modName == expectMod =
182+ name == fromString (T.unpack prefix <> show n)
183+ isNFn _ _ _ _ = False
184+
185+ runFn :: Int -> AST -> AST
186+ runFn = runFn' C.dataFunctionUncurried C.runFn (\ss f args ->
187+ let len = length args
188+ typ = mkString $ uncurriedFnType len in
189+ if len > 0
190+ then App ss (App Nothing (StringLiteral Nothing typ) [f]) args
191+ else App ss f args)
192+ runEffFn :: Text -> Text -> Int -> AST -> AST
193+ runEffFn modName fnName = runFn' modName fnName $ \ss fn acc ->
194+ let typ = mkString . uncurriedFnType $ length acc in
195+ Function ss Nothing [] (Block ss [Return ss (App ss (App Nothing (StringLiteral Nothing typ) [fn]) acc)])
196+
197+ runFn' :: Text -> Text -> (Maybe SourceSpan -> AST -> [AST] -> AST) -> Int -> AST -> AST
198+ runFn' modName runFnName res n = convert where
199+ convert :: AST -> AST
200+ convert il = fromMaybe il $ go n [] il
201+
202+ go :: Int -> [AST] -> AST -> Maybe AST
203+ go 0 acc (App ss runFnN [fn]) | isNFn modName runFnName n runFnN && length acc == n =
204+ Just $ res ss fn acc
205+ go m acc (App _ lhs [arg]) = go (m - 1) (arg : acc) lhs
206+ go _ _ _ = Nothing
207+
208+ inlineNonClassFunction :: (AST -> Bool) -> (AST -> AST -> AST) -> AST -> AST
209+ inlineNonClassFunction p f = convert where
210+ convert :: AST -> AST
211+ convert (App _ (App _ op' [x]) [y]) | p op' = f x y
212+ convert other = other
213+
214+ inlineUnsafeIndex :: (AST -> Bool) -> (AST -> AST -> AST) -> AST -> AST
215+ inlineUnsafeIndex p _ = convert where
216+ convert :: AST -> AST
217+ convert (App _ (App ss op' [x]) [y@NumericLiteral{}])
218+ | p op' = Indexer ss y x
219+ convert (App _ (App ss op' [x]) [y])
220+ | p op' = App ss (Var Nothing indexFn) [x, y]
221+ convert other = other
222+
223+ isModFn :: (Text, PSString) -> AST -> Bool
224+ isModFn (m, op) (Indexer _ (Var _ op') (Var _ m')) =
225+ m == m' && decodeString op == Just op'
226+ isModFn _ _ = False
227+
228+ isModFnWithDict :: (Text, PSString) -> AST -> Bool
229+ isModFnWithDict (m, op) (App _ (Indexer _ (Var _ op') (Var _ m')) [Var _ _]) =
230+ m == m' && decodeString op == Just op'
231+ isModFnWithDict _ _ = False
232+
233+-- (f <<< g $ x) = f (g x)
234+-- (f <<< g) = \x -> f (g x)
235+inlineFnComposition :: forall m. MonadSupply m => AST -> m AST
236+inlineFnComposition = everywhereTopDownM convert where
237+ convert :: AST -> m AST
238+ convert (App s1 (App s2 (App _ (App _ fn [dict']) [x]) [y]) [z])
239+ | isFnCompose dict' fn = return $ App s1 x [App s2 y [z]]
240+ | isFnComposeFlipped dict' fn = return $ App s2 y [App s1 x [z]]
241+ convert app@(App ss (App _ (App _ fn [dict']) _) _)
242+ | isFnCompose dict' fn || isFnComposeFlipped dict' fn = mkApps ss <$> goApps app <*> freshName'
243+ convert other = return other
244+
245+ mkApps :: Maybe SourceSpan -> [Either AST (Text, AST)] -> Text -> AST
246+ mkApps ss fns a = App ss (Function ss Nothing [] (Block ss $ vars <> [Return Nothing comp])) []
247+ where
248+ vars = uncurry (VariableIntroduction ss) . fmap Just <$> rights fns
249+ comp = Function ss Nothing [a] (Block ss [Return Nothing apps])
250+ apps = foldr (\fn acc -> App ss (mkApp fn) [acc]) (Var ss a) fns
251+
252+ mkApp :: Either AST (Text, AST) -> AST
253+ mkApp = either id $ \(name, arg) -> Var (getSourceSpan arg) name
254+
255+ goApps :: AST -> m [Either AST (Text, AST)]
256+ goApps (App _ (App _ (App _ fn [dict']) [x]) [y])
257+ | isFnCompose dict' fn = mappend <$> goApps x <*> goApps y
258+ | isFnComposeFlipped dict' fn = mappend <$> goApps y <*> goApps x
259+ goApps app@(App {}) = pure . Right . (,app) <$> freshName'
260+ goApps other = pure [Left other]
261+
262+ isFnCompose :: AST -> AST -> Bool
263+ isFnCompose dict' fn = isDict semigroupoidFn dict' && isDict fnCompose fn
264+
265+ isFnComposeFlipped :: AST -> AST -> Bool
266+ isFnComposeFlipped dict' fn = isDict semigroupoidFn dict' && isDict fnComposeFlipped fn
267+
268+ fnCompose :: forall a b. (IsString a, IsString b) => (a, b)
269+ fnCompose = (C.controlSemigroupoid, C.compose)
270+
271+ fnComposeFlipped :: forall a b. (IsString a, IsString b) => (a, b)
272+ fnComposeFlipped = (C.controlSemigroupoid, C.composeFlipped)
273+
274+inlineUnsafeCoerce :: AST -> AST
275+inlineUnsafeCoerce = everywhereTopDown convert where
276+ convert (App _ (Indexer _ (Var _ unsafeCoerceFn) (Var _ unsafeCoerce)) [ comp ])
277+ | unsafeCoerceFn == C.unsafeCoerceFn && unsafeCoerce == C.unsafeCoerce
278+ = comp
279+ convert other = other
280+
281+inlineUnsafePartial :: AST -> AST
282+inlineUnsafePartial = everywhereTopDown convert where
283+ convert (App ss fn [ comp ])
284+ | isDict fnUnsafePartial fn
285+ = App ss comp []
286+ where
287+ fnUnsafePartial :: forall a b. (IsString a, IsString b) => (a, b)
288+ fnUnsafePartial = (C.partialUnsafe, C.unsafePartial)
289+ convert other = other
290+
291+semiringNumber :: forall a b. (IsString a, IsString b) => (a, b)
292+semiringNumber = (C.dataSemiring, C.semiringNumber)
293+
294+semiringInt :: forall a b. (IsString a, IsString b) => (a, b)
295+semiringInt = (C.dataSemiring, C.semiringInt)
296+
297+ringNumber :: forall a b. (IsString a, IsString b) => (a, b)
298+ringNumber = (C.dataRing, C.ringNumber)
299+
300+ringInt :: forall a b. (IsString a, IsString b) => (a, b)
301+ringInt = (C.dataRing, C.ringInt)
302+
303+euclideanRingNumber :: forall a b. (IsString a, IsString b) => (a, b)
304+euclideanRingNumber = (C.dataEuclideanRing, C.euclideanRingNumber)
305+
306+-- eqNumber :: forall a b. (IsString a, IsString b) => (a, b)
307+-- eqNumber = (C.dataEq, C.eqNumber)
308+
309+eqInt :: forall a b. (IsString a, IsString b) => (a, b)
310+eqInt = (C.dataEq, C.eqInt)
311+
312+eqString :: forall a b. (IsString a, IsString b) => (a, b)
313+eqString = (C.dataEq, C.eqString)
314+
315+eqChar :: forall a b. (IsString a, IsString b) => (a, b)
316+eqChar = (C.dataEq, C.eqChar)
317+
318+eqBoolean :: forall a b. (IsString a, IsString b) => (a, b)
319+eqBoolean = (C.dataEq, C.eqBoolean)
320+
321+ordBoolean :: forall a b. (IsString a, IsString b) => (a, b)
322+ordBoolean = (C.dataOrd, C.ordBoolean)
323+
324+ordNumber :: forall a b. (IsString a, IsString b) => (a, b)
325+ordNumber = (C.dataOrd, C.ordNumber)
326+
327+ordInt :: forall a b. (IsString a, IsString b) => (a, b)
328+ordInt = (C.dataOrd, C.ordInt)
329+
330+ordString :: forall a b. (IsString a, IsString b) => (a, b)
331+ordString = (C.dataOrd, C.ordString)
332+
333+ordChar :: forall a b. (IsString a, IsString b) => (a, b)
334+ordChar = (C.dataOrd, C.ordChar)
335+
336+semigroupString :: forall a b. (IsString a, IsString b) => (a, b)
337+semigroupString = (C.dataSemigroup, C.semigroupString)
338+
339+boundedBoolean :: forall a b. (IsString a, IsString b) => (a, b)
340+boundedBoolean = (C.dataBounded, C.boundedBoolean)
341+
342+heytingAlgebraBoolean :: forall a b. (IsString a, IsString b) => (a, b)
343+heytingAlgebraBoolean = (C.dataHeytingAlgebra, C.heytingAlgebraBoolean)
344+
345+semigroupoidFn :: forall a b. (IsString a, IsString b) => (a, b)
346+semigroupoidFn = (C.controlSemigroupoid, C.semigroupoidFn)
347+
348+opAdd :: forall a b. (IsString a, IsString b) => (a, b)
349+opAdd = (C.dataSemiring, C.add)
350+
351+opMul :: forall a b. (IsString a, IsString b) => (a, b)
352+opMul = (C.dataSemiring, C.mul)
353+
354+opEq :: forall a b. (IsString a, IsString b) => (a, b)
355+opEq = (C.dataEq, C.eq)
356+
357+opNotEq :: forall a b. (IsString a, IsString b) => (a, b)
358+opNotEq = (C.dataEq, C.notEq)
359+
360+opLessThan :: forall a b. (IsString a, IsString b) => (a, b)
361+opLessThan = (C.dataOrd, C.lessThan)
362+
363+opLessThanOrEq :: forall a b. (IsString a, IsString b) => (a, b)
364+opLessThanOrEq = (C.dataOrd, C.lessThanOrEq)
365+
366+opGreaterThan :: forall a b. (IsString a, IsString b) => (a, b)
367+opGreaterThan = (C.dataOrd, C.greaterThan)
368+
369+opGreaterThanOrEq :: forall a b. (IsString a, IsString b) => (a, b)
370+opGreaterThanOrEq = (C.dataOrd, C.greaterThanOrEq)
371+
372+opAppend :: forall a b. (IsString a, IsString b) => (a, b)
373+opAppend = (C.dataSemigroup, C.append)
374+
375+opSub :: forall a b. (IsString a, IsString b) => (a, b)
376+opSub = (C.dataRing, C.sub)
377+
378+opNegate :: forall a b. (IsString a, IsString b) => (a, b)
379+opNegate = (C.dataRing, C.negate)
380+
381+opDiv :: forall a b. (IsString a, IsString b) => (a, b)
382+opDiv = (C.dataEuclideanRing, C.div)
383+
384+opConj :: forall a b. (IsString a, IsString b) => (a, b)
385+opConj = (C.dataHeytingAlgebra, C.conj)
386+
387+opDisj :: forall a b. (IsString a, IsString b) => (a, b)
388+opDisj = (C.dataHeytingAlgebra, C.disj)
389+
390+opNot :: forall a b. (IsString a, IsString b) => (a, b)
391+opNot = (C.dataHeytingAlgebra, C.not)
392+
393+unbox :: AST -> PSString -> AST
394+unbox e d = select . inlineCommonValues $ inlineCommonOperators e
395+ where
396+ select :: AST -> AST
397+ select e' =
398+ case e' of
399+ Var{} -> unbox' e'
400+ App{} -> unbox' e'
401+ Indexer{} -> unbox' e'
402+ _ -> e'
403+ unbox' :: AST -> AST
404+ unbox' e' = maybe e' (\t -> App Nothing (StringLiteral Nothing t) [e']) $ unboxType d
405+
406+unboxType :: PSString -> Maybe PSString
407+unboxType s = do
408+ t <- decodeString s
409+ t' <- unboxType' t
410+ return $ mkString t'
411+ where
412+ unboxType' :: Text -> Maybe Text
413+ unboxType' t
414+ | t == C.eqInt ||
415+ t == C.semiringInt ||
416+ t == C.ringInt ||
417+ t == C.ordInt ||
418+ t == C.dataIntBits
419+ = Just int
420+ | t == C.semiringNumber ||
421+ t == C.ringNumber ||
422+ t == C.ordNumber ||
423+ t == C.euclideanRingNumber
424+ = Just float
425+ | t == C.eqBoolean ||
426+ t == C.ordBoolean ||
427+ t == C.heytingAlgebraBoolean
428+ = Just bool
429+ | t == C.eqChar ||
430+ t == C.eqString ||
431+ t == C.ordChar ||
432+ t == C.ordString ||
433+ t == C.semigroupString
434+ = Just string
435+ | otherwise = Nothing
src/CodeGen/IL/Optimizer/MagicDo.hsnew file+146
@@ -0,0 +1,146 @@
1+-- | This module implements the "Magic Do" optimization, which inlines calls to return
2+-- and bind for the Eff monad, as well as some of its actions.
3+module CodeGen.IL.Optimizer.MagicDo (magicDoEffect, magicDoEff, magicDoST, inlineST) where
4+
5+import Prelude.Compat
6+import Protolude (ordNub)
7+
8+import Data.Maybe (fromJust, isJust)
9+import Data.Text (Text)
10+
11+import Language.PureScript.CoreImp.AST
12+import Language.PureScript.CoreImp.Optimizer.Common hiding (isDict)
13+import Language.PureScript.PSString (PSString, decodeString, mkString)
14+import qualified Language.PureScript.Constants as C
15+
16+import CodeGen.IL.Common (undefinedName, unusedName)
17+import CodeGen.IL.Optimizer.Common
18+
19+-- | Inline type class dictionaries for >>= and return for the Eff monad
20+--
21+-- E.g.
22+--
23+-- Prelude[">>="](dict)(m1)(function(x) {
24+-- return ...;
25+-- })
26+--
27+-- becomes
28+--
29+-- function __do {
30+-- var x = m1();
31+-- ...
32+-- }
33+magicDoEff :: AST -> AST
34+magicDoEff = magicDo C.eff C.effDictionaries
35+
36+magicDoEffect :: AST -> AST
37+magicDoEffect = magicDo C.effect C.effectDictionaries
38+
39+magicDoST :: AST -> AST
40+magicDoST = magicDo C.st C.stDictionaries
41+
42+magicDo :: Text -> C.EffectDictionaries -> AST -> AST
43+magicDo effectModule C.EffectDictionaries{..} = everywhereTopDown convert
44+ where
45+ -- Desugar monomorphic calls to >>= and return for the Eff monad
46+ convert :: AST -> AST
47+ -- Desugar pure
48+ convert (App _ (App _ pure' [val]) []) | isPure pure' = val
49+ -- Desugar discard
50+ convert (App _ (App _ bind [m]) [Function s1 Nothing [unused] (Block s2 il)]) | isDiscard bind && unused == unusedName =
51+ Function s1 Nothing [] $ Block s2 (App s2 m [] : map applyReturns il )
52+ -- Desugar bind
53+ convert (App _ (App _ bind [m]) [Function s1 Nothing [arg] (Block s2 il)]) | isBind bind =
54+ Function s1 Nothing [] $ Block s2 (VariableIntroduction s2 arg (Just (App s2 m [])) : map applyReturns il)
55+ -- Desugar untilE
56+ convert (App s1 (App _ f [arg]) []) | isEffFunc edUntil f =
57+ App s1 (Function s1 Nothing [] (Block s1 [ While s1 (Unary s1 Not (App s1 arg [])) (Block s1 []), Return s1 $ ObjectLiteral s1 []])) []
58+ -- Desugar whileE
59+ convert (App _ (App _ (App s1 f [arg1]) [arg2]) []) | isEffFunc edWhile f =
60+ App s1 (Function s1 Nothing [] (Block s1 [ While s1 (App s1 arg1 []) (Block s1 [ App s1 arg2 [] ]), Return s1 $ ObjectLiteral s1 []])) []
61+ -- -- Inline __do returns
62+ -- convert (Return _ (App _ (Function _ (Just ident) [] body) [])) | ident == fnName = body
63+ -- Inline double applications
64+ convert (App _ (App s1 (Function s2 Nothing [] (Block ss body)) []) []) =
65+ App s1 (Function s2 Nothing [] (Block ss (applyReturns `fmap` body))) []
66+ convert other = other
67+ -- Check if an expression represents a monomorphic call to >>= for the Eff monad
68+ isBind (App _ fn [dict]) | isDict (effectModule, edBindDict) dict && isBindPoly fn = True
69+ isBind _ = False
70+ -- Check if an expression represents a call to @discard@
71+ isDiscard (App _ (App _ fn [dict1]) [dict2])
72+ | isDict (C.controlBind, C.discardUnitDictionary) dict1 &&
73+ isDict (effectModule, edBindDict) dict2 &&
74+ isDiscardPoly fn = True
75+ isDiscard _ = False
76+
77+ -- Check if an expression represents a monomorphic call to pure or return for the Eff applicative
78+ isPure (App _ fn [dict]) | isDict (effectModule, edApplicativeDict) dict && isPurePoly fn = True
79+ isPure _ = False
80+ -- Check if an expression represents the polymorphic >>= function
81+ isBindPoly = isDict (C.controlBind, C.bind)
82+ -- Check if an expression represents the polymorphic pure function
83+ isPurePoly = isDict (C.controlApplicative, C.pure')
84+ -- Check if an expression represents the polymorphic discard function
85+ isDiscardPoly = isDict (C.controlBind, C.discard)
86+ -- Check if an expression represents a function in the Effect module
87+ isEffFunc name (Indexer _ (StringLiteral _ name') (Var _ eff)) = eff == effectModule && name == name'
88+ isEffFunc _ _ = False
89+
90+ applyReturns :: AST -> AST
91+ applyReturns (Return ss ret) = Return ss (App ss ret [])
92+ applyReturns (Block ss ils) = Block ss (map applyReturns ils)
93+ applyReturns (While ss cond il) = While ss cond (applyReturns il)
94+ applyReturns (For ss v lo hi il) = For ss v lo hi (applyReturns il)
95+ applyReturns (ForIn ss v xs il) = ForIn ss v xs (applyReturns il)
96+ applyReturns (IfElse ss cond t f) = IfElse ss cond (applyReturns t) (applyReturns `fmap` f)
97+ applyReturns other = other
98+
99+-- | Inline functions in the ST module
100+inlineST :: AST -> AST
101+inlineST = everywhere convertBlock
102+ where
103+ -- Look for runST blocks and inline the STRefs there.
104+ -- If all STRefs are used in the scope of the same runST, only using { read, write, modify }STRef then
105+ -- we can be more aggressive about inlining, and actually turn STRefs into local variables.
106+ convertBlock (App s1 f [arg]) | isSTFunc C.runST f =
107+ let refs = ordNub . findSTRefsIn $ arg
108+ usages = findAllSTUsagesIn arg
109+ allUsagesAreLocalVars = all (\u -> let v = toVar u in isJust v && fromJust v `elem` refs) usages
110+ localVarsDoNotEscape = all (\r -> length (r `appearingIn` arg) == length (filter (\u -> let v = toVar u in v == Just r) usages)) refs
111+ in App s1 (everywhere (convert (allUsagesAreLocalVars && localVarsDoNotEscape)) arg) []
112+ convertBlock other = other
113+ -- Convert a block in a safe way, preserving object wrappers of references,
114+ -- or in a more aggressive way, turning wrappers into local variables depending on the
115+ -- agg(ressive) parameter.
116+ convert agg (App s1 f [arg]) | isSTFunc C.newSTRef f =
117+ Function s1 Nothing [] (Block s1 [Return s1 $ if agg then arg else ObjectLiteral s1 [(mkString C.stRefValue, arg)]])
118+ convert agg (App _ (App s1 f [ref]) []) | isSTFunc C.readSTRef f =
119+ if agg then ref else Indexer s1 (StringLiteral s1 C.stRefValue) ref
120+ convert agg (App _ (App _ (App s1 f [arg]) [ref]) []) | isSTFunc C.writeSTRef f =
121+ if agg then Assignment s1 ref arg else Assignment s1 (Indexer s1 (StringLiteral s1 C.stRefValue) ref) arg
122+ convert agg (App _ (App _ (App s1 f [func]) [ref]) []) | isSTFunc C.modifySTRef f =
123+ if agg then Assignment s1 ref (App s1 func [ref]) else Assignment s1 (Indexer s1 (StringLiteral s1 C.stRefValue) ref) (App s1 func [Indexer s1 (StringLiteral s1 C.stRefValue) ref])
124+ convert _ other = other
125+ -- Check if an expression represents a function in the ST module
126+ isSTFunc name (Indexer _ (StringLiteral _ name') (Var _ st)) = st == C.st && name == name'
127+ isSTFunc _ _ = False
128+ -- Find all ST Refs initialized in this block
129+ findSTRefsIn = everything (++) isSTRef
130+ where
131+ isSTRef (VariableIntroduction _ ident (Just (App _ (App _ f [_]) []))) | isSTFunc C.newSTRef f = [ident]
132+ isSTRef _ = []
133+ -- Find all STRefs used as arguments to readSTRef, writeSTRef, modifySTRef
134+ findAllSTUsagesIn = everything (++) isSTUsage
135+ where
136+ isSTUsage (App _ (App _ f [ref]) []) | isSTFunc C.readSTRef f = [ref]
137+ isSTUsage (App _ (App _ (App _ f [_]) [ref]) []) | isSTFunc C.writeSTRef f || isSTFunc C.modifySTRef f = [ref]
138+ isSTUsage _ = []
139+ -- Find all uses of a variable
140+ appearingIn ref = everything (++) isVar
141+ where
142+ isVar e@(Var _ v) | v == ref = [e]
143+ isVar _ = []
144+ -- Convert a AST value to a String if it is a Var
145+ toVar (Var _ v) = Just v
146+ toVar _ = Nothing
src/CodeGen/IL/Optimizer/TCO.hsnew file+141
@@ -0,0 +1,141 @@
1+module CodeGen.IL.Optimizer.TCO (tco, tcoLoop) where
2+
3+import Prelude.Compat
4+
5+import Data.Text (Text)
6+import Data.Monoid ((<>))
7+import Language.PureScript.CoreImp.AST
8+import Language.PureScript.AST.SourcePos (SourceSpan)
9+import Safe (headDef, tailSafe)
10+import CodeGen.IL.Common
11+
12+import qualified Language.PureScript.Constants as C
13+
14+tcoLoop :: Text
15+tcoLoop = "ṩtco_loop"
16+
17+tco :: AST -> AST -> AST
18+tco mn = everywhere convert where
19+ tcoVar :: Text -> Text
20+ tcoVar arg = "ṩtco_var_" <> arg
21+
22+ copyVar :: Text -> Text
23+ copyVar arg = "ṩcopy_" <> arg
24+
25+ tcoDone :: Text
26+ tcoDone = "ṩtco_done"
27+
28+ tcoResult :: Text
29+ tcoResult = "ṩtco_result"
30+
31+ convert :: AST -> AST
32+ convert fn@(Function ss (Just name) args _)
33+ | isTailRecursive name body'
34+ = replace (toLoop name outerArgs innerArgs body')
35+ where
36+ innerArgs = headDef [] argss
37+ outerArgs = concat . reverse $ tailSafe argss
38+ (argss, body', replace) = collectAllFunctionArgs [] id fn
39+ convert (Assignment ss (Var _ name) fn@(Function _ Nothing _ _))
40+ | isTailRecursive name body'
41+ = Assignment ss (Var ss name) (replace (toLoop name outerArgs innerArgs body'))
42+ where
43+ innerArgs = headDef [] argss
44+ outerArgs = concat . reverse $ tailSafe argss
45+ (argss, body', replace) = collectAllFunctionArgs [] id fn
46+ convert js = js
47+
48+ collectAllFunctionArgs :: [[Text]] -> (AST -> AST) -> AST -> ([[Text]], AST, AST -> AST)
49+ collectAllFunctionArgs allArgs f (Function s1 ident args (Block s2 (body@(Return _ _):_))) =
50+ collectAllFunctionArgs (args : allArgs) (\b -> f (Function s1 ident (map copyVar args) (Block s2 [b]))) body
51+ collectAllFunctionArgs allArgs f (Function ss ident args body@(Block _ _)) =
52+ (args : allArgs, body, f . Function ss ident (map copyVar args))
53+ collectAllFunctionArgs allArgs f (Return s1 (Function s2 ident args (Block s3 [body]))) =
54+ collectAllFunctionArgs (args : allArgs) (\b -> f (Return s1 (Function s2 ident (map copyVar args) (Block s3 [b])))) body
55+ collectAllFunctionArgs allArgs f (Return s1 (Function s2 ident args body@(Block _ _))) =
56+ (args : allArgs, body, f . Return s1 . Function s2 ident (map copyVar args))
57+ collectAllFunctionArgs allArgs f body = (allArgs, body, f)
58+
59+ isTailRecursive :: Text -> AST -> Bool
60+ isTailRecursive ident js = countSelfReferences js > 0 && allInTailPosition js where
61+ countSelfReferences = everything (+) match where
62+ match :: AST -> Int
63+ match (Var _ ident') | ident == ident' = 1
64+ match _ = 0
65+
66+ allInTailPosition (Return _ expr)
67+ | isSelfCall ident expr = countSelfReferences expr == 1
68+ | otherwise = countSelfReferences expr == 0
69+ allInTailPosition (While _ js1 body)
70+ = countSelfReferences js1 == 0 && allInTailPosition body
71+ allInTailPosition (For _ _ js1 js2 body)
72+ = countSelfReferences js1 == 0 && countSelfReferences js2 == 0 && allInTailPosition body
73+ allInTailPosition (ForIn _ _ js1 body)
74+ = countSelfReferences js1 == 0 && allInTailPosition body
75+ allInTailPosition (IfElse _ js1 body el)
76+ = countSelfReferences js1 == 0 && allInTailPosition body && all allInTailPosition el
77+ allInTailPosition (Block _ body)
78+ = all allInTailPosition body
79+ allInTailPosition (Throw _ js1)
80+ = countSelfReferences js1 == 0
81+ allInTailPosition (ReturnNoResult _)
82+ = True
83+ allInTailPosition (VariableIntroduction _ _ js1)
84+ = all ((== 0) . countSelfReferences) js1
85+ allInTailPosition (Assignment _ _ js1)
86+ = countSelfReferences js1 == 0
87+ allInTailPosition (Comment _ _ js1)
88+ = allInTailPosition js1
89+ allInTailPosition _
90+ = False
91+
92+ toLoop :: Text -> [Text] -> [Text] -> AST -> AST
93+ toLoop ident outerArgs innerArgs js =
94+ Block rootSS $
95+ concatMap (\arg -> [ VariableIntroduction rootSS (tcoVar arg) . Just $
96+ Var rootSS (copyVar arg) ]) (outerArgs ++ innerArgs) ++
97+ [ Assignment rootSS (Var rootSS $ "var " <> tcoDone) $ BooleanLiteral Nothing False
98+ , VariableIntroduction rootSS tcoResult Nothing
99+ , Assignment rootSS (Var rootSS $ "var " <> tcoLoop) (Function rootSS (Just tcoLoop) (outerArgs ++ innerArgs) (Block rootSS [loopify js]))
100+ , While rootSS (Unary Nothing Not (Var rootSS tcoDone))
101+ (Block rootSS
102+ [(Assignment rootSS (Var rootSS tcoResult) (App rootSS (Var rootSS tcoLoop) ((map (Var rootSS . tcoVar) outerArgs) ++ (map (Var rootSS . copyVar) innerArgs))))])
103+ , Return rootSS (Var rootSS tcoResult)
104+ ]
105+ where
106+ rootSS = Nothing
107+
108+ loopify :: AST -> AST
109+ loopify (Return ss ret)
110+ | isSelfCall ident ret =
111+ let
112+ allArgumentValues = concat $ collectArgs [] ret
113+ in
114+ Block ss $
115+ zipWith (\val arg ->
116+ Assignment ss (Var ss (tcoVar arg)) val) allArgumentValues outerArgs
117+ ++ zipWith (\val arg ->
118+ Assignment ss (Var ss (copyVar arg)) val) (drop (length outerArgs) allArgumentValues) innerArgs
119+ ++ [ ReturnNoResult ss ]
120+ | otherwise = Block ss [ markDone ss, Return ss ret ]
121+ loopify (ReturnNoResult ss) = Block ss [ markDone ss, ReturnNoResult ss ]
122+ loopify (While ss cond body) = While ss cond (loopify body)
123+ loopify (For ss i js1 js2 body) = For ss i js1 js2 (loopify body)
124+ loopify (ForIn ss i js1 body) = ForIn ss i js1 (loopify body)
125+ loopify (IfElse ss cond body el) = IfElse ss cond (loopify body) (fmap loopify el)
126+ loopify (Block ss body) = Block ss (map loopify body)
127+ loopify other = other
128+
129+ markDone :: Maybe SourceSpan -> AST
130+ markDone ss = Assignment ss (Var ss tcoDone) (BooleanLiteral ss True)
131+
132+ collectArgs :: [[AST]] -> AST -> [[AST]]
133+ collectArgs acc (App _ fn args') = collectArgs (args' : acc) fn
134+ collectArgs acc _ = acc
135+
136+ isSelfCall :: Text -> AST -> Bool
137+ isSelfCall ident (App _ (Var _ ident') _) = ident == ident'
138+ isSelfCall ident (App _ (Indexer _ (Var _ ident') (Var _ mn')) _) = mn' == "" && ident == ident'
139+ isSelfCall ident (App _ (Indexer _ (Var _ ident') mn') _) = mn' == mn && ident == ident'
140+ isSelfCall ident (App _ fn _) = isSelfCall ident fn
141+ isSelfCall _ _ = False
src/CodeGen/IL/Printer.hsnew file+527
@@ -0,0 +1,527 @@
1+-- | Pretty printer for the AST
2+module CodeGen.IL.Printer
3+ ( prettyPrintIL
4+ , prettyPrintIL1
5+ , prettyPrintILWithSourceMaps
6+ , interfaceSource
7+ , implHeaderSource
8+ , implFooterSource
9+ , isLiteral
10+ , modLabel
11+ , modPrefix
12+ , ffiLoader
13+ ) where
14+
15+import Prelude.Compat
16+
17+import Control.Arrow ((<+>))
18+import Control.Monad (forM, mzero)
19+import Control.Monad.State (StateT, evalStateT)
20+import Control.PatternArrows
21+import Data.List (filter, (\\))
22+import qualified Control.Arrow as A
23+
24+import Data.Maybe (fromMaybe)
25+import Data.Monoid ((<>))
26+import Data.Text (Text)
27+import qualified Data.Text as T
28+
29+import Language.PureScript.AST (SourceSpan(..))
30+import Language.PureScript.CoreImp.AST
31+import Language.PureScript.Comments
32+import Language.PureScript.Crash
33+import Language.PureScript.Names (Ident, runIdent)
34+import Language.PureScript.Pretty.Common
35+import Language.PureScript.PSString (PSString, decodeString, mkString)
36+
37+import CodeGen.IL.Common
38+import CodeGen.IL.Optimizer.TCO (tcoLoop)
39+
40+import qualified Language.PureScript.Constants as C
41+
42+-- TODO (Christoph): Get rid of T.unpack / pack
43+
44+literals :: (Emit gen) => Pattern PrinterState AST gen
45+literals = mkPattern' match'
46+ where
47+ match' :: (Emit gen) => AST -> StateT PrinterState Maybe gen
48+ match' il = (addMapping' (getSourceSpan il) <>) <$> match il
49+
50+ match :: (Emit gen) => AST -> StateT PrinterState Maybe gen
51+ match (NumericLiteral _ n) = return $ emit $ T.pack $ either show show n
52+ match (StringLiteral _ s) = return $ emit $ stringLiteral s
53+ match (BooleanLiteral _ True) = return $ emit "true"
54+ match (BooleanLiteral _ False) = return $ emit "false"
55+ match (ArrayLiteral _ xs) = mconcat <$> sequence
56+ [ return . emit $ arrayType <> "{"
57+ , intercalate (emit ", ") <$> forM xs prettyPrintIL'
58+ , return $ emit "}"
59+ ]
60+ -- match (ObjectLiteral _ []) = return $ emit "std::initializer_list<std::pair<const string, boxed>>{}"
61+ match (ObjectLiteral _ ps) = mconcat <$> sequence
62+ [ return . emit $ dictType <> "{"
63+ , withIndent $ do
64+ ils <- forM ps $ \(key, value) -> do
65+ value' <- prettyPrintIL' value
66+ return $ objectPropertyToString key <> value'
67+ return $ intercalate (emit " ") $ map (<> emit ",") ils
68+ , return $ emit "}"
69+ ]
70+ where
71+ objectPropertyToString :: (Emit gen) => PSString -> gen
72+ objectPropertyToString s = emit $ stringLiteral s <> ": "
73+ match (Block _ sts) = mconcat <$> sequence
74+ [ return $ emit "{\n"
75+ , withIndent $ prettyStatements sts
76+ , return $ emit "\n"
77+ , currentIndent
78+ , return $ emit "}"
79+ ]
80+ match (Var _ ident) | ident == C.undefined = return $ emit undefinedName
81+ match (Var _ ident) = return $ emit ident
82+ match (VariableIntroduction _ ident value) = mconcat <$> sequence
83+ [ return . emit $ varDecl <> " " <> ident <> " " <> anyType
84+ , maybe (return mempty) (fmap (emit " = " <>) . prettyPrintIL') value
85+ ]
86+ match (Assignment _ target value) = mconcat <$> sequence
87+ [ prettyPrintIL' target
88+ , return $ emit " = "
89+ , prettyPrintIL' value
90+ ]
91+ match (App _ val []) = mconcat <$> sequence
92+ [ return $ emit "Run("
93+ , prettyPrintIL' val
94+ , return $ emit ")"
95+ ]
96+ match (App _ (StringLiteral _ u) [arg])
97+ | Just ty <- decodeString u = mconcat <$> sequence
98+ [ prettyPrintIL' arg
99+ , return $ emit ".("
100+ , return $ emit ty
101+ , return $ emit ")"
102+ ]
103+ match (App _ (Var _ fn) [arg]) | fn == arrayLengthFn = mconcat <$> sequence
104+ [ return $ emit fn
105+ , return $ emit "("
106+ , prettyPrintIL' arg
107+ , return $ emit ")"
108+ ]
109+ match (App _ (Var _ fn) args) | fn == indexFn = mconcat <$> sequence
110+ [ return $ emit fn
111+ , return $ emit "("
112+ , intercalate (emit ", ") <$> forM args prettyPrintIL'
113+ , return $ emit ")"
114+ ]
115+ match (App _ (Var _ fn) args) | fn == tcoLoop = mconcat <$> sequence
116+ [ return $ emit fn
117+ , return $ emit "("
118+ , intercalate (emit ", ") <$> forM args prettyPrintIL'
119+ , return $ emit ")"
120+ ]
121+ match (App _ (App Nothing (StringLiteral Nothing fnx) [fn@Function{}]) args)
122+ | Just ftype <- decodeString fnx
123+ , "Fn" `T.isPrefixOf` ftype = mconcat <$> sequence
124+ [ prettyPrintIL' fn
125+ , return $ emit "("
126+ , intercalate (emit ", ") <$> forM args prettyPrintIL'
127+ , return $ emit ")"
128+ ]
129+ match (App _ (App Nothing (StringLiteral Nothing fnx) [fn]) args)
130+ | Just ftype <- decodeString fnx
131+ , "Fn" `T.isPrefixOf` ftype = mconcat <$> sequence
132+ [ prettyPrintIL' fn
133+ , return $ emit ".("
134+ , return $ emit ftype
135+ , return $ emit ")("
136+ , intercalate (emit ", ") <$> forM args prettyPrintIL'
137+ , return $ emit ")"
138+ ]
139+ match app@(App{})
140+ | (val, args) <- unApp app []
141+ , length args > 1
142+ = mconcat <$> sequence
143+ [ return $ emit "Apply("
144+ , prettyPrintIL' val
145+ , return $ emit ", "
146+ , intercalate (emit ", ") <$> forM args prettyPrintIL'
147+ , return $ emit ")"
148+ ]
149+ match (App _ val args) = mconcat <$> sequence
150+ [ return $ emit "Apply("
151+ , prettyPrintIL' val
152+ , return $ emit ", "
153+ , intercalate (emit ", ") <$> forM args prettyPrintIL'
154+ , return $ emit ")"
155+ ]
156+ match (Function _ (Just name) [] (Block _ [Return _ ret]))
157+ | isComplexLiteral ret = mconcat <$> sequence
158+ [ return $ emit "\n"
159+ , return . emit $ varDecl <> " " <> initName name <> " Once\n"
160+ , prettyPrintIL' $ VariableIntroduction Nothing (valueName name) Nothing
161+ , return $ emit "\n\n"
162+ , return $ emit "func "
163+ , return . emit $ withPrefix name
164+ , return . emit $ "() " <> anyType <> " "
165+ , return $ emit "{\n"
166+ , withIndent $ do
167+ indentString <- currentIndent
168+ return $ indentString <> (emit $ initName name <> ".Do(func() {\n") <>
169+ indentString <> indentString <> (emit $ valueName name <> " = ")
170+ , withIndent $ do
171+ case ret of
172+ Function _ Nothing args body -> mconcat <$> sequence
173+ [ return $ emit "func("
174+ , return . emit $ intercalate ", " (renderArg anyType <$> args)
175+ , return . emit $ ") " <> anyType <> " "
176+ , prettyPrintIL' body
177+ ]
178+ _ -> do
179+ prettyPrintIL' ret
180+ , return $ emit "\n"
181+ , withIndent $ do
182+ indentString <- currentIndent
183+ return $ indentString <> (emit $ "})\n" <> "return " <> valueName name <>"\n")
184+ , return $ emit "}\n\n"
185+ ]
186+ match (Function _ (Just name) [] ret) = mconcat <$> sequence
187+ [ return $ emit "func "
188+ , return . emit $ withPrefix name
189+ , return . emit $ "() " <> anyType <> " "
190+ , prettyPrintIL' ret
191+ ]
192+ match (Function _ _ args ret) = mconcat <$> sequence
193+ [ return $ emit "func("
194+ , return . emit $ intercalate ", " (renderArg anyType <$> args)
195+ , return . emit $ ") " <> anyType <> " "
196+ , prettyPrintIL' ret
197+ ]
198+ match (Indexer _ (Var _ name) (Var _ "")) = mconcat <$> sequence
199+ [ prettyPrintIL' (Var Nothing $ withPrefix name)
200+ , return $ emit "()"
201+ ]
202+ match (Indexer _ (Var _ name) val) = mconcat <$> sequence
203+ [ prettyPrintIL' val
204+ , return $ emit "."
205+ , prettyPrintIL' (Var Nothing $ withPrefix name)
206+ , return $ emit "()"
207+ ]
208+ match (Indexer _ prop@StringLiteral{} val@ObjectLiteral{}) = mconcat <$> sequence
209+ [ prettyPrintIL' val
210+ , return $ emit "["
211+ , prettyPrintIL' prop
212+ , return $ emit "]"
213+ ]
214+ match (Indexer _ prop@StringLiteral{} val) = mconcat <$> sequence
215+ [ prettyPrintIL' val
216+ , return $ emit ".("
217+ , return $ emit dictType
218+ , return $ emit ")["
219+ , prettyPrintIL' prop
220+ , return $ emit "]"
221+ ]
222+ match (Indexer _ index val@ArrayLiteral{}) = mconcat <$> sequence
223+ [ prettyPrintIL' val
224+ , return $ emit "["
225+ , prettyPrintIL' index
226+ , return $ emit "]"
227+ ]
228+ match (Indexer _ index val) = mconcat <$> sequence
229+ [ prettyPrintIL' val
230+ , return $ emit ".("
231+ , return $ emit arrayType
232+ , return $ emit ")["
233+ , prettyPrintIL' index
234+ , return $ emit "]"
235+ ]
236+ match (InstanceOf _ val ty) = mconcat <$> sequence
237+ [ return $ emit "Is("
238+ , prettyPrintIL' val
239+ , return $ emit ", "
240+ , prettyPrintIL' ty
241+ , return $ emit ")"
242+ ]
243+ match (While _ cond sts) = mconcat <$> sequence
244+ [ return $ emit "for "
245+ , prettyPrintIL' cond
246+ , return $ emit " "
247+ , prettyPrintIL' sts
248+ ]
249+ match (For _ ident start end sts) = mconcat <$> sequence
250+ [ return $ emit $ "for var " <> ident <> " = "
251+ , prettyPrintIL' start
252+ , return $ emit $ "; " <> ident <> " < "
253+ , prettyPrintIL' end
254+ , return $ emit $ "; " <> ident <> "++ "
255+ , prettyPrintIL' sts
256+ ]
257+ match (ForIn _ ident obj sts) = mconcat <$> sequence
258+ [ return $ emit $ "for var " <> ident <> " in "
259+ , prettyPrintIL' obj
260+ , return $ emit " "
261+ , prettyPrintIL' sts
262+ ]
263+ match (IfElse _ (Binary _ EqualTo cond@Binary{} (BooleanLiteral Nothing True)) thens elses) = mconcat <$> sequence
264+ [ return $ emit "if "
265+ , prettyPrintIL' cond
266+ , return $ emit " "
267+ , prettyPrintIL' thens
268+ , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintIL') elses
269+ ]
270+ match (IfElse _ (Binary _ EqualTo cond@Binary{} (BooleanLiteral Nothing False)) thens elses) = mconcat <$> sequence
271+ [ return $ emit "if !("
272+ , prettyPrintIL' cond
273+ , return $ emit ") "
274+ , prettyPrintIL' thens
275+ , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintIL') elses
276+ ]
277+ match (IfElse _ cond thens elses) = mconcat <$> sequence
278+ [ return $ emit "if "
279+ , prettyPrintIL' cond
280+ , return $ emit " "
281+ , prettyPrintIL' thens
282+ , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintIL') elses
283+ ]
284+ match (Return _ value) = mconcat <$> sequence
285+ [ return $ emit "return "
286+ , prettyPrintIL' value
287+ ]
288+ match (ReturnNoResult _) = return . emit $ "return " <> undefinedName
289+ -- match (Throw _ _) = return mempty
290+ match (Throw _ value) = mconcat <$> sequence
291+ [ return $ emit "panic("
292+ , prettyPrintIL' value
293+ , return $ emit ")"
294+ ]
295+ match (Comment _ com il) = mconcat <$> sequence
296+ [ return $ emit "\n"
297+ , mconcat <$> forM com comment
298+ , prettyPrintIL' il
299+ ]
300+ match _ = mzero
301+
302+ comment :: (Emit gen) => Comment -> StateT PrinterState Maybe gen
303+ comment (LineComment com) = fmap mconcat $ sequence $
304+ [ currentIndent
305+ , return $ emit "//" <> emit com <> emit "\n"
306+ ]
307+ comment (BlockComment com) = fmap mconcat $ sequence $
308+ [ currentIndent
309+ , return $ emit "/**\n"
310+ ] ++
311+ map asLine (T.lines com) ++
312+ [ currentIndent
313+ , return $ emit " */\n"
314+ , currentIndent
315+ ]
316+ where
317+ asLine :: (Emit gen) => Text -> StateT PrinterState Maybe gen
318+ asLine s = do
319+ i <- currentIndent
320+ return $ i <> emit " * " <> (emit . removeComments) s <> emit "\n"
321+
322+ removeComments :: Text -> Text
323+ removeComments t =
324+ case T.stripPrefix "*/" t of
325+ Just rest -> removeComments rest
326+ Nothing -> case T.uncons t of
327+ Just (x, xs) -> x `T.cons` removeComments xs
328+ Nothing -> ""
329+
330+unary' :: (Emit gen) => UnaryOperator -> (AST -> Text) -> Operator PrinterState AST gen
331+unary' op mkStr = Wrap match (<>)
332+ where
333+ match :: (Emit gen) => Pattern PrinterState AST (gen, AST)
334+ match = mkPattern match'
335+ where
336+ match' (Unary _ op' val) | op' == op = Just (emit $ mkStr val, val)
337+ match' _ = Nothing
338+
339+unary :: (Emit gen) => UnaryOperator -> Text -> Operator PrinterState AST gen
340+unary op str = unary' op (const str)
341+
342+negateOperator :: (Emit gen) => Operator PrinterState AST gen
343+negateOperator = unary' Negate (\v -> if isNegate v then "- " else "-")
344+ where
345+ isNegate (Unary _ Negate _) = True
346+ isNegate _ = False
347+
348+binary :: (Emit gen) => BinaryOperator -> Text -> Operator PrinterState AST gen
349+binary op str = AssocL match (\v1 v2 -> v1 <> emit (" " <> str <> " ") <> v2)
350+ where
351+ match :: Pattern PrinterState AST (AST, AST)
352+ match = mkPattern match'
353+ where
354+ match' (Binary _ op' v1 v2) | op' == op = Just (v1, v2)
355+ match' _ = Nothing
356+
357+isLiteral :: AST -> Bool
358+isLiteral Function{} = True
359+isLiteral NumericLiteral{} = True
360+isLiteral StringLiteral{} = True
361+isLiteral BooleanLiteral{} = True
362+isLiteral ObjectLiteral{} = True
363+isLiteral ArrayLiteral{} = True
364+isLiteral _ = False
365+
366+isComplexLiteral :: AST -> Bool
367+-- isComplexLiteral Function{} = True
368+isComplexLiteral ObjectLiteral{} = True
369+isComplexLiteral ArrayLiteral{} = True
370+isComplexLiteral _ = False
371+
372+unApp :: AST -> [AST] -> (AST, [AST])
373+unApp (App _ val [arg]) args = unApp val (arg : args)
374+unApp other args = (other, args)
375+
376+prettyStatements :: (Emit gen) => [AST] -> StateT PrinterState Maybe gen
377+prettyStatements sts = do
378+ ils <- forM sts prettyPrintIL'
379+ indentString <- currentIndent
380+ return $ intercalate (emit "\n") $ map (indentString <>) ils
381+
382+-- | Generate a pretty-printed string representing a collection of C++ expressions at the same indentation level
383+prettyPrintILWithSourceMaps :: [AST] -> (Text, [SMap])
384+prettyPrintILWithSourceMaps il =
385+ let StrPos (_, s, mp) = (fromMaybe (internalError "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyStatements) il
386+ in (s, mp)
387+
388+prettyPrintIL :: [AST] -> Text
389+prettyPrintIL = maybe (internalError "Incomplete pattern") runPlainString . flip evalStateT (PrinterState 0) . prettyStatements
390+
391+-- | Generate an indented, pretty-printed string representing a C++ expression
392+prettyPrintIL' :: (Emit gen) => AST -> StateT PrinterState Maybe gen
393+prettyPrintIL' = A.runKleisli $ runPattern matchValue
394+ where
395+ matchValue :: (Emit gen) => Pattern PrinterState AST gen
396+ matchValue = buildPrettyPrinter operators (literals <+> fmap parensPos matchValue)
397+ operators :: (Emit gen) => OperatorTable PrinterState AST gen
398+ operators =
399+ OperatorTable [ [ unary New "?" ]
400+ , [ unary Not "!"
401+ , unary BitwiseNot "~"
402+ , unary Positive "+"
403+ , negateOperator ]
404+ , [ binary Multiply "*"
405+ , binary Divide "/"
406+ , binary Modulus "%" ]
407+ , [ binary Add "+"
408+ , binary Subtract "-" ]
409+ , [ binary ShiftLeft "<<"
410+ , binary ShiftRight ">>" ]
411+ , [ binary LessThan "<"
412+ , binary LessThanOrEqualTo "<="
413+ , binary GreaterThan ">"
414+ , binary GreaterThanOrEqualTo ">=" ]
415+ , [ binary EqualTo "=="
416+ , binary NotEqualTo "!=" ]
417+ , [ binary BitwiseAnd "&" ]
418+ , [ binary BitwiseXor "^" ]
419+ , [ binary BitwiseOr "|" ]
420+ , [ binary And "&&" ]
421+ , [ binary Or "||" ]
422+ ]
423+
424+prettyPrintIL1 :: AST -> Text
425+prettyPrintIL1 = maybe (internalError "Incomplete pattern") runPlainString . flip evalStateT (PrinterState 0) . prettyPrintIL'
426+
427+stringLiteral :: PSString -> Text
428+stringLiteral pss | Just s <- decodeString pss = stringLiteral' s
429+ where
430+ stringLiteral' :: Text -> Text
431+ stringLiteral' s = "\"" <> T.concatMap encodeChar s <> "\""
432+ encodeChar :: Char -> Text
433+ encodeChar '\0' = "\\x00"
434+ encodeChar '\b' = "\\b"
435+ encodeChar '\t' = "\\t"
436+ encodeChar '\n' = "\\n"
437+ encodeChar '\v' = "\\v"
438+ encodeChar '\f' = "\\f"
439+ encodeChar '\r' = "\\r"
440+ encodeChar '"' = "\\\""
441+ encodeChar '\\' = "\\\\"
442+ encodeChar c = T.singleton $ c
443+stringLiteral _ = "\"\\uFFFD\""
444+
445+interfaceSource :: Text -> [(Text,Bool)] -> [Ident] -> Text
446+interfaceSource _ _ _ = ""
447+
448+implHeaderSource :: Text -> [Text] -> Text -> Text
449+implHeaderSource mn imports otherPrefix =
450+ "// Code generated by psgo. DO NOT EDIT.\n\n" <>
451+ "package " <> (if mn == "Main" || mn == "Test_Main" then "main" else mn) <> "\n\n" <>
452+ "import . \"" <> runtime <> "\"\n" <>
453+ (if mn == "Main" || mn == "Test_Main"
454+ then "import _ \"" <> otherPrefix <> "/" <> ffiLoader <> "\"\n"
455+ else "\n") <>
456+ "import (\n" <>
457+ (T.concat $ formatImport <$> imports) <> ")\n\n" <>
458+ "type _ = Any\n\n"
459+ where
460+ formatImport :: Text -> Text
461+ formatImport s =
462+ "\t\"" <> otherPrefix <> "/" <> modPrefix <> "/" <> moduleRenamer s <> "\"\n"
463+ moduleRenamer :: Text -> Text
464+ moduleRenamer s
465+ | (s', sfx) <- T.breakOn moduleRenamerMarker s,
466+ not $ T.null sfx = s'
467+ moduleRenamer s = s
468+
469+implFooterSource :: Text -> [Ident] -> Text
470+implFooterSource mn foreigns =
471+ "\n\n\n" <>
472+ (if null foreigns
473+ then ""
474+ else ("// Foreign values\n\n" <>
475+ "var " <> foreignDict <> " = "<> foreignMod <> "(\"" <> mn <> "\")\n\n" <>
476+ (T.concat $ (\foreign' ->
477+ let name = moduleIdentToIL foreign' in
478+ varDecl <> " " <> initName name <> " Once\n" <>
479+ varDecl <> " " <> valueName name <> " " <> anyType <> "\n\n" <>
480+ "func " <>
481+ withPrefix name <>
482+ "() Any { \n" <>
483+ " " <> initName name <> ".Do(func() {\n" <>
484+ " " <> valueName name <> " = " <>
485+ "Get(" <> foreignDict <> ", " <>
486+ (stringLiteral . mkString $ runIdent foreign') <> ")\n" <>
487+ " })\n" <>
488+ " return " <> valueName name <> "\n" <>
489+ "}\n\n") <$> foreigns))) <>
490+ if mn == "Main" || mn == "Test.Main" then mainSource else "\n"
491+ where
492+ mainSource :: Text
493+ mainSource = "\
494+ \func main() {\n\
495+ \ Run(Ꞌmain())\n\
496+ \}\n\n\
497+ \"
498+
499+varDecl :: Text
500+varDecl = "var"
501+
502+renderArg :: Text -> Text -> Text
503+renderArg decl arg = arg <> " " <> decl
504+
505+foreignMod :: Text
506+foreignMod = "Foreign"
507+
508+foreignDict :: Text
509+foreignDict = "foreign"
510+
511+modLabel :: Text
512+modLabel = "purescript-native"
513+
514+modPrefix :: Text
515+modPrefix = modLabel <> "/output"
516+
517+runtime :: Text
518+runtime = "github.com/" <> modLabel <> "/go-runtime"
519+
520+ffiLoader :: Text
521+ffiLoader = modLabel <> "/ffi-loader"
522+
523+initName :: Text -> Text
524+initName s = "ᛌ" <> s <> "_once"
525+
526+valueName :: Text -> Text
527+valueName s = "ᛧ" <> s
src/Data/Generics/Extras.hsdeleted−73
@@ -1,73 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Data.Generics.Extras
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Additional SYB combinators
13−--
14−-----------------------------------------------------------------------------
15−
16−{-# LANGUAGE Rank2Types #-}
17−
18−module Data.Generics.Extras where
19−
20−import Data.Data
21−
22−-- |
23−-- Apply a top-down monadic transformation everywhere
24−--
25−everywhereM' :: (Monad m, Data d) => (forall d1. (Data d1) => d1 -> m d1) -> d -> m d
26−everywhereM' f x = do
27− y <- f x
28− gmapM (everywhereM' f) y
29−
30−-- |
31−-- Apply a top-down transformation, mutating a state when descending from parents to children
32−--
33−-- For example, if we want to relabel bound variables with a different data constructor, we can do so:
34−--
35−-- > data Expr = Var String
36−-- > | Lam String Test
37−-- > | App Test Test
38−-- > | LocalVar String deriving (Show, Data, Typeable)
39−-- >
40−-- > test = App (Lam "a" (App (Var "a") (Var "b"))) (Var "a")
41−-- >
42−-- > varsToLocals :: Expr -> Expr
43−-- > varsToLocals = everywhereWithContext' [] (mkS go)
44−-- > where
45−-- > go locals (Var v) | v `elem` locals = (locals, LocalVar v)
46−-- > go locals lam@(Lam local _) = (local : locals, lam)
47−-- > go locals other = (locals, other)
48−--
49−everywhereWithContextM' :: (Monad m, Data d) => s -> (forall d1. (Data d1) => s -> d1 -> m (s, d1)) -> d -> m d
50−everywhereWithContextM' s0 f x = do
51− (s, y) <- f s0 x
52− gmapM (everywhereWithContextM' s f) y
53−
54−-- |
55−-- Make a stateful transformation function
56−--
57−mkS :: (Monad m, Data a, Data b) => (s -> a -> m (s, a)) -> s -> b -> m (s, b)
58−mkS = extS (curry return)
59−
60−-- |
61−-- Extend a stateful transformation function
62−--
63−extS :: (Monad m, Data a, Data b) => (s -> a -> m (s, a)) -> (s -> b -> m (s, b)) -> (s -> a -> m (s, a))
64−extS f g s a = do
65− (s', a') <- f s a
66− case cast a' of
67− Just b -> do
68− (s'', b') <- g s' b
69− case cast b' of
70− Just a'' -> return (s'', a'')
71− Nothing -> return (s', a')
72− Nothing -> return (s', a')
73−
src/Language/PureScript.hsdeleted−254
@@ -1,254 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- The main compiler module
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript (module P, compile, compile', MonadMake(..), make) where
17−
18−import Language.PureScript.Types as P
19−import Language.PureScript.Kinds as P
20−import Language.PureScript.Declarations as P
21−import Language.PureScript.Names as P
22−import Language.PureScript.Parser as P
23−import Language.PureScript.CodeGen as P
24−import Language.PureScript.CodeGen.Common as P
25−import Language.PureScript.TypeChecker as P
26−import Language.PureScript.Pretty as P
27−import Language.PureScript.Sugar as P
28−import Language.PureScript.Options as P
29−import Language.PureScript.ModuleDependencies as P
30−import Language.PureScript.Environment as P
31−import Language.PureScript.Errors as P
32−import Language.PureScript.DeadCodeElimination as P
33−
34−import qualified Language.PureScript.Constants as C
35−
36−import Data.List (find, sortBy, groupBy, intercalate)
37−import Data.Time.Clock
38−import Data.Function (on)
39−import Data.Generics (mkQ, everything)
40−import Data.Maybe (fromMaybe, mapMaybe)
41−import Control.Monad.Error
42−import Control.Monad.State.Lazy
43−import Control.Arrow ((&&&))
44−import Control.Applicative ((<$>))
45−import qualified Data.Map as M
46−import qualified Data.Set as S
47−import System.FilePath (pathSeparator)
48−
49−-- |
50−-- Compile a collection of modules
51−--
52−-- The compilation pipeline proceeds as follows:
53−--
54−-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
55−--
56−-- * Perform a set of desugaring passes.
57−--
58−-- * Type check, and elaborate values to include type annotations and type class dictionaries.
59−--
60−-- * Regroup values to take into account new value dependencies introduced by elaboration.
61−--
62−-- * Eliminate dead code.
63−--
64−-- * Generate Javascript, and perform optimization passes.
65−--
66−-- * Pretty-print the generated Javascript
67−--
68−compile :: Options -> [Module] -> Either String (String, String, Environment)
69−compile = compile' initEnvironment
70−
71−compile' :: Environment -> Options -> [Module] -> Either String (String, String, Environment)
72−compile' env opts ms = do
73− (sorted, _) <- sortModules $ if optionsNoPrelude opts then ms else (map importPrelude ms)
74− desugared <- stringifyErrorStack True $ desugar sorted
75− (elaborated, env') <- runCheck' opts env $ forM desugared $ typeCheckModule mainModuleIdent
76− regrouped <- stringifyErrorStack True $ createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
77− let entryPoints = moduleNameFromString `map` optionsModules opts
78− let elim = if null entryPoints then regrouped else eliminateDeadCode entryPoints regrouped
79− let codeGenModules = moduleNameFromString `map` optionsCodeGenModules opts
80− let modulesToCodeGen = if null codeGenModules then elim else filter (\(Module mn _ _) -> mn `elem` codeGenModules) elim
81− let js = mapMaybe (flip (moduleToJs opts) env') modulesToCodeGen
82− let exts = intercalate "\n" . map (`moduleToPs` env') $ modulesToCodeGen
83− js' <- generateMain env' opts js
84− return (prettyPrintJS [wrapExportsContainer opts js'], exts, env')
85− where
86− mainModuleIdent = moduleNameFromString <$> optionsMain opts
87−
88−typeCheckModule :: Maybe ModuleName -> Module -> Check Module
89−typeCheckModule mainModuleName (Module mn decls exps) = do
90− modify (\s -> s { checkCurrentModule = Just mn })
91− decls' <- typeCheckAll mainModuleName mn decls
92− mapM_ checkTypesAreExported exps'
93− return $ Module mn decls' exps
94− where
95−
96− exps' = fromMaybe (error "exports should have been elaborated") exps
97−
98− -- Check that all the type constructors defined in the current module that appear in member types
99− -- have also been exported from the module
100− checkTypesAreExported :: DeclarationRef -> Check ()
101− checkTypesAreExported (ValueRef name) = do
102− ty <- lookupVariable mn (Qualified (Just mn) name)
103− case find isTconHidden (findTcons ty) of
104− Just hiddenType -> throwError . strMsg $
105− "Error in module '" ++ show mn ++ "':\n\
106− \Exporting declaration '" ++ show name ++ "' requires type '" ++ show hiddenType ++ "' to be exported as well"
107− Nothing -> return ()
108− checkTypesAreExported _ = return ()
109−
110− -- Find the type constructors exported from the current module used in a type
111− findTcons :: Type -> [ProperName]
112− findTcons = everything (++) (mkQ [] go)
113− where
114− go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [name]
115− go _ = []
116−
117− -- Checks whether a type constructor is not being exported from the current module
118− isTconHidden :: ProperName -> Bool
119− isTconHidden tyName = all go exps'
120− where
121− go (TypeRef tyName' _) = tyName' /= tyName
122− go _ = True
123−
124−
125−generateMain :: Environment -> Options -> [JS] -> Either String [JS]
126−generateMain env opts js =
127− case moduleNameFromString <$> optionsMain opts of
128− Just mmi -> do
129− when ((mmi, Ident C.main) `M.notMember` names env) $
130− Left $ show mmi ++ "." ++ C.main ++ " is undefined"
131− return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar C._ps))) []]
132− _ -> return js
133−
134−-- |
135−-- A type class which collects the IO actions we need to be able to run in "make" mode
136−--
137−class MonadMake m where
138− -- |
139− -- Get a file timestamp
140− --
141− getTimestamp :: FilePath -> m (Maybe UTCTime)
142−
143− -- |
144− -- Read a file as a string
145− --
146− readTextFile :: FilePath -> m String
147−
148− -- |
149− -- Write a text file
150− --
151− writeTextFile :: FilePath -> String -> m ()
152−
153− -- |
154− -- Report an error
155− --
156− liftError :: Either String a -> m a
157−
158−
159−-- |
160−-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
161−--
162−-- If timestamps have not changed, the externs file can be used to provide the module's types without
163−-- having to typecheck the module again.
164−--
165−make :: (Functor m, Monad m, MonadMake m) => Options -> [(FilePath, Module)] -> m ()
166−make opts ms = do
167− let filePathMap = M.fromList (map (\(fp, Module mn _ _) -> (mn, fp)) ms)
168−
169− (sorted, graph) <- liftError $ sortModules $ if optionsNoPrelude opts then map snd ms else (map (importPrelude . snd) ms)
170−
171− toRebuild <- foldM (\s (Module moduleName' _ _) -> do
172− let filePath = toFileName moduleName'
173−
174− jsFile = "js" ++ pathSeparator : filePath ++ ".js"
175− externsFile = "externs" ++ pathSeparator : filePath ++ ".externs"
176− inputFile = fromMaybe (error "Input file is undefined in make") $ M.lookup moduleName' filePathMap
177−
178− jsTimestamp <- getTimestamp jsFile
179− externsTimestamp <- getTimestamp externsFile
180− inputTimestamp <- getTimestamp inputFile
181−
182− return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
183− (Just t1, Just t2, Just t3) | t1 < min t2 t3 -> s
184− _ -> S.insert moduleName' s) S.empty sorted
185−
186− marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
187−
188− desugared <- liftError $ stringifyErrorStack True $ zip (map fst marked) <$> desugar (map snd marked)
189−
190− go initEnvironment desugared
191−
192− where
193− go :: (Functor m, Monad m, MonadMake m) => Environment -> [(Bool, Module)] -> m ()
194− go _ [] = return ()
195− go env ((False, m) : ms') = do
196− (_, env') <- liftError . runCheck' opts env $ typeCheckModule Nothing m
197−
198− go env' ms'
199− go env ((True, m@(Module moduleName' _ exps)) : ms') = do
200− let filePath = toFileName moduleName'
201− jsFile = "js" ++ pathSeparator : filePath ++ ".js"
202− externsFile = "externs" ++ pathSeparator : filePath ++ ".externs"
203−
204− (Module _ elaborated _, env') <- liftError . runCheck' opts env $ typeCheckModule Nothing m
205−
206− regrouped <- liftError . stringifyErrorStack True . createBindingGroups moduleName' . collapseBindingGroups $ elaborated
207−
208− let mod' = Module moduleName' regrouped exps
209− js = moduleToJs opts mod' env'
210− exts = moduleToPs mod' env'
211− js' = maybe "" (prettyPrintJS . return . wrapExportsContainer opts . return) js
212−
213− writeTextFile jsFile js'
214− writeTextFile externsFile exts
215−
216− go env' ms'
217−
218−toFileName :: ModuleName -> FilePath
219−toFileName (ModuleName ps) = intercalate [pathSeparator] . map runProperName $ ps
220−
221−rebuildIfNecessary :: (Functor m, Monad m, MonadMake m) => M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
222−rebuildIfNecessary _ _ [] = return []
223−rebuildIfNecessary graph toRebuild (m@(Module moduleName' _ _) : ms) | moduleName' `S.member` toRebuild = do
224− let deps = fromMaybe [] $ moduleName' `M.lookup` graph
225− toRebuild' = toRebuild `S.union` S.fromList deps
226− (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms
227−rebuildIfNecessary graph toRebuild (Module moduleName' _ _ : ms) = do
228− let externsFile = "externs" ++ pathSeparator : toFileName moduleName' ++ ".externs"
229− externs <- readTextFile externsFile
230− externsModules <- liftError . either (Left . show) Right $ P.runIndentParser externsFile P.parseModules externs
231− case externsModules of
232− [m'@(Module moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms
233− _ -> liftError . Left $ "Externs file " ++ externsFile ++ " was invalid"
234−
235−reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
236−reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
237− where
238− combine :: (Ord a) => [(a, b)] -> M.Map a [b]
239− combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
240−
241−-- |
242−-- Add an import declaration for the Prelude to a module if it does not already explicitly import
243−-- it.
244−--
245−importPrelude :: Module -> Module
246−importPrelude m@(Module mn decls exps) =
247− if isPreludeImport `any` decls || mn == prelude then m
248− else Module mn (preludeImport : decls) exps
249− where
250− prelude = ModuleName [ProperName C.prelude]
251− isPreludeImport (ImportDeclaration (ModuleName [ProperName mn']) _ _) | mn' == C.prelude = True
252− isPreludeImport (PositionedDeclaration _ d) = isPreludeImport d
253− isPreludeImport _ = False
254− preludeImport = ImportDeclaration prelude Nothing Nothing
src/Language/PureScript/CodeGen.hsdeleted−25
@@ -1,25 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.CodeGen
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- A collection of modules related to code generation:
13−--
14−-- [@Language.PureScript.CodeGen.JS@] Code generator for Javascript
15−--
16−-- [@Language.PureScript.CodeGen.Externs@] Code generator for extern (foreign import) files
17−--
18−-- [@Language.PureScript.CodeGen.Optimize@] Optimization passes for generated Javascript
19−--
20−-----------------------------------------------------------------------------
21−
22−module Language.PureScript.CodeGen (module C) where
23−
24−import Language.PureScript.CodeGen.JS as C
25−import Language.PureScript.CodeGen.Externs as C
src/Language/PureScript/CodeGen/Common.hsdeleted−140
@@ -1,140 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.CodeGen.Common
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Common code generation utility functions
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.CodeGen.Common where
17−
18−import Data.Char
19−import Data.List (intercalate)
20−import Language.PureScript.Names
21−
22−-- |
23−-- Convert an Ident into a valid Javascript identifier:
24−--
25−-- * Alphanumeric characters are kept unmodified.
26−--
27−-- * Reserved javascript identifiers are prefixed with '$$'.
28−--
29−-- * Symbols are prefixed with '$' followed by a symbol name or their ordinal value.
30−--
31−identToJs :: Ident -> String
32−identToJs (Ident name) | nameIsJsReserved name = "$$" ++ name
33−identToJs (Ident name) = concatMap identCharToString name
34−identToJs (Op op) = concatMap identCharToString op
35−
36−-- |
37−-- Attempts to find a human-readable name for a symbol, if none has been specified returns the
38−-- ordinal value.
39−--
40−identCharToString :: Char -> String
41−identCharToString c | isAlphaNum c = [c]
42−identCharToString '_' = "_"
43−identCharToString '.' = "$dot"
44−identCharToString '$' = "$dollar"
45−identCharToString '~' = "$tilde"
46−identCharToString '=' = "$eq"
47−identCharToString '<' = "$less"
48−identCharToString '>' = "$greater"
49−identCharToString '!' = "$bang"
50−identCharToString '#' = "$hash"
51−identCharToString '%' = "$percent"
52−identCharToString '^' = "$up"
53−identCharToString '&' = "$amp"
54−identCharToString '|' = "$bar"
55−identCharToString '*' = "$times"
56−identCharToString '/' = "$div"
57−identCharToString '+' = "$plus"
58−identCharToString '-' = "$minus"
59−identCharToString ':' = "$colon"
60−identCharToString '\\' = "$bslash"
61−identCharToString '?' = "$qmark"
62−identCharToString '@' = "$at"
63−identCharToString '\'' = "$prime"
64−identCharToString c = '$' : show (ord c)
65−
66−-- |
67−-- Checks whether an identifier name is reserved in Javascript.
68−--
69−nameIsJsReserved :: String -> Bool
70−nameIsJsReserved name =
71− name `elem` [ "abstract"
72− , "arguments"
73− , "boolean"
74− , "break"
75− , "byte"
76− , "case"
77− , "catch"
78− , "char"
79− , "class"
80− , "const"
81− , "continue"
82− , "debugger"
83− , "default"
84− , "delete"
85− , "do"
86− , "double"
87− , "else"
88− , "enum"
89− , "eval"
90− , "export"
91− , "extends"
92− , "final"
93− , "finally"
94− , "float"
95− , "for"
96− , "function"
97− , "goto"
98− , "if"
99− , "implements"
100− , "import"
101− , "in"
102− , "instanceof"
103− , "int"
104− , "interface"
105− , "let"
106− , "long"
107− , "native"
108− , "new"
109− , "package"
110− , "private"
111− , "protected"
112− , "public"
113− , "return"
114− , "short"
115− , "static"
116− , "super"
117− , "switch"
118− , "synchronized"
119− , "this"
120− , "throw"
121− , "throws"
122− , "transient"
123− , "try"
124− , "typeof"
125− , "var"
126− , "void"
127− , "volatile"
128− , "while"
129− , "with"
130− , "yield" ]
131−
132−-- |
133−-- Test if a string is a valid JS identifier (may return false negatives)
134−--
135−isIdent :: String -> Bool
136−isIdent s@(first : rest) | not (nameIsJsReserved s) && isAlpha first && all isAlphaNum rest = True
137−isIdent _ = False
138−
139−moduleNameToJs :: ModuleName -> String
140−moduleNameToJs (ModuleName pns) = intercalate "_" (runProperName `map` pns)
src/Language/PureScript/CodeGen/Externs.hsdeleted−96
@@ -1,96 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.CodeGen.Externs
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module generates code for \"externs\" files, i.e. files containing only foreign import declarations.
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.CodeGen.Externs (
17− moduleToPs
18−) where
19−
20−import Data.Maybe (fromMaybe, mapMaybe)
21−import Data.List (intercalate, find)
22−
23−import qualified Data.Map as M
24−
25−import Control.Monad.Writer
26−
27−import Language.PureScript.TypeClassDictionaries
28−import Language.PureScript.Declarations
29−import Language.PureScript.Pretty
30−import Language.PureScript.Names
31−import Language.PureScript.Environment
32−
33−-- |
34−-- Generate foreign imports for all declarations in a module
35−--
36−moduleToPs :: Module -> Environment -> String
37−moduleToPs (Module _ _ Nothing) _ = error "Module exports were not elaborated in moduleToPs"
38−moduleToPs (Module moduleName ds (Just exts)) env = intercalate "\n" . execWriter $ do
39− tell [ "module " ++ runModuleName moduleName ++ " where"]
40− mapM_ declToPs ds
41− mapM_ exportToPs exts
42− where
43−
44− declToPs :: Declaration -> Writer [String] ()
45− declToPs (ImportDeclaration mn _ _) = tell ["import " ++ show mn ++ " ()"]
46− declToPs (FixityDeclaration (Fixity assoc prec) ident) =
47− tell [ unwords [ show assoc, show prec, ident ] ]
48− declToPs (PositionedDeclaration _ d) = declToPs d
49− declToPs _ = return ()
50−
51− exportToPs :: DeclarationRef -> Writer [String] ()
52− exportToPs (PositionedDeclarationRef _ r) = exportToPs r
53− exportToPs (TypeRef pn dctors) = do
54− case Qualified (Just moduleName) pn `M.lookup` types env of
55− Nothing -> error $ show pn ++ " has no kind in exportToPs"
56− Just (kind, ExternData) ->
57− tell ["foreign import data " ++ show pn ++ " :: " ++ prettyPrintKind kind]
58− Just (_, DataType args tys) -> do
59− let dctors' = fromMaybe (map fst tys) dctors
60− printDctor dctor = case dctor `lookup` tys of
61− Nothing -> Nothing
62− Just tyArgs -> Just $ show dctor ++ " " ++ unwords (map prettyPrintTypeAtom tyArgs)
63− tell ["data " ++ show pn ++ " " ++ unwords args ++ (if null dctors' then "" else " = " ++ intercalate " | " (mapMaybe printDctor dctors'))]
64− Just (_, TypeSynonym) ->
65− case Qualified (Just moduleName) pn `M.lookup` typeSynonyms env of
66− Nothing -> error $ show pn ++ " has no type synonym info in exportToPs"
67− Just (args, synTy) ->
68− tell ["type " ++ show pn ++ " " ++ unwords args ++ " = " ++ prettyPrintType synTy]
69− _ -> error "Invalid input in exportToPs"
70−
71− exportToPs (ValueRef ident) =
72− case (moduleName, ident) `M.lookup` names env of
73− Nothing -> error $ show ident ++ " has no type in exportToPs"
74− Just (ty, nameKind) | nameKind == Value || nameKind == Extern ForeignImport || nameKind == Extern InlineJavascript ->
75− tell ["foreign import " ++ show ident ++ " :: " ++ prettyPrintType ty]
76− _ -> return ()
77− exportToPs (TypeClassRef className) =
78− case Qualified (Just moduleName) className `M.lookup` typeClasses env of
79− Nothing -> error $ show className ++ " has no type class definition in exportToPs"
80− Just (args, members, implies) -> do
81− let impliesString = if null implies then "" else "(" ++ intercalate ", " (map (\(pn, tys') -> show pn ++ " " ++ unwords (map prettyPrintTypeAtom tys')) implies) ++ ") <= "
82− tell ["class " ++ impliesString ++ show className ++ " " ++ unwords args ++ " where"]
83− forM_ (filter (isValueExported . fst) members) $ \(member ,ty) ->
84− tell [ " " ++ show member ++ " :: " ++ prettyPrintType ty ]
85−
86− exportToPs (TypeInstanceRef ident) = do
87− let TypeClassDictionaryInScope { tcdClassName = className, tcdInstanceTypes = tys, tcdDependencies = deps} =
88− fromMaybe (error $ "Type class instance has no dictionary in exportToPs") . find ((== Qualified (Just moduleName) ident) . tcdName) $ typeClassDictionaries env
89− let constraintsText = case fromMaybe [] deps of
90− [] -> ""
91− cs -> "(" ++ intercalate ", " (map (\(pn, tys') -> show pn ++ " " ++ unwords (map prettyPrintTypeAtom tys')) cs) ++ ") => "
92− tell ["foreign import instance " ++ show ident ++ " :: " ++ constraintsText ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys)]
93−
94− isValueExported :: Ident -> Bool
95− isValueExported ident = ValueRef ident `elem` exts
96−
src/Language/PureScript/CodeGen/JS.hsdeleted−340
@@ -1,340 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.CodeGen.JS
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module generates code in the simplified Javascript intermediate representation from Purescript code
13−--
14−-----------------------------------------------------------------------------
15−
16−{-# LANGUAGE DoAndIfThenElse #-}
17−
18−module Language.PureScript.CodeGen.JS (
19− module AST,
20− declToJs,
21− moduleToJs,
22− wrapExportsContainer,
23− isIdent
24−) where
25−
26−import Data.Maybe (fromMaybe, mapMaybe)
27−import Data.Function (on)
28−
29−import Control.Arrow (second)
30−import Control.Monad (replicateM, forM)
31−
32−import qualified Data.Map as M
33−
34−import Language.PureScript.Names
35−import Language.PureScript.Scope
36−import Language.PureScript.Declarations
37−import Language.PureScript.CodeGen.Monad
38−import Language.PureScript.Options
39−import Language.PureScript.CodeGen.JS.AST as AST
40−import Language.PureScript.Types
41−import Language.PureScript.Optimizer
42−import Language.PureScript.CodeGen.Common
43−import Language.PureScript.Environment
44−import qualified Language.PureScript.Constants as C
45−
46−-- |
47−-- Generate code in the simplified Javascript intermediate representation for all declarations in a
48−-- module.
49−--
50−moduleToJs :: Options -> Module -> Environment -> Maybe JS
51−moduleToJs opts (Module name decls (Just exps)) env =
52− case jsDecls of
53− [] -> Nothing
54− _ -> Just $ JSAssignment (JSAccessor (moduleNameToJs name) (JSVar C._ps)) $
55− JSApp (JSFunction Nothing [] (JSBlock $
56− JSVariableIntroduction "module" (Just $ JSObjectLiteral []) :
57− jsDecls ++
58− jsExports ++
59− [JSReturn $ JSVar "module"])) []
60− where
61− jsDecls = (concat $ mapMaybe (\decl -> fmap (map $ optimize opts) $ declToJs opts name decl env) decls)
62− jsExports = concatMap exportToJs exps
63−moduleToJs _ _ _ = error "Exports should have been elaborated in name desugaring"
64−
65−-- |
66−-- Generate code in the simplified Javascript intermediate representation for a declaration
67−--
68−declToJs :: Options -> ModuleName -> Declaration -> Environment -> Maybe [JS]
69−declToJs opts mp (ValueDeclaration ident _ _ _ val) e =
70− Just [JSVariableIntroduction (identToJs ident) (Just (valueToJs opts mp e val))]
71−declToJs opts mp (BindingGroupDeclaration vals) e =
72− Just $ flip concatMap vals $ \(ident, _, val) ->
73− [JSVariableIntroduction (identToJs ident) (Just (valueToJs opts mp e val))]
74−declToJs _ mp (DataDeclaration _ _ ctors) _ =
75− Just $ flip concatMap ctors $ \(pn@(ProperName ctor), tys) ->
76− [JSVariableIntroduction ctor (Just (go pn 0 tys []))]
77− where
78− go :: ProperName -> Integer -> [Type] -> [JS] -> JS
79− go pn _ [] values =
80− JSObjectLiteral [ ("ctor", JSStringLiteral (show (Qualified (Just mp) pn))), ("values", JSArrayLiteral $ reverse values) ]
81− go pn index (_ : tys') values =
82− JSFunction Nothing ["value" ++ show index]
83− (JSBlock [JSReturn (go pn (index + 1) tys' (JSVar ("value" ++ show index) : values))])
84−declToJs opts mp (DataBindingGroupDeclaration ds) e = Just $ concat $ mapMaybe (flip (declToJs opts mp) e) ds
85−declToJs _ _ (ExternDeclaration _ _ (Just js) _) _ = Just [js]
86−declToJs opts mp (PositionedDeclaration _ d) e = declToJs opts mp d e
87−declToJs _ _ _ _ = Nothing
88−
89−-- |
90−-- Generate code in the simplified Javascript intermediate representation for an export from a
91−-- module.
92−--
93−exportToJs :: DeclarationRef -> [JS]
94−exportToJs (TypeRef _ (Just dctors)) = flip map dctors (export . Ident . runProperName)
95−exportToJs (ValueRef name) = [export name]
96−exportToJs (TypeInstanceRef name) = [export name]
97−exportToJs _ = []
98−
99−-- |
100−-- Generate code in the simplified Javascript intermediate representation for assigning an exported
101−-- value to the current module object.
102−--
103−export :: Ident -> JS
104−export ident = JSAssignment (accessor ident (JSVar "module")) (var ident)
105−
106−-- |
107−-- Generate code in the simplified Javascript intermediate representation for a variable based on a
108−-- PureScript identifier.
109−--
110−var :: Ident -> JS
111−var = JSVar . identToJs
112−
113−-- |
114−-- Generate code in the simplified Javascript intermediate representation for an accessor based on
115−-- a PureScript identifier. If the name is not valid in Javascript (symbol based, reserved name) an
116−-- indexer is returned.
117−--
118−accessor :: Ident -> JS -> JS
119−accessor (Ident prop) = accessorString prop
120−accessor (Op op) = JSIndexer (JSStringLiteral op)
121−
122−accessorString :: String -> JS -> JS
123−accessorString prop | isIdent prop = JSAccessor prop
124− | otherwise = JSIndexer (JSStringLiteral prop)
125−
126−-- |
127−-- Generate code in the simplified Javascript intermediate representation for a value or expression.
128−--
129−valueToJs :: Options -> ModuleName -> Environment -> Value -> JS
130−valueToJs _ _ _ (NumericLiteral n) = JSNumericLiteral n
131−valueToJs _ _ _ (StringLiteral s) = JSStringLiteral s
132−valueToJs _ _ _ (BooleanLiteral b) = JSBooleanLiteral b
133−valueToJs opts m e (ArrayLiteral xs) = JSArrayLiteral (map (valueToJs opts m e) xs)
134−valueToJs opts m e (ObjectLiteral ps) = JSObjectLiteral (map (second (valueToJs opts m e)) ps)
135−valueToJs opts m e (ObjectUpdate o ps) = extendObj (valueToJs opts m e o) (map (second (valueToJs opts m e)) ps)
136−valueToJs _ m _ (Constructor name) = qualifiedToJS m (Ident . runProperName) name
137−valueToJs opts m e (Case values binders) = bindersToJs opts m e binders (map (valueToJs opts m e) values)
138−valueToJs opts m e (IfThenElse cond th el) = JSConditional (valueToJs opts m e cond) (valueToJs opts m e th) (valueToJs opts m e el)
139−valueToJs opts m e (Accessor prop val) = accessorString prop (valueToJs opts m e val)
140−valueToJs opts m e (App val arg) = JSApp (valueToJs opts m e val) [valueToJs opts m e arg]
141−valueToJs opts m e (Let ds val) = JSApp (JSFunction Nothing [] (JSBlock (concat (mapMaybe (flip (declToJs opts m) e) ds) ++ [JSReturn $ valueToJs opts m e val]))) []
142−valueToJs opts m e (Abs (Left arg) val) = JSFunction Nothing [identToJs arg] (JSBlock [JSReturn (valueToJs opts m (bindName m arg e) val)])
143−valueToJs opts m e (TypedValue _ (Abs (Left arg) val) ty) | optionsPerformRuntimeTypeChecks opts = let arg' = identToJs arg in JSFunction Nothing [arg'] (JSBlock $ runtimeTypeChecks arg' ty ++ [JSReturn (valueToJs opts m e val)])
144−valueToJs _ m _ (Var ident) = varToJs m ident
145−valueToJs opts m e (TypedValue _ val _) = valueToJs opts m e val
146−valueToJs opts m e (PositionedValue _ val) = valueToJs opts m e val
147−valueToJs _ _ _ (TypeClassDictionary _ _ _) = error "Type class dictionary was not replaced"
148−valueToJs _ _ _ _ = error "Invalid argument to valueToJs"
149−
150−-- |
151−-- Shallow copy an object.
152−--
153−extendObj :: JS -> [(String, JS)] -> JS
154−extendObj obj sts = JSApp (JSFunction Nothing [] block) []
155− where
156− [newObj, key] = take 2 . map identToJs . unusedNames $ (obj, sts)
157− jsKey = JSVar key
158− jsNewObj = JSVar newObj
159− block = JSBlock (objAssign:copy:extend ++ [JSReturn jsNewObj])
160− objAssign = JSVariableIntroduction newObj (Just $ JSObjectLiteral [])
161− copy = JSForIn key obj $ JSBlock [JSIfElse cond assign Nothing]
162− cond = JSApp (JSAccessor "hasOwnProperty" obj) [jsKey]
163− assign = JSBlock [JSAssignment (JSIndexer jsKey jsNewObj) (JSIndexer jsKey obj)]
164− stToAssign (s, js) = JSAssignment (JSAccessor s jsNewObj) js
165− extend = map stToAssign sts
166−
167−-- |
168−-- Temporarily extends the environment with a single local variable name
169−--
170−bindName :: ModuleName -> Ident -> Environment -> Environment
171−bindName m ident = bindNames m [ident]
172−
173−-- |
174−-- Temporarily extends the environment to include local variable names introduced by lambda
175−-- abstractions or case statements
176−--
177−bindNames :: ModuleName -> [Ident] -> Environment -> Environment
178−bindNames m idents env = env { names = M.fromList [ ((m, ident), (noType, LocalVariable)) | ident <- idents ] `M.union` names env }
179− where
180− noType = error "Temporary lambda variable type was read"
181−
182−
183−-- |
184−-- Generate code in the simplified Javascript intermediate representation for runtime type checks.
185−--
186−runtimeTypeChecks :: String -> Type -> [JS]
187−runtimeTypeChecks arg ty =
188− let
189− argTy = getFunctionArgumentType ty
190− in
191− maybe [] (argumentCheck (JSVar arg)) argTy
192− where
193− getFunctionArgumentType :: Type -> Maybe Type
194− getFunctionArgumentType (TypeApp (TypeApp t funArg) _) | t == tyFunction = Just funArg
195− getFunctionArgumentType (ForAll _ ty' _) = getFunctionArgumentType ty'
196− getFunctionArgumentType _ = Nothing
197− argumentCheck :: JS -> Type -> [JS]
198− argumentCheck val t | t == tyNumber = [typeCheck val "number"]
199− argumentCheck val t | t == tyString = [typeCheck val "string"]
200− argumentCheck val t | t == tyBoolean = [typeCheck val "boolean"]
201− argumentCheck val (TypeApp t _) | t == tyArray = [arrayCheck val]
202− argumentCheck val (TypeApp t row) | t == tyObject =
203− let
204− (pairs, _) = rowToList row
205− in
206− typeCheck val "object" : concatMap (\(prop, ty') -> argumentCheck (accessorString prop val) ty') pairs
207− argumentCheck val (TypeApp (TypeApp t _) _) | t == tyFunction = [typeCheck val "function"]
208− argumentCheck val (ForAll _ ty' _) = argumentCheck val ty'
209− argumentCheck _ _ = []
210− typeCheck :: JS -> String -> JS
211− typeCheck js ty' = JSIfElse (JSBinary NotEqualTo (JSTypeOf js) (JSStringLiteral ty')) (JSBlock [JSThrow (JSStringLiteral $ ty' ++ " expected")]) Nothing
212− arrayCheck :: JS -> JS
213− arrayCheck js = JSIfElse (JSUnary Not (JSApp (JSAccessor "isArray" (JSVar "Array")) [js])) (JSBlock [JSThrow (JSStringLiteral "Array expected")]) Nothing
214−
215−-- |
216−-- Generate code in the simplified Javascript intermediate representation for a reference to a
217−-- variable.
218−--
219−varToJs :: ModuleName -> Qualified Ident -> JS
220−varToJs _ (Qualified Nothing ident) = var ident
221−varToJs m qual = qualifiedToJS m id qual
222−
223−-- |
224−-- Generate code in the simplified Javascript intermediate representation for a reference to a
225−-- variable that may have a qualified name.
226−--
227−qualifiedToJS :: ModuleName -> (a -> Ident) -> Qualified a -> JS
228−qualifiedToJS m f (Qualified (Just m') a) | m /= m' = accessor (f a) (JSAccessor (moduleNameToJs m') $ JSVar C._ps)
229−qualifiedToJS _ f (Qualified _ a) = JSVar $ identToJs (f a)
230−
231−-- |
232−-- Generate code in the simplified Javascript intermediate representation for pattern match binders
233−-- and guards.
234−--
235−bindersToJs :: Options -> ModuleName -> Environment -> [CaseAlternative] -> [JS] -> JS
236−bindersToJs opts m e binders vals = runGen (map identToJs (unusedNames (binders, vals))) $ do
237− valNames <- replicateM (length vals) fresh
238− jss <- forM binders $ \(CaseAlternative bs grd result) -> go valNames [JSReturn (valueToJs opts m (bindNames m (binderNames bs) e) result)] bs grd
239− return $ JSApp (JSFunction Nothing valNames (JSBlock (concat jss ++ [JSThrow (JSStringLiteral "Failed pattern match")])))
240− vals
241− where
242− go :: [String] -> [JS] -> [Binder] -> Maybe Guard -> Gen [JS]
243− go _ done [] Nothing = return done
244− go _ done [] (Just cond) = return [JSIfElse (valueToJs opts m e cond) (JSBlock done) Nothing]
245− go (v:vs) done' (b:bs) grd = do
246− done'' <- go vs done' bs grd
247− binderToJs m e v done'' b
248− go _ _ _ _ = error "Invalid arguments to bindersToJs"
249−
250−-- |
251−-- Generate code in the simplified Javascript intermediate representation for a pattern match
252−-- binder.
253−--
254−binderToJs :: ModuleName -> Environment -> String -> [JS] -> Binder -> Gen [JS]
255−binderToJs _ _ _ done NullBinder = return done
256−binderToJs _ _ varName done (StringBinder str) =
257− return [JSIfElse (JSBinary EqualTo (JSVar varName) (JSStringLiteral str)) (JSBlock done) Nothing]
258−binderToJs _ _ varName done (NumberBinder num) =
259− return [JSIfElse (JSBinary EqualTo (JSVar varName) (JSNumericLiteral num)) (JSBlock done) Nothing]
260−binderToJs _ _ varName done (BooleanBinder True) =
261− return [JSIfElse (JSVar varName) (JSBlock done) Nothing]
262−binderToJs _ _ varName done (BooleanBinder False) =
263− return [JSIfElse (JSUnary Not (JSVar varName)) (JSBlock done) Nothing]
264−binderToJs _ _ varName done (VarBinder ident) =
265− return (JSVariableIntroduction (identToJs ident) (Just (JSVar varName)) : done)
266−binderToJs m e varName done (ConstructorBinder ctor bs) = do
267− js <- go 0 done bs
268− if isOnlyConstructor e ctor
269− then
270− return js
271− else
272− return [JSIfElse (JSBinary EqualTo (JSAccessor "ctor" (JSVar varName)) (JSStringLiteral (show ctor)))
273− (JSBlock js)
274− Nothing]
275− where
276− go :: Integer -> [JS] -> [Binder] -> Gen [JS]
277− go _ done' [] = return done'
278− go index done' (binder:bs') = do
279− argVar <- fresh
280− done'' <- go (index + 1) done' bs'
281− js <- binderToJs m e argVar done'' binder
282− return (JSVariableIntroduction argVar (Just (JSIndexer (JSNumericLiteral (Left index)) (JSAccessor "values" (JSVar varName)))) : js)
283−binderToJs m e varName done (ObjectBinder bs) = go done bs
284− where
285− go :: [JS] -> [(String, Binder)] -> Gen [JS]
286− go done' [] = return done'
287− go done' ((prop, binder):bs') = do
288− propVar <- fresh
289− done'' <- go done' bs'
290− js <- binderToJs m e propVar done'' binder
291− return (JSVariableIntroduction propVar (Just (accessorString prop (JSVar varName))) : js)
292−binderToJs m e varName done (ArrayBinder bs) = do
293− js <- go done 0 bs
294− return [JSIfElse (JSBinary EqualTo (JSAccessor "length" (JSVar varName)) (JSNumericLiteral (Left (fromIntegral $ length bs)))) (JSBlock js) Nothing]
295− where
296− go :: [JS] -> Integer -> [Binder] -> Gen [JS]
297− go done' _ [] = return done'
298− go done' index (binder:bs') = do
299− elVar <- fresh
300− done'' <- go done' (index + 1) bs'
301− js <- binderToJs m e elVar done'' binder
302− return (JSVariableIntroduction elVar (Just (JSIndexer (JSNumericLiteral (Left index)) (JSVar varName))) : js)
303−binderToJs m e varName done (ConsBinder headBinder tailBinder) = do
304− headVar <- fresh
305− tailVar <- fresh
306− js1 <- binderToJs m e headVar done headBinder
307− js2 <- binderToJs m e tailVar js1 tailBinder
308− return [JSIfElse (JSBinary GreaterThan (JSAccessor "length" (JSVar varName)) (JSNumericLiteral (Left 0))) (JSBlock
309− ( JSVariableIntroduction headVar (Just (JSIndexer (JSNumericLiteral (Left 0)) (JSVar varName))) :
310− JSVariableIntroduction tailVar (Just (JSApp (JSAccessor "slice" (JSVar varName)) [JSNumericLiteral (Left 1)])) :
311− js2
312− )) Nothing]
313−binderToJs m e varName done (NamedBinder ident binder) = do
314− js <- binderToJs m e varName done binder
315− return (JSVariableIntroduction (identToJs ident) (Just (JSVar varName)) : js)
316−binderToJs m e varName done (PositionedBinder _ binder) =
317− binderToJs m e varName done binder
318−
319−-- |
320−-- Checks whether a data constructor is the only constructor for that type, used to simplify the
321−-- check when generating code for binders.
322−--
323−isOnlyConstructor :: Environment -> Qualified ProperName -> Bool
324−isOnlyConstructor e ctor =
325− let ty = fromMaybe (error "Data constructor not found") $ ctor `M.lookup` dataConstructors e
326− in numConstructors (ctor, ty) == 1
327− where
328− numConstructors ty = length $ filter (((==) `on` typeConstructor) ty) $ M.toList $ dataConstructors e
329− typeConstructor (Qualified (Just moduleName) _, (tyCtor, _)) = (moduleName, tyCtor)
330− typeConstructor _ = error "Invalid argument to isOnlyConstructor"
331−
332−wrapExportsContainer :: Options -> [JS] -> JS
333−wrapExportsContainer opts modules = JSApp (JSFunction Nothing [C._ps] $ JSBlock $ JSStringLiteral "use strict" : modules) [exportSelector]
334− where
335− exportSelector = JSConditional (JSBinary And (JSBinary NotEqualTo (JSTypeOf $ JSVar "module") (JSStringLiteral "undefined")) (JSAccessor "exports" (JSVar "module")))
336− (JSAccessor "exports" (JSVar "module"))
337− (JSConditional (JSBinary NotEqualTo (JSTypeOf $ JSVar "window") (JSStringLiteral "undefined"))
338− (JSAssignment (JSAccessor browserNamespace (JSVar "window")) (JSBinary Or (JSAccessor browserNamespace (JSVar "window")) (JSObjectLiteral [])))
339− (JSApp (JSFunction Nothing [] $ JSBlock [JSThrow $ JSStringLiteral "PureScript doesn't know how to export modules in the current environment"]) []))
340− browserNamespace = optionsBrowserNamespace opts
src/Language/PureScript/CodeGen/JS/AST.hsdeleted−235
@@ -1,235 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.CodeGen.JS.AST
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Data types for the intermediate simplified-Javascript AST
13−--
14−-----------------------------------------------------------------------------
15−
16−{-# LANGUAGE DeriveDataTypeable #-}
17−
18−module Language.PureScript.CodeGen.JS.AST where
19−
20−import Data.Data
21−
22−-- |
23−-- Built-in unary operators
24−--
25−data UnaryOperator
26− -- |
27− -- Numeric negation
28− --
29− = Negate
30− -- |
31− -- Boolean negation
32− --
33− | Not
34− -- |
35− -- Bitwise negation
36− --
37− | BitwiseNot
38− -- |
39− -- Numeric unary \'plus\'
40− --
41− | Positive deriving (Show, Eq, Data, Typeable)
42−
43−-- |
44−-- Built-in binary operators
45−--
46−data BinaryOperator
47− -- |
48− -- Numeric addition
49− --
50− = Add
51− -- |
52− -- Numeric subtraction
53− --
54− | Subtract
55− -- |
56− -- Numeric multiplication
57− --
58− | Multiply
59− -- |
60− -- Numeric division
61− --
62− | Divide
63− -- |
64− -- Remainder
65− --
66− | Modulus
67− -- |
68− -- Generic equality test
69− --
70− | EqualTo
71− -- |
72− -- Generic inequality test
73− --
74− | NotEqualTo
75− -- |
76− -- Numeric less-than
77− --
78− | LessThan
79− -- |
80− -- Numeric less-than-or-equal
81− --
82− | LessThanOrEqualTo
83− -- |
84− -- Numeric greater-than
85− --
86− | GreaterThan
87− -- |
88− -- Numeric greater-than-or-equal
89− --
90− | GreaterThanOrEqualTo
91− -- |
92− -- Boolean and
93− --
94− | And
95− -- |
96− -- Boolean or
97− --
98− | Or
99− -- |
100− -- Bitwise and
101− --
102− | BitwiseAnd
103− -- |
104− -- Bitwise or
105− --
106− | BitwiseOr
107− -- |
108− -- Bitwise xor
109− --
110− | BitwiseXor
111− -- |
112− -- Bitwise left shift
113− --
114− | ShiftLeft
115− -- |
116− -- Bitwise right shift
117− --
118− | ShiftRight
119− -- |
120− -- Bitwise right shift with zero-fill
121− --
122− | ZeroFillShiftRight deriving (Show, Eq, Data, Typeable)
123−
124−-- |
125−-- Data type for simplified Javascript expressions
126−--
127−data JS
128− -- |
129− -- A numeric literal
130− --
131− = JSNumericLiteral (Either Integer Double)
132− -- |
133− -- A string literal
134− --
135− | JSStringLiteral String
136− -- |
137− -- A boolean literal
138− --
139− | JSBooleanLiteral Bool
140− -- |
141− -- A unary operator application
142− --
143− | JSUnary UnaryOperator JS
144− -- |
145− -- A binary operator application
146− --
147− | JSBinary BinaryOperator JS JS
148− -- |
149− -- An array literal
150− --
151− | JSArrayLiteral [JS]
152− -- |
153− -- An array indexer expression
154− --
155− | JSIndexer JS JS
156− -- |
157− -- An object literal
158− --
159− | JSObjectLiteral [(String, JS)]
160− -- |
161− -- An object property accessor expression
162− --
163− | JSAccessor String JS
164− -- |
165− -- A function introduction (optional name, arguments, body)
166− --
167− | JSFunction (Maybe String) [String] JS
168− -- |
169− -- Function application
170− --
171− | JSApp JS [JS]
172− -- |
173− -- Variable
174− --
175− | JSVar String
176− -- |
177− -- Conditional expression
178− --
179− | JSConditional JS JS JS
180− -- |
181− -- A block of expressions in braces
182− --
183− | JSBlock [JS]
184− -- |
185− -- A variable introduction and optional initialization
186− --
187− | JSVariableIntroduction String (Maybe JS)
188− -- |
189− -- A variable assignment
190− --
191− | JSAssignment JS JS
192− -- |
193− -- While loop
194− --
195− | JSWhile JS JS
196− -- |
197− -- For loop
198− --
199− | JSFor String JS JS JS
200− -- |
201− -- ForIn loop
202− --
203− | JSForIn String JS JS
204− -- |
205− -- If-then-else statement
206− --
207− | JSIfElse JS JS (Maybe JS)
208− -- |
209− -- Return statement
210− --
211− | JSReturn JS
212− -- |
213− -- Throw statement
214− --
215− | JSThrow JS
216− -- |
217− -- Type-Of operator
218− --
219− | JSTypeOf JS
220− -- |
221− -- Labelled statement
222− --
223− | JSLabel String JS
224− -- |
225− -- Break statement
226− --
227− | JSBreak String
228− -- |
229− -- Continue statement
230− --
231− | JSContinue String
232− -- |
233− -- Raw Javascript (generated when parsing fails for an inline foreign import declaration)
234− --
235− | JSRaw String deriving (Show, Eq, Data, Typeable)
src/Language/PureScript/CodeGen/Monad.hsdeleted−43
@@ -1,43 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.CodeGen.Monad
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Code generation monad
13−--
14−-- This monad provides a supply of fresh names which can be used to create variables.
15−--
16−-----------------------------------------------------------------------------
17−
18−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
19−
20−module Language.PureScript.CodeGen.Monad where
21−
22−import Control.Monad.State
23−import Control.Applicative
24−
25−-- |
26−-- Code generation monad data type
27−--
28−newtype Gen a = Gen { unGen :: State [String] a } deriving (Functor, Applicative, Monad, MonadState [String])
29−
30−-- |
31−-- Run a computation in the code generation monad
32−--
33−runGen :: [String] -> Gen a -> a
34−runGen names = flip evalState names . unGen
35−
36−-- |
37−-- Generate a fresh name
38−--
39−fresh :: Gen String
40−fresh = do
41− (s:ss) <- get
42− put ss
43− return s
src/Language/PureScript/Constants.hsdeleted−198
@@ -1,198 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Constants
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Various constants which refer to things in the Prelude
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Constants where
17−
18−-- Prelude Operators
19−
20−($) :: String
21−($) = "$"
22−
23−(#) :: String
24−(#) = "#"
25−
26−(!!) :: String
27−(!!) = "!!"
28−
29−(++) :: String
30−(++) = "++"
31−
32−(>>=) :: String
33−(>>=) = ">>="
34−
35−(+) :: String
36−(+) = "+"
37−
38−(-) :: String
39−(-) = "-"
40−
41−(*) :: String
42−(*) = "*"
43−
44−(/) :: String
45−(/) = "/"
46−
47−(%) :: String
48−(%) = "%"
49−
50−(<) :: String
51−(<) = "<"
52−
53−(>) :: String
54−(>) = ">"
55−
56−(<=) :: String
57−(<=) = "<="
58−
59−(>=) :: String
60−(>=) = ">="
61−
62−(==) :: String
63−(==) = "=="
64−
65−(/=) :: String
66−(/=) = "/="
67−
68−(&) :: String
69−(&) = "&"
70−
71−bar :: String
72−bar = "|"
73−
74−(^) :: String
75−(^) = "^"
76−
77−(&&) :: String
78−(&&) = "&&"
79−
80−(||) :: String
81−(||) = "||"
82−
83−-- Prelude Operator Functions
84−
85−negate :: String
86−negate = "negate"
87−
88−shl :: String
89−shl = "shl"
90−
91−shr :: String
92−shr = "shr"
93−
94−zshr :: String
95−zshr = "zshr"
96−
97−complement :: String
98−complement = "complement"
99−
100−not :: String
101−not = "not"
102−
103−-- Prelude Values
104−
105−return :: String
106−return = "return"
107−
108−returnEscaped :: String
109−returnEscaped = "$return"
110−
111−untilE :: String
112−untilE = "untilE"
113−
114−whileE :: String
115−whileE = "whileE"
116−
117−runST :: String
118−runST = "runST"
119−
120−runSTArray :: String
121−runSTArray = "runSTArray"
122−
123−stRefValue :: String
124−stRefValue = "value"
125−
126−newSTRef :: String
127−newSTRef = "newSTRef"
128−
129−readSTRef :: String
130−readSTRef = "readSTRef"
131−
132−writeSTRef :: String
133−writeSTRef = "writeSTRef"
134−
135−modifySTRef :: String
136−modifySTRef = "modifySTRef"
137−
138−peekSTArray :: String
139−peekSTArray = "peekSTArray"
140−
141−pokeSTArray :: String
142−pokeSTArray = "pokeSTArray"
143−
144−-- Type Class Dictionary Names
145−
146−monadEffDictionary :: String
147−monadEffDictionary = "monadEff"
148−
149−numNumber :: String
150−numNumber = "numNumber"
151−
152−ordNumber :: String
153−ordNumber = "ordNumber"
154−
155−eqNumber :: String
156−eqNumber = "eqNumber"
157−
158−eqString :: String
159−eqString = "eqString"
160−
161−eqBoolean :: String
162−eqBoolean = "eqBoolean"
163−
164−bitsNumber :: String
165−bitsNumber = "bitsNumber"
166−
167−boolLikeBoolean :: String
168−boolLikeBoolean = "boolLikeBoolean"
169−
170−semigroupString :: String
171−semigroupString = "semigroupString"
172−
173−-- Main module
174−
175−main :: String
176−main = "main"
177−
178−-- Code Generation
179−
180−_ps :: String
181−_ps = "_ps"
182−
183−__superclasses :: String
184−__superclasses = "__superclasses"
185−
186−-- Modules
187−
188−prim :: String
189−prim = "Prim"
190−
191−prelude :: String
192−prelude = "Prelude"
193−
194−eff :: String
195−eff = "Control_Monad_Eff"
196−
197−st :: String
198−st = "Control_Monad_ST"
src/Language/PureScript/DeadCodeElimination.hsdeleted−105
@@ -1,105 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.DeadCodeElimination
4−-- Copyright : (c) 2014 Phil Freeman
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−--
13−-----------------------------------------------------------------------------
14−
15−module Language.PureScript.DeadCodeElimination (
16− eliminateDeadCode
17−) where
18−
19−import Data.Data
20−import Data.List
21−import Data.Graph
22−import Data.Generics
23−import Data.Maybe (mapMaybe)
24−
25−import Language.PureScript.Names
26−import Language.PureScript.Declarations
27−
28−-- |
29−-- Eliminate all declarations which are not a transitive dependency of the entry point module
30−--
31−eliminateDeadCode :: [ModuleName] -> [Module] -> [Module]
32−eliminateDeadCode entryPoints ms = map go ms
33− where
34− go (Module moduleName ds (Just exps)) = Module moduleName ds' (Just exps')
35− where
36− ds' = filter (isUsed moduleName graph vertexFor entryPointVertices) ds
37− exps' = mapMaybe (filterExport ds') exps
38− go _ = error "Exports should have been elaborated in name desugaring"
39− declarations = concatMap declarationsByModule ms
40− (graph, _, vertexFor) = graphFromEdges $ map (\(key, deps) -> (key, key, deps)) declarations
41− entryPointVertices = mapMaybe (vertexFor . fst) . filter (\((mn, _), _) -> mn `elem` entryPoints) $ declarations
42−
43− filterExport :: [Declaration] -> DeclarationRef -> Maybe DeclarationRef
44− filterExport decls r@(TypeRef name _) | (any $ typeExists name) decls = Just r
45− filterExport decls r@(ValueRef name) | (any $ valueExists name) decls = Just r
46− filterExport decls r@(TypeInstanceRef name) | (any $ valueExists name) decls = Just r
47− filterExport _ _ = Nothing
48−
49− valueExists :: Ident -> Declaration -> Bool
50− valueExists name (ValueDeclaration name' _ _ _ _) = name == name'
51− valueExists name (ExternDeclaration _ name' _ _) = name == name'
52− valueExists name (BindingGroupDeclaration decls) = any (\(name', _, _) -> name == name') decls
53− valueExists name (PositionedDeclaration _ d) = valueExists name d
54− valueExists _ _ = False
55−
56− typeExists :: ProperName -> Declaration -> Bool
57− typeExists name (DataDeclaration name' _ _) = name == name'
58− typeExists name (DataBindingGroupDeclaration decls) = any (typeExists name) decls
59− typeExists name (PositionedDeclaration _ d) = typeExists name d
60− typeExists _ _ = False
61−
62−type Key = (ModuleName, Either Ident ProperName)
63−
64−declarationsByModule :: Module -> [(Key, [Key])]
65−declarationsByModule (Module moduleName ds _) = concatMap go ds
66− where
67− go :: Declaration -> [(Key, [Key])]
68− go d@(ValueDeclaration name _ _ _ _) = [((moduleName, Left name), dependencies moduleName d)]
69− go (DataDeclaration _ _ dctors) = map (\(name, _) -> ((moduleName, Right name), [])) dctors
70− go (ExternDeclaration _ name _ _) = [((moduleName, Left name), [])]
71− go d@(BindingGroupDeclaration names') = map (\(name, _, _) -> ((moduleName, Left name), dependencies moduleName d)) names'
72− go (DataBindingGroupDeclaration ds') = concatMap go ds'
73− go (PositionedDeclaration _ d) = go d
74− go _ = []
75−
76−dependencies :: (Data d) => ModuleName -> d -> [Key]
77−dependencies moduleName = nub . everything (++) (mkQ [] values)
78− where
79− values :: Value -> [Key]
80− values (Var ident) = let (mn, name) = qualify moduleName ident in [(mn, Left name)]
81− values (Constructor (Qualified (Just mn) name)) = [(mn, Right name)]
82− values (Constructor (Qualified Nothing _)) = error "Found unqualified data constructor"
83− values _ = []
84−
85−isUsed :: ModuleName -> Graph -> (Key -> Maybe Vertex) -> [Vertex] -> Declaration -> Bool
86−isUsed moduleName graph vertexFor entryPointVertices (ValueDeclaration name _ _ _ _) =
87− let Just v' = vertexFor (moduleName, Left name)
88− in any (\v -> path graph v v') entryPointVertices
89−isUsed moduleName graph vertexFor entryPointVertices (FixityDeclaration _ name) =
90− let Just v' = vertexFor (moduleName, Left $ Op name)
91− in any (\v -> path graph v v') entryPointVertices
92−isUsed moduleName graph vertexFor entryPointVertices (DataDeclaration _ _ dctors) =
93− any (\(pn, _) -> let Just v' = vertexFor (moduleName, Right pn)
94− in any (\v -> path graph v v') entryPointVertices) dctors
95−isUsed moduleName graph vertexFor entryPointVertices (ExternDeclaration _ name _ _) =
96− let Just v' = vertexFor (moduleName, Left name)
97− in any (\v -> path graph v v') entryPointVertices
98−isUsed moduleName graph vertexFor entryPointVertices (BindingGroupDeclaration ds) =
99− any (\(name, _, _) -> let Just v' = vertexFor (moduleName, Left name)
100− in any (\v -> path graph v v') entryPointVertices) ds
101−isUsed moduleName graph vertexFor entryPointVertices (DataBindingGroupDeclaration ds) =
102− any (isUsed moduleName graph vertexFor entryPointVertices) ds
103−isUsed moduleName graph vertexFor entryPointVertices (PositionedDeclaration _ d) =
104− isUsed moduleName graph vertexFor entryPointVertices d
105−isUsed _ _ _ _ _ = True
src/Language/PureScript/Declarations.hsdeleted−445
@@ -1,445 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Declarations
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- | Data types for modules and declarations
12−--
13−-----------------------------------------------------------------------------
14−
15−{-# LANGUAGE DeriveDataTypeable #-}
16−
17−module Language.PureScript.Declarations where
18−
19−import Language.PureScript.Types
20−import Language.PureScript.Names
21−import Language.PureScript.Kinds
22−import Language.PureScript.TypeClassDictionaries
23−import Language.PureScript.CodeGen.JS.AST
24−import Language.PureScript.Environment
25−
26−import qualified Data.Data as D
27−import Data.Generics (mkQ, everything)
28−
29−-- |
30−-- A precedence level for an infix operator
31−--
32−type Precedence = Integer
33−
34−-- |
35−-- Associativity for infix operators
36−--
37−data Associativity = Infixl | Infixr | Infix deriving (D.Data, D.Typeable)
38−
39−instance Show Associativity where
40− show Infixl = "infixl"
41− show Infixr = "infixr"
42− show Infix = "infix"
43−
44−-- |
45−-- Source position information
46−--
47−data SourcePos = SourcePos
48− { -- |
49− -- Source name
50− --
51− sourceName :: String
52− -- |
53− -- Line number
54− --
55− , sourcePosLine :: Int
56− -- |
57− -- Column number
58− --
59− , sourcePosColumn :: Int
60− } deriving (D.Data, D.Typeable)
61−
62−instance Show SourcePos where
63− show sp = (sourceName sp) ++ " line " ++ show (sourcePosLine sp) ++ ", column " ++ show (sourcePosColumn sp)
64−
65−-- |
66−-- Fixity data for infix operators
67−--
68−data Fixity = Fixity Associativity Precedence deriving (Show, D.Data, D.Typeable)
69−
70−-- |
71−-- A module declaration, consisting of a module name, a list of declarations, and a list of the
72−-- declarations that are explicitly exported. If the export list is Nothing, everything is exported.
73−--
74−data Module = Module ModuleName [Declaration] (Maybe [DeclarationRef]) deriving (Show, D.Data, D.Typeable)
75−
76−-- |
77−-- An item in a list of explicit imports or exports
78−--
79−data DeclarationRef
80− -- |
81− -- A type constructor with data constructors
82− --
83− = TypeRef ProperName (Maybe [ProperName])
84− -- |
85− -- A value
86− --
87− | ValueRef Ident
88− -- |
89− -- A type class
90− --
91− | TypeClassRef ProperName
92− -- |
93− -- A type class instance, created during typeclass desugaring (name, class name, instance types)
94− --
95− | TypeInstanceRef Ident
96− -- |
97− -- A declaration reference with source position information
98− --
99− | PositionedDeclarationRef SourcePos DeclarationRef
100− deriving (Show, D.Data, D.Typeable)
101−
102−instance Eq DeclarationRef where
103− (TypeRef name dctors) == (TypeRef name' dctors') = name == name' && dctors == dctors'
104− (ValueRef name) == (ValueRef name') = name == name'
105− (TypeClassRef name) == (TypeClassRef name') = name == name'
106− (TypeInstanceRef name) == (TypeInstanceRef name') = name == name'
107− (PositionedDeclarationRef _ r) == r' = r == r'
108− r == (PositionedDeclarationRef _ r') = r == r'
109− _ == _ = False
110−
111−-- |
112−-- The data type of declarations
113−--
114−data Declaration
115− -- |
116− -- A data type declaration (name, arguments, data constructors)
117− --
118− = DataDeclaration ProperName [String] [(ProperName, [Type])]
119− -- |
120− -- A minimal mutually recursive set of data type declarations
121− --
122− | DataBindingGroupDeclaration [Declaration]
123− -- |
124− -- A type synonym declaration (name, arguments, type)
125− --
126− | TypeSynonymDeclaration ProperName [String] Type
127− -- |
128− -- A type declaration for a value (name, ty)
129− --
130− | TypeDeclaration Ident Type
131− -- |
132− -- A value declaration (name, top-level binders, optional guard, value)
133− --
134− | ValueDeclaration Ident NameKind [Binder] (Maybe Guard) Value
135− -- |
136− -- A minimal mutually recursive set of value declarations
137− --
138− | BindingGroupDeclaration [(Ident, NameKind, Value)]
139− -- |
140− -- A foreign import declaration (type, name, optional inline Javascript, type)
141− --
142− | ExternDeclaration ForeignImportType Ident (Maybe JS) Type
143− -- |
144− -- A data type foreign import (name, kind)
145− --
146− | ExternDataDeclaration ProperName Kind
147− -- |
148− -- A type class instance foreign import
149− --
150− | ExternInstanceDeclaration Ident [(Qualified ProperName, [Type])] (Qualified ProperName) [Type]
151− -- |
152− -- A fixity declaration (fixity data, operator name)
153− --
154− | FixityDeclaration Fixity String
155− -- |
156− -- A module import (module name, optional set of identifiers to import, optional "qualified as"
157− -- name)
158− --
159− | ImportDeclaration ModuleName (Maybe [DeclarationRef]) (Maybe ModuleName)
160− -- |
161− -- A type class declaration (name, argument, implies, member declarations)
162− --
163− | TypeClassDeclaration ProperName [String] [(Qualified ProperName, [Type])] [Declaration]
164− -- |
165− -- A type instance declaration (name, dependencies, class name, instance types, member
166− -- declarations)
167− --
168− | TypeInstanceDeclaration Ident [(Qualified ProperName, [Type])] (Qualified ProperName) [Type] [Declaration]
169− -- |
170− -- A declaration with source position information
171− --
172− | PositionedDeclaration SourcePos Declaration
173− deriving (Show, D.Data, D.Typeable)
174−
175−-- |
176−-- Test if a declaration is a value declaration
177−--
178−isValueDecl :: Declaration -> Bool
179−isValueDecl ValueDeclaration{} = True
180−isValueDecl (PositionedDeclaration _ d) = isValueDecl d
181−isValueDecl _ = False
182−
183−-- |
184−-- Test if a declaration is a data type or type synonym declaration
185−--
186−isDataDecl :: Declaration -> Bool
187−isDataDecl DataDeclaration{} = True
188−isDataDecl TypeSynonymDeclaration{} = True
189−isDataDecl (PositionedDeclaration _ d) = isDataDecl d
190−isDataDecl _ = False
191−
192−-- |
193−-- Test if a declaration is a module import
194−--
195−isImportDecl :: Declaration -> Bool
196−isImportDecl ImportDeclaration{} = True
197−isImportDecl (PositionedDeclaration _ d) = isImportDecl d
198−isImportDecl _ = False
199−
200−-- |
201−-- Test if a declaration is a data type foreign import
202−--
203−isExternDataDecl :: Declaration -> Bool
204−isExternDataDecl ExternDataDeclaration{} = True
205−isExternDataDecl (PositionedDeclaration _ d) = isExternDataDecl d
206−isExternDataDecl _ = False
207−
208−-- |
209−-- Test if a declaration is a type class instance foreign import
210−--
211−isExternInstanceDecl :: Declaration -> Bool
212−isExternInstanceDecl ExternInstanceDeclaration{} = True
213−isExternInstanceDecl (PositionedDeclaration _ d) = isExternInstanceDecl d
214−isExternInstanceDecl _ = False
215−
216−-- |
217−-- Test if a declaration is a fixity declaration
218−--
219−isFixityDecl :: Declaration -> Bool
220−isFixityDecl FixityDeclaration{} = True
221−isFixityDecl (PositionedDeclaration _ d) = isFixityDecl d
222−isFixityDecl _ = False
223−
224−-- |
225−-- Test if a declaration is a foreign import
226−--
227−isExternDecl :: Declaration -> Bool
228−isExternDecl ExternDeclaration{} = True
229−isExternDecl (PositionedDeclaration _ d) = isExternDecl d
230−isExternDecl _ = False
231−
232−-- |
233−-- Test if a declaration is a type class or instance declaration
234−--
235−isTypeClassDeclaration :: Declaration -> Bool
236−isTypeClassDeclaration TypeClassDeclaration{} = True
237−isTypeClassDeclaration TypeInstanceDeclaration{} = True
238−isTypeClassDeclaration (PositionedDeclaration _ d) = isTypeClassDeclaration d
239−isTypeClassDeclaration _ = False
240−
241−-- |
242−-- A guard is just a boolean-valued expression that appears alongside a set of binders
243−--
244−type Guard = Value
245−
246−-- |
247−-- Data type for values
248−--
249−data Value
250− -- |
251− -- A numeric literal
252− --
253− = NumericLiteral (Either Integer Double)
254− -- |
255− -- A string literal
256− --
257− | StringLiteral String
258− -- |
259− -- A boolean literal
260− --
261− | BooleanLiteral Bool
262− -- |
263− -- A prefix -, will be desugared
264− --
265− | UnaryMinus Value
266− -- |
267− -- Binary operator application. During the rebracketing phase of desugaring, this data constructor
268− -- will be removed.
269− --
270− | BinaryNoParens (Qualified Ident) Value Value
271− -- |
272− -- Explicit parentheses. During the rebracketing phase of desugaring, this data constructor
273− -- will be removed.
274− --
275− | Parens Value
276− -- |
277− -- An array literal
278− --
279− | ArrayLiteral [Value]
280− -- |
281− -- An object literal
282− --
283− | ObjectLiteral [(String, Value)]
284− -- |
285− -- An record property accessor expression
286− --
287− | Accessor String Value
288− -- |
289− -- Partial record update
290− --
291− | ObjectUpdate Value [(String, Value)]
292− -- |
293− -- Function introduction
294− --
295− | Abs (Either Ident Binder) Value
296− -- |
297− -- Function application
298− --
299− | App Value Value
300− -- |
301− -- Variable
302− --
303− | Var (Qualified Ident)
304− -- |
305− -- Conditional (if-then-else expression)
306− --
307− | IfThenElse Value Value Value
308− -- |
309− -- A data constructor
310− --
311− | Constructor (Qualified ProperName)
312− -- |
313− -- A case expression. During the case expansion phase of desugaring, top-level binders will get
314− -- desugared into case expressions, hence the need for guards and multiple binders per branch here.
315− --
316− | Case [Value] [CaseAlternative]
317− -- |
318− -- A value with a type annotation
319− --
320− | TypedValue Bool Value Type
321− -- |
322− -- A let binding
323− --
324− | Let [Declaration] Value
325− -- |
326− -- A do-notation block
327− --
328− | Do [DoNotationElement]
329− -- |
330− -- A placeholder for a type class dictionary to be inserted later. At the end of type checking, these
331− -- placeholders will be replaced with actual expressions representing type classes dictionaries which
332− -- can be evaluated at runtime. The constructor arguments represent (in order): whether or not to look
333− -- at superclass implementations when searching for a dictionary, the type class name and
334− -- instance type, and the type class dictionaries in scope.
335− --
336− | TypeClassDictionary Bool (Qualified ProperName, [Type]) (Maybe [TypeClassDictionaryInScope])
337− -- |
338− -- A value with source position information
339− --
340− | PositionedValue SourcePos Value deriving (Show, D.Data, D.Typeable)
341−
342−-- |
343−-- An alternative in a case statement
344−--
345−data CaseAlternative = CaseAlternative
346− { -- |
347− -- A collection of binders with which to match the inputs
348− --
349− caseAlternativeBinders :: [Binder]
350− -- |
351− -- An optional guard
352− --
353− , caseAlternativeGuard :: Maybe Guard
354− -- |
355− -- The result expression
356− --
357− , caseAlternativeResult :: Value
358− } deriving (Show, D.Data, D.Typeable)
359−
360−-- |
361−-- Find the original dictionary which a type class dictionary in scope refers to
362−--
363−canonicalizeDictionary :: TypeClassDictionaryInScope -> Qualified Ident
364−canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
365−canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
366−
367−-- |
368−-- A statement in a do-notation block
369−--
370−data DoNotationElement
371− -- |
372− -- A monadic value without a binder
373− --
374− = DoNotationValue Value
375− -- |
376− -- A monadic value with a binder
377− --
378− | DoNotationBind Binder Value
379− -- |
380− -- A let statement, i.e. a pure value with a binder
381− --
382− | DoNotationLet [Declaration]
383− -- |
384− -- A do notation element with source position information
385− --
386− | PositionedDoNotationElement SourcePos DoNotationElement deriving (Show, D.Data, D.Typeable)
387−
388−-- |
389−-- Data type for binders
390−--
391−data Binder
392− -- |
393− -- Wildcard binder
394− --
395− = NullBinder
396− -- |
397− -- A binder which matches a boolean literal
398− --
399− | BooleanBinder Bool
400− -- |
401− -- A binder which matches a string literal
402− --
403− | StringBinder String
404− -- |
405− -- A binder which matches a numeric literal
406− --
407− | NumberBinder (Either Integer Double)
408− -- |
409− -- A binder which binds an identifier
410− --
411− | VarBinder Ident
412− -- |
413− -- A binder which matches a data constructor
414− --
415− | ConstructorBinder (Qualified ProperName) [Binder]
416− -- |
417− -- A binder which matches a record and binds its properties
418− --
419− | ObjectBinder [(String, Binder)]
420− -- |
421− -- A binder which matches an array and binds its elements
422− --
423− | ArrayBinder [Binder]
424− -- |
425− -- A binder which matches an array and binds its head and tail
426− --
427− | ConsBinder Binder Binder
428− -- |
429− -- A binder which binds its input to an identifier
430− --
431− | NamedBinder Ident Binder
432− -- |
433− -- A binder with source position information
434− --
435− | PositionedBinder SourcePos Binder deriving (Show, D.Data, D.Typeable)
436−
437−-- |
438−-- Collect all names introduced in binders in an expression
439−--
440−binderNames :: (D.Data d) => d -> [Ident]
441−binderNames = everything (++) (mkQ [] go)
442− where
443− go (VarBinder ident) = [ident]
444− go (NamedBinder ident _) = [ident]
445− go _ = []
src/Language/PureScript/Environment.hsdeleted−191
@@ -1,191 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Prim
4−-- Copyright : (c) 2013-14 Phil Freeman, (c) 2014 Gary Burgess, and other contributors
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−--
13−-----------------------------------------------------------------------------
14−
15−{-# LANGUAGE DeriveDataTypeable #-}
16−
17−module Language.PureScript.Environment where
18−
19−import Data.Data
20−
21−import Language.PureScript.Names
22−import Language.PureScript.Types
23−import Language.PureScript.Kinds
24−import Language.PureScript.TypeClassDictionaries
25−import qualified Language.PureScript.Constants as C
26−
27−import qualified Data.Map as M
28−
29−-- |
30−-- The @Environment@ defines all values and types which are currently in scope:
31−--
32−data Environment = Environment {
33− -- |
34− -- Value names currently in scope
35− --
36− names :: M.Map (ModuleName, Ident) (Type, NameKind)
37− -- |
38− -- Type names currently in scope
39− --
40− , types :: M.Map (Qualified ProperName) (Kind, TypeKind)
41− -- |
42− -- Data constructors currently in scope, along with their associated data type constructors
43− --
44− , dataConstructors :: M.Map (Qualified ProperName) (ProperName, Type)
45− -- |
46− -- Type synonyms currently in scope
47− --
48− , typeSynonyms :: M.Map (Qualified ProperName) ([String], Type)
49− -- |
50− -- Available type class dictionaries
51− --
52− , typeClassDictionaries :: [TypeClassDictionaryInScope]
53− -- |
54− -- Type classes
55− --
56− , typeClasses :: M.Map (Qualified ProperName) ([String], [(Ident, Type)], [(Qualified ProperName, [Type])])
57− } deriving (Show)
58−
59−-- |
60−-- The initial environment with no values and only the default javascript types defined
61−--
62−initEnvironment :: Environment
63−initEnvironment = Environment M.empty primTypes M.empty M.empty [] M.empty
64−
65−-- |
66−-- The type of a foreign import
67−--
68−data ForeignImportType
69− -- |
70− -- A regular foreign import
71− --
72− = ForeignImport
73− -- |
74− -- A foreign import which contains inline Javascript as a string literal
75− --
76− | InlineJavascript
77− -- |
78− -- A type class dictionary member accessor import, generated during desugaring of type class declarations
79− --
80− | TypeClassAccessorImport deriving (Show, Eq, Data, Typeable)
81−
82−-- |
83−-- The kind of a name
84−--
85−data NameKind
86− -- |
87− -- A value introduced as a binding in a module
88− --
89− = Value
90− -- |
91− -- A foreign import
92− --
93− | Extern ForeignImportType
94− -- |
95− -- A local name introduced using a lambda abstraction, variable introduction or binder
96− --
97− | LocalVariable
98− -- |
99− -- A data constructor
100− --
101− | DataConstructor
102− -- |
103− -- A type class dictionary, generated during desugaring of type class declarations
104− --
105− | TypeInstanceDictionaryValue deriving (Show, Eq, Data, Typeable)
106−
107−-- |
108−-- The kinds of a type
109−--
110−data TypeKind
111− -- |
112− -- Data type
113− --
114− = DataType [String] [(ProperName, [Type])]
115− -- |
116− -- Type synonym
117− --
118− | TypeSynonym
119− -- |
120− -- Foreign data
121− --
122− | ExternData
123− -- |
124− -- A local type variable
125− --
126− | LocalTypeVariable deriving (Show, Eq, Data, Typeable)
127−
128−-- |
129−-- Construct a ProperName in the Prim module
130−--
131−primName :: String -> Qualified ProperName
132−primName = Qualified (Just $ ModuleName [ProperName C.prim]) . ProperName
133−
134−-- |
135−-- Construct a type in the Prim module
136−--
137−primTy :: String -> Type
138−primTy = TypeConstructor . primName
139−
140−-- |
141−-- Type constructor for functions
142−--
143−tyFunction :: Type
144−tyFunction = primTy "Function"
145−
146−-- |
147−-- Type constructor for strings
148−--
149−tyString :: Type
150−tyString = primTy "String"
151−
152−-- |
153−-- Type constructor for numbers
154−--
155−tyNumber :: Type
156−tyNumber = primTy "Number"
157−
158−-- |
159−-- Type constructor for booleans
160−--
161−tyBoolean :: Type
162−tyBoolean = primTy "Boolean"
163−
164−-- |
165−-- Type constructor for arrays
166−--
167−tyArray :: Type
168−tyArray = primTy "Array"
169−
170−-- |
171−-- Type constructor for objects
172−--
173−tyObject :: Type
174−tyObject = primTy "Object"
175−
176−-- |
177−-- Smart constructor for function types
178−--
179−function :: Type -> Type -> Type
180−function t1 = TypeApp (TypeApp tyFunction t1)
181−
182−-- |
183−-- The primitive types in the external javascript environment with their associated kinds.
184−--
185−primTypes :: M.Map (Qualified ProperName) (Kind, TypeKind)
186−primTypes = M.fromList [ (primName "Function" , (FunKind Star (FunKind Star Star), ExternData))
187− , (primName "Array" , (FunKind Star Star, ExternData))
188− , (primName "Object" , (FunKind (Row Star) Star, ExternData))
189− , (primName "String" , (Star, ExternData))
190− , (primName "Number" , (Star, ExternData))
191− , (primName "Boolean" , (Star, ExternData)) ]
src/Language/PureScript/Errors.hsdeleted−111
@@ -1,111 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Error
4−-- Copyright : (c) 2013-14 Phil Freeman, (c) 2014 Gary Burgess, and other contributors
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−--
13−-----------------------------------------------------------------------------
14−
15−{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleContexts #-}
16−
17−module Language.PureScript.Errors where
18−
19−import Data.List (intercalate)
20−import Data.Monoid
21−
22−import Control.Monad.Error
23−
24−import Language.PureScript.Declarations
25−import Language.PureScript.Pretty
26−import Language.PureScript.Types
27−
28−-- |
29−-- Type for sources of type checking errors
30−--
31−data ErrorSource
32− -- |
33− -- An error which originated at a Value
34− --
35− = ValueError Value
36− -- |
37− -- An error which originated at a Type
38− --
39− | TypeError Type deriving (Show)
40−
41−-- |
42−-- Compilation errors
43−--
44−data CompileError = CompileError {
45− -- |
46− -- Error message
47− --
48− compileErrorMessage :: String
49− -- |
50− -- The value where the error occurred
51− --
52− , compileErrorValue :: Maybe ErrorSource
53− -- |
54− -- Optional source position information
55− --
56− , compileErrorPosition :: Maybe SourcePos
57− } deriving (Show)
58−
59−-- |
60−-- A stack trace for an error
61−--
62−newtype ErrorStack = ErrorStack { runErrorStack :: [CompileError] } deriving (Show, Monoid)
63−
64−instance Error ErrorStack where
65− strMsg s = ErrorStack [CompileError s Nothing Nothing]
66− noMsg = ErrorStack []
67−
68−prettyPrintErrorStack :: Bool -> ErrorStack -> String
69−prettyPrintErrorStack printFullStack (ErrorStack es) =
70− case mconcat $ map (Last . compileErrorPosition) es of
71− Last (Just sourcePos) -> "Error at " ++ show sourcePos ++ ": \n" ++ prettyPrintErrorStack'
72− _ -> prettyPrintErrorStack'
73− where
74− prettyPrintErrorStack' :: String
75− prettyPrintErrorStack'
76− | printFullStack = intercalate "\n" (map showError (filter isErrorNonEmpty es))
77− | otherwise =
78− let
79− es' = filter isErrorNonEmpty es
80− in case length es' of
81− 1 -> showError (head es')
82− _ -> showError (head es') ++ "\n" ++ showError (last es')
83−
84−stringifyErrorStack :: Bool -> Either ErrorStack a -> Either String a
85−stringifyErrorStack printFullStack = either (Left . prettyPrintErrorStack printFullStack) Right
86−
87−isErrorNonEmpty :: CompileError -> Bool
88−isErrorNonEmpty = not . null . compileErrorMessage
89−
90−showError :: CompileError -> String
91−showError (CompileError msg Nothing _) = msg
92−showError (CompileError msg (Just (ValueError val)) _) = "Error in value " ++ prettyPrintValue val ++ ":\n" ++ msg
93−showError (CompileError msg (Just (TypeError ty)) _) = "Error in type " ++ prettyPrintType ty ++ ":\n" ++ msg
94−
95−mkErrorStack :: String -> Maybe ErrorSource -> ErrorStack
96−mkErrorStack msg t = ErrorStack [CompileError msg t Nothing]
97−
98−positionError :: SourcePos -> ErrorStack
99−positionError pos = ErrorStack [CompileError "" Nothing (Just pos)]
100−
101−-- |
102−-- Rethrow an error with a more detailed error message in the case of failure
103−--
104−rethrow :: (MonadError e m) => (e -> e) -> m a -> m a
105−rethrow f = flip catchError $ \e -> throwError (f e)
106−
107−-- |
108−-- Rethrow an error with source position information
109−--
110−rethrowWithPosition :: (MonadError ErrorStack m) => SourcePos -> m a -> m a
111−rethrowWithPosition pos = rethrow (positionError pos <>)
src/Language/PureScript/Kinds.hsdeleted−46
@@ -1,46 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Kinds
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−--
13−-----------------------------------------------------------------------------
14−
15−{-# LANGUAGE DeriveDataTypeable #-}
16−
17−module Language.PureScript.Kinds where
18−
19−import Data.Data
20−
21−import Control.Monad.Unify (Unknown)
22−
23−-- |
24−-- The data type of kinds
25−--
26−data Kind
27− -- |
28− -- Unification variable of type Kind
29− --
30− = KUnknown Unknown
31− -- |
32− -- The kind of types
33− --
34− | Star
35− -- |
36− -- The kind of effects
37− --
38− | Bang
39− -- |
40− -- Kinds for labelled, unordered rows without duplicates
41− --
42− | Row Kind
43− -- |
44− -- Function kinds
45− --
46− | FunKind Kind Kind deriving (Show, Eq, Data, Typeable)
src/Language/PureScript/ModuleDependencies.hsdeleted−71
@@ -1,71 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.ModuleDependencies
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- | Provides the ability to sort modules based on module dependencies
12−--
13−-----------------------------------------------------------------------------
14−
15−module Language.PureScript.ModuleDependencies (
16− sortModules,
17− ModuleGraph
18−) where
19−
20−import Data.Data
21−import Data.Graph
22−import Data.Generics
23−import Data.List (nub)
24−
25−import Language.PureScript.Declarations
26−import Language.PureScript.Names
27−
28−-- |
29−-- A list of modules with their dependencies
30−--
31−type ModuleGraph = [(ModuleName, [ModuleName])]
32−
33−-- |
34−-- Sort a collection of modules based on module dependencies.
35−--
36−-- Reports an error if the module graph contains a cycle.
37−--
38−sortModules :: [Module] -> Either String ([Module], ModuleGraph)
39−sortModules ms = do
40− let verts = map (\m -> (m, getModuleName m, usedModules m)) ms
41− ms' <- mapM toModule $ stronglyConnComp verts
42− let moduleGraph = map (\(_, mn, deps) -> (mn, deps)) verts
43− return (ms', moduleGraph)
44−
45−-- |
46−-- Calculate a list of used modules based on explicit imports and qualified names
47−--
48−usedModules :: (Data d) => d -> [ModuleName]
49−usedModules = nub . everything (++) (mkQ [] qualifiedIdents `extQ` qualifiedProperNames `extQ` imports)
50− where
51− qualifiedIdents :: Qualified Ident -> [ModuleName]
52− qualifiedIdents (Qualified (Just mn) _) = [mn]
53− qualifiedIdents _ = []
54− qualifiedProperNames :: Qualified ProperName -> [ModuleName]
55− qualifiedProperNames (Qualified (Just mn) _) = [mn]
56− qualifiedProperNames _ = []
57− imports :: Declaration -> [ModuleName]
58− imports (ImportDeclaration mn _ _) = [mn]
59− imports (PositionedDeclaration _ d) = imports d
60− imports _ = []
61−
62−getModuleName :: Module -> ModuleName
63−getModuleName (Module mn _ _) = mn
64−
65−-- |
66−-- Convert a strongly connected component of the module graph to a module
67−--
68−toModule :: SCC Module -> Either String Module
69−toModule (AcyclicSCC m) = return m
70−toModule (CyclicSCC [m]) = return m
71−toModule (CyclicSCC ms) = Left $ "Cycle in module dependencies: " ++ show (map getModuleName ms)
src/Language/PureScript/Names.hsdeleted−81
@@ -1,81 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Names
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Data types for names
13−--
14−-----------------------------------------------------------------------------
15−
16−{-# LANGUAGE DeriveDataTypeable #-}
17−
18−module Language.PureScript.Names where
19−
20−import Data.List
21−import Data.Data
22−
23−-- |
24−-- Names for value identifiers
25−--
26−data Ident
27− -- |
28− -- An alphanumeric identifier
29− --
30− = Ident String
31− -- |
32− -- A symbolic name for an infix operator
33− --
34− | Op String deriving (Eq, Ord, Data, Typeable)
35−
36−instance Show Ident where
37− show (Ident s) = s
38− show (Op op) = '(':op ++ ")"
39−
40−-- |
41−-- Proper names, i.e. capitalized names for e.g. module names, type//data constructors.
42−--
43−newtype ProperName = ProperName { runProperName :: String } deriving (Eq, Ord, Data, Typeable)
44−
45−instance Show ProperName where
46− show = runProperName
47−
48−-- |
49−-- Module names
50−--
51−data ModuleName = ModuleName [ProperName] deriving (Eq, Ord, Data, Typeable)
52−
53−runModuleName :: ModuleName -> String
54−runModuleName (ModuleName pns) = intercalate "." (runProperName `map` pns)
55−
56−moduleNameFromString :: String -> ModuleName
57−moduleNameFromString = ModuleName . splitProperNames
58− where
59− splitProperNames s = case dropWhile (== '.') s of
60− "" -> []
61− s' -> ProperName w : splitProperNames s''
62− where (w, s'') = break (== '.') s'
63−
64−instance Show ModuleName where
65− show = runModuleName
66−
67−-- |
68−-- A qualified name, i.e. a name with an optional module name
69−--
70−data Qualified a = Qualified (Maybe ModuleName) a deriving (Eq, Ord, Data, Typeable)
71−
72−instance (Show a) => Show (Qualified a) where
73− show (Qualified Nothing a) = show a
74− show (Qualified (Just name) a) = show name ++ "." ++ show a
75−
76−-- |
77−-- Provide a default module name, if a name is unqualified
78−--
79−qualify :: ModuleName -> Qualified a -> (ModuleName, a)
80−qualify m (Qualified Nothing a) = (m, a)
81−qualify _ (Qualified (Just m) a) = (m, a)
src/Language/PureScript/Optimizer.hsdeleted−76
@@ -1,76 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Optimizer
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module optimizes code in the simplified-Javascript intermediate representation.
13−--
14−-- The following optimizations are supported:
15−--
16−-- * Collapsing nested blocks
17−--
18−-- * Tail call elimination
19−--
20−-- * Inlining of (>>=) and ret for the Eff monad
21−--
22−-- * Removal of unused variables
23−--
24−-- * Removal of unnecessary thunks
25−--
26−-- * Eta conversion
27−--
28−-- * Inlining variables
29−--
30−-- * Inline Prelude.($), Prelude.(#), Prelude.(++), Prelude.(!!)
31−--
32−-- * Inlining primitive Javascript operators
33−--
34−-----------------------------------------------------------------------------
35−
36−module Language.PureScript.Optimizer (
37− optimize
38−) where
39−
40−import Language.PureScript.CodeGen.JS.AST
41−import Language.PureScript.Options
42−import qualified Language.PureScript.Constants as C
43−
44−import Language.PureScript.Optimizer.Common
45−import Language.PureScript.Optimizer.TCO
46−import Language.PureScript.Optimizer.MagicDo
47−import Language.PureScript.Optimizer.Inliner
48−import Language.PureScript.Optimizer.Unused
49−import Language.PureScript.Optimizer.Blocks
50−
51−-- |
52−-- Apply a series of optimizer passes to simplified Javascript code
53−--
54−optimize :: Options -> JS -> JS
55−optimize opts | optionsNoOptimizations opts = id
56− | otherwise = untilFixedPoint (applyAll
57− [ collapseNestedBlocks
58− , tco opts
59− , magicDo opts
60− , removeUnusedVariables
61− , removeCodeAfterReturnStatements
62− , unThunk
63− , etaConvert
64− , evaluateIifes
65− , inlineVariables
66− , inlineOperator (C.$) $ \f x -> JSApp f [x]
67− , inlineOperator (C.#) $ \x f -> JSApp f [x]
68− , inlineOperator (C.!!) $ flip JSIndexer
69− , inlineCommonOperators ])
70−
71−untilFixedPoint :: (Eq a) => (a -> a) -> a -> a
72−untilFixedPoint f = go
73− where
74− go a = let a' = f a in
75− if a' == a then a' else go a'
76−
src/Language/PureScript/Optimizer/Blocks.hsdeleted−35
@@ -1,35 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Optimizer.Blocks
4−-- Copyright : (c) Phil Freeman 2013-14
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Optimizer steps for simplifying Javascript blocks
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Optimizer.Blocks (
17− collapseNestedBlocks
18−) where
19−
20−import Data.Generics
21−
22−import Language.PureScript.CodeGen.JS.AST
23−
24−-- |
25−-- Collapse blocks which appear nested directly below another block
26−--
27−collapseNestedBlocks :: JS -> JS
28−collapseNestedBlocks = everywhere (mkT collapse)
29− where
30− collapse :: JS -> JS
31− collapse (JSBlock sts) = JSBlock (concatMap go sts)
32− collapse js = js
33− go :: JS -> [JS]
34− go (JSBlock sts) = sts
35− go s = [s]
src/Language/PureScript/Optimizer/Common.hsdeleted−78
@@ -1,78 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Optimizer.Common
4−-- Copyright : (c) Phil Freeman 2013-14
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Common functions used by the various optimizer phases
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Optimizer.Common where
17−
18−import Data.Maybe (fromMaybe)
19−import Data.Generics
20−
21−import Language.PureScript.CodeGen.JS.AST
22−
23−applyAll :: [a -> a] -> a -> a
24−applyAll = foldl1 (.)
25−
26−replaceIdent :: (Data d) => String -> JS -> d -> d
27−replaceIdent var1 js = everywhere (mkT replace)
28− where
29− replace (JSVar var2) | var1 == var2 = js
30− replace other = other
31−
32−replaceIdents :: (Data d) => [(String, JS)] -> d -> d
33−replaceIdents vars = everywhere (mkT replace)
34− where
35− replace v@(JSVar var) = fromMaybe v $ lookup var vars
36− replace other = other
37−
38−isReassigned :: (Data d) => String -> d -> Bool
39−isReassigned var1 = everything (||) (mkQ False check)
40− where
41− check :: JS -> Bool
42− check (JSFunction _ args _) | var1 `elem` args = True
43− check (JSVariableIntroduction arg _) | var1 == arg = True
44− check (JSAssignment (JSVar arg) _) | var1 == arg = True
45− check (JSFor arg _ _ _) | var1 == arg = True
46− check (JSForIn arg _ _) | var1 == arg = True
47− check _ = False
48−
49−isRebound :: (Data d) => JS -> d -> Bool
50−isRebound js d = any (\v -> isReassigned v d || isUpdated v d) (everything (++) (mkQ [] variablesOf) js)
51− where
52− variablesOf (JSVar var) = [var]
53− variablesOf _ = []
54−
55−isUsed :: (Data d) => String -> d -> Bool
56−isUsed var1 = everything (||) (mkQ False check)
57− where
58− check :: JS -> Bool
59− check (JSVar var2) | var1 == var2 = True
60− check (JSAssignment target _) | var1 == targetVariable target = True
61− check _ = False
62−
63−targetVariable :: JS -> String
64−targetVariable (JSVar var) = var
65−targetVariable (JSAccessor _ tgt) = targetVariable tgt
66−targetVariable (JSIndexer _ tgt) = targetVariable tgt
67−targetVariable _ = error "Invalid argument to targetVariable"
68−
69−isUpdated :: (Data d) => String -> d -> Bool
70−isUpdated var1 = everything (||) (mkQ False check)
71− where
72− check :: JS -> Bool
73− check (JSAssignment target _) | var1 == targetVariable target = True
74− check _ = False
75−
76−removeFromBlock :: ([JS] -> [JS]) -> JS -> JS
77−removeFromBlock go (JSBlock sts) = JSBlock (go sts)
78−removeFromBlock _ js = js
src/Language/PureScript/Optimizer/Inliner.hsdeleted−163
@@ -1,163 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Optimizer.Inliner
4−-- Copyright : (c) Phil Freeman 2013-14
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module provides basic inlining capabilities
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Optimizer.Inliner (
17− inlineVariables,
18− inlineOperator,
19− inlineCommonOperators,
20− etaConvert,
21− unThunk,
22− evaluateIifes
23−) where
24−
25−import Data.Generics
26−
27−import Language.PureScript.CodeGen.JS.AST
28−import Language.PureScript.CodeGen.Common (identToJs)
29−import Language.PureScript.Optimizer.Common
30−import Language.PureScript.Names
31−
32−import qualified Language.PureScript.Constants as C
33−
34−shouldInline :: JS -> Bool
35−shouldInline (JSVar _) = True
36−shouldInline (JSNumericLiteral _) = True
37−shouldInline (JSStringLiteral _) = True
38−shouldInline (JSBooleanLiteral _) = True
39−shouldInline (JSAccessor _ val) = shouldInline val
40−shouldInline (JSIndexer index val) = shouldInline index && shouldInline val
41−shouldInline _ = False
42−
43−etaConvert :: JS -> JS
44−etaConvert = everywhere (mkT convert)
45− where
46− convert :: JS -> JS
47− convert (JSBlock [JSReturn (JSApp (JSFunction Nothing idents block@(JSBlock body)) args)])
48− | all shouldInline args &&
49− not (any (`isRebound` block) (map JSVar idents)) &&
50− not (any (`isRebound` block) args)
51− = JSBlock (replaceIdents (zip idents args) body)
52− convert js = js
53−
54−unThunk :: JS -> JS
55−unThunk = everywhere (mkT convert)
56− where
57− convert :: JS -> JS
58− convert (JSBlock [JSReturn (JSApp (JSFunction Nothing [] (JSBlock body)) [])]) = JSBlock body
59− convert js = js
60−
61−evaluateIifes :: JS -> JS
62−evaluateIifes = everywhere (mkT convert)
63− where
64− convert :: JS -> JS
65− convert (JSApp (JSFunction Nothing [] (JSBlock [JSReturn ret])) []) = ret
66− convert js = js
67−
68−inlineVariables :: JS -> JS
69−inlineVariables = everywhere (mkT $ removeFromBlock go)
70− where
71− go :: [JS] -> [JS]
72− go [] = []
73− go (JSVariableIntroduction var (Just js) : sts)
74− | shouldInline js && not (isReassigned var sts) && not (isRebound js sts) && not (isUpdated var sts) =
75− go (replaceIdent var js sts)
76− go (s:sts) = s : go sts
77−
78−inlineOperator :: String -> (JS -> JS -> JS) -> JS -> JS
79−inlineOperator op f = everywhere (mkT convert)
80− where
81− convert :: JS -> JS
82− convert (JSApp (JSApp op' [x]) [y]) | isOp op' = f x y
83− convert other = other
84− isOp (JSAccessor longForm (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
85− _ps == C._ps &&
86− longForm == identToJs (Op op) = True
87− isOp (JSIndexer (JSStringLiteral op') (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
88− _ps == C._ps &&
89− op == op' = True
90− isOp _ = False
91−
92−inlineCommonOperators :: JS -> JS
93−inlineCommonOperators = applyAll
94− [ binary C.numNumber (C.+) Add
95− , binary C.numNumber (C.-) Subtract
96− , binary C.numNumber (C.*) Multiply
97− , binary C.numNumber (C./) Divide
98− , binary C.numNumber (C.%) Modulus
99− , unary C.numNumber C.negate Negate
100−
101− , binary C.ordNumber (C.<) LessThan
102− , binary C.ordNumber (C.>) GreaterThan
103− , binary C.ordNumber (C.<=) LessThanOrEqualTo
104− , binary C.ordNumber (C.>=) GreaterThanOrEqualTo
105−
106− , binary C.eqNumber (C.==) EqualTo
107− , binary C.eqNumber (C./=) NotEqualTo
108− , binary C.eqString (C.==) EqualTo
109− , binary C.eqString (C./=) NotEqualTo
110− , binary C.eqBoolean (C.==) EqualTo
111− , binary C.eqBoolean (C./=) NotEqualTo
112−
113− , binary C.semigroupString (C.++) Add
114−
115− , binaryFunction C.bitsNumber C.shl ShiftLeft
116− , binaryFunction C.bitsNumber C.shr ShiftRight
117− , binaryFunction C.bitsNumber C.zshr ZeroFillShiftRight
118− , binary C.bitsNumber (C.&) BitwiseAnd
119− , binary C.bitsNumber C.bar BitwiseOr
120− , binary C.bitsNumber (C.^) BitwiseXor
121− , unary C.bitsNumber C.complement BitwiseNot
122−
123− , binary C.boolLikeBoolean (C.&&) And
124− , binary C.boolLikeBoolean (C.||) Or
125− , unary C.boolLikeBoolean C.not Not
126− ]
127− where
128− binary :: String -> String -> BinaryOperator -> JS -> JS
129− binary dictName opString op = everywhere (mkT convert)
130− where
131− convert :: JS -> JS
132− convert (JSApp (JSApp (JSApp fn [dict]) [x]) [y]) | isOp fn && isOpDict dictName dict = JSBinary op x y
133− convert other = other
134− isOp (JSAccessor longForm (JSAccessor prelude (JSVar _))) | prelude == C.prelude &&
135− longForm == identToJs (Op opString) = True
136− isOp (JSIndexer (JSStringLiteral op') (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
137− _ps == C._ps &&
138− opString == op' = True
139− isOp _ = False
140− binaryFunction :: String -> String -> BinaryOperator -> JS -> JS
141− binaryFunction dictName fnName op = everywhere (mkT convert)
142− where
143− convert :: JS -> JS
144− convert (JSApp (JSApp (JSApp fn [dict]) [x]) [y]) | isOp fn && isOpDict dictName dict = JSBinary op x y
145− convert other = other
146− isOp (JSAccessor fnName' (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
147− _ps == C._ps &&
148− fnName == fnName' = True
149− isOp _ = False
150− unary :: String -> String -> UnaryOperator -> JS -> JS
151− unary dictName fnName op = everywhere (mkT convert)
152− where
153− convert :: JS -> JS
154− convert (JSApp (JSApp fn [dict]) [x]) | isOp fn && isOpDict dictName dict = JSUnary op x
155− convert other = other
156− isOp (JSAccessor fnName' (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
157− _ps == C._ps &&
158− fnName' == fnName = True
159− isOp _ = False
160− isOpDict dictName (JSApp (JSAccessor prop (JSAccessor prelude (JSVar _ps))) [JSObjectLiteral []]) | prelude == C.prelude &&
161− _ps == C._ps &&
162− prop == dictName = True
163− isOpDict _ _ = False
src/Language/PureScript/Optimizer/MagicDo.hsdeleted−172
@@ -1,172 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Optimizer.MagicDo
4−-- Copyright : (c) Phil Freeman 2013-14
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module implements the "Magic Do" optimization, which inlines calls to return
13−-- and bind for the Eff monad, as well as some of its actions.
14−--
15−-----------------------------------------------------------------------------
16−
17−module Language.PureScript.Optimizer.MagicDo (
18− magicDo
19−) where
20−
21−import Data.List (nub)
22−import Data.Maybe (fromJust, isJust)
23−import Data.Generics
24−
25−import Language.PureScript.Options
26−import Language.PureScript.CodeGen.JS.AST
27−import Language.PureScript.CodeGen.Common (identToJs)
28−import Language.PureScript.Names
29−
30−import qualified Language.PureScript.Constants as C
31−
32−magicDo :: Options -> JS -> JS
33−magicDo opts | optionsNoMagicDo opts = id
34− | otherwise = inlineST . magicDo'
35−
36−-- |
37−-- Inline type class dictionaries for >>= and return for the Eff monad
38−--
39−-- E.g.
40−--
41−-- Prelude[">>="](dict)(m1)(function(x) {
42−-- return ...;
43−-- })
44−--
45−-- becomes
46−--
47−-- function __do {
48−-- var x = m1();
49−-- ...
50−-- }
51−--
52−magicDo' :: JS -> JS
53−magicDo' = everywhere (mkT undo) . everywhere' (mkT convert)
54− where
55− -- The name of the function block which is added to denote a do block
56− fnName = "__do"
57− -- Desugar monomorphic calls to >>= and return for the Eff monad
58− convert :: JS -> JS
59− -- Desugar return
60− convert (JSApp (JSApp ret [val]) []) | isReturn ret = val
61− -- Desugar >>
62− convert (JSApp (JSApp bind [m]) [JSFunction Nothing ["_"] (JSBlock js)]) | isBind bind && isJSReturn (last js) =
63− let JSReturn ret = last js in
64− JSFunction (Just fnName) [] $ JSBlock (JSApp m [] : init js ++ [JSReturn (JSApp ret [])] )
65− -- Desugar >>=
66− convert (JSApp (JSApp bind [m]) [JSFunction Nothing [arg] (JSBlock js)]) | isBind bind && isJSReturn (last js) =
67− let JSReturn ret = last js in
68− JSFunction (Just fnName) [] $ JSBlock (JSVariableIntroduction arg (Just (JSApp m [])) : init js ++ [JSReturn (JSApp ret [])] )
69− -- Desugar untilE
70− convert (JSApp (JSApp f [arg]) []) | isEffFunc C.untilE f =
71− JSApp (JSFunction Nothing [] (JSBlock [ JSWhile (JSUnary Not (JSApp arg [])) (JSBlock []), JSReturn (JSObjectLiteral []) ])) []
72− -- Desugar whileE
73− convert (JSApp (JSApp (JSApp f [arg1]) [arg2]) []) | isEffFunc C.whileE f =
74− JSApp (JSFunction Nothing [] (JSBlock [ JSWhile (JSApp arg1 []) (JSBlock [ JSApp arg2 [] ]), JSReturn (JSObjectLiteral []) ])) []
75− convert other = other
76− -- Check if an expression represents a monomorphic call to >>= for the Eff monad
77− isBind (JSApp bindPoly [effDict]) | isBindPoly bindPoly && isEffDict effDict = True
78− isBind _ = False
79− -- Check if an expression represents a monomorphic call to return for the Eff monad
80− isReturn (JSApp retPoly [effDict]) | isRetPoly retPoly && isEffDict effDict = True
81− isReturn _ = False
82− -- Check if an expression represents the polymorphic >>= function
83− isBindPoly (JSAccessor prop (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
84− _ps == C._ps &&
85− prop == identToJs (Op (C.>>=)) = True
86− isBindPoly (JSIndexer (JSStringLiteral bind) (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
87− _ps == C._ps &&
88− bind == (C.>>=) = True
89− isBindPoly _ = False
90− -- Check if an expression represents the polymorphic return function
91− isRetPoly (JSAccessor returnEscaped (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
92− _ps == C._ps &&
93− returnEscaped == C.returnEscaped = True
94− isRetPoly (JSIndexer (JSStringLiteral return') (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
95− _ps == C._ps &&
96− return' == C.return = True
97− isRetPoly _ = False
98− -- Check if an expression represents a function in the Ef module
99− isEffFunc name (JSAccessor name' (JSAccessor eff (JSVar _ps))) | eff == C.eff &&
100− _ps == C._ps &&
101− name == name' = True
102− isEffFunc _ _ = False
103− -- Check if an expression represents the Monad Eff dictionary
104− isEffDict (JSApp (JSVar ident) [JSObjectLiteral []]) | ident == C.monadEffDictionary = True
105− isEffDict (JSApp (JSAccessor prop (JSAccessor eff (JSVar _ps))) [JSObjectLiteral []]) | eff == C.eff &&
106− _ps == C._ps &&
107− prop == C.monadEffDictionary = True
108− isEffDict _ = False
109− -- Remove __do function applications which remain after desugaring
110− undo :: JS -> JS
111− undo (JSReturn (JSApp (JSFunction (Just ident) [] body) [])) | ident == fnName = body
112− undo other = other
113−
114− isJSReturn (JSReturn _) = True
115− isJSReturn _ = False
116−
117−-- |
118−-- Inline functions in the ST module
119−--
120−inlineST :: JS -> JS
121−inlineST = everywhere (mkT convertBlock)
122− where
123− -- Look for runST blocks and inline the STRefs there.
124− -- If all STRefs are used in the scope of the same runST, only using { read, write, modify }STRef then
125− -- we can be more aggressive about inlining, and actually turn STRefs into local variables.
126− convertBlock (JSApp f [arg]) | isSTFunc C.runST f || isSTFunc C.runSTArray f =
127− let refs = nub . findSTRefsIn $ arg
128− usages = findAllSTUsagesIn arg
129− allUsagesAreLocalVars = all (\u -> let v = toVar u in isJust v && fromJust v `elem` refs) usages
130− localVarsDoNotEscape = all (\r -> length (r `appearingIn` arg) == length (filter (\u -> let v = toVar u in v == Just r) usages)) refs
131− in everywhere (mkT $ convert (allUsagesAreLocalVars && localVarsDoNotEscape)) arg
132− convertBlock other = other
133− -- Convert a block in a safe way, preserving object wrappers of references,
134− -- or in a more aggressive way, turning wrappers into local variables depending on the
135− -- agg(ressive) parameter.
136− convert agg (JSApp f [arg]) | isSTFunc C.newSTRef f =
137− JSFunction Nothing [] (JSBlock [JSReturn $ if agg then arg else JSObjectLiteral [(C.stRefValue, arg)]])
138− convert agg (JSApp (JSApp f [ref]) []) | isSTFunc C.readSTRef f =
139− if agg then ref else JSAccessor C.stRefValue ref
140− convert agg (JSApp (JSApp (JSApp f [ref]) [arg]) []) | isSTFunc C.writeSTRef f =
141− if agg then JSAssignment ref arg else JSAssignment (JSAccessor C.stRefValue ref) arg
142− convert agg (JSApp (JSApp (JSApp f [ref]) [func]) []) | isSTFunc C.modifySTRef f =
143− if agg then JSAssignment ref (JSApp func [ref]) else JSAssignment (JSAccessor C.stRefValue ref) (JSApp func [JSAccessor C.stRefValue ref])
144− convert _ (JSApp (JSApp (JSApp f [arr]) [i]) []) | isSTFunc C.peekSTArray f =
145− JSIndexer i arr
146− convert _ (JSApp (JSApp (JSApp (JSApp f [arr]) [i]) [val]) []) | isSTFunc C.pokeSTArray f =
147− JSAssignment (JSIndexer i arr) val
148− convert _ other = other
149− -- Check if an expression represents a function in the ST module
150− isSTFunc name (JSAccessor name' (JSAccessor st (JSVar _ps))) | st == C.st &&
151− _ps == C._ps &&
152− name == name' = True
153− isSTFunc _ _ = False
154− -- Find all ST Refs initialized in this block
155− findSTRefsIn = everything (++) (mkQ [] isSTRef)
156− where
157− isSTRef (JSVariableIntroduction ident (Just (JSApp (JSApp f [_]) []))) | isSTFunc C.newSTRef f = [ident]
158− isSTRef _ = []
159− -- Find all STRefs used as arguments to readSTRef, writeSTRef, modifySTRef
160− findAllSTUsagesIn = everything (++) (mkQ [] isSTUsage)
161− where
162− isSTUsage (JSApp (JSApp f [ref]) []) | isSTFunc C.readSTRef f = [ref]
163− isSTUsage (JSApp (JSApp (JSApp f [ref]) [_]) []) | isSTFunc C.writeSTRef f || isSTFunc C.modifySTRef f = [ref]
164− isSTUsage _ = []
165− -- Find all uses of a variable
166− appearingIn ref = everything (++) (mkQ [] isVar)
167− where
168− isVar e@(JSVar v) | v == ref = [e]
169− isVar _ = []
170− -- Convert a JS value to a String if it is a JSVar
171− toVar (JSVar v) = Just v
172− toVar _ = Nothing
src/Language/PureScript/Optimizer/TCO.hsdeleted−102
@@ -1,102 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Optimizer.TCO
4−-- Copyright : (c) Phil Freeman 2013-14
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module implements tail call elimination.
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Optimizer.TCO (tco) where
17−
18−import Data.Generics
19−
20−import Language.PureScript.Options
21−import Language.PureScript.CodeGen.JS.AST
22−
23−-- |
24−-- Eliminate tail calls
25−--
26−tco :: Options -> JS -> JS
27−tco opts | optionsNoTco opts = id
28− | otherwise = tco'
29−
30−tco' :: JS -> JS
31−tco' = everywhere (mkT convert)
32− where
33− tcoLabel :: String
34− tcoLabel = "tco"
35− tcoVar :: String -> String
36− tcoVar arg = "__tco_" ++ arg
37− copyVar :: String -> String
38− copyVar arg = "__copy_" ++ arg
39− convert :: JS -> JS
40− convert js@(JSVariableIntroduction name (Just fn@JSFunction {})) =
41− let
42− (argss, body', replace) = collectAllFunctionArgs [] id fn
43− in case () of
44− _ | isTailCall name body' ->
45− let
46− allArgs = reverse $ concat argss
47− in
48− JSVariableIntroduction name (Just (replace (toLoop name allArgs body')))
49− | otherwise -> js
50− convert js = js
51− collectAllFunctionArgs :: [[String]] -> (JS -> JS) -> JS -> ([[String]], JS, JS -> JS)
52− collectAllFunctionArgs allArgs f (JSFunction ident args (JSBlock (body@(JSReturn _):_))) =
53− collectAllFunctionArgs (args : allArgs) (\b -> f (JSFunction ident (map copyVar args) (JSBlock [b]))) body
54− collectAllFunctionArgs allArgs f (JSFunction ident args body@(JSBlock _)) =
55− (args : allArgs, body, f . JSFunction ident (map copyVar args))
56− collectAllFunctionArgs allArgs f (JSReturn (JSFunction ident args (JSBlock [body]))) =
57− collectAllFunctionArgs (args : allArgs) (\b -> f (JSReturn (JSFunction ident (map copyVar args) (JSBlock [b])))) body
58− collectAllFunctionArgs allArgs f (JSReturn (JSFunction ident args body@(JSBlock _))) =
59− (args : allArgs, body, f . JSReturn . JSFunction ident (map copyVar args))
60− collectAllFunctionArgs allArgs f body = (allArgs, body, f)
61− isTailCall :: String -> JS -> Bool
62− isTailCall ident js =
63− let
64− numSelfCalls = everything (+) (mkQ 0 countSelfCalls) js
65− numSelfCallsInTailPosition = everything (+) (mkQ 0 countSelfCallsInTailPosition) js
66− numSelfCallsUnderFunctions = everything (+) (mkQ 0 countSelfCallsUnderFunctions) js
67− in
68− numSelfCalls > 0
69− && numSelfCalls == numSelfCallsInTailPosition
70− && numSelfCallsUnderFunctions == 0
71− where
72− countSelfCalls :: JS -> Int
73− countSelfCalls (JSApp (JSVar ident') _) | ident == ident' = 1
74− countSelfCalls _ = 0
75− countSelfCallsInTailPosition :: JS -> Int
76− countSelfCallsInTailPosition (JSReturn ret) | isSelfCall ident ret = 1
77− countSelfCallsInTailPosition _ = 0
78− countSelfCallsUnderFunctions (JSFunction _ _ js') = everything (+) (mkQ 0 countSelfCalls) js'
79− countSelfCallsUnderFunctions _ = 0
80− toLoop :: String -> [String] -> JS -> JS
81− toLoop ident allArgs js = JSBlock $
82− map (\arg -> JSVariableIntroduction arg (Just (JSVar (copyVar arg)))) allArgs ++
83− [ JSLabel tcoLabel $ JSWhile (JSBooleanLiteral True) (JSBlock [ everywhere (mkT loopify) js ]) ]
84− where
85− loopify :: JS -> JS
86− loopify (JSReturn ret) | isSelfCall ident ret =
87− let
88− allArgumentValues = concat $ collectSelfCallArgs [] ret
89− in
90− JSBlock $ zipWith (\val arg ->
91− JSVariableIntroduction (tcoVar arg) (Just val)) allArgumentValues allArgs
92− ++ map (\arg ->
93− JSAssignment (JSVar arg) (JSVar (tcoVar arg))) allArgs
94− ++ [ JSContinue tcoLabel ]
95− loopify other = other
96− collectSelfCallArgs :: [[JS]] -> JS -> [[JS]]
97− collectSelfCallArgs allArgumentValues (JSApp fn args') = collectSelfCallArgs (args' : allArgumentValues) fn
98− collectSelfCallArgs allArgumentValues _ = allArgumentValues
99− isSelfCall :: String -> JS -> Bool
100− isSelfCall ident (JSApp (JSVar ident') _) | ident == ident' = True
101− isSelfCall ident (JSApp fn _) = isSelfCall ident fn
102− isSelfCall _ _ = False
src/Language/PureScript/Optimizer/Unused.hsdeleted−43
@@ -1,43 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Optimizer.Unused
4−-- Copyright : (c) Phil Freeman 2013-14
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Removes unused variables
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Optimizer.Unused (
17− removeUnusedVariables,
18− removeCodeAfterReturnStatements
19−) where
20−
21−import Data.Generics
22−
23−import Language.PureScript.CodeGen.JS.AST
24−import Language.PureScript.Optimizer.Common
25−
26−removeUnusedVariables :: JS -> JS
27−removeUnusedVariables = everywhere (mkT $ removeFromBlock withBlock)
28− where
29− withBlock :: [JS] -> [JS]
30− withBlock sts = go sts sts
31− go :: [JS] -> [JS] -> [JS]
32− go _ [] = []
33− go sts (JSVariableIntroduction var _ : rest) | not (isUsed var sts) = go sts rest
34− go sts (s : rest) = s : go sts rest
35−
36−removeCodeAfterReturnStatements :: JS -> JS
37−removeCodeAfterReturnStatements = everywhere (mkT $ removeFromBlock go)
38− where
39− go :: [JS] -> [JS]
40− go jss | not (any isJSReturn jss) = jss
41− | otherwise = let (body, ret : _) = span (not . isJSReturn) jss in body ++ [ret]
42− isJSReturn (JSReturn _) = True
43− isJSReturn _ = False
src/Language/PureScript/Options.hsdeleted−70
@@ -1,70 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Options
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- The data type of compiler options
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Options where
17−
18−-- |
19−-- The data type of compiler options
20−--
21−data Options = Options {
22− -- |
23− -- Disable inclusion of the built in Prelude
24− --
25− optionsNoPrelude :: Bool
26− -- |
27− -- Disable tail-call elimination
28− --
29− , optionsNoTco :: Bool
30− -- |
31− -- Perform type checks at runtime
32− --
33− , optionsPerformRuntimeTypeChecks :: Bool
34− -- |
35− -- Disable inlining of calls to return and bind for the Eff monad
36− --
37− , optionsNoMagicDo :: Bool
38− -- |
39− -- When specified, checks the type of `main` in the module, and generate a call to run main
40− -- after the module definitions.
41− --
42− , optionsMain :: Maybe String
43− -- |
44− -- Skip all optimizations
45− --
46− , optionsNoOptimizations :: Bool
47− -- |
48− -- Specify the namespace that PureScript modules will be exported to when running in the
49− -- browser.
50− --
51− , optionsBrowserNamespace :: String
52− -- |
53− -- The modules to keep while enabling dead code elimination
54− --
55− , optionsModules :: [String]
56− -- |
57− -- The modules to code gen
58− --
59− , optionsCodeGenModules :: [String]
60− -- |
61− -- Verbose error message
62− --
63− , optionsVerboseErrors :: Bool
64− } deriving Show
65−
66−-- |
67−-- Default compiler options
68−--
69−defaultOptions :: Options
70−defaultOptions = Options False False False False Nothing False "PS" [] [] False
src/Language/PureScript/Parser.hsdeleted−34
@@ -1,34 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Parser
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- A collection of parsers for core data types:
13−--
14−-- [@Language.PureScript.Parser.Kinds@] Parser for kinds
15−--
16−-- [@Language.PureScript.Parser.Values@] Parser for values
17−--
18−-- [@Language.PureScript.Parser.Types@] Parser for types
19−--
20−-- [@Language.PureScript.Parser.Declaration@] Parsers for declarations and modules
21−--
22−-- [@Language.PureScript.Parser.State@] Parser state, including indentation
23−--
24−-- [@Language.PureScript.Parser.Common@] Common parsing utility functions
25−--
26−-----------------------------------------------------------------------------
27−
28−module Language.PureScript.Parser (module P) where
29−
30−import Language.PureScript.Parser.Common as P
31−import Language.PureScript.Parser.Types as P
32−import Language.PureScript.Parser.State as P
33−import Language.PureScript.Parser.Kinds as P
34−import Language.PureScript.Parser.Declarations as P
src/Language/PureScript/Parser/Common.hsdeleted−372
@@ -1,372 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Parser.Common
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Constants, and utility functions to be used when parsing
13−--
14−-----------------------------------------------------------------------------
15−
16−{-# LANGUAGE FlexibleContexts #-}
17−
18−module Language.PureScript.Parser.Common where
19−
20−import Data.Functor.Identity
21−import Control.Applicative
22−import Control.Monad
23−import Language.PureScript.Parser.State
24−import qualified Text.Parsec as P
25−import qualified Text.Parsec.Token as PT
26−
27−import Language.PureScript.Names
28−
29−-- |
30−-- A list of purescript reserved identifiers
31−--
32−reservedPsNames :: [String]
33−reservedPsNames = [ "data"
34− , "type"
35− , "foreign"
36− , "import"
37− , "infixl"
38− , "infixr"
39− , "infix"
40− , "class"
41− , "instance"
42− , "module"
43− , "case"
44− , "of"
45− , "if"
46− , "then"
47− , "else"
48− , "do"
49− , "let"
50− , "true"
51− , "false"
52− , "in"
53− , "where"
54− ]
55−
56−-- |
57−-- A list of reserved identifiers for types
58−--
59−reservedTypeNames :: [String]
60−reservedTypeNames = [ "forall"
61− , "where" ]
62−
63−-- |
64−-- A list of reserved operators
65−--
66−reservedOpNames :: [String]
67−reservedOpNames = [ "=>", "->", "=", ".", "\\" ]
68−
69−-- |
70−-- Valid first characters for an identifier
71−--
72−identStart :: P.Parsec String u Char
73−identStart = P.lower <|> P.oneOf "_"
74−
75−-- |
76−-- Valid identifier characters
77−--
78−identLetter :: P.Parsec String u Char
79−identLetter = P.alphaNum <|> P.oneOf "_'"
80−
81−-- |
82−-- Valid first characters for an operator
83−--
84−opStart :: P.Parsec String u Char
85−opStart = P.oneOf ":!#$%&*+./<=>?@\\^|-~"
86−
87−-- |
88−-- Valid operators characters
89−--
90−opLetter :: P.Parsec String u Char
91−opLetter = P.oneOf ":!#$%&*+./<=>?@\\^|-~"
92−
93−-- |
94−-- The PureScript language definition
95−--
96−langDef :: PT.GenLanguageDef String u Identity
97−langDef = PT.LanguageDef
98− { PT.reservedNames = reservedPsNames
99− , PT.reservedOpNames = reservedOpNames
100− , PT.commentStart = "{-"
101− , PT.commentEnd = "-}"
102− , PT.commentLine = "--"
103− , PT.nestedComments = True
104− , PT.identStart = identStart
105− , PT.identLetter = identLetter
106− , PT.opStart = opStart
107− , PT.opLetter = opLetter
108− , PT.caseSensitive = True
109− }
110−
111−-- |
112−-- A token parser based on the language definition
113−--
114−tokenParser :: PT.GenTokenParser String u Identity
115−tokenParser = PT.makeTokenParser langDef
116−
117−-- |
118−-- Parse a token
119−--
120−lexeme :: P.Parsec String u a -> P.Parsec String u a
121−lexeme = PT.lexeme tokenParser
122−
123−-- |
124−-- Parse an identifier
125−--
126−identifier :: P.Parsec String u String
127−identifier = PT.identifier tokenParser
128−
129−-- |
130−-- Parse a reserved word
131−--
132−reserved :: String -> P.Parsec String u ()
133−reserved = PT.reserved tokenParser
134−
135−-- |
136−-- Parse a reserved operator
137−--
138−reservedOp :: String -> P.Parsec String u ()
139−reservedOp = PT.reservedOp tokenParser
140−
141−-- |
142−-- Parse an operator
143−--
144−operator :: P.Parsec String u String
145−operator = PT.operator tokenParser
146−
147−-- |
148−-- Parse a string literal
149−--
150−stringLiteral :: P.Parsec String u String
151−stringLiteral = PT.stringLiteral tokenParser
152−
153−-- |
154−-- Parse whitespace
155−--
156−whiteSpace :: P.Parsec String u ()
157−whiteSpace = PT.whiteSpace tokenParser
158−
159−-- |
160−-- Semicolon
161−--
162−semi :: P.Parsec String u String
163−semi = PT.semi tokenParser
164−
165−-- |
166−-- Colon
167−--
168−colon :: P.Parsec String u String
169−colon = PT.colon tokenParser
170−
171−-- |
172−-- Period
173−--
174−dot :: P.Parsec String u String
175−dot = PT.dot tokenParser
176−
177−-- |
178−-- Comma
179−--
180−comma :: P.Parsec String u String
181−comma = PT.comma tokenParser
182−
183−-- |
184−-- Backtick
185−--
186−tick :: P.Parsec String u Char
187−tick = lexeme $ P.char '`'
188−
189−-- |
190−-- Pipe character
191−--
192−pipe :: P.Parsec String u Char
193−pipe = lexeme $ P.char '|'
194−
195−-- |
196−-- Natural number
197−--
198−natural :: P.Parsec String u Integer
199−natural = PT.natural tokenParser
200−
201−-- |
202−-- Parse a proper name
203−--
204−properName :: P.Parsec String u ProperName
205−properName = lexeme $ ProperName <$> P.try ((:) <$> P.upper <*> many P.alphaNum P.<?> "name")
206−
207−-- |
208−-- Parse a module name
209−--
210−moduleName :: P.Parsec String ParseState ModuleName
211−moduleName = ModuleName <$> P.try (sepBy properName dot)
212−
213−-- |
214−-- Parse a qualified name, i.e. M.name or just name
215−--
216−parseQualified :: P.Parsec String ParseState a -> P.Parsec String ParseState (Qualified a)
217−parseQualified parser = part []
218− where
219− part path = (do name <- P.try (properName <* delimiter)
220− part (updatePath path name))
221− <|> (Qualified (qual path) <$> P.try parser)
222− delimiter = indented *> dot <* P.notFollowedBy dot
223− updatePath path name = path ++ [name]
224− qual path = if null path then Nothing else Just $ ModuleName path
225−
226−-- |
227−-- Parse an integer or floating point value
228−--
229−integerOrFloat :: P.Parsec String u (Either Integer Double)
230−integerOrFloat = (Right <$> P.try (PT.float tokenParser) <|>
231− Left <$> P.try (PT.natural tokenParser)) P.<?> "number"
232−
233−-- |
234−-- Parse an identifier or parenthesized operator
235−--
236−parseIdent :: P.Parsec String ParseState Ident
237−parseIdent = (Ident <$> identifier) <|> (Op <$> parens operator)
238−
239−-- |
240−-- Parse a token inside square brackets
241−--
242−squares :: P.Parsec String ParseState a -> P.Parsec String ParseState a
243−squares = P.between (lexeme $ P.char '[') (lexeme $ indented *> P.char ']') . (indented *>)
244−
245−-- |
246−-- Parse a token inside parentheses
247−--
248−parens :: P.Parsec String ParseState a -> P.Parsec String ParseState a
249−parens = P.between (lexeme $ P.char '(') (lexeme $ indented *> P.char ')') . (indented *>)
250−
251−-- |
252−-- Parse a token inside braces
253−--
254−braces :: P.Parsec String ParseState a -> P.Parsec String ParseState a
255−braces = P.between (lexeme $ P.char '{') (lexeme $ indented *> P.char '}') . (indented *>)
256−
257−-- |
258−-- Parse a token inside angle brackets
259−--
260−angles :: P.Parsec String ParseState a -> P.Parsec String ParseState a
261−angles = P.between (lexeme $ P.char '<') (lexeme $ indented *> P.char '>') . (indented *>)
262−
263−-- |
264−-- Parse zero or more values separated by a separator token
265−--
266−sepBy :: P.Parsec String ParseState a -> P.Parsec String ParseState sep -> P.Parsec String ParseState [a]
267−sepBy p s = P.sepBy (indented *> p) (indented *> s)
268−
269−-- |
270−-- Parse one or more values separated by a separator token
271−--
272−sepBy1 :: P.Parsec String ParseState a -> P.Parsec String ParseState sep -> P.Parsec String ParseState [a]
273−sepBy1 p s = P.sepBy1 (indented *> p) (indented *> s)
274−
275−-- |
276−-- Parse zero or more values separated by semicolons
277−--
278−semiSep :: P.Parsec String ParseState a -> P.Parsec String ParseState [a]
279−semiSep = flip sepBy semi
280−
281−-- |
282−-- Parse one or more values separated by semicolons
283−--
284−semiSep1 :: P.Parsec String ParseState a -> P.Parsec String ParseState [a]
285−semiSep1 = flip sepBy1 semi
286−
287−-- |
288−-- Parse zero or more values separated by commas
289−--
290−commaSep :: P.Parsec String ParseState a -> P.Parsec String ParseState [a]
291−commaSep = flip sepBy comma
292−
293−-- |
294−-- Parse one or more values separated by commas
295−--
296−commaSep1 :: P.Parsec String ParseState a -> P.Parsec String ParseState [a]
297−commaSep1 = flip sepBy1 comma
298−
299−-- |
300−-- Run the first parser, then match the second if possible, applying the specified function on a successful match
301−--
302−augment :: P.Stream s m t => P.ParsecT s u m a -> P.ParsecT s u m b -> (a -> b -> a) -> P.ParsecT s u m a
303−augment p q f = flip (maybe id $ flip f) <$> p <*> P.optionMaybe q
304−
305−-- |
306−-- Run the first parser, then match the second zero or more times, applying the specified function for each match
307−--
308−fold :: P.Stream s m t => P.ParsecT s u m a -> P.ParsecT s u m b -> (a -> b -> a) -> P.ParsecT s u m a
309−fold first more combine = do
310− a <- first
311− bs <- P.many more
312− return $ foldl combine a bs
313−
314−-- |
315−-- Build a parser from a smaller parser and a list of parsers for postfix operators
316−--
317−buildPostfixParser :: P.Stream s m t => [a -> P.ParsecT s u m a] -> P.ParsecT s u m a -> P.ParsecT s u m a
318−buildPostfixParser fs first = do
319− a <- first
320− go a
321− where
322− go a = do
323− maybeA <- P.optionMaybe $ P.choice (map ($ a) fs)
324− case maybeA of
325− Nothing -> return a
326− Just a' -> go a'
327−
328−-- |
329−-- Parse an identifier in backticks or an operator
330−--
331−parseIdentInfix :: P.Parsec String ParseState (Qualified Ident)
332−parseIdentInfix = P.between tick tick (parseQualified (Ident <$> identifier)) <|> (parseQualified (Op <$> operator))
333−
334−-- |
335−-- Mark the current indentation level
336−--
337−mark :: P.Parsec String ParseState a -> P.Parsec String ParseState a
338−mark p = do
339− current <- indentationLevel <$> P.getState
340− pos <- P.sourceColumn <$> P.getPosition
341− P.modifyState $ \st -> st { indentationLevel = pos }
342− a <- p
343− P.modifyState $ \st -> st { indentationLevel = current }
344− return a
345−
346−-- |
347−-- Check that the current identation level matches a predicate
348−--
349−checkIndentation :: (P.Column -> P.Column -> Bool) -> P.Parsec String ParseState ()
350−checkIndentation rel = do
351− col <- P.sourceColumn <$> P.getPosition
352− current <- indentationLevel <$> P.getState
353− guard (col `rel` current)
354−
355−-- |
356−-- Check that the current indentation level is past the current mark
357−--
358−indented :: P.Parsec String ParseState ()
359−indented = checkIndentation (>) P.<?> "indentation"
360−
361−-- |
362−-- Check that the current indentation level is at the same indentation as the current mark
363−--
364−same :: P.Parsec String ParseState ()
365−same = checkIndentation (==) P.<?> "no indentation"
366−
367−-- |
368−-- Run a parser which supports indentation
369−--
370−runIndentParser :: FilePath -> P.Parsec String ParseState a -> String -> Either P.ParseError a
371−runIndentParser filePath p = P.runParser p (ParseState 0) filePath
372−
src/Language/PureScript/Parser/Declarations.hsdeleted−427
@@ -1,427 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Parser.Declarations
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Parsers for module definitions and declarations
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Parser.Declarations (
17− parseDeclaration,
18− parseModule,
19− parseModules,
20− parseValue,
21− parseGuard,
22− parseBinder,
23− parseBinderNoParens,
24−) where
25−
26−import Data.Maybe (isJust, fromMaybe)
27−import Control.Applicative
28−
29−import Language.PureScript.Parser.State
30−import Language.PureScript.Parser.Common
31−import Language.PureScript.Declarations
32−import Language.PureScript.Parser.Types
33−import Language.PureScript.Parser.Kinds
34−import Language.PureScript.CodeGen.JS.AST
35−import Language.PureScript.Environment
36−
37−import qualified Language.PureScript.Parser.Common as C
38−import qualified Text.Parsec as P
39−import qualified Text.Parsec.Expr as P
40−
41−-- |
42−-- Read source position information
43−--
44−sourcePos :: P.Parsec s u SourcePos
45−sourcePos = toSourcePos <$> P.getPosition
46− where
47− toSourcePos p = SourcePos (P.sourceName p) (P.sourceLine p) (P.sourceColumn p)
48−
49−parseDataDeclaration :: P.Parsec String ParseState Declaration
50−parseDataDeclaration = do
51− reserved "data"
52− name <- indented *> properName
53− tyArgs <- many (indented *> identifier)
54− ctors <- P.option [] $ do
55− _ <- lexeme $ indented *> P.char '='
56− sepBy1 ((,) <$> properName <*> P.many (indented *> parseTypeAtom)) pipe
57− return $ DataDeclaration name tyArgs ctors
58−
59−parseTypeDeclaration :: P.Parsec String ParseState Declaration
60−parseTypeDeclaration =
61− TypeDeclaration <$> P.try (parseIdent <* lexeme (indented *> P.string "::"))
62− <*> parsePolyType
63−
64−parseTypeSynonymDeclaration :: P.Parsec String ParseState Declaration
65−parseTypeSynonymDeclaration =
66− TypeSynonymDeclaration <$> (P.try (reserved "type") *> indented *> properName)
67− <*> many (indented *> identifier)
68− <*> (lexeme (indented *> P.char '=') *> parsePolyType)
69−
70−parseValueDeclaration :: P.Parsec String ParseState Declaration
71−parseValueDeclaration = do
72− name <- parseIdent
73− binders <- P.many parseBinderNoParens
74− guard <- P.optionMaybe parseGuard
75− value <- lexeme (indented *> P.char '=') *> parseValue
76− whereClause <- P.optionMaybe $ do
77− C.indented
78− reserved "where"
79− C.indented
80− C.mark $ P.many1 (C.same *> parseLocalDeclaration)
81− return $ ValueDeclaration name Value binders guard (maybe value (`Let` value) whereClause)
82−
83−parseExternDeclaration :: P.Parsec String ParseState Declaration
84−parseExternDeclaration = P.try (reserved "foreign") *> indented *> reserved "import" *> indented *>
85− (ExternDataDeclaration <$> (P.try (reserved "data") *> indented *> properName)
86− <*> (lexeme (indented *> P.string "::") *> parseKind)
87− <|> (do reserved "instance"
88− name <- parseIdent <* lexeme (indented *> P.string "::")
89− deps <- P.option [] $ do
90− deps <- parens (commaSep1 ((,) <$> parseQualified properName <*> P.many parseTypeAtom))
91− indented
92− reservedOp "=>"
93− return deps
94− className <- indented *> parseQualified properName
95− tys <- P.many (indented *> parseTypeAtom)
96− return $ ExternInstanceDeclaration name deps className tys)
97− <|> (do ident <- parseIdent
98− js <- P.optionMaybe (JSRaw <$> stringLiteral)
99− ty <- lexeme (indented *> P.string "::") *> parsePolyType
100− return $ ExternDeclaration (if isJust js then InlineJavascript else ForeignImport) ident js ty))
101−
102−parseAssociativity :: P.Parsec String ParseState Associativity
103−parseAssociativity =
104− (P.try (reserved "infixl") >> return Infixl) <|>
105− (P.try (reserved "infixr") >> return Infixr) <|>
106− (P.try (reserved "infix") >> return Infix)
107−
108−parseFixity :: P.Parsec String ParseState Fixity
109−parseFixity = Fixity <$> parseAssociativity <*> (indented *> natural)
110−
111−parseFixityDeclaration :: P.Parsec String ParseState Declaration
112−parseFixityDeclaration = do
113− fixity <- parseFixity
114− indented
115− name <- operator
116− return $ FixityDeclaration fixity name
117−
118−parseImportDeclaration :: P.Parsec String ParseState Declaration
119−parseImportDeclaration = do
120− reserved "import"
121− indented
122− qualImport <|> stdImport
123− where
124− stdImport = do
125− moduleName' <- moduleName
126− idents <- P.optionMaybe $ parens $ commaSep parseDeclarationRef
127− return $ ImportDeclaration moduleName' idents Nothing
128− qualImport = do
129− reserved "qualified"
130− indented
131− moduleName' <- moduleName
132− idents <- P.optionMaybe $ parens $ commaSep parseDeclarationRef
133− reserved "as"
134− asQ <- moduleName
135− return $ ImportDeclaration moduleName' idents (Just asQ)
136−
137−parseDeclarationRef :: P.Parsec String ParseState DeclarationRef
138−parseDeclarationRef = PositionedDeclarationRef <$> sourcePos <*>
139− (ValueRef <$> parseIdent
140− <|> do name <- properName
141− dctors <- P.optionMaybe $ parens (lexeme (P.string "..") *> pure Nothing <|> Just <$> commaSep properName)
142− return $ maybe (TypeClassRef name) (TypeRef name) dctors)
143−
144−parseTypeClassDeclaration :: P.Parsec String ParseState Declaration
145−parseTypeClassDeclaration = do
146− reserved "class"
147− implies <- P.option [] $ do
148− indented
149− implies <- parens (commaSep1 ((,) <$> parseQualified properName <*> P.many parseTypeAtom))
150− reservedOp "<="
151− return implies
152− className <- indented *> properName
153− idents <- P.many (indented *> identifier)
154− members <- P.option [] . P.try $ do
155− indented *> reserved "where"
156− mark (P.many (same *> parseTypeDeclaration))
157− return $ TypeClassDeclaration className idents implies members
158−
159−parseTypeInstanceDeclaration :: P.Parsec String ParseState Declaration
160−parseTypeInstanceDeclaration = do
161− reserved "instance"
162− name <- parseIdent <* lexeme (indented *> P.string "::")
163− deps <- P.optionMaybe $ do
164− deps <- parens (commaSep1 ((,) <$> parseQualified properName <*> P.many parseTypeAtom))
165− indented
166− reservedOp "=>"
167− return deps
168− className <- indented *> parseQualified properName
169− ty <- P.many (indented *> parseTypeAtom)
170− members <- P.option [] . P.try $ do
171− indented *> reserved "where"
172− mark (P.many (same *> parseValueDeclaration))
173− return $ TypeInstanceDeclaration name (fromMaybe [] deps) className ty members
174−
175−-- |
176−-- Parse a single declaration
177−--
178−parseDeclaration :: P.Parsec String ParseState Declaration
179−parseDeclaration = PositionedDeclaration <$> sourcePos <*> P.choice
180− [ parseDataDeclaration
181− , parseTypeDeclaration
182− , parseTypeSynonymDeclaration
183− , parseValueDeclaration
184− , parseExternDeclaration
185− , parseFixityDeclaration
186− , parseImportDeclaration
187− , parseTypeClassDeclaration
188− , parseTypeInstanceDeclaration
189− ] P.<?> "declaration"
190−
191−parseLocalDeclaration :: P.Parsec String ParseState Declaration
192−parseLocalDeclaration = PositionedDeclaration <$> sourcePos <*> P.choice
193− [ parseTypeDeclaration
194− , parseValueDeclaration
195− ] P.<?> "local declaration"
196−
197−-- |
198−-- Parse a module header and a collection of declarations
199−--
200−parseModule :: P.Parsec String ParseState Module
201−parseModule = do
202− reserved "module"
203− indented
204− name <- moduleName
205− exports <- P.optionMaybe $ parens $ commaSep1 parseDeclarationRef
206− _ <- lexeme $ P.string "where"
207− decls <- mark (P.many (same *> parseDeclaration))
208− return $ Module name decls exports
209−
210−-- |
211−-- Parse a collection of modules
212−--
213−parseModules :: P.Parsec String ParseState [Module]
214−parseModules = whiteSpace *> mark (P.many (same *> parseModule)) <* P.eof
215−
216−booleanLiteral :: P.Parsec String ParseState Bool
217−booleanLiteral = (C.reserved "true" >> return True) P.<|> (C.reserved "false" >> return False)
218−
219−parseNumericLiteral :: P.Parsec String ParseState Value
220−parseNumericLiteral = NumericLiteral <$> C.integerOrFloat
221−
222−parseStringLiteral :: P.Parsec String ParseState Value
223−parseStringLiteral = StringLiteral <$> C.stringLiteral
224−
225−parseBooleanLiteral :: P.Parsec String ParseState Value
226−parseBooleanLiteral = BooleanLiteral <$> booleanLiteral
227−
228−parseArrayLiteral :: P.Parsec String ParseState Value
229−parseArrayLiteral = ArrayLiteral <$> C.squares (C.commaSep parseValue)
230−
231−parseObjectLiteral :: P.Parsec String ParseState Value
232−parseObjectLiteral = ObjectLiteral <$> C.braces (C.commaSep parseIdentifierAndValue)
233−
234−parseIdentifierAndValue :: P.Parsec String ParseState (String, Value)
235−parseIdentifierAndValue = (,) <$> (C.indented *> (C.identifier <|> C.stringLiteral) <* C.indented <* C.colon)
236− <*> (C.indented *> parseValue)
237−
238−parseAbs :: P.Parsec String ParseState Value
239−parseAbs = do
240− C.reservedOp "\\"
241− args <- P.many1 (C.indented *> (Abs <$> (Left <$> P.try C.parseIdent <|> Right <$> parseBinderNoParens)))
242− C.indented *> C.reservedOp "->"
243− value <- parseValue
244− return $ toFunction args value
245− where
246− toFunction :: [Value -> Value] -> Value -> Value
247− toFunction args value = foldr ($) value args
248−
249−parseVar :: P.Parsec String ParseState Value
250−parseVar = Var <$> C.parseQualified C.parseIdent
251−
252−parseConstructor :: P.Parsec String ParseState Value
253−parseConstructor = Constructor <$> C.parseQualified C.properName
254−
255−parseCase :: P.Parsec String ParseState Value
256−parseCase = Case <$> P.between (P.try (C.reserved "case")) (C.indented *> C.reserved "of") (return <$> parseValue)
257− <*> (C.indented *> C.mark (P.many (C.same *> C.mark parseCaseAlternative)))
258−
259−parseCaseAlternative :: P.Parsec String ParseState CaseAlternative
260−parseCaseAlternative = CaseAlternative <$> (return <$> parseBinder)
261− <*> P.optionMaybe parseGuard
262− <*> (C.indented *> C.reservedOp "->" *> parseValue)
263− P.<?> "case alternative"
264−
265−parseIfThenElse :: P.Parsec String ParseState Value
266−parseIfThenElse = IfThenElse <$> (P.try (C.reserved "if") *> C.indented *> parseValue)
267− <*> (C.indented *> C.reserved "then" *> C.indented *> parseValue)
268− <*> (C.indented *> C.reserved "else" *> C.indented *> parseValue)
269−
270−parseLet :: P.Parsec String ParseState Value
271−parseLet = do
272− C.reserved "let"
273− C.indented
274− ds <- C.mark $ P.many1 (C.same *> parseLocalDeclaration)
275− C.indented
276− C.reserved "in"
277− result <- parseValue
278− return $ Let ds result
279−
280−parseValueAtom :: P.Parsec String ParseState Value
281−parseValueAtom = P.choice
282− [ P.try parseNumericLiteral
283− , P.try parseStringLiteral
284− , P.try parseBooleanLiteral
285− , parseArrayLiteral
286− , P.try parseObjectLiteral
287− , parseAbs
288− , P.try parseConstructor
289− , P.try parseVar
290− , parseCase
291− , parseIfThenElse
292− , parseDo
293− , parseLet
294− , Parens <$> C.parens parseValue ]
295−
296−parsePropertyUpdate :: P.Parsec String ParseState (String, Value)
297−parsePropertyUpdate = do
298− name <- C.lexeme (C.identifier <|> C.stringLiteral)
299− _ <- C.lexeme $ C.indented *> P.char '='
300− value <- C.indented *> parseValue
301− return (name, value)
302−
303−parseAccessor :: Value -> P.Parsec String ParseState Value
304−parseAccessor (Constructor _) = P.unexpected "constructor"
305−parseAccessor obj = P.try $ Accessor <$> (C.indented *> C.dot *> P.notFollowedBy C.opLetter *> C.indented *> (C.identifier <|> C.stringLiteral)) <*> pure obj
306−
307−parseDo :: P.Parsec String ParseState Value
308−parseDo = do
309− C.reserved "do"
310− C.indented
311− Do <$> C.mark (P.many (C.same *> C.mark parseDoNotationElement))
312−
313−parseDoNotationLet :: P.Parsec String ParseState DoNotationElement
314−parseDoNotationLet = DoNotationLet <$> (C.reserved "let" *> C.indented *> C.mark (P.many1 (C.same *> parseLocalDeclaration)))
315−
316−parseDoNotationBind :: P.Parsec String ParseState DoNotationElement
317−parseDoNotationBind = DoNotationBind <$> parseBinder <*> (C.indented *> C.reservedOp "<-" *> parseValue)
318−
319−parseDoNotationElement :: P.Parsec String ParseState DoNotationElement
320−parseDoNotationElement = P.choice
321− [ P.try parseDoNotationBind
322− , parseDoNotationLet
323− , P.try (DoNotationValue <$> parseValue) ]
324−
325−-- |
326−-- Parse a value
327−--
328−parseValue :: P.Parsec String ParseState Value
329−parseValue = PositionedValue <$> sourcePos <*>
330− (P.buildExpressionParser operators
331− . C.buildPostfixParser postfixTable2
332− $ indexersAndAccessors) P.<?> "expression"
333− where
334− indexersAndAccessors = C.buildPostfixParser postfixTable1 parseValueAtom
335− postfixTable1 = [ parseAccessor
336− , \v -> P.try $ flip ObjectUpdate <$> (C.indented *> C.braces (C.commaSep1 (C.indented *> parsePropertyUpdate))) <*> pure v ]
337− postfixTable2 = [ \v -> P.try (flip App <$> (C.indented *> indexersAndAccessors)) <*> pure v
338− , \v -> flip (TypedValue True) <$> (P.try (C.lexeme (C.indented *> P.string "::")) *> parsePolyType) <*> pure v
339− ]
340− operators = [ [ P.Prefix (C.lexeme (P.try (C.indented *> P.char '-') >> return UnaryMinus))
341− ]
342− , [ P.Infix (C.lexeme (P.try (C.indented *> C.parseIdentInfix P.<?> "operator") >>= \ident ->
343− return (BinaryNoParens ident))) P.AssocRight
344− ]
345− ]
346−
347−parseStringBinder :: P.Parsec String ParseState Binder
348−parseStringBinder = StringBinder <$> C.stringLiteral
349−
350−parseBooleanBinder :: P.Parsec String ParseState Binder
351−parseBooleanBinder = BooleanBinder <$> booleanLiteral
352−
353−parseNumberBinder :: P.Parsec String ParseState Binder
354−parseNumberBinder = NumberBinder <$> C.integerOrFloat
355−
356−parseVarBinder :: P.Parsec String ParseState Binder
357−parseVarBinder = VarBinder <$> C.parseIdent
358−
359−parseNullaryConstructorBinder :: P.Parsec String ParseState Binder
360−parseNullaryConstructorBinder = ConstructorBinder <$> C.lexeme (C.parseQualified C.properName) <*> pure []
361−
362−parseConstructorBinder :: P.Parsec String ParseState Binder
363−parseConstructorBinder = ConstructorBinder <$> C.lexeme (C.parseQualified C.properName) <*> many (C.indented *> parseBinderNoParens)
364−
365−parseObjectBinder :: P.Parsec String ParseState Binder
366−parseObjectBinder = ObjectBinder <$> C.braces (C.commaSep (C.indented *> parseIdentifierAndBinder))
367−
368−parseArrayBinder :: P.Parsec String ParseState Binder
369−parseArrayBinder = C.squares $ ArrayBinder <$> C.commaSep (C.indented *> parseBinder)
370−
371−parseNamedBinder :: P.Parsec String ParseState Binder
372−parseNamedBinder = NamedBinder <$> (C.parseIdent <* C.indented <* C.lexeme (P.char '@'))
373− <*> (C.indented *> parseBinder)
374−
375−parseNullBinder :: P.Parsec String ParseState Binder
376−parseNullBinder = C.lexeme (P.char '_') *> P.notFollowedBy C.identLetter *> return NullBinder
377−
378−parseIdentifierAndBinder :: P.Parsec String ParseState (String, Binder)
379−parseIdentifierAndBinder = do
380− name <- C.lexeme (C.identifier <|> C.stringLiteral)
381− _ <- C.lexeme $ C.indented *> P.char '='
382− binder <- C.indented *> parseBinder
383− return (name, binder)
384−
385−-- |
386−-- Parse a binder
387−--
388−parseBinder :: P.Parsec String ParseState Binder
389−parseBinder = PositionedBinder <$> sourcePos <*>
390− P.buildExpressionParser operators parseBinderAtom P.<?> "expression"
391− where
392− operators = [ [ P.Infix ( C.lexeme (P.try $ C.indented *> C.reservedOp ":") >> return ConsBinder) P.AssocRight ] ]
393− parseBinderAtom :: P.Parsec String ParseState Binder
394− parseBinderAtom = P.choice (map P.try
395− [ parseNullBinder
396− , parseStringBinder
397− , parseBooleanBinder
398− , parseNumberBinder
399− , parseNamedBinder
400− , parseVarBinder
401− , parseConstructorBinder
402− , parseObjectBinder
403− , parseArrayBinder
404− , C.parens parseBinder ]) P.<?> "binder"
405−
406−-- |
407−-- Parse a binder as it would appear in a top level declaration
408−--
409−parseBinderNoParens :: P.Parsec String ParseState Binder
410−parseBinderNoParens = P.choice (map P.try
411− [ parseNullBinder
412− , parseStringBinder
413− , parseBooleanBinder
414− , parseNumberBinder
415− , parseNamedBinder
416− , parseVarBinder
417− , parseNullaryConstructorBinder
418− , parseObjectBinder
419− , parseArrayBinder
420− , C.parens parseBinder ]) P.<?> "binder"
421−-- |
422−-- Parse a guard
423−--
424−parseGuard :: P.Parsec String ParseState Guard
425−parseGuard = C.indented *> C.pipe *> C.indented *> parseValue
426−
427−
src/Language/PureScript/Parser/Kinds.hsdeleted−45
@@ -1,45 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Parser.Kinds
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- A parser for kinds
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Parser.Kinds (
17− parseKind
18−) where
19−
20−import Language.PureScript.Kinds
21−import Language.PureScript.Parser.State
22−import Language.PureScript.Parser.Common
23−import Control.Applicative
24−import qualified Text.Parsec as P
25−import qualified Text.Parsec.Expr as P
26−
27−parseStar :: P.Parsec String ParseState Kind
28−parseStar = const Star <$> lexeme (P.char '*')
29−
30−parseBang :: P.Parsec String ParseState Kind
31−parseBang = const Bang <$> lexeme (P.char '!')
32−
33−parseTypeAtom :: P.Parsec String ParseState Kind
34−parseTypeAtom = indented *> P.choice (map P.try
35− [ parseStar
36− , parseBang
37− , parens parseKind ])
38−-- |
39−-- Parse a kind
40−--
41−parseKind :: P.Parsec String ParseState Kind
42−parseKind = P.buildExpressionParser operators parseTypeAtom P.<?> "kind"
43− where
44− operators = [ [ P.Prefix (lexeme (P.char '#') >> return Row) ]
45− , [ P.Infix (lexeme (P.try (P.string "->")) >> return FunKind) P.AssocRight ] ]
src/Language/PureScript/Parser/State.hsdeleted−30
@@ -1,30 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Parser.State
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- State for the parser monad
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Parser.State where
17−
18−import qualified Text.Parsec as P
19−
20−-- |
21−-- State for the parser monad
22−--
23−data ParseState = ParseState {
24− -- |
25− -- The most recently marked indentation level
26− --
27− indentationLevel :: P.Column
28− } deriving Show
29−
30−
src/Language/PureScript/Parser/Types.hsdeleted−128
@@ -1,128 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Parser.Types
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Parsers for types
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Parser.Types (
17− parseType,
18− parsePolyType,
19− parseTypeAtom
20−) where
21−
22−import Control.Applicative
23−import Control.Monad (when, unless)
24−
25−import Language.PureScript.Types
26−import Language.PureScript.Parser.State
27−import Language.PureScript.Parser.Common
28−import Language.PureScript.Environment
29−
30−import qualified Text.Parsec as P
31−import qualified Text.Parsec.Expr as P
32−
33−parseNumber :: P.Parsec String ParseState Type
34−parseNumber = const tyNumber <$> reserved "Number"
35−
36−parseString :: P.Parsec String ParseState Type
37−parseString = const tyString <$> reserved "String"
38−
39−parseBoolean :: P.Parsec String ParseState Type
40−parseBoolean = const tyBoolean <$> reserved "Boolean"
41−
42−parseArray :: P.Parsec String ParseState Type
43−parseArray = squares $ return tyArray
44−
45−parseArrayOf :: P.Parsec String ParseState Type
46−parseArrayOf = squares $ TypeApp tyArray <$> parseType
47−
48−parseFunction :: P.Parsec String ParseState Type
49−parseFunction = parens $ P.try (lexeme (P.string "->")) >> return tyFunction
50−
51−parseObject :: P.Parsec String ParseState Type
52−parseObject = braces $ TypeApp tyObject <$> parseRow False
53−
54−parseTypeVariable :: P.Parsec String ParseState Type
55−parseTypeVariable = do
56− ident <- identifier
57− when (ident `elem` reservedTypeNames) $ P.unexpected ident
58− return $ TypeVar ident
59−
60−parseTypeConstructor :: P.Parsec String ParseState Type
61−parseTypeConstructor = TypeConstructor <$> parseQualified properName
62−
63−parseForAll :: P.Parsec String ParseState Type
64−parseForAll = mkForAll <$> (P.try (reserved "forall") *> P.many1 (indented *> identifier) <* indented <* dot)
65− <*> parseConstrainedType
66−
67−-- |
68−-- Parse a type as it appears in e.g. a data constructor
69−--
70−parseTypeAtom :: P.Parsec String ParseState Type
71−parseTypeAtom = indented *> P.choice (map P.try
72− [ parseNumber
73− , parseString
74− , parseBoolean
75− , parseArray
76− , parseArrayOf
77− , parseFunction
78− , parseObject
79− , parseTypeVariable
80− , parseTypeConstructor
81− , parseForAll
82− , parens (parseRow True)
83− , parens parsePolyType ])
84−
85−parseConstrainedType :: P.Parsec String ParseState Type
86−parseConstrainedType = do
87− constraints <- P.optionMaybe . P.try $ do
88− constraints <- parens . commaSep1 $ do
89− className <- parseQualified properName
90− indented
91− ty <- P.many parseTypeAtom
92− return (className, ty)
93− _ <- lexeme $ P.string "=>"
94− return constraints
95− indented
96− ty <- parseType
97− return $ maybe ty (flip ConstrainedType ty) constraints
98−
99−parseAnyType :: P.Parsec String ParseState Type
100−parseAnyType = P.buildExpressionParser operators parseTypeAtom P.<?> "type"
101− where
102− operators = [ [ P.Infix (return TypeApp) P.AssocLeft ]
103− , [ P.Infix (P.try (lexeme (P.string "->")) >> return function) P.AssocRight ] ]
104−
105−-- |
106−-- Parse a monotype
107−--
108−parseType :: P.Parsec String ParseState Type
109−parseType = do
110− ty <- parseAnyType
111− unless (isMonoType ty) $ P.unexpected "polymorphic type"
112− return ty
113−
114−-- |
115−-- Parse a polytype
116−--
117−parsePolyType :: P.Parsec String ParseState Type
118−parsePolyType = parseAnyType
119−
120−parseNameAndType :: P.Parsec String ParseState t -> P.Parsec String ParseState (String, t)
121−parseNameAndType p = (,) <$> (indented *> (identifier <|> stringLiteral) <* indented <* lexeme (P.string "::")) <*> p
122−
123−parseRowEnding :: P.Parsec String ParseState Type
124−parseRowEnding = P.option REmpty (TypeVar <$> (lexeme (indented *> P.char '|') *> indented *> identifier))
125−
126−parseRow :: Bool -> P.Parsec String ParseState Type
127−parseRow nonEmpty = (curry rowFromList <$> many' (parseNameAndType parsePolyType) <*> parseRowEnding) P.<?> "row"
128− where many' = if nonEmpty then commaSep1 else commaSep
src/Language/PureScript/Pretty.hsdeleted−32
@@ -1,32 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Pretty
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- A collection of pretty printers for core data types:
13−--
14−-- [@Language.PureScript.Pretty.Kinds@] Pretty printer for kinds
15−--
16−-- [@Language.PureScript.Pretty.Values@] Pretty printer for values
17−--
18−-- [@Language.PureScript.Pretty.Types@] Pretty printer for types
19−--
20−-- [@Language.PureScript.Pretty.JS@] Pretty printer for values, used for code generation
21−--
22−-----------------------------------------------------------------------------
23−
24−module Language.PureScript.Pretty (module P) where
25−
26−import Language.PureScript.Pretty.Kinds as P
27−import Language.PureScript.Pretty.Values as P
28−import Language.PureScript.Pretty.Types as P
29−import Language.PureScript.Pretty.JS as P
30−
31−
32−
src/Language/PureScript/Pretty/Common.hsdeleted−60
@@ -1,60 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Pretty.Common
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Common pretty-printing utility functions
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Pretty.Common where
17−
18−import Control.Monad.State
19−import Data.List (intercalate)
20−
21−-- |
22−-- Wrap a string in parentheses
23−--
24−parens :: String -> String
25−parens s = ('(':s) ++ ")"
26−
27−newtype PrinterState = PrinterState { indent :: Int } deriving (Show, Eq, Ord)
28−
29−-- |
30−-- Number of characters per identation level
31−--
32−blockIndent :: Int
33−blockIndent = 4
34−
35−-- |
36−-- Pretty print with a new indentation level
37−--
38−withIndent :: StateT PrinterState Maybe String -> StateT PrinterState Maybe String
39−withIndent action = do
40− modify $ \st -> st { indent = indent st + blockIndent }
41− result <- action
42− modify $ \st -> st { indent = indent st - blockIndent }
43− return result
44−
45−-- |
46−-- Get the current indentation level
47−--
48−currentIndent :: StateT PrinterState Maybe String
49−currentIndent = do
50− current <- get
51− return $ replicate (indent current) ' '
52−
53−-- |
54−-- Print many lines
55−--
56−prettyPrintMany :: (a -> StateT PrinterState Maybe String) -> [a] -> StateT PrinterState Maybe String
57−prettyPrintMany f xs = do
58− ss <- mapM f xs
59− indentString <- currentIndent
60− return $ intercalate "\n" $ map (indentString ++) ss
src/Language/PureScript/Pretty/JS.hsdeleted−255
@@ -1,255 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Pretty.JS
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Pretty printer for the Javascript AST
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Pretty.JS (
17− prettyPrintJS
18−) where
19−
20−import Language.PureScript.Pretty.Common
21−import Language.PureScript.CodeGen.JS (isIdent)
22−import Language.PureScript.CodeGen.JS.AST
23−
24−import Data.List
25−import Data.Maybe (fromMaybe)
26−import qualified Control.Arrow as A
27−import Control.Arrow ((<+>))
28−import Control.PatternArrows
29−import Control.Applicative
30−import Control.Monad.State
31−import Numeric
32−
33−literals :: Pattern PrinterState JS String
34−literals = mkPattern' match
35− where
36− match :: JS -> StateT PrinterState Maybe String
37− match (JSNumericLiteral n) = return $ either show show n
38− match (JSStringLiteral s) = return $ string s
39− match (JSBooleanLiteral True) = return "true"
40− match (JSBooleanLiteral False) = return "false"
41− match (JSArrayLiteral xs) = fmap concat $ sequence
42− [ return "[ "
43− , fmap (intercalate ", ") $ forM xs prettyPrintJS'
44− , return " ]"
45− ]
46− match (JSObjectLiteral []) = return "{}"
47− match (JSObjectLiteral ps) = fmap concat $ sequence
48− [ return "{\n"
49− , withIndent $ do
50− jss <- forM ps $ \(key, value) -> fmap ((objectPropertyToString key ++ ": ") ++) . prettyPrintJS' $ value
51− indentString <- currentIndent
52− return $ intercalate ", \n" $ map (indentString ++) jss
53− , return "\n"
54− , currentIndent
55− , return "}"
56− ]
57− where
58− objectPropertyToString :: String -> String
59− objectPropertyToString s | isIdent s = s
60− | otherwise = show s
61− match (JSBlock sts) = fmap concat $ sequence
62− [ return "{\n"
63− , withIndent $ prettyStatements sts
64− , return "\n"
65− , currentIndent
66− , return "}"
67− ]
68− match (JSVar ident) = return ident
69− match (JSVariableIntroduction ident value) = fmap concat $ sequence
70− [ return "var "
71− , return ident
72− , maybe (return "") (fmap (" = " ++) . prettyPrintJS') value
73− ]
74− match (JSAssignment target value) = fmap concat $ sequence
75− [ prettyPrintJS' target
76− , return " = "
77− , prettyPrintJS' value
78− ]
79− match (JSWhile cond sts) = fmap concat $ sequence
80− [ return "while ("
81− , prettyPrintJS' cond
82− , return ") "
83− , prettyPrintJS' sts
84− ]
85− match (JSFor ident start end sts) = fmap concat $ sequence
86− [ return $ "for (var " ++ ident ++ " = "
87− , prettyPrintJS' start
88− , return $ "; " ++ ident ++ " < "
89− , prettyPrintJS' end
90− , return $ "; " ++ ident ++ "++) "
91− , prettyPrintJS' sts
92− ]
93− match (JSForIn ident obj sts) = fmap concat $ sequence
94− [ return $ "for (var " ++ ident ++ " in "
95− , prettyPrintJS' obj
96− , return ") "
97− , prettyPrintJS' sts
98− ]
99− match (JSIfElse cond thens elses) = fmap concat $ sequence
100− [ return "if ("
101− , prettyPrintJS' cond
102− , return ") "
103− , prettyPrintJS' thens
104− , maybe (return "") (fmap (" else " ++) . prettyPrintJS') elses
105− ]
106− match (JSReturn value) = fmap concat $ sequence
107− [ return "return "
108− , prettyPrintJS' value
109− ]
110− match (JSThrow value) = fmap concat $ sequence
111− [ return "throw "
112− , prettyPrintJS' value
113− ]
114− match (JSBreak lbl) = return $ "break " ++ lbl
115− match (JSContinue lbl) = return $ "continue " ++ lbl
116− match (JSLabel lbl js) = fmap concat $ sequence
117− [ return $ lbl ++ ": "
118− , prettyPrintJS' js
119− ]
120− match (JSRaw js) = return js
121− match _ = mzero
122−
123−string :: String -> String
124−string s = '"' : concatMap encodeChar s ++ "\""
125− where
126− encodeChar :: Char -> String
127− encodeChar '\b' = "\\b"
128− encodeChar '\t' = "\\t"
129− encodeChar '\n' = "\\n"
130− encodeChar '\v' = "\\v"
131− encodeChar '\f' = "\\f"
132− encodeChar '\r' = "\\r"
133− encodeChar '"' = "\\\""
134− encodeChar '\\' = "\\\\"
135− encodeChar c | fromEnum c > 0xFFF = "\\u" ++ showHex (fromEnum c) ""
136− encodeChar c | fromEnum c > 0xFF = "\\u0" ++ showHex (fromEnum c) ""
137− encodeChar c = [c]
138−
139−conditional :: Pattern PrinterState JS ((JS, JS), JS)
140−conditional = mkPattern match
141− where
142− match (JSConditional cond th el) = Just ((th, el), cond)
143− match _ = Nothing
144−
145−accessor :: Pattern PrinterState JS (String, JS)
146−accessor = mkPattern match
147− where
148− match (JSAccessor prop val) = Just (prop, val)
149− match _ = Nothing
150−
151−indexer :: Pattern PrinterState JS (String, JS)
152−indexer = mkPattern' match
153− where
154− match (JSIndexer index val) = (,) <$> prettyPrintJS' index <*> pure val
155− match _ = mzero
156−
157−lam :: Pattern PrinterState JS ((Maybe String, [String]), JS)
158−lam = mkPattern match
159− where
160− match (JSFunction name args ret) = Just ((name, args), ret)
161− match _ = Nothing
162−
163−app :: Pattern PrinterState JS (String, JS)
164−app = mkPattern' match
165− where
166− match (JSApp val args) = do
167− jss <- mapM prettyPrintJS' args
168− return (intercalate ", " jss, val)
169− match _ = mzero
170−
171−typeOf :: Pattern PrinterState JS ((), JS)
172−typeOf = mkPattern match
173− where
174− match (JSTypeOf val) = Just ((), val)
175− match _ = Nothing
176−
177−unary :: UnaryOperator -> String -> Operator PrinterState JS String
178−unary op str = Wrap match (++)
179− where
180− match :: Pattern PrinterState JS (String, JS)
181− match = mkPattern match'
182− where
183− match' (JSUnary op' val) | op' == op = Just (str, val)
184− match' _ = Nothing
185−
186−binary :: BinaryOperator -> String -> Operator PrinterState JS String
187−binary op str = AssocR match (\v1 v2 -> v1 ++ " " ++ str ++ " " ++ v2)
188− where
189− match :: Pattern PrinterState JS (JS, JS)
190− match = mkPattern match'
191− where
192− match' (JSBinary op' v1 v2) | op' == op = Just (v1, v2)
193− match' _ = Nothing
194−
195−prettyStatements :: [JS] -> StateT PrinterState Maybe String
196−prettyStatements sts = do
197− jss <- forM sts prettyPrintJS'
198− indentString <- currentIndent
199− return $ intercalate "\n" $ map ((++ ";") . (indentString ++)) jss
200−
201−-- |
202−-- Generate a pretty-printed string representing a Javascript expression
203−--
204−prettyPrintJS1 :: JS -> String
205−prettyPrintJS1 = fromMaybe (error "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyPrintJS'
206−
207−-- |
208−-- Generate a pretty-printed string representing a collection of Javascript expressions at the same indentation level
209−--
210−prettyPrintJS :: [JS] -> String
211−prettyPrintJS = fromMaybe (error "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyStatements
212−
213−-- |
214−-- Generate an indented, pretty-printed string representing a Javascript expression
215−--
216−prettyPrintJS' :: JS -> StateT PrinterState Maybe String
217−prettyPrintJS' = A.runKleisli $ runPattern matchValue
218− where
219− matchValue :: Pattern PrinterState JS String
220− matchValue = buildPrettyPrinter operators (literals <+> fmap parens matchValue)
221− operators :: OperatorTable PrinterState JS String
222− operators =
223− OperatorTable [ [ Wrap accessor $ \prop val -> val ++ "." ++ prop ]
224− , [ Wrap indexer $ \index val -> val ++ "[" ++ index ++ "]" ]
225− , [ Wrap app $ \args val -> val ++ "(" ++ args ++ ")" ]
226− , [ Wrap lam $ \(name, args) ret -> "function "
227− ++ fromMaybe "" name
228− ++ "(" ++ intercalate ", " args ++ ") "
229− ++ ret ]
230− , [ Wrap conditional $ \(th, el) cond -> cond ++ " ? " ++ prettyPrintJS1 th ++ " : " ++ prettyPrintJS1 el ]
231− , [ binary LessThan "<" ]
232− , [ binary LessThanOrEqualTo "<=" ]
233− , [ binary GreaterThan ">" ]
234− , [ binary GreaterThanOrEqualTo ">=" ]
235− , [ Wrap typeOf $ \_ s -> "typeof " ++ s ]
236− , [ unary Not "!" ]
237− , [ unary BitwiseNot "~" ]
238− , [ unary Negate "-" ]
239− , [ unary Positive "+" ]
240− , [ binary Multiply "*" ]
241− , [ binary Divide "/" ]
242− , [ binary Modulus "%" ]
243− , [ binary Add "+" ]
244− , [ binary Subtract "-" ]
245− , [ binary ShiftLeft "<<" ]
246− , [ binary ShiftRight ">>" ]
247− , [ binary ZeroFillShiftRight ">>>" ]
248− , [ binary EqualTo "===" ]
249− , [ binary NotEqualTo "!==" ]
250− , [ binary BitwiseAnd "&" ]
251− , [ binary BitwiseXor "^" ]
252− , [ binary BitwiseOr "|" ]
253− , [ binary And "&&" ]
254− , [ binary Or "||" ]
255− ]
src/Language/PureScript/Pretty/Kinds.hsdeleted−60
@@ -1,60 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Pretty.Kinds
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Pretty printer for kinds
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Pretty.Kinds (
17− prettyPrintKind
18−) where
19−
20−import Data.Maybe (fromMaybe)
21−
22−import Control.Arrow (ArrowPlus(..))
23−import Control.PatternArrows
24−import Control.Monad.Unify
25−
26−import Language.PureScript.Kinds
27−import Language.PureScript.Pretty.Common
28−
29−typeLiterals :: Pattern () Kind String
30−typeLiterals = mkPattern match
31− where
32− match Star = Just "*"
33− match Bang = Just "!"
34− match (KUnknown (Unknown u)) = Just $ 'u' : show u
35− match _ = Nothing
36−
37−matchRow :: Pattern () Kind ((), Kind)
38−matchRow = mkPattern match
39− where
40− match (Row k) = Just ((), k)
41− match _ = Nothing
42−
43−funKind :: Pattern () Kind (Kind, Kind)
44−funKind = mkPattern match
45− where
46− match (FunKind arg ret) = Just (arg, ret)
47− match _ = Nothing
48−
49−-- |
50−-- Generate a pretty-printed string representing a Kind
51−--
52−prettyPrintKind :: Kind -> String
53−prettyPrintKind = fromMaybe (error "Incomplete pattern") . pattern matchKind ()
54− where
55− matchKind :: Pattern () Kind String
56− matchKind = buildPrettyPrinter operators (typeLiterals <+> fmap parens matchKind)
57− operators :: OperatorTable () Kind String
58− operators =
59− OperatorTable [ [ Wrap matchRow $ \_ k -> "# " ++ k]
60− , [ AssocR funKind $ \arg ret -> arg ++ " -> " ++ ret ] ]
src/Language/PureScript/Pretty/Types.hsdeleted−120
@@ -1,120 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Pretty.Types
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Pretty printer for Types
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Pretty.Types (
17− prettyPrintType,
18− prettyPrintTypeAtom,
19− prettyPrintRow
20−) where
21−
22−import Data.Maybe (fromMaybe)
23−import Data.List (intercalate)
24−import Data.Generics (mkT, everywhere, everywhere')
25−
26−import Control.Arrow ((<+>))
27−import Control.PatternArrows
28−import Control.Monad.Unify
29−
30−import Language.PureScript.Types
31−import Language.PureScript.Pretty.Common
32−import Language.PureScript.Environment
33−
34−typeLiterals :: Pattern () Type String
35−typeLiterals = mkPattern match
36− where
37− match (TypeVar var) = Just var
38− match (PrettyPrintObject row) = Just $ "{ " ++ prettyPrintRow row ++ " }"
39− match (PrettyPrintArray ty) = Just $ "[" ++ prettyPrintType ty ++ "]"
40− match (TypeConstructor ctor) = Just $ show ctor
41− match (TUnknown (Unknown u)) = Just $ 'u' : show u
42− match (Skolem s _) = Just $ 's' : show s
43− match (ConstrainedType deps ty) = Just $ "(" ++ intercalate ", " (map (\(pn, ty') -> show pn ++ " " ++ unwords (map prettyPrintTypeAtom ty')) deps) ++ ") => " ++ prettyPrintType ty
44− match (SaturatedTypeSynonym name args) = Just $ show name ++ "<" ++ intercalate "," (map prettyPrintTypeAtom args) ++ ">"
45− match REmpty = Just "()"
46− match row@RCons{} = Just $ '(' : prettyPrintRow row ++ ")"
47− match _ = Nothing
48−
49−-- |
50−-- Generate a pretty-printed string representing a Row
51−--
52−prettyPrintRow :: Type -> String
53−prettyPrintRow = (\(tys, rest) -> intercalate ", " (map (uncurry nameAndTypeToPs) tys) ++ tailToPs rest) . toList []
54− where
55− nameAndTypeToPs :: String -> Type -> String
56− nameAndTypeToPs name ty = name ++ " :: " ++ prettyPrintType ty
57− tailToPs :: Type -> String
58− tailToPs REmpty = ""
59− tailToPs other = " | " ++ prettyPrintType other
60− toList :: [(String, Type)] -> Type -> ([(String, Type)], Type)
61− toList tys (RCons name ty row) = toList ((name, ty):tys) row
62− toList tys r = (tys, r)
63−
64−typeApp :: Pattern () Type (Type, Type)
65−typeApp = mkPattern match
66− where
67− match (TypeApp f x) = Just (f, x)
68− match _ = Nothing
69−
70−appliedFunction :: Pattern () Type (Type, Type)
71−appliedFunction = mkPattern match
72− where
73− match (PrettyPrintFunction arg ret) = Just (arg, ret)
74− match _ = Nothing
75−
76−insertPlaceholders :: Type -> Type
77−insertPlaceholders = everywhere' (mkT convertForAlls) . everywhere (mkT convert)
78− where
79− convert (TypeApp (TypeApp f arg) ret) | f == tyFunction = PrettyPrintFunction arg ret
80− convert (TypeApp a el) | a == tyArray = PrettyPrintArray el
81− convert (TypeApp o r) | o == tyObject = PrettyPrintObject r
82− convert other = other
83− convertForAlls (ForAll ident ty _) = go [ident] ty
84− where
85− go idents (ForAll ident' ty' _) = go (ident' : idents) ty'
86− go idents other = PrettyPrintForAll idents other
87− convertForAlls other = other
88−
89−matchTypeAtom :: Pattern () Type String
90−matchTypeAtom = typeLiterals <+> fmap parens matchType
91−
92−matchType :: Pattern () Type String
93−matchType = buildPrettyPrinter operators matchTypeAtom
94− where
95− operators :: OperatorTable () Type String
96− operators =
97− OperatorTable [ [ AssocL typeApp $ \f x -> f ++ " " ++ x ]
98− , [ AssocR appliedFunction $ \arg ret -> arg ++ " -> " ++ ret
99− ]
100− , [ Wrap forall_ $ \idents ty -> "forall " ++ unwords idents ++ ". " ++ ty ]
101− ]
102−
103−forall_ :: Pattern () Type ([String], Type)
104−forall_ = mkPattern match
105− where
106− match (PrettyPrintForAll idents ty) = Just (idents, ty)
107− match _ = Nothing
108−
109−-- |
110−-- Generate a pretty-printed string representing a Type, as it should appear inside parentheses
111−--
112−prettyPrintTypeAtom :: Type -> String
113−prettyPrintTypeAtom = fromMaybe (error "Incomplete pattern") . pattern matchTypeAtom () . insertPlaceholders
114−
115−
116−-- |
117−-- Generate a pretty-printed string representing a Type
118−--
119−prettyPrintType :: Type -> String
120−prettyPrintType = fromMaybe (error "Incomplete pattern") . pattern matchType () . insertPlaceholders
src/Language/PureScript/Pretty/Values.hsdeleted−225
@@ -1,225 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Pretty.Values
4−-- Copyright : Kinds.hs(c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Pretty printer for values
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Pretty.Values (
17− prettyPrintValue,
18− prettyPrintBinder
19−) where
20−
21−import Data.Maybe (fromMaybe)
22−import Data.List (intercalate)
23−
24−import Control.Arrow ((<+>), runKleisli)
25−import Control.PatternArrows
26−import Control.Monad.State
27−import Control.Applicative
28−
29−import Language.PureScript.Declarations
30−import Language.PureScript.Pretty.Common
31−import Language.PureScript.Pretty.Types (prettyPrintType)
32−
33−literals :: Pattern PrinterState Value String
34−literals = mkPattern' match
35− where
36− match :: Value -> StateT PrinterState Maybe String
37− match (NumericLiteral n) = return $ either show show n
38− match (StringLiteral s) = return $ show s
39− match (BooleanLiteral True) = return "true"
40− match (BooleanLiteral False) = return "false"
41− match (ArrayLiteral xs) = fmap concat $ sequence
42− [ return "[ "
43− , withIndent $ prettyPrintMany prettyPrintValue' xs
44− , return " ]"
45− ]
46− match (ObjectLiteral []) = return "{}"
47− match (ObjectLiteral ps) = fmap concat $ sequence
48− [ return "{\n"
49− , withIndent $ prettyPrintMany prettyPrintObjectProperty ps
50− , return "\n"
51− , currentIndent
52− , return "}"
53− ]
54− match (Constructor name) = return $ show name
55− match (Case values binders) = fmap concat $ sequence
56− [ return "case "
57− , unwords <$> forM values prettyPrintValue'
58− , return " of\n"
59− , withIndent $ prettyPrintMany prettyPrintCaseAlternative binders
60− , currentIndent
61− ]
62− match (Let ds val) = fmap concat $ sequence
63− [ return "let\n"
64− , withIndent $ prettyPrintMany prettyPrintDeclaration ds
65− , return "\n"
66− , currentIndent
67− , return "in "
68− , prettyPrintValue' val
69− ]
70− match (Var ident) = return $ show ident
71− match (Do els) = fmap concat $ sequence
72− [ return "do "
73− , withIndent $ prettyPrintMany prettyPrintDoNotationElement els
74− , currentIndent
75− ]
76− match (TypeClassDictionary _ _ _) = return "<<dict>>"
77− match (TypedValue _ val _) = prettyPrintValue' val
78− match (PositionedValue _ val) = prettyPrintValue' val
79− match _ = mzero
80−
81−prettyPrintDeclaration :: Declaration -> StateT PrinterState Maybe String
82−prettyPrintDeclaration (TypeDeclaration ident ty) = return $ show ident ++ " :: " ++ prettyPrintType ty
83−prettyPrintDeclaration (ValueDeclaration ident _ [] Nothing val) = fmap concat $ sequence
84− [ return $ show ident ++ " = "
85− , prettyPrintValue' val
86− ]
87−prettyPrintDeclaration (PositionedDeclaration _ d) = prettyPrintDeclaration d
88−prettyPrintDeclaration _ = error "Invalid argument to prettyPrintDeclaration"
89−
90−prettyPrintCaseAlternative :: CaseAlternative -> StateT PrinterState Maybe String
91−prettyPrintCaseAlternative (CaseAlternative binders grd val) =
92− fmap concat $ sequence
93− [ intercalate ", " <$> forM binders prettyPrintBinder'
94− , maybe (return "") (fmap ("| " ++) . prettyPrintValue') grd
95− , return " -> "
96− , prettyPrintValue' val
97− ]
98−
99−prettyPrintDoNotationElement :: DoNotationElement -> StateT PrinterState Maybe String
100−prettyPrintDoNotationElement (DoNotationValue val) =
101− prettyPrintValue' val
102−prettyPrintDoNotationElement (DoNotationBind binder val) =
103− fmap concat $ sequence
104− [ prettyPrintBinder' binder
105− , return " <- "
106− , prettyPrintValue' val
107− ]
108−prettyPrintDoNotationElement (DoNotationLet ds) =
109− fmap concat $ sequence
110− [ return "let "
111− , withIndent $ prettyPrintMany prettyPrintDeclaration ds
112− ]
113−prettyPrintDoNotationElement (PositionedDoNotationElement _ el) = prettyPrintDoNotationElement el
114−
115−ifThenElse :: Pattern PrinterState Value ((Value, Value), Value)
116−ifThenElse = mkPattern match
117− where
118− match (IfThenElse cond th el) = Just ((th, el), cond)
119− match _ = Nothing
120−
121−accessor :: Pattern PrinterState Value (String, Value)
122−accessor = mkPattern match
123− where
124− match (Accessor prop val) = Just (prop, val)
125− match _ = Nothing
126−
127−objectUpdate :: Pattern PrinterState Value ([String], Value)
128−objectUpdate = mkPattern match
129− where
130− match (ObjectUpdate o ps) = Just (flip map ps $ \(key, val) -> key ++ " = " ++ prettyPrintValue val, o)
131− match _ = Nothing
132−
133−app :: Pattern PrinterState Value (String, Value)
134−app = mkPattern match
135− where
136− match (App val arg) = Just (prettyPrintValue arg, val)
137− match _ = Nothing
138−
139−lam :: Pattern PrinterState Value (String, Value)
140−lam = mkPattern match
141− where
142− match (Abs (Left arg) val) = Just (show arg, val)
143− match _ = Nothing
144−
145−-- |
146−-- Generate a pretty-printed string representing an expression
147−--
148−prettyPrintValue :: Value -> String
149−prettyPrintValue = fromMaybe (error "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyPrintValue'
150−
151−prettyPrintValue' :: Value -> StateT PrinterState Maybe String
152−prettyPrintValue' = runKleisli $ runPattern matchValue
153− where
154− matchValue :: Pattern PrinterState Value String
155− matchValue = buildPrettyPrinter operators (literals <+> fmap parens matchValue)
156− operators :: OperatorTable PrinterState Value String
157− operators =
158− OperatorTable [ [ Wrap accessor $ \prop val -> val ++ "." ++ prop ]
159− , [ Wrap objectUpdate $ \ps val -> val ++ "{ " ++ intercalate ", " ps ++ " }" ]
160− , [ Wrap app $ \arg val -> val ++ "(" ++ arg ++ ")" ]
161− , [ Split lam $ \arg val -> "\\" ++ arg ++ " -> " ++ prettyPrintValue val ]
162− , [ Wrap ifThenElse $ \(th, el) cond -> "if " ++ cond ++ " then " ++ prettyPrintValue th ++ " else " ++ prettyPrintValue el ]
163− ]
164−
165−prettyPrintBinderAtom :: Pattern PrinterState Binder String
166−prettyPrintBinderAtom = mkPattern' match
167− where
168− match :: Binder -> StateT PrinterState Maybe String
169− match NullBinder = return "_"
170− match (StringBinder str) = return $ show str
171− match (NumberBinder num) = return $ either show show num
172− match (BooleanBinder True) = return "true"
173− match (BooleanBinder False) = return "false"
174− match (VarBinder ident) = return $ show ident
175− match (ConstructorBinder ctor args) = fmap concat $ sequence
176− [ return $ show ctor ++ " "
177− , unwords <$> forM args match
178− ]
179− match (ObjectBinder bs) = fmap concat $ sequence
180− [ return "{\n"
181− , withIndent $ prettyPrintMany prettyPrintObjectPropertyBinder bs
182− , currentIndent
183− , return "}"
184− ]
185− match (ArrayBinder bs) = fmap concat $ sequence
186− [ return "["
187− , unwords <$> mapM prettyPrintBinder' bs
188− , return "]"
189− ]
190− match (NamedBinder ident binder) = ((show ident ++ "@") ++) <$> prettyPrintBinder' binder
191− match (PositionedBinder _ binder) = prettyPrintBinder' binder
192− match _ = mzero
193−
194−-- |
195−-- Generate a pretty-printed string representing a Binder
196−--
197−prettyPrintBinder :: Binder -> String
198−prettyPrintBinder = fromMaybe (error "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyPrintBinder'
199−
200−prettyPrintBinder' :: Binder -> StateT PrinterState Maybe String
201−prettyPrintBinder' = runKleisli $ runPattern matchBinder
202− where
203− matchBinder :: Pattern PrinterState Binder String
204− matchBinder = buildPrettyPrinter operators (prettyPrintBinderAtom <+> fmap parens matchBinder)
205− operators :: OperatorTable PrinterState Binder String
206− operators =
207− OperatorTable [ [ AssocR matchConsBinder (\b1 b2 -> b1 ++ " : " ++ b2) ] ]
208−
209−matchConsBinder :: Pattern PrinterState Binder (Binder, Binder)
210−matchConsBinder = mkPattern match'
211− where
212− match' (ConsBinder b1 b2) = Just (b1, b2)
213− match' _ = Nothing
214−
215−prettyPrintObjectPropertyBinder :: (String, Binder) -> StateT PrinterState Maybe String
216−prettyPrintObjectPropertyBinder (key, binder) = fmap concat $ sequence
217− [ return $ key ++ ": "
218− , prettyPrintBinder' binder
219− ]
220−
221−prettyPrintObjectProperty :: (String, Value) -> StateT PrinterState Maybe String
222−prettyPrintObjectProperty (key, value) = fmap concat $ sequence
223− [ return $ key ++ ": "
224− , prettyPrintValue' value
225− ]
src/Language/PureScript/Scope.hsdeleted−62
@@ -1,62 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Scope
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Utility functions for working with names in scope
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Scope (
17− usedNames,
18− unusedNames
19−) where
20−
21−import Control.Applicative ((<$>))
22−
23−import Data.Data
24−import Data.List ((\\), nub)
25−import Data.Generics (extQ, mkQ, everything)
26−
27−import Language.PureScript.Declarations
28−import Language.PureScript.Names
29−import Language.PureScript.CodeGen.JS.AST
30−
31−-- |
32−-- Gather all used names appearing inside a value
33−--
34−usedNames :: (Data d) => d -> [Ident]
35−usedNames val = nub $ everything (++) (mkQ [] namesV `extQ` namesB `extQ` namesJS) val
36− where
37− namesV :: Value -> [Ident]
38− namesV (Abs (Left arg) _) = [arg]
39− namesV (Var (Qualified Nothing name)) = [name]
40− namesV _ = []
41− namesB :: Binder -> [Ident]
42− namesB (VarBinder name) = [name]
43− namesB _ = []
44− namesJS :: JS -> [Ident]
45− namesJS (JSVar name) = [Ident name]
46− namesJS (JSFunction (Just name) args _) = Ident name : (Ident <$> args)
47− namesJS (JSFunction Nothing args _) = Ident <$> args
48− namesJS (JSVariableIntroduction name _) = [Ident name]
49− namesJS (JSFor name _ _ _) = [Ident name]
50− namesJS (JSForIn name _ _) = [Ident name]
51− namesJS _ = []
52−
53−-- |
54−-- Generate a set of names which are unused inside a value, of the form @_{n}@ for an integer @n@
55−--
56−unusedNames :: (Data d) => d -> [Ident]
57−unusedNames val =
58− let
59− allNames = usedNames val
60− varNames = map (Ident . ('_' :) . show) ([1..] :: [Int])
61− in
62− varNames \\ allNames
src/Language/PureScript/Sugar.hsdeleted−58
@@ -1,58 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Sugar
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Desugaring passes
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.Sugar (desugar, module S) where
17−
18−import Control.Monad
19−
20−import Language.PureScript.Declarations
21−import Language.PureScript.Errors
22−
23−import Language.PureScript.Sugar.Operators as S
24−import Language.PureScript.Sugar.DoNotation as S
25−import Language.PureScript.Sugar.CaseDeclarations as S
26−import Language.PureScript.Sugar.TypeDeclarations as S
27−import Language.PureScript.Sugar.BindingGroups as S
28−import Language.PureScript.Sugar.TypeClasses as S
29−import Language.PureScript.Sugar.Names as S
30−
31−import Control.Category ((>>>))
32−
33−-- |
34−-- The desugaring pipeline proceeds as follows:
35−--
36−-- * Introduce type synonyms for type class dictionaries
37−--
38−-- * Rebracket user-defined binary operators
39−--
40−-- * Desugar do-notation using the @Prelude.Monad@ type class
41−--
42−-- * Desugar top-level case declarations into explicit case expressions
43−--
44−-- * Desugar type declarations into value declarations with explicit type annotations
45−--
46−-- * Group mutually recursive value and data declarations into binding groups.
47−--
48−-- * Qualify any unqualified names and types
49−--
50−desugar :: [Module] -> Either ErrorStack [Module]
51−desugar = removeSignedLiterals
52− >>> desugarDo
53− >=> desugarCasesModule
54− >=> desugarTypeDeclarationsModule
55− >=> desugarImports
56− >=> rebracket
57− >=> desugarTypeClasses
58− >=> createBindingGroupsModule
src/Language/PureScript/Sugar/BindingGroups.hsdeleted−146
@@ -1,146 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.BindingGroups
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module implements the desugaring pass which creates binding groups from sets of
13−-- mutually-recursive value declarations and mutually-recursive type declarations.
14−--
15−-----------------------------------------------------------------------------
16−
17−module Language.PureScript.Sugar.BindingGroups (
18− createBindingGroups,
19− createBindingGroupsModule,
20− collapseBindingGroups,
21− collapseBindingGroupsModule
22−) where
23−
24−import Data.Data
25−import Data.Graph
26−import Data.Generics
27−import Data.Generics.Extras
28−import Data.List (nub, intersect)
29−import Data.Maybe (isJust, mapMaybe)
30−import Control.Applicative ((<$>), (<*>), pure)
31−
32−import Language.PureScript.Declarations
33−import Language.PureScript.Names
34−import Language.PureScript.Types
35−import Language.PureScript.Environment
36−import Language.PureScript.Errors
37−
38−-- |
39−-- Replace all sets of mutually-recursive declarations in a module with binding groups
40−--
41−createBindingGroupsModule :: [Module] -> Either ErrorStack [Module]
42−createBindingGroupsModule = mapM $ \(Module name ds exps) -> Module name <$> createBindingGroups name ds <*> pure exps
43−
44−-- |
45−-- Collapse all binding groups in a module to individual declarations
46−--
47−collapseBindingGroupsModule :: [Module] -> [Module]
48−collapseBindingGroupsModule = map $ \(Module name ds exps) -> Module name (collapseBindingGroups ds) exps
49−
50−-- |
51−-- Replace all sets of mutually-recursive declarations with binding groups
52−--
53−createBindingGroups :: ModuleName -> [Declaration] -> Either ErrorStack [Declaration]
54−createBindingGroups moduleName ds = do
55− values <- mapM (createBindingGroupsForValue moduleName) $ filter isValueDecl ds
56− let dataDecls = filter isDataDecl ds
57− allProperNames = map getProperName dataDecls
58− dataVerts = map (\d -> (d, getProperName d, usedProperNames moduleName d `intersect` allProperNames)) dataDecls
59− dataBindingGroupDecls <- mapM toDataBindingGroup $ stronglyConnComp dataVerts
60− let allIdents = map getIdent values
61− valueVerts = map (\d -> (d, getIdent d, usedIdents moduleName d `intersect` allIdents)) values
62− bindingGroupDecls = map toBindingGroup $ stronglyConnComp valueVerts
63− return $ filter isImportDecl ds ++
64− filter isExternDataDecl ds ++
65− filter isExternInstanceDecl ds ++
66− dataBindingGroupDecls ++
67− filter isTypeClassDeclaration ds ++
68− filter isFixityDecl ds ++
69− filter isExternDecl ds ++
70− bindingGroupDecls
71−
72−createBindingGroupsForValue :: ModuleName -> Declaration -> Either ErrorStack Declaration
73−createBindingGroupsForValue moduleName = everywhereM' (mkM go)
74− where
75− go (Let ds val) = Let <$> createBindingGroups moduleName ds <*> pure val
76− go other = return other
77−
78−-- |
79−-- Collapse all binding groups to individual declarations
80−--
81−collapseBindingGroups :: [Declaration] -> [Declaration]
82−collapseBindingGroups = everywhere (mkT collapseBindingGroupsForValue) . concatMap go
83− where
84− go (DataBindingGroupDeclaration ds) = ds
85− go (BindingGroupDeclaration ds) = map (\(ident, nameKind, val) -> ValueDeclaration ident nameKind [] Nothing val) ds
86− go (PositionedDeclaration pos d) = map (PositionedDeclaration pos) $ go d
87− go other = [other]
88−
89−collapseBindingGroupsForValue :: Value -> Value
90−collapseBindingGroupsForValue (Let ds val) = Let (collapseBindingGroups ds) val
91−collapseBindingGroupsForValue other = other
92−
93−usedIdents :: (Data d) => ModuleName -> d -> [Ident]
94−usedIdents moduleName = nub . everything (++) (mkQ [] usedNames)
95− where
96− usedNames :: Value -> [Ident]
97− usedNames (Var (Qualified Nothing name)) = [name]
98− usedNames (Var (Qualified (Just moduleName') name)) | moduleName == moduleName' = [name]
99− usedNames _ = []
100−
101−usedProperNames :: (Data d) => ModuleName -> d -> [ProperName]
102−usedProperNames moduleName = nub . everything (++) (mkQ [] usedNames)
103− where
104− usedNames :: Type -> [ProperName]
105− usedNames (ConstrainedType constraints _) = flip mapMaybe constraints $ \qual ->
106− case qual of
107− (Qualified (Just moduleName') name, _) | moduleName == moduleName' -> Just name
108− _ -> Nothing
109− usedNames (TypeConstructor (Qualified (Just moduleName') name)) | moduleName == moduleName' = [name]
110− usedNames _ = []
111−
112−getIdent :: Declaration -> Ident
113−getIdent (ValueDeclaration ident _ _ _ _) = ident
114−getIdent (PositionedDeclaration _ d) = getIdent d
115−getIdent _ = error "Expected ValueDeclaration"
116−
117−getProperName :: Declaration -> ProperName
118−getProperName (DataDeclaration pn _ _) = pn
119−getProperName (TypeSynonymDeclaration pn _ _) = pn
120−getProperName (PositionedDeclaration _ d) = getProperName d
121−getProperName _ = error "Expected DataDeclaration"
122−
123−toBindingGroup :: SCC Declaration -> Declaration
124−toBindingGroup (AcyclicSCC d) = d
125−toBindingGroup (CyclicSCC [d]) = d
126−toBindingGroup (CyclicSCC ds') = BindingGroupDeclaration $ map fromValueDecl ds'
127−
128−toDataBindingGroup :: SCC Declaration -> Either ErrorStack Declaration
129−toDataBindingGroup (AcyclicSCC d) = return d
130−toDataBindingGroup (CyclicSCC [d]) = case isTypeSynonym d of
131− Just pn -> Left $ mkErrorStack ("Cycle in type synonym " ++ show pn) Nothing
132− _ -> return d
133−toDataBindingGroup (CyclicSCC ds')
134− | all (isJust . isTypeSynonym) ds' = Left $ mkErrorStack "Cycle in type synonyms" Nothing
135− | otherwise = return $ DataBindingGroupDeclaration ds'
136−
137−isTypeSynonym :: Declaration -> Maybe ProperName
138−isTypeSynonym (TypeSynonymDeclaration pn _ _) = Just pn
139−isTypeSynonym (PositionedDeclaration _ d) = isTypeSynonym d
140−isTypeSynonym _ = Nothing
141−
142−fromValueDecl :: Declaration -> (Ident, NameKind, Value)
143−fromValueDecl (ValueDeclaration ident nameKind [] Nothing val) = (ident, nameKind, val)
144−fromValueDecl ValueDeclaration{} = error "Binders should have been desugared"
145−fromValueDecl (PositionedDeclaration _ d) = fromValueDecl d
146−fromValueDecl _ = error "Expected ValueDeclaration"
src/Language/PureScript/Sugar/CaseDeclarations.hsdeleted−115
@@ -1,115 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.CaseDeclarations
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module implements the desugaring pass which replaces top-level binders with
13−-- case expressions.
14−--
15−-----------------------------------------------------------------------------
16−
17−module Language.PureScript.Sugar.CaseDeclarations (
18− desugarCases,
19− desugarCasesModule
20−) where
21−
22−import Data.Monoid ((<>))
23−import Data.List (groupBy)
24−import Data.Generics (mkM, mkT, everywhere)
25−import Data.Generics.Extras
26−
27−import Control.Applicative
28−import Control.Monad ((<=<), forM, join, unless)
29−import Control.Monad.Error.Class
30−
31−import Language.PureScript.Names
32−import Language.PureScript.Declarations
33−import Language.PureScript.Scope
34−import Language.PureScript.Environment
35−import Language.PureScript.Errors
36−
37−-- |
38−-- Replace all top-level binders in a module with case expressions.
39−--
40−desugarCasesModule :: [Module] -> Either ErrorStack [Module]
41−desugarCasesModule ms = forM ms $ \(Module name ds exps) ->
42− rethrow (strMsg ("Error in module " ++ show name) <>) $
43− Module name <$> (desugarCases . desugarAbs $ ds) <*> pure exps
44−
45−desugarAbs :: [Declaration] -> [Declaration]
46−desugarAbs = everywhere (mkT replace)
47− where
48− replace (Abs (Right binder) val) =
49− let
50− ident = head $ unusedNames (binder, val)
51− in
52− Abs (Left ident) $ Case [Var (Qualified Nothing ident)] [CaseAlternative [binder] Nothing val]
53− replace other = other
54−
55−-- |
56−-- Replace all top-level binders with case expressions.
57−--
58−desugarCases :: [Declaration] -> Either ErrorStack [Declaration]
59−desugarCases = desugarRest <=< fmap join . mapM toDecls . groupBy inSameGroup
60− where
61− desugarRest :: [Declaration] -> Either ErrorStack [Declaration]
62− desugarRest (TypeInstanceDeclaration name constraints className tys ds : rest) =
63− (:) <$> (TypeInstanceDeclaration name constraints className tys <$> desugarCases ds) <*> desugarRest rest
64− desugarRest (ValueDeclaration name nameKind bs g val : rest) = do
65− (:) <$> (ValueDeclaration name nameKind bs g <$> everywhereM' (mkM go) val) <*> desugarRest rest
66− where
67− go (Let ds val') = Let <$> desugarCases ds <*> pure val'
68− go other = return other
69− desugarRest (PositionedDeclaration pos d : ds) = do
70− (d' : ds') <- desugarRest (d : ds)
71− return (PositionedDeclaration pos d' : ds')
72− desugarRest (d : ds) = (:) d <$> desugarRest ds
73− desugarRest [] = pure []
74−
75−inSameGroup :: Declaration -> Declaration -> Bool
76−inSameGroup (ValueDeclaration ident1 _ _ _ _) (ValueDeclaration ident2 _ _ _ _) = ident1 == ident2
77−inSameGroup (PositionedDeclaration _ d1) d2 = inSameGroup d1 d2
78−inSameGroup d1 (PositionedDeclaration _ d2) = inSameGroup d1 d2
79−inSameGroup _ _ = False
80−
81−toDecls :: [Declaration] -> Either ErrorStack [Declaration]
82−toDecls [ValueDeclaration ident nameKind bs Nothing val] | all isVarBinder bs = do
83− let args = map (\(VarBinder arg) -> arg) bs
84− body = foldr (Abs . Left) val args
85− return [ValueDeclaration ident nameKind [] Nothing body]
86−toDecls ds@(ValueDeclaration ident _ bs _ _ : _) = do
87− let tuples = map toTuple ds
88− unless (all ((== length bs) . length . fst) tuples) $
89− throwError $ mkErrorStack ("Argument list lengths differ in declaration " ++ show ident) Nothing
90− return [makeCaseDeclaration ident tuples]
91−toDecls (PositionedDeclaration pos d : ds) = do
92− (d' : ds') <- rethrowWithPosition pos $ toDecls (d : ds)
93− return (PositionedDeclaration pos d' : ds')
94−toDecls ds = return ds
95−
96−isVarBinder :: Binder -> Bool
97−isVarBinder (VarBinder _) = True
98−isVarBinder _ = False
99−
100−toTuple :: Declaration -> ([Binder], (Maybe Guard, Value))
101−toTuple (ValueDeclaration _ _ bs g val) = (bs, (g, val))
102−toTuple (PositionedDeclaration _ d) = toTuple d
103−toTuple _ = error "Not a value declaration"
104−
105−makeCaseDeclaration :: Ident -> [([Binder], (Maybe Guard, Value))] -> Declaration
106−makeCaseDeclaration ident alternatives =
107− let
108− argPattern = length . fst . head $ alternatives
109− args = take argPattern $ unusedNames (ident, alternatives)
110− vars = map (Var . Qualified Nothing) args
111− binders = [ CaseAlternative bs g val | (bs, (g, val)) <- alternatives ]
112− value = foldr (Abs . Left) (Case vars binders) args
113− in
114− ValueDeclaration ident Value [] Nothing value
115−
src/Language/PureScript/Sugar/DoNotation.hsdeleted−66
@@ -1,66 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Sugar.DoNotation
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module implements the desugaring pass which replaces do-notation statements with
13−-- appropriate calls to (>>=) from the Prelude.Monad type class.
14−--
15−-----------------------------------------------------------------------------
16−
17−module Language.PureScript.Sugar.DoNotation (
18− desugarDo
19−) where
20−
21−import Data.Data
22−import Data.Generics
23−
24−import Language.PureScript.Names
25−import Language.PureScript.Scope
26−import Language.PureScript.Declarations
27−import Language.PureScript.Errors
28−
29−import qualified Language.PureScript.Constants as C
30−
31−import Control.Applicative
32−
33−-- |
34−-- Replace all @DoNotationBind@ and @DoNotationValue@ constructors with applications of the Prelude.(>>=) function,
35−-- and all @DoNotationLet@ constructors with let expressions.
36−--
37−desugarDo :: (Data d) => d -> Either ErrorStack d
38−desugarDo = everywhereM (mkM replace)
39− where
40− prelude :: ModuleName
41− prelude = ModuleName [ProperName C.prelude]
42− bind :: Value
43− bind = Var (Qualified (Just prelude) (Op (C.>>=)))
44− replace :: Value -> Either ErrorStack Value
45− replace (Do els) = go els
46− replace other = return other
47− go :: [DoNotationElement] -> Either ErrorStack Value
48− go [] = error "The impossible happened in desugarDo"
49− go [DoNotationValue val] = return val
50− go (DoNotationValue val : rest) = do
51− rest' <- go rest
52− return $ App (App bind val) (Abs (Left (Ident "_")) rest')
53− go [DoNotationBind _ _] = Left $ mkErrorStack "Bind statement cannot be the last statement in a do block" Nothing
54− go (DoNotationBind NullBinder val : rest) = go (DoNotationValue val : rest)
55− go (DoNotationBind (VarBinder ident) val : rest) = do
56− rest' <- go rest
57− return $ App (App bind val) (Abs (Left ident) rest')
58− go (DoNotationBind binder val : rest) = do
59− rest' <- go rest
60− let ident = head $ unusedNames rest'
61− return $ App (App bind val) (Abs (Left ident) (Case [Var (Qualified Nothing ident)] [CaseAlternative [binder] Nothing rest']))
62− go [DoNotationLet _] = Left $ mkErrorStack "Let statement cannot be the last statement in a do block" Nothing
63− go (DoNotationLet ds : rest) = do
64− rest' <- go rest
65− return $ Let ds rest'
66− go (PositionedDoNotationElement pos el : rest) = PositionedValue pos <$> go (el : rest)
src/Language/PureScript/Sugar/Names.hsdeleted−476
@@ -1,476 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Sugar.Names
4−-- Copyright : (c) 2013-14 Phil Freeman, (c) 2014 Gary Burgess, and other contributors
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−--
13−-----------------------------------------------------------------------------
14−
15−module Language.PureScript.Sugar.Names (
16− desugarImports
17−) where
18−
19−import Data.Data
20−import Data.Maybe (fromMaybe, isJust, mapMaybe)
21−import Data.Monoid ((<>))
22−import Data.Generics.Extras (mkS, extS, everywhereWithContextM')
23−
24−import Control.Applicative (Applicative(..), (<$>), (<*>))
25−import Control.Monad.Error
26−
27−import qualified Data.Map as M
28−
29−import Language.PureScript.Declarations
30−import Language.PureScript.Names
31−import Language.PureScript.Types
32−import Language.PureScript.Environment
33−import Language.PureScript.Errors
34−
35−-- |
36−-- The global export environment - every declaration exported from every module.
37−--
38−type ExportEnvironment = M.Map ModuleName Exports
39−
40−-- |
41−-- The exported declarations from a module.
42−--
43−data Exports = Exports
44− -- |
45− -- The types exported from each module
46− --
47− { exportedTypes :: [(ProperName, [ProperName])]
48− -- |
49− -- The classes exported from each module
50− --
51− , exportedTypeClasses :: [ProperName]
52− -- |
53− -- The values exported from each module
54− , exportedValues :: [Ident]
55− --
56− } deriving (Show)
57−
58−-- |
59−-- An imported environment for a particular module. This also contains the module's own members.
60−--
61−data ImportEnvironment = ImportEnvironment
62− -- |
63− -- Local names for types within a module mapped to to their qualified names
64− --
65− { importedTypes :: M.Map (Qualified ProperName) (Qualified ProperName)
66− -- |
67− -- Local names for data constructors within a module mapped to to their qualified names
68− --
69− , importedDataConstructors :: M.Map (Qualified ProperName) (Qualified ProperName)
70− -- |
71− -- Local names for classes within a module mapped to to their qualified names
72− --
73− , importedTypeClasses :: M.Map (Qualified ProperName) (Qualified ProperName)
74− -- |
75− -- Local names for values within a module mapped to to their qualified names
76− --
77− , importedValues :: M.Map (Qualified Ident) (Qualified Ident)
78− } deriving (Show)
79−
80−-- |
81−-- Updates the exports for a module from the global environment. If the module was not previously
82−-- present in the global environment, it is created.
83−--
84−updateExportedModule :: ExportEnvironment -> ModuleName -> (Exports -> Either ErrorStack Exports) -> Either ErrorStack ExportEnvironment
85−updateExportedModule env mn update = do
86− let exports = fromMaybe (error "Module was undefined in updateExportedModule") $ mn `M.lookup` env
87− exports' <- update exports
88− return $ M.insert mn exports' env
89−
90−-- |
91−-- Adds an empty module to an ExportEnvironment.
92−--
93−addEmptyModule :: ExportEnvironment -> ModuleName -> Either ErrorStack ExportEnvironment
94−addEmptyModule env name =
95− if name `M.member` env
96− then throwError $ mkErrorStack ("Module '" ++ show name ++ "' has been defined more than once") Nothing
97− else return $ M.insert name (Exports [] [] []) env
98−
99−-- |
100−-- Adds a type belonging to a module to the export environment.
101−--
102−addType :: ExportEnvironment -> ModuleName -> ProperName -> [ProperName] -> Either ErrorStack ExportEnvironment
103−addType env mn name dctors = updateExportedModule env mn $ \m -> do
104− types' <- addExport (exportedTypes m) (name, dctors)
105− return $ m { exportedTypes = types' }
106−
107−-- |
108−-- Adds a class to the export environment.
109−--
110−addTypeClass :: ExportEnvironment -> ModuleName -> ProperName -> Either ErrorStack ExportEnvironment
111−addTypeClass env mn name = updateExportedModule env mn $ \m -> do
112− classes <- addExport (exportedTypeClasses m) name
113− return $ m { exportedTypeClasses = classes }
114−
115−-- |
116−-- Adds a class to the export environment.
117−--
118−addValue :: ExportEnvironment -> ModuleName -> Ident -> Either ErrorStack ExportEnvironment
119−addValue env mn name = updateExportedModule env mn $ \m -> do
120− values <- addExport (exportedValues m) name
121− return $ m { exportedValues = values }
122−
123−-- |
124−-- Adds an entry to a list of exports unless it is already present, in which case an error is
125−-- returned.
126−--
127−addExport :: (Eq a, Show a) => [a] -> a -> Either ErrorStack [a]
128−addExport exports name =
129− if name `elem` exports
130− then throwError $ mkErrorStack ("Multiple definitions for '" ++ show name ++ "'") Nothing
131− else return $ name : exports
132−
133−-- |
134−-- Replaces all local names with qualified names within a set of modules.
135−--
136−desugarImports :: [Module] -> Either ErrorStack [Module]
137−desugarImports modules = do
138− unfilteredExports <- findExports modules
139− exports <- foldM filterModuleExports unfilteredExports modules
140− mapM (renameInModule' unfilteredExports exports) modules
141− where
142−
143− -- Filters the exports for a module in the global exports environment so that only explicitly
144− -- exported members remain. If the module does not explicitly export anything, everything is
145− -- exported.
146− filterModuleExports :: ExportEnvironment -> Module -> Either ErrorStack ExportEnvironment
147− filterModuleExports env (Module mn _ (Just exps)) = filterExports mn exps env
148− filterModuleExports env _ = return env
149−
150− -- Rename and check all the names within a module. We tweak the global exports environment so
151− -- the module has access to an unfiltered list of its own members.
152− renameInModule' :: ExportEnvironment -> ExportEnvironment -> Module -> Either ErrorStack Module
153− renameInModule' unfilteredExports exports m@(Module mn _ _) =
154− rethrow (strMsg ("Error in module " ++ show mn) <>) $ do
155− let env = M.update (\_ -> M.lookup mn unfilteredExports) mn exports
156− let exps = fromMaybe (error "Module is missing in renameInModule'") $ M.lookup mn exports
157− imports <- resolveImports env m
158− renameInModule imports env (elaborateExports exps m)
159−
160−-- |
161−-- Make all exports for a module explicit. This may still effect modules that have an exports list,
162−-- as it will also make all data constructor exports explicit.
163−--
164−elaborateExports :: Exports -> Module -> Module
165−elaborateExports exps (Module mn decls _) = Module mn decls (Just $
166− map (\(ctor, dctors) -> TypeRef ctor (Just dctors)) (exportedTypes exps) ++
167− map TypeClassRef (exportedTypeClasses exps) ++
168− map ValueRef (exportedValues exps))
169−
170−-- |
171−-- Replaces all local names with qualified names within a module and checks that all existing
172−-- qualified names are valid.
173−--
174−renameInModule :: ImportEnvironment -> ExportEnvironment -> Module -> Either ErrorStack Module
175−renameInModule imports exports (Module mn decls exps) =
176− Module mn <$> mapM go decls <*> pure exps
177− where
178− go :: Declaration -> Either ErrorStack Declaration
179− go (PositionedDeclaration pos d) = rethrowWithPosition pos $ PositionedDeclaration pos <$> go d
180− go (DataDeclaration name args dctors) =
181− rethrow (strMsg ("Error in data declaration " ++ show name) <>) $
182− DataDeclaration <$> pure name <*> pure args <*> updateAll dctors
183− go (DataBindingGroupDeclaration decls') =
184− DataBindingGroupDeclaration <$> mapM go decls'
185− go (TypeSynonymDeclaration name ps ty) =
186− rethrow (strMsg ("Error in type synonym " ++ show name) <>) $
187− TypeSynonymDeclaration <$> pure name <*> pure ps <*> updateType' ty
188− go (TypeClassDeclaration className args implies ds) =
189− TypeClassDeclaration className args <$> updateConstraints Nothing implies <*> mapM go ds
190− go (TypeInstanceDeclaration name cs cn ts ds) =
191− TypeInstanceDeclaration name <$> updateConstraints Nothing cs <*> updateClassName cn Nothing <*> updateType' ts <*> mapM go ds
192− go (ExternInstanceDeclaration name cs cn ts) =
193− ExternInstanceDeclaration name <$> updateConstraints Nothing cs <*> updateClassName cn Nothing <*> updateType' ts
194− go (ValueDeclaration name nameKind [] Nothing val) = do
195− val' <- everywhereWithContextM' (Nothing, []) (mkS bindFunctionArgs `extS` bindBinders) val
196− rethrow (strMsg ("Error in declaration " ++ show name) <>) $
197− ValueDeclaration name nameKind [] Nothing <$> updateAll val'
198− where
199− bindFunctionArgs :: (Maybe SourcePos, [Ident]) -> Value -> Either ErrorStack ((Maybe SourcePos, [Ident]), Value)
200− bindFunctionArgs (_, bound) v@(PositionedValue pos' _) = return ((Just pos', bound), v)
201− bindFunctionArgs (pos, bound) (Abs (Left arg) val') = return ((pos, arg : bound), Abs (Left arg) val')
202− bindFunctionArgs (pos, bound) (Let ds val') =
203− let args = mapMaybe letBoundVariable ds
204− in return ((pos, args ++ bound), Let ds val')
205− bindFunctionArgs (pos, bound) (Var name'@(Qualified Nothing ident)) | ident `notElem` bound =
206− (,) (pos, bound) <$> (Var <$> updateValueName name' pos)
207− bindFunctionArgs (pos, bound) (Var name'@(Qualified (Just _) _)) =
208− (,) (pos, bound) <$> (Var <$> updateValueName name' pos)
209− bindFunctionArgs (pos, bound) (BinaryNoParens name'@(Qualified Nothing ident) v1 v2) | ident `notElem` bound =
210− (,) (pos, bound) <$> (BinaryNoParens <$> updateValueName name' pos <*> pure v1 <*> pure v2)
211− bindFunctionArgs (pos, bound) (BinaryNoParens name'@(Qualified (Just _) _) v1 v2) =
212− (,) (pos, bound) <$> (BinaryNoParens <$> updateValueName name' pos <*> pure v1 <*> pure v2)
213− bindFunctionArgs pb other = return (pb, other)
214−
215− bindBinders :: (Maybe SourcePos, [Ident]) -> CaseAlternative -> Either ErrorStack ((Maybe SourcePos, [Ident]), CaseAlternative)
216− bindBinders (pos, bound) c@(CaseAlternative bs _ _) = return ((pos, binderNames bs ++ bound), c)
217−
218− letBoundVariable :: Declaration -> Maybe Ident
219− letBoundVariable (ValueDeclaration ident _ _ _ _) = Just ident
220− letBoundVariable (PositionedDeclaration _ d) = letBoundVariable d
221− letBoundVariable _ = Nothing
222− go (ValueDeclaration name _ _ _ _) = error $ "Binders should have been desugared in " ++ show name
223− go (ExternDeclaration fit name js ty) =
224− rethrow (strMsg ("Error in declaration " ++ show name) <>) $
225− ExternDeclaration <$> pure fit <*> pure name <*> pure js <*> updateType' ty
226− go (BindingGroupDeclaration decls') = BindingGroupDeclaration <$> mapM go' decls'
227− where
228− go' (name, nk, value) = rethrow (strMsg ("Error in declaration " ++ show name) <>) $
229− (,,) <$> pure name <*> pure nk <*> updateAll value
230− go d = updateAll d
231−
232− updateAll :: Data d => d -> Either ErrorStack d
233− updateAll = everywhereWithContextM' Nothing (mkS updateType `extS` updateValue `extS` updateBinder)
234−
235− updateValue :: Maybe SourcePos -> Value -> Either ErrorStack (Maybe SourcePos, Value)
236− updateValue _ v@(PositionedValue pos _) = return (Just pos, v)
237− updateValue pos (Constructor name) = (,) <$> pure pos <*> (Constructor <$> updateDataConstructorName name pos)
238− updateValue pos v = return (pos, v)
239−
240− updateBinder :: Maybe SourcePos -> Binder -> Either ErrorStack (Maybe SourcePos, Binder)
241− updateBinder _ v@(PositionedBinder pos _) = return (Just pos, v)
242− updateBinder pos (ConstructorBinder name b) = (,) <$> pure pos <*> (ConstructorBinder <$> updateDataConstructorName name pos <*> pure b)
243− updateBinder pos v = return (pos, v)
244−
245− updateType :: Maybe SourcePos -> Type -> Either ErrorStack (Maybe SourcePos, Type)
246− updateType pos (TypeConstructor name) = (,) <$> pure pos <*> (TypeConstructor <$> updateTypeName name pos)
247− updateType pos (SaturatedTypeSynonym name tys) = (,) <$> pure pos <*> (SaturatedTypeSynonym <$> updateTypeName name pos <*> updateType' tys)
248− updateType pos (ConstrainedType cs t) = (,) <$> pure pos <*> (ConstrainedType <$> updateConstraints pos cs <*> pure t)
249− updateType pos t = return (pos, t)
250−
251− updateType' :: Data d => d -> Either ErrorStack d
252− updateType' = everywhereWithContextM' Nothing (mkS updateType)
253−
254− updateConstraints pos = mapM (\(name, ts) -> (,) <$> updateClassName name pos <*> pure ts)
255−
256− updateTypeName = update "type" importedTypes (\mes -> isJust . (`lookup` exportedTypes mes))
257− updateClassName = update "type class" importedTypeClasses (flip elem . exportedTypeClasses)
258− updateValueName = update "value" importedValues (flip elem . exportedValues)
259− updateDataConstructorName = update "data constructor" importedDataConstructors (\mes -> flip elem (join $ snd `map` exportedTypes mes))
260−
261− -- Update names so unqualified references become qualified, and locally qualified references
262− -- are replaced with their canoncial qualified names (e.g. M.Map -> Data.Map.Map)
263− update :: (Ord a, Show a) => String
264− -> (ImportEnvironment -> M.Map (Qualified a) (Qualified a))
265− -> (Exports -> a -> Bool)
266− -> Qualified a
267− -> Maybe SourcePos
268− -> Either ErrorStack (Qualified a)
269− update t getI checkE qname@(Qualified mn' name) pos = case (M.lookup qname (getI imports), mn') of
270− (Just qname', _) -> return qname'
271− (Nothing, Just mn'') -> do
272− modExports <- getExports mn''
273− if checkE modExports name
274− then return qname
275− else positioned $ throwError $ mkErrorStack ("Unknown " ++ t ++ " '" ++ show qname ++ "'") Nothing
276− _ -> positioned $ throwError $ mkErrorStack ("Unknown " ++ t ++ " '" ++ show name ++ "'") Nothing
277− where
278− positioned err = case pos of
279− Nothing -> err
280− Just pos' -> rethrowWithPosition pos' err
281−
282− -- Gets the exports for a module, or an error message if the module doesn't exist
283− getExports :: ModuleName -> Either ErrorStack Exports
284− getExports mn' = maybe (throwError $ mkErrorStack ("Unknown module '" ++ show mn' ++ "'") Nothing) return $ M.lookup mn' exports
285−
286−-- |
287−-- Finds all exported declarations in a set of modules.
288−--
289−findExports :: [Module] -> Either ErrorStack ExportEnvironment
290−findExports = foldM addModule $ M.singleton (ModuleName [ProperName "Prim"]) primExports
291− where
292−
293− -- The exported types from the Prim module
294− primExports = Exports (mkTypeEntry `map` M.keys primTypes) [] []
295− where
296− mkTypeEntry (Qualified _ name) = (name, [])
297−
298− -- Add all of the exported declarations from a module to the global export environment
299− addModule :: ExportEnvironment -> Module -> Either ErrorStack ExportEnvironment
300− addModule env (Module mn ds _) = do
301− env' <- addEmptyModule env mn
302− rethrow (strMsg ("Error in module " ++ show mn) <>) $ foldM (addDecl mn) env' ds
303−
304− -- Add a declaration from a module to the global export environment
305− addDecl :: ModuleName -> ExportEnvironment -> Declaration -> Either ErrorStack ExportEnvironment
306− addDecl mn env (TypeClassDeclaration tcn _ _ ds) = do
307− env' <- addTypeClass env mn tcn
308− foldM (\env'' (TypeDeclaration name _) -> addValue env'' mn name) env' ds
309− addDecl mn env (DataDeclaration tn _ dcs) = addType env mn tn (map fst dcs)
310− addDecl mn env (TypeSynonymDeclaration tn _ _) = addType env mn tn []
311− addDecl mn env (ExternDataDeclaration tn _) = addType env mn tn []
312− addDecl mn env (ValueDeclaration name _ _ _ _) = addValue env mn name
313− addDecl mn env (ExternDeclaration _ name _ _) = addValue env mn name
314− addDecl mn env (PositionedDeclaration _ d) = addDecl mn env d
315− addDecl _ env _ = return env
316−
317−-- |
318−-- Filters the exports for a module to ensure only explicit exports are kept in the global exports
319−-- environment.
320−--
321−filterExports :: ModuleName -> [DeclarationRef] -> ExportEnvironment -> Either ErrorStack ExportEnvironment
322−filterExports mn exps env = do
323− let moduleExports = fromMaybe (error "Module is missing") (mn `M.lookup` env)
324− moduleExports' <- rethrow (strMsg ("Error in module " ++ show mn) <>) $ filterModule moduleExports
325− return $ M.insert mn moduleExports' env
326− where
327−
328− -- Filter the exports for the specific module
329− filterModule :: Exports -> Either ErrorStack Exports
330− filterModule exported = do
331− types' <- foldM (filterTypes $ exportedTypes exported) [] exps
332− values <- foldM (filterValues $ exportedValues exported) [] exps
333− classes <- foldM (filterClasses $ exportedTypeClasses exported) [] exps
334− return exported { exportedTypes = types', exportedTypeClasses = classes, exportedValues = values }
335−
336− -- Ensure the exported types and data constructors exist in the module and add them to the set of
337− -- exports
338− filterTypes :: [(ProperName, [ProperName])] -> [(ProperName, [ProperName])] -> DeclarationRef -> Either ErrorStack [(ProperName, [ProperName])]
339− filterTypes expTys result (PositionedDeclarationRef pos r) = rethrowWithPosition pos $ filterTypes expTys result r
340− filterTypes expTys result (TypeRef name expDcons) = do
341− dcons <- maybe (throwError $ mkErrorStack ("Cannot export undefined type '" ++ show name ++ "'") Nothing) return $ name `lookup` expTys
342− dcons' <- maybe (return dcons) (foldM (filterDcons name dcons) []) expDcons
343− return $ (name, dcons') : result
344− filterTypes _ result _ = return result
345−
346− -- Ensure the exported data constructors exists for a type and add them to the list of exports
347− filterDcons :: ProperName -> [ProperName] -> [ProperName] -> ProperName -> Either ErrorStack [ProperName]
348− filterDcons tcon exps' result name =
349− if name `elem` exps'
350− then return $ name : result
351− else throwError $ mkErrorStack ("Cannot export undefined data constructor '" ++ show name ++ "' for type '" ++ show tcon ++ "'") Nothing
352−
353− -- Ensure the exported classes exist in the module and add them to the set of exports
354− filterClasses :: [ProperName] -> [ProperName] -> DeclarationRef -> Either ErrorStack [ProperName]
355− filterClasses exps' result (PositionedDeclarationRef pos r) = rethrowWithPosition pos $ filterClasses exps' result r
356− filterClasses exps' result (TypeClassRef name) =
357− if name `elem` exps'
358− then return $ name : result
359− else throwError $ mkErrorStack ("Cannot export undefined type class '" ++ show name ++ "'") Nothing
360− filterClasses _ result _ = return result
361−
362− -- Ensure the exported values exist in the module and add them to the set of exports
363− filterValues :: [Ident] -> [Ident] -> DeclarationRef -> Either ErrorStack [Ident]
364− filterValues exps' result (PositionedDeclarationRef pos r) = rethrowWithPosition pos $ filterValues exps' result r
365− filterValues exps' result (ValueRef name) =
366− if name `elem` exps'
367− then return $ name : result
368− else throwError $ mkErrorStack ("Cannot export undefined value '" ++ show name ++ "'") Nothing
369− filterValues _ result _ = return result
370−
371−-- |
372−-- Type representing a set of declarations being explicitly imported from a module
373−--
374−type ExplicitImports = [DeclarationRef]
375−
376−-- |
377−-- Finds the imports within a module, mapping the imported module name to an optional set of
378−-- explicitly imported declarations.
379−--
380−findImports :: [Declaration] -> M.Map ModuleName (Maybe SourcePos, Maybe ExplicitImports, Maybe ModuleName)
381−findImports = foldl (findImports' Nothing) M.empty
382− where
383− findImports' pos result (ImportDeclaration mn expl qual) = M.insert mn (pos, expl, qual) result
384− findImports' _ result (PositionedDeclaration pos d) = findImports' (Just pos) result d
385− findImports' _ result _ = result
386−
387−-- |
388−-- Constructs a local environment for a module.
389−--
390−resolveImports :: ExportEnvironment -> Module -> Either ErrorStack ImportEnvironment
391−resolveImports env (Module currentModule decls _) =
392− foldM resolveImport' (ImportEnvironment M.empty M.empty M.empty M.empty) (M.toList scope)
393− where
394−
395− -- A Map from module name to the source position for the import, the list of imports from that
396− -- module (where Nothing indicates everything is to be imported), and optionally a qualified name
397− -- for the module
398− scope :: M.Map ModuleName (Maybe SourcePos, Maybe ExplicitImports, Maybe ModuleName)
399− scope = M.insert currentModule (Nothing, Nothing, Nothing) (findImports decls)
400−
401− resolveImport' :: ImportEnvironment -> (ModuleName, (Maybe SourcePos, Maybe ExplicitImports, Maybe ModuleName)) -> Either ErrorStack ImportEnvironment
402− resolveImport' imp (mn, (pos, explImports, impQual)) = do
403− modExports <- positioned $ maybe (throwError $ mkErrorStack ("Cannot import unknown module '" ++ show mn ++ "'") Nothing) return $ mn `M.lookup` env
404− positioned $ resolveImport currentModule mn modExports imp impQual explImports
405− where
406− positioned err = case pos of
407− Nothing -> err
408− Just pos' -> rethrowWithPosition pos' err
409−
410−-- |
411−-- Extends the local environment for a module by resolving an import of another module.
412−--
413−resolveImport :: ModuleName -> ModuleName -> Exports -> ImportEnvironment -> Maybe ModuleName -> Maybe ExplicitImports-> Either ErrorStack ImportEnvironment
414−resolveImport currentModule importModule exps imps impQual = maybe importAll (foldM importExplicit imps)
415− where
416−
417− -- Import everything from a module
418− importAll :: Either ErrorStack ImportEnvironment
419− importAll = do
420− imp' <- foldM (\m (name, dctors) -> importExplicit m (TypeRef name (Just dctors))) imps (exportedTypes exps)
421− imp'' <- foldM (\m name -> importExplicit m (ValueRef name)) imp' (exportedValues exps)
422− foldM (\m name -> importExplicit m (TypeClassRef name)) imp'' (exportedTypeClasses exps)
423−
424− -- Import something explicitly
425− importExplicit :: ImportEnvironment -> DeclarationRef -> Either ErrorStack ImportEnvironment
426− importExplicit imp (PositionedDeclarationRef pos r) = rethrowWithPosition pos $ importExplicit imp r
427− importExplicit imp (ValueRef name) = do
428− _ <- checkImportExists "value" values name
429− values' <- updateImports (importedValues imp) name
430− return $ imp { importedValues = values' }
431− importExplicit imp (TypeRef name dctors) = do
432− _ <- checkImportExists "type" availableTypes name
433− types' <- updateImports (importedTypes imp) name
434− let allDctors = allExportedDataConstructors name
435− dctors' <- maybe (return allDctors) (mapM $ checkDctorExists allDctors) dctors
436− dctors'' <- foldM updateImports (importedDataConstructors imp) dctors'
437− return $ imp { importedTypes = types', importedDataConstructors = dctors'' }
438− importExplicit imp (TypeClassRef name) = do
439− _ <- checkImportExists "type class" classes name
440− typeClasses' <- updateImports (importedTypeClasses imp) name
441− return $ imp { importedTypeClasses = typeClasses' }
442− importExplicit _ _ = error "Invalid argument to importExplicit"
443−
444− -- Find all exported data constructors for a given type
445− allExportedDataConstructors :: ProperName -> [ProperName]
446− allExportedDataConstructors name = fromMaybe [] $ name `lookup` exportedTypes exps
447−
448− -- Add something to the ImportEnvironment if it does not already exist there
449− updateImports :: (Ord a, Show a) => M.Map (Qualified a) (Qualified a) -> a -> Either ErrorStack (M.Map (Qualified a) (Qualified a))
450− updateImports m name = case M.lookup (Qualified impQual name) m of
451− Nothing -> return $ M.insert (Qualified impQual name) (Qualified (Just importModule) name) m
452− Just (Qualified Nothing _) -> error "Invalid state in updateImports"
453− Just x@(Qualified (Just mn) _) -> throwError $ mkErrorStack err Nothing
454− where
455− err = if mn == currentModule || importModule == currentModule
456− then "Definition '" ++ show name ++ "' conflicts with import '" ++ show (Qualified (Just importModule) name) ++ "'"
457− else "Conflicting imports for '" ++ show name ++ "': '" ++ show x ++ "', '" ++ show (Qualified (Just importModule) name) ++ "'"
458−
459− -- The available values, types, and classes in the module being imported
460− values = exportedValues exps
461− availableTypes = fst `map` exportedTypes exps
462− classes = exportedTypeClasses exps
463−
464− -- Ensure that an explicitly imported data constructor exists for the type it is being imported
465− -- from
466− checkDctorExists :: [ProperName] -> ProperName -> Either ErrorStack ProperName
467− checkDctorExists = checkImportExists "data constructor"
468−
469− -- Check that an explicitly imported item exists in the module it is being imported from
470− checkImportExists :: (Eq a, Show a) => String -> [a] -> a -> Either ErrorStack a
471− checkImportExists t exports item =
472− if item `elem` exports
473− then return item
474− else throwError $ mkErrorStack ("Cannot import unknown " ++ t ++ " '" ++ show item ++ "' from '" ++ show importModule ++ "'") Nothing
475−
476−
src/Language/PureScript/Sugar/Operators.hsdeleted−150
@@ -1,150 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Sugar.Operators
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module implements the desugaring pass which reapplies binary operators based
13−-- on their fixity data and removes explicit parentheses.
14−--
15−-- The value parser ignores fixity data when parsing binary operator applications, so
16−-- it is necessary to reorder them here.
17−--
18−-----------------------------------------------------------------------------
19−
20−{-# LANGUAGE Rank2Types, FlexibleContexts #-}
21−
22−module Language.PureScript.Sugar.Operators (
23− rebracket,
24− removeSignedLiterals
25−) where
26−
27−import Language.PureScript.Names
28−import Language.PureScript.Declarations
29−import Language.PureScript.Errors
30−
31−import Control.Applicative
32−import Control.Monad.State
33−import Control.Monad.Error.Class
34−
35−import Data.Monoid ((<>))
36−import Data.Function (on)
37−import Data.Functor.Identity
38−import Data.List (groupBy, sortBy)
39−
40−import qualified Data.Data as D
41−import qualified Data.Generics as G
42−import qualified Data.Generics.Extras as G
43−
44−import qualified Text.Parsec as P
45−import qualified Text.Parsec.Pos as P
46−import qualified Text.Parsec.Expr as P
47−
48−import qualified Language.PureScript.Constants as C
49−
50−-- |
51−-- Remove explicit parentheses and reorder binary operator applications
52−--
53−rebracket :: [Module] -> Either ErrorStack [Module]
54−rebracket ms = do
55− let fixities = concatMap collectFixities ms
56− ensureNoDuplicates $ map (\(i, pos, _) -> (i, pos)) fixities
57− let opTable = customOperatorTable $ map (\(i, _, f) -> (i, f)) fixities
58− mapM (rebracketModule opTable) ms
59−
60−removeSignedLiterals :: (D.Data d) => d -> d
61−removeSignedLiterals = G.everywhere (G.mkT go)
62− where
63− go (UnaryMinus (NumericLiteral (Left n))) = NumericLiteral (Left $ negate n)
64− go (UnaryMinus (NumericLiteral (Right n))) = NumericLiteral (Right $ negate n)
65− go (UnaryMinus val) = App (Var (Qualified (Just (ModuleName [ProperName C.prelude])) (Ident C.negate))) val
66− go other = other
67−
68−rebracketModule :: [[(Qualified Ident, Value -> Value -> Value, Associativity)]] -> Module -> Either ErrorStack Module
69−rebracketModule opTable (Module mn ds exts) = Module mn <$> (removeParens <$> G.everywhereM' (G.mkM (matchOperators opTable)) ds) <*> pure exts
70−
71−removeParens :: (D.Data d) => d -> d
72−removeParens = G.everywhere (G.mkT go)
73− where
74− go (Parens val) = val
75− go val = val
76−
77−collectFixities :: Module -> [(Qualified Ident, SourcePos, Fixity)]
78−collectFixities (Module moduleName ds _) = concatMap collect ds
79− where
80− collect :: Declaration -> [(Qualified Ident, SourcePos, Fixity)]
81− collect (PositionedDeclaration pos (FixityDeclaration fixity name)) = [(Qualified (Just moduleName) (Op name), pos, fixity)]
82− collect FixityDeclaration{} = error "Fixity without srcpos info"
83− collect _ = []
84−
85−ensureNoDuplicates :: [(Qualified Ident, SourcePos)] -> Either ErrorStack ()
86−ensureNoDuplicates m = go $ sortBy (compare `on` fst) m
87− where
88− go [] = return ()
89− go [_] = return ()
90− go ((x@(Qualified (Just mn) name), _) : (y, pos) : _) | x == y =
91− rethrow (strMsg ("Error in module " ++ show mn) <>) $
92− rethrowWithPosition pos $
93− throwError $ mkErrorStack ("Redefined fixity for " ++ show name) Nothing
94− go (_ : rest) = go rest
95−
96−customOperatorTable :: [(Qualified Ident, Fixity)] -> [[(Qualified Ident, Value -> Value -> Value, Associativity)]]
97−customOperatorTable fixities =
98− let
99− applyUserOp ident t1 = App (App (Var ident) t1)
100− userOps = map (\(name, Fixity a p) -> (name, applyUserOp name, p, a)) fixities
101− sorted = sortBy (flip compare `on` (\(_, _, p, _) -> p)) userOps
102− groups = groupBy ((==) `on` (\(_, _, p, _) -> p)) sorted
103− in
104− map (map (\(name, f, _, a) -> (name, f, a))) groups
105−
106−type Chain = [Either Value (Qualified Ident)]
107−
108−matchOperators :: [[(Qualified Ident, Value -> Value -> Value, Associativity)]] -> Value -> Either ErrorStack Value
109−matchOperators ops = parseChains
110− where
111− parseChains :: Value -> Either ErrorStack Value
112− parseChains b@BinaryNoParens{} = bracketChain (extendChain b)
113− parseChains other = return other
114− extendChain :: Value -> Chain
115− extendChain (BinaryNoParens name l r) = Left l : Right name : extendChain r
116− extendChain other = [Left other]
117− bracketChain :: Chain -> Either ErrorStack Value
118− bracketChain = either (Left . (`mkErrorStack` Nothing) . show) Right . P.parse (P.buildExpressionParser opTable parseValue <* P.eof) "operator expression"
119− opTable = [P.Infix (P.try (parseTicks >>= \ident -> return (\t1 t2 -> App (App (Var ident) t1) t2))) P.AssocLeft]
120− : map (map (\(name, f, a) -> P.Infix (P.try (matchOp name) >> return f) (toAssoc a))) ops
121− ++ [[ P.Infix (P.try (parseOp >>= \ident -> return (\t1 t2 -> App (App (Var ident) t1) t2))) P.AssocLeft ]]
122−
123−toAssoc :: Associativity -> P.Assoc
124−toAssoc Infixl = P.AssocLeft
125−toAssoc Infixr = P.AssocRight
126−toAssoc Infix = P.AssocNone
127−
128−token :: (P.Stream s Identity t, Show t) => (t -> Maybe a) -> P.Parsec s u a
129−token = P.token show (const (P.initialPos ""))
130−
131−parseValue :: P.Parsec Chain () Value
132−parseValue = token (either Just (const Nothing)) P.<?> "expression"
133−
134−parseOp :: P.Parsec Chain () (Qualified Ident)
135−parseOp = token (either (const Nothing) fromOp) P.<?> "operator"
136− where
137− fromOp q@(Qualified _ (Op _)) = Just q
138− fromOp _ = Nothing
139−
140−parseTicks :: P.Parsec Chain () (Qualified Ident)
141−parseTicks = token (either (const Nothing) fromOp) P.<?> "infix function"
142− where
143− fromOp q@(Qualified _ (Ident _)) = Just q
144− fromOp _ = Nothing
145−
146−matchOp :: Qualified Ident -> P.Parsec Chain () ()
147−matchOp op = do
148− ident <- parseOp
149− guard $ ident == op
150−
src/Language/PureScript/Sugar/TypeClasses.hsdeleted−194
@@ -1,194 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Sugar.TypeClasses
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module implements the desugaring pass which creates type synonyms for type class dictionaries
13−-- and dictionary expressions for type class instances.
14−--
15−-----------------------------------------------------------------------------
16−
17−module Language.PureScript.Sugar.TypeClasses (
18− desugarTypeClasses
19−) where
20−
21−import Language.PureScript.Declarations
22−import Language.PureScript.Names
23−import Language.PureScript.Types
24−import Language.PureScript.CodeGen.JS.AST
25−import Language.PureScript.Sugar.CaseDeclarations
26−import Language.PureScript.Environment
27−import Language.PureScript.Errors
28−import Language.PureScript.CodeGen.Common (identToJs)
29−
30−import qualified Language.PureScript.Constants as C
31−
32−import Control.Applicative
33−import Control.Monad.State
34−import Control.Arrow (first, second)
35−import Data.Maybe (catMaybes)
36−
37−import qualified Data.Map as M
38−
39−type MemberMap = M.Map (ModuleName, ProperName) Declaration
40−
41−type Desugar = StateT MemberMap (Either ErrorStack)
42−
43−-- |
44−-- Add type synonym declarations for type class dictionary types, and value declarations for type class
45−-- instance dictionary expressions.
46−--
47−desugarTypeClasses :: [Module] -> Either ErrorStack [Module]
48−desugarTypeClasses = flip evalStateT M.empty . mapM desugarModule
49−
50−desugarModule :: Module -> Desugar Module
51−desugarModule (Module name decls (Just exps)) = do
52− (newExpss, declss) <- unzip <$> mapM (desugarDecl name) decls
53− return $ Module name (concat declss) $ Just (exps ++ catMaybes newExpss)
54−desugarModule _ = error "Exports should have been elaborated in name desugaring"
55−
56−-- |
57−-- Desugar type class and type class instance declarations
58−--
59−-- Type classes become type synonyms for their dictionaries, and type instances become dictionary declarations.
60−-- Additional values are generated to access individual members of a dictionary, with the appropriate type.
61−--
62−-- E.g. the following
63−--
64−-- module Test where
65−--
66−-- class Foo a where
67−-- foo :: a -> a
68−--
69−-- instance fooString :: Foo String where
70−-- foo s = s ++ s
71−--
72−-- instance fooArray :: (Foo a) => Foo [a] where
73−-- foo = map foo
74−--
75−-- {- Superclasses -}
76−--
77−-- class (Foo a) <= Sub a where
78−-- sub :: a
79−--
80−-- instance subString :: Sub String where
81−-- sub = ""
82−--
83−-- becomes
84−--
85−-- type Foo a = { foo :: a -> a }
86−--
87−-- foreign import foo "function foo(dict) {\
88−-- \ return dict.foo;\
89−-- \}" :: forall a. (Foo a) => a -> a
90−--
91−-- fooString :: {} -> Foo String
92−-- fooString _ = { foo: \s -> s ++ s }
93−--
94−-- fooArray :: forall a. (Foo a) => Foo [a]
95−-- fooArray = { foo: map foo }
96−--
97−-- {- Superclasses -}
98−--
99−-- ...
100−--
101−-- subString :: {} -> { __superclasses :: [{}], sub :: String }
102−-- subString _ = {
103−-- __superclasses: [\<dictionary placeholder to be inserted during type checking\>]
104−-- sub: ""
105−-- }
106−--
107−-- Here, the __superclasses property is not typechecked (it is not even well-typed, since its
108−-- entries might be dictionaries of different types).
109−--
110−desugarDecl :: ModuleName -> Declaration -> Desugar (Maybe DeclarationRef, [Declaration])
111−desugarDecl mn d@(TypeClassDeclaration name args _ members) = do
112− modify (M.insert (mn, name) d)
113− return $ (Nothing, d : typeClassDictionaryDeclaration name args members : map (typeClassMemberToDictionaryAccessor mn name args) members)
114−desugarDecl mn d@(TypeInstanceDeclaration name deps className ty members) = do
115− desugared <- lift $ desugarCases members
116− dictDecl <- typeInstanceDictionaryDeclaration name mn deps className ty desugared
117− return $ (Just $ TypeInstanceRef name, [d, dictDecl])
118−desugarDecl mn (PositionedDeclaration pos d) = do
119− (dr, ds) <- desugarDecl mn d
120− return (dr, map (PositionedDeclaration pos) ds)
121−desugarDecl _ other = return (Nothing, [other])
122−
123−memberToNameAndType :: Declaration -> (Ident, Type)
124−memberToNameAndType (TypeDeclaration ident ty) = (ident, ty)
125−memberToNameAndType (PositionedDeclaration _ d) = memberToNameAndType d
126−memberToNameAndType _ = error "Invalid declaration in type class definition"
127−
128−identToProperty :: Ident -> String
129−identToProperty (Ident name) = name
130−identToProperty (Op op) = op
131−
132−typeClassDictionaryDeclaration :: ProperName -> [String] -> [Declaration] -> Declaration
133−typeClassDictionaryDeclaration name args members =
134− TypeSynonymDeclaration name args (TypeApp tyObject $ rowFromList (map (first identToProperty . memberToNameAndType) members, REmpty))
135−
136−typeClassMemberToDictionaryAccessor :: ModuleName -> ProperName -> [String] -> Declaration -> Declaration
137−typeClassMemberToDictionaryAccessor mn name args (TypeDeclaration ident ty) =
138− ExternDeclaration TypeClassAccessorImport ident
139− (Just (JSFunction (Just $ identToJs ident) ["dict"] (JSBlock [JSReturn (JSIndexer (JSStringLiteral (identToProperty ident)) (JSVar "dict"))])))
140− (quantify (ConstrainedType [(Qualified (Just mn) name, map TypeVar args)] ty))
141−typeClassMemberToDictionaryAccessor mn name args (PositionedDeclaration pos d) =
142− PositionedDeclaration pos $ typeClassMemberToDictionaryAccessor mn name args d
143−typeClassMemberToDictionaryAccessor _ _ _ _ = error "Invalid declaration in type class definition"
144−
145−typeInstanceDictionaryDeclaration :: Ident -> ModuleName -> [(Qualified ProperName, [Type])] -> Qualified ProperName -> [Type] -> [Declaration] -> Desugar Declaration
146−typeInstanceDictionaryDeclaration name mn deps className tys decls = do
147− m <- get
148−
149− -- Lookup the type arguments and member types for the type class
150− (TypeClassDeclaration _ args implies tyDecls) <- lift $
151− maybe (Left $ mkErrorStack ("Type class " ++ show className ++ " is undefined") Nothing) Right $
152− M.lookup (qualify mn className) m
153− let instanceTys = map memberToNameAndType tyDecls
154−
155− let superclasses = TypedValue False (ArrayLiteral [ TypeClassDictionary False (superclass, tyArgs) Nothing
156− | (superclass, suTyArgs) <- implies
157− , let tyArgs = map (replaceAllTypeVars (zip args tys)) suTyArgs
158− ]) (TypeApp tyArray unit)
159−
160− -- Replace the type arguments with the appropriate types in the member types
161− let memberTypes = map (second (replaceAllTypeVars (zip args tys))) instanceTys
162− -- Create values for the type instance members
163− memberNames <- map (first identToProperty) <$> mapM (memberToNameAndValue memberTypes) decls
164− -- Create the type of the dictionary
165− -- The type is an object type, but depending on type instance dependencies, may be constrained.
166− -- The dictionary itself is an object literal, but for reasons related to recursion, the dictionary
167− -- must be guarded by at least one function abstraction. For that reason, if the dictionary has no
168− -- dependencies, we introduce an unnamed function parameter.
169− let (memberTypes', memberNames') =
170− if null implies
171− then (memberTypes, memberNames)
172− else ((Ident C.__superclasses, TypeApp tyArray unit) : memberTypes, (C.__superclasses, superclasses) : memberNames)
173− dictTy = TypeApp tyObject (rowFromList (map (first identToProperty) memberTypes', REmpty))
174− constrainedTy = quantify (if null deps then function unit dictTy else ConstrainedType deps dictTy)
175− dict = if null deps then Abs (Left (Ident "_")) (ObjectLiteral memberNames') else ObjectLiteral memberNames'
176− return $ ValueDeclaration name TypeInstanceDictionaryValue [] Nothing (TypedValue True dict constrainedTy)
177− where
178− unit :: Type
179− unit = TypeApp tyObject REmpty
180−
181− memberToNameAndValue :: [(Ident, Type)] -> Declaration -> Desugar (Ident, Value)
182− memberToNameAndValue tys' d@(ValueDeclaration ident _ _ _ _) = do
183− _ <- lift . maybe (Left $ mkErrorStack "Type class member type not found" Nothing) Right $ lookup ident tys'
184− let memberValue = typeInstanceDictionaryEntryValue d
185− return (ident, memberValue)
186− memberToNameAndValue tys' (PositionedDeclaration pos d) = do
187− (ident, val) <- memberToNameAndValue tys' d
188− return (ident, PositionedValue pos val)
189− memberToNameAndValue _ _ = error "Invalid declaration in type instance definition"
190−
191− typeInstanceDictionaryEntryValue :: Declaration -> Value
192− typeInstanceDictionaryEntryValue (ValueDeclaration _ _ [] _ val) = val
193− typeInstanceDictionaryEntryValue (PositionedDeclaration pos d) = PositionedValue pos (typeInstanceDictionaryEntryValue d)
194− typeInstanceDictionaryEntryValue _ = error "Invalid declaration in type instance definition"
src/Language/PureScript/Sugar/TypeDeclarations.hsdeleted−67
@@ -1,67 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Sugar.TypeDeclarations
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module implements the desugaring pass which replaces top-level type declarations with
13−-- type annotations on the corresponding expression.
14−--
15−-----------------------------------------------------------------------------
16−
17−module Language.PureScript.Sugar.TypeDeclarations (
18− desugarTypeDeclarations,
19− desugarTypeDeclarationsModule
20−) where
21−
22−import Data.Generics (mkM)
23−import Data.Generics.Extras
24−import Data.Monoid ((<>))
25−
26−import Control.Applicative
27−import Control.Monad.Error.Class
28−import Control.Monad (forM)
29−
30−import Language.PureScript.Declarations
31−import Language.PureScript.Names
32−import Language.PureScript.Environment
33−import Language.PureScript.Errors
34−
35−-- |
36−-- Replace all top level type declarations in a module with type annotations
37−--
38−desugarTypeDeclarationsModule :: [Module] -> Either ErrorStack [Module]
39−desugarTypeDeclarationsModule ms = forM ms $ \(Module name ds exps) ->
40− rethrow (strMsg ("Error in module " ++ show name) <>) $
41− Module name <$> desugarTypeDeclarations ds <*> pure exps
42−
43−-- |
44−-- Replace all top level type declarations with type annotations
45−--
46−desugarTypeDeclarations :: [Declaration] -> Either ErrorStack [Declaration]
47−desugarTypeDeclarations (PositionedDeclaration pos d : ds) = do
48− (d' : ds') <- rethrowWithPosition pos $ desugarTypeDeclarations (d : ds)
49− return (PositionedDeclaration pos d' : ds')
50−desugarTypeDeclarations (TypeDeclaration name ty : d : rest) = do
51− (_, nameKind, val) <- fromValueDeclaration d
52− desugarTypeDeclarations (ValueDeclaration name nameKind [] Nothing (TypedValue True val ty) : rest)
53− where
54− fromValueDeclaration :: Declaration -> Either ErrorStack (Ident, NameKind, Value)
55− fromValueDeclaration (ValueDeclaration name' nameKind [] Nothing val) | name == name' = return (name', nameKind, val)
56− fromValueDeclaration (PositionedDeclaration pos d') = do
57− (ident, nameKind, val) <- rethrowWithPosition pos $ fromValueDeclaration d'
58− return (ident, nameKind, PositionedValue pos val)
59− fromValueDeclaration _ = throwError $ mkErrorStack ("Orphan type declaration for " ++ show name) Nothing
60−desugarTypeDeclarations (TypeDeclaration name _ : []) = throwError $ mkErrorStack ("Orphan type declaration for " ++ show name) Nothing
61−desugarTypeDeclarations (ValueDeclaration name nameKind bs g val : rest) = do
62− (:) <$> (ValueDeclaration name nameKind bs g <$> everywhereM' (mkM go) val) <*> desugarTypeDeclarations rest
63− where
64− go (Let ds val') = Let <$> desugarTypeDeclarations ds <*> pure val'
65− go other = return other
66−desugarTypeDeclarations (d:ds) = (:) d <$> desugarTypeDeclarations ds
67−desugarTypeDeclarations [] = return []
src/Language/PureScript/TypeChecker.hsdeleted−204
@@ -1,204 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.TypeChecker
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- The top-level type checker, which checks all declarations in a module.
13−--
14−-----------------------------------------------------------------------------
15−
16−{-# LANGUAGE FlexibleInstances #-}
17−
18−module Language.PureScript.TypeChecker (
19− module T,
20− typeCheckAll
21−) where
22−
23−import Language.PureScript.TypeChecker.Monad as T
24−import Language.PureScript.TypeChecker.Kinds as T
25−import Language.PureScript.TypeChecker.Types as T
26−import Language.PureScript.TypeChecker.Synonyms as T
27−
28−import Data.Maybe
29−import Data.Monoid ((<>))
30−import qualified Data.Map as M
31−import Control.Monad.State
32−import Control.Monad.Error
33−
34−import Language.PureScript.Types
35−import Language.PureScript.Names
36−import Language.PureScript.Kinds
37−import Language.PureScript.Declarations
38−import Language.PureScript.TypeClassDictionaries
39−import Language.PureScript.Environment
40−import Language.PureScript.Errors
41−
42−addDataType :: ModuleName -> ProperName -> [String] -> [(ProperName, [Type])] -> Kind -> Check ()
43−addDataType moduleName name args dctors ctorKind = do
44− env <- getEnv
45− putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (ctorKind, DataType args dctors) (types env) }
46− forM_ dctors $ \(dctor, tys) ->
47− rethrow (strMsg ("Error in data constructor " ++ show dctor) <>) $
48− addDataConstructor moduleName name args dctor tys
49−
50−addDataConstructor :: ModuleName -> ProperName -> [String] -> ProperName -> [Type] -> Check ()
51−addDataConstructor moduleName name args dctor tys = do
52− env <- getEnv
53− let retTy = foldl TypeApp (TypeConstructor (Qualified (Just moduleName) name)) (map TypeVar args)
54− let dctorTy = foldr function retTy tys
55− let polyType = mkForAll args dctorTy
56− putEnv $ env { dataConstructors = M.insert (Qualified (Just moduleName) dctor) (name, polyType) (dataConstructors env) }
57−
58−addTypeSynonym :: ModuleName -> ProperName -> [String] -> Type -> Kind -> Check ()
59−addTypeSynonym moduleName name args ty kind = do
60− env <- getEnv
61− putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, TypeSynonym) (types env)
62− , typeSynonyms = M.insert (Qualified (Just moduleName) name) (args, ty) (typeSynonyms env) }
63−
64−valueIsNotDefined :: ModuleName -> Ident -> Check ()
65−valueIsNotDefined moduleName name = do
66− env <- getEnv
67− case M.lookup (moduleName, name) (names env) of
68− Just _ -> throwError . strMsg $ show name ++ " is already defined"
69− Nothing -> return ()
70−
71−addValue :: ModuleName -> Ident -> Type -> NameKind -> Check ()
72−addValue moduleName name ty nameKind = do
73− env <- getEnv
74− putEnv (env { names = M.insert (moduleName, name) (ty, nameKind) (names env) })
75−
76−addTypeClass :: ModuleName -> ProperName -> [String] -> [(Qualified ProperName, [Type])] -> [Declaration] -> Check ()
77−addTypeClass moduleName pn args implies ds =
78− let members = map (\(TypeDeclaration ident ty) -> (ident, ty)) ds in
79− modify $ \st -> st { checkEnv = (checkEnv st) { typeClasses = M.insert (Qualified (Just moduleName) pn) (args, members, implies) (typeClasses . checkEnv $ st) } }
80−
81−addTypeClassDictionaries :: [TypeClassDictionaryInScope] -> Check ()
82−addTypeClassDictionaries entries =
83− modify $ \st -> st { checkEnv = (checkEnv st) { typeClassDictionaries = entries ++ (typeClassDictionaries . checkEnv $ st) } }
84−
85−checkTypeClassInstance :: ModuleName -> Type -> Check ()
86−checkTypeClassInstance _ (TypeVar _) = return ()
87−checkTypeClassInstance _ (TypeConstructor ctor) = do
88− env <- getEnv
89− when (ctor `M.member` typeSynonyms env) . throwError . strMsg $ "Type synonym instances are disallowed"
90− return ()
91−checkTypeClassInstance m (TypeApp t1 t2) = checkTypeClassInstance m t1 >> checkTypeClassInstance m t2
92−checkTypeClassInstance _ ty = throwError $ mkErrorStack "Type class instance head is invalid." (Just (TypeError ty))
93−
94−-- |
95−-- Type check all declarations in a module
96−--
97−-- At this point, many declarations will have been desugared, but it is still necessary to
98−--
99−-- * Kind-check all types and add them to the @Environment@
100−--
101−-- * Type-check all values and add them to the @Environment@
102−--
103−-- * Bring type class instances into scope
104−--
105−-- * Process module imports
106−--
107−typeCheckAll :: Maybe ModuleName -> ModuleName -> [Declaration] -> Check [Declaration]
108−typeCheckAll _ _ [] = return []
109−typeCheckAll mainModuleName moduleName (d@(DataDeclaration name args dctors) : rest) = do
110− rethrow (strMsg ("Error in type constructor " ++ show name) <>) $ do
111− ctorKind <- kindsOf True moduleName name args (concatMap snd dctors)
112− addDataType moduleName name args dctors ctorKind
113− ds <- typeCheckAll mainModuleName moduleName rest
114− return $ d : ds
115−typeCheckAll mainModuleName moduleName (d@(DataBindingGroupDeclaration tys) : rest) = do
116− rethrow (strMsg "Error in data binding group" <>) $ do
117− let syns = mapMaybe toTypeSynonym tys
118− let dataDecls = mapMaybe toDataDecl tys
119− (syn_ks, data_ks) <- kindsOfAll moduleName syns (map (\(name, args, dctors) -> (name, args, concatMap snd dctors)) dataDecls)
120− forM_ (zip dataDecls data_ks) $ \((name, args, dctors), ctorKind) ->
121− addDataType moduleName name args dctors ctorKind
122− forM_ (zip syns syn_ks) $ \((name, args, ty), kind) ->
123− addTypeSynonym moduleName name args ty kind
124− ds <- typeCheckAll mainModuleName moduleName rest
125− return $ d : ds
126− where
127− toTypeSynonym (TypeSynonymDeclaration nm args ty) = Just (nm, args, ty)
128− toTypeSynonym (PositionedDeclaration _ d') = toTypeSynonym d'
129− toTypeSynonym _ = Nothing
130− toDataDecl (DataDeclaration nm args dctors) = Just (nm, args, dctors)
131− toDataDecl (PositionedDeclaration _ d') = toDataDecl d'
132− toDataDecl _ = Nothing
133−typeCheckAll mainModuleName moduleName (d@(TypeSynonymDeclaration name args ty) : rest) = do
134− rethrow (strMsg ("Error in type synonym " ++ show name) <>) $ do
135− kind <- kindsOf False moduleName name args [ty]
136− addTypeSynonym moduleName name args ty kind
137− ds <- typeCheckAll mainModuleName moduleName rest
138− return $ d : ds
139−typeCheckAll _ _ (TypeDeclaration _ _ : _) = error "Type declarations should have been removed"
140−typeCheckAll mainModuleName moduleName (ValueDeclaration name nameKind [] Nothing val : rest) = do
141− d <- rethrow (strMsg ("Error in declaration " ++ show name) <>) $ do
142− valueIsNotDefined moduleName name
143− [(_, (val', ty))] <- typesOf mainModuleName moduleName [(name, val)]
144− addValue moduleName name ty nameKind
145− return $ ValueDeclaration name nameKind [] Nothing val'
146− ds <- typeCheckAll mainModuleName moduleName rest
147− return $ d : ds
148−typeCheckAll _ _ (ValueDeclaration{} : _) = error "Binders were not desugared"
149−typeCheckAll mainModuleName moduleName (BindingGroupDeclaration vals : rest) = do
150− d <- rethrow (strMsg ("Error in binding group " ++ show (map (\(ident, _, _) -> ident) vals)) <>) $ do
151− forM_ (map (\(ident, _, _) -> ident) vals) $ \name ->
152− valueIsNotDefined moduleName name
153− tys <- typesOf mainModuleName moduleName $ map (\(ident, _, ty) -> (ident, ty)) vals
154− vals' <- forM (zipWith (\(name, nameKind, _) (_, (val, ty)) -> (name, val, nameKind, ty)) vals tys) $ \(name, val, nameKind, ty) -> do
155− addValue moduleName name ty nameKind
156− return (name, nameKind, val)
157− return $ BindingGroupDeclaration vals'
158− ds <- typeCheckAll mainModuleName moduleName rest
159− return $ d : ds
160−typeCheckAll mainModuleName moduleName (d@(ExternDataDeclaration name kind) : rest) = do
161− env <- getEnv
162− putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, ExternData) (types env) }
163− ds <- typeCheckAll mainModuleName moduleName rest
164− return $ d : ds
165−typeCheckAll mainModuleName moduleName (d@(ExternDeclaration importTy name _ ty) : rest) = do
166− rethrow (strMsg ("Error in foreign import declaration " ++ show name) <>) $ do
167− env <- getEnv
168− kind <- kindOf moduleName ty
169− guardWith (strMsg "Expected kind *") $ kind == Star
170− case M.lookup (moduleName, name) (names env) of
171− Just _ -> throwError . strMsg $ show name ++ " is already defined"
172− Nothing -> putEnv (env { names = M.insert (moduleName, name) (ty, Extern importTy) (names env) })
173− ds <- typeCheckAll mainModuleName moduleName rest
174− return $ d : ds
175−typeCheckAll mainModuleName moduleName (d@(FixityDeclaration _ name) : rest) = do
176− ds <- typeCheckAll mainModuleName moduleName rest
177− env <- getEnv
178− guardWith (strMsg ("Fixity declaration with no binding: " ++ name)) $ M.member (moduleName, Op name) $ names env
179− return $ d : ds
180−typeCheckAll mainModuleName currentModule (d@(ImportDeclaration moduleName _ _) : rest) = do
181− env <- getEnv
182− let instances = filter (\tcd -> let Qualified (Just mn) _ = tcdName tcd in moduleName == mn) (typeClassDictionaries env)
183− addTypeClassDictionaries [ tcd { tcdName = Qualified (Just currentModule) ident, tcdType = TCDAlias (canonicalizeDictionary tcd) }
184− | tcd <- instances
185− , let (Qualified _ ident) = tcdName tcd
186− ]
187− ds <- typeCheckAll mainModuleName currentModule rest
188− return $ d : ds
189−typeCheckAll mainModuleName moduleName (d@(TypeClassDeclaration pn args implies tys) : rest) = do
190− addTypeClass moduleName pn args implies tys
191− ds <- typeCheckAll mainModuleName moduleName rest
192− return $ d : ds
193−typeCheckAll mainModuleName moduleName (TypeInstanceDeclaration dictName deps className tys _ : rest) = do
194− typeCheckAll mainModuleName moduleName (ExternInstanceDeclaration dictName deps className tys : rest)
195−typeCheckAll mainModuleName moduleName (d@(ExternInstanceDeclaration dictName deps className tys) : rest) = do
196− mapM_ (checkTypeClassInstance moduleName) tys
197− forM_ deps $ mapM_ (checkTypeClassInstance moduleName) . snd
198− addTypeClassDictionaries [TypeClassDictionaryInScope (Qualified (Just moduleName) dictName) className tys (Just deps) TCDRegular]
199− ds <- typeCheckAll mainModuleName moduleName rest
200− return $ d : ds
201−typeCheckAll mainModuleName moduleName (PositionedDeclaration pos d : rest) =
202− rethrowWithPosition pos $ do
203− (d' : rest') <- typeCheckAll mainModuleName moduleName (d : rest)
204− return (PositionedDeclaration pos d' : rest')
src/Language/PureScript/TypeChecker/Kinds.hsdeleted−173
@@ -1,173 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.TypeChecker.Kinds
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module implements the kind checker
13−--
14−-----------------------------------------------------------------------------
15−
16−{-# OPTIONS_GHC -fno-warn-orphans #-}
17−{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
18−
19−module Language.PureScript.TypeChecker.Kinds (
20− kindOf,
21− kindsOf,
22− kindsOfAll
23−) where
24−
25−import Language.PureScript.Types
26−import Language.PureScript.Kinds
27−import Language.PureScript.Names
28−import Language.PureScript.TypeChecker.Monad
29−import Language.PureScript.Pretty
30−import Language.PureScript.Environment
31−import Language.PureScript.Errors
32−
33−import Control.Monad.State
34−import Control.Monad.Error
35−import Control.Monad.Unify
36−
37−import Control.Applicative
38−
39−import qualified Data.Map as M
40−import Data.Monoid ((<>))
41−
42−instance Partial Kind where
43− unknown = KUnknown
44− isUnknown (KUnknown u) = Just u
45− isUnknown _ = Nothing
46−
47−instance Unifiable Check Kind where
48− KUnknown u1 =?= KUnknown u2 | u1 == u2 = return ()
49− KUnknown u =?= k = u =:= k
50− k =?= KUnknown u = u =:= k
51− Star =?= Star = return ()
52− Bang =?= Bang = return ()
53− Row k1 =?= Row k2 = k1 =?= k2
54− FunKind k1 k2 =?= FunKind k3 k4 = do
55− k1 =?= k3
56− k2 =?= k4
57− k1 =?= k2 = UnifyT . lift . throwError . strMsg $ "Cannot unify " ++ prettyPrintKind k1 ++ " with " ++ prettyPrintKind k2 ++ "."
58−
59−-- |
60−-- Infer the kind of a single type
61−--
62−kindOf :: ModuleName -> Type -> Check Kind
63−kindOf _ ty =
64− rethrow (mkErrorStack "Error checking kind" (Just (TypeError ty)) <>) $
65− fmap tidyUp . liftUnify $ starIfUnknown <$> infer ty
66− where
67− tidyUp (k, sub) = sub $? k
68−
69−-- |
70−-- Infer the kind of a type constructor with a collection of arguments and a collection of associated data constructors
71−--
72−kindsOf :: Bool -> ModuleName -> ProperName -> [String] -> [Type] -> Check Kind
73−kindsOf isData moduleName name args ts = fmap tidyUp . liftUnify $ do
74− tyCon <- fresh
75− kargs <- replicateM (length args) fresh
76− let dict = (name, tyCon) : zipWith (\arg kind -> (arg, kind)) (map ProperName args) kargs
77− bindLocalTypeVariables moduleName dict $
78− solveTypes isData ts kargs tyCon
79− where
80− tidyUp (k, sub) = starIfUnknown $ sub $? k
81−
82−-- |
83−-- Simultaneously infer the kinds of several mutually recursive type constructors
84−--
85−kindsOfAll :: ModuleName -> [(ProperName, [String], Type)] -> [(ProperName, [String], [Type])] -> Check ([Kind], [Kind])
86−kindsOfAll moduleName syns tys = fmap tidyUp . liftUnify $ do
87− synVars <- replicateM (length syns) fresh
88− let dict = zipWith (\(name, _, _) var -> (name, var)) syns synVars
89− bindLocalTypeVariables moduleName dict $ do
90− tyCons <- replicateM (length tys) fresh
91− let dict' = zipWith (\(name, _, _) tyCon -> (name, tyCon)) tys tyCons
92− bindLocalTypeVariables moduleName dict' $ do
93− data_ks <- zipWithM (\tyCon (_, args, ts) -> do
94− kargs <- replicateM (length args) fresh
95− let argDict = zip (map ProperName args) kargs
96− bindLocalTypeVariables moduleName argDict $
97− solveTypes True ts kargs tyCon) tyCons tys
98− syn_ks <- zipWithM (\synVar (_, args, ty) -> do
99− kargs <- replicateM (length args) fresh
100− let argDict = zip (map ProperName args) kargs
101− bindLocalTypeVariables moduleName argDict $
102− solveTypes False [ty] kargs synVar) synVars syns
103− return (syn_ks, data_ks)
104− where
105− tidyUp ((ks1, ks2), sub) = (map (starIfUnknown . (sub $?)) ks1, map (starIfUnknown . (sub $?)) ks2)
106−
107−-- |
108−-- Solve the set of kind constraints associated with the data constructors for a type constructor
109−--
110−solveTypes :: Bool -> [Type] -> [Kind] -> Kind -> UnifyT Kind (Check) Kind
111−solveTypes isData ts kargs tyCon = do
112− ks <- mapM infer ts
113− when isData $ do
114− tyCon =?= foldr FunKind Star kargs
115− forM_ ks $ \k -> k =?= Star
116− when (not isData) $ do
117− tyCon =?= foldr FunKind (head ks) kargs
118− return tyCon
119−
120−-- |
121−-- Default all unknown kinds to the Star kind of types
122−--
123−starIfUnknown :: Kind -> Kind
124−starIfUnknown (KUnknown _) = Star
125−starIfUnknown (Row k) = Row (starIfUnknown k)
126−starIfUnknown (FunKind k1 k2) = FunKind (starIfUnknown k1) (starIfUnknown k2)
127−starIfUnknown k = k
128−
129−-- |
130−-- Infer a kind for a type
131−--
132−infer :: Type -> UnifyT Kind Check Kind
133−infer ty = rethrow (mkErrorStack "Error inferring type of value" (Just (TypeError ty)) <>) $ infer' ty
134−
135−infer' :: Type -> UnifyT Kind Check Kind
136−infer' (TypeVar v) = do
137− Just moduleName <- checkCurrentModule <$> get
138− UnifyT . lift $ lookupTypeVariable moduleName (Qualified Nothing (ProperName v))
139−infer' c@(TypeConstructor v) = do
140− env <- liftCheck getEnv
141− case M.lookup v (types env) of
142− Nothing -> UnifyT . lift . throwError $ mkErrorStack "Unknown type constructor" (Just (TypeError c))
143− Just (kind, _) -> return kind
144−infer' (TypeApp t1 t2) = do
145− k0 <- fresh
146− k1 <- infer t1
147− k2 <- infer t2
148− k1 =?= FunKind k2 k0
149− return k0
150−infer' (ForAll ident ty _) = do
151− k1 <- fresh
152− Just moduleName <- checkCurrentModule <$> get
153− k2 <- bindLocalTypeVariables moduleName [(ProperName ident, k1)] $ infer ty
154− k2 =?= Star
155− return Star
156−infer' REmpty = do
157− k <- fresh
158− return $ Row k
159−infer' (RCons _ ty row) = do
160− k1 <- infer ty
161− k2 <- infer row
162− k2 =?= Row k1
163− return $ Row k1
164−infer' (ConstrainedType deps ty) = do
165− forM_ deps $ \(className, tys) -> do
166− _ <- infer $ foldl TypeApp (TypeConstructor className) tys
167− return ()
168− k <- infer ty
169− k =?= Star
170− return Star
171−infer' _ = error "Invalid argument to infer"
172−
173−
src/Language/PureScript/TypeChecker/Monad.hsdeleted−202
@@ -1,202 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.TypeChecker.Monad
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Monads for type checking and type inference and associated data types
13−--
14−-----------------------------------------------------------------------------
15−
16−{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleInstances, RankNTypes,
17− MultiParamTypeClasses, FlexibleContexts #-}
18−
19−module Language.PureScript.TypeChecker.Monad where
20−
21−import Language.PureScript.Types
22−import Language.PureScript.Kinds
23−import Language.PureScript.Names
24−import Language.PureScript.Environment
25−import Language.PureScript.TypeClassDictionaries
26−import Language.PureScript.Options
27−import Language.PureScript.Errors
28−
29−import Data.Maybe
30−
31−import Control.Applicative
32−import Control.Monad.State
33−import Control.Monad.Error
34−import Control.Monad.Unify
35−
36−import qualified Data.Map as M
37−
38−-- |
39−-- Temporarily bind a collection of names to values
40−--
41−bindNames :: (MonadState CheckState m) => M.Map (ModuleName, Ident) (Type, NameKind) -> m a -> m a
42−bindNames newNames action = do
43− orig <- get
44− modify $ \st -> st { checkEnv = (checkEnv st) { names = newNames `M.union` (names . checkEnv $ st) } }
45− a <- action
46− modify $ \st -> st { checkEnv = (checkEnv st) { names = names . checkEnv $ orig } }
47− return a
48−
49−-- |
50−-- Temporarily bind a collection of names to types
51−--
52−bindTypes :: (MonadState CheckState m) => M.Map (Qualified ProperName) (Kind, TypeKind) -> m a -> m a
53−bindTypes newNames action = do
54− orig <- get
55− modify $ \st -> st { checkEnv = (checkEnv st) { types = newNames `M.union` (types . checkEnv $ st) } }
56− a <- action
57− modify $ \st -> st { checkEnv = (checkEnv st) { types = types . checkEnv $ orig } }
58− return a
59−
60−-- |
61−-- Temporarily make a collection of type class dictionaries available
62−--
63−withTypeClassDictionaries :: (MonadState CheckState m) => [TypeClassDictionaryInScope] -> m a -> m a
64−withTypeClassDictionaries entries action = do
65− orig <- get
66− modify $ \st -> st { checkEnv = (checkEnv st) { typeClassDictionaries = entries ++ (typeClassDictionaries . checkEnv $ st) } }
67− a <- action
68− modify $ \st -> st { checkEnv = (checkEnv st) { typeClassDictionaries = typeClassDictionaries . checkEnv $ orig } }
69− return a
70−
71−-- |
72−-- Get the currently available list of type class dictionaries
73−--
74−getTypeClassDictionaries :: (Functor m, MonadState CheckState m) => m [TypeClassDictionaryInScope]
75−getTypeClassDictionaries = typeClassDictionaries . checkEnv <$> get
76−
77−-- |
78−-- Temporarily bind a collection of names to local variables
79−--
80−bindLocalVariables :: (Functor m, MonadState CheckState m) => ModuleName -> [(Ident, Type)] -> m a -> m a
81−bindLocalVariables moduleName bindings =
82− bindNames (M.fromList $ flip map bindings $ \(name, ty) -> ((moduleName, name), (ty, LocalVariable)))
83−
84−-- |
85−-- Temporarily bind a collection of names to local type variables
86−--
87−bindLocalTypeVariables :: (Functor m, MonadState CheckState m) => ModuleName -> [(ProperName, Kind)] -> m a -> m a
88−bindLocalTypeVariables moduleName bindings =
89− bindTypes (M.fromList $ flip map bindings $ \(pn, kind) -> (Qualified (Just moduleName) pn, (kind, LocalTypeVariable)))
90−
91−-- |
92−-- Lookup the type of a value by name in the @Environment@
93−--
94−lookupVariable :: (Error e, Functor m, MonadState CheckState m, MonadError e m) => ModuleName -> Qualified Ident -> m Type
95−lookupVariable currentModule (Qualified moduleName var) = do
96− env <- getEnv
97− case M.lookup (fromMaybe currentModule moduleName, var) (names env) of
98− Nothing -> throwError . strMsg $ show var ++ " is undefined"
99− Just (ty, _) -> return ty
100−
101−-- |
102−-- Lookup the kind of a type by name in the @Environment@
103−--
104−lookupTypeVariable :: (Error e, Functor m, MonadState CheckState m, MonadError e m) => ModuleName -> Qualified ProperName -> m Kind
105−lookupTypeVariable currentModule (Qualified moduleName name) = do
106− env <- getEnv
107− case M.lookup (Qualified (Just $ fromMaybe currentModule moduleName) name) (types env) of
108− Nothing -> throwError . strMsg $ "Type variable " ++ show name ++ " is undefined"
109− Just (k, _) -> return k
110−
111−-- |
112−-- State required for type checking:
113−--
114−data CheckState = CheckState {
115− -- |
116− -- The current @Environment@
117− --
118− checkEnv :: Environment
119− -- |
120− -- The next fresh unification variable name
121− --
122− , checkNextVar :: Int
123− -- |
124− -- The next type class dictionary name
125− --
126− , checkNextDictName :: Int
127− -- |
128− -- The current module
129− --
130− , checkCurrentModule :: Maybe ModuleName
131− }
132−
133−-- |
134−-- The type checking monad, which provides the state of the type checker, and error reporting capabilities
135−--
136−newtype Check a = Check { unCheck :: StateT CheckState (Either ErrorStack) a }
137− deriving (Functor, Monad, Applicative, MonadPlus, MonadState CheckState, MonadError ErrorStack)
138−
139−-- |
140−-- Get the current @Environment@
141−--
142−getEnv :: (Functor m, MonadState CheckState m) => m Environment
143−getEnv = checkEnv <$> get
144−
145−-- |
146−-- Update the @Environment#
147−--
148−putEnv :: (MonadState CheckState m) => Environment -> m ()
149−putEnv env = modify (\s -> s { checkEnv = env })
150−
151−-- |
152−-- Modify the @Environment@
153−--
154−modifyEnv :: (MonadState CheckState m) => (Environment -> Environment) -> m ()
155−modifyEnv f = modify (\s -> s { checkEnv = f (checkEnv s) })
156−
157−-- |
158−-- Run a computation in the Check monad, starting with an empty @Environment@
159−--
160−runCheck :: Options -> Check a -> Either String (a, Environment)
161−runCheck opts = runCheck' opts initEnvironment
162−
163−-- |
164−-- Run a computation in the Check monad, failing with an error, or succeeding with a return value and the final @Environment@.
165−--
166−runCheck' :: Options -> Environment -> Check a -> Either String (a, Environment)
167−runCheck' opts env c = stringifyErrorStack (optionsVerboseErrors opts) $ do
168− (a, s) <- flip runStateT (CheckState env 0 0 Nothing) $ unCheck c
169− return (a, checkEnv s)
170−
171−-- |
172−-- Make an assertion, failing with an error message
173−--
174−guardWith :: (MonadError e m) => e -> Bool -> m ()
175−guardWith _ True = return ()
176−guardWith e False = throwError e
177−
178−-- |
179−-- Generate new type class dictionary name
180−--
181−freshDictionaryName :: Check Int
182−freshDictionaryName = do
183− n <- checkNextDictName <$> get
184− modify $ \s -> s { checkNextDictName = succ (checkNextDictName s) }
185− return n
186−
187−-- |
188−-- Lift a computation in the @Check@ monad into the substitution monad.
189−--
190−liftCheck :: Check a -> UnifyT t Check a
191−liftCheck = UnifyT . lift
192−
193−-- |
194−-- Run a computation in the substitution monad, generating a return value and the final substitution.
195−--
196−liftUnify :: (Partial t) => UnifyT t Check a -> Check (a, Substitution t)
197−liftUnify unify = do
198− st <- get
199− (a, ust) <- runUnify (defaultUnifyState { unifyNextVar = checkNextVar st }) unify
200− modify $ \st' -> st' { checkNextVar = unifyNextVar ust }
201− return (a, unifyCurrentSubstitution ust)
202−
src/Language/PureScript/TypeChecker/Synonyms.hsdeleted−59
@@ -1,59 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.TypeChecker.Synonyms
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Functions for replacing fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor
13−--
14−-----------------------------------------------------------------------------
15−
16−module Language.PureScript.TypeChecker.Synonyms (
17− saturateTypeSynonym,
18− saturateAllTypeSynonyms
19−) where
20−
21−import Language.PureScript.Types
22−import Language.PureScript.Names
23−
24−import Control.Applicative ((<$>))
25−import Data.Maybe (fromMaybe)
26−import Data.Data
27−import Data.Generics
28−import Data.Generics.Extras
29−import Control.Monad.Writer
30−import Control.Monad.Error
31−
32−-- |
33−-- Build a type substitution for a type synonym
34−--
35−buildTypeSubstitution :: Qualified ProperName -> Int -> Type -> Either String (Maybe Type)
36−buildTypeSubstitution name n = go n []
37− where
38− go :: Int -> [Type] -> Type -> Either String (Maybe Type)
39− go 0 args (TypeConstructor ctor) | name == ctor = return (Just $ SaturatedTypeSynonym ctor args)
40− go m _ (TypeConstructor ctor) | m > 0 && name == ctor = throwError $ "Partially applied type synonym " ++ show name
41− go m args (TypeApp f arg) = go (m - 1) (arg:args) f
42− go _ _ _ = return Nothing
43−
44−-- |
45−-- Replace all instances of a specific type synonym with the @SaturatedTypeSynonym@ data constructor
46−--
47−saturateTypeSynonym :: (Data d) => Qualified ProperName -> Int -> d -> Either String d
48−saturateTypeSynonym name n = everywhereM' (mkM replace)
49− where
50− replace t = fromMaybe t <$> buildTypeSubstitution name n t
51−
52−-- |
53−-- Replace all type synonyms with the @SaturatedTypeSynonym@ data constructor
54−--
55−saturateAllTypeSynonyms :: (Data d) => [(Qualified ProperName, Int)] -> d -> Either String d
56−saturateAllTypeSynonyms syns d = foldM (\result (name, n) -> saturateTypeSynonym name n result) d syns
57−
58−
59−
src/Language/PureScript/TypeChecker/Types.hsdeleted−1061
@@ -1,1061 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.TypeChecker.Types
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module implements the type checker
13−--
14−-----------------------------------------------------------------------------
15−
16−{-# OPTIONS_GHC -fno-warn-orphans #-}
17−{-# LANGUAGE FlexibleInstances #-}
18−{-# LANGUAGE FlexibleContexts #-}
19−{-# LANGUAGE MultiParamTypeClasses #-}
20−
21−module Language.PureScript.TypeChecker.Types (
22− typesOf
23−) where
24−
25−{-
26− The following functions represent the corresponding type checking judgements:
27−
28− infer
29− Synthesize a type for a value
30−
31− check
32− Check a value has a given type
33−
34− checkProperties
35− Check an object with a given type contains specified properties
36−
37− checkFunctionApplication
38− Check a function of a given type returns a value of another type when applied to its arguments
39−
40− subsumes
41− Check a type subsumes another type
42−-}
43−
44−import Data.List
45−import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
46−import qualified Data.Data as D
47−import Data.Generics
48− (everythingWithContext, mkM, everywhereM, everything, mkT,
49− something, everywhere, mkQ)
50−import Data.Generics.Extras
51−
52−import Language.PureScript.Declarations
53−import Language.PureScript.Types
54−import Language.PureScript.Kinds
55−import Language.PureScript.Names
56−import Language.PureScript.TypeClassDictionaries
57−import Language.PureScript.TypeChecker.Monad
58−import Language.PureScript.TypeChecker.Kinds
59−import Language.PureScript.TypeChecker.Synonyms
60−import Language.PureScript.Pretty
61−import Language.PureScript.Environment
62−import Language.PureScript.Errors
63−import qualified Language.PureScript.Constants as C
64−
65−import Control.Monad.State
66−import Control.Monad.Error
67−import Control.Monad.Unify
68−
69−import Control.Applicative
70−import Control.Arrow (Arrow(..))
71−
72−import qualified Data.Map as M
73−import Data.Function (on)
74−import Data.Ord (comparing)
75−import Data.Monoid ((<>))
76−
77−instance Partial Type where
78− unknown = TUnknown
79− isUnknown (TUnknown u) = Just u
80− isUnknown _ = Nothing
81−
82−instance Unifiable Check Type where
83− (=?=) = unifyTypes
84−
85−-- |
86−-- Unify two types, updating the current substitution
87−--
88−unifyTypes :: Type -> Type -> UnifyT Type Check ()
89−unifyTypes t1 t2 = rethrow (mkErrorStack ("Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2) Nothing <>) $
90− unifyTypes' t1 t2
91− where
92− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
93− unifyTypes' (TUnknown u) t = u =:= t
94− unifyTypes' t (TUnknown u) = u =:= t
95− unifyTypes' (SaturatedTypeSynonym name args) ty = do
96− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
97− ty1 `unifyTypes` ty
98− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
99− unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
100− case (sc1, sc2) of
101− (Just sc1', Just sc2') -> do
102− sko <- newSkolemConstant
103− let sk1 = skolemize ident1 sko sc1' ty1
104− let sk2 = skolemize ident2 sko sc2' ty2
105− sk1 `unifyTypes` sk2
106− _ -> error "Skolemized type variable was not given a scope"
107− unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
108− sko <- newSkolemConstant
109− let sk = skolemize ident sko sc ty1
110− sk `unifyTypes` ty2
111− unifyTypes' ForAll{} _ = throwError . strMsg $ "Skolem variable scope is unspecified"
112− unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
113− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
114− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) =
115− guardWith (strMsg ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".")) (c1 == c2)
116− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
117− t3 `unifyTypes` t5
118− t4 `unifyTypes` t6
119− unifyTypes' (Skolem s1 _) (Skolem s2 _) | s1 == s2 = return ()
120− unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
121− unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
122− unifyTypes' r1@REmpty r2 = unifyRows r1 r2
123− unifyTypes' r1 r2@REmpty = unifyRows r1 r2
124− unifyTypes' t@(ConstrainedType _ _) _ = throwError . strMsg $ "Attempted to unify a constrained type " ++ prettyPrintType t ++ " with another type."
125− unifyTypes' t3 t4@(ConstrainedType _ _) = unifyTypes' t4 t3
126− unifyTypes' t3 t4 = throwError . strMsg $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
127−
128−-- |
129−-- Unify two rows, updating the current substitution
130−--
131−-- Common labels are first identified, and unified. Remaining labels and types are unified with a
132−-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
133−-- error.
134−--
135−unifyRows :: Type -> Type -> UnifyT Type Check ()
136−unifyRows r1 r2 =
137− let
138− (s1, r1') = rowToList r1
139− (s2, r2') = rowToList r2
140− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
141− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
142− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
143− in do
144− forM_ int (uncurry (=?=))
145− unifyRows' sd1 r1' sd2 r2'
146− where
147− unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
148− unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
149− unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
150− unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
151− occursCheck un ty
152− forM_ row $ \(_, t) -> occursCheck un t
153− u' <- fresh
154− u =?= RCons name ty u'
155− unifyRows' row r others u'
156− unifyRows' [] REmpty [] REmpty = return ()
157− unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
158− unifyRows' [] (Skolem s1 _) [] (Skolem s2 _) | s1 == s2 = return ()
159− unifyRows' sd3 r3 sd4 r4 = throwError . strMsg $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")"
160−
161−-- |
162−-- Infer the types of multiple mutually-recursive values, and return elaborated values including
163−-- type class dictionaries and type annotations.
164−--
165−typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
166−typesOf mainModuleName moduleName vals = do
167− tys <- fmap tidyUp . liftUnify $ do
168− (es, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName vals
169− forM es $ \e -> do
170− triple@(_, (_, ty)) <- typeForBindingGroupElement moduleName e dict untypedDict
171− -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
172− when (Just moduleName == mainModuleName && fst e == Ident C.main) $ do
173− [eff, a] <- replicateM 2 fresh
174− ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
175− return triple
176−
177− forM tys $ \(ident, (val, ty)) -> do
178− -- Replace type class dictionary placeholders with actual dictionaries
179− val' <- replaceTypeClassDictionaries moduleName val
180− -- Check skolem variables did not escape their scope
181− skolemEscapeCheck val'
182− -- Remove type synonyms placeholders, remove duplicate row fields, and replace
183− -- top-level unification variables with named type variables.
184− let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
185− ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
186− return (ident, (val'', ty'))
187− where
188− -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
189− tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
190−
191−typeDictionaryForBindingGroup :: ModuleName -> [(Ident, Value)] -> UnifyT Type Check ([(Ident, (Value, Maybe (Type, Bool)))], M.Map (ModuleName, Ident) (Type, NameKind), [(Ident, Type)])
192−typeDictionaryForBindingGroup moduleName vals = do
193− let
194− -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
195− es = map isTyped vals
196− -- Filter the typed and untyped declarations
197− typed = filter (isJust . snd . snd) es
198− untyped = filter (isNothing . snd . snd) es
199− -- Make a map of names to typed declarations
200− typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
201−
202− -- Create fresh unification variables for the types of untyped declarations
203− untypedNames <- replicateM (length untyped) fresh
204−
205− let
206− -- Make a map of names to the unification variables of untyped declarations
207− untypedDict = zip (map fst untyped) untypedNames
208− -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
209− dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
210− return (es, dict, untypedDict)
211−
212−typeForBindingGroupElement :: ModuleName -> (Ident, (Value, Maybe (Type, Bool))) -> M.Map (ModuleName, Ident) (Type, NameKind) -> [(Ident, Type)] -> UnifyT Type Check (Ident, (Value, Type))
213−typeForBindingGroupElement moduleName e@(_, (val, _)) dict untypedDict = do
214− -- If the declaration is a function, it has access to other values in the binding group.
215− -- If not, the generated code might fail at runtime since those values might be undefined.
216− let dict' = if isFunction val then dict else M.empty
217− case e of
218− -- Typed declarations
219− (ident, (val', Just (ty, checkType))) -> do
220− -- Kind check
221− kind <- liftCheck $ kindOf moduleName ty
222− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
223− -- Check the type with the new names in scope
224− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
225− val'' <- bindNames dict' $ if checkType
226− then TypedValue True <$> check val' ty' <*> pure ty'
227− else return (TypedValue False val' ty')
228− return (ident, (val'', ty'))
229− -- Untyped declarations
230− (ident, (val', Nothing)) -> do
231− -- Infer the type with the new names in scope
232− TypedValue _ val'' ty <- bindNames dict' $ infer val'
233− ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
234− return (ident, (TypedValue True val'' ty, ty))
235−
236−-- |
237−-- Check if a value introduces a function
238−--
239−isFunction :: Value -> Bool
240−isFunction (Abs _ _) = True
241−isFunction (TypedValue _ val _) = isFunction val
242−isFunction (PositionedValue _ val) = isFunction val
243−isFunction _ = False
244−
245−-- |
246−-- Check if a value contains a type annotation
247−--
248−isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
249−isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
250−isTyped (name, value) = (name, (value, Nothing))
251−
252−-- |
253−-- Map a function over type annotations appearing inside a value
254−--
255−overTypes :: (Type -> Type) -> Value -> Value
256−overTypes f = everywhere (mkT f)
257−
258−-- |
259−-- Replace type class dictionary placeholders with inferred type class dictionaries
260−--
261−replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
262−replaceTypeClassDictionaries mn = everywhereM' (mkM go)
263− where
264− go (TypeClassDictionary trySuperclasses constraint dicts) = do
265− env <- getEnv
266− let dicts' = fromMaybe (typeClassDictionaries env) dicts
267− entails env mn dicts' constraint trySuperclasses
268− go other = return other
269−
270−-- |
271−-- A simplified representation of expressions which are used to represent type
272−-- class dictionaries at runtime, which can be compared for equality
273−--
274−data DictionaryValue
275− -- |
276− -- A dictionary which is brought into scope by a local constraint
277− --
278− = LocalDictionaryValue (Qualified Ident)
279− -- |
280− -- A dictionary which is brought into scope by an instance declaration
281− --
282− | GlobalDictionaryValue (Qualified Ident)
283− -- |
284− -- A dictionary which depends on other dictionaries
285− --
286− | DependentDictionaryValue (Qualified Ident) [DictionaryValue]
287− -- |
288− -- A subclass dictionary
289− --
290− | SubclassDictionaryValue DictionaryValue Integer
291− deriving (Show, Ord, Eq)
292−
293−-- |
294−-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
295−-- return a type class dictionary reference.
296−--
297−entails :: Environment -> ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Bool -> Check Value
298−entails env moduleName context = solve (sortedNubBy canonicalizeDictionary (filter filterModule context))
299− where
300− sortedNubBy :: (Ord k) => (v -> k) -> [v] -> [v]
301− sortedNubBy f vs = M.elems (M.fromList (map (f &&& id) vs))
302−
303− -- Filter out type dictionaries which are in scope in the current module
304− filterModule :: TypeClassDictionaryInScope -> Bool
305− filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
306− filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
307− filterModule _ = False
308−
309− solve context' (className, tys) trySuperclasses =
310− case chooseSimplestDictionaries (go className tys) of
311− [] -> throwError . strMsg $ "No instance found for " ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys)
312− [dict] -> return (dictionaryValueToValue dict)
313− _ -> throwError . strMsg $ "Overlapping instances found for " ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys)
314− where
315− go className' tys' =
316− -- Look for regular type instances
317− [ mkDictionary (canonicalizeDictionary tcd) args
318− | tcd <- context'
319− -- Make sure the type class name matches the one we are trying to satisfy
320− , className' == tcdClassName tcd
321− -- Make sure the type unifies with the type in the type instance definition
322− , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
323− -- Solve any necessary subgoals
324− , args <- solveSubgoals subst (tcdDependencies tcd) ] ++
325−
326− -- Look for implementations via superclasses
327− [ SubclassDictionaryValue suDict index
328− | trySuperclasses
329− , (subclassName, (args, _, implies)) <- M.toList (typeClasses env)
330− -- Try each superclass
331− , (index, (superclass, suTyArgs)) <- zip [0..] implies
332− -- Make sure the type class name matches the superclass name
333− , className' == superclass
334− -- Make sure the types unify with the types in the superclass implication
335− , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' suTyArgs
336− -- Finally, satisfy the subclass constraint
337− , suDict <- go subclassName (map (applySubst subst . TypeVar) args) ]
338−
339− -- Create dictionaries for subgoals which still need to be solved by calling go recursively
340− -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
341− -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
342− solveSubgoals :: [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [DictionaryValue]]
343− solveSubgoals _ Nothing = return Nothing
344− solveSubgoals subst (Just subgoals) = do
345− dict <- mapM (uncurry go . second (map (replaceAllTypeVars subst))) subgoals
346− return $ Just dict
347− -- Make a dictionary from subgoal dictionaries by applying the correct function
348− mkDictionary :: Qualified Ident -> Maybe [DictionaryValue] -> DictionaryValue
349− mkDictionary fnName Nothing = LocalDictionaryValue fnName
350− mkDictionary fnName (Just []) = GlobalDictionaryValue fnName
351− mkDictionary fnName (Just dicts) = DependentDictionaryValue fnName dicts
352− -- Turn a DictionaryValue into a Value
353− dictionaryValueToValue :: DictionaryValue -> Value
354− dictionaryValueToValue (LocalDictionaryValue fnName) = Var fnName
355− dictionaryValueToValue (GlobalDictionaryValue fnName) = App (Var fnName) (ObjectLiteral [])
356− dictionaryValueToValue (DependentDictionaryValue fnName dicts) = foldl App (Var fnName) (map dictionaryValueToValue dicts)
357− dictionaryValueToValue (SubclassDictionaryValue dict index) =
358− App (App (Var (Qualified (Just (ModuleName [ProperName C.prelude])) (Ident (C.!!))))
359− (Accessor C.__superclasses (dictionaryValueToValue dict)))
360− (NumericLiteral (Left index))
361− -- Ensure that a substitution is valid
362− verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
363− verifySubstitution subst = do
364− let grps = groupBy ((==) `on` fst) subst
365− guard (all (pairwise (unifiesWith env) . map snd) grps)
366− return $ map head grps
367− -- Apply a substitution to a type
368− applySubst :: [(String, Type)] -> Type -> Type
369− applySubst subst = everywhere (mkT replace)
370− where
371− replace t@(TypeVar v) = fromMaybe t $ lookup v subst
372− replace other = other
373− -- Choose the simplest DictionaryValues from a list of candidates
374− -- The reason for this function is as follows:
375− -- When considering overlapping instances, we don't want to consider the same dictionary
376− -- to be an overlap of itself when obtained as a superclass of another class.
377− -- Observing that we probably don't want to select a superclass instance when an instance
378− -- is available directly, and that there is no way for a superclass instance to actually
379− -- introduce an overlap that wouldn't have been there already, we simply remove dictionaries
380− -- obtained as superclass instances if there are simpler instances available.
381− chooseSimplestDictionaries :: [DictionaryValue] -> [DictionaryValue]
382− chooseSimplestDictionaries ds = case filter isSimpleDictionaryValue ds of
383− [] -> ds
384− simple -> simple
385− isSimpleDictionaryValue SubclassDictionaryValue{} = False
386− isSimpleDictionaryValue _ = True
387−
388−-- |
389−-- Check all values in a list pairwise match a predicate
390−--
391−pairwise :: (a -> a -> Bool) -> [a] -> Bool
392−pairwise _ [] = True
393−pairwise _ [_] = True
394−pairwise p (x : xs) = all (p x) xs && pairwise p xs
395−
396−-- |
397−-- Check that two types unify
398−--
399−unifiesWith :: Environment -> Type -> Type -> Bool
400−unifiesWith _ (TUnknown _) _ = True
401−unifiesWith _ _ (TUnknown _) = True
402−unifiesWith _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = True
403−unifiesWith _ (TypeVar v1) (TypeVar v2) | v1 == v2 = True
404−unifiesWith _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = True
405−unifiesWith e (TypeApp h1 t1) (TypeApp h2 t2) = unifiesWith e h1 h2 && unifiesWith e t1 t2
406−unifiesWith e (SaturatedTypeSynonym name args) t2 =
407− case expandTypeSynonym' e name args of
408− Left _ -> False
409− Right t1 -> unifiesWith e t1 t2
410−unifiesWith e t1 t2@(SaturatedTypeSynonym _ _) = unifiesWith e t2 t1
411−unifiesWith _ _ _ = False
412−
413−-- |
414−-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
415−-- and return a substitution from type variables to types which makes the type heads unify.
416−--
417−typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
418−typeHeadsAreEqual _ _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = Just []
419−typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
420−typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
421−typeHeadsAreEqual m e (TypeApp h1 t1) (TypeApp h2 t2) = (++) <$> typeHeadsAreEqual m e h1 h2 <*> typeHeadsAreEqual m e t1 t2
422−typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
423− Left _ -> Nothing
424− Right t1 -> typeHeadsAreEqual m e t1 t2
425−typeHeadsAreEqual _ _ _ _ = Nothing
426−
427−-- |
428−-- Ensure skolem variables do not escape their scope
429−--
430−skolemEscapeCheck :: Value -> Check ()
431−skolemEscapeCheck (TypedValue False _ _) = return ()
432−skolemEscapeCheck root@TypedValue{} =
433− -- Every skolem variable is created when a ForAll type is skolemized.
434− -- This determines the scope of that skolem variable, which is copied from the SkolemScope
435− -- field of the ForAll constructor.
436− -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
437− -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
438− -- an escaped skolem variable.
439− case everythingWithContext [] (++) (mkQ ((,) []) go) root of
440− [] -> return ()
441− ((binding, val) : _) -> throwError $ mkErrorStack ("Rigid/skolem type variable " ++ maybe "" (("bound by " ++) . prettyPrintValue) binding ++ " has escaped.") (Just (ValueError val))
442− where
443− go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
444− go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
445− go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
446− (sco : _) -> ([(findBindingScope sco, val)], scos)
447− _ -> ([], scos)
448− where
449− collectSkolems :: Type -> [SkolemScope]
450− collectSkolems = nub . everything (++) (mkQ [] collect)
451− where
452− collect (Skolem _ scope) = [scope]
453− collect _ = []
454− go _ scos = ([], scos)
455− findBindingScope :: SkolemScope -> Maybe Value
456− findBindingScope sco = something (mkQ Nothing go') root
457− where
458− go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = Just val
459− go' _ = Nothing
460−skolemEscapeCheck val = throwError $ mkErrorStack "Untyped value passed to skolemEscapeCheck" (Just (ValueError val))
461−
462−-- |
463−-- Ensure a row contains no duplicate labels
464−--
465−setify :: Type -> Type
466−setify = rowFromList . first (M.toList . M.fromList) . rowToList
467−
468−-- |
469−-- \"Setify\" all rows occuring inside a value
470−--
471−setifyAll :: (D.Data d) => d -> d
472−setifyAll = everywhere (mkT setify)
473−
474−-- |
475−-- Replace outermost unsolved unification variables with named type variables
476−--
477−varIfUnknown :: Type -> Type
478−varIfUnknown ty =
479− let unks = nub $ unknowns ty
480− toName = (:) 't' . show
481− ty' = everywhere (mkT typeToVar) ty
482− typeToVar :: Type -> Type
483− typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
484− typeToVar t = t
485− in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
486−
487−-- |
488−-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
489−-- or TypeClassDictionary values.
490−--
491−-- This is necessary during type checking to avoid unifying a polymorphic type with a
492−-- unification variable.
493−--
494−instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
495−instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
496− ty' <- replaceVarWithUnknown ident ty
497− instantiatePolyTypeWithUnknowns val ty'
498−instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
499− dicts <- getTypeClassDictionaries
500− (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
501− return (foldl App val (map (flip (TypeClassDictionary True) (Just dicts)) constraints), ty')
502−instantiatePolyTypeWithUnknowns val ty = return (val, ty)
503−
504−-- |
505−-- Replace a single type variable with a new unification variable
506−--
507−replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
508−replaceVarWithUnknown ident ty = do
509− tu <- fresh
510− return $ replaceTypeVars ident tu ty
511−
512−-- |
513−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
514−-- better error messages during unification.
515−--
516−replaceAllTypeSynonyms' :: (D.Data d) => Environment -> d -> Either String d
517−replaceAllTypeSynonyms' env d =
518− let
519− syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
520− in
521− saturateAllTypeSynonyms syns d
522−
523−replaceAllTypeSynonyms :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => (D.Data d) => d -> m d
524−replaceAllTypeSynonyms d = do
525− env <- getEnv
526− either (throwError . strMsg) return $ replaceAllTypeSynonyms' env d
527−
528−-- |
529−-- \"Desaturate\" @SaturatedTypeSynonym@s
530−--
531−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
532−desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
533− where
534− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
535− replaceSaturatedTypeSynonym t = t
536−
537−-- |
538−-- Replace a type synonym and its arguments with the aliased type
539−--
540−expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
541−expandTypeSynonym' env name args =
542− case M.lookup name (typeSynonyms env) of
543− Just (synArgs, body) -> do
544− let repl = replaceAllTypeVars (zip synArgs args) body
545− replaceAllTypeSynonyms' env repl
546− Nothing -> error "Type synonym was not defined"
547−
548−expandTypeSynonym :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Qualified ProperName -> [Type] -> m Type
549−expandTypeSynonym name args = do
550− env <- getEnv
551− either (throwError . strMsg) return $ expandTypeSynonym' env name args
552−
553−expandAllTypeSynonyms :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
554−expandAllTypeSynonyms = everywhereM' (mkM go)
555− where
556− go (SaturatedTypeSynonym name args) = expandTypeSynonym name args
557− go other = return other
558−
559−-- |
560−-- Ensure a set of property names and value does not contain duplicate labels
561−--
562−ensureNoDuplicateProperties :: (Error e, MonadError e m) => [(String, Value)] -> m ()
563−ensureNoDuplicateProperties ps = guardWith (strMsg "Duplicate property names") $ length (nub . map fst $ ps) == length ps
564−
565−-- |
566−-- Infer a type for a value, rethrowing any error to provide a more useful error message
567−--
568−infer :: Value -> UnifyT Type Check Value
569−infer val = rethrow (mkErrorStack "Error inferring type of value" (Just (ValueError val)) <>) $ infer' val
570−
571−-- |
572−-- Infer a type for a value
573−--
574−infer' :: Value -> UnifyT Type Check Value
575−infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
576−infer' v@(StringLiteral _) = return $ TypedValue True v tyString
577−infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
578−infer' (ArrayLiteral vals) = do
579− ts <- mapM infer vals
580− els <- fresh
581− forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
582− return $ TypedValue True (ArrayLiteral ts) els
583−infer' (ObjectLiteral ps) = do
584− ensureNoDuplicateProperties ps
585− ts <- mapM (infer . snd) ps
586− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
587− ty = TypeApp tyObject $ rowFromList (fields, REmpty)
588− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
589−infer' (ObjectUpdate o ps) = do
590− ensureNoDuplicateProperties ps
591− row <- fresh
592− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
593− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
594− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
595− let oldTy = TypeApp tyObject $ rowFromList (oldTys, row)
596− o' <- TypedValue True <$> check o oldTy <*> pure oldTy
597− return $ TypedValue True (ObjectUpdate o' newVals) $ TypeApp tyObject $ rowFromList (newTys, row)
598−infer' (Accessor prop val) = do
599− typed@(TypedValue _ _ objTy) <- infer val
600− propTy <- inferProperty objTy prop
601− case propTy of
602− Nothing -> do
603− field <- fresh
604− rest <- fresh
605− _ <- subsumes Nothing objTy (TypeApp tyObject (RCons prop field rest))
606− return $ TypedValue True (Accessor prop typed) field
607− Just ty -> return $ TypedValue True (Accessor prop typed) ty
608−infer' (Abs (Left arg) ret) = do
609− ty <- fresh
610− Just moduleName <- checkCurrentModule <$> get
611− bindLocalVariables moduleName [(arg, ty)] $ do
612− body@(TypedValue _ _ bodyTy) <- infer' ret
613− return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
614−infer' (Abs (Right _) _) = error "Binder was not desugared"
615−infer' (App f arg) = do
616− f'@(TypedValue _ _ ft) <- infer f
617− (ret, app) <- checkFunctionApplication f' ft arg Nothing
618− return $ TypedValue True app ret
619−infer' (Var var) = do
620− Just moduleName <- checkCurrentModule <$> get
621− ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
622− case ty of
623− ConstrainedType constraints ty' -> do
624− dicts <- getTypeClassDictionaries
625− return $ TypedValue True (foldl App (Var var) (map (flip (TypeClassDictionary True) (Just dicts)) constraints)) ty'
626− _ -> return $ TypedValue True (Var var) ty
627−infer' v@(Constructor c) = do
628− env <- getEnv
629− case M.lookup c (dataConstructors env) of
630− Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
631− Just (_, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
632− return $ TypedValue True v ty'
633−infer' (Case vals binders) = do
634− ts <- mapM infer vals
635− ret <- fresh
636− binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
637− return $ TypedValue True (Case ts binders') ret
638−infer' (IfThenElse cond th el) = do
639− cond' <- check cond tyBoolean
640− v2@(TypedValue _ _ t2) <- infer th
641− v3@(TypedValue _ _ t3) <- infer el
642− t2 =?= t3
643− return $ TypedValue True (IfThenElse cond' v2 v3) t2
644−infer' (Let ds val) = do
645− (ds', val'@(TypedValue _ _ valTy)) <- inferLetBinding [] ds val infer
646− return $ TypedValue True (Let ds' val') valTy
647−infer' (TypedValue checkType val ty) = do
648− Just moduleName <- checkCurrentModule <$> get
649− kind <- liftCheck $ kindOf moduleName ty
650− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
651− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
652− val' <- if checkType then check val ty' else return val
653− return $ TypedValue True val' ty'
654−infer' (PositionedValue pos val) = rethrowWithPosition pos $ infer' val
655−infer' _ = error "Invalid argument to infer"
656−
657−inferLetBinding :: [Declaration] -> [Declaration] -> Value -> (Value -> UnifyT Type Check Value) -> UnifyT Type Check ([Declaration], Value)
658−inferLetBinding seen [] ret j = (,) seen <$> j ret
659−inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing val : rest) ret j = do
660− valTy <- fresh
661− Just moduleName <- checkCurrentModule <$> get
662− let dict = if isFunction val then M.singleton (moduleName, ident) (valTy, nameKind) else M.empty
663− TypedValue _ val' valTy' <- bindNames dict $ infer val
664− valTy =?= valTy'
665− bindNames (M.singleton (moduleName, ident) (valTy', nameKind)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing val']) rest ret j
666−inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
667− Just moduleName <- checkCurrentModule <$> get
668− (es, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName (map (\(i, _, v) -> (i, v)) ds)
669− ds' <- forM es $ \e -> do
670− (ident, (val', _)) <- typeForBindingGroupElement moduleName e dict untypedDict
671− return $ (ident, LocalVariable, val')
672− bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
673−inferLetBinding seen (PositionedDeclaration pos d : ds) ret j = do
674− ((d' : ds'), val') <- inferLetBinding seen (d : ds) ret j
675− return (PositionedDeclaration pos d' : ds', val')
676−inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
677−
678−-- |
679−-- Infer the type of a property inside a record with a given type
680−--
681−inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
682−inferProperty (TypeApp obj row) prop | obj == tyObject = do
683− let (props, _) = rowToList row
684− return $ lookup prop props
685−inferProperty (SaturatedTypeSynonym name args) prop = do
686− replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
687− inferProperty replaced prop
688−inferProperty (ForAll ident ty _) prop = do
689− replaced <- replaceVarWithUnknown ident ty
690− inferProperty replaced prop
691−inferProperty _ _ = return Nothing
692−
693−-- |
694−-- Infer the types of variables brought into scope by a binder
695−--
696−inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
697−inferBinder _ NullBinder = return M.empty
698−inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
699−inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
700−inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
701−inferBinder val (VarBinder name) = return $ M.singleton name val
702−inferBinder val (ConstructorBinder ctor binders) = do
703− env <- getEnv
704− case M.lookup ctor (dataConstructors env) of
705− Just (_, ty) -> do
706− (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
707− fn' <- replaceAllTypeSynonyms fn
708− go binders fn'
709− where
710− go [] ty' = do
711− _ <- subsumes Nothing val ty'
712− return M.empty
713− go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
714− M.union <$> inferBinder obj binder <*> go binders' ret
715− go _ _ = throwError . strMsg $ "Wrong number of arguments to constructor " ++ show ctor
716− _ -> throwError . strMsg $ "Constructor " ++ show ctor ++ " is not defined"
717−inferBinder val (ObjectBinder props) = do
718− row <- fresh
719− rest <- fresh
720− m1 <- inferRowProperties row rest props
721− val =?= TypeApp tyObject row
722− return m1
723− where
724− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
725− inferRowProperties nrow row [] = nrow =?= row >> return M.empty
726− inferRowProperties nrow row ((name, binder):binders) = do
727− propTy <- fresh
728− m1 <- inferBinder propTy binder
729− m2 <- inferRowProperties nrow (RCons name propTy row) binders
730− return $ m1 `M.union` m2
731−inferBinder val (ArrayBinder binders) = do
732− el <- fresh
733− m1 <- M.unions <$> mapM (inferBinder el) binders
734− val =?= TypeApp tyArray el
735− return m1
736−inferBinder val (ConsBinder headBinder tailBinder) = do
737− el <- fresh
738− m1 <- inferBinder el headBinder
739− m2 <- inferBinder val tailBinder
740− val =?= TypeApp tyArray el
741− return $ m1 `M.union` m2
742−inferBinder val (NamedBinder name binder) = do
743− m <- inferBinder val binder
744− return $ M.insert name val m
745−inferBinder val (PositionedBinder pos binder) =
746− rethrowWithPosition pos $ inferBinder val binder
747−
748−-- |
749−-- Check the types of the return values in a set of binders in a case statement
750−--
751−checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
752−checkBinders _ _ [] = return []
753−checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
754− Just moduleName <- checkCurrentModule <$> get
755− m1 <- M.unions <$> zipWithM inferBinder nvals binders
756− r <- bindLocalVariables moduleName (M.toList m1) $ do
757− val' <- TypedValue True <$> check val ret <*> pure ret
758− case grd of
759− Nothing -> return $ CaseAlternative binders Nothing val'
760− Just g -> do
761− g' <- check g tyBoolean
762− return $ CaseAlternative binders (Just g') val'
763− rs <- checkBinders nvals ret bs
764− return $ r : rs
765−
766−-- |
767−-- Generate a new skolem constant
768−--
769−newSkolemConstant :: UnifyT Type Check Int
770−newSkolemConstant = runUnknown <$> fresh'
771−
772−-- |
773−-- Generate a new skolem scope
774−--
775−newSkolemScope :: UnifyT Type Check SkolemScope
776−newSkolemScope = SkolemScope . runUnknown <$> fresh'
777−
778−-- |
779−-- Skolemize a type variable by replacing its instances with fresh skolem constants
780−--
781−skolemize :: String -> Int -> SkolemScope -> Type -> Type
782−skolemize ident sko scope = replaceTypeVars ident (Skolem sko scope)
783−
784−-- |
785−-- Introduce skolem scope at every occurence of a ForAll
786−--
787−introduceSkolemScope :: Type -> UnifyT Type Check Type
788−introduceSkolemScope = everywhereM (mkM go)
789− where
790− go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
791− go other = return other
792−
793−-- |
794−-- Check the type of a value, rethrowing errors to provide a better error message
795−--
796−check :: Value -> Type -> UnifyT Type Check Value
797−check val ty = rethrow (mkErrorStack errorMessage (Just (ValueError val)) <>) $ check' val ty
798− where
799− errorMessage =
800− "Error checking type of term " ++
801− prettyPrintValue val ++
802− " against type " ++
803− prettyPrintType ty
804−
805−-- |
806−-- Check the type of a value
807−--
808−check' :: Value -> Type -> UnifyT Type Check Value
809−check' val (ForAll ident ty _) = do
810− scope <- newSkolemScope
811− sko <- newSkolemConstant
812− let sk = skolemize ident sko scope ty
813− val' <- check val sk
814− return $ TypedValue True val' (ForAll ident ty (Just scope))
815−check' val t@(ConstrainedType constraints ty) = do
816− dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
817− n <- liftCheck freshDictionaryName
818− return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
819− val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
820− TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
821− constraints) $ check val ty
822− return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
823−check' val (SaturatedTypeSynonym name args) = do
824− ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
825− check val ty
826−check' val u@(TUnknown _) = do
827− val'@(TypedValue _ _ ty) <- infer val
828− -- Don't unify an unknown with an inferred polytype
829− (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
830− ty' =?= u
831− return $ TypedValue True val'' ty'
832−check' v@(NumericLiteral _) t | t == tyNumber =
833− return $ TypedValue True v t
834−check' v@(StringLiteral _) t | t == tyString =
835− return $ TypedValue True v t
836−check' v@(BooleanLiteral _) t | t == tyBoolean =
837− return $ TypedValue True v t
838−check' (ArrayLiteral vals) t@(TypeApp a ty) = do
839− a =?= tyArray
840− array <- ArrayLiteral <$> forM vals (`check` ty)
841− return $ TypedValue True array t
842−check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
843− Just moduleName <- checkCurrentModule <$> get
844− ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
845− return $ TypedValue True (Abs (Left arg) ret') ty
846−check' (Abs (Right _) _) _ = error "Binder was not desugared"
847−check' (App f arg) ret = do
848− f'@(TypedValue _ _ ft) <- infer f
849− (_, app) <- checkFunctionApplication f' ft arg (Just ret)
850− return $ TypedValue True app ret
851−check' v@(Var var) ty = do
852− Just moduleName <- checkCurrentModule <$> get
853− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
854− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
855− v' <- subsumes (Just v) repl ty'
856− case v' of
857− Nothing -> throwError . strMsg $ "Unable to check type subsumption"
858− Just v'' -> return $ TypedValue True v'' ty'
859−check' (TypedValue checkType val ty1) ty2 = do
860− Just moduleName <- checkCurrentModule <$> get
861− kind <- liftCheck $ kindOf moduleName ty1
862− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
863− ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
864− val' <- subsumes (Just val) ty1' ty2
865− case val' of
866− Nothing -> throwError . strMsg $ "Unable to check type subsumption"
867− Just val'' -> do
868− val''' <- if checkType then check val'' ty1' else return val''
869− return $ TypedValue checkType (TypedValue True val''' ty1) ty2
870−check' (Case vals binders) ret = do
871− vals' <- mapM infer vals
872− let ts = map (\(TypedValue _ _ t) -> t) vals'
873− binders' <- checkBinders ts ret binders
874− return $ TypedValue True (Case vals' binders') ret
875−check' (IfThenElse cond th el) ty = do
876− cond' <- check cond tyBoolean
877− th' <- check th ty
878− el' <- check el ty
879− return $ TypedValue True (IfThenElse cond' th' el') ty
880−check' (ObjectLiteral ps) t@(TypeApp obj row) | obj == tyObject = do
881− ensureNoDuplicateProperties ps
882− ps' <- checkProperties ps row False
883− return $ TypedValue True (ObjectLiteral ps') t
884−check' (ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
885− ensureNoDuplicateProperties ps
886− us <- zip (map fst ps) <$> replicateM (length ps) fresh
887− let (propsToCheck, rest) = rowToList row
888− propsToRemove = map fst ps
889− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
890− obj' <- check obj (TypeApp tyObject (rowFromList (us ++ remainingProps, rest)))
891− ps' <- checkProperties ps row True
892− return $ TypedValue True (ObjectUpdate obj' ps') t
893−check' (Accessor prop val) ty = do
894− rest <- fresh
895− val' <- check val (TypeApp tyObject (RCons prop ty rest))
896− return $ TypedValue True (Accessor prop val') ty
897−check' (Constructor c) ty = do
898− env <- getEnv
899− case M.lookup c (dataConstructors env) of
900− Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
901− Just (_, ty1) -> do
902− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
903− _ <- subsumes Nothing repl ty
904− return $ TypedValue True (Constructor c) ty
905−check' (Let ds val) ty = do
906− (ds', val') <- inferLetBinding [] ds val (flip check ty)
907− return $ TypedValue True (Let ds' val') ty
908−check' val ty | containsTypeSynonyms ty = do
909− ty' <- introduceSkolemScope <=< expandAllTypeSynonyms $ ty
910− check val ty'
911−check' (PositionedValue pos val) ty =
912− rethrowWithPosition pos $ check val ty
913−check' val ty = throwError $ mkErrorStack ("Value does not have type " ++ prettyPrintType ty) (Just (ValueError val))
914−
915−containsTypeSynonyms :: Type -> Bool
916−containsTypeSynonyms = everything (||) (mkQ False go) where
917− go (SaturatedTypeSynonym _ _) = True
918− go _ = False
919−
920−-- |
921−-- Check the type of a collection of named record fields
922−--
923−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
924−--
925−checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
926−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
927− go [] [] REmpty = return []
928− go [] [] u@(TUnknown _) = do u =?= REmpty
929− return []
930− go [] [] (Skolem _ _) | lax = return []
931− go [] ((p, _): _) _ | lax = return []
932− | otherwise = throwError $ mkErrorStack ("Object does not have property " ++ p) (Just (ValueError (ObjectLiteral ps)))
933− go ((p,_):_) [] REmpty = throwError $ mkErrorStack ("Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row) (Just (ValueError (ObjectLiteral ps)))
934− go ((p,v):ps') [] u@(TUnknown _) = do
935− v'@(TypedValue _ _ ty) <- infer v
936− rest <- fresh
937− u =?= RCons p ty rest
938− ps'' <- go ps' [] rest
939− return $ (p, v') : ps''
940− go ((p,v):ps') ts r =
941− case lookup p ts of
942− Nothing -> do
943− v'@(TypedValue _ _ ty) <- infer v
944− rest <- fresh
945− r =?= RCons p ty rest
946− ps'' <- go ps' ts rest
947− return $ (p, v') : ps''
948− Just ty -> do
949− v' <- check v ty
950− ps'' <- go ps' (delete (p, ty) ts) r
951− return $ (p, v') : ps''
952− go _ _ _ = throwError $ mkErrorStack ("Object does not have type " ++ prettyPrintType (TypeApp tyObject row)) (Just (ValueError (ObjectLiteral ps)))
953−
954−-- |
955−-- Check the type of a function application, rethrowing errors to provide a better error message
956−--
957−checkFunctionApplication :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
958−checkFunctionApplication fn fnTy arg ret = rethrow (mkErrorStack errorMessage (Just (ValueError fn)) <>) $ checkFunctionApplication' fn fnTy arg ret
959− where
960− errorMessage = "Error applying function of type "
961− ++ prettyPrintType fnTy
962− ++ " to argument " ++ prettyPrintValue arg
963−
964−-- |
965−-- Check the type of a function application
966−--
967−checkFunctionApplication' :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
968−checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
969− tyFunction' =?= tyFunction
970− _ <- maybe (return Nothing) (subsumes Nothing retTy) ret
971− subst <- unifyCurrentSubstitution <$> UnifyT get
972− arg' <- check arg (subst $? argTy)
973− return (retTy, App fn arg')
974−checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
975− replaced <- replaceVarWithUnknown ident ty
976− checkFunctionApplication fn replaced arg ret
977−checkFunctionApplication' fn u@(TUnknown _) arg ret = do
978− arg' <- do
979− TypedValue _ arg' t <- infer arg
980− (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
981− return $ TypedValue True arg'' t'
982− let ty = (\(TypedValue _ _ t) -> t) arg'
983− ret' <- maybe fresh return ret
984− u =?= function ty ret'
985− return (ret', App fn arg')
986−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
987− ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
988− checkFunctionApplication fn ty arg ret
989−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
990− dicts <- getTypeClassDictionaries
991− checkFunctionApplication' (foldl App fn (map (flip (TypeClassDictionary True) (Just dicts)) constraints)) fnTy arg ret
992−checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
993− ++ prettyPrintType fnTy
994− ++ " to argument " ++ prettyPrintValue arg
995−
996−-- |
997−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
998−--
999−subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
1000−subsumes val ty1 ty2 = rethrow (mkErrorStack errorMessage (ValueError <$> val) <>) $ subsumes' val ty1 ty2
1001− where
1002− errorMessage = "Error checking that type "
1003− ++ prettyPrintType ty1
1004− ++ " subsumes type "
1005− ++ prettyPrintType ty2
1006−
1007−-- |
1008−-- Check whether one type subsumes another
1009−--
1010−subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
1011−subsumes' val (ForAll ident ty1 _) ty2 = do
1012− replaced <- replaceVarWithUnknown ident ty1
1013− subsumes val replaced ty2
1014−subsumes' val ty1 (ForAll ident ty2 sco) =
1015− case sco of
1016− Just sco' -> do
1017− sko <- newSkolemConstant
1018− let sk = skolemize ident sko sco' ty2
1019− subsumes val ty1 sk
1020− Nothing -> throwError . strMsg $ "Skolem variable scope is unspecified"
1021−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
1022− _ <- subsumes Nothing arg2 arg1
1023− _ <- subsumes Nothing ret1 ret2
1024− return val
1025−subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
1026− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1027− subsumes val ty1 ty2
1028−subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
1029− ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1030− subsumes val ty1 ty2
1031−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
1032− dicts <- getTypeClassDictionaries
1033− _ <- subsumes' Nothing ty1 ty2
1034− return . Just $ foldl App val (map (flip (TypeClassDictionary True) (Just dicts)) constraints)
1035−subsumes' val (TypeApp f1 r1) (TypeApp f2 r2) | f1 == tyObject && f2 == tyObject = do
1036− let
1037− (ts1, r1') = rowToList r1
1038− (ts2, r2') = rowToList r2
1039− ts1' = sortBy (comparing fst) ts1
1040− ts2' = sortBy (comparing fst) ts2
1041− go ts1' ts2' r1' r2'
1042− return val
1043− where
1044− go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
1045− go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
1046− go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
1047− | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
1048− go ts1 ts2 r1' r2'
1049− | p1 < p2 = do rest <- fresh
1050− r2' =?= RCons p1 ty1 rest
1051− go ts1 ((p2, ty2) : ts2) r1' rest
1052− | otherwise = do rest <- fresh
1053− r1' =?= RCons p2 ty2 rest
1054− go ((p1, ty1) : ts1) ts2 rest r2'
1055−subsumes' val ty1 ty2@(TypeApp obj _) | obj == tyObject = subsumes val ty2 ty1
1056−subsumes' val ty1 ty2 = do
1057− ty1 =?= ty2
1058− return val
1059−
1060−
1061−
src/Language/PureScript/TypeClassDictionaries.hsdeleted−62
@@ -1,62 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.TypeClassDictionaries
4−-- Copyright : (c) 2014 Phil Freeman
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−--
13−-----------------------------------------------------------------------------
14−
15−{-# LANGUAGE DeriveDataTypeable #-}
16−
17−module Language.PureScript.TypeClassDictionaries where
18−
19−import Data.Data
20−
21−import Language.PureScript.Names
22−import Language.PureScript.Types
23−
24−-- |
25−-- Data representing a type class dictionary which is in scope
26−--
27−data TypeClassDictionaryInScope
28− = TypeClassDictionaryInScope {
29− -- |
30− -- The identifier with which the dictionary can be accessed at runtime
31− --
32− tcdName :: Qualified Ident
33− -- |
34− -- The name of the type class to which this type class instance applies
35− --
36− , tcdClassName :: Qualified ProperName
37− -- |
38− -- The types to which this type class instance applies
39− --
40− , tcdInstanceTypes :: [Type]
41− -- |
42− -- Type class dependencies which must be satisfied to construct this dictionary
43− --
44− , tcdDependencies :: Maybe [(Qualified ProperName, [Type])]
45− -- |
46− -- The type of this dictionary
47− --
48− , tcdType :: TypeClassDictionaryType
49− } deriving (Show, Data, Typeable)
50−
51−-- |
52−-- The type of a type class dictionary
53−--
54−data TypeClassDictionaryType
55− -- |
56− -- A regular type class dictionary
57− --
58− = TCDRegular
59− -- |
60− -- A type class dictionary which is an alias for an imported dictionary from another module
61− --
62− | TCDAlias (Qualified Ident) deriving (Show, Eq, Data, Typeable)
src/Language/PureScript/Types.hsdeleted−184
@@ -1,184 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.Types
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- Data types for types
13−--
14−-----------------------------------------------------------------------------
15−
16−{-# LANGUAGE DeriveDataTypeable #-}
17−
18−module Language.PureScript.Types where
19−
20−import Data.Data
21−import Data.List (nub)
22−import Data.Generics (everything, mkQ)
23−
24−import Control.Monad.Unify
25−import Control.Arrow (second)
26−
27−import Language.PureScript.Names
28−
29−-- |
30−-- An identifier for the scope of a skolem variable
31−--
32−newtype SkolemScope = SkolemScope { runSkolemScope :: Int } deriving (Show, Eq, Ord, Data, Typeable)
33−
34−-- |
35−-- The type of types
36−--
37−data Type
38− -- |
39− -- A unification variable of type Type
40− --
41− = TUnknown Unknown
42− -- |
43− -- A named type variable
44− --
45− | TypeVar String
46− -- |
47− -- A type constructor
48− --
49− | TypeConstructor (Qualified ProperName)
50− -- |
51− -- A type application
52− --
53− | TypeApp Type Type
54− -- |
55− -- A type synonym which is \"saturated\", i.e. fully applied
56− --
57− | SaturatedTypeSynonym (Qualified ProperName) [Type]
58− -- |
59− -- Forall quantifier
60− --
61− | ForAll String Type (Maybe SkolemScope)
62− -- |
63− -- A type with a set of type class constraints
64− --
65− | ConstrainedType [(Qualified ProperName, [Type])] Type
66− -- |
67− -- A skolem constant
68− --
69− | Skolem Int SkolemScope
70− -- |
71− -- An empty row
72− --
73− | REmpty
74− -- |
75− -- A non-empty row
76− --
77− | RCons String Type Type
78− -- |
79− -- A placeholder used in pretty printing
80− --
81− | PrettyPrintFunction Type Type
82− -- |
83− -- A placeholder used in pretty printing
84− --
85− | PrettyPrintArray Type
86− -- |
87− -- A placeholder used in pretty printing
88− --
89− | PrettyPrintObject Type
90− -- |
91− -- A placeholder used in pretty printing
92− --
93− | PrettyPrintForAll [String] Type deriving (Show, Eq, Data, Typeable)
94−
95−-- |
96−-- Convert a row to a list of pairs of labels and types
97−--
98−rowToList :: Type -> ([(String, Type)], Type)
99−rowToList (RCons name ty row) = let (tys, rest) = rowToList row
100− in ((name, ty):tys, rest)
101−rowToList r = ([], r)
102−
103−-- |
104−-- Convert a list of labels and types to a row
105−--
106−rowFromList :: ([(String, Type)], Type) -> Type
107−rowFromList ([], r) = r
108−rowFromList ((name, t):ts, r) = RCons name t (rowFromList (ts, r))
109−
110−-- |
111−-- Check whether a type is a monotype
112−--
113−isMonoType :: Type -> Bool
114−isMonoType ForAll{} = False
115−isMonoType _ = True
116−
117−-- |
118−-- Universally quantify a type
119−--
120−mkForAll :: [String] -> Type -> Type
121−mkForAll args ty = foldl (\t arg -> ForAll arg t Nothing) ty args
122−
123−-- |
124−-- Replace a type variable, taking into account variable shadowing
125−--
126−replaceTypeVars :: String -> Type -> Type -> Type
127−replaceTypeVars = replaceTypeVars' []
128− where
129− replaceTypeVars' bound name replacement = go bound
130− where
131− go :: [String] -> Type -> Type
132− go _ (TypeVar v) | v == name = replacement
133− go bs (TypeApp t1 t2) = TypeApp (go bs t1) (go bs t2)
134− go bs (SaturatedTypeSynonym name' ts) = SaturatedTypeSynonym name' $ map (go bs) ts
135− go bs f@(ForAll v t sco) | v == name = f
136− | v `elem` usedTypeVariables replacement =
137− let v' = genName v (name : bs ++ usedTypeVariables replacement)
138− t' = replaceTypeVars' bs v (TypeVar v') t
139− in ForAll v' (go (v' : bs) t') sco
140− | otherwise = ForAll v (go (v : bs) t) sco
141− go bs (ConstrainedType cs t) = ConstrainedType (map (second $ map (go bs)) cs) (go bs t)
142− go bs (RCons name' t r) = RCons name' (go bs t) (go bs r)
143− go _ ty = ty
144− genName orig inUse = try 0
145− where
146− try :: Integer -> String
147− try n | (orig ++ show n) `elem` inUse = try (n + 1)
148− | otherwise = orig ++ show n
149−
150−-- |
151−-- Replace named type variables with types
152−--
153−replaceAllTypeVars :: [(String, Type)] -> Type -> Type
154−replaceAllTypeVars = foldl (\f (name, ty) -> replaceTypeVars name ty . f) id
155−
156−-- |
157−-- Collect all type variables appearing in a type
158−--
159−usedTypeVariables :: Type -> [String]
160−usedTypeVariables = nub . everything (++) (mkQ [] go)
161− where
162− go (TypeVar v) = [v]
163− go _ = []
164−
165−-- |
166−-- Collect all free type variables appearing in a type
167−--
168−freeTypeVariables :: Type -> [String]
169−freeTypeVariables = nub . go []
170− where
171− go :: [String] -> Type -> [String]
172− go bound (TypeVar v) | v `notElem` bound = [v]
173− go bound (TypeApp t1 t2) = go bound t1 ++ go bound t2
174− go bound (SaturatedTypeSynonym _ ts) = concatMap (go bound) ts
175− go bound (ForAll v t _) = go (v : bound) t
176− go bound (ConstrainedType cs t) = concatMap (concatMap (go bound) . snd) cs ++ go bound t
177− go bound (RCons _ t r) = go bound t ++ go bound r
178− go _ _ = []
179−
180−-- |
181−-- Universally quantify over all type variables appearing free in a type
182−--
183−quantify :: Type -> Type
184−quantify ty = foldr (\arg t -> ForAll arg t Nothing) ty $ freeTypeVariables ty
src/Tests.hsnew file+141
@@ -0,0 +1,141 @@
1+module Tests (runTests) where
2+
3+import Prelude.Compat
4+import Data.List
5+import Control.Applicative
6+import Control.Monad
7+
8+import System.Process
9+import System.FilePath
10+import System.IO
11+import System.Directory
12+
13+-------------------------------------------------------------------------------
14+testsDir :: IO (FilePath, FilePath)
15+-------------------------------------------------------------------------------
16+testsDir = do
17+ baseDir <- getCurrentDirectory
18+ return (baseDir </> "purescript-tests", baseDir)
19+
20+-------------------------------------------------------------------------------
21+runTests :: IO ()
22+-------------------------------------------------------------------------------
23+runTests = do
24+
25+ (outputDir, baseDir) <- testsDir
26+
27+ outputDirExists <- doesDirectoryExist outputDir
28+ when outputDirExists $ removeDirectoryRecursive outputDir
29+ createDirectory outputDir
30+
31+ let srcDir = outputDir </> "src"
32+ createDirectory srcDir
33+
34+ callProcess "git" ["clone", "--branch", "v0.13.8", "--depth", "1", "https://github.com/purescript/purescript.git"]
35+ let passingDir = baseDir </> "purescript" </> "tests" </> "purs" </> "passing"
36+ passingTestCases <- sort . filter (".purs" `isSuffixOf`) <$> getDirectoryContents passingDir
37+
38+ setCurrentDirectory outputDir
39+
40+ fetchPackages
41+
42+ let tests = filter (`notElem` skipped) passingTestCases
43+
44+ tmp <- getTemporaryDirectory
45+ createDirectoryIfMissing False (tmp </> logpath)
46+ outputFile <- openFile (tmp </> logpath </> logfile) WriteMode
47+ hClose outputFile
48+
49+ -- Run the tests
50+ --
51+ forM_ tests $ \inputFile -> do
52+ --
53+ -- Compile/build
54+ --
55+ putStrLn $ "Compiling test " ++ inputFile ++ " ..."
56+ setCurrentDirectory outputDir
57+ copyFile (passingDir </> inputFile) (srcDir </> inputFile)
58+
59+ let testCaseDir = passingDir </> (takeWhile (/='.') inputFile)
60+ testCaseDirExists <- doesDirectoryExist testCaseDir
61+ when testCaseDirExists $ callProcess "cp" ["-R", testCaseDir, srcDir]
62+
63+ callProcess "rm" ["-rf", "output"]
64+ callProcess "rm" ["-rf", "Main"]
65+ callProcess "spago" ["build"]
66+ --
67+ -- Run executable file
68+ --
69+ outputFile <- openFile (tmp </> logpath </> logfile) AppendMode
70+ hPutStrLn outputFile ("\n" ++ inputFile ++ ":")
71+ proc <- runProcess ("./" </> "Main") [] Nothing Nothing Nothing (Just outputFile) Nothing
72+
73+ removeFile (srcDir </> inputFile)
74+ when testCaseDirExists $ callProcess "rm" ["-rf", srcDir </> (takeWhile (/='.') inputFile)]
75+
76+ -- TODO: support failing test cases
77+ --
78+ -- let failing = baseDir </> "examples" </> "failing"
79+ -- failingTestCases <- sort . filter (".purs" `isSuffixOf`) <$> getDirectoryContents failing
80+ --
81+
82+ setCurrentDirectory baseDir
83+ putStrLn "PureScript tests finished"
84+ putStrLn $ "Total tests available: " ++ show (length passingTestCases)
85+ putStrLn $ "Tests run: " ++ show (length tests)
86+ putStrLn $ "Tests skipped: " ++ show (length skipped)
87+
88+-------------------------------------------------------------------------------
89+packages :: [String]
90+-------------------------------------------------------------------------------
91+packages =
92+ [ "arrays"
93+ , "assert"
94+ , "console"
95+ , "control"
96+ , "effect"
97+ , "foldable-traversable"
98+ , "functions"
99+ , "generics-rep"
100+ , "invariant"
101+ , "newtype"
102+ , "partial"
103+ , "prelude"
104+ , "proxy"
105+ , "refs"
106+ , "st"
107+ , "type-equality"
108+ , "typelevel-prelude"
109+ ]
110+
111+-------------------------------------------------------------------------------
112+fetchPackages :: IO ()
113+-------------------------------------------------------------------------------
114+fetchPackages = do
115+ callProcess "spago" ["init"]
116+ callCommand "sed '$s/\\(}\\)/, backend = \"psgo\"\\1/' < spago.dhall | dhall format > spago.tmp"
117+ callCommand "mv spago.tmp spago.dhall"
118+
119+ mapM (callProcess "spago" . (\p -> ["install", p])) packages
120+ return ()
121+
122+-------------------------------------------------------------------------------
123+skipped :: [String]
124+-------------------------------------------------------------------------------
125+skipped =
126+ [ "2172.purs" -- foreign in Main needed (test manually)
127+ , "EffFn.purs" -- foreign in Main needed (test manually)
128+ , "FunWithFunDeps.purs" -- foreign in Main needed (test manually)
129+ , "NumberLiterals.purs" -- unreliable float string comparison (test manually)
130+ , "PolyLabels.purs" -- foreign in Main needed (test manually)
131+ , "RowUnion.purs" -- foreign in Main needed (test manually)
132+ , "ShadowedModuleName.purs" -- ?
133+ , "StringEdgeCases.purs" -- javascript char encoding specific
134+ , "StringEscapes.purs" -- Partially javascript-char-encoding-specific (test manually)
135+ ]
136+
137+logpath :: FilePath
138+logpath = "purescript-output"
139+
140+logfile :: FilePath
141+logfile = "purescript-tests.out"
stack.nixnew file+23
@@ -0,0 +1,23 @@
1+#
2+# You may need to manually run `unset STACK_IN_NIX_SHELL`
3+# (doesn't work from a `shellHook`; see: https://github.com/commercialhaskell/stack/issues/5000
4+#
5+#
6+# You may need to set LC_ALL when building, e.g.
7+# LC_ALL=en_US.iso88591 stack --nix build; see e.g. https://github.com/koalaman/shellcheck/issues/324
8+#
9+#
10+{ pkgs ?
11+ import (builtins.fetchTarball {
12+ name = "nixos-release-19.03";
13+ url = https://github.com/nixos/nixpkgs/archive/34c7eb7545d155cc5b6f499b23a7cb1c96ab4d59.tar.gz;
14+ sha256 = "11z6ajj108fy2q5g8y4higlcaqncrbjm3dnv17pvif6avagw4mcb";
15+ }) {}
16+}:
17+
18+pkgs.haskell.lib.buildStackProject {
19+ name = "default-stack-shell";
20+ ghc = pkgs.haskell.compiler.ghc865;
21+ buildInputs = with pkgs; [git git-lfs gmp ncurses zlib];
22+ LANG = "en_US.UTF-8";
23+}
stack.yamlnew file+24
@@ -0,0 +1,24 @@
1+resolver: lts-13.26
2+
3+packages:
4+- .
5+
6+extra-deps:
7+- git: https://github.com/purescript/purescript
8+ commit: 9cad73ed8ea7df3011032ddbd2f3de5a0c08629c
9+- happy-1.19.9
10+- language-javascript-0.7.0.0
11+- network-3.0.1.1
12+- these-1.0.1
13+- semialign-1
14+
15+nix:
16+ enable: false
17+ shell-file: stack.nix
18+
19+flags:
20+ aeson-pretty:
21+ lib-only: true
22+ these:
23+ assoc: false
24+ quickcheck: false
support/ffi-loader.gonew file+30
@@ -0,0 +1,30 @@
1+package ffi_loader
2+
3+// Load PureScript standard library FFI packages. Comment out the ones you don't need for
4+// faster/smaller builds.
5+
6+import (
7+ _ "github.com/purescript-native/go-ffi/purescript-arrays"
8+ _ "github.com/purescript-native/go-ffi/purescript-assert"
9+ _ "github.com/purescript-native/go-ffi/purescript-console"
10+ _ "github.com/purescript-native/go-ffi/purescript-effect"
11+ _ "github.com/purescript-native/go-ffi/purescript-enums"
12+ _ "github.com/purescript-native/go-ffi/purescript-exceptions"
13+ _ "github.com/purescript-native/go-ffi/purescript-foldable-traversable"
14+ _ "github.com/purescript-native/go-ffi/purescript-functions"
15+ _ "github.com/purescript-native/go-ffi/purescript-globals"
16+ _ "github.com/purescript-native/go-ffi/purescript-integers"
17+ _ "github.com/purescript-native/go-ffi/purescript-lazy"
18+ _ "github.com/purescript-native/go-ffi/purescript-math"
19+ _ "github.com/purescript-native/go-ffi/purescript-partial"
20+ _ "github.com/purescript-native/go-ffi/purescript-prelude"
21+ _ "github.com/purescript-native/go-ffi/purescript-random"
22+ _ "github.com/purescript-native/go-ffi/purescript-refs"
23+ _ "github.com/purescript-native/go-ffi/purescript-st"
24+ _ "github.com/purescript-native/go-ffi/purescript-strings"
25+ _ "github.com/purescript-native/go-ffi/purescript-unfoldable"
26+)
27+
28+// Add your own FFI packages here.
29+
30+import ()
support/go.mod.ffi-loadernew file+2
@@ -0,0 +1,2 @@
1+module $PROJECT/purescript-native/ffi-loader
2+
support/go.mod.outputnew file+2
@@ -0,0 +1,2 @@
1+module $PROJECT/purescript-native/output
2+
support/go.mod.workingnew file+1
@@ -0,0 +1 @@
1+module $PROJECT/example
test/Spec.hsnew file+2
@@ -0,0 +1,2 @@
1+main :: IO ()
2+main = putStrLn "Test suite not yet implemented"
tests/Main.hsdeleted−103
@@ -1,103 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Main
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−--
13−-----------------------------------------------------------------------------
14−
15−{-# LANGUAGE DoAndIfThenElse #-}
16−
17−module Main (main) where
18−
19−import qualified Language.PureScript as P
20−
21−import Data.List (isSuffixOf)
22−import Data.Traversable (traverse)
23−import Control.Monad
24−import Control.Monad.Trans.Maybe (MaybeT(..), runMaybeT)
25−import System.Exit
26−import System.Process
27−import System.FilePath (pathSeparator)
28−import System.Directory (getCurrentDirectory, getTemporaryDirectory, getDirectoryContents, findExecutable)
29−import Text.Parsec (ParseError)
30−import qualified Paths_purescript as Paths
31−import qualified System.IO.UTF8 as U
32−
33−preludeFilename :: IO FilePath
34−preludeFilename = Paths.getDataFileName "prelude/prelude.purs"
35−
36−readInput :: [FilePath] -> IO (Either ParseError [P.Module])
37−readInput inputFiles = fmap (fmap concat . sequence) $ forM inputFiles $ \inputFile -> do
38− text <- U.readFile inputFile
39− return $ P.runIndentParser inputFile P.parseModules text
40−
41−compile :: P.Options -> [FilePath] -> IO (Either String (String, String, P.Environment))
42−compile opts inputFiles = do
43− modules <- readInput inputFiles
44− case modules of
45− Left parseError ->
46− return (Left $ show parseError)
47− Right ms -> return $ P.compile opts ms
48−
49−assert :: FilePath -> P.Options -> FilePath -> (Either String (String, String, P.Environment) -> IO (Maybe String)) -> IO ()
50−assert preludeExterns opts inputFile f = do
51− e <- compile opts [preludeExterns, inputFile]
52− maybeErr <- f e
53− case maybeErr of
54− Just err -> putStrLn err >> exitFailure
55− Nothing -> return ()
56−
57−assertCompiles :: FilePath -> FilePath -> FilePath -> IO ()
58−assertCompiles preludeJs preludeExterns inputFile = do
59− putStrLn $ "Assert " ++ inputFile ++ " compiles successfully"
60− let options = P.defaultOptions { P.optionsMain = Just "Main", P.optionsModules = ["Main"], P.optionsCodeGenModules = ["Main"] }
61− assert preludeExterns options inputFile $ either (return . Just) $ \(js, _, _) -> do
62− process <- findNodeProcess
63− result <- traverse (\node -> readProcessWithExitCode node [] (preludeJs ++ js)) process
64− case result of
65− Just (ExitSuccess, out, _) -> putStrLn out >> return Nothing
66− Just (ExitFailure _, _, err) -> return $ Just err
67− Nothing -> return $ Just "Couldn't find node.js executable"
68−
69−assertDoesNotCompile :: FilePath -> FilePath -> IO ()
70−assertDoesNotCompile preludeExterns inputFile = do
71− putStrLn $ "Assert " ++ inputFile ++ " does not compile"
72− assert preludeExterns P.defaultOptions inputFile $ \e ->
73− case e of
74− Left _ -> return Nothing
75− Right _ -> return $ Just "Should not have compiled"
76−
77−findNodeProcess :: IO (Maybe String)
78−findNodeProcess = runMaybeT . msum $ map (MaybeT . findExecutable) names
79− where names = ["nodejs", "node"]
80−
81−main :: IO ()
82−main = do
83− prelude <- preludeFilename
84− putStrLn "Compiling Prelude"
85− preludeResult <- compile P.defaultOptions [prelude]
86− case preludeResult of
87− Left err -> putStrLn err >> exitFailure
88− Right (preludeJs, exts, _) -> do
89− tmp <- getTemporaryDirectory
90− let preludeExterns = tmp ++ pathSeparator : "prelude.externs"
91− writeFile preludeExterns exts
92− putStrLn $ "Wrote " ++ preludeExterns
93− cd <- getCurrentDirectory
94− let examples = cd ++ pathSeparator : "examples"
95− let passing = examples ++ pathSeparator : "passing"
96− passingTestCases <- getDirectoryContents passing
97− forM_ passingTestCases $ \inputFile -> when (".purs" `isSuffixOf` inputFile) $
98− assertCompiles preludeJs preludeExterns (passing ++ pathSeparator : inputFile)
99− let failing = examples ++ pathSeparator : "failing"
100− failingTestCases <- getDirectoryContents failing
101− forM_ failingTestCases $ \inputFile -> when (".purs" `isSuffixOf` inputFile) $
102− assertDoesNotCompile preludeExterns (failing ++ pathSeparator : inputFile)
103− exitSuccess