git.iko.soy/rowtype-yoga/purescript-native
on 3339928 help sign in
220 files changed+14913−2723
since splitsnapshots
unifiedsplit
.gitignore−13 .travis.yml+3 CONTRIBUTING.md+16 ChangeLog.md−3 LICENSE+16−26 README-go.md−48 README.md+10−38 RELEASE-0.2.md+85 RELEASE-0.3.md+85 RELEASE-0.4.md+60 RELEASE-0.5.md+57 Setup.hs+37−1 app/Main.hs−250 default.nix−23 docgen/Main.hs+178 docs/.gitignore+1 docs/Makefile+177 docs/source/conf.py+258 docs/source/ffi.rst+31 docs/source/index.rst+30 docs/source/intro.rst+145 docs/source/kinds.rst+21 docs/source/modules.rst+29 docs/source/patterns.rst+139 docs/source/prelude.rst+904 docs/source/syntax.rst+217 docs/source/typeclasses.rst+26 docs/source/types.rst+159 examples/.gitignore+1 examples/failing/Arrays.purs+5 examples/failing/Do.purs+8 examples/failing/ExportExplicit.purs+16 examples/failing/ExportExplicit2.purs+13 examples/failing/ExportExplicit3.purs+5 examples/failing/ExportExplicit4.purs+14 examples/failing/ExportExplicit5.purs+5 examples/failing/ExportExplicit6.purs+13 examples/failing/Import.purs+3 examples/failing/ImportExplicit.purs+14 examples/failing/ImportExplicit2.purs+7 examples/failing/ImportExplicit3.purs+7 examples/failing/ImportModule.purs+7 examples/failing/KindError.purs+3 examples/failing/MPTCs.purs+7 examples/failing/ModuleDeps.purs+7 examples/failing/MutRec.purs+5 examples/failing/MutRec2.purs+3 examples/failing/NullaryAbs.purs+3 examples/failing/Object.purs+5 examples/failing/OverlappingVars.purs+12 examples/failing/Rank2Types.purs+7 examples/failing/ReadShow.purs+7 examples/failing/Reserved.purs+4 examples/failing/SkolemEscape.purs+5 examples/failing/SkolemEscape2.purs+9 examples/failing/TypeClassInstances.purs+8 examples/failing/TypeClasses.purs+7 examples/failing/TypeClasses2.purs+15 examples/failing/TypeError.purs+5 examples/failing/TypeSynonyms.purs+5 examples/failing/TypeSynonyms2.purs+9 examples/failing/TypeSynonyms3.purs+13 examples/passing/Applicative.purs+16 examples/passing/ArrayType.purs+17 examples/passing/Arrays.purs+34 examples/passing/Auto.purs+15 examples/passing/BindersInFunctions.purs+12 examples/passing/Church.purs+18 examples/passing/Collatz.purs+18 examples/passing/Conditional.purs+9 examples/passing/Cons.purs+12 examples/passing/Console.purs+13 examples/passing/DataAndType.purs+9 examples/passing/DataImport.purs+13 examples/passing/Do.purs+49 examples/passing/Dollar.purs+16 examples/passing/DottedModules.purs+20 examples/passing/Eff.purs+27 examples/passing/EmptyDataDecls.purs+20 examples/passing/EmptyTypeClass.purs+18 examples/passing/ExportExplicit.purs+20 examples/passing/ExportExplicit2.purs+15 examples/passing/ExternData.purs+19 examples/passing/ExternRaw.purs+15 examples/passing/FFI.purs+16 examples/passing/FinalTagless.purs+22 examples/passing/Foldable.purs+19 examples/passing/ForeignInstance.purs+23 examples/passing/FunctionScope.purs+17 examples/passing/Functions.purs+17 examples/passing/Functions2.purs+17 examples/passing/Guards.purs+16 examples/passing/Import.purs+16 examples/passing/ImportExplicit.purs+14 examples/passing/InferRecFunWithConstrainedArgument.purs+8 examples/passing/JSReserved.purs+21 examples/passing/Let.purs+26 examples/passing/List.purs+10 examples/passing/MPTCs.purs+24 examples/passing/Match.purs+9 examples/passing/Math.purs+10 examples/passing/Maybe.purs+12 examples/passing/Module.purs+28 examples/passing/ModuleDeps.purs+17 examples/passing/Monad.purs+32 examples/passing/MonadState.purs+35 examples/passing/MultipleConstructorArgs.purs+28 examples/passing/MutRec.purs+21 examples/passing/NamedPatterns.purs+9 examples/passing/Nested.purs+9 examples/passing/NestedTypeSynonyms.purs+13 examples/passing/ObjectSynonym.purs+15 examples/passing/ObjectUpdate.purs+22 examples/passing/Objects.purs+20 examples/passing/OneConstructor.purs+9 examples/passing/Operators.purs+86 examples/passing/OptimizerBug.purs+11 examples/passing/Patterns.purs+30 examples/passing/Person.purs+15 examples/passing/Rank2Data.purs+31 examples/passing/Rank2Types.purs+25 examples/passing/Recursion.purs+12 examples/passing/RedefinedFixity.purs+18 examples/passing/RuntimeScopeIssue.purs+25 examples/passing/STArray.purs+23 examples/passing/TailCall.purs+20 examples/passing/Tick.purs+7 examples/passing/TopLevelCase.purs+20 examples/passing/Traversable.purs+8 examples/passing/TypeClasses.purs+69 examples/passing/TypeClassesInOrder.purs+11 examples/passing/TypeClassesWithOverlappingTypeVariables.purs+10 examples/passing/TypeDecl.purs+14 examples/passing/TypeSynonymInData.purs+9 examples/passing/TypeSynonyms.purs+40 examples/passing/iota.purs+11 examples/passing/s.purs+7 package.yaml−86 prelude/README.md+798 prelude/prelude.purs+1368 prelude/tests/.gitignore+1 prelude/tests/Eff.purs+60 prelude/tests/build.sh+2 prelude/updateDocs.sh+2 psc/Main.hs+128 psci/Commands.hs+68 psci/Main.hs+329 psci/Parser.hs+92 psgo.cabal−145 purescript.cabal+124 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+81 src/Language/PureScript/CodeGen.hs+25 src/Language/PureScript/CodeGen/Common.hs+134 src/Language/PureScript/CodeGen/Externs.hs+91 src/Language/PureScript/CodeGen/JS.hs+332 src/Language/PureScript/CodeGen/JS/AST.hs+237 src/Language/PureScript/CodeGen/Monad.hs+43 src/Language/PureScript/Constants.hs+192 src/Language/PureScript/DeadCodeElimination.hs+98 src/Language/PureScript/Declarations.hs+190 src/Language/PureScript/Environment.hs+188 src/Language/PureScript/Kinds.hs+46 src/Language/PureScript/ModuleDependencies.hs+62 src/Language/PureScript/Names.hs+98 src/Language/PureScript/Optimizer.hs+75 src/Language/PureScript/Optimizer/Blocks.hs+35 src/Language/PureScript/Optimizer/Common.hs+78 src/Language/PureScript/Optimizer/Inliner.hs+153 src/Language/PureScript/Optimizer/MagicDo.hs+167 src/Language/PureScript/Optimizer/TCO.hs+102 src/Language/PureScript/Optimizer/Unused.hs+31 src/Language/PureScript/Options.hs+58 src/Language/PureScript/Parser.hs+35 src/Language/PureScript/Parser/Common.hs+370 src/Language/PureScript/Parser/Declarations.hs+170 src/Language/PureScript/Parser/Kinds.hs+45 src/Language/PureScript/Parser/State.hs+30 src/Language/PureScript/Parser/Types.hs+128 src/Language/PureScript/Parser/Values.hs+246 src/Language/PureScript/Pretty.hs+32 src/Language/PureScript/Pretty/Common.hs+22 src/Language/PureScript/Pretty/JS.hs+259 src/Language/PureScript/Pretty/Kinds.hs+60 src/Language/PureScript/Pretty/Types.hs+122 src/Language/PureScript/Pretty/Values.hs+150 src/Language/PureScript/Scope.hs+62 src/Language/PureScript/Sugar.hs+59 src/Language/PureScript/Sugar/BindingGroups.hs+128 src/Language/PureScript/Sugar/CaseDeclarations.hs+97 src/Language/PureScript/Sugar/DoNotation.hs+62 src/Language/PureScript/Sugar/Let.hs+34 src/Language/PureScript/Sugar/Names.hs+420 src/Language/PureScript/Sugar/Operators.hs+118 src/Language/PureScript/Sugar/TypeClasses.hs+165 src/Language/PureScript/Sugar/TypeDeclarations.hs+43 src/Language/PureScript/TypeChecker.hs+198 src/Language/PureScript/TypeChecker/Kinds.hs+166 src/Language/PureScript/TypeChecker/Monad.hs+202 src/Language/PureScript/TypeChecker/Synonyms.hs+59 src/Language/PureScript/TypeChecker/Types.hs+929 src/Language/PureScript/Types.hs+192 src/Language/PureScript/Values.hs+247 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+99
.gitignore−13
@@ -8,16 +8,3 @@ 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.ymlnew file+3
@@ -0,0 +1,3 @@
1+language: haskell
2+notifications:
3+ email: true
CONTRIBUTING.mdnew file+16
@@ -0,0 +1,16 @@
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.mddeleted−3
@@ -1,3 +0,0 @@
1−# Changelog for pscpp
2−
3−## Unreleased changes
LICENSE+16−26
@@ -1,30 +1,20 @@
1−Copyright Andy Arvanitis (c) 2018
1+The MIT License (MIT)
22
3−All rights reserved.
3+Copyright (c) 2013 Phil Freeman
44
5−Redistribution and use in source and binary forms, with or without
6−modification, are permitted provided that the following conditions are met:
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:
711
8− * Redistributions of source code must retain the above copyright
9− notice, this list of conditions and the following disclaimer.
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
1014
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.
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.
README-go.mddeleted−48
@@ -1,48 +0,0 @@
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+10−38
@@ -1,41 +1,13 @@
1−[![PureScript](https://raw.githubusercontent.com/purescript/purescript/master/logo.png)](http://purescript.org)
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)
23
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.
4+PureScript is a small strongly, statically typed programming language with expressive types, written in and inspired by Haskell, and compiling to Javascript.
45
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).
6+## Resources
67
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−---
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)
RELEASE-0.2.mdnew file+85
@@ -0,0 +1,85 @@
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.mdnew file+85
@@ -0,0 +1,85 @@
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.mdnew file+60
@@ -0,0 +1,60 @@
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.mdnew file+57
@@ -0,0 +1,57 @@
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+
14+### New Features
15+
16+- `let ... in` syntax for bindings (paf31)
17+- Multi parameter typeclasses (paf31)
18+- Empty data declarations and empty type classes are now supported (paf31)
19+
20+### Enhancements
21+
22+- Pretty printing for row types was improved (garyb)
23+- Module names can now contain `.` (garyb)
24+- 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)
25+- Pattern binders are now usable in lambda expression arguments (paf31)
26+- PSCI now has a `:t` command for checking the type of a value (paf31)
27+- Array pretty printing via `show` has been improved (joneshf)
28+- PSCI completions are sorted (joneshf)
29+- PSCI now has help commands (joneshf)
30+- PSCI history is in XDG config (joneshf)
31+- PSCI allows loading of modules from ~ paths (joneshf)
32+- PSCI can accept a list of modules to load on start from the command line (paf31)
33+- Type class instances are now named, to enable easier interop with Javascript (paf31)
34+- Class names no longer need to be qualified in instance declarations (garyb)
35+- Module exports can now be specified explicitly (garyb)
36+- Let bindings can now define functions with binders (paf31)
37+- Case statements and functions which do not pattern match on their arguments now generate smaller code (paf31)
38+
39+### Bug Fixes
40+
41+- The subsumes relation has been fixed for object types (paf31)
42+- `sort` no longer mutates arrays (joneshf)
43+- PSCI now evaluates expressions (joneshf)
44+- Overlapping variables in typeclass instances are rejected (paf31)
45+- A bug in the optimizer related to inlining was fixed (paf31)
46+- A type checker bug related to array literals was fixed (paf31)
47+- Externs files (`--externs`) are now working again (paf31)
48+
49+### Libraries
50+
51+- The [purescript-date](https://github.com/purescript/purescript-date) library provides basic date/time functions
52+- The [purescript-reactive](https://github.com/purescript/purescript-reactive) and [purescript-reactive-jquery]() libraries provide reactive variables, and bindings to jQuery properties.
53+- The [purescript-generics](https://github.com/purescript/purescript-generics) library provides generic programming capabilities.
54+
55+### Documentation
56+
57+-
Setup.hs+37−1
@@ -1,2 +1,38 @@
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
116import Distribution.Simple
2−main = defaultMain
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
app/Main.hsdeleted−250
@@ -1,250 +0,0 @@
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.nixdeleted−23
@@ -1,23 +0,0 @@
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.hsnew file+178
@@ -0,0 +1,178 @@
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 (Just exps) decl = any (matches decl) exps
88+ where
89+ matches (P.TypeDeclaration ident _) (P.ValueRef ident') = ident == ident'
90+ matches (P.ExternDeclaration _ ident _ _) (P.ValueRef ident') = ident == ident'
91+ matches (P.DataDeclaration ident _ _) (P.TypeRef ident' _) = ident == ident'
92+ matches (P.ExternDataDeclaration ident _) (P.TypeRef ident' _) = ident == ident'
93+ matches (P.TypeSynonymDeclaration ident _ _) (P.TypeRef ident' _) = ident == ident'
94+ matches (P.TypeClassDeclaration ident _ _) (P.TypeClassRef ident') = ident == ident'
95+ matches _ _ = False
96+
97+isDctorExported :: P.ProperName -> Maybe [P.DeclarationRef] -> P.ProperName -> Bool
98+isDctorExported _ Nothing _ = True
99+isDctorExported ident (Just exps) ctor = flip any exps $ \e -> case e of
100+ P.TypeRef ident' Nothing -> ident == ident'
101+ P.TypeRef ident' (Just ctors) -> ident == ident' && ctor `elem` ctors
102+ _ -> False
103+
104+renderTopLevel :: Maybe [P.DeclarationRef] -> [P.Declaration] -> Docs
105+renderTopLevel exps decls = forM_ (sortBy (compare `on` getName) decls) $ \decl -> do
106+ renderDeclaration 4 exps decl
107+ spacer
108+
109+renderDeclaration :: Int -> Maybe [P.DeclarationRef] -> P.Declaration -> Docs
110+renderDeclaration n _ (P.TypeDeclaration ident ty) =
111+ atIndent n $ show ident ++ " :: " ++ P.prettyPrintType ty
112+renderDeclaration n _ (P.ExternDeclaration _ ident _ ty) =
113+ atIndent n $ show ident ++ " :: " ++ P.prettyPrintType ty
114+renderDeclaration n exps (P.DataDeclaration name args ctors) = do
115+ let typeName = P.runProperName name ++ " " ++ unwords args
116+ atIndent n $ "data " ++ typeName ++ " where"
117+ let exported = filter (isDctorExported name exps . fst) ctors
118+ forM_ exported $ \(ctor, tys) ->
119+ atIndent (n + 2) $ P.runProperName ctor ++ " :: " ++ concatMap (\ty -> P.prettyPrintType ty ++ " -> ") tys ++ typeName
120+renderDeclaration n _ (P.ExternDataDeclaration name kind) =
121+ atIndent n $ "data " ++ P.runProperName name ++ " :: " ++ P.prettyPrintKind kind
122+renderDeclaration n _ (P.TypeSynonymDeclaration name args ty) = do
123+ let typeName = P.runProperName name ++ " " ++ unwords args
124+ atIndent n $ "type " ++ typeName ++ " = " ++ P.prettyPrintType ty
125+renderDeclaration n exps (P.TypeClassDeclaration name args ds) = do
126+ atIndent n $ "class " ++ P.runProperName name ++ " " ++ unwords args ++ " where"
127+ mapM_ (renderDeclaration (n + 2) exps) ds
128+renderDeclaration n _ (P.TypeInstanceDeclaration name constraints className tys _) = do
129+ let constraintsText = case constraints of
130+ [] -> ""
131+ cs -> "(" ++ intercalate ", " (map (\(pn, tys') -> show pn ++ " " ++ unwords (map P.prettyPrintTypeAtom tys')) cs) ++ ") => "
132+ atIndent n $ "instance " ++ show name ++ " :: " ++ constraintsText ++ show className ++ " " ++ unwords (map P.prettyPrintTypeAtom tys)
133+renderDeclaration _ _ _ = return ()
134+
135+getName :: P.Declaration -> String
136+getName (P.TypeDeclaration ident _) = show ident
137+getName (P.ExternDeclaration _ ident _ _) = show ident
138+getName (P.DataDeclaration name _ _) = P.runProperName name
139+getName (P.ExternDataDeclaration name _) = P.runProperName name
140+getName (P.TypeSynonymDeclaration name _ _) = P.runProperName name
141+getName (P.TypeClassDeclaration name _ _) = P.runProperName name
142+getName (P.TypeInstanceDeclaration name _ _ _ _) = show name
143+getName _ = error "Invalid argument to getName"
144+
145+isValueDeclaration :: P.Declaration -> Bool
146+isValueDeclaration P.TypeDeclaration{} = True
147+isValueDeclaration P.ExternDeclaration{} = True
148+isValueDeclaration _ = False
149+
150+isTypeDeclaration :: P.Declaration -> Bool
151+isTypeDeclaration P.DataDeclaration{} = True
152+isTypeDeclaration P.ExternDataDeclaration{} = True
153+isTypeDeclaration P.TypeSynonymDeclaration{} = True
154+isTypeDeclaration _ = False
155+
156+isTypeClassDeclaration :: P.Declaration -> Bool
157+isTypeClassDeclaration P.TypeClassDeclaration{} = True
158+isTypeClassDeclaration _ = False
159+
160+isTypeInstanceDeclaration :: P.Declaration -> Bool
161+isTypeInstanceDeclaration P.TypeInstanceDeclaration{} = True
162+isTypeInstanceDeclaration _ = False
163+
164+inputFile :: Term FilePath
165+inputFile = value $ pos 0 "input.ps" $ posInfo { posDoc = "The input .ps file" }
166+
167+term :: Term (IO ())
168+term = docgen <$> inputFile
169+
170+termInfo :: TermInfo
171+termInfo = defTI
172+ { termName = "docgen"
173+ , version = showVersion Paths.version
174+ , termDoc = "Generate Markdown documentation from PureScript extern files"
175+ }
176+
177+main :: IO ()
178+main = run (term, termInfo)
docs/.gitignorenew file+1
@@ -0,0 +1 @@
1+build
docs/Makefilenew file+177
@@ -0,0 +1,177 @@
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.pynew file+258
@@ -0,0 +1,258 @@
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.4.0'
55+# The full version, including alpha/beta/rc tags.
56+release = '0.4.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.rstnew file+31
@@ -0,0 +1,31 @@
1+Foreign Function Interface
2+==========================
3+
4+Importing Values
5+----------------
6+
7+The `foreign import` keyword declares 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 "function pow(n) {\
17+ \ return function(p) {\
18+ \ return Math.pow(n, p);\
19+ \ };\
20+ \}" :: Number -> Number -> Number
21+
22+Importing Types
23+---------------
24+
25+To declare a new type with no constructors, use `foreign import data` and provide the kind::
26+
27+ foreign import data DOM :: *
28+
29+ foreign import document :: {
30+ createElement :: String -> DOM
31+ }
docs/source/index.rstnew file+30
@@ -0,0 +1,30 @@
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.rstnew file+145
@@ -0,0 +1,145 @@
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+- Optional 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+--tco Perform tail-call elimination on the generated Javascript.
48+--no-prelude Do not include the Prelude in the generated Javascript.
49+--magic-do Overload the `do` keyword to inline calls to `bind` for the `Eff` monad, to generate more efficient code.
50+--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.
51+--module If specified, any code which is not referenced transitively from this module will be removed. This argument can be used multiple times.
52+--browser-namespace Specify the namespace that PureScript modules will be exported to when running in the browser.
53+
54+Motivation
55+----------
56+
57+I was looking for a simple functional language which would compile to JavaScript and have the following characteristics:
58+
59+- Generate simple readable Javascript
60+- Provide the ability to compile to tight loops if necessary
61+- Reasonable type system
62+- Ideally, written in a programming language I would enjoy working in
63+- Provides a simple interface to existing Javascript code
64+
65+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.
66+
67+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.
68+
69+PureScript can also be seen as a trade-off between a theoretically ideal language and one which generates reasonably high performance code.
70+
71+Hello, PureScript!
72+------------------
73+
74+As an introductory example, here is the usual "Hello World" written in PureScript::
75+
76+ module Main where
77+
78+ import Debug.Trace
79+
80+ main = trace "Hello, World!"
81+
82+which compiles to the following Javascript, ignoring the Prelude::
83+
84+ var Main;
85+ (function (Main) {
86+ var main = trace("Hello, World!");
87+ Main.main = main;
88+ })(Main = Main || {});
89+
90+The following command will compile and execute the PureScript code above::
91+
92+ psc input.purs --main | node
93+
94+Another Example
95+---------------
96+
97+The following code defines a `Person` data type and a function to generate a string representation for a `Person`::
98+
99+ data Person = Person { name :: String, age :: Number }
100+
101+ foreign import numberToString :: Number -> String
102+
103+ showPerson :: Person -> String
104+ showPerson (Person o) = o.name ++ ", aged " ++ numberToString(o.age)
105+
106+ examplePerson :: Person
107+ examplePerson = Person {name: "Bonnie", age: 26}
108+
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 `numberToString` function is written in Javascript, and converts a `Number` to its `String` representation
115+- The `showPerson` function takes a `Person` and returns a `String`
116+- `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.
117+- `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.
118+
119+The generated Javascript looks like this::
120+
121+ var Person = function (value) {
122+ return { ctor: 'Person', values: [value] };
123+ };
124+
125+ function showPerson(_1) {
126+ return _1.values[0].name + ", aged " + numberToString(_1.values[0].age);
127+ };
128+
129+ var examplePerson = Person({
130+ name: "Bonnie",
131+ age: 26
132+ });
133+
134+
135+Related Projects
136+----------------
137+
138+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.
139+
140+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)
141+
142+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.
143+
144+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.
145+
docs/source/kinds.rstnew file+21
@@ -0,0 +1,21 @@
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.rstnew file+29
@@ -0,0 +1,29 @@
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 (id)
docs/source/patterns.rstnew file+139
@@ -0,0 +1,139 @@
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.rstnew file+904
@@ -0,0 +1,904 @@
1+Module Documentation
2+====================
3+
4+Module Prelude
5+--------------
6+
7+Types
8+~~~~~
9+
10+Type Classes
11+~~~~~~~~~~~~
12+
13+::
14+
15+ class Alternative f where
16+ empty :: forall a. f a
17+ (<|>) :: forall a. f a -> f a -> f a
18+
19+ class Applicative f where
20+ pure :: forall a. a -> f a
21+ (<*>) :: forall a b. f (a -> b) -> f a -> f b
22+
23+ class Bits b where
24+ (&) :: b -> b -> b
25+ (|) :: b -> b -> b
26+ (^) :: b -> b -> b
27+ shl :: b -> Prim.Number -> b
28+ shr :: b -> Prim.Number -> b
29+ zshr :: b -> Prim.Number -> b
30+ complement :: b -> b
31+
32+ class BoolLike b where
33+ (&&) :: b -> b -> b
34+ (||) :: b -> b -> b
35+ not :: b -> b
36+
37+ class Category a where
38+ id :: forall t. a t t
39+ (<<<) :: forall b c d. a c d -> a b c -> a b d
40+ (>>>) :: forall b c d. a b c -> a c d -> a b d
41+
42+ class Eq a where
43+ (==) :: a -> a -> Prim.Boolean
44+ (/=) :: a -> a -> Prim.Boolean
45+
46+ class Functor f where
47+ (<$>) :: forall a b. (a -> b) -> f a -> f b
48+
49+ class Monad m where
50+ return :: forall a. a -> m a
51+ (>>=) :: forall a b. m a -> (a -> m b) -> m b
52+
53+ class Num a where
54+ (+) :: a -> a -> a
55+ (-) :: a -> a -> a
56+ (*) :: a -> a -> a
57+ (/) :: a -> a -> a
58+ (%) :: a -> a -> a
59+ negate :: a -> a
60+
61+ class Ord a where
62+ (<) :: a -> a -> Prim.Boolean
63+ (>) :: a -> a -> Prim.Boolean
64+ (<=) :: a -> a -> Prim.Boolean
65+ (>=) :: a -> a -> Prim.Boolean
66+
67+ class Read a where
68+ read :: Prim.String -> a
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 readBoolean :: Read Prim.Boolean
101+
102+ instance readNumber :: Read Prim.Number
103+
104+ instance readString :: Read Prim.String
105+
106+ instance showBoolean :: Show Prim.Boolean
107+
108+ instance showNumber :: Show Prim.Number
109+
110+ instance showString :: Show Prim.String
111+
112+Values
113+~~~~~~
114+
115+::
116+
117+ (!!) :: forall a. [a] -> Prim.Number -> a
118+
119+ (#) :: forall a b. a -> (a -> b) -> b
120+
121+ ($) :: forall a b. (a -> b) -> a -> b
122+
123+ (++) :: Prim.String -> Prim.String -> Prim.String
124+
125+ boolAnd :: Prim.Boolean -> Prim.Boolean -> Prim.Boolean
126+
127+ boolNot :: Prim.Boolean -> Prim.Boolean
128+
129+ boolOr :: Prim.Boolean -> Prim.Boolean -> Prim.Boolean
130+
131+ const :: forall a b. a -> b -> a
132+
133+ flip :: forall a b c. (a -> b -> c) -> b -> a -> c
134+
135+ numAdd :: Prim.Number -> Prim.Number -> Prim.Number
136+
137+ numAnd :: Prim.Number -> Prim.Number -> Prim.Number
138+
139+ numComplement :: Prim.Number -> Prim.Number
140+
141+ numDiv :: Prim.Number -> Prim.Number -> Prim.Number
142+
143+ numGreater :: Prim.Number -> Prim.Number -> Prim.Boolean
144+
145+ numGreaterEq :: Prim.Number -> Prim.Number -> Prim.Boolean
146+
147+ numLess :: Prim.Number -> Prim.Number -> Prim.Boolean
148+
149+ numLessEq :: Prim.Number -> Prim.Number -> Prim.Boolean
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+ readNumberImpl :: Prim.String -> Prim.Number
170+
171+ showNumberImpl :: Prim.Number -> Prim.String
172+
173+ unsafeRefEq :: forall a. a -> a -> Prim.Boolean
174+
175+ unsafeRefIneq :: forall a. a -> a -> Prim.Boolean
176+
177+Module Data.Monoid
178+------------------
179+
180+Types
181+~~~~~
182+
183+Type Classes
184+~~~~~~~~~~~~
185+
186+::
187+
188+ class Monoid m where
189+ mempty :: m
190+ (<>) :: m -> m -> m
191+
192+Type Class Instances
193+~~~~~~~~~~~~~~~~~~~~
194+
195+::
196+
197+ instance monoidArray :: Monoid [a]
198+
199+ instance monoidString :: Monoid Prim.String
200+
201+Values
202+~~~~~~
203+
204+::
205+
206+ mconcat :: forall m. (Monoid m) => [m] -> m
207+
208+Module Control.Monad
209+--------------------
210+
211+Types
212+~~~~~
213+
214+Type Classes
215+~~~~~~~~~~~~
216+
217+Type Class Instances
218+~~~~~~~~~~~~~~~~~~~~
219+
220+Values
221+~~~~~~
222+
223+::
224+
225+ (<=<) :: forall m a b c. (Monad m) => (b -> m c) -> (a -> m b) -> a -> m c
226+
227+ (>=>) :: forall m a b c. (Monad m) => (a -> m b) -> (b -> m c) -> a -> m c
228+
229+ foldM :: forall m a b. (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
230+
231+ join :: forall m a. (Monad m) => m (m a) -> m a
232+
233+ mapM :: forall m a b. (Monad m) => (a -> m b) -> [a] -> m [b]
234+
235+ replicateM :: forall m a. (Monad m) => Prim.Number -> m a -> m [a]
236+
237+ sequence :: forall m a. (Monad m) => [m a] -> m [a]
238+
239+ when :: forall m. (Monad m) => Prim.Boolean -> m { } -> m { }
240+
241+ zipWithM :: forall m a b c. (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m [c]
242+
243+Module Data.Maybe
244+-----------------
245+
246+Types
247+~~~~~
248+
249+::
250+
251+ data Maybe a where
252+ Nothing :: Maybe a
253+ Just :: a -> Maybe a
254+
255+Type Classes
256+~~~~~~~~~~~~
257+
258+Type Class Instances
259+~~~~~~~~~~~~~~~~~~~~
260+
261+::
262+
263+ instance applicativeMaybe :: Applicative Maybe
264+
265+ instance functorMaybe :: Functor Maybe
266+
267+ instance monadMaybe :: Monad Maybe
268+
269+ instance showMaybe :: (Show a) => Show (Maybe a)
270+
271+Values
272+~~~~~~
273+
274+::
275+
276+ fromMaybe :: forall a. a -> Maybe a -> a
277+
278+ maybe :: forall a b. b -> (a -> b) -> Maybe a -> b
279+
280+Module Data.Either
281+------------------
282+
283+Types
284+~~~~~
285+
286+::
287+
288+ data Either a b where
289+ Left :: a -> Either a b
290+ Right :: b -> Either a b
291+
292+Type Classes
293+~~~~~~~~~~~~
294+
295+Type Class Instances
296+~~~~~~~~~~~~~~~~~~~~
297+
298+::
299+
300+ instance applicativeEither :: Applicative (Either e)
301+
302+ instance functorEither :: Functor (Either a)
303+
304+ instance monadEither :: Monad (Either e)
305+
306+ instance showEither :: (Show a, Show b) => Show (Either a b)
307+
308+Values
309+~~~~~~
310+
311+::
312+
313+ either :: forall a b c. (a -> c) -> (b -> c) -> Either a b -> c
314+
315+Module Data.Array
316+-----------------
317+
318+Types
319+~~~~~
320+
321+Type Classes
322+~~~~~~~~~~~~
323+
324+Type Class Instances
325+~~~~~~~~~~~~~~~~~~~~
326+
327+::
328+
329+ instance alternativeArray :: Alternative Prim.Array
330+
331+ instance functorArray :: Functor Prim.Array
332+
333+ instance monadArray :: Monad Prim.Array
334+
335+ instance showArray :: (Show a) => Show [a]
336+
337+Values
338+~~~~~~
339+
340+::
341+
342+ (:) :: forall a. a -> [a] -> [a]
343+
344+ all :: forall a. (a -> Prim.Boolean) -> [a] -> Prim.Boolean
345+
346+ any :: forall a. (a -> Prim.Boolean) -> [a] -> Prim.Boolean
347+
348+ concat :: forall a. [a] -> [a] -> [a]
349+
350+ concatMap :: forall a b. [a] -> (a -> [b]) -> [b]
351+
352+ deleteAt :: forall a. Prim.Number -> Prim.Number -> [a] -> [a]
353+
354+ drop :: forall a. Prim.Number -> [a] -> [a]
355+
356+ filter :: forall a. (a -> Prim.Boolean) -> [a] -> [a]
357+
358+ find :: forall a. (a -> Prim.Boolean) -> [a] -> Maybe a
359+
360+ foldl :: forall a b. (b -> a -> b) -> b -> [a] -> b
361+
362+ foldr :: forall a b. (a -> b -> a) -> a -> [b] -> a
363+
364+ head :: forall a. [a] -> Maybe a
365+
366+ indexOf :: forall a. [a] -> a -> Prim.Number
367+
368+ insertAt :: forall a. Prim.Number -> a -> [a] -> [a]
369+
370+ isEmpty :: forall a. [a] -> Prim.Boolean
371+
372+ joinS :: [Prim.String] -> Prim.String
373+
374+ joinWith :: [Prim.String] -> Prim.String -> Prim.String
375+
376+ lastIndexOf :: forall a. [a] -> a -> Prim.Number
377+
378+ length :: forall a. [a] -> Prim.Number
379+
380+ map :: forall a b. (a -> b) -> [a] -> [b]
381+
382+ push :: forall a. [a] -> a -> [a]
383+
384+ range :: Prim.Number -> Prim.Number -> [Prim.Number]
385+
386+ reverse :: forall a. [a] -> [a]
387+
388+ shift :: forall a. [a] -> [a]
389+
390+ singleton :: forall a. a -> [a]
391+
392+ slice :: forall a. Prim.Number -> Prim.Number -> [a] -> [a]
393+
394+ sort :: forall a. [a] -> [a]
395+
396+ tail :: forall a. [a] -> Maybe [a]
397+
398+ take :: forall a. Prim.Number -> [a] -> [a]
399+
400+ updateAt :: forall a. Prim.Number -> a -> [a] -> [a]
401+
402+ zipWith :: forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
403+
404+Module Data.Eq
405+--------------
406+
407+Types
408+~~~~~
409+
410+::
411+
412+ data Ref a where
413+ Ref :: a -> Ref a
414+
415+Type Classes
416+~~~~~~~~~~~~
417+
418+Type Class Instances
419+~~~~~~~~~~~~~~~~~~~~
420+
421+::
422+
423+ instance eqRef :: Eq (Ref a)
424+
425+Values
426+~~~~~~
427+
428+::
429+
430+ liftRef :: forall a b. (a -> a -> b) -> Ref a -> Ref a -> b
431+
432+ refEq :: forall a. Ref a -> Ref a -> Prim.Boolean
433+
434+ refIneq :: forall a. Ref a -> Ref a -> Prim.Boolean
435+
436+Module Data.Array.Unsafe
437+------------------------
438+
439+Types
440+~~~~~
441+
442+Type Classes
443+~~~~~~~~~~~~
444+
445+Type Class Instances
446+~~~~~~~~~~~~~~~~~~~~
447+
448+Values
449+~~~~~~
450+
451+::
452+
453+ head :: forall a. [a] -> a
454+
455+ tail :: forall a. [a] -> [a]
456+
457+Module Data.Tuple
458+-----------------
459+
460+Types
461+~~~~~
462+
463+::
464+
465+ data Tuple a b where
466+ Tuple :: a -> b -> Tuple a b
467+
468+Type Classes
469+~~~~~~~~~~~~
470+
471+Type Class Instances
472+~~~~~~~~~~~~~~~~~~~~
473+
474+::
475+
476+ instance showTuple :: (Show a, Show b) => Show (Tuple a b)
477+
478+Values
479+~~~~~~
480+
481+::
482+
483+ curry :: forall a b c. (Tuple a b -> c) -> a -> b -> c
484+
485+ uncurry :: forall a b c. (a -> b -> c) -> Tuple a b -> c
486+
487+ unzip :: forall a b. [Tuple a b] -> Tuple [a] [b]
488+
489+ zip :: forall a b. [a] -> [b] -> [Tuple a b]
490+
491+Module Data.String
492+------------------
493+
494+Types
495+~~~~~
496+
497+Type Classes
498+~~~~~~~~~~~~
499+
500+Type Class Instances
501+~~~~~~~~~~~~~~~~~~~~
502+
503+Values
504+~~~~~~
505+
506+::
507+
508+ charAt :: Prim.Number -> Prim.String -> Prim.String
509+
510+ indexOfS :: Prim.String -> Prim.String -> Prim.Number
511+
512+ lastIndexOfS :: Prim.String -> Prim.String -> Prim.Number
513+
514+ lengthS :: Prim.String -> Prim.Number
515+
516+ localeCompare :: Prim.String -> Prim.String -> Prim.Number
517+
518+ replace :: Prim.String -> Prim.String -> Prim.String -> Prim.String
519+
520+ sliceS :: Prim.Number -> Prim.Number -> Prim.String -> Prim.String
521+
522+ split :: Prim.String -> Prim.String -> [Prim.String]
523+
524+ substr :: Prim.Number -> Prim.Number -> Prim.String -> Prim.String
525+
526+ substring :: Prim.Number -> Prim.Number -> Prim.String -> Prim.String
527+
528+ toLower :: Prim.String -> Prim.String
529+
530+ toUpper :: Prim.String -> Prim.String
531+
532+ trim :: Prim.String -> Prim.String
533+
534+Module Data.String.Regex
535+------------------------
536+
537+Types
538+~~~~~
539+
540+::
541+
542+ data Regex :: *
543+
544+Type Classes
545+~~~~~~~~~~~~
546+
547+Type Class Instances
548+~~~~~~~~~~~~~~~~~~~~
549+
550+Values
551+~~~~~~
552+
553+::
554+
555+ match :: Regex -> Prim.String -> [Prim.String]
556+
557+ regex :: Prim.String -> Prim.String -> Regex
558+
559+ replaceR :: Regex -> Prim.String -> Prim.String -> Prim.String
560+
561+ search :: Regex -> Prim.String -> Prim.Number
562+
563+ test :: Regex -> Prim.String -> Prim.Boolean
564+
565+Module Global
566+-------------
567+
568+Types
569+~~~~~
570+
571+Type Classes
572+~~~~~~~~~~~~
573+
574+Type Class Instances
575+~~~~~~~~~~~~~~~~~~~~
576+
577+Values
578+~~~~~~
579+
580+::
581+
582+ decodeURI :: Prim.String -> Prim.String
583+
584+ decodeURIComponent :: Prim.String -> Prim.String
585+
586+ encodeURI :: Prim.String -> Prim.String
587+
588+ encodeURIComponent :: Prim.String -> Prim.String
589+
590+ infinity :: Prim.Number
591+
592+ isFinite :: Prim.Number -> Prim.Boolean
593+
594+ isNaN :: Prim.Number -> Prim.Boolean
595+
596+ nan :: Prim.Number
597+
598+ parseFloat :: Prim.String -> Prim.Number
599+
600+ parseInt :: Prim.String -> Prim.Number
601+
602+ toExponential :: Prim.Number -> Prim.String
603+
604+ toFixed :: Prim.Number -> Prim.Number -> Prim.String
605+
606+ toPrecision :: Prim.Number -> Prim.Number -> Prim.String
607+
608+Module Math
609+-----------
610+
611+Types
612+~~~~~
613+
614+Type Classes
615+~~~~~~~~~~~~
616+
617+Type Class Instances
618+~~~~~~~~~~~~~~~~~~~~
619+
620+Values
621+~~~~~~
622+
623+::
624+
625+ abs :: Prim.Number -> Prim.Number
626+
627+ aceil :: Prim.Number -> Prim.Number
628+
629+ acos :: Prim.Number -> Prim.Number
630+
631+ asin :: Prim.Number -> Prim.Number
632+
633+ atan :: Prim.Number -> Prim.Number
634+
635+ atan2 :: Prim.Number -> Prim.Number -> Prim.Number
636+
637+ cos :: Prim.Number -> Prim.Number
638+
639+ e :: Prim.Number
640+
641+ exp :: Prim.Number -> Prim.Number
642+
643+ floor :: Prim.Number -> Prim.Number
644+
645+ ln10 :: Prim.Number
646+
647+ ln2 :: Prim.Number
648+
649+ log :: Prim.Number -> Prim.Number
650+
651+ log10e :: Prim.Number
652+
653+ log2e :: Prim.Number
654+
655+ max :: Prim.Number -> Prim.Number -> Prim.Number
656+
657+ min :: Prim.Number -> Prim.Number -> Prim.Number
658+
659+ pi :: Prim.Number
660+
661+ pow :: Prim.Number -> Prim.Number -> Prim.Number
662+
663+ round :: Prim.Number -> Prim.Number
664+
665+ sin :: Prim.Number -> Prim.Number
666+
667+ sqrt :: Prim.Number -> Prim.Number
668+
669+ sqrt1_2 :: Prim.Number
670+
671+ sqrt2 :: Prim.Number
672+
673+ tan :: Prim.Number -> Prim.Number
674+
675+Module Control.Monad.Eff
676+------------------------
677+
678+Types
679+~~~~~
680+
681+::
682+
683+ data Eff :: # ! -> * -> *
684+
685+ type Pure a = forall e. Eff e a
686+
687+Type Classes
688+~~~~~~~~~~~~
689+
690+Type Class Instances
691+~~~~~~~~~~~~~~~~~~~~
692+
693+::
694+
695+ instance monadEff :: Monad (Eff e)
696+
697+Values
698+~~~~~~
699+
700+::
701+
702+ bindEff :: forall e a b. Eff e a -> (a -> Eff e b) -> Eff e b
703+
704+ forE :: forall e. Prim.Number -> Prim.Number -> (Prim.Number -> Eff e { }) -> Eff e { }
705+
706+ foreachE :: forall e a. [a] -> (a -> Eff e { }) -> Eff e { }
707+
708+ retEff :: forall e a. a -> Eff e a
709+
710+ runPure :: forall a. Pure a -> a
711+
712+ untilE :: forall e. Eff e Prim.Boolean -> Eff e { }
713+
714+ whileE :: forall e a. Eff e Prim.Boolean -> Eff e a -> Eff e { }
715+
716+Module Control.Monad.Eff.Unsafe
717+-------------------------------
718+
719+Types
720+~~~~~
721+
722+Type Classes
723+~~~~~~~~~~~~
724+
725+Type Class Instances
726+~~~~~~~~~~~~~~~~~~~~
727+
728+Values
729+~~~~~~
730+
731+::
732+
733+ unsafeInterleaveEff :: forall eff1 eff2 a. Eff eff1 a -> Eff eff2 a
734+
735+Module Random
736+-------------
737+
738+Types
739+~~~~~
740+
741+::
742+
743+ data Random :: !
744+
745+Type Classes
746+~~~~~~~~~~~~
747+
748+Type Class Instances
749+~~~~~~~~~~~~~~~~~~~~
750+
751+Values
752+~~~~~~
753+
754+::
755+
756+ random :: forall e. Eff (random :: Random | e) Prim.Number
757+
758+Module Control.Monad.Error
759+--------------------------
760+
761+Types
762+~~~~~
763+
764+::
765+
766+ data Error :: * -> !
767+
768+Type Classes
769+~~~~~~~~~~~~
770+
771+Type Class Instances
772+~~~~~~~~~~~~~~~~~~~~
773+
774+Values
775+~~~~~~
776+
777+::
778+
779+ catchError :: forall e r a. (e -> Eff r a) -> Eff (err :: Error e | r) a -> Eff r a
780+
781+ throwError :: forall a e r. e -> Eff (err :: Error e | r) a
782+
783+Module Data.IORef
784+-----------------
785+
786+Types
787+~~~~~
788+
789+::
790+
791+ data IORef :: * -> *
792+
793+ data Ref :: !
794+
795+Type Classes
796+~~~~~~~~~~~~
797+
798+Type Class Instances
799+~~~~~~~~~~~~~~~~~~~~
800+
801+Values
802+~~~~~~
803+
804+::
805+
806+ modifyIORef :: forall s r. IORef s -> (s -> s) -> Eff (ref :: Ref | r) { }
807+
808+ newIORef :: forall s r. s -> Eff (ref :: Ref | r) (IORef s)
809+
810+ readIORef :: forall s r. IORef s -> Eff (ref :: Ref | r) s
811+
812+ unsafeRunIORef :: forall eff a. Eff (ref :: Ref | eff) a -> Eff eff a
813+
814+ writeIORef :: forall s r. IORef s -> s -> Eff (ref :: Ref | r) { }
815+
816+Module Debug.Trace
817+------------------
818+
819+Types
820+~~~~~
821+
822+::
823+
824+ data Trace :: !
825+
826+Type Classes
827+~~~~~~~~~~~~
828+
829+Type Class Instances
830+~~~~~~~~~~~~~~~~~~~~
831+
832+Values
833+~~~~~~
834+
835+::
836+
837+ print :: forall a r. (Show a) => a -> Eff (trace :: Trace | r) { }
838+
839+ trace :: forall r. Prim.String -> Eff (trace :: Trace | r) { }
840+
841+Module Control.Monad.ST
842+-----------------------
843+
844+Types
845+~~~~~
846+
847+::
848+
849+ data ST :: * -> !
850+
851+ data STArray :: * -> * -> *
852+
853+ data STRef :: * -> * -> *
854+
855+Type Classes
856+~~~~~~~~~~~~
857+
858+Type Class Instances
859+~~~~~~~~~~~~~~~~~~~~
860+
861+Values
862+~~~~~~
863+
864+::
865+
866+ modifySTRef :: forall a h r. STRef h a -> (a -> a) -> Eff (st :: ST h | r) a
867+
868+ newSTArray :: forall a h r. Prim.Number -> a -> Eff (st :: ST h | r) (STArray h a)
869+
870+ newSTRef :: forall a h r. a -> Eff (st :: ST h | r) (STRef h a)
871+
872+ peekSTArray :: forall a h r. STArray h a -> Eff (st :: ST h | r) a
873+
874+ pokeSTArray :: forall a h r. STArray h a -> Prim.Number -> a -> Eff (st :: ST h | r) a
875+
876+ readSTRef :: forall a h r. STRef h a -> Eff (st :: ST h | r) a
877+
878+ runST :: forall a r. forall h. Eff (st :: ST h | r) a -> Eff r a
879+
880+ runSTArray :: forall a r. forall h. Eff (st :: ST h | r) (STArray h a) -> Eff r [a]
881+
882+ writeSTRef :: forall a h r. STRef h a -> a -> Eff (st :: ST h | r) a
883+
884+Module Data.Enum
885+----------------
886+
887+Types
888+~~~~~
889+
890+Type Classes
891+~~~~~~~~~~~~
892+
893+::
894+
895+ class Enum a where
896+ toEnum :: Prim.Number -> Maybe a
897+ fromEnum :: a -> Prim.Number
898+
899+Type Class Instances
900+~~~~~~~~~~~~~~~~~~~~
901+
902+Values
903+~~~~~~
904+
docs/source/syntax.rstnew file+217
@@ -0,0 +1,217 @@
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+
docs/source/typeclasses.rstnew file+26
@@ -0,0 +1,26 @@
1+Type Classes
2+============
3+
4+PureScript has basic support for type classes via the `class` and `instance` keywords.
5+
6+Type class instances must be of the form `String`, `Number`, `Boolean`, `[t]` or `C t1 ... tn`, and only a single type class parameter is supported.
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 Strings, Booleans and arrays::
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.rstnew file+159
@@ -0,0 +1,159 @@
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 ``Foo``s are constructed.
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+::
84+ forall r. { foo :: Number, bar :: Number | r } -> Number
85+
86+Here, the type variable ``r`` has kind ``# *`` - it represents a `row` of `types`. It can be instantiated with any row of named types.
87+
88+In other words, ``addProps`` accepts any record which has properties ``Foo`` and ``Bar``, and *any other record properties*.
89+
90+Therefore, the following application compiles::
91+
92+ addProps { foo: 1, bar: 2, baz: 3 }
93+
94+even though the type of ``addProps`` does not mention the property ``baz``. However, the following does not compile::
95+
96+ addProps { foo: 1 }
97+
98+since the `bar` property is missing.
99+
100+Rank N Types
101+------------
102+
103+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.
104+
105+In most cases, a type annotation is necessary when using this feature.
106+
107+As an example, we can pass a polymorphic function as an argument to another function::
108+
109+ poly :: (forall a. a -> a) -> Boolean
110+ poly f = (f 0 < 1) == f true
111+
112+Notice that the polymorphic function's type argument is instantiated to both `Number` and `Boolean`.
113+
114+An argument to ``poly`` must indeed be polymorphic. For example, the following fails::
115+
116+ test = poly (\n -> n + 1)
117+
118+since the skolemized type variable ``a`` does not unify with ``Number``.
119+
120+Rows
121+----
122+
123+A row of types represents an unordered collection of named types without duplicates.
124+
125+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.
126+
127+To denote a closed row, separate the fields with commas, with each label separated from its type with a double colon::
128+
129+ (name :: String, age :: Number)
130+
131+It may be necessary, depending on the context, to surround a row in parentheses.
132+
133+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::
134+
135+ (name :: String, age :: Number | r)
136+
137+Type Synonyms
138+-------------
139+
140+For convenience, it is possible to declare a synonym for a type using the ``type`` keyword. Type synonyms can include type arguments.
141+
142+For example::
143+
144+ type Foo = { foo :: Number, bar :: Number }
145+
146+ addFoo :: Foo -> Number
147+ addFoo = \o -> o.foo + o.bar
148+
149+Constrained Types
150+-----------------
151+
152+Polymorphic types may be predicated on one or more ``constraints``. See the chapter on type classes for more information.
153+
154+Type Annotations
155+----------------
156+
157+Most types can be inferred (not including Rank N Types and constrained types), but annotations can optionally be provided using a double-colon::
158+
159+ one = 1 :: Number
examples/.gitignorenew file+1
@@ -0,0 +1 @@
1+shelltest/tests
examples/failing/Arrays.pursnew file+5
@@ -0,0 +1,5 @@
1+module Data.Array where
2+
3+ import Prelude
4+
5+ test = \arr -> arr !! (0 !! 0)
examples/failing/Do.pursnew file+8
@@ -0,0 +1,8 @@
1+module Do 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/ExportExplicit.pursnew file+16
@@ -0,0 +1,16 @@
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+ testX = X
11+ testY = Y
12+
13+ -- should fail as Z is not exported from M1
14+ testZ = Z
15+
16+ main = Debug.Trace.trace "Done"
examples/failing/ExportExplicit2.pursnew file+13
@@ -0,0 +1,13 @@
1+module M1 (x) where
2+
3+ x = 1
4+ y = 0
5+
6+module Main where
7+
8+ import M1
9+
10+ -- should fail as y is not exported from M1
11+ testY = y
12+
13+ main = Debug.Trace.trace "Done"
examples/failing/ExportExplicit3.pursnew file+5
@@ -0,0 +1,5 @@
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/failing/ExportExplicit4.pursnew file+14
@@ -0,0 +1,14 @@
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/failing/ExportExplicit5.pursnew file+5
@@ -0,0 +1,5 @@
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/failing/ExportExplicit6.pursnew file+13
@@ -0,0 +1,13 @@
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/failing/Import.pursnew file+3
@@ -0,0 +1,3 @@
1+module Module where
2+
3+ import UndefinedModule
examples/failing/ImportExplicit.pursnew file+14
@@ -0,0 +1,14 @@
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+ testY = Y
12+ testZ = Z
13+
14+ main = Debug.Trace.trace "Done"
examples/failing/ImportExplicit2.pursnew file+7
@@ -0,0 +1,7 @@
1+module M1 where
2+
3+ foo = "foo"
4+
5+module Main where
6+
7+ import M1 (X(..))
examples/failing/ImportExplicit3.pursnew file+7
@@ -0,0 +1,7 @@
1+module M1 where
2+
3+ data X = Y
4+
5+module Main where
6+
7+ import M1 (X(Z, Q))
examples/failing/ImportModule.pursnew file+7
@@ -0,0 +1,7 @@
1+module M2 where
2+
3+ data X = X
4+
5+module Main where
6+
7+ import M1
examples/failing/KindError.pursnew file+3
@@ -0,0 +1,3 @@
1+module KindError where
2+
3+ data KindError f a = One f | Two (f a)
examples/failing/MPTCs.pursnew file+7
@@ -0,0 +1,7 @@
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/ModuleDeps.pursnew file+7
@@ -0,0 +1,7 @@
1+module M1 where
2+
3+import M2
4+
5+module M2 where
6+
7+import M1
examples/failing/MutRec.pursnew file+5
@@ -0,0 +1,5 @@
1+module MutRec where
2+
3+x = y
4+
5+y = x
examples/failing/MutRec2.pursnew file+3
@@ -0,0 +1,3 @@
1+module MutRec2 where
2+
3+x = x
examples/failing/NullaryAbs.pursnew file+3
@@ -0,0 +1,3 @@
1+module NullaryAbs where
2+
3+ func = \ -> "no"
examples/failing/Object.pursnew file+5
@@ -0,0 +1,5 @@
1+module Object where
2+
3+test o = o.foo
4+
5+test1 = test {}
examples/failing/OverlappingVars.pursnew file+12
@@ -0,0 +1,12 @@
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.pursnew file+7
@@ -0,0 +1,7 @@
1+module Rank2Types where
2+
3+ import Prelude
4+
5+ foreign import test :: (forall a. a -> a) -> Number
6+
7+ test1 = test (\n -> n + 1)
examples/failing/ReadShow.pursnew file+7
@@ -0,0 +1,7 @@
1+module ReadShow where
2+
3+ foreign import read :: forall a. String -> a
4+
5+ foreign import show :: forall a. a -> String
6+
7+ test = \x -> show (read x)
examples/failing/Reserved.pursnew file+4
@@ -0,0 +1,4 @@
1+module Reserved where
2+
3+(<) :: Number -> Number -> Number
4+(<) a b = !(a >= b)
examples/failing/SkolemEscape.pursnew file+5
@@ -0,0 +1,5 @@
1+module SkolemEscape where
2+
3+ foreign import foo :: (forall a. a -> a) -> Number
4+
5+ test = \x -> foo x
examples/failing/SkolemEscape2.pursnew file+9
@@ -0,0 +1,9 @@
1+module SkolemEscape 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/TypeClassInstances.pursnew file+8
@@ -0,0 +1,8 @@
1+module TypeClassInstances 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/TypeClasses.pursnew file+7
@@ -0,0 +1,7 @@
1+module TypeClasses where
2+
3+class Show a where
4+ show :: a -> String
5+
6+instance TypeClasses.Show ([[String]]) where
7+ show _ = "array"
examples/failing/TypeClasses2.pursnew file+15
@@ -0,0 +1,15 @@
1+module TC1 where
2+
3+class Show a where
4+ show :: a -> String
5+
6+module TC2 where
7+
8+instance TC1.Show String where
9+ show s = s
10+
11+module TC3 where
12+
13+import TC1
14+
15+test = show "testing"
examples/failing/TypeError.pursnew file+5
@@ -0,0 +1,5 @@
1+module TypeError where
2+
3+ import Prelude
4+
5+ test = 1 ++ "A"
examples/failing/TypeSynonyms.pursnew file+5
@@ -0,0 +1,5 @@
1+module TypeSynonyms where
2+
3+type T1 = [T2]
4+
5+type T2 = T1
examples/failing/TypeSynonyms2.pursnew file+9
@@ -0,0 +1,9 @@
1+module TypeSynonyms2 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.pursnew file+13
@@ -0,0 +1,13 @@
1+module TypeSynonyms2 where
2+
3+class Foo a where
4+ foo :: a -> String
5+
6+type Bar = String
7+
8+module M where
9+
10+import TypeSynonyms2
11+
12+instance TypeSynonyms2.Foo Bar where
13+ foo s = s
examples/passing/Applicative.pursnew file+16
@@ -0,0 +1,16 @@
1+module Applicative where
2+
3+class Applicative f where
4+ pure :: forall a. a -> f a
5+ (<*>) :: forall a b. f (a -> b) -> f a -> f b
6+
7+data Maybe a = Nothing | Just a
8+
9+instance applicativeMaybe :: Applicative Maybe where
10+ pure = Just
11+ (<*>) (Just f) (Just a) = Just (f a)
12+ (<*>) _ _ = Nothing
13+
14+module Main where
15+
16+main = Debug.Trace.trace "Done"
examples/passing/ArrayType.pursnew file+17
@@ -0,0 +1,17 @@
1+module ArrayType where
2+
3+test :: [] Number
4+test = [1, 2, 3]
5+
6+class Functor f where
7+ fmap :: forall a b. (a -> b) -> f a -> f b
8+
9+foreign import (:) :: forall a. a -> [a] -> [a]
10+
11+instance functorArray :: Functor [] where
12+ fmap _ [] = []
13+ fmap f (x:xs) = f x : fmap f xs
14+
15+module Main where
16+
17+main = Debug.Trace.trace "Done"
examples/passing/Arrays.pursnew file+34
@@ -0,0 +1,34 @@
1+module Data.ArrayTests 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+module Main where
25+
26+import Data.Array
27+import Prelude
28+
29+main = do
30+ let x = [3,2,1]
31+ let y = sort x
32+ if x == [3,2,1]
33+ then Debug.Trace.trace "Done"
34+ else Control.Monad.Eff.Error.throwError "Not done"
examples/passing/Auto.pursnew file+15
@@ -0,0 +1,15 @@
1+module Auto 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+module Main where
14+
15+main = Debug.Trace.trace "Done"
examples/passing/BindersInFunctions.pursnew file+12
@@ -0,0 +1,12 @@
1+module Main where
2+
3+import Prelude
4+import Data.Array
5+
6+tails = map (\(_:xs) -> xs)
7+
8+main =
9+ let ts = tails [[1, 2, 3], [4, 5], [6]] in
10+ if ts == [[2, 3], [5], []]
11+ then Debug.Trace.trace "Done"
12+ else Control.Monad.Eff.Error.throwError "Incorrect result from 'tails'."
examples/passing/Church.pursnew file+18
@@ -0,0 +1,18 @@
1+module Church where
2+
3+ type List a = forall r. r -> (a -> r -> r) -> r
4+
5+ empty :: forall a. List a
6+ empty = \r f -> r
7+
8+ cons :: forall a. a -> List a -> List a
9+ cons = \a l r f -> f a (l r f)
10+
11+ append :: forall a. List a -> List a -> List a
12+ append = \l1 l2 r f -> l2 (l1 r f) f
13+
14+ test = append (cons 1 empty) (cons 2 empty)
15+
16+module Main where
17+
18+main = Debug.Trace.trace "Done"
examples/passing/Collatz.pursnew file+18
@@ -0,0 +1,18 @@
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.pursnew file+9
@@ -0,0 +1,9 @@
1+module Conditional where
2+
3+ fns = \f -> if f true then f else \x -> x
4+
5+ not = \x -> if x then false else true
6+
7+module Main where
8+
9+main = Debug.Trace.trace "Done"
examples/passing/Cons.pursnew file+12
@@ -0,0 +1,12 @@
1+module Cons where
2+
3+ import Prelude
4+ import Data.Array
5+
6+ test1 = \xs -> 1 : xs
7+
8+ test2 = 1 : 2 : 3 : []
9+
10+module Main where
11+
12+main = Debug.Trace.trace "Done"
examples/passing/Console.pursnew file+13
@@ -0,0 +1,13 @@
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.pursnew file+9
@@ -0,0 +1,9 @@
1+module DataAndType where
2+
3+data A = A B
4+
5+type B = A
6+
7+module Main where
8+
9+main = Debug.Trace.trace "Done"
examples/passing/DataImport.pursnew file+13
@@ -0,0 +1,13 @@
1+module M1 where
2+
3+data Test = Test String
4+
5+module Main where
6+
7+import M1
8+
9+unTest (Test s) = s
10+
11+main = do
12+ let x = unTest (Test "Done")
13+ Debug.Trace.trace x
examples/passing/Do.pursnew file+49
@@ -0,0 +1,49 @@
1+module Do where
2+
3+import Prelude
4+
5+data Maybe a = Nothing | Just a
6+
7+instance monadMaybe :: Prelude.Monad Maybe where
8+ return = Just
9+ (>>=) Nothing _ = Nothing
10+ (>>=) (Just a) f = f a
11+
12+test1 = \_ -> do
13+ Just "abc"
14+
15+test2 = \_ -> do
16+ (x : _) <- Just [1, 2, 3]
17+ (y : _) <- Just [4, 5, 6]
18+ Just (x + y)
19+
20+test3 = \_ -> do
21+ Just 1
22+ Nothing :: Maybe Number
23+ Just 2
24+
25+test4 mx my = do
26+ x <- mx
27+ y <- my
28+ Just (x + y + 1)
29+
30+test5 mx my mz = do
31+ x <- mx
32+ y <- my
33+ let sum = x + y
34+ z <- mz
35+ Just (z + sum + 1)
36+
37+test6 mx = \_ -> do
38+ let Just x = mx
39+ Just x
40+
41+test8 = \_ -> do
42+ Just (do
43+ Just 1)
44+
45+test9 = \_ -> (+) <$> Just 1 <*> Just 2
46+
47+module Main where
48+
49+main = Debug.Trace.trace "Done"
examples/passing/Dollar.pursnew file+16
@@ -0,0 +1,16 @@
1+module Dollar where
2+
3+($) :: forall a b. (a -> b) -> a -> b
4+($) f x = f x
5+
6+infixr 1000 $
7+
8+id x = x
9+
10+test1 x = id $ id $ id $ id $ x
11+
12+test2 x = id id $ id x
13+
14+module Main where
15+
16+main = Debug.Trace.trace "Done"
examples/passing/DottedModules.pursnew file+20
@@ -0,0 +1,20 @@
1+module Some.Module.Name where
2+
3+ class Foo a where
4+ foo :: a -> a
5+
6+ data Text = Text String
7+
8+ x = Text "Done"
9+
10+module Main where
11+
12+ import Prelude
13+ import Some.Module.Name
14+
15+ instance fooString :: Some.Module.Name.Foo String where
16+ foo s = s
17+
18+ unwrap (Text x) = x
19+
20+ main = Debug.Trace.print $ foo $ unwrap x
examples/passing/Eff.pursnew file+27
@@ -0,0 +1,27 @@
1+module TestEff where
2+
3+import Prelude
4+import Control.Monad.Eff
5+import Control.Monad.ST
6+import Control.Monad.Eff.Error
7+import Debug.Trace
8+
9+test1 = catchError (\s -> return 0) $ do
10+ trace "Testing"
11+ throwError "Error!"
12+
13+test2 = runPure (runST (do
14+ ref <- newSTRef 0
15+ modifySTRef ref $ \n -> n + 1
16+ readSTRef ref))
17+
18+module Main where
19+
20+import Prelude
21+import Control.Monad.Eff
22+import TestEff
23+
24+main = do
25+ n <- test1
26+ Debug.Trace.print n
27+ Debug.Trace.print test2
examples/passing/EmptyDataDecls.pursnew file+20
@@ -0,0 +1,20 @@
1+module Main where
2+
3+import Prelude
4+import Data.Array
5+
6+data Z
7+data S n
8+
9+data Array n a = Array [a]
10+
11+nil :: forall a. Array Z a
12+nil = Array []
13+
14+cons :: forall a n. a -> Array n a -> Array (S n) a
15+cons x (Array xs) = Array $ x : xs
16+
17+main = let (Array xs) = cons 1 $ cons 2 $ cons 3 nil
18+ in if xs == [1, 2, 3]
19+ then Debug.Trace.trace "Done"
20+ else Control.Monad.Eff.Error.throwError "Failed"
examples/passing/EmptyTypeClass.pursnew file+18
@@ -0,0 +1,18 @@
1+module EmptyTypeClass where
2+
3+class Partial
4+
5+head :: forall a. (Partial) => [a] -> a
6+head (x:xs) = x
7+
8+module AllowPartialFns where
9+
10+instance allowPartials :: EmptyTypeClass.Partial
11+
12+module Main where
13+
14+import Prelude
15+import AllowPartialFns
16+import EmptyTypeClass
17+
18+main = Debug.Trace.trace $ head ["Done"]
examples/passing/ExportExplicit.pursnew file+20
@@ -0,0 +1,20 @@
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/passing/ExportExplicit2.pursnew file+15
@@ -0,0 +1,15 @@
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/passing/ExternData.pursnew file+19
@@ -0,0 +1,19 @@
1+module ExternData where
2+
3+ foreign import data IO :: * -> *
4+
5+ foreign import fmap :: forall a b. IO a -> (a -> b) -> IO b
6+
7+ foreign import return :: forall a. a -> IO a
8+
9+ foreign import bind :: forall a b. IO a -> (a -> IO b) -> IO b
10+
11+ foreign import showMessage :: String -> IO { }
12+
13+ foreign import prompt :: IO String
14+
15+ main = \_ -> prompt `bind` \s -> showMessage s
16+
17+module Main where
18+
19+main = Debug.Trace.trace "Done"
examples/passing/ExternRaw.pursnew file+15
@@ -0,0 +1,15 @@
1+module ExternRaw 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+module Main where
14+
15+main = Debug.Trace.trace "Done"
examples/passing/FFI.pursnew file+16
@@ -0,0 +1,16 @@
1+module FFI where
2+
3+foreign import foo :: String -> String
4+
5+bar :: String -> String
6+bar _ = foo "test"
7+
8+module FFIModuleTest where
9+
10+import FFI
11+
12+baz _ = foo "test"
13+
14+module Main where
15+
16+main = Debug.Trace.trace "Done"
examples/passing/FinalTagless.pursnew file+22
@@ -0,0 +1,22 @@
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/Foldable.pursnew file+19
@@ -0,0 +1,19 @@
1+module Main where
2+
3+ import Prelude
4+ import Data.Foldable
5+ import Data.Monoid
6+
7+ data Tree a = Node a | Branch (Tree a) (Tree a)
8+
9+ instance foldableTree :: Foldable Tree where
10+ foldr f z (Node x) = x `f` z
11+ foldr f z (Branch l r) = foldr f (foldr f z r) l
12+
13+ foldl f z (Node x) = z `f` x
14+ foldl f z (Branch l r) = foldl f (foldl f z l) r
15+
16+ foldMap f (Node x) = f x
17+ foldMap f (Branch l r) = foldMap f l <> foldMap f r
18+
19+ main = Debug.Trace.print <<< sum $ Branch (Node 1) (Branch (Node 2) (Node 3))
examples/passing/ForeignInstance.pursnew file+23
@@ -0,0 +1,23 @@
1+module Foo where
2+
3+class Foo a where
4+ foo :: a -> String
5+
6+foreign import instance fooArray :: (Foo a) => Foo [a]
7+
8+module M1 where
9+
10+foreign import instance fooNumber :: Foo.Foo Number
11+
12+module Main where
13+
14+import M1
15+import Foo
16+
17+foreign import instance fooString :: Foo String
18+
19+test1 _ = foo [1, 2, 3]
20+
21+test2 _ = foo "Test"
22+
23+main = Debug.Trace.trace "Done"
examples/passing/FunctionScope.pursnew file+17
@@ -0,0 +1,17 @@
1+module FunctionScope where
2+
3+ import Prelude
4+
5+ mkValue :: Number -> Number
6+ mkValue id = id
7+
8+module Main where
9+
10+ import Prelude
11+ import FunctionScope
12+
13+ main = do
14+ let value = mkValue 1
15+ if value == 1
16+ then Debug.Trace.trace "Done"
17+ else Control.Monad.Eff.Error.throwError "Not done"
examples/passing/Functions.pursnew file+17
@@ -0,0 +1,17 @@
1+module Functions 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+module Main where
16+
17+main = Debug.Trace.trace "Done"
examples/passing/Functions2.pursnew file+17
@@ -0,0 +1,17 @@
1+module Functions2 where
2+
3+ import Prelude
4+
5+ test :: forall a b. a -> b -> a
6+ test = \const _ -> const
7+
8+module Main where
9+
10+ import Prelude
11+ import Functions2
12+
13+ main = do
14+ let value = test "Done" {}
15+ if value == "Done"
16+ then Debug.Trace.trace "Done"
17+ else Control.Monad.Eff.Error.throwError "Not done"
examples/passing/Guards.pursnew file+16
@@ -0,0 +1,16 @@
1+module Guards 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+module Main where
15+
16+main = Debug.Trace.trace "Done"
examples/passing/Import.pursnew file+16
@@ -0,0 +1,16 @@
1+module M1 where
2+
3+ id :: forall a. a -> a
4+ id = \x -> x
5+
6+ foo = id
7+
8+module M2 where
9+
10+ import M1
11+
12+ main = \_ -> foo 42
13+
14+module Main where
15+
16+main = Debug.Trace.trace "Done"
examples/passing/ImportExplicit.pursnew file+14
@@ -0,0 +1,14 @@
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/passing/InferRecFunWithConstrainedArgument.pursnew file+8
@@ -0,0 +1,8 @@
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.pursnew file+21
@@ -0,0 +1,21 @@
1+module JSReserved where
2+
3+ import Prelude
4+
5+ yield = 0
6+ member = 1
7+
8+ public = \return -> return
9+
10+ this catch = catch
11+
12+module Main where
13+
14+ import Prelude
15+ import Data.Array
16+ import JSReserved
17+
18+ main = Debug.Trace.print [ yield
19+ , member
20+ , this 1
21+ , public 1 ]
examples/passing/Let.pursnew file+26
@@ -0,0 +1,26 @@
1+module Main where
2+
3+import Prelude
4+import Control.Monad.Eff
5+
6+test1 x = let y = x + 1 in y
7+
8+test2 x y =
9+ let x' = x + 1 in
10+ let y' = y + 1 in
11+ x' + y'
12+
13+test3 x = let 1 = x in 2
14+
15+test4 = let f x y z = x + y + z in
16+ f 1 2 3
17+
18+test5 = let f x [y, z] = x y z in
19+ f (+) [1, 2]
20+
21+main = do
22+ Debug.Trace.print (test1 1)
23+ Debug.Trace.print (test2 1 2)
24+ Debug.Trace.print (test3 1)
25+ Debug.Trace.print test4
26+ Debug.Trace.print test5
examples/passing/List.pursnew file+10
@@ -0,0 +1,10 @@
1+module Main where
2+
3+import Prelude
4+import Control.Monad.Eff
5+import Data.Array
6+import Global
7+
8+main = do
9+ let test1 = concat [1, 2, 3] [4, 5, 6]
10+ Debug.Trace.print test1
examples/passing/MPTCs.pursnew file+24
@@ -0,0 +1,24 @@
1+module Main where
2+
3+import Prelude
4+import Data.Array
5+
6+class NullaryTypeClass where
7+ greeting :: String
8+
9+instance nullaryTypeClass :: NullaryTypeClass where
10+ greeting = "Hello, World!"
11+
12+class Coerce a b where
13+ coerce :: a -> b
14+
15+instance coerceRefl :: Coerce a a where
16+ coerce a = a
17+
18+instance coerceShow :: (Prelude.Show a) => Coerce a String where
19+ coerce = show
20+
21+instance coerceArray :: (Coerce a b) => Coerce [a] [b] where
22+ coerce = map coerce
23+
24+main = Debug.Trace.print $ coerce [greeting] :: [String]
examples/passing/Match.pursnew file+9
@@ -0,0 +1,9 @@
1+module Match where
2+
3+ data Foo a = Foo
4+
5+ foo = \f -> case f of Foo -> "foo"
6+
7+module Main where
8+
9+main = Debug.Trace.trace "Done"
examples/passing/Math.pursnew file+10
@@ -0,0 +1,10 @@
1+module Main where
2+
3+ import Prelude
4+ import Debug.Trace
5+ import Control.Monad.Eff
6+
7+ main = do
8+ print $ Math.sin 0
9+ print $ Math.sin $ Math.pi * 0.5
10+ print $ Math.e / Math.ln2
examples/passing/Maybe.pursnew file+12
@@ -0,0 +1,12 @@
1+module Main where
2+
3+import Prelude
4+import Data.Maybe
5+import Global
6+
7+main = do
8+ let test1 = fromMaybe 0 $ do
9+ a <- Just 1
10+ b <- Just 2
11+ return (a + b)
12+ Debug.Trace.print test1
examples/passing/Module.pursnew file+28
@@ -0,0 +1,28 @@
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/passing/ModuleDeps.pursnew file+17
@@ -0,0 +1,17 @@
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/passing/Monad.pursnew file+32
@@ -0,0 +1,32 @@
1+module MonadTest where
2+
3+ type Monad m = { return :: forall a. a -> m a
4+ , bind :: forall a b. m a -> (a -> m b) -> m b }
5+
6+ data Id a = Id a
7+
8+ id :: Monad Id
9+ id = { return : Id
10+ , bind : \ma f -> case ma of Id a -> f a }
11+
12+ data Maybe a = Nothing | Just a
13+
14+ maybe :: Monad Maybe
15+ maybe = { return : Just
16+ , bind : \ma f -> case ma of
17+ Nothing -> Nothing
18+ Just a -> f a
19+ }
20+
21+ test :: forall m. Monad m -> m Number
22+ test = \m -> m.bind (m.return 1) (\n1 ->
23+ m.bind (m.return "Test") (\n2 ->
24+ m.return n1))
25+
26+ test1 = test id
27+
28+ test2 = test maybe
29+
30+module Main where
31+
32+main = Debug.Trace.trace "Done"
examples/passing/MonadState.pursnew file+35
@@ -0,0 +1,35 @@
1+module Main where
2+
3+import Prelude
4+import Data.Tuple
5+
6+class MonadState s m where
7+ get :: m s
8+ put :: s -> m {}
9+
10+data State s a = State (s -> Tuple s a)
11+
12+runState s (State f) = f s
13+
14+instance monadState :: Prelude.Monad (State s) where
15+ return a = State $ \s -> Tuple s a
16+ (>>=) f g = State $ \s -> let (Tuple s1 a) = runState s f in
17+ runState s1 (g a)
18+
19+instance monadStateState :: MonadState s (State s) where
20+ get = State (\s -> Tuple s s)
21+ put s = State (\_ -> Tuple s {})
22+
23+modify :: forall m s. (Prelude.Monad m, MonadState s m) => (s -> s) -> m {}
24+modify f = do
25+ s <- get
26+ put (f s)
27+
28+test :: Tuple String String
29+test = runState "" $ do
30+ modify $ (++) "World!"
31+ modify $ (++) "Hello, "
32+ get
33+
34+main = Debug.Trace.print test
35+
examples/passing/MultipleConstructorArgs.pursnew file+28
@@ -0,0 +1,28 @@
1+module MultipleConstructorArgs where
2+
3+import Data.Array
4+
5+data P a b = P a b
6+
7+runP :: forall a b r. (a -> b -> r) -> P a b -> r
8+runP f (P a b) = f a b
9+
10+idP = runP P
11+
12+testCase = \p -> case p of
13+ P (x:xs) (y:ys) -> x : y : testCase (P xs ys)
14+ P _ _ -> []
15+
16+test1 = testCase (P [1, 2, 3] [4, 5, 6])
17+
18+module Main where
19+
20+import Prelude
21+import MultipleConstructorArgs
22+import Global
23+import Control.Monad.Eff
24+import Data.Array
25+
26+main = do
27+ Debug.Trace.trace (runP (\s n -> s ++ show n) (P "Test" 1))
28+ Debug.Trace.print test1
examples/passing/MutRec.pursnew file+21
@@ -0,0 +1,21 @@
1+module MutRec 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+module Main where
20+
21+main = Debug.Trace.trace "Done"
examples/passing/NamedPatterns.pursnew file+9
@@ -0,0 +1,9 @@
1+module NamedPatterns where
2+
3+ foo = \x -> case x of
4+ y@{ foo = "Foo" } -> y
5+ y -> y
6+
7+module Main where
8+
9+main = Debug.Trace.trace "Done"
examples/passing/Nested.pursnew file+9
@@ -0,0 +1,9 @@
1+module Nested 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+module Main where
8+
9+main = Debug.Trace.trace "Done"
examples/passing/NestedTypeSynonyms.pursnew file+13
@@ -0,0 +1,13 @@
1+module NestedTypeSynonyms where
2+
3+ type X = String
4+ type Y = X -> X
5+
6+ fn :: Y
7+ fn a = a
8+
9+module Main where
10+
11+ import Prelude
12+
13+ main = Debug.Trace.print (NestedTypeSynonyms.fn "Done")
examples/passing/ObjectSynonym.pursnew file+15
@@ -0,0 +1,15 @@
1+module ObjectSynonym 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+module Main where
14+
15+main = Debug.Trace.trace "Done"
examples/passing/ObjectUpdate.pursnew file+22
@@ -0,0 +1,22 @@
1+module ObjectUpdate 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+module Main where
19+
20+import ObjectUpdate
21+
22+main = Debug.Trace.trace ((update1 {foo: ""}).foo)
examples/passing/Objects.pursnew file+20
@@ -0,0 +1,20 @@
1+module Objects 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+module Main where
19+
20+main = Debug.Trace.trace "Done"
examples/passing/OneConstructor.pursnew file+9
@@ -0,0 +1,9 @@
1+module OneConstructor where
2+
3+data One a = One a
4+
5+one (One a) = a
6+
7+module Main where
8+
9+main = Debug.Trace.trace "Done"
examples/passing/Operators.pursnew file+86
@@ -0,0 +1,86 @@
1+module Operators1 where
2+
3+ import Prelude ((++))
4+
5+ (@@) :: forall a b. (a -> b) -> a -> b
6+ (@@) = \f x -> f x
7+
8+ foo :: String -> String
9+ foo = \s -> s
10+
11+ test8 = foo @@ "Hello World"
12+
13+ bar = \s1 s2 -> s1 ++ s2
14+
15+module Operators2 where
16+
17+ import Prelude
18+ import Operators1 ((@@))
19+
20+ test1 :: forall n. (Num n) => n -> n -> (n -> n -> n) -> n
21+ test1 x y z = x * y + z x y
22+
23+ test2 = (\x -> x.foo false) { foo : \_ -> 1 }
24+
25+ test3 = (\x y -> x)(1 + 2 * (1 + 2)) (true && (false || false))
26+
27+ k = \x -> \y -> x
28+
29+ test4 = 1 `k` 2
30+
31+ infixl 5 %%
32+
33+ (%%) :: Number -> Number -> Number
34+ (%%) x y = x * y + y
35+
36+ test5 = 1 %% 2 %% 3
37+
38+ test6 = ((\x -> x) `k` 2) 3
39+
40+ (<>) = \s1 s2 -> s1 ++ s2
41+
42+ test7 = "Hello" <> "World!"
43+
44+ test9 = Operators1.foo @@ "Hello World"
45+
46+ test10 = "Hello" `Operators1.bar` "World"
47+
48+ (...) :: forall a. [a] -> [a] -> [a]
49+ (...) = \as -> \bs -> as
50+
51+ test11 = [1, 2, 3] ... [4, 5, 6]
52+
53+ test12 (<%>) a b = a <%> b
54+
55+ test13 = \(<%>) a b -> a <%> b
56+
57+ test14 :: Number -> Number -> Boolean
58+ test14 a b = a < b
59+
60+module Main where
61+
62+import Operators1
63+import Operators2
64+
65+import Prelude
66+import Control.Monad.Eff
67+import Debug.Trace
68+import Global
69+import Data.Array
70+
71+main =
72+ print [ show $ test1 1 2 $ \x y -> x + y
73+ , show test2
74+ , show test3
75+ , show test4
76+ , show test5
77+ , show test6
78+ , show test7
79+ , show test8
80+ , show test9
81+ , show test10
82+ , show test11
83+ , show (test12 k 1 2)
84+ , show (test13 k 1 2)
85+ , show (test14 1 2)
86+ ]
examples/passing/OptimizerBug.pursnew file+11
@@ -0,0 +1,11 @@
1+module OptimizerBug where
2+
3+import Prelude
4+
5+x a = 1 + y a
6+
7+y a = x a
8+
9+module Main where
10+
11+main = Debug.Trace.trace "Done"
examples/passing/Patterns.pursnew file+30
@@ -0,0 +1,30 @@
1+module Patterns 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+module Main where
29+
30+main = Debug.Trace.trace "Done"
examples/passing/Person.pursnew file+15
@@ -0,0 +1,15 @@
1+module Person where
2+
3+ import Prelude ((++))
4+
5+ data Person = Person { name :: String, age :: Number }
6+
7+ foreign import itoa :: Number -> String
8+
9+ showPerson :: Person -> String
10+ showPerson = \p -> case p of
11+ Person o -> o.name ++ ", aged " ++ itoa(o.age)
12+
13+module Main where
14+
15+main = Debug.Trace.trace "Done"
examples/passing/Rank2Data.pursnew file+31
@@ -0,0 +1,31 @@
1+module Rank2Data 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+module Main where
30+
31+main = Debug.Trace.trace "Done"
examples/passing/Rank2Types.pursnew file+25
@@ -0,0 +1,25 @@
1+module Rank2Types where
2+
3+ import Prelude
4+
5+ test1 :: (forall a. (a -> a)) -> Number
6+ test1 = \f -> f 0
7+
8+ foreign import data ST :: * -> * -> *
9+
10+ foreign import runST :: forall a. (forall s. ST s a) -> a
11+
12+ foreign import exampleST :: forall s. ST s Number
13+
14+ testST = \_ -> runST exampleST
15+
16+ foreign import push :: forall el. el -> [el] -> [el]
17+
18+ replicateM :: forall m a. (forall a. a -> m a) -> (forall a b. m a -> (a -> m b) -> m b) -> Number -> m a -> m [a]
19+ replicateM = \return bind n m -> case n of
20+ 0 -> return []
21+ n -> bind m (\x -> bind (replicateM return bind (n - 1) m) (\xs -> return (push x xs)))
22+
23+module Main where
24+
25+main = Debug.Trace.trace "Done"
examples/passing/Recursion.pursnew file+12
@@ -0,0 +1,12 @@
1+module Recursion 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+module Main where
11+
12+main = Debug.Trace.trace "Done"
examples/passing/RedefinedFixity.pursnew file+18
@@ -0,0 +1,18 @@
1+module M1 where
2+
3+($) f a = f a
4+
5+infixr 1000 $
6+
7+module M2 where
8+
9+import M1
10+
11+module M3 where
12+
13+import M1
14+import M2
15+
16+module Main where
17+
18+main = Debug.Trace.trace "Done"
examples/passing/RuntimeScopeIssue.pursnew file+25
@@ -0,0 +1,25 @@
1+module RuntimeScopeIssue 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+module Main where
20+
21+import RuntimeScopeIssue
22+
23+import Prelude
24+
25+main = Debug.Trace.print $ a 10
examples/passing/STArray.pursnew file+23
@@ -0,0 +1,23 @@
1+module Main where
2+
3+import Prelude
4+import Control.Monad.Eff
5+import Control.Monad.ST
6+import Data.Array
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 _ arr | lo > hi = return arr
15+fromTo' lo hi i arr = do
16+ pokeSTArray arr i lo
17+ fromTo' (lo + 1) hi (i + 1) arr
18+
19+fromTo lo hi = runSTArray (do
20+ arr <- newSTArray (hi - lo + 1) 0
21+ fromTo' lo hi 0 arr)
22+
23+main = Debug.Trace.print $ runPure (fromTo 10 20)
examples/passing/TailCall.pursnew file+20
@@ -0,0 +1,20 @@
1+module TailCall 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+module Main where
16+
17+import Prelude
18+import TailCall
19+
20+main = Debug.Trace.print (test 0 [1, 2, 3])
examples/passing/Tick.pursnew file+7
@@ -0,0 +1,7 @@
1+module Tick where
2+
3+test' x = x
4+
5+module Main where
6+
7+main = Debug.Trace.trace "Done"
examples/passing/TopLevelCase.pursnew file+20
@@ -0,0 +1,20 @@
1+module TopLevelCase 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+module Main where
19+
20+main = Debug.Trace.trace "Done"
examples/passing/Traversable.pursnew file+8
@@ -0,0 +1,8 @@
1+module Main where
2+
3+ import Prelude
4+ import Data.Array
5+ import Data.Maybe
6+ import Data.Traversable
7+
8+ main = Debug.Trace.print (sequence (Just [1,2,3]))
examples/passing/TypeClasses.pursnew file+69
@@ -0,0 +1,69 @@
1+module TypeClasses 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+module TypeClasses2 where
41+
42+import Prelude
43+import TypeClasses
44+
45+instance showArray :: (Prelude.Show a) => Prelude.Show [a] where
46+ show [] = "[]"
47+ show (x:xs) = show x ++ ", " ++ show xs
48+
49+test6 = \_ -> show ["testing"]
50+
51+instance monadFunction :: Prelude.Monad ((->) r) where
52+ return a r = a
53+ (>>=) f g r = g (f r) r
54+
55+ask r = r
56+
57+runReader r f = f r
58+
59+test9 _ = runReader 0 $ do
60+ n <- ask
61+ return $ n + 1
62+
63+module Main where
64+
65+import Prelude
66+import TypeClasses
67+
68+main = Debug.Trace.trace (test7 "Done")
69+
examples/passing/TypeClassesInOrder.pursnew file+11
@@ -0,0 +1,11 @@
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.pursnew file+10
@@ -0,0 +1,10 @@
1+module Main where
2+
3+ import Prelude
4+ import Data.Either
5+
6+ instance functorEither :: Prelude.Functor (Either a) where
7+ (<$>) _ (Left x) = Left x
8+ (<$>) f (Right y) = Right (f y)
9+
10+ main = Debug.Trace.trace "Done"
examples/passing/TypeDecl.pursnew file+14
@@ -0,0 +1,14 @@
1+module TypeDecl 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+module Main where
13+
14+main = Debug.Trace.trace "Done"
examples/passing/TypeSynonymInData.pursnew file+9
@@ -0,0 +1,9 @@
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.pursnew file+40
@@ -0,0 +1,40 @@
1+module TypeSynonyms 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+ import Data.Array ((:))
26+ import Data.Array.Unsafe
27+
28+ headLens :: forall a. Lens [a] a
29+ headLens =
30+ { get: \l -> head l
31+ , set: \l a -> case l of
32+ _:xs -> a : xs
33+ }
34+
35+ test2 :: forall a b c. Lens (Pair [Pair a b] c) a
36+ test2 = composeLenses fst (composeLenses headLens fst)
37+
38+module Main where
39+
40+main = Debug.Trace.trace "Done"
examples/passing/iota.pursnew file+11
@@ -0,0 +1,11 @@
1+module Iota 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+module Main where
10+
11+main = Debug.Trace.trace "Done"
examples/passing/s.pursnew file+7
@@ -0,0 +1,7 @@
1+module S where
2+
3+ s = \x y z -> x z (y z)
4+
5+module Main where
6+
7+main = Debug.Trace.trace "Done"
package.yamldeleted−86
@@ -1,86 +0,0 @@
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.mdnew file+798
@@ -0,0 +1,798 @@
1+# Module Documentation
2+## Module Prelude
3+
4+### Types
5+
6+
7+### Type Classes
8+
9+ class Alternative f where
10+ empty :: forall a. f a
11+ (<|>) :: forall a. f a -> f a -> f a
12+
13+ class Applicative f where
14+ pure :: forall a. a -> f a
15+ (<*>) :: forall a b. f (a -> b) -> f a -> f b
16+
17+ class Bits b where
18+ (&) :: b -> b -> b
19+ (|) :: b -> b -> b
20+ (^) :: b -> b -> b
21+ shl :: b -> Prim.Number -> b
22+ shr :: b -> Prim.Number -> b
23+ zshr :: b -> Prim.Number -> b
24+ complement :: b -> b
25+
26+ class BoolLike b where
27+ (&&) :: b -> b -> b
28+ (||) :: b -> b -> b
29+ not :: b -> b
30+
31+ class Category a where
32+ id :: forall t. a t t
33+ (<<<) :: forall b c d. a c d -> a b c -> a b d
34+ (>>>) :: forall b c d. a b c -> a c d -> a b d
35+
36+ class Eq a where
37+ (==) :: a -> a -> Prim.Boolean
38+ (/=) :: a -> a -> Prim.Boolean
39+
40+ class Functor f where
41+ (<$>) :: forall a b. (a -> b) -> f a -> f b
42+
43+ class Monad m where
44+ return :: forall a. a -> m a
45+ (>>=) :: forall a b. m a -> (a -> m b) -> m b
46+
47+ class Num a where
48+ (+) :: a -> a -> a
49+ (-) :: a -> a -> a
50+ (*) :: a -> a -> a
51+ (/) :: a -> a -> a
52+ (%) :: a -> a -> a
53+ negate :: a -> a
54+
55+ class Ord a where
56+ (<) :: a -> a -> Prim.Boolean
57+ (>) :: a -> a -> Prim.Boolean
58+ (<=) :: a -> a -> Prim.Boolean
59+ (>=) :: a -> a -> Prim.Boolean
60+
61+ class Read a where
62+ read :: Prim.String -> a
63+
64+ class Show a where
65+ show :: a -> Prim.String
66+
67+
68+### Type Class Instances
69+
70+ instance applicativeFromMonad :: (Monad m) => Applicative m
71+
72+ instance bitsNumber :: Bits Prim.Number
73+
74+ instance boolLikeBoolean :: BoolLike Prim.Boolean
75+
76+ instance categoryArr :: Category Prim.Function
77+
78+ instance eqArray :: (Eq a) => Eq [a]
79+
80+ instance eqBoolean :: Eq Prim.Boolean
81+
82+ instance eqNumber :: Eq Prim.Number
83+
84+ instance eqString :: Eq Prim.String
85+
86+ instance functorFromApplicative :: (Applicative f) => Functor f
87+
88+ instance numNumber :: Num Prim.Number
89+
90+ instance ordNumber :: Ord Prim.Number
91+
92+ instance readBoolean :: Read Prim.Boolean
93+
94+ instance readNumber :: Read Prim.Number
95+
96+ instance readString :: Read Prim.String
97+
98+ instance showBoolean :: Show Prim.Boolean
99+
100+ instance showNumber :: Show Prim.Number
101+
102+ instance showString :: Show Prim.String
103+
104+
105+### Values
106+
107+ (!!) :: forall a. [a] -> Prim.Number -> a
108+
109+ (#) :: forall a b. a -> (a -> b) -> b
110+
111+ ($) :: forall a b. (a -> b) -> a -> b
112+
113+ (++) :: Prim.String -> Prim.String -> Prim.String
114+
115+ boolAnd :: Prim.Boolean -> Prim.Boolean -> Prim.Boolean
116+
117+ boolNot :: Prim.Boolean -> Prim.Boolean
118+
119+ boolOr :: Prim.Boolean -> Prim.Boolean -> Prim.Boolean
120+
121+ const :: forall a b. a -> b -> a
122+
123+ flip :: forall a b c. (a -> b -> c) -> b -> a -> c
124+
125+ numAdd :: Prim.Number -> Prim.Number -> Prim.Number
126+
127+ numAnd :: Prim.Number -> Prim.Number -> Prim.Number
128+
129+ numComplement :: Prim.Number -> Prim.Number
130+
131+ numDiv :: Prim.Number -> Prim.Number -> Prim.Number
132+
133+ numGreater :: Prim.Number -> Prim.Number -> Prim.Boolean
134+
135+ numGreaterEq :: Prim.Number -> Prim.Number -> Prim.Boolean
136+
137+ numLess :: Prim.Number -> Prim.Number -> Prim.Boolean
138+
139+ numLessEq :: Prim.Number -> Prim.Number -> Prim.Boolean
140+
141+ numMod :: Prim.Number -> Prim.Number -> Prim.Number
142+
143+ numMul :: Prim.Number -> Prim.Number -> Prim.Number
144+
145+ numNegate :: Prim.Number -> Prim.Number
146+
147+ numOr :: Prim.Number -> Prim.Number -> Prim.Number
148+
149+ numShl :: Prim.Number -> Prim.Number -> Prim.Number
150+
151+ numShr :: Prim.Number -> Prim.Number -> Prim.Number
152+
153+ numSub :: Prim.Number -> Prim.Number -> Prim.Number
154+
155+ numXor :: Prim.Number -> Prim.Number -> Prim.Number
156+
157+ numZshr :: Prim.Number -> Prim.Number -> Prim.Number
158+
159+ readNumberImpl :: Prim.String -> Prim.Number
160+
161+ showNumberImpl :: Prim.Number -> Prim.String
162+
163+ unsafeRefEq :: forall a. a -> a -> Prim.Boolean
164+
165+ unsafeRefIneq :: forall a. a -> a -> Prim.Boolean
166+
167+
168+## Module Data.Monoid
169+
170+### Types
171+
172+
173+### Type Classes
174+
175+ class Monoid m where
176+ mempty :: m
177+ (<>) :: m -> m -> m
178+
179+
180+### Type Class Instances
181+
182+ instance monoidArray :: Monoid [a]
183+
184+ instance monoidString :: Monoid Prim.String
185+
186+
187+### Values
188+
189+ mconcat :: forall m. (Monoid m) => [m] -> m
190+
191+
192+## Module Control.Monad
193+
194+### Types
195+
196+
197+### Type Classes
198+
199+
200+### Type Class Instances
201+
202+
203+### Values
204+
205+ (<=<) :: forall m a b c. (Monad m) => (b -> m c) -> (a -> m b) -> a -> m c
206+
207+ (>=>) :: forall m a b c. (Monad m) => (a -> m b) -> (b -> m c) -> a -> m c
208+
209+ foldM :: forall m a b. (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
210+
211+ join :: forall m a. (Monad m) => m (m a) -> m a
212+
213+ mapM :: forall m a b. (Monad m) => (a -> m b) -> [a] -> m [b]
214+
215+ replicateM :: forall m a. (Monad m) => Prim.Number -> m a -> m [a]
216+
217+ sequence :: forall m a. (Monad m) => [m a] -> m [a]
218+
219+ when :: forall m. (Monad m) => Prim.Boolean -> m { } -> m { }
220+
221+ zipWithM :: forall m a b c. (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m [c]
222+
223+
224+## Module Data.Maybe
225+
226+### Types
227+
228+ data Maybe a where
229+ Nothing :: Maybe a
230+ Just :: a -> Maybe a
231+
232+
233+### Type Classes
234+
235+
236+### Type Class Instances
237+
238+ instance applicativeMaybe :: Applicative Maybe
239+
240+ instance functorMaybe :: Functor Maybe
241+
242+ instance monadMaybe :: Monad Maybe
243+
244+ instance showMaybe :: (Show a) => Show (Maybe a)
245+
246+
247+### Values
248+
249+ fromMaybe :: forall a. a -> Maybe a -> a
250+
251+ maybe :: forall a b. b -> (a -> b) -> Maybe a -> b
252+
253+
254+## Module Data.Either
255+
256+### Types
257+
258+ data Either a b where
259+ Left :: a -> Either a b
260+ Right :: b -> Either a b
261+
262+
263+### Type Classes
264+
265+
266+### Type Class Instances
267+
268+ instance applicativeEither :: Applicative (Either e)
269+
270+ instance functorEither :: Functor (Either a)
271+
272+ instance monadEither :: Monad (Either e)
273+
274+ instance showEither :: (Show a, Show b) => Show (Either a b)
275+
276+
277+### Values
278+
279+ either :: forall a b c. (a -> c) -> (b -> c) -> Either a b -> c
280+
281+
282+## Module Data.Array
283+
284+### Types
285+
286+
287+### Type Classes
288+
289+
290+### Type Class Instances
291+
292+ instance alternativeArray :: Alternative Prim.Array
293+
294+ instance functorArray :: Functor Prim.Array
295+
296+ instance monadArray :: Monad Prim.Array
297+
298+ instance showArray :: (Show a) => Show [a]
299+
300+
301+### Values
302+
303+ (:) :: forall a. a -> [a] -> [a]
304+
305+ all :: forall a. (a -> Prim.Boolean) -> [a] -> Prim.Boolean
306+
307+ any :: forall a. (a -> Prim.Boolean) -> [a] -> Prim.Boolean
308+
309+ concat :: forall a. [a] -> [a] -> [a]
310+
311+ concatMap :: forall a b. [a] -> (a -> [b]) -> [b]
312+
313+ deleteAt :: forall a. Prim.Number -> Prim.Number -> [a] -> [a]
314+
315+ drop :: forall a. Prim.Number -> [a] -> [a]
316+
317+ filter :: forall a. (a -> Prim.Boolean) -> [a] -> [a]
318+
319+ find :: forall a. (a -> Prim.Boolean) -> [a] -> Maybe a
320+
321+ foldl :: forall a b. (b -> a -> b) -> b -> [a] -> b
322+
323+ foldr :: forall a b. (a -> b -> a) -> a -> [b] -> a
324+
325+ head :: forall a. [a] -> Maybe a
326+
327+ indexOf :: forall a. [a] -> a -> Prim.Number
328+
329+ insertAt :: forall a. Prim.Number -> a -> [a] -> [a]
330+
331+ isEmpty :: forall a. [a] -> Prim.Boolean
332+
333+ joinS :: [Prim.String] -> Prim.String
334+
335+ joinWith :: [Prim.String] -> Prim.String -> Prim.String
336+
337+ lastIndexOf :: forall a. [a] -> a -> Prim.Number
338+
339+ length :: forall a. [a] -> Prim.Number
340+
341+ map :: forall a b. (a -> b) -> [a] -> [b]
342+
343+ push :: forall a. [a] -> a -> [a]
344+
345+ range :: Prim.Number -> Prim.Number -> [Prim.Number]
346+
347+ reverse :: forall a. [a] -> [a]
348+
349+ shift :: forall a. [a] -> [a]
350+
351+ singleton :: forall a. a -> [a]
352+
353+ slice :: forall a. Prim.Number -> Prim.Number -> [a] -> [a]
354+
355+ sort :: forall a. [a] -> [a]
356+
357+ tail :: forall a. [a] -> Maybe [a]
358+
359+ take :: forall a. Prim.Number -> [a] -> [a]
360+
361+ updateAt :: forall a. Prim.Number -> a -> [a] -> [a]
362+
363+ zipWith :: forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
364+
365+
366+## Module Data.Eq
367+
368+### Types
369+
370+ data Ref a where
371+ Ref :: a -> Ref a
372+
373+
374+### Type Classes
375+
376+
377+### Type Class Instances
378+
379+ instance eqRef :: Eq (Ref a)
380+
381+
382+### Values
383+
384+ liftRef :: forall a b. (a -> a -> b) -> Ref a -> Ref a -> b
385+
386+ refEq :: forall a. Ref a -> Ref a -> Prim.Boolean
387+
388+ refIneq :: forall a. Ref a -> Ref a -> Prim.Boolean
389+
390+
391+## Module Data.Array.Unsafe
392+
393+### Types
394+
395+
396+### Type Classes
397+
398+
399+### Type Class Instances
400+
401+
402+### Values
403+
404+ head :: forall a. [a] -> a
405+
406+ tail :: forall a. [a] -> [a]
407+
408+
409+## Module Data.Tuple
410+
411+### Types
412+
413+ data Tuple a b where
414+ Tuple :: a -> b -> Tuple a b
415+
416+
417+### Type Classes
418+
419+
420+### Type Class Instances
421+
422+ instance showTuple :: (Show a, Show b) => Show (Tuple a b)
423+
424+
425+### Values
426+
427+ curry :: forall a b c. (Tuple a b -> c) -> a -> b -> c
428+
429+ uncurry :: forall a b c. (a -> b -> c) -> Tuple a b -> c
430+
431+ unzip :: forall a b. [Tuple a b] -> Tuple [a] [b]
432+
433+ zip :: forall a b. [a] -> [b] -> [Tuple a b]
434+
435+
436+## Module Data.String
437+
438+### Types
439+
440+
441+### Type Classes
442+
443+
444+### Type Class Instances
445+
446+
447+### Values
448+
449+ charAt :: Prim.Number -> Prim.String -> Prim.String
450+
451+ indexOfS :: Prim.String -> Prim.String -> Prim.Number
452+
453+ lastIndexOfS :: Prim.String -> Prim.String -> Prim.Number
454+
455+ lengthS :: Prim.String -> Prim.Number
456+
457+ localeCompare :: Prim.String -> Prim.String -> Prim.Number
458+
459+ replace :: Prim.String -> Prim.String -> Prim.String -> Prim.String
460+
461+ sliceS :: Prim.Number -> Prim.Number -> Prim.String -> Prim.String
462+
463+ split :: Prim.String -> Prim.String -> [Prim.String]
464+
465+ substr :: Prim.Number -> Prim.Number -> Prim.String -> Prim.String
466+
467+ substring :: Prim.Number -> Prim.Number -> Prim.String -> Prim.String
468+
469+ toLower :: Prim.String -> Prim.String
470+
471+ toUpper :: Prim.String -> Prim.String
472+
473+ trim :: Prim.String -> Prim.String
474+
475+
476+## Module Data.String.Regex
477+
478+### Types
479+
480+ data Regex :: *
481+
482+
483+### Type Classes
484+
485+
486+### Type Class Instances
487+
488+
489+### Values
490+
491+ match :: Regex -> Prim.String -> [Prim.String]
492+
493+ regex :: Prim.String -> Prim.String -> Regex
494+
495+ replaceR :: Regex -> Prim.String -> Prim.String -> Prim.String
496+
497+ search :: Regex -> Prim.String -> Prim.Number
498+
499+ test :: Regex -> Prim.String -> Prim.Boolean
500+
501+
502+## Module Global
503+
504+### Types
505+
506+
507+### Type Classes
508+
509+
510+### Type Class Instances
511+
512+
513+### Values
514+
515+ decodeURI :: Prim.String -> Prim.String
516+
517+ decodeURIComponent :: Prim.String -> Prim.String
518+
519+ encodeURI :: Prim.String -> Prim.String
520+
521+ encodeURIComponent :: Prim.String -> Prim.String
522+
523+ infinity :: Prim.Number
524+
525+ isFinite :: Prim.Number -> Prim.Boolean
526+
527+ isNaN :: Prim.Number -> Prim.Boolean
528+
529+ nan :: Prim.Number
530+
531+ parseFloat :: Prim.String -> Prim.Number
532+
533+ parseInt :: Prim.String -> Prim.Number
534+
535+ toExponential :: Prim.Number -> Prim.String
536+
537+ toFixed :: Prim.Number -> Prim.Number -> Prim.String
538+
539+ toPrecision :: Prim.Number -> Prim.Number -> Prim.String
540+
541+
542+## Module Math
543+
544+### Types
545+
546+
547+### Type Classes
548+
549+
550+### Type Class Instances
551+
552+
553+### Values
554+
555+ abs :: Prim.Number -> Prim.Number
556+
557+ aceil :: Prim.Number -> Prim.Number
558+
559+ acos :: Prim.Number -> Prim.Number
560+
561+ asin :: Prim.Number -> Prim.Number
562+
563+ atan :: Prim.Number -> Prim.Number
564+
565+ atan2 :: Prim.Number -> Prim.Number -> Prim.Number
566+
567+ cos :: Prim.Number -> Prim.Number
568+
569+ e :: Prim.Number
570+
571+ exp :: Prim.Number -> Prim.Number
572+
573+ floor :: Prim.Number -> Prim.Number
574+
575+ ln10 :: Prim.Number
576+
577+ ln2 :: Prim.Number
578+
579+ log :: Prim.Number -> Prim.Number
580+
581+ log10e :: Prim.Number
582+
583+ log2e :: Prim.Number
584+
585+ max :: Prim.Number -> Prim.Number -> Prim.Number
586+
587+ min :: Prim.Number -> Prim.Number -> Prim.Number
588+
589+ pi :: Prim.Number
590+
591+ pow :: Prim.Number -> Prim.Number -> Prim.Number
592+
593+ round :: Prim.Number -> Prim.Number
594+
595+ sin :: Prim.Number -> Prim.Number
596+
597+ sqrt :: Prim.Number -> Prim.Number
598+
599+ sqrt1_2 :: Prim.Number
600+
601+ sqrt2 :: Prim.Number
602+
603+ tan :: Prim.Number -> Prim.Number
604+
605+
606+## Module Control.Monad.Eff
607+
608+### Types
609+
610+ data Eff :: # ! -> * -> *
611+
612+ type Pure a = forall e. Eff e a
613+
614+
615+### Type Classes
616+
617+
618+### Type Class Instances
619+
620+ instance monadEff :: Monad (Eff e)
621+
622+
623+### Values
624+
625+ bindEff :: forall e a b. Eff e a -> (a -> Eff e b) -> Eff e b
626+
627+ forE :: forall e. Prim.Number -> Prim.Number -> (Prim.Number -> Eff e { }) -> Eff e { }
628+
629+ foreachE :: forall e a. [a] -> (a -> Eff e { }) -> Eff e { }
630+
631+ retEff :: forall e a. a -> Eff e a
632+
633+ runPure :: forall a. Pure a -> a
634+
635+ untilE :: forall e. Eff e Prim.Boolean -> Eff e { }
636+
637+ whileE :: forall e a. Eff e Prim.Boolean -> Eff e a -> Eff e { }
638+
639+
640+## Module Control.Monad.Eff.Unsafe
641+
642+### Types
643+
644+
645+### Type Classes
646+
647+
648+### Type Class Instances
649+
650+
651+### Values
652+
653+ unsafeInterleaveEff :: forall eff1 eff2 a. Eff eff1 a -> Eff eff2 a
654+
655+
656+## Module Random
657+
658+### Types
659+
660+ data Random :: !
661+
662+
663+### Type Classes
664+
665+
666+### Type Class Instances
667+
668+
669+### Values
670+
671+ random :: forall e. Eff (random :: Random | e) Prim.Number
672+
673+
674+## Module Control.Monad.Error
675+
676+### Types
677+
678+ data Error :: * -> !
679+
680+
681+### Type Classes
682+
683+
684+### Type Class Instances
685+
686+
687+### Values
688+
689+ catchError :: forall e r a. (e -> Eff r a) -> Eff (err :: Error e | r) a -> Eff r a
690+
691+ throwError :: forall a e r. e -> Eff (err :: Error e | r) a
692+
693+
694+## Module Data.IORef
695+
696+### Types
697+
698+ data IORef :: * -> *
699+
700+ data Ref :: !
701+
702+
703+### Type Classes
704+
705+
706+### Type Class Instances
707+
708+
709+### Values
710+
711+ modifyIORef :: forall s r. IORef s -> (s -> s) -> Eff (ref :: Ref | r) { }
712+
713+ newIORef :: forall s r. s -> Eff (ref :: Ref | r) (IORef s)
714+
715+ readIORef :: forall s r. IORef s -> Eff (ref :: Ref | r) s
716+
717+ unsafeRunIORef :: forall eff a. Eff (ref :: Ref | eff) a -> Eff eff a
718+
719+ writeIORef :: forall s r. IORef s -> s -> Eff (ref :: Ref | r) { }
720+
721+
722+## Module Debug.Trace
723+
724+### Types
725+
726+ data Trace :: !
727+
728+
729+### Type Classes
730+
731+
732+### Type Class Instances
733+
734+
735+### Values
736+
737+ print :: forall a r. (Show a) => a -> Eff (trace :: Trace | r) { }
738+
739+ trace :: forall r. Prim.String -> Eff (trace :: Trace | r) { }
740+
741+
742+## Module Control.Monad.ST
743+
744+### Types
745+
746+ data ST :: * -> !
747+
748+ data STArray :: * -> * -> *
749+
750+ data STRef :: * -> * -> *
751+
752+
753+### Type Classes
754+
755+
756+### Type Class Instances
757+
758+
759+### Values
760+
761+ modifySTRef :: forall a h r. STRef h a -> (a -> a) -> Eff (st :: ST h | r) a
762+
763+ newSTArray :: forall a h r. Prim.Number -> a -> Eff (st :: ST h | r) (STArray h a)
764+
765+ newSTRef :: forall a h r. a -> Eff (st :: ST h | r) (STRef h a)
766+
767+ peekSTArray :: forall a h r. STArray h a -> Eff (st :: ST h | r) a
768+
769+ pokeSTArray :: forall a h r. STArray h a -> Prim.Number -> a -> Eff (st :: ST h | r) a
770+
771+ readSTRef :: forall a h r. STRef h a -> Eff (st :: ST h | r) a
772+
773+ runST :: forall a r. forall h. Eff (st :: ST h | r) a -> Eff r a
774+
775+ runSTArray :: forall a r. forall h. Eff (st :: ST h | r) (STArray h a) -> Eff r [a]
776+
777+ writeSTRef :: forall a h r. STRef h a -> a -> Eff (st :: ST h | r) a
778+
779+
780+## Module Data.Enum
781+
782+### Types
783+
784+
785+### Type Classes
786+
787+ class Enum a where
788+ toEnum :: Prim.Number -> Maybe a
789+ fromEnum :: a -> Prim.Number
790+
791+
792+### Type Class Instances
793+
794+
795+### Values
796+
797+
798+
prelude/prelude.pursnew file+1368
@@ -0,0 +1,1368 @@
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+ infixr 9 >>>
10+ infixr 9 <<<
11+
12+ class Category a where
13+ id :: forall t. a t t
14+ (<<<) :: forall b c d. a c d -> a b c -> a b d
15+
16+ (>>>) :: forall a b c d. (Category a) => a b c -> a c d -> a b d
17+ (>>>) f g = g <<< f
18+
19+ instance categoryArr :: Category (->) where
20+ id x = x
21+ (<<<) f g x = f (g x)
22+
23+ infixr 0 $
24+ infixl 0 #
25+
26+ ($) :: forall a b. (a -> b) -> a -> b
27+ ($) f x = f x
28+
29+ (#) :: forall a b. a -> (a -> b) -> b
30+ (#) x f = f x
31+
32+ class Show a where
33+ show :: a -> String
34+
35+ instance showString :: Show String where
36+ show s = s
37+
38+ instance showBoolean :: Show Boolean where
39+ show true = "true"
40+ show false = "false"
41+
42+ foreign import showNumberImpl "function showNumberImpl(n) {\
43+ \ return n.toString();\
44+ \}" :: Number -> String
45+
46+ instance showNumber :: Show Number where
47+ show = showNumberImpl
48+
49+ infixl 4 <$>
50+
51+ class Functor f where
52+ (<$>) :: forall a b. (a -> b) -> f a -> f b
53+
54+ infixl 4 <*>
55+
56+ class Applicative f where
57+ pure :: forall a. a -> f a
58+ (<*>) :: forall a b. f (a -> b) -> f a -> f b
59+
60+ instance functorFromApplicative :: (Applicative f) => Functor f where
61+ (<$>) f a = pure f <*> a
62+
63+ infixl 3 <|>
64+
65+ class Alternative f where
66+ empty :: forall a. f a
67+ (<|>) :: forall a. f a -> f a -> f a
68+
69+ infixl 1 >>=
70+
71+ class Monad m where
72+ return :: forall a. a -> m a
73+ (>>=) :: forall a b. m a -> (a -> m b) -> m b
74+
75+ instance applicativeFromMonad :: (Monad m) => Applicative m where
76+ pure = return
77+ (<*>) f a = do
78+ f' <- f
79+ a' <- a
80+ return (f' a')
81+
82+ infixl 7 *
83+ infixl 7 /
84+ infixl 7 %
85+
86+ infixl 6 -
87+ infixl 6 +
88+
89+ class Num a where
90+ (+) :: a -> a -> a
91+ (-) :: a -> a -> a
92+ (*) :: a -> a -> a
93+ (/) :: a -> a -> a
94+ (%) :: a -> a -> a
95+ negate :: a -> a
96+
97+ foreign import numAdd "function numAdd(n1) {\
98+ \ return function(n2) {\
99+ \ return n1 + n2;\
100+ \ };\
101+ \}" :: Number -> Number -> Number
102+
103+ foreign import numSub "function numSub(n1) {\
104+ \ return function(n2) {\
105+ \ return n1 - n2;\
106+ \ };\
107+ \}" :: Number -> Number -> Number
108+
109+ foreign import numMul "function numMul(n1) {\
110+ \ return function(n2) {\
111+ \ return n1 * n2;\
112+ \ };\
113+ \}" :: Number -> Number -> Number
114+
115+ foreign import numDiv "function numDiv(n1) {\
116+ \ return function(n2) {\
117+ \ return n1 / n2;\
118+ \ };\
119+ \}" :: Number -> Number -> Number
120+
121+ foreign import numMod "function numMod(n1) {\
122+ \ return function(n2) {\
123+ \ return n1 % n2;\
124+ \ };\
125+ \}" :: Number -> Number -> Number
126+
127+ foreign import numNegate "function numNegate(n) {\
128+ \ return -n;\
129+ \}" :: Number -> Number
130+
131+ instance numNumber :: Num Number where
132+ (+) = numAdd
133+ (-) = numSub
134+ (*) = numMul
135+ (/) = numDiv
136+ (%) = numMod
137+ negate = numNegate
138+
139+ infixl 4 ==
140+ infixl 4 /=
141+
142+ class Eq a where
143+ (==) :: a -> a -> Boolean
144+ (/=) :: a -> a -> Boolean
145+
146+ foreign import unsafeRefEq "function unsafeRefEq(r1) {\
147+ \ return function(r2) {\
148+ \ return r1 === r2;\
149+ \ };\
150+ \}" :: forall a. a -> a -> Boolean
151+
152+ foreign import unsafeRefIneq "function unsafeRefIneq(r1) {\
153+ \ return function(r2) {\
154+ \ return r1 !== r2;\
155+ \ };\
156+ \}" :: forall a. a -> a -> Boolean
157+
158+ instance eqString :: Eq String where
159+ (==) = unsafeRefEq
160+ (/=) = unsafeRefIneq
161+
162+ instance eqNumber :: Eq Number where
163+ (==) = unsafeRefEq
164+ (/=) = unsafeRefIneq
165+
166+ instance eqBoolean :: Eq Boolean where
167+ (==) = unsafeRefEq
168+ (/=) = unsafeRefIneq
169+
170+ instance eqArray :: (Eq a) => Eq [a] where
171+ (==) [] [] = true
172+ (==) (x:xs) (y:ys) = x == y && xs == ys
173+ (==) _ _ = false
174+ (/=) xs ys = not (xs == ys)
175+
176+ data Ordering = LT | GT | EQ
177+
178+ instance showOrdering :: Show Ordering where
179+ show LT = "LT"
180+ show GT = "GT"
181+ show EQ = "EQ"
182+
183+ class Ord a where
184+ compare :: a -> a -> Ordering
185+
186+ infixl 4 <
187+
188+ (<) :: forall a. (Ord a) => a -> a -> Boolean
189+ (<) a1 a2 = case a1 `compare` a2 of
190+ LT -> true
191+ _ -> false
192+
193+ infixl 4 >
194+
195+ (>) :: forall a. (Ord a) => a -> a -> Boolean
196+ (>) a1 a2 = case a1 `compare` a2 of
197+ GT -> true
198+ _ -> false
199+
200+ infixl 4 <=
201+
202+ (<=) :: forall a. (Ord a) => a -> a -> Boolean
203+ (<=) a1 a2 = case a1 `compare` a2 of
204+ GT -> false
205+ _ -> true
206+
207+ infixl 4 >=
208+
209+ (>=) :: forall a. (Ord a) => a -> a -> Boolean
210+ (>=) a1 a2 = case a1 `compare` a2 of
211+ LT -> false
212+ _ -> true
213+
214+ foreign import numCompare
215+ "function numCompare(n1) {\
216+ \ return function(n2) {\
217+ \ return n1 < n2 ? module.LT : n1 > n2 ? module.GT : module.EQ;\
218+ \ };\
219+ \}" :: Number -> Number -> Ordering
220+
221+ instance ordNumber :: Ord Number where
222+ compare = numCompare
223+
224+ infixl 10 &
225+ infixl 10 |
226+ infixl 10 ^
227+
228+ class Bits b where
229+ (&) :: b -> b -> b
230+ (|) :: b -> b -> b
231+ (^) :: b -> b -> b
232+ shl :: b -> Number -> b
233+ shr :: b -> Number -> b
234+ zshr :: b -> Number -> b
235+ complement :: b -> b
236+
237+ foreign import numShl "function numShl(n1) {\
238+ \ return function(n2) {\
239+ \ return n1 << n2;\
240+ \ };\
241+ \}" :: Number -> Number -> Number
242+
243+ foreign import numShr "function numShr(n1) {\
244+ \ return function(n2) {\
245+ \ return n1 >> n2;\
246+ \ };\
247+ \}" :: Number -> Number -> Number
248+
249+ foreign import numZshr "function numZshr(n1) {\
250+ \ return function(n2) {\
251+ \ return n1 >>> n2;\
252+ \ };\
253+ \}" :: Number -> Number -> Number
254+
255+ foreign import numAnd "function numAnd(n1) {\
256+ \ return function(n2) {\
257+ \ return n1 & n2;\
258+ \ };\
259+ \}" :: Number -> Number -> Number
260+
261+ foreign import numOr "function numOr(n1) {\
262+ \ return function(n2) {\
263+ \ return n1 | n2;\
264+ \ };\
265+ \}" :: Number -> Number -> Number
266+
267+ foreign import numXor "function numXor(n1) {\
268+ \ return function(n2) {\
269+ \ return n1 ^ n2;\
270+ \ };\
271+ \}" :: Number -> Number -> Number
272+
273+ foreign import numComplement "function numComplement(n) {\
274+ \ return ~n;\
275+ \}" :: Number -> Number
276+
277+ instance bitsNumber :: Bits Number where
278+ (&) = numAnd
279+ (|) = numOr
280+ (^) = numXor
281+ shl = numShl
282+ shr = numShr
283+ zshr = numZshr
284+ complement = numComplement
285+
286+ infixl 8 !!
287+
288+ foreign import (!!) "function $bang$bang(xs) {\
289+ \ return function(n) {\
290+ \ return xs[n];\
291+ \ };\
292+ \}" :: forall a. [a] -> Number -> a
293+
294+ infixr 2 ||
295+ infixr 3 &&
296+
297+ class BoolLike b where
298+ (&&) :: b -> b -> b
299+ (||) :: b -> b -> b
300+ not :: b -> b
301+
302+ foreign import boolAnd "function boolAnd(b1) {\
303+ \ return function(b2) {\
304+ \ return b1 && b2;\
305+ \ };\
306+ \}" :: Boolean -> Boolean -> Boolean
307+
308+ foreign import boolOr "function boolOr(b1) {\
309+ \ return function(b2) {\
310+ \ return b1 || b2;\
311+ \ };\
312+ \}" :: Boolean -> Boolean -> Boolean
313+
314+ foreign import boolNot "function boolNot(b) {\
315+ \ return !b;\
316+ \}" :: Boolean -> Boolean
317+
318+ instance boolLikeBoolean :: BoolLike Boolean where
319+ (&&) = boolAnd
320+ (||) = boolOr
321+ not = boolNot
322+
323+ infixr 5 ++
324+
325+ foreign import (++) "function $plus$plus(s1) {\
326+ \ return function(s2) {\
327+ \ return s1 + s2;\
328+ \ };\
329+ \}" :: String -> String -> String
330+
331+module Data.Monoid where
332+
333+ import Prelude
334+
335+ infixr 6 <>
336+
337+ class Monoid m where
338+ mempty :: m
339+ (<>) :: m -> m -> m
340+
341+ instance monoidString :: Monoid String where
342+ mempty = ""
343+ (<>) = (++)
344+
345+ instance monoidArray :: Monoid [a] where
346+ mempty = []
347+ (<>) = Data.Array.concat
348+
349+module Control.Applicative where
350+
351+ import Prelude
352+
353+ infixl 4 <*
354+ infixl 4 *>
355+
356+ (<*) :: forall a b f. (Applicative f) => f a -> f b -> f a
357+ (<*) x y = const <$> x <*> y
358+
359+ (*>) :: forall a b f. (Applicative f) => f a -> f b -> f b
360+ (*>) x y = const id <$> x <*> y
361+
362+ lift2 :: forall a b c f. (Applicative f) => (a -> b -> c) -> f a -> f b -> f c
363+ lift2 f x y = f <$> x <*> y
364+
365+ lift3 :: forall a b c d f. (Applicative f) => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
366+ lift3 f x y z = f <$> x <*> y <*> z
367+
368+module Control.Monad where
369+
370+ import Prelude
371+ import Data.Array
372+ import Data.Traversable
373+
374+ replicateM :: forall m a. (Monad m) => Number -> m a -> m [a]
375+ replicateM 0 _ = return []
376+ replicateM n m = do
377+ a <- m
378+ as <- replicateM (n - 1) m
379+ return (a : as)
380+
381+ infixr 1 >=>
382+ infixr 1 <=<
383+
384+ (>=>) :: forall m a b c. (Monad m) => (a -> m b) -> (b -> m c) -> a -> m c
385+ (>=>) f g a = do
386+ b <- f a
387+ g b
388+
389+ (<=<) :: forall m a b c. (Monad m) => (b -> m c) -> (a -> m b) -> a -> m c
390+ (<=<) = flip (>=>)
391+
392+ join :: forall m a. (Monad m) => m (m a) -> m a
393+ join mm = do
394+ m <- mm
395+ m
396+
397+ foldM :: forall m a b. (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
398+ foldM _ a [] = return a
399+ foldM f a (b:bs) = f a b >>= \a' -> foldM f a' bs
400+
401+ when :: forall m. (Monad m) => Boolean -> m {} -> m {}
402+ when true m = m
403+ when false _ = return {}
404+
405+ zipWithA :: forall m a b c. (Applicative m) => (a -> b -> m c) -> [a] -> [b] -> m [c]
406+ zipWithA f xs ys = sequence (zipWith f xs ys)
407+
408+module Data.Maybe where
409+
410+ import Prelude
411+
412+ data Maybe a = Nothing | Just a
413+
414+ maybe :: forall a b. b -> (a -> b) -> Maybe a -> b
415+ maybe b _ Nothing = b
416+ maybe _ f (Just a) = f a
417+
418+ fromMaybe :: forall a. a -> Maybe a -> a
419+ fromMaybe a = maybe a (id :: forall a. a -> a)
420+
421+ instance monadMaybe :: Monad Maybe where
422+ return = Just
423+ (>>=) m f = maybe Nothing f m
424+
425+ instance applicativeMaybe :: Applicative Maybe where
426+ pure = Just
427+ (<*>) (Just fn) x = fn <$> x
428+ (<*>) Nothing _ = Nothing
429+
430+ instance functorMaybe :: Functor Maybe where
431+ (<$>) fn (Just x) = Just (fn x)
432+ (<$>) _ _ = Nothing
433+
434+ instance showMaybe :: (Show a) => Show (Maybe a) where
435+ show (Just x) = "Just " ++ (show x)
436+ show Nothing = "Nothing"
437+
438+ instance eqMaybe :: (Eq a) => Eq (Maybe a) where
439+ (==) Nothing Nothing = true
440+ (==) (Just a1) (Just a2) = a1 == a2
441+ (==) _ _ = false
442+ (/=) a b = not (a == b)
443+
444+module Data.Either where
445+
446+ import Prelude
447+
448+ data Either a b = Left a | Right b
449+
450+ either :: forall a b c. (a -> c) -> (b -> c) -> Either a b -> c
451+ either f _ (Left a) = f a
452+ either _ g (Right b) = g b
453+
454+ instance monadEither :: Monad (Either e) where
455+ return = Right
456+ (>>=) = either (\e _ -> Left e) (\a f -> f a)
457+
458+ instance applicativeEither :: Applicative (Either e) where
459+ pure = Right
460+ (<*>) (Left e) _ = Left e
461+ (<*>) (Right f) r = f <$> r
462+
463+ instance functorEither :: Functor (Either a) where
464+ (<$>) _ (Left x) = Left x
465+ (<$>) f (Right y) = Right (f y)
466+
467+ instance showEither :: (Show a, Show b) => Show (Either a b) where
468+ show (Left x) = "Left " ++ (show x)
469+ show (Right y) = "Right " ++ (show y)
470+
471+ instance eqEither :: (Eq a, Eq b) => Eq (Either a b) where
472+ (==) (Left a1) (Left a2) = a1 == a2
473+ (==) (Right b1) (Right b2) = b1 == b2
474+ (==) _ _ = false
475+ (/=) a b = not (a == b)
476+
477+module Data.Array where
478+
479+ import Prelude
480+ import Data.Maybe
481+
482+ head :: forall a. [a] -> Maybe a
483+ head (x : _) = Just x
484+ head _ = Nothing
485+
486+ tail :: forall a. [a] -> Maybe [a]
487+ tail (_ : xs) = Just xs
488+ tail _ = Nothing
489+
490+ map :: forall a b. (a -> b) -> [a] -> [b]
491+ map _ [] = []
492+ map f (x:xs) = f x : map f xs
493+
494+ foreign import length "function length(xs) {\
495+ \ return xs.length;\
496+ \}" :: forall a. [a] -> Number
497+
498+ foreign import indexOf "function indexOf(l) {\
499+ \ return function (e) {\
500+ \ return l.indexOf(e);\
501+ \ };\
502+ \}" :: forall a. [a] -> a -> Number
503+
504+ foreign import lastIndexOf "function lastIndexOf(l) {\
505+ \ return function (e) {\
506+ \ return l.lastIndexOf(e);\
507+ \ };\
508+ \}" :: forall a. [a] -> a -> Number
509+
510+ foreign import concat "function concat(l1) {\
511+ \ return function (l2) {\
512+ \ return l1.concat(l2);\
513+ \ };\
514+ \}" :: forall a. [a] -> [a] -> [a]
515+
516+ foreign import joinS "function joinS(l) {\
517+ \ return l.join();\
518+ \}" :: [String] -> String
519+
520+ foreign import joinWith "function joinWith(l) {\
521+ \ return function (s) {\
522+ \ return l.join(s);\
523+ \ };\
524+ \}" :: [String] -> String -> String
525+
526+ foreign import push "function push(l) {\
527+ \ return function (e) {\
528+ \ var l1 = l.slice();\
529+ \ l1.push(e); \
530+ \ return l1;\
531+ \ };\
532+ \}" :: forall a. [a] -> a -> [a]
533+
534+ foreign import reverse "function reverse(l) {\
535+ \ var l1 = l.slice();\
536+ \ l1.reverse(); \
537+ \ return l1;\
538+ \}" :: forall a. [a] -> [a]
539+
540+ foreign import shift "function shift(l) {\
541+ \ var l1 = l.slice();\
542+ \ l1.shift();\
543+ \ return l1;\
544+ \}" :: forall a. [a] -> [a]
545+
546+ foreign import slice "function slice(s) {\
547+ \ return function(e) {\
548+ \ return function (l) {\
549+ \ return l.slice(s, e);\
550+ \ };\
551+ \ };\
552+ \}" :: forall a. Number -> Number -> [a] -> [a]
553+
554+ foreign import sort "function sort(l) {\
555+ \ var l1 = l.slice();\
556+ \ l1.sort();\
557+ \ return l1;\
558+ \}" :: forall a. [a] -> [a]
559+
560+ foreign import insertAt
561+ "function insertAt(index) {\
562+ \ return function(a) {\
563+ \ return function(l) {\
564+ \ var l1 = l.slice();\
565+ \ l1.splice(index, 0, a);\
566+ \ return l1;\
567+ \ }; \
568+ \ };\
569+ \}":: forall a. Number -> a -> [a] -> [a]
570+
571+ foreign import deleteAt
572+ "function deleteAt(index) {\
573+ \ return function(n) {\
574+ \ return function(l) {\
575+ \ var l1 = l.slice();\
576+ \ l1.splice(index, n);\
577+ \ return l1;\
578+ \ }; \
579+ \ };\
580+ \}":: forall a. Number -> Number -> [a] -> [a]
581+
582+ foreign import updateAt
583+ "function updateAt(index) {\
584+ \ return function(a) {\
585+ \ return function(l) {\
586+ \ var l1 = l.slice();\
587+ \ l1[index] = a;\
588+ \ return l1;\
589+ \ }; \
590+ \ };\
591+ \}":: forall a. Number -> a -> [a] -> [a]
592+
593+ infixr 6 :
594+
595+ (:) :: forall a. a -> [a] -> [a]
596+ (:) a = concat [a]
597+
598+ singleton :: forall a. a -> [a]
599+ singleton a = [a]
600+
601+ concatMap :: forall a b. [a] -> (a -> [b]) -> [b]
602+ concatMap [] f = []
603+ concatMap (a:as) f = f a `concat` concatMap as f
604+
605+ filter :: forall a. (a -> Boolean) -> [a] -> [a]
606+ filter _ [] = []
607+ filter p (x:xs) | p x = x : filter p xs
608+ filter p (_:xs) = filter p xs
609+
610+ isEmpty :: forall a. [a] -> Boolean
611+ isEmpty [] = true
612+ isEmpty _ = false
613+
614+ range :: Number -> Number -> [Number]
615+ range lo hi | lo > hi = []
616+ range lo hi = lo : range (lo + 1) hi
617+
618+ zipWith :: forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
619+ zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
620+ zipWith _ _ _ = []
621+
622+ drop :: forall a. Number -> [a] -> [a]
623+ drop 0 xs = xs
624+ drop _ [] = []
625+ drop n (x:xs) = drop (n - 1) xs
626+
627+ take :: forall a. Number -> [a] -> [a]
628+ take 0 _ = []
629+ take _ [] = []
630+ take n (x:xs) = x : take (n - 1) xs
631+
632+ instance showArray :: (Show a) => Show [a] where
633+ show xs = "[" ++ joinWith (map show xs) "," ++ "]"
634+
635+ instance monadArray :: Monad [] where
636+ return = singleton
637+ (>>=) = concatMap
638+
639+ instance functorArray :: Functor [] where
640+ (<$>) = map
641+
642+ instance alternativeArray :: Alternative [] where
643+ empty = []
644+ (<|>) = concat
645+
646+module Data.Eq where
647+
648+ import Prelude
649+
650+ -- Referential equality
651+ data Ref a = Ref a
652+
653+ liftRef :: forall a b. (a -> a -> b) -> Ref a -> Ref a -> b
654+ liftRef f (Ref x) (Ref y) = f x y
655+
656+ refEq :: forall a. Ref a -> Ref a -> Boolean
657+ refEq = liftRef unsafeRefEq
658+
659+ refIneq :: forall a. Ref a -> Ref a -> Boolean
660+ refIneq = liftRef unsafeRefIneq
661+
662+ instance eqRef :: Eq (Ref a) where
663+ (==) = refEq
664+ (/=) = refIneq
665+
666+module Data.Array.Unsafe where
667+
668+ head :: forall a. [a] -> a
669+ head (x : _) = x
670+
671+ tail :: forall a. [a] -> [a]
672+ tail (_ : xs) = xs
673+
674+module Data.Tuple where
675+
676+ import Prelude
677+ import Data.Array
678+
679+ data Tuple a b = Tuple a b
680+
681+ instance showTuple :: (Show a, Show b) => Show (Tuple a b) where
682+ show (Tuple a b) = "Tuple(" ++ show a ++ ", " ++ show b ++ ")"
683+
684+ curry :: forall a b c. (Tuple a b -> c) -> a -> b -> c
685+ curry f a b = f (Tuple a b)
686+
687+ uncurry :: forall a b c. (a -> b -> c) -> Tuple a b -> c
688+ uncurry f (Tuple a b) = f a b
689+
690+ zip :: forall a b. [a] -> [b] -> [Tuple a b]
691+ zip = zipWith Tuple
692+
693+ unzip :: forall a b. [Tuple a b] -> Tuple [a] [b]
694+ unzip ((Tuple a b):ts) = case unzip ts of
695+ Tuple as bs -> Tuple (a : as) (b : bs)
696+ unzip [] = Tuple [] []
697+
698+ instance eqTuple :: (Eq a, Eq b) => Eq (Tuple a b) where
699+ (==) (Tuple a1 b1) (Tuple a2 b2) = a1 == a2 && b1 == b2
700+ (/=) t1 t2 = not (t1 == t2)
701+
702+ instance functorTuple :: Functor (Tuple a) where
703+ (<$>) f (Tuple x y) = Tuple x (f y)
704+
705+module Data.String where
706+
707+ foreign import lengthS "function lengthS(s) {\
708+ \ return s.length;\
709+ \}" :: String -> Number
710+
711+ foreign import charAt "function charAt(i) {\
712+ \ return function(s) {\
713+ \ return s.charAt(i); \
714+ \ };\
715+ \}" :: Number -> String -> String
716+
717+ foreign import indexOfS "function indexOfS(s1) {\
718+ \ return function(s2) {\
719+ \ return s1.indexOf(s2);\
720+ \ }; \
721+ \}" :: String -> String -> Number
722+
723+ foreign import lastIndexOfS "function lastIndexOfS(s1) {\
724+ \ return function(s2) {\
725+ \ return s1.lastIndexOf(s2);\
726+ \ };\
727+ \}" :: String -> String -> Number
728+
729+ foreign import localeCompare "function localeCompare(s1) {\
730+ \ return function(s2) {\
731+ \ return s1.localeCompare(s2);\
732+ \ };\
733+ \}" :: String -> String -> Number
734+
735+ foreign import replace "function replace(s1) {\
736+ \ return function(s2) {\
737+ \ return function(s3) {\
738+ \ return s3.replace(s1, s2);\
739+ \ };\
740+ \ };\
741+ \}" :: String -> String -> String -> String
742+
743+ foreign import sliceS "function sliceS(st) {\
744+ \ return function(e) {\
745+ \ return function(s) {\
746+ \ return s.slice(st, e);\
747+ \ };\
748+ \ };\
749+ \}" :: Number -> Number -> String -> String
750+
751+ foreign import split "function split(sep) {\
752+ \ return function(s) {\
753+ \ return s.split(sep);\
754+ \ };\
755+ \}" :: String -> String -> [String]
756+
757+ foreign import substr "function substr(n1) {\
758+ \ return function(n2) {\
759+ \ return function(s) {\
760+ \ return s.substr(n1, n2);\
761+ \ };\
762+ \ };\
763+ \}" :: Number -> Number -> String -> String
764+
765+ foreign import substring "function substring(n1) {\
766+ \ return function(n2) {\
767+ \ return function(s) {\
768+ \ return s.substring(n1, n2);\
769+ \ };\
770+ \ };\
771+ \}" :: Number -> Number -> String -> String
772+
773+ foreign import toLower "function toLower(s) {\
774+ \ return s.toLowerCase();\
775+ \}" :: String -> String
776+
777+ foreign import toUpper "function toUpper(s) {\
778+ \ return s.toUpperCase();\
779+ \}" :: String -> String
780+
781+ foreign import trim "function trim(s) {\
782+ \ return s.trim();\
783+ \}" :: String -> String
784+
785+module Data.String.Regex where
786+
787+ foreign import data Regex :: *
788+
789+ foreign import regex "function regex(s1) {\
790+ \ return function(s2) {\
791+ \ return new Regex(s1, s2);\
792+ \ };\
793+ \}" :: String -> String -> Regex
794+
795+ foreign import test "function test(r) {\
796+ \ return function (s) {\
797+ \ return r.test(s);\
798+ \ };\
799+ \}" :: Regex -> String -> Boolean
800+
801+ foreign import match "function match(r) {\
802+ \ return function (s) {\
803+ \ return s.match(r); \
804+ \ };\
805+ \}" :: Regex -> String -> [String]
806+
807+ foreign import replaceR "function replaceR(r) {\
808+ \ return function(s1) {\
809+ \ return function(s2) {\
810+ \ return s2.replace(r, s1);\
811+ \ };\
812+ \ };\
813+ \}" :: Regex -> String -> String -> String
814+
815+ foreign import search "function search(r) {\
816+ \ return function (s) {\
817+ \ return s.search(r);\
818+ \ };\
819+ \}" :: Regex -> String -> Number
820+
821+module Global where
822+
823+ foreign import nan "var nan = NaN;" :: Number
824+
825+ foreign import infinity "var infinity = Infinity;" :: Number
826+
827+ foreign import toExponential "function toExponential(n) {\
828+ \ return n.toExponential();\
829+ \}" :: Number -> String
830+
831+ foreign import toFixed "function toFixed(d) {\
832+ \ return function(n) {\
833+ \ return n.toFixed(d);\
834+ \ };\
835+ \}" :: Number -> Number -> String
836+
837+ foreign import toPrecision "function toPrecision(d) {\
838+ \ return function(n) {\
839+ \ return n.toPrecision(d);\
840+ \ };\
841+ \}" :: Number -> Number -> String
842+
843+ foreign import isFinite :: Number -> Boolean
844+
845+ foreign import parseFloat :: String -> Number
846+
847+ foreign import parseInt :: String -> Number
848+
849+ foreign import encodeURIComponent :: String -> String
850+
851+ foreign import decodeURIComponent :: String -> String
852+
853+ foreign import encodeURI :: String -> String
854+
855+ foreign import decodeURI :: String -> String
856+
857+ foreign import isNaN :: Number -> Boolean
858+
859+module Math where
860+
861+ foreign import abs "function abs(n){\
862+ \ return Math.abs(n);\
863+ \}" :: Number -> Number
864+
865+ foreign import acos "function acos(n){\
866+ \ return Math.acos(n);\
867+ \}" :: Number -> Number
868+
869+ foreign import asin "function asin(n){\
870+ \ return Math.asin(n);\
871+ \}" :: Number -> Number
872+
873+ foreign import atan "function atan(n){\
874+ \ return Math.atan(n);\
875+ \}" :: Number -> Number
876+
877+ foreign import atan2 "function atan2(y){\
878+ \ return function (x) {\
879+ \ return Math.atan2(y, x);\
880+ \ };\
881+ \}" :: Number -> Number -> Number
882+
883+ foreign import aceil "function aceil(n){\
884+ \ return Math.aceil(n);\
885+ \}" :: Number -> Number
886+
887+ foreign import cos "function cos(n){\
888+ \ return Math.cos(n);\
889+ \}" :: Number -> Number
890+
891+ foreign import exp "function exp(n){\
892+ \ return Math.exp(n);\
893+ \}" :: Number -> Number
894+
895+ foreign import floor "function floor(n){\
896+ \ return Math.floor(n);\
897+ \}" :: Number -> Number
898+
899+ foreign import log "function log(n){\
900+ \ return Math.log(n);\
901+ \}" :: Number -> Number
902+
903+ foreign import max "function max(n1){\
904+ \ return function(n2) {\
905+ \ return Math.max(n1, n2);\
906+ \ }\
907+ \}" :: Number -> Number -> Number
908+
909+ foreign import min "function min(n1){\
910+ \ return function(n2) {\
911+ \ return Math.min(n1, n2);\
912+ \ }\
913+ \}" :: Number -> Number -> Number
914+
915+ foreign import pow "function pow(n){\
916+ \ return function(p) {\
917+ \ return Math.pow(n, p);\
918+ \ }\
919+ \}" :: Number -> Number -> Number
920+
921+ foreign import round "function round(n){\
922+ \ return Math.round(n);\
923+ \}" :: Number -> Number
924+
925+ foreign import sin "function sin(n){\
926+ \ return Math.sin(n);\
927+ \}" :: Number -> Number
928+
929+ foreign import sqrt "function sqrt(n){\
930+ \ return Math.sqrt(n);\
931+ \}" :: Number -> Number
932+
933+ foreign import tan "function tan(n){\
934+ \ return Math.tan(n);\
935+ \}" :: Number -> Number
936+
937+ foreign import e "var e = Math.E;" :: Number
938+ foreign import ln2 "var ln2 = Math.LN2;" :: Number
939+ foreign import ln10 "var ln10 = Math.LN10;" :: Number
940+ foreign import log2e "var log2e = Math.LOG2E;" :: Number
941+ foreign import log10e "var log10e = Math.LOG10E;" :: Number
942+ foreign import pi "var pi = Math.PI;" :: Number
943+ foreign import sqrt1_2 "var sqrt1_2 = Math.SQRT1_2;" :: Number
944+ foreign import sqrt2 "var sqrt2 = Math.SQRT2;" :: Number
945+
946+module Control.Monad.Eff where
947+
948+ import Prelude
949+
950+ foreign import data Eff :: # ! -> * -> *
951+
952+ foreign import retEff "function retEff(a) {\
953+ \ return function() {\
954+ \ return a;\
955+ \ };\
956+ \}" :: forall e a. a -> Eff e a
957+
958+ foreign import bindEff "function bindEff(a) {\
959+ \ return function(f) {\
960+ \ return function() {\
961+ \ return f(a())();\
962+ \ };\
963+ \ };\
964+ \}" :: forall e a b. Eff e a -> (a -> Eff e b) -> Eff e b
965+
966+ type Pure a = forall e. Eff e a
967+
968+ foreign import runPure "function runPure(f) {\
969+ \ return f();\
970+ \}" :: forall a. Pure a -> a
971+
972+ instance monadEff :: Monad (Eff e) where
973+ return = retEff
974+ (>>=) = bindEff
975+
976+ foreign import untilE "function untilE(f) {\
977+ \ return function() {\
978+ \ while (!f()) { }\
979+ \ return {};\
980+ \ };\
981+ \}" :: forall e. Eff e Boolean -> Eff e {}
982+
983+ foreign import whileE "function whileE(f) {\
984+ \ return function(a) {\
985+ \ return function() {\
986+ \ while (f()) {\
987+ \ a();\
988+ \ }\
989+ \ return {};\
990+ \ };\
991+ \ };\
992+ \}" :: forall e a. Eff e Boolean -> Eff e a -> Eff e {}
993+
994+ foreign import forE "function forE(lo) {\
995+ \ return function(hi) {\
996+ \ return function(f) {\
997+ \ return function() {\
998+ \ for (var i = lo; i < hi; i++) {\
999+ \ f(i)();\
1000+ \ }\
1001+ \ };\
1002+ \ };\
1003+ \ };\
1004+ \}" :: forall e. Number -> Number -> (Number -> Eff e {}) -> Eff e {}
1005+
1006+
1007+ foreign import foreachE "function foreachE(as) {\
1008+ \ return function(f) {\
1009+ \ for (var i = 0; i < as.length; i++) {\
1010+ \ f(as[i])();\
1011+ \ }\
1012+ \ };\
1013+ \}" :: forall e a. [a] -> (a -> Eff e {}) -> Eff e {}
1014+
1015+module Control.Monad.Eff.Unsafe where
1016+
1017+ import Control.Monad.Eff
1018+
1019+ foreign import unsafeInterleaveEff
1020+ "function unsafeInterleaveEff(f) {\
1021+ \ return f;\
1022+ \}" :: forall eff1 eff2 a. Eff eff1 a -> Eff eff2 a
1023+
1024+module Random where
1025+
1026+ import Control.Monad.Eff
1027+
1028+ foreign import data Random :: !
1029+
1030+ foreign import random "function random() {\
1031+ \ return Math.random();\
1032+ \}" :: forall e. Eff (random :: Random | e) Number
1033+
1034+module Control.Monad.Eff.Error where
1035+
1036+ import Control.Monad.Eff
1037+
1038+ foreign import data Error :: * -> !
1039+
1040+ foreign import throwError "function throwError(e) {\
1041+ \ return function() {\
1042+ \ throw e;\
1043+ \ };\
1044+ \}" :: forall a e r. e -> Eff (err :: Error e | r) a
1045+
1046+ foreign import catchError "function catchError(c) {\
1047+ \ return function(t) {\
1048+ \ return function() {\
1049+ \ try {\
1050+ \ return t();\
1051+ \ } catch(e) {\
1052+ \ return c(e)();\
1053+ \ }\
1054+ \ };\
1055+ \ };\
1056+ \}" :: forall e r a. (e -> Eff r a) -> Eff (err :: Error e | r) a -> Eff r a
1057+
1058+module Data.IORef where
1059+
1060+ import Control.Monad.Eff
1061+
1062+ foreign import data Ref :: !
1063+
1064+ foreign import data IORef :: * -> *
1065+
1066+ foreign import newIORef "function newIORef(val) {\
1067+ \ return function () {\
1068+ \ return { value: val };\
1069+ \ };\
1070+ \}" :: forall s r. s -> Eff (ref :: Ref | r) (IORef s)
1071+
1072+ foreign import readIORef "function readIORef(ref) {\
1073+ \ return function() {\
1074+ \ return ref.value;\
1075+ \ };\
1076+ \}" :: forall s r. IORef s -> Eff (ref :: Ref | r) s
1077+
1078+
1079+ foreign import modifyIORef "function modifyIORef(ref) {\
1080+ \ return function(f) {\
1081+ \ return function() {\
1082+ \ ref.value = f(ref.value);\
1083+ \ return {};\
1084+ \ };\
1085+ \ };\
1086+ \}" :: forall s r. IORef s -> (s -> s) -> Eff (ref :: Ref | r) {}
1087+
1088+ foreign import writeIORef "function writeIORef(ref) {\
1089+ \ return function(val) {\
1090+ \ return function() {\
1091+ \ ref.value = val;\
1092+ \ return {};\
1093+ \ };\
1094+ \ };\
1095+ \}" :: forall s r. IORef s -> s -> Eff (ref :: Ref | r) {}
1096+
1097+ foreign import unsafeRunIORef "function unsafeRunIORef(f) {\
1098+ \ return f;\
1099+ \}" :: forall eff a. Eff (ref :: Ref | eff) a -> Eff eff a
1100+
1101+module Debug.Trace where
1102+
1103+ import Prelude
1104+ import Control.Monad.Eff
1105+
1106+ foreign import data Trace :: !
1107+
1108+ foreign import trace "function trace(s) {\
1109+ \ return function() {\
1110+ \ console.log(s);\
1111+ \ return {};\
1112+ \ };\
1113+ \}" :: forall r. String -> Eff (trace :: Trace | r) {}
1114+
1115+ print :: forall a r. (Show a) => a -> Eff (trace :: Trace | r) {}
1116+ print o = trace (show o)
1117+
1118+module Control.Monad.ST where
1119+
1120+ import Control.Monad.Eff
1121+
1122+ foreign import data ST :: * -> !
1123+
1124+ foreign import data STRef :: * -> * -> *
1125+
1126+ foreign import data STArray :: * -> * -> *
1127+
1128+ foreign import newSTRef "function newSTRef(val) {\
1129+ \ return function () {\
1130+ \ return { value: val };\
1131+ \ };\
1132+ \}" :: forall a h r. a -> Eff (st :: ST h | r) (STRef h a)
1133+
1134+ foreign import readSTRef "function readSTRef(ref) {\
1135+ \ return function() {\
1136+ \ return ref.value;\
1137+ \ };\
1138+ \}" :: forall a h r. STRef h a -> Eff (st :: ST h | r) a
1139+
1140+ foreign import modifySTRef "function modifySTRef(ref) {\
1141+ \ return function(f) {\
1142+ \ return function() {\
1143+ \ return ref.value = f(ref.value);\
1144+ \ };\
1145+ \ };\
1146+ \}" :: forall a h r. STRef h a -> (a -> a) -> Eff (st :: ST h | r) a
1147+
1148+ foreign import writeSTRef "function writeSTRef(ref) {\
1149+ \ return function(a) {\
1150+ \ return function() {\
1151+ \ return ref.value = a;\
1152+ \ };\
1153+ \ };\
1154+ \}" :: forall a h r. STRef h a -> a -> Eff (st :: ST h | r) a
1155+
1156+ foreign import newSTArray "function newSTArray(len) {\
1157+ \ return function(a) {\
1158+ \ return function() {\
1159+ \ var arr = [];\
1160+ \ for (var i = 0; i < len; i++) {\
1161+ \ arr[i] = a;\
1162+ \ };\
1163+ \ return arr;\
1164+ \ };\
1165+ \ };\
1166+ \}" :: forall a h r. Number -> a -> Eff (st :: ST h | r) (STArray h a)
1167+
1168+ foreign import peekSTArray "function peekSTArray(arr) {\
1169+ \ return function(i) {\
1170+ \ return function() {\
1171+ \ return arr[i];\
1172+ \ };\
1173+ \ };\
1174+ \}" :: forall a h r. STArray h a -> Eff (st :: ST h | r) a
1175+
1176+ foreign import pokeSTArray "function pokeSTArray(arr) {\
1177+ \ return function(i) {\
1178+ \ return function(a) {\
1179+ \ return function() {\
1180+ \ return arr[i] = a;\
1181+ \ };\
1182+ \ };\
1183+ \ };\
1184+ \}" :: forall a h r. STArray h a -> Number -> a -> Eff (st :: ST h | r) a
1185+
1186+ foreign import runST "function runST(f) {\
1187+ \ return f;\
1188+ \}" :: forall a r. (forall h. Eff (st :: ST h | r) a) -> Eff r a
1189+
1190+ foreign import runSTArray "function runSTArray(f) {\
1191+ \ return f;\
1192+ \}" :: forall a r. (forall h. Eff (st :: ST h | r) (STArray h a)) -> Eff r [a]
1193+
1194+module Data.Enum where
1195+
1196+ import Data.Maybe
1197+
1198+ class Enum a where
1199+ toEnum :: Number -> Maybe a
1200+ fromEnum :: a -> Number
1201+
1202+module Text.Parsing.Read where
1203+
1204+ class Read a where
1205+ read :: String -> a
1206+
1207+ instance readString :: Read String where
1208+ read s = s
1209+
1210+ instance readBoolean :: Read Boolean where
1211+ read "true" = true
1212+ read _ = false
1213+
1214+ foreign import readNumberImpl "var readNumberImpl = parseFloat;" :: String -> Number
1215+
1216+ instance readNumber :: Read Number where
1217+ read = readNumberImpl
1218+
1219+module Data.Foldable where
1220+
1221+ import Prelude
1222+ import Control.Applicative
1223+ import Data.Either
1224+ import Data.Eq
1225+ import Data.Maybe
1226+ import Data.Monoid
1227+ import Data.Tuple
1228+
1229+ class Foldable f where
1230+ foldr :: forall a b. (a -> b -> b) -> b -> f a -> b
1231+ foldl :: forall a b. (b -> a -> b) -> b -> f a -> b
1232+ foldMap :: forall a m. (Monoid m) => (a -> m) -> f a -> m
1233+
1234+ instance foldableArray :: Foldable [] where
1235+ foldr _ z [] = z
1236+ foldr f z (x:xs) = x `f` (foldr f z xs)
1237+
1238+ foldl _ z [] = z
1239+ foldl f z (x:xs) = foldl f (z `f` x) xs
1240+
1241+ foldMap _ [] = mempty
1242+ foldMap f (x:xs) = f x <> foldMap f xs
1243+
1244+ instance foldableEither :: Foldable (Either a) where
1245+ foldr _ z (Left _) = z
1246+ foldr f z (Right x) = x `f` z
1247+
1248+ foldl _ z (Left _) = z
1249+ foldl f z (Right x) = z `f` x
1250+
1251+ foldMap f (Left _) = mempty
1252+ foldMap f (Right x) = f x
1253+
1254+ instance foldableMaybe :: Foldable Maybe where
1255+ foldr _ z Nothing = z
1256+ foldr f z (Just x) = x `f` z
1257+
1258+ foldl _ z Nothing = z
1259+ foldl f z (Just x) = z `f` x
1260+
1261+ foldMap f Nothing = mempty
1262+ foldMap f (Just x) = f x
1263+
1264+ instance foldableRef :: Foldable Ref where
1265+ foldr f z (Ref x) = x `f` z
1266+
1267+ foldl f z (Ref x) = z `f` x
1268+
1269+ foldMap f (Ref x) = f x
1270+
1271+ instance foldableTuple :: Foldable (Tuple a) where
1272+ foldr f z (Tuple _ x) = x `f` z
1273+
1274+ foldl f z (Tuple _ x) = z `f` x
1275+
1276+ foldMap f (Tuple _ x) = f x
1277+
1278+ fold :: forall f m. (Foldable f, Monoid m) => f m -> m
1279+ fold = foldMap id
1280+
1281+ traverse_ :: forall a b f m. (Applicative m, Foldable f) => (a -> m b) -> f a -> m {}
1282+ traverse_ f = foldr ((*>) <<< f) (pure {})
1283+
1284+ for_ :: forall a b f m. (Applicative m, Foldable f) => f a -> (a -> m b) -> m {}
1285+ for_ = flip traverse_
1286+
1287+ sequence_ :: forall a f m. (Applicative m, Foldable f) => f (m a) -> m {}
1288+ sequence_ = traverse_ id
1289+
1290+ mconcat :: forall f m. (Foldable f, Monoid m) => f m -> m
1291+ mconcat = foldl (<>) mempty
1292+
1293+ and :: forall f. (Foldable f) => f Boolean -> Boolean
1294+ and = foldl (&&) true
1295+
1296+ or :: forall f. (Foldable f) => f Boolean -> Boolean
1297+ or = foldl (||) false
1298+
1299+ any :: forall a f. (Foldable f) => (a -> Boolean) -> f a -> Boolean
1300+ any p = or <<< foldMap (\x -> [p x])
1301+
1302+ all :: forall a f. (Foldable f) => (a -> Boolean) -> f a -> Boolean
1303+ all p = and <<< foldMap (\x -> [p x])
1304+
1305+ sum :: forall f. (Foldable f) => f Number -> Number
1306+ sum = foldl (+) 0
1307+
1308+ product :: forall f. (Foldable f) => f Number -> Number
1309+ product = foldl (*) 1
1310+
1311+ elem :: forall a f. (Eq a, Foldable f) => a -> f a -> Boolean
1312+ elem = any <<< (==)
1313+
1314+ notElem :: forall a f. (Eq a, Foldable f) => a -> f a -> Boolean
1315+ notElem x = not <<< elem x
1316+
1317+ find :: forall a f. (Foldable f) => (a -> Boolean) -> f a -> Maybe a
1318+ find p f = case foldMap (\x -> if p x then [x] else []) f of
1319+ (x:_) -> Just x
1320+ [] -> Nothing
1321+
1322+module Data.Traversable where
1323+
1324+ import Prelude
1325+ import Data.Array ((:))
1326+ import Data.Either
1327+ import Data.Eq
1328+ import Data.Foldable
1329+ import Data.Maybe
1330+ import Data.Tuple
1331+
1332+ class Traversable t where
1333+ traverse :: forall a b m. (Applicative m) => (a -> m b) -> t a -> m (t b)
1334+ sequence :: forall a m. (Applicative m) => t (m a) -> m (t a)
1335+
1336+ instance traversableArray :: Traversable [] where
1337+ traverse _ [] = pure []
1338+ traverse f (x:xs) = (:) <$> (f x) <*> traverse f xs
1339+
1340+ sequence [] = pure []
1341+ sequence (x:xs) = (:) <$> x <*> sequence xs
1342+
1343+ instance traversableEither :: Traversable (Either a) where
1344+ traverse _ (Left x) = pure (Left x)
1345+ traverse f (Right x) = Right <$> f x
1346+
1347+ sequence (Left x) = pure (Left x)
1348+ sequence (Right x) = Right <$> x
1349+
1350+ instance traversableRef :: Traversable Ref where
1351+ traverse f (Ref x) = Ref <$> f x
1352+
1353+ sequence (Ref x) = Ref <$> x
1354+
1355+ instance traversableMaybe :: Traversable Maybe where
1356+ traverse _ Nothing = pure Nothing
1357+ traverse f (Just x) = Just <$> f x
1358+
1359+ sequence Nothing = pure Nothing
1360+ sequence (Just x) = Just <$> x
1361+
1362+ instance traversableTuple :: Traversable (Tuple a) where
1363+ traverse f (Tuple x y) = Tuple x <$> f y
1364+
1365+ sequence (Tuple x y) = Tuple x <$> y
1366+
1367+ for :: forall a b m t. (Applicative m, Traversable t) => t a -> (a -> m b) -> m (t b)
1368+ for x f = traverse f x
prelude/tests/.gitignorenew file+1
@@ -0,0 +1 @@
1+Eff.js
prelude/tests/Eff.pursnew file+60
@@ -0,0 +1,60 @@
1+module Tests where
2+
3+import Prelude
4+import Eff
5+import Errors
6+import Trace
7+import Global
8+
9+test1 n = runPure (catchError (\s -> return 0) $ do
10+ case {} of
11+ _ | n > 10 -> do
12+ throwError "Error!"
13+ _ -> return n)
14+
15+test2 = do
16+ trace "Hello World"
17+ throwError "Error!"
18+
19+test3 n = catchError (\s -> return 0) $ do
20+ case {} of
21+ _ | n > 10 -> do
22+ trace "n > 10"
23+ throwError "Error!"
24+ _ -> return n
25+
26+test4 = do
27+ trace "Hello World!"
28+ return 0
29+
30+test5 _ = do
31+ trace "Hello World!"
32+ test5 {}
33+
34+test6 s = do
35+ trace s
36+ test6 (s ++ " test")
37+
38+import ST
39+
40+test7 _ = do
41+ n <- runST (do
42+ r <- newSTRef 0
43+ modifySTRef r $ \n -> n + 1
44+ readSTRef r)
45+ print n
46+
47+test8 _ = (\_1 _2 -> {}) <$> print "Test" <*> print 8
48+
49+test9 _ = runST (do
50+ r <- newSTRef 1
51+ whileE (return true) $ do
52+ n <- readSTRef r
53+ trace $ "Count " ++ show n
54+ modifySTRef r $ (+) 1)
55+
56+module Main where
57+
58+import Tests
59+
60+main = test5 {}
prelude/tests/build.shnew file+2
@@ -0,0 +1,2 @@
1+psc ../prelude.purs Eff.purs --magic-do --tco --run-main --no-prelude --entry-point Main -o Eff.js
2+
prelude/updateDocs.shnew file+2
@@ -0,0 +1,2 @@
1+../dist/build/docgen/docgen prelude.purs > README.md
2+pandoc -o ../docs/source/prelude.rst README.md
psc/Main.hsnew file+128
@@ -0,0 +1,128 @@
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 (forM)
21+import System.Exit (exitSuccess, exitFailure)
22+import qualified System.IO.UTF8 as U
23+import Text.Parsec (ParseError)
24+import qualified Paths_purescript as Paths
25+import Data.Version (showVersion)
26+
27+preludeFilename :: IO FilePath
28+preludeFilename = Paths.getDataFileName "prelude/prelude.purs"
29+
30+readInput :: Maybe [FilePath] -> IO (Either ParseError [P.Module])
31+readInput Nothing = P.runIndentParser "" P.parseModules <$> getContents
32+readInput (Just input) = fmap (fmap concat . sequence) $ forM input $ \inputFile -> do
33+ text <- U.readFile inputFile
34+ return $ P.runIndentParser inputFile P.parseModules text
35+
36+compile :: P.Options -> Maybe [FilePath] -> Maybe FilePath -> Maybe FilePath -> IO ()
37+compile opts input output externs = do
38+ modules <- readInput input
39+ case modules of
40+ Left err -> do
41+ U.print err
42+ exitFailure
43+ Right ms ->
44+ case P.compile opts ms of
45+ Left err -> do
46+ U.putStrLn err
47+ exitFailure
48+ Right (js, exts, _) -> do
49+ case output of
50+ Just path -> U.writeFile path js
51+ Nothing -> U.putStrLn js
52+ case externs of
53+ Nothing -> return ()
54+ Just filePath -> U.writeFile filePath exts
55+ exitSuccess
56+
57+useStdIn :: Term Bool
58+useStdIn = value . flag $ (optInfo [ "s", "stdin" ])
59+ { optDoc = "Read from standard input" }
60+
61+inputFiles :: Term [FilePath]
62+inputFiles = value $ posAny [] $ posInfo
63+ { posDoc = "The input .ps files" }
64+
65+outputFile :: Term (Maybe FilePath)
66+outputFile = value $ opt Nothing $ (optInfo [ "o", "output" ])
67+ { optDoc = "The output .js file" }
68+
69+externsFile :: Term (Maybe FilePath)
70+externsFile = value $ opt Nothing $ (optInfo [ "e", "externs" ])
71+ { optDoc = "The output .e.ps file" }
72+
73+tco :: Term Bool
74+tco = value $ flag $ (optInfo [ "tco" ])
75+ { optDoc = "Perform tail call optimizations" }
76+
77+performRuntimeTypeChecks :: Term Bool
78+performRuntimeTypeChecks = value $ flag $ (optInfo [ "runtime-type-checks" ])
79+ { optDoc = "Generate runtime type checks" }
80+
81+noPrelude :: Term Bool
82+noPrelude = value $ flag $ (optInfo [ "no-prelude" ])
83+ { optDoc = "Omit the Prelude" }
84+
85+magicDo :: Term Bool
86+magicDo = value $ flag $ (optInfo [ "magic-do" ])
87+ { optDoc = "Overload the do keyword to generate efficient code specifically for the Eff monad." }
88+
89+runMain :: Term (Maybe String)
90+runMain = value $ defaultOpt (Just "Main") Nothing $ (optInfo [ "main" ])
91+ { optDoc = "Generate code to run the main method in the specified module." }
92+
93+noOpts :: Term Bool
94+noOpts = value $ flag $ (optInfo [ "no-opts" ])
95+ { optDoc = "Skip the optimization phase." }
96+
97+browserNamespace :: Term String
98+browserNamespace = value $ opt "PS" $ (optInfo [ "browser-namespace" ])
99+ { optDoc = "Specify the namespace that PureScript modules will be exported to when running in the browser." }
100+
101+dceModules :: Term [String]
102+dceModules = value $ optAll [] $ (optInfo [ "m", "module" ])
103+ { 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." }
104+
105+options :: Term P.Options
106+options = P.Options <$> tco <*> performRuntimeTypeChecks <*> magicDo <*> runMain <*> noOpts <*> browserNamespace <*> dceModules
107+
108+stdInOrInputFiles :: FilePath -> Term (Maybe [FilePath])
109+stdInOrInputFiles prelude = combine <$> useStdIn <*> (not <$> noPrelude) <*> inputFiles
110+ where
111+ combine False True input = Just (prelude : input)
112+ combine False False input = Just input
113+ combine True _ _ = Nothing
114+
115+term :: FilePath -> Term (IO ())
116+term prelude = compile <$> options <*> stdInOrInputFiles prelude <*> outputFile <*> externsFile
117+
118+termInfo :: TermInfo
119+termInfo = defTI
120+ { termName = "psc"
121+ , version = showVersion Paths.version
122+ , termDoc = "Compiles PureScript to Javascript"
123+ }
124+
125+main :: IO ()
126+main = do
127+ prelude <- preludeFilename
128+ run (term prelude, termInfo)
psci/Commands.hsnew file+68
@@ -0,0 +1,68 @@
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.hsnew file+329
@@ -0,0 +1,329 @@
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.Traversable (traverse)
31+import Data.Version (showVersion)
32+
33+import Parser
34+
35+import System.Console.Haskeline
36+import System.Directory (doesFileExist, findExecutable, getHomeDirectory)
37+import System.Exit
38+import System.Environment.XDG.BaseDir
39+import System.FilePath ((</>), isPathSeparator)
40+import qualified System.Console.CmdTheLine as Cmd
41+import System.Process
42+
43+import Text.Parsec (ParseError)
44+
45+import qualified Data.Map as M
46+import qualified Language.PureScript as P
47+import qualified Paths_purescript as Paths
48+import qualified System.IO.UTF8 as U (readFile)
49+
50+-- |
51+-- The PSCI state.
52+-- Holds a list of imported modules, loaded files, and partial let bindings.
53+-- The let bindings are partial,
54+-- because it makes more sense to apply the binding to the final evaluated expression.
55+--
56+data PSCiState = PSCiState
57+ { psciImportedFilenames :: [FilePath]
58+ , psciImportedModuleNames :: [P.ModuleName]
59+ , psciLoadedModules :: [P.Module]
60+ , psciLetBindings :: [P.Value -> P.Value]
61+ }
62+
63+-- State helpers
64+
65+-- |
66+-- Updates the state to have more imported modules.
67+--
68+updateImportedFiles :: FilePath -> PSCiState -> PSCiState
69+updateImportedFiles filename st = st { psciImportedFilenames = filename : psciImportedFilenames st }
70+
71+-- |
72+-- Updates the state to have more imported modules.
73+--
74+updateImports :: P.ModuleName -> PSCiState -> PSCiState
75+updateImports name st = st { psciImportedModuleNames = name : psciImportedModuleNames st }
76+
77+-- |
78+-- Updates the state to have more loaded files.
79+--
80+updateModules :: [P.Module] -> PSCiState -> PSCiState
81+updateModules modules st = st { psciLoadedModules = psciLoadedModules st ++ modules }
82+
83+-- |
84+-- Updates the state to have more let bindings.
85+--
86+updateLets :: (P.Value -> P.Value) -> PSCiState -> PSCiState
87+updateLets name st = st { psciLetBindings = name : psciLetBindings st }
88+
89+-- File helpers
90+-- |
91+-- Load the necessary modules.
92+--
93+defaultImports :: [P.ModuleName]
94+defaultImports = [P.ModuleName [P.ProperName "Prelude"]]
95+
96+-- |
97+-- Locates the node executable.
98+-- Checks for either @nodejs@ or @node@.
99+--
100+findNodeProcess :: IO (Maybe String)
101+findNodeProcess = runMaybeT . msum $ map (MaybeT . findExecutable) names
102+ where names = ["nodejs", "node"]
103+
104+-- |
105+-- Grabs the filename where the history is stored.
106+--
107+getHistoryFilename :: IO FilePath
108+getHistoryFilename = getUserConfigFile "purescript" "psci_history"
109+
110+-- |
111+-- Grabs the filename where prelude is.
112+--
113+getPreludeFilename :: IO FilePath
114+getPreludeFilename = Paths.getDataFileName "prelude/prelude.purs"
115+
116+-- |
117+-- Loads a file for use with imports.
118+--
119+loadModule :: FilePath -> IO (Either String [P.Module])
120+loadModule filename = either (Left . show) Right . P.runIndentParser filename P.parseModules <$> U.readFile filename
121+
122+-- |
123+-- Expands tilde in path.
124+--
125+expandTilde :: FilePath -> IO FilePath
126+expandTilde ('~':p:rest) | isPathSeparator p = (</> rest) <$> getHomeDirectory
127+expandTilde p = return p
128+-- Messages
129+
130+-- |
131+-- The help message.
132+--
133+helpMessage :: String
134+helpMessage = "The following commands are available:\n\n " ++
135+ intercalate "\n " (map (intercalate " ") help)
136+
137+-- |
138+-- The welcome prologue.
139+--
140+prologueMessage :: String
141+prologueMessage = intercalate "\n"
142+ [ " ____ ____ _ _ "
143+ , "| _ \\ _ _ _ __ ___/ ___| ___ _ __(_)_ __ | |_ "
144+ , "| |_) | | | | '__/ _ \\___ \\ / __| '__| | '_ \\| __|"
145+ , "| __/| |_| | | | __/___) | (__| | | | |_) | |_ "
146+ , "|_| \\__,_|_| \\___|____/ \\___|_| |_| .__/ \\__|"
147+ , " |_| "
148+ , ""
149+ , ":? shows help"
150+ , ""
151+ , "Expressions are terminated using Ctrl+D"
152+ ]
153+
154+-- |
155+-- The quit message.
156+--
157+quitMessage :: String
158+quitMessage = "See ya!"
159+
160+-- Haskeline completions
161+
162+-- |
163+-- Loads module, function, and file completions.
164+-- TODO: filter names to only include exported decls
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 = flip any exts $ \e -> case e of
180+ P.ValueRef ident' -> ident == ident'
181+ _ -> False
182+ getDeclName _ _ = Nothing
183+ names :: [P.Module] -> [String]
184+ names ms = nub [ show qual
185+ | P.Module moduleName ds exts <- ms
186+ , ident <- mapMaybe (getDeclName exts) ds
187+ , qual <- [ P.Qualified Nothing ident
188+ , P.Qualified (Just moduleName) ident]
189+ ]
190+ sorter :: Completion -> Completion -> Ordering
191+ sorter (Completion _ d1 _) (Completion _ d2 _) = compare d1 d2
192+
193+-- Compilation
194+
195+-- | Compilation options.
196+--
197+options :: P.Options
198+options = P.Options True False True (Just "Main") True "PS" []
199+
200+-- |
201+-- Makes a volatile module to execute the current expression.
202+--
203+createTemporaryModule :: Bool -> PSCiState -> P.Value -> P.Module
204+createTemporaryModule exec PSCiState{psciImportedModuleNames = imports, psciLetBindings = lets} value =
205+ let
206+ moduleName = P.ModuleName [P.ProperName "Main"]
207+ importDecl m = P.ImportDeclaration m Nothing
208+ traceModule = P.ModuleName [P.ProperName "Debug", P.ProperName "Trace"]
209+ trace = P.Var (P.Qualified (Just traceModule) (P.Ident "print"))
210+ itValue = foldl (\x f -> f x) value lets
211+ mainValue = P.App trace (P.Var (P.Qualified Nothing (P.Ident "it")))
212+ itDecl = P.ValueDeclaration (P.Ident "it") P.Value [] Nothing itValue
213+ mainDecl = P.ValueDeclaration (P.Ident "main") P.Value [] Nothing mainValue
214+ decls = if exec then [itDecl, mainDecl] else [itDecl]
215+ in
216+ P.Module moduleName ((importDecl `map` imports) ++ decls) Nothing
217+
218+-- |
219+-- Takes a value declaration and evaluates it with the current state.
220+--
221+handleDeclaration :: P.Value -> PSCiState -> InputT (StateT PSCiState IO) ()
222+handleDeclaration value st = do
223+ let m = createTemporaryModule True st value
224+ case P.compile options (psciLoadedModules st ++ [m]) of
225+ Left err -> outputStrLn err
226+ Right (js, _, _) -> do
227+ process <- lift . lift $ findNodeProcess
228+ result <- lift . lift $ traverse (\node -> readProcessWithExitCode node [] js) process
229+ case result of
230+ Just (ExitSuccess, out, _) -> outputStrLn out
231+ Just (ExitFailure _, _, err) -> outputStrLn err
232+ Nothing -> outputStrLn "Couldn't find node.js"
233+
234+-- |
235+-- Takes a value and prints its type
236+--
237+handleTypeOf :: P.Value -> PSCiState -> InputT (StateT PSCiState IO) ()
238+handleTypeOf value st = do
239+ let m = createTemporaryModule False st value
240+ case P.compile options { P.optionsMain = Nothing } (psciLoadedModules st ++ [m]) of
241+ Left err -> outputStrLn err
242+ Right (_, _, env') ->
243+ case M.lookup (P.ModuleName [P.ProperName "Main"], P.Ident "it") (P.names env') of
244+ Just (ty, _) -> outputStrLn . P.prettyPrintType $ ty
245+ Nothing -> outputStrLn "Could not find type"
246+
247+-- Commands
248+
249+-- |
250+-- Parses the input and returns either a Metacommand or an expression.
251+--
252+getCommand :: InputT (StateT PSCiState IO) (Either ParseError (Maybe Command))
253+getCommand = do
254+ firstLine <- getInputLine "> "
255+ case firstLine of
256+ Nothing -> return (Right Nothing)
257+ Just s@ (':' : _) -> return . either Left (Right . Just) $ parseCommand s -- The start of a command
258+ Just s -> either Left (Right . Just) . parseCommand <$> go [s]
259+ where
260+ go :: [String] -> InputT (StateT PSCiState IO) String
261+ go ls = maybe (return . unlines $ reverse ls) (go . (:ls)) =<< getInputLine " "
262+
263+-- |
264+-- Performs an action for each meta-command given, and also for expressions..
265+--
266+handleCommand :: Command -> InputT (StateT PSCiState IO) ()
267+handleCommand (Expression val) = lift get >>= handleDeclaration val
268+handleCommand Help = outputStrLn helpMessage
269+handleCommand (Import moduleName) = lift $ modify (updateImports moduleName)
270+handleCommand (Let l) = lift $ modify (updateLets l)
271+handleCommand (LoadFile filePath) = do
272+ absPath <- lift . lift $ expandTilde filePath
273+ exists <- lift . lift $ doesFileExist absPath
274+ if exists then do
275+ lift $ modify (updateImportedFiles absPath)
276+ either outputStrLn (lift . modify . updateModules) =<< (lift . lift $ loadModule absPath)
277+ else
278+ outputStrLn $ "Couldn't locate: " ++ filePath
279+handleCommand Reset = do
280+ files <- psciImportedFilenames <$> lift get
281+ modulesOrFirstError <- fmap concat . sequence <$> mapM (lift . lift . loadModule) files
282+ case modulesOrFirstError of
283+ Left err -> lift . lift $ putStrLn err >> exitFailure
284+ Right modules -> lift $ put (PSCiState files defaultImports modules [])
285+handleCommand (TypeOf val) = lift get >>= handleTypeOf val
286+handleCommand _ = outputStrLn "Unknown command"
287+
288+inputFiles :: Cmd.Term [FilePath]
289+inputFiles = Cmd.value $ Cmd.posAny [] $ Cmd.posInfo { Cmd.posName = "file(s)"
290+ , Cmd.posDoc = "Optional .purs files to load on start" }
291+
292+-- |
293+-- The PSCI main loop.
294+--
295+loop :: [FilePath] -> IO ()
296+loop files = do
297+ preludeFilename <- getPreludeFilename
298+ modulesOrFirstError <- fmap concat . sequence <$> mapM loadModule (preludeFilename : files)
299+ case modulesOrFirstError of
300+ Left err -> putStrLn err >> exitFailure
301+ Right modules -> do
302+ historyFilename <- getHistoryFilename
303+ let settings = defaultSettings {historyFile = Just historyFilename}
304+ flip evalStateT (PSCiState (preludeFilename : files) defaultImports modules []) . runInputT (setComplete completion settings) $ do
305+ outputStrLn prologueMessage
306+ go
307+ where
308+ go :: InputT (StateT PSCiState IO) ()
309+ go = do
310+ c <- getCommand
311+ case c of
312+ Left err -> outputStrLn (show err) >> go
313+ Right Nothing -> go
314+ Right (Just Quit) -> outputStrLn quitMessage
315+ Right (Just c') -> handleCommand c' >> go
316+
317+term :: Cmd.Term (IO ())
318+term = loop <$> inputFiles
319+
320+termInfo :: Cmd.TermInfo
321+termInfo = Cmd.defTI
322+ { Cmd.termName = "psci"
323+ , Cmd.version = showVersion Paths.version
324+ , Cmd.termDoc = "Interactive mode for PureScript"
325+ }
326+
327+main :: IO ()
328+main = Cmd.run (term, termInfo)
329+
psci/Parser.hsnew file+92
@@ -0,0 +1,92 @@
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+
30+-- |
31+-- PSCI version of @let@.
32+-- This is essentially let from do-notation.
33+-- However, since we don't support the @Eff@ monad,
34+-- we actually want the normal @let@.
35+--
36+psciLet :: Parsec String P.ParseState Command
37+psciLet = Let <$> (P.Let <$> (P.reserved "let" *> P.indented *> (Left <$> P.parseBinder))
38+ <*> (P.indented *> P.reservedOp "=" *> P.parseValue))
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.cabaldeleted−145
@@ -1,145 +0,0 @@
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.cabalnew file+124
@@ -0,0 +1,124 @@
1+name: purescript
2+version: 0.4.5.1
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 -any, filepath -any, mtl -any, parsec -any, syb -any,
23+ transformers -any, utf8-string -any, pattern-arrows -any, monad-unify >= 0.2 && < 0.3,
24+ xdg-basedir -any
25+ if (!os(windows))
26+ build-depends: unix -any
27+ exposed-modules: Data.Generics.Extras
28+ Language.PureScript
29+ Language.PureScript.Constants
30+ Language.PureScript.Options
31+ Language.PureScript.Declarations
32+ Language.PureScript.Environment
33+ Language.PureScript.Kinds
34+ Language.PureScript.Names
35+ Language.PureScript.Types
36+ Language.PureScript.Values
37+ Language.PureScript.Scope
38+ Language.PureScript.DeadCodeElimination
39+ Language.PureScript.Sugar
40+ Language.PureScript.ModuleDependencies
41+ Language.PureScript.Sugar.CaseDeclarations
42+ Language.PureScript.Sugar.DoNotation
43+ Language.PureScript.Sugar.TypeDeclarations
44+ Language.PureScript.Sugar.BindingGroups
45+ Language.PureScript.Sugar.Operators
46+ Language.PureScript.Sugar.TypeClasses
47+ Language.PureScript.Sugar.Let
48+ Language.PureScript.Sugar.Names
49+ Language.PureScript.CodeGen
50+ Language.PureScript.CodeGen.Common
51+ Language.PureScript.CodeGen.Externs
52+ Language.PureScript.CodeGen.JS
53+ Language.PureScript.CodeGen.JS.AST
54+ Language.PureScript.CodeGen.Monad
55+ Language.PureScript.Optimizer
56+ Language.PureScript.Optimizer.Common
57+ Language.PureScript.Optimizer.MagicDo
58+ Language.PureScript.Optimizer.TCO
59+ Language.PureScript.Optimizer.Inliner
60+ Language.PureScript.Optimizer.Unused
61+ Language.PureScript.Optimizer.Blocks
62+ Language.PureScript.Parser
63+ Language.PureScript.Parser.Common
64+ Language.PureScript.Parser.Declarations
65+ Language.PureScript.Parser.Kinds
66+ Language.PureScript.Parser.State
67+ Language.PureScript.Parser.Types
68+ Language.PureScript.Parser.Values
69+ Language.PureScript.Pretty
70+ Language.PureScript.Pretty.Common
71+ Language.PureScript.Pretty.JS
72+ Language.PureScript.Pretty.Kinds
73+ Language.PureScript.Pretty.Types
74+ Language.PureScript.Pretty.Values
75+ Language.PureScript.TypeChecker
76+ Language.PureScript.TypeChecker.Kinds
77+ Language.PureScript.TypeChecker.Monad
78+ Language.PureScript.TypeChecker.Synonyms
79+ Language.PureScript.TypeChecker.Types
80+ exposed: True
81+ buildable: True
82+ hs-source-dirs: src
83+ other-modules:
84+ ghc-options: -Wall -O2
85+
86+executable psc
87+ build-depends: base >=4 && <5, cmdtheline -any, containers -any,
88+ directory -any, filepath -any, mtl -any, parsec -any,
89+ purescript -any, syb -any, transformers -any, utf8-string -any
90+ main-is: Main.hs
91+ buildable: True
92+ hs-source-dirs: psc
93+ other-modules:
94+ ghc-options: -Wall -O2 -fno-warn-unused-do-bind
95+
96+executable psci
97+ build-depends: base >=4 && <5, containers -any, directory -any, filepath -any,
98+ mtl -any, parsec -any, haskeline <=0.7.1.1, purescript -any,
99+ syb -any, transformers -any, utf8-string -any, process -any,
100+ xdg-basedir -any, cmdtheline -any
101+ main-is: Main.hs
102+ buildable: True
103+ hs-source-dirs: psci
104+ other-modules: Commands
105+ Parser
106+ ghc-options: -Wall -O2
107+
108+executable docgen
109+ build-depends: base >=4 && <5, cmdtheline -any, purescript -any, utf8-string -any,
110+ process -any, mtl -any
111+ main-is: Main.hs
112+ buildable: True
113+ hs-source-dirs: docgen
114+ other-modules:
115+ ghc-options: -Wall -O2
116+
117+test-suite tests
118+ build-depends: base >=4 && <5, containers -any, directory -any,
119+ filepath -any, mtl -any, parsec -any, purescript -any, syb -any,
120+ transformers -any, utf8-string -any, process -any
121+ type: exitcode-stdio-1.0
122+ main-is: Main.hs
123+ buildable: True
124+ hs-source-dirs: tests
src/CodeGen/IL.hsdeleted−321
@@ -1,321 +0,0 @@
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.hsdeleted−196
@@ -1,196 +0,0 @@
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.hsdeleted−81
@@ -1,81 +0,0 @@
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.hsdeleted−18
@@ -1,18 +0,0 @@
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.hsdeleted−435
@@ -1,435 +0,0 @@
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.hsdeleted−146
@@ -1,146 +0,0 @@
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.hsdeleted−141
@@ -1,141 +0,0 @@
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.hsdeleted−527
@@ -1,527 +0,0 @@
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.hsnew file+73
@@ -0,0 +1,73 @@
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.hsnew file+81
@@ -0,0 +1,81 @@
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) where
17+
18+import Language.PureScript.Values as P
19+import Language.PureScript.Types as P
20+import Language.PureScript.Kinds as P
21+import Language.PureScript.Declarations as P
22+import Language.PureScript.Names as P
23+import Language.PureScript.Parser as P
24+import Language.PureScript.CodeGen as P
25+import Language.PureScript.CodeGen.Common as P
26+import Language.PureScript.TypeChecker as P
27+import Language.PureScript.Pretty as P
28+import Language.PureScript.Sugar as P
29+import Language.PureScript.Options as P
30+import Language.PureScript.ModuleDependencies as P
31+import Language.PureScript.Environment as P
32+import Language.PureScript.DeadCodeElimination as P
33+
34+import qualified Language.PureScript.Constants as C
35+
36+import Data.List (intercalate)
37+import Data.Maybe (mapMaybe)
38+import Control.Monad.State.Lazy
39+import Control.Applicative ((<$>), (<*>), pure)
40+import qualified Data.Map as M
41+
42+-- |
43+-- Compile a collection of modules
44+--
45+-- The compilation pipeline proceeds as follows:
46+--
47+-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
48+--
49+-- * Perform a set of desugaring passes.
50+--
51+-- * Type check, and elaborate values to include type annotations and type class dictionaries.
52+--
53+-- * Regroup values to take into account new value dependencies introduced by elaboration.
54+--
55+-- * Eliminate dead code.
56+--
57+-- * Generate Javascript, and perform optimization passes.
58+--
59+-- * Pretty-print the generated Javascript
60+--
61+compile :: Options -> [Module] -> Either String (String, String, Environment)
62+compile opts ms = do
63+ sorted <- sortModules ms
64+ desugared <- desugar sorted
65+ (elaborated, env) <- runCheck $ forM desugared $ \(Module moduleName' decls exps) -> do
66+ modify (\s -> s { checkCurrentModule = Just moduleName' })
67+ Module moduleName' <$> typeCheckAll mainModuleIdent moduleName' decls <*> pure exps
68+ regrouped <- createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
69+ let entryPoints = moduleNameFromString `map` optionsModules opts
70+ let elim = if null entryPoints then regrouped else eliminateDeadCode entryPoints regrouped
71+ let js = mapMaybe (flip (moduleToJs opts) env) elim
72+ let exts = intercalate "\n" . map (`moduleToPs` env) $ elim
73+ js' <- case mainModuleIdent of
74+ Just mmi -> do
75+ when ((mmi, Ident C.main) `M.notMember` names env) $
76+ Left $ show mmi ++ "." ++ C.main ++ " is undefined"
77+ return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar C._ps))) []]
78+ _ -> return js
79+ return (prettyPrintJS [wrapExportsContainer opts js'], exts, env)
80+ where
81+ mainModuleIdent = moduleNameFromString <$> optionsMain opts
src/Language/PureScript/CodeGen.hsnew file+25
@@ -0,0 +1,25 @@
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.hsnew file+134
@@ -0,0 +1,134 @@
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+identToJs (Escaped name) = name
36+
37+-- |
38+-- Attempts to find a human-readable name for a symbol, if none has been specified returns the
39+-- ordinal value.
40+--
41+identCharToString :: Char -> String
42+identCharToString c | isAlphaNum c = [c]
43+identCharToString '_' = "_"
44+identCharToString '.' = "$dot"
45+identCharToString '$' = "$dollar"
46+identCharToString '~' = "$tilde"
47+identCharToString '=' = "$eq"
48+identCharToString '<' = "$less"
49+identCharToString '>' = "$greater"
50+identCharToString '!' = "$bang"
51+identCharToString '#' = "$hash"
52+identCharToString '%' = "$percent"
53+identCharToString '^' = "$up"
54+identCharToString '&' = "$amp"
55+identCharToString '|' = "$bar"
56+identCharToString '*' = "$times"
57+identCharToString '/' = "$div"
58+identCharToString '+' = "$plus"
59+identCharToString '-' = "$minus"
60+identCharToString ':' = "$colon"
61+identCharToString '\\' = "$bslash"
62+identCharToString '?' = "$qmark"
63+identCharToString '@' = "$at"
64+identCharToString '\'' = "$prime"
65+identCharToString c = '$' : show (ord c)
66+
67+-- |
68+-- Checks whether an identifier name is reserved in Javascript.
69+--
70+nameIsJsReserved :: String -> Bool
71+nameIsJsReserved name =
72+ name `elem` [ "abstract"
73+ , "arguments"
74+ , "boolean"
75+ , "break"
76+ , "byte"
77+ , "case"
78+ , "catch"
79+ , "char"
80+ , "class"
81+ , "const"
82+ , "continue"
83+ , "debugger"
84+ , "default"
85+ , "delete"
86+ , "do"
87+ , "double"
88+ , "else"
89+ , "enum"
90+ , "eval"
91+ , "export"
92+ , "extends"
93+ , "final"
94+ , "finally"
95+ , "float"
96+ , "for"
97+ , "function"
98+ , "goto"
99+ , "if"
100+ , "implements"
101+ , "import"
102+ , "in"
103+ , "instanceof"
104+ , "int"
105+ , "interface"
106+ , "let"
107+ , "long"
108+ , "native"
109+ , "new"
110+ , "package"
111+ , "private"
112+ , "protected"
113+ , "public"
114+ , "return"
115+ , "short"
116+ , "static"
117+ , "super"
118+ , "switch"
119+ , "synchronized"
120+ , "this"
121+ , "throw"
122+ , "throws"
123+ , "transient"
124+ , "try"
125+ , "typeof"
126+ , "var"
127+ , "void"
128+ , "volatile"
129+ , "while"
130+ , "with"
131+ , "yield" ]
132+
133+moduleNameToJs :: ModuleName -> String
134+moduleNameToJs (ModuleName pns) = intercalate "_" (runProperName `map` pns)
src/Language/PureScript/CodeGen/Externs.hsnew file+91
@@ -0,0 +1,91 @@
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.Declarations
28+import Language.PureScript.Pretty
29+import Language.PureScript.Names
30+import Language.PureScript.Values
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_ fixityToPs ds
41+ mapM_ exportToPs exts
42+ where
43+
44+ fixityToPs :: Declaration -> Writer [String] ()
45+ fixityToPs (FixityDeclaration (Fixity assoc prec) ident) =
46+ tell [ unwords [ show assoc, show prec, ident ] ]
47+ fixityToPs _ = return ()
48+
49+ exportToPs :: DeclarationRef -> Writer [String] ()
50+ exportToPs (TypeRef pn dctors) = do
51+ case Qualified (Just moduleName) pn `M.lookup` types env of
52+ Nothing -> error $ show pn ++ " has no kind in exportToPs"
53+ Just (kind, ExternData) ->
54+ tell ["foreign import data " ++ show pn ++ " :: " ++ prettyPrintKind kind]
55+ Just (_, DataType args tys) -> do
56+ let dctors' = fromMaybe (map fst tys) dctors
57+ printDctor dctor = case dctor `lookup` tys of
58+ Nothing -> Nothing
59+ Just tyArgs -> Just $ show dctor ++ " " ++ unwords (map prettyPrintTypeAtom tyArgs)
60+ tell ["data " ++ show pn ++ " " ++ unwords args ++ " = " ++ intercalate " | " (mapMaybe printDctor dctors')]
61+ Just (_, TypeSynonym) ->
62+ case Qualified (Just moduleName) pn `M.lookup` typeSynonyms env of
63+ Nothing -> error $ show pn ++ " has no type synonym info in exportToPs"
64+ Just (args, synTy) ->
65+ tell ["type " ++ show pn ++ " " ++ unwords args ++ " = " ++ prettyPrintType synTy]
66+ _ -> error "Invalid input in exportToPs"
67+
68+ exportToPs (ValueRef ident) =
69+ case (moduleName, ident) `M.lookup` names env of
70+ Nothing -> error $ show ident ++ " has no type in exportToPs"
71+ Just (ty, nameKind) | nameKind == Value || nameKind == Extern ForeignImport || nameKind == Extern InlineJavascript ->
72+ tell ["foreign import " ++ show ident ++ " :: " ++ prettyPrintType ty]
73+ _ -> return ()
74+ exportToPs (TypeClassRef className) =
75+ case Qualified (Just moduleName) className `M.lookup` typeClasses env of
76+ Nothing -> error $ show className ++ " has no type class definition in exportToPs"
77+ Just (args, members) -> do
78+ tell ["class " ++ show className ++ " " ++ unwords args ++ " where"]
79+ forM_ (filter (isValueExported . fst) members) $ \(member ,ty) ->
80+ tell [ " " ++ show member ++ " :: " ++ prettyPrintType ty ]
81+ exportToPs (TypeInstanceRef ident) = do
82+ let TypeClassDictionaryInScope { tcdClassName = className, tcdInstanceTypes = tys, tcdDependencies = deps} =
83+ fromMaybe (error $ "Type class instance has no dictionary in exportToPs") . find ((== Qualified (Just moduleName) ident) . tcdName) $ typeClassDictionaries env
84+ let constraintsText = case fromMaybe [] deps of
85+ [] -> ""
86+ cs -> "(" ++ intercalate ", " (map (\(pn, tys') -> show pn ++ " " ++ unwords (map prettyPrintTypeAtom tys')) cs) ++ ") => "
87+ tell ["foreign import instance " ++ show ident ++ " :: " ++ constraintsText ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys)]
88+
89+ isValueExported :: Ident -> Bool
90+ isValueExported ident = ValueRef ident `elem` exts
91+
src/Language/PureScript/CodeGen/JS.hsnew file+332
@@ -0,0 +1,332 @@
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+) where
24+
25+import Data.Maybe (fromMaybe, mapMaybe)
26+import Data.Function (on)
27+
28+import Control.Arrow (second)
29+import Control.Monad (replicateM, forM)
30+
31+import qualified Data.Map as M
32+
33+import Language.PureScript.Values
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 _ _ _ _ = Nothing
87+
88+-- |
89+-- Generate code in the simplified Javascript intermediate representation for an export from a
90+-- module.
91+--
92+exportToJs :: DeclarationRef -> [JS]
93+exportToJs (TypeRef _ (Just dctors)) = flip map dctors (export . Escaped . runProperName)
94+exportToJs (ValueRef name) = [export name]
95+exportToJs (TypeInstanceRef name) = [export name]
96+exportToJs _ = []
97+
98+-- |
99+-- Generate code in the simplified Javascript intermediate representation for assigning an exported
100+-- value to the current module object.
101+--
102+export :: Ident -> JS
103+export ident = JSAssignment (accessor ident (JSVar "module")) (var ident)
104+
105+-- |
106+-- Generate code in the simplified Javascript intermediate representation for a variable based on a
107+-- PureScript identifier.
108+--
109+var :: Ident -> JS
110+var = JSVar . identToJs
111+
112+-- |
113+-- Generate code in the simplified Javascript intermediate representation for an accessor based on
114+-- a PureScript identifier. If the name is not valid in Javascript (symbol based, reserved name) an
115+-- indexer is returned.
116+--
117+accessor :: Ident -> JS -> JS
118+accessor (Ident name) | nameIsJsReserved name = JSIndexer (JSStringLiteral name)
119+accessor (Op op) = JSIndexer (JSStringLiteral op)
120+accessor ident = JSAccessor (identToJs ident)
121+
122+-- |
123+-- Generate code in the simplified Javascript intermediate representation for a value or expression.
124+--
125+valueToJs :: Options -> ModuleName -> Environment -> Value -> JS
126+valueToJs _ _ _ (NumericLiteral n) = JSNumericLiteral n
127+valueToJs _ _ _ (StringLiteral s) = JSStringLiteral s
128+valueToJs _ _ _ (BooleanLiteral b) = JSBooleanLiteral b
129+valueToJs opts m e (ArrayLiteral xs) = JSArrayLiteral (map (valueToJs opts m e) xs)
130+valueToJs opts m e (ObjectLiteral ps) = JSObjectLiteral (map (second (valueToJs opts m e)) ps)
131+valueToJs opts m e (ObjectUpdate o ps) = extendObj (valueToJs opts m e o) (map (second (valueToJs opts m e)) ps)
132+valueToJs _ m _ (Constructor name) = qualifiedToJS m (Ident . runProperName) name
133+valueToJs opts m e (Case values binders) = bindersToJs opts m e binders (map (valueToJs opts m e) values)
134+valueToJs opts m e (IfThenElse cond th el) = JSConditional (valueToJs opts m e cond) (valueToJs opts m e th) (valueToJs opts m e el)
135+valueToJs opts m e (Accessor prop val) = JSAccessor prop (valueToJs opts m e val)
136+valueToJs opts m e (App val arg) = JSApp (valueToJs opts m e val) [valueToJs opts m e arg]
137+valueToJs opts m e (Abs (Left arg) val) = JSFunction Nothing [identToJs arg] (JSBlock [JSReturn (valueToJs opts m (bindName m arg e) val)])
138+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)])
139+valueToJs _ m _ (Var ident) = varToJs m ident
140+valueToJs opts m e (TypedValue _ val _) = valueToJs opts m e val
141+valueToJs _ _ _ (TypeClassDictionary _ _) = error "Type class dictionary was not replaced"
142+valueToJs _ _ _ _ = error "Invalid argument to valueToJs"
143+
144+-- |
145+-- Shallow copy an object.
146+--
147+extendObj :: JS -> [(String, JS)] -> JS
148+extendObj obj sts = JSApp (JSFunction Nothing [] block) []
149+ where
150+ [newObj, key] = take 2 . map identToJs . unusedNames $ (obj, sts)
151+ jsKey = JSVar key
152+ jsNewObj = JSVar newObj
153+ block = JSBlock (objAssign:copy:extend ++ [JSReturn jsNewObj])
154+ objAssign = JSVariableIntroduction newObj (Just $ JSObjectLiteral [])
155+ copy = JSForIn key obj $ JSBlock [JSIfElse cond assign Nothing]
156+ cond = JSApp (JSAccessor "hasOwnProperty" obj) [jsKey]
157+ assign = JSBlock [JSAssignment (JSIndexer jsKey jsNewObj) (JSIndexer jsKey obj)]
158+ stToAssign (s, js) = JSAssignment (JSAccessor s jsNewObj) js
159+ extend = map stToAssign sts
160+
161+-- |
162+-- Temporarily extends the environment with a single local variable name
163+--
164+bindName :: ModuleName -> Ident -> Environment -> Environment
165+bindName m ident = bindNames m [ident]
166+
167+-- |
168+-- Temporarily extends the environment to include local variable names introduced by lambda
169+-- abstractions or case statements
170+--
171+bindNames :: ModuleName -> [Ident] -> Environment -> Environment
172+bindNames m idents env = env { names = M.fromList [ ((m, ident), (noType, LocalVariable)) | ident <- idents ] `M.union` names env }
173+ where
174+ noType = error "Temporary lambda variable type was read"
175+
176+
177+-- |
178+-- Generate code in the simplified Javascript intermediate representation for runtime type checks.
179+--
180+runtimeTypeChecks :: String -> Type -> [JS]
181+runtimeTypeChecks arg ty =
182+ let
183+ argTy = getFunctionArgumentType ty
184+ in
185+ maybe [] (argumentCheck (JSVar arg)) argTy
186+ where
187+ getFunctionArgumentType :: Type -> Maybe Type
188+ getFunctionArgumentType (TypeApp (TypeApp t funArg) _) | t == tyFunction = Just funArg
189+ getFunctionArgumentType (ForAll _ ty' _) = getFunctionArgumentType ty'
190+ getFunctionArgumentType _ = Nothing
191+ argumentCheck :: JS -> Type -> [JS]
192+ argumentCheck val t | t == tyNumber = [typeCheck val "number"]
193+ argumentCheck val t | t == tyString = [typeCheck val "string"]
194+ argumentCheck val t | t == tyBoolean = [typeCheck val "boolean"]
195+ argumentCheck val (TypeApp t _) | t == tyArray = [arrayCheck val]
196+ argumentCheck val (Object row) =
197+ let
198+ (pairs, _) = rowToList row
199+ in
200+ typeCheck val "object" : concatMap (\(prop, ty') -> argumentCheck (JSAccessor prop val) ty') pairs
201+ argumentCheck val (TypeApp (TypeApp t _) _) | t == tyFunction = [typeCheck val "function"]
202+ argumentCheck val (ForAll _ ty' _) = argumentCheck val ty'
203+ argumentCheck _ _ = []
204+ typeCheck :: JS -> String -> JS
205+ typeCheck js ty' = JSIfElse (JSBinary NotEqualTo (JSTypeOf js) (JSStringLiteral ty')) (JSBlock [JSThrow (JSStringLiteral $ ty' ++ " expected")]) Nothing
206+ arrayCheck :: JS -> JS
207+ arrayCheck js = JSIfElse (JSUnary Not (JSApp (JSAccessor "isArray" (JSVar "Array")) [js])) (JSBlock [JSThrow (JSStringLiteral "Array expected")]) Nothing
208+
209+-- |
210+-- Generate code in the simplified Javascript intermediate representation for a reference to a
211+-- variable.
212+--
213+varToJs :: ModuleName -> Qualified Ident -> JS
214+varToJs _ (Qualified Nothing ident) = var ident
215+varToJs m qual = qualifiedToJS m id qual
216+
217+-- |
218+-- Generate code in the simplified Javascript intermediate representation for a reference to a
219+-- variable that may have a qualified name.
220+--
221+qualifiedToJS :: ModuleName -> (a -> Ident) -> Qualified a -> JS
222+qualifiedToJS m f (Qualified (Just m') a) | m /= m' = accessor (f a) (JSAccessor (moduleNameToJs m') $ JSVar C._ps)
223+qualifiedToJS _ f (Qualified _ a) = JSVar $ identToJs (f a)
224+
225+-- |
226+-- Generate code in the simplified Javascript intermediate representation for pattern match binders
227+-- and guards.
228+--
229+bindersToJs :: Options -> ModuleName -> Environment -> [CaseAlternative] -> [JS] -> JS
230+bindersToJs opts m e binders vals = runGen (map identToJs (unusedNames (binders, vals))) $ do
231+ valNames <- replicateM (length vals) fresh
232+ jss <- forM binders $ \(CaseAlternative bs grd result) -> go valNames [JSReturn (valueToJs opts m (bindNames m (binderNames bs) e) result)] bs grd
233+ return $ JSApp (JSFunction Nothing valNames (JSBlock (concat jss ++ [JSThrow (JSStringLiteral "Failed pattern match")])))
234+ vals
235+ where
236+ go :: [String] -> [JS] -> [Binder] -> Maybe Guard -> Gen [JS]
237+ go _ done [] Nothing = return done
238+ go _ done [] (Just cond) = return [JSIfElse (valueToJs opts m e cond) (JSBlock done) Nothing]
239+ go (v:vs) done' (b:bs) grd = do
240+ done'' <- go vs done' bs grd
241+ binderToJs m e v done'' b
242+ go _ _ _ _ = error "Invalid arguments to bindersToJs"
243+
244+-- |
245+-- Generate code in the simplified Javascript intermediate representation for a pattern match
246+-- binder.
247+--
248+binderToJs :: ModuleName -> Environment -> String -> [JS] -> Binder -> Gen [JS]
249+binderToJs _ _ _ done NullBinder = return done
250+binderToJs _ _ varName done (StringBinder str) =
251+ return [JSIfElse (JSBinary EqualTo (JSVar varName) (JSStringLiteral str)) (JSBlock done) Nothing]
252+binderToJs _ _ varName done (NumberBinder num) =
253+ return [JSIfElse (JSBinary EqualTo (JSVar varName) (JSNumericLiteral num)) (JSBlock done) Nothing]
254+binderToJs _ _ varName done (BooleanBinder True) =
255+ return [JSIfElse (JSVar varName) (JSBlock done) Nothing]
256+binderToJs _ _ varName done (BooleanBinder False) =
257+ return [JSIfElse (JSUnary Not (JSVar varName)) (JSBlock done) Nothing]
258+binderToJs _ _ varName done (VarBinder ident) =
259+ return (JSVariableIntroduction (identToJs ident) (Just (JSVar varName)) : done)
260+binderToJs m e varName done (ConstructorBinder ctor bs) = do
261+ js <- go 0 done bs
262+ if isOnlyConstructor e ctor
263+ then
264+ return js
265+ else
266+ return [JSIfElse (JSBinary EqualTo (JSAccessor "ctor" (JSVar varName)) (JSStringLiteral (show ctor)))
267+ (JSBlock js)
268+ Nothing]
269+ where
270+ go :: Integer -> [JS] -> [Binder] -> Gen [JS]
271+ go _ done' [] = return done'
272+ go index done' (binder:bs') = do
273+ argVar <- fresh
274+ done'' <- go (index + 1) done' bs'
275+ js <- binderToJs m e argVar done'' binder
276+ return (JSVariableIntroduction argVar (Just (JSIndexer (JSNumericLiteral (Left index)) (JSAccessor "values" (JSVar varName)))) : js)
277+binderToJs m e varName done (ObjectBinder bs) = go done bs
278+ where
279+ go :: [JS] -> [(String, Binder)] -> Gen [JS]
280+ go done' [] = return done'
281+ go done' ((prop, binder):bs') = do
282+ propVar <- fresh
283+ done'' <- go done' bs'
284+ js <- binderToJs m e propVar done'' binder
285+ return (JSVariableIntroduction propVar (Just (JSAccessor prop (JSVar varName))) : js)
286+binderToJs m e varName done (ArrayBinder bs) = do
287+ js <- go done 0 bs
288+ return [JSIfElse (JSBinary EqualTo (JSAccessor "length" (JSVar varName)) (JSNumericLiteral (Left (fromIntegral $ length bs)))) (JSBlock js) Nothing]
289+ where
290+ go :: [JS] -> Integer -> [Binder] -> Gen [JS]
291+ go done' _ [] = return done'
292+ go done' index (binder:bs') = do
293+ elVar <- fresh
294+ done'' <- go done' (index + 1) bs'
295+ js <- binderToJs m e elVar done'' binder
296+ return (JSVariableIntroduction elVar (Just (JSIndexer (JSNumericLiteral (Left index)) (JSVar varName))) : js)
297+binderToJs m e varName done (ConsBinder headBinder tailBinder) = do
298+ headVar <- fresh
299+ tailVar <- fresh
300+ js1 <- binderToJs m e headVar done headBinder
301+ js2 <- binderToJs m e tailVar js1 tailBinder
302+ return [JSIfElse (JSBinary GreaterThan (JSAccessor "length" (JSVar varName)) (JSNumericLiteral (Left 0))) (JSBlock
303+ ( JSVariableIntroduction headVar (Just (JSIndexer (JSNumericLiteral (Left 0)) (JSVar varName))) :
304+ JSVariableIntroduction tailVar (Just (JSApp (JSAccessor "slice" (JSVar varName)) [JSNumericLiteral (Left 1)])) :
305+ js2
306+ )) Nothing]
307+binderToJs m e varName done (NamedBinder ident binder) = do
308+ js <- binderToJs m e varName done binder
309+ return (JSVariableIntroduction (identToJs ident) (Just (JSVar varName)) : js)
310+
311+-- |
312+-- Checks whether a data constructor is the only constructor for that type, used to simplify the
313+-- check when generating code for binders.
314+--
315+isOnlyConstructor :: Environment -> Qualified ProperName -> Bool
316+isOnlyConstructor e ctor =
317+ let ty = fromMaybe (error "Data constructor not found") $ ctor `M.lookup` dataConstructors e
318+ in numConstructors (ctor, ty) == 1
319+ where
320+ numConstructors ty = length $ filter (((==) `on` typeConstructor) ty) $ M.toList $ dataConstructors e
321+ typeConstructor (Qualified (Just moduleName) _, (tyCtor, _)) = (moduleName, tyCtor)
322+ typeConstructor _ = error "Invalid argument to isOnlyConstructor"
323+
324+wrapExportsContainer :: Options -> [JS] -> JS
325+wrapExportsContainer opts modules = JSApp (JSFunction Nothing [C._ps] $ JSBlock $ JSStringLiteral "use strict" : modules) [exportSelector]
326+ where
327+ exportSelector = JSConditional (JSBinary And (JSBinary NotEqualTo (JSTypeOf $ JSVar "module") (JSStringLiteral "undefined")) (JSAccessor "exports" (JSVar "module")))
328+ (JSAccessor "exports" (JSVar "module"))
329+ (JSConditional (JSBinary NotEqualTo (JSTypeOf $ JSVar "window") (JSStringLiteral "undefined"))
330+ (JSAssignment (JSAccessor browserNamespace (JSVar "window")) (JSBinary Or (JSAccessor browserNamespace (JSVar "window")) (JSObjectLiteral [])))
331+ (JSApp (JSFunction Nothing [] $ JSBlock [JSThrow $ JSStringLiteral "PureScript doesn't know how to export modules in the current environment"]) []))
332+ browserNamespace = optionsBrowserNamespace opts
src/Language/PureScript/CodeGen/JS/AST.hsnew file+237
@@ -0,0 +1,237 @@
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+
24+-- |
25+-- Built-in unary operators
26+--
27+data UnaryOperator
28+ -- |
29+ -- Numeric negation
30+ --
31+ = Negate
32+ -- |
33+ -- Boolean negation
34+ --
35+ | Not
36+ -- |
37+ -- Bitwise negation
38+ --
39+ | BitwiseNot
40+ -- |
41+ -- Numeric unary \'plus\'
42+ --
43+ | Positive deriving (Show, Eq, Data, Typeable)
44+
45+-- |
46+-- Built-in binary operators
47+--
48+data BinaryOperator
49+ -- |
50+ -- Numeric addition
51+ --
52+ = Add
53+ -- |
54+ -- Numeric subtraction
55+ --
56+ | Subtract
57+ -- |
58+ -- Numeric multiplication
59+ --
60+ | Multiply
61+ -- |
62+ -- Numeric division
63+ --
64+ | Divide
65+ -- |
66+ -- Remainder
67+ --
68+ | Modulus
69+ -- |
70+ -- Generic equality test
71+ --
72+ | EqualTo
73+ -- |
74+ -- Generic inequality test
75+ --
76+ | NotEqualTo
77+ -- |
78+ -- Numeric less-than
79+ --
80+ | LessThan
81+ -- |
82+ -- Numeric less-than-or-equal
83+ --
84+ | LessThanOrEqualTo
85+ -- |
86+ -- Numeric greater-than
87+ --
88+ | GreaterThan
89+ -- |
90+ -- Numeric greater-than-or-equal
91+ --
92+ | GreaterThanOrEqualTo
93+ -- |
94+ -- Boolean and
95+ --
96+ | And
97+ -- |
98+ -- Boolean or
99+ --
100+ | Or
101+ -- |
102+ -- Bitwise and
103+ --
104+ | BitwiseAnd
105+ -- |
106+ -- Bitwise or
107+ --
108+ | BitwiseOr
109+ -- |
110+ -- Bitwise xor
111+ --
112+ | BitwiseXor
113+ -- |
114+ -- Bitwise left shift
115+ --
116+ | ShiftLeft
117+ -- |
118+ -- Bitwise right shift
119+ --
120+ | ShiftRight
121+ -- |
122+ -- Bitwise right shift with zero-fill
123+ --
124+ | ZeroFillShiftRight deriving (Show, Eq, Data, Typeable)
125+
126+-- |
127+-- Data type for simplified Javascript expressions
128+--
129+data JS
130+ -- |
131+ -- A numeric literal
132+ --
133+ = JSNumericLiteral (Either Integer Double)
134+ -- |
135+ -- A string literal
136+ --
137+ | JSStringLiteral String
138+ -- |
139+ -- A boolean literal
140+ --
141+ | JSBooleanLiteral Bool
142+ -- |
143+ -- A unary operator application
144+ --
145+ | JSUnary UnaryOperator JS
146+ -- |
147+ -- A binary operator application
148+ --
149+ | JSBinary BinaryOperator JS JS
150+ -- |
151+ -- An array literal
152+ --
153+ | JSArrayLiteral [JS]
154+ -- |
155+ -- An array indexer expression
156+ --
157+ | JSIndexer JS JS
158+ -- |
159+ -- An object literal
160+ --
161+ | JSObjectLiteral [(String, JS)]
162+ -- |
163+ -- An object property accessor expression
164+ --
165+ | JSAccessor String JS
166+ -- |
167+ -- A function introduction (optional name, arguments, body)
168+ --
169+ | JSFunction (Maybe String) [String] JS
170+ -- |
171+ -- Function application
172+ --
173+ | JSApp JS [JS]
174+ -- |
175+ -- Variable
176+ --
177+ | JSVar String
178+ -- |
179+ -- Conditional expression
180+ --
181+ | JSConditional JS JS JS
182+ -- |
183+ -- A block of expressions in braces
184+ --
185+ | JSBlock [JS]
186+ -- |
187+ -- A variable introduction and optional initialization
188+ --
189+ | JSVariableIntroduction String (Maybe JS)
190+ -- |
191+ -- A variable assignment
192+ --
193+ | JSAssignment JS JS
194+ -- |
195+ -- While loop
196+ --
197+ | JSWhile JS JS
198+ -- |
199+ -- For loop
200+ --
201+ | JSFor String JS JS JS
202+ -- |
203+ -- ForIn loop
204+ --
205+ | JSForIn String JS JS
206+ -- |
207+ -- If-then-else statement
208+ --
209+ | JSIfElse JS JS (Maybe JS)
210+ -- |
211+ -- Return statement
212+ --
213+ | JSReturn JS
214+ -- |
215+ -- Throw statement
216+ --
217+ | JSThrow JS
218+ -- |
219+ -- Type-Of operator
220+ --
221+ | JSTypeOf JS
222+ -- |
223+ -- Labelled statement
224+ --
225+ | JSLabel String JS
226+ -- |
227+ -- Break statement
228+ --
229+ | JSBreak String
230+ -- |
231+ -- Continue statement
232+ --
233+ | JSContinue String
234+ -- |
235+ -- Raw Javascript (generated when parsing fails for an inline foreign import declaration)
236+ --
237+ | JSRaw String deriving (Show, Eq, Data, Typeable)
src/Language/PureScript/CodeGen/Monad.hsnew file+43
@@ -0,0 +1,43 @@
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.hsnew file+192
@@ -0,0 +1,192 @@
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+-- Main module
171+
172+main :: String
173+main = "main"
174+
175+-- Code Generation
176+
177+_ps :: String
178+_ps = "_ps"
179+
180+-- Modules
181+
182+prim :: String
183+prim = "Prim"
184+
185+prelude :: String
186+prelude = "Prelude"
187+
188+eff :: String
189+eff = "Control_Monad_Eff"
190+
191+st :: String
192+st = "Control_Monad_ST"
src/Language/PureScript/DeadCodeElimination.hsnew file+98
@@ -0,0 +1,98 @@
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.Values
27+import Language.PureScript.Declarations
28+
29+-- |
30+-- Eliminate all declarations which are not a transitive dependency of the entry point module
31+--
32+eliminateDeadCode :: [ModuleName] -> [Module] -> [Module]
33+eliminateDeadCode entryPoints ms = map go ms
34+ where
35+ go (Module moduleName ds (Just exps)) = Module moduleName ds' (Just exps')
36+ where
37+ ds' = filter (isUsed moduleName graph vertexFor entryPointVertices) ds
38+ exps' = mapMaybe (filterExport ds') exps
39+ go _ = error "Exports should have been elaborated in name desugaring"
40+ declarations = concatMap declarationsByModule ms
41+ (graph, _, vertexFor) = graphFromEdges $ map (\(key, deps) -> (key, key, deps)) declarations
42+ entryPointVertices = mapMaybe (vertexFor . fst) . filter (\((mn, _), _) -> mn `elem` entryPoints) $ declarations
43+
44+ filterExport :: [Declaration] -> DeclarationRef -> Maybe DeclarationRef
45+ filterExport decls r@(TypeRef name _) | (any $ typeExists name) decls = Just r
46+ filterExport decls r@(ValueRef name) | (any $ valueExists name) decls = Just r
47+ filterExport decls r@(TypeInstanceRef name) | (any $ valueExists name) decls = Just r
48+ filterExport _ _ = Nothing
49+
50+ valueExists :: Ident -> Declaration -> Bool
51+ valueExists name (ValueDeclaration name' _ _ _ _) = name == name'
52+ valueExists name (ExternDeclaration _ name' _ _) = name == name'
53+ valueExists name (BindingGroupDeclaration decls) = any (\(name', _, _) -> name == name') decls
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 _ _ = False
60+
61+type Key = (ModuleName, Either Ident ProperName)
62+
63+declarationsByModule :: Module -> [(Key, [Key])]
64+declarationsByModule (Module moduleName ds _) = concatMap go ds
65+ where
66+ go :: Declaration -> [(Key, [Key])]
67+ go d@(ValueDeclaration name _ _ _ _) = [((moduleName, Left name), dependencies moduleName d)]
68+ go (DataDeclaration _ _ dctors) = map (\(name, _) -> ((moduleName, Right name), [])) dctors
69+ go (ExternDeclaration _ name _ _) = [((moduleName, Left name), [])]
70+ go d@(BindingGroupDeclaration names') = map (\(name, _, _) -> ((moduleName, Left name), dependencies moduleName d)) names'
71+ go (DataBindingGroupDeclaration ds') = concatMap go ds'
72+ go _ = []
73+
74+dependencies :: (Data d) => ModuleName -> d -> [Key]
75+dependencies moduleName = nub . everything (++) (mkQ [] values)
76+ where
77+ values :: Value -> [Key]
78+ values (Var ident) = let (mn, name) = qualify moduleName ident in [(mn, Left name)]
79+ values (Constructor (Qualified (Just mn) name)) = [(mn, Right name)]
80+ values (Constructor (Qualified Nothing _)) = error "Found unqualified data constructor"
81+ values _ = []
82+
83+isUsed :: ModuleName -> Graph -> (Key -> Maybe Vertex) -> [Vertex] -> Declaration -> Bool
84+isUsed moduleName graph vertexFor entryPointVertices (ValueDeclaration name _ _ _ _) =
85+ let Just v' = vertexFor (moduleName, Left name)
86+ in any (\v -> path graph v v') entryPointVertices
87+isUsed moduleName graph vertexFor entryPointVertices (DataDeclaration _ _ dctors) =
88+ any (\(pn, _) -> let Just v' = vertexFor (moduleName, Right pn)
89+ in any (\v -> path graph v v') entryPointVertices) dctors
90+isUsed moduleName graph vertexFor entryPointVertices (ExternDeclaration _ name _ _) =
91+ let Just v' = vertexFor (moduleName, Left name)
92+ in any (\v -> path graph v v') entryPointVertices
93+isUsed moduleName graph vertexFor entryPointVertices (BindingGroupDeclaration ds) =
94+ any (\(name, _, _) -> let Just v' = vertexFor (moduleName, Left name)
95+ in any (\v -> path graph v v') entryPointVertices) ds
96+isUsed moduleName graph vertexFor entryPointVertices (DataBindingGroupDeclaration ds) =
97+ any (isUsed moduleName graph vertexFor entryPointVertices) ds
98+isUsed _ _ _ _ _ = True
src/Language/PureScript/Declarations.hsnew file+190
@@ -0,0 +1,190 @@
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.Values
20+import Language.PureScript.Types
21+import Language.PureScript.Names
22+import Language.PureScript.Kinds
23+import Language.PureScript.CodeGen.JS.AST
24+import Language.PureScript.Environment
25+
26+import qualified Data.Data as D
27+
28+-- |
29+-- A precedence level for an infix operator
30+--
31+type Precedence = Integer
32+
33+-- |
34+-- Associativity for infix operators
35+--
36+data Associativity = Infixl | Infixr deriving (D.Data, D.Typeable)
37+
38+instance Show Associativity where
39+ show Infixl = "infixl"
40+ show Infixr = "infixr"
41+
42+-- |
43+-- Fixity data for infix operators
44+--
45+data Fixity = Fixity Associativity Precedence deriving (Show, D.Data, D.Typeable)
46+
47+-- |
48+-- A module declaration, consisting of a module name, a list of declarations, and a list of the
49+-- declarations that are explicitly imported. If the export list is Nothing, everything is exported.
50+--
51+data Module = Module ModuleName [Declaration] (Maybe [DeclarationRef]) deriving (Show, D.Data, D.Typeable)
52+
53+-- |
54+-- An item in a list of explicit imports or exports
55+--
56+data DeclarationRef
57+ -- |
58+ -- A type constructor with data constructors
59+ --
60+ = TypeRef ProperName (Maybe [ProperName])
61+ -- |
62+ -- A value
63+ --
64+ | ValueRef Ident
65+ -- |
66+ -- A type class
67+ --
68+ | TypeClassRef ProperName
69+ -- |
70+ -- A type class instance, created during typeclass desugaring (name, class name, instance types)
71+ --
72+ | TypeInstanceRef Ident
73+ deriving (Show, Eq, D.Data, D.Typeable)
74+
75+-- |
76+-- The data type of declarations
77+--
78+data Declaration
79+ -- |
80+ -- A data type declaration (name, arguments, data constructors)
81+ --
82+ = DataDeclaration ProperName [String] [(ProperName, [Type])]
83+ -- |
84+ -- A minimal mutually recursive set of data type declarations
85+ --
86+ | DataBindingGroupDeclaration [Declaration]
87+ -- |
88+ -- A type synonym declaration (name, arguments, type)
89+ --
90+ | TypeSynonymDeclaration ProperName [String] Type
91+ -- |
92+ -- A type declaration for a value (name, ty)
93+ --
94+ | TypeDeclaration Ident Type
95+ -- |
96+ -- A value declaration (name, top-level binders, optional guard, value)
97+ --
98+ | ValueDeclaration Ident NameKind [Binder] (Maybe Guard) Value
99+ -- |
100+ -- A minimal mutually recursive set of value declarations
101+ --
102+ | BindingGroupDeclaration [(Ident, NameKind, Value)]
103+ -- |
104+ -- A foreign import declaration (type, name, optional inline Javascript, type)
105+ --
106+ | ExternDeclaration ForeignImportType Ident (Maybe JS) Type
107+ -- |
108+ -- A data type foreign import (name, kind)
109+ --
110+ | ExternDataDeclaration ProperName Kind
111+ -- |
112+ -- A type class instance foreign import
113+ --
114+ | ExternInstanceDeclaration Ident [(Qualified ProperName, [Type])] (Qualified ProperName) [Type]
115+ -- |
116+ -- A fixity declaration (fixity data, operator name)
117+ --
118+ | FixityDeclaration Fixity String
119+ -- |
120+ -- A module import (module name, optional set of identifiers to import)
121+ --
122+ | ImportDeclaration ModuleName (Maybe [DeclarationRef])
123+ -- |
124+ -- A type class declaration (name, argument, member declarations)
125+ --
126+ | TypeClassDeclaration ProperName [String] [Declaration]
127+ -- |
128+ -- A type instance declaration (name, dependencies, class name, instance types, member
129+ -- declarations)
130+ --
131+ | TypeInstanceDeclaration Ident [(Qualified ProperName, [Type])] (Qualified ProperName) [Type] [Declaration]
132+ deriving (Show, D.Data, D.Typeable)
133+
134+-- |
135+-- Test if a declaration is a value declaration
136+--
137+isValueDecl :: Declaration -> Bool
138+isValueDecl ValueDeclaration{} = True
139+isValueDecl _ = False
140+
141+-- |
142+-- Test if a declaration is a data type or type synonym declaration
143+--
144+isDataDecl :: Declaration -> Bool
145+isDataDecl DataDeclaration{} = True
146+isDataDecl TypeSynonymDeclaration{} = True
147+isDataDecl _ = False
148+
149+-- |
150+-- Test if a declaration is a module import
151+--
152+isImportDecl :: Declaration -> Bool
153+isImportDecl ImportDeclaration{} = True
154+isImportDecl _ = False
155+
156+-- |
157+-- Test if a declaration is a data type foreign import
158+--
159+isExternDataDecl :: Declaration -> Bool
160+isExternDataDecl ExternDataDeclaration{} = True
161+isExternDataDecl _ = False
162+
163+-- |
164+-- Test if a declaration is a type class instance foreign import
165+--
166+isExternInstanceDecl :: Declaration -> Bool
167+isExternInstanceDecl ExternInstanceDeclaration{} = True
168+isExternInstanceDecl _ = False
169+
170+-- |
171+-- Test if a declaration is a fixity declaration
172+--
173+isFixityDecl :: Declaration -> Bool
174+isFixityDecl FixityDeclaration{} = True
175+isFixityDecl _ = False
176+
177+-- |
178+-- Test if a declaration is a foreign import
179+--
180+isExternDecl :: Declaration -> Bool
181+isExternDecl ExternDeclaration{} = True
182+isExternDecl _ = False
183+
184+-- |
185+-- Test if a declaration is a type class or instance declaration
186+--
187+isTypeClassDeclaration :: Declaration -> Bool
188+isTypeClassDeclaration TypeClassDeclaration{} = True
189+isTypeClassDeclaration TypeInstanceDeclaration{} = True
190+isTypeClassDeclaration _ = False
src/Language/PureScript/Environment.hsnew file+188
@@ -0,0 +1,188 @@
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.Values
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)])
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
106+ -- |
107+ -- A type instance member, generated during desugaring of type class declarations
108+ --
109+ | TypeInstanceMember deriving (Show, Eq, Data, Typeable)
110+
111+-- |
112+-- The kinds of a type
113+--
114+data TypeKind
115+ -- |
116+ -- Data type
117+ --
118+ = DataType [String] [(ProperName, [Type])]
119+ -- |
120+ -- Type synonym
121+ --
122+ | TypeSynonym
123+ -- |
124+ -- Foreign data
125+ --
126+ | ExternData
127+ -- |
128+ -- A local type variable
129+ --
130+ | LocalTypeVariable deriving (Show, Eq, Data, Typeable)
131+
132+-- |
133+-- Construct a ProperName in the Prim module
134+--
135+primName :: String -> Qualified ProperName
136+primName = Qualified (Just $ ModuleName [ProperName C.prim]) . ProperName
137+
138+-- |
139+-- Construct a type in the Prim module
140+--
141+primTy :: String -> Type
142+primTy = TypeConstructor . primName
143+
144+-- |
145+-- Type constructor for functions
146+--
147+tyFunction :: Type
148+tyFunction = primTy "Function"
149+
150+-- |
151+-- Type constructor for strings
152+--
153+tyString :: Type
154+tyString = primTy "String"
155+
156+-- |
157+-- Type constructor for numbers
158+--
159+tyNumber :: Type
160+tyNumber = primTy "Number"
161+
162+-- |
163+-- Type constructor for booleans
164+--
165+tyBoolean :: Type
166+tyBoolean = primTy "Boolean"
167+
168+-- |
169+-- Type constructor for arrays
170+--
171+tyArray :: Type
172+tyArray = primTy "Array"
173+
174+-- |
175+-- Smart constructor for function types
176+--
177+function :: Type -> Type -> Type
178+function t1 = TypeApp (TypeApp tyFunction t1)
179+
180+-- |
181+-- The primitive types in the external javascript environment with their associated kinds.
182+--
183+primTypes :: M.Map (Qualified ProperName) (Kind, TypeKind)
184+primTypes = M.fromList [ (primName "Function" , (FunKind Star (FunKind Star Star), ExternData))
185+ , (primName "Array" , (FunKind Star Star, ExternData))
186+ , (primName "String" , (Star, ExternData))
187+ , (primName "Number" , (Star, ExternData))
188+ , (primName "Boolean" , (Star, ExternData)) ]
src/Language/PureScript/Kinds.hsnew file+46
@@ -0,0 +1,46 @@
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.hsnew file+62
@@ -0,0 +1,62 @@
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+) where
18+
19+import Data.Data
20+import Data.Graph
21+import Data.Generics
22+import Data.List (nub)
23+
24+import Language.PureScript.Declarations
25+import Language.PureScript.Names
26+
27+-- |
28+-- Sort a collection of modules based on module dependencies.
29+--
30+-- Reports an error if the module graph contains a cycle.
31+--
32+sortModules :: [Module] -> Either String [Module]
33+sortModules ms = do
34+ let verts = map (\m -> (m, getModuleName m, usedModules m)) ms
35+ mapM toModule $ stronglyConnComp verts
36+
37+-- |
38+-- Calculate a list of used modules based on explicit imports and qualified names
39+--
40+usedModules :: (Data d) => d -> [ModuleName]
41+usedModules = nub . everything (++) (mkQ [] qualifiedIdents `extQ` qualifiedProperNames `extQ` imports)
42+ where
43+ qualifiedIdents :: Qualified Ident -> [ModuleName]
44+ qualifiedIdents (Qualified (Just mn) _) = [mn]
45+ qualifiedIdents _ = []
46+ qualifiedProperNames :: Qualified ProperName -> [ModuleName]
47+ qualifiedProperNames (Qualified (Just mn) _) = [mn]
48+ qualifiedProperNames _ = []
49+ imports :: Declaration -> [ModuleName]
50+ imports (ImportDeclaration mn _) = [mn]
51+ imports _ = []
52+
53+getModuleName :: Module -> ModuleName
54+getModuleName (Module mn _ _) = mn
55+
56+-- |
57+-- Convert a strongly connected component of the module graph to a module
58+--
59+toModule :: SCC Module -> Either String Module
60+toModule (AcyclicSCC m) = return m
61+toModule (CyclicSCC [m]) = return m
62+toModule (CyclicSCC _) = Left "Cycle in module dependencies"
src/Language/PureScript/Names.hsnew file+98
@@ -0,0 +1,98 @@
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+import Data.Function (on)
23+
24+-- |
25+-- Names for value identifiers
26+--
27+data Ident
28+ -- |
29+ -- An alphanumeric identifier
30+ --
31+ = Ident String
32+ -- |
33+ -- A symbolic name for an infix operator
34+ --
35+ | Op String
36+ -- |
37+ -- An escaped name
38+ --
39+ | Escaped String deriving (Data, Typeable)
40+
41+instance Show Ident where
42+ show (Ident s) = s
43+ show (Op op) = '(':op ++ ")"
44+ show (Escaped s) = s
45+
46+instance Eq Ident where
47+ Ident s1 == Ident s2 = s1 == s2
48+ Op s1 == Op s2 = s1 == s2
49+ Escaped s1 == Escaped s2 = s1 == s2
50+ Ident s1 == Escaped s2 = s1 == s2
51+ Escaped s1 == Ident s2 = s1 == s2
52+ _ == _ = False
53+
54+instance Ord Ident where
55+ compare = compare `on` show
56+
57+-- |
58+-- Proper names, i.e. capitalized names for e.g. module names, type//data constructors.
59+--
60+newtype ProperName = ProperName { runProperName :: String } deriving (Eq, Ord, Data, Typeable)
61+
62+instance Show ProperName where
63+ show = runProperName
64+
65+-- |
66+-- Module names
67+--
68+data ModuleName = ModuleName [ProperName] deriving (Eq, Ord, Data, Typeable)
69+
70+runModuleName :: ModuleName -> String
71+runModuleName (ModuleName pns) = intercalate "." (runProperName `map` pns)
72+
73+moduleNameFromString :: String -> ModuleName
74+moduleNameFromString = ModuleName . splitProperNames
75+ where
76+ splitProperNames s = case dropWhile (== '.') s of
77+ "" -> []
78+ s' -> ProperName w : splitProperNames s''
79+ where (w, s'') = break (== '.') s'
80+
81+instance Show ModuleName where
82+ show = runModuleName
83+
84+-- |
85+-- A qualified name, i.e. a name with an optional module name
86+--
87+data Qualified a = Qualified (Maybe ModuleName) a deriving (Eq, Ord, Data, Typeable)
88+
89+instance (Show a) => Show (Qualified a) where
90+ show (Qualified Nothing a) = show a
91+ show (Qualified (Just name) a) = show name ++ "." ++ show a
92+
93+-- |
94+-- Provide a default module name, if a name is unqualified
95+--
96+qualify :: ModuleName -> Qualified a -> (ModuleName, a)
97+qualify m (Qualified Nothing a) = (m, a)
98+qualify _ (Qualified (Just m) a) = (m, a)
src/Language/PureScript/Optimizer.hsnew file+75
@@ -0,0 +1,75 @@
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+ , unThunk
62+ , etaConvert
63+ , inlineVariables
64+ , inlineOperator (C.$) $ \f x -> JSApp f [x]
65+ , inlineOperator (C.#) $ \x f -> JSApp f [x]
66+ , inlineOperator (C.!!) $ flip JSIndexer
67+ , inlineOperator (C.++) $ JSBinary Add
68+ , inlineCommonOperators ]
69+
70+untilFixedPoint :: (Eq a) => (a -> a) -> a -> a
71+untilFixedPoint f = go
72+ where
73+ go a = let a' = f a in
74+ if a' == a then a' else go a'
75+
src/Language/PureScript/Optimizer/Blocks.hsnew file+35
@@ -0,0 +1,35 @@
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.hsnew file+78
@@ -0,0 +1,78 @@
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 (`isReassigned` 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.hsnew file+153
@@ -0,0 +1,153 @@
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+) where
23+
24+import Data.Generics
25+
26+import Language.PureScript.CodeGen.JS.AST
27+import Language.PureScript.CodeGen.Common (identToJs)
28+import Language.PureScript.Optimizer.Common
29+import Language.PureScript.Names
30+
31+import qualified Language.PureScript.Constants as C
32+
33+shouldInline :: JS -> Bool
34+shouldInline (JSVar _) = True
35+shouldInline (JSNumericLiteral _) = True
36+shouldInline (JSStringLiteral _) = True
37+shouldInline (JSBooleanLiteral _) = True
38+shouldInline (JSAccessor _ val) = shouldInline val
39+shouldInline (JSIndexer index val) = shouldInline index && shouldInline val
40+shouldInline _ = False
41+
42+etaConvert :: JS -> JS
43+etaConvert = everywhere (mkT convert)
44+ where
45+ convert :: JS -> JS
46+ convert (JSBlock [JSReturn (JSApp (JSFunction Nothing idents block@(JSBlock body)) args)])
47+ | all shouldInline args &&
48+ not (any (`isRebound` block) (map JSVar idents)) &&
49+ not (any (`isRebound` block) args)
50+ = JSBlock (replaceIdents (zip idents args) body)
51+ convert js = js
52+
53+unThunk :: JS -> JS
54+unThunk = everywhere (mkT convert)
55+ where
56+ convert :: JS -> JS
57+ convert (JSBlock [JSReturn (JSApp (JSFunction Nothing [] (JSBlock body)) [])]) = JSBlock body
58+ convert js = js
59+
60+inlineVariables :: JS -> JS
61+inlineVariables = everywhere (mkT $ removeFromBlock go)
62+ where
63+ go :: [JS] -> [JS]
64+ go [] = []
65+ go (JSVariableIntroduction var (Just js) : sts)
66+ | shouldInline js && not (isReassigned var sts) && not (isRebound js sts) && not (isUpdated var sts) =
67+ go (replaceIdent var js sts)
68+ go (s:sts) = s : go sts
69+
70+inlineOperator :: String -> (JS -> JS -> JS) -> JS -> JS
71+inlineOperator op f = everywhere (mkT convert)
72+ where
73+ convert :: JS -> JS
74+ convert (JSApp (JSApp op' [x]) [y]) | isOp op' = f x y
75+ convert other = other
76+ isOp (JSAccessor longForm (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
77+ _ps == C._ps &&
78+ longForm == identToJs (Op op) = True
79+ isOp (JSIndexer (JSStringLiteral op') (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
80+ _ps == C._ps &&
81+ op == op' = True
82+ isOp _ = False
83+
84+inlineCommonOperators :: JS -> JS
85+inlineCommonOperators = applyAll
86+ [ binary C.numNumber (C.+) Add
87+ , binary C.numNumber (C.-) Subtract
88+ , binary C.numNumber (C.*) Multiply
89+ , binary C.numNumber (C./) Divide
90+ , binary C.numNumber (C.%) Modulus
91+ , unary C.numNumber C.negate Negate
92+
93+ , binary C.ordNumber (C.<) LessThan
94+ , binary C.ordNumber (C.>) GreaterThan
95+ , binary C.ordNumber (C.<=) LessThanOrEqualTo
96+ , binary C.ordNumber (C.>=) GreaterThanOrEqualTo
97+
98+ , binary C.eqNumber (C.==) EqualTo
99+ , binary C.eqNumber (C./=) NotEqualTo
100+ , binary C.eqString (C.==) EqualTo
101+ , binary C.eqString (C./=) NotEqualTo
102+ , binary C.eqBoolean (C.==) EqualTo
103+ , binary C.eqBoolean (C./=) NotEqualTo
104+
105+ , binaryFunction C.bitsNumber C.shl ShiftLeft
106+ , binaryFunction C.bitsNumber C.shr ShiftRight
107+ , binaryFunction C.bitsNumber C.zshr ZeroFillShiftRight
108+ , binary C.bitsNumber (C.&) BitwiseAnd
109+ , binary C.bitsNumber C.bar BitwiseOr
110+ , binary C.bitsNumber (C.^) BitwiseXor
111+ , unary C.bitsNumber C.complement BitwiseNot
112+
113+ , binary C.boolLikeBoolean (C.&&) And
114+ , binary C.boolLikeBoolean (C.||) Or
115+ , unary C.boolLikeBoolean C.not Not
116+ ]
117+ where
118+ binary :: String -> String -> BinaryOperator -> JS -> JS
119+ binary dictName opString op = everywhere (mkT convert)
120+ where
121+ convert :: JS -> JS
122+ convert (JSApp (JSApp (JSApp fn [dict]) [x]) [y]) | isOp fn && isOpDict dictName dict = JSBinary op x y
123+ convert other = other
124+ isOp (JSAccessor longForm (JSAccessor prelude (JSVar _))) | prelude == C.prelude &&
125+ longForm == identToJs (Op opString) = True
126+ isOp (JSIndexer (JSStringLiteral op') (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
127+ _ps == C._ps &&
128+ opString == op' = True
129+ isOp _ = False
130+ binaryFunction :: String -> String -> BinaryOperator -> JS -> JS
131+ binaryFunction dictName fnName op = everywhere (mkT convert)
132+ where
133+ convert :: JS -> JS
134+ convert (JSApp (JSApp (JSApp fn [dict]) [x]) [y]) | isOp fn && isOpDict dictName dict = JSBinary op x y
135+ convert other = other
136+ isOp (JSAccessor fnName' (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
137+ _ps == C._ps &&
138+ fnName == fnName' = True
139+ isOp _ = False
140+ unary :: String -> String -> UnaryOperator -> JS -> JS
141+ unary dictName fnName op = everywhere (mkT convert)
142+ where
143+ convert :: JS -> JS
144+ convert (JSApp (JSApp fn [dict]) [x]) | isOp fn && isOpDict dictName dict = JSUnary op x
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+ isOpDict dictName (JSApp (JSAccessor prop (JSAccessor prelude (JSVar _ps))) [JSObjectLiteral []]) | prelude == C.prelude &&
151+ _ps == C._ps &&
152+ prop == dictName = True
153+ isOpDict _ _ = False
src/Language/PureScript/Optimizer/MagicDo.hsnew file+167
@@ -0,0 +1,167 @@
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 | optionsMagicDo opts = inlineST . magicDo'
34+ | otherwise = id
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+ -- Desugae >>
62+ convert (JSApp (JSApp bind [m]) [JSFunction Nothing ["_"] (JSBlock [JSReturn ret])]) | isBind bind =
63+ JSFunction (Just fnName) [] $ JSBlock [ JSApp m [], JSReturn (JSApp ret []) ]
64+ -- Desugar >>=
65+ convert (JSApp (JSApp bind [m]) [JSFunction Nothing [arg] (JSBlock [JSReturn ret])]) | isBind bind =
66+ JSFunction (Just fnName) [] $ JSBlock [ JSVariableIntroduction arg (Just (JSApp m [])), JSReturn (JSApp ret []) ]
67+ -- Desugar untilE
68+ convert (JSApp (JSApp f [arg]) []) | isEffFunc C.untilE f =
69+ JSApp (JSFunction Nothing [] (JSBlock [ JSWhile (JSUnary Not (JSApp arg [])) (JSBlock []), JSReturn (JSObjectLiteral []) ])) []
70+ -- Desugar whileE
71+ convert (JSApp (JSApp (JSApp f [arg1]) [arg2]) []) | isEffFunc C.whileE f =
72+ JSApp (JSFunction Nothing [] (JSBlock [ JSWhile (JSApp arg1 []) (JSBlock [ JSApp arg2 [] ]), JSReturn (JSObjectLiteral []) ])) []
73+ convert other = other
74+ -- Check if an expression represents a monomorphic call to >>= for the Eff monad
75+ isBind (JSApp bindPoly [effDict]) | isBindPoly bindPoly && isEffDict effDict = True
76+ isBind _ = False
77+ -- Check if an expression represents a monomorphic call to return for the Eff monad
78+ isReturn (JSApp retPoly [effDict]) | isRetPoly retPoly && isEffDict effDict = True
79+ isReturn _ = False
80+ -- Check if an expression represents the polymorphic >>= function
81+ isBindPoly (JSAccessor prop (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
82+ _ps == C._ps &&
83+ prop == identToJs (Op (C.>>=)) = True
84+ isBindPoly (JSIndexer (JSStringLiteral bind) (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
85+ _ps == C._ps &&
86+ bind == (C.>>=) = True
87+ isBindPoly _ = False
88+ -- Check if an expression represents the polymorphic return function
89+ isRetPoly (JSAccessor returnEscaped (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
90+ _ps == C._ps &&
91+ returnEscaped == C.returnEscaped = True
92+ isRetPoly (JSIndexer (JSStringLiteral return') (JSAccessor prelude (JSVar _ps))) | prelude == C.prelude &&
93+ _ps == C._ps &&
94+ return' == C.return = True
95+ isRetPoly _ = False
96+ -- Check if an expression represents a function in the Ef module
97+ isEffFunc name (JSAccessor name' (JSAccessor eff (JSVar _ps))) | eff == C.eff &&
98+ _ps == C._ps &&
99+ name == name' = True
100+ isEffFunc _ _ = False
101+ -- Check if an expression represents the Monad Eff dictionary
102+ isEffDict (JSApp (JSVar ident) [JSObjectLiteral []]) | ident == C.monadEffDictionary = True
103+ isEffDict (JSApp (JSAccessor prop (JSAccessor eff (JSVar _ps))) [JSObjectLiteral []]) | eff == C.eff &&
104+ _ps == C._ps &&
105+ prop == C.monadEffDictionary = True
106+ isEffDict _ = False
107+ -- Remove __do function applications which remain after desugaring
108+ undo :: JS -> JS
109+ undo (JSReturn (JSApp (JSFunction (Just ident) [] body) [])) | ident == fnName = body
110+ undo other = other
111+
112+-- |
113+-- Inline functions in the ST module
114+--
115+inlineST :: JS -> JS
116+inlineST = everywhere (mkT convertBlock)
117+ where
118+ -- Look for runST blocks and inline the STRefs there.
119+ -- If all STRefs are used in the scope of the same runST, only using { read, write, modify }STRef then
120+ -- we can be more aggressive about inlining, and actually turn STRefs into local variables.
121+ convertBlock (JSApp f [arg]) | isSTFunc C.runST f || isSTFunc C.runSTArray f =
122+ let refs = nub . findSTRefsIn $ arg
123+ usages = findAllSTUsagesIn arg
124+ allUsagesAreLocalVars = all (\u -> let v = toVar u in isJust v && fromJust v `elem` refs) usages
125+ localVarsDoNotEscape = all (\r -> length (r `appearingIn` arg) == length (filter (\u -> let v = toVar u in v == Just r) usages)) refs
126+ in everywhere (mkT $ convert (allUsagesAreLocalVars && localVarsDoNotEscape)) arg
127+ convertBlock other = other
128+ -- Convert a block in a safe way, preserving object wrappers of references,
129+ -- or in a more aggressive way, turning wrappers into local variables depending on the
130+ -- agg(ressive) parameter.
131+ convert agg (JSApp (JSApp f [arg]) []) | isSTFunc C.newSTRef f =
132+ if agg then arg else JSObjectLiteral [(C.stRefValue, arg)]
133+ convert agg (JSApp (JSApp f [ref]) []) | isSTFunc C.readSTRef f =
134+ if agg then ref else JSAccessor C.stRefValue ref
135+ convert agg (JSApp (JSApp (JSApp f [ref]) [arg]) []) | isSTFunc C.writeSTRef f =
136+ if agg then JSAssignment ref arg else JSAssignment (JSAccessor C.stRefValue ref) arg
137+ convert agg (JSApp (JSApp (JSApp f [ref]) [func]) []) | isSTFunc C.modifySTRef f =
138+ if agg then JSAssignment ref (JSApp func [ref]) else JSAssignment (JSAccessor C.stRefValue ref) (JSApp func [JSAccessor C.stRefValue ref])
139+ convert _ (JSApp (JSApp (JSApp f [arr]) [i]) []) | isSTFunc C.peekSTArray f =
140+ JSIndexer i arr
141+ convert _ (JSApp (JSApp (JSApp (JSApp f [arr]) [i]) [val]) []) | isSTFunc C.pokeSTArray f =
142+ JSAssignment (JSIndexer i arr) val
143+ convert _ other = other
144+ -- Check if an expression represents a function in the ST module
145+ isSTFunc name (JSAccessor name' (JSAccessor st (JSVar _ps))) | st == C.st &&
146+ _ps == C._ps &&
147+ name == name' = True
148+ isSTFunc _ _ = False
149+ -- Find all ST Refs initialized in this block
150+ findSTRefsIn = everything (++) (mkQ [] isSTRef)
151+ where
152+ isSTRef (JSVariableIntroduction ident (Just (JSApp (JSApp f [_]) []))) | isSTFunc C.newSTRef f = [ident]
153+ isSTRef _ = []
154+ -- Find all STRefs used as arguments to readSTRef, writeSTRef, modifySTRef
155+ findAllSTUsagesIn = everything (++) (mkQ [] isSTUsage)
156+ where
157+ isSTUsage (JSApp (JSApp f [ref]) []) | isSTFunc C.readSTRef f = [ref]
158+ isSTUsage (JSApp (JSApp (JSApp f [ref]) [_]) []) | isSTFunc C.writeSTRef f || isSTFunc C.modifySTRef f = [ref]
159+ isSTUsage _ = []
160+ -- Find all uses of a variable
161+ appearingIn ref = everything (++) (mkQ [] isVar)
162+ where
163+ isVar e@(JSVar v) | v == ref = [e]
164+ isVar _ = []
165+ -- Convert a JS value to a String if it is a JSVar
166+ toVar (JSVar v) = Just v
167+ toVar _ = Nothing
src/Language/PureScript/Optimizer/TCO.hsnew file+102
@@ -0,0 +1,102 @@
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 | optionsTco opts = tco'
28+ | otherwise = id
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.hsnew file+31
@@ -0,0 +1,31 @@
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+) where
19+
20+import Data.Generics
21+
22+import Language.PureScript.CodeGen.JS.AST
23+import Language.PureScript.Optimizer.Common
24+
25+removeUnusedVariables :: JS -> JS
26+removeUnusedVariables = everywhere (mkT $ removeFromBlock go)
27+ where
28+ go :: [JS] -> [JS]
29+ go [] = []
30+ go (JSVariableIntroduction var _ : sts) | not (isUsed var sts) = go sts
31+ go (s:sts) = s : go sts
src/Language/PureScript/Options.hsnew file+58
@@ -0,0 +1,58 @@
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+ -- Perform tail-call elimination
24+ --
25+ optionsTco :: Bool
26+ -- |
27+ -- Perform type checks at runtime
28+ --
29+ , optionsPerformRuntimeTypeChecks :: Bool
30+ -- |
31+ -- Inline calls to ret and bind for the Eff monad
32+ --
33+ , optionsMagicDo :: Bool
34+ -- |
35+ -- When specified, checks the type of `main` in the module, and generate a call to run main
36+ -- after the module definitions.
37+ --
38+ , optionsMain :: Maybe String
39+ -- |
40+ -- Skip all optimizations
41+ --
42+ , optionsNoOptimizations :: Bool
43+ -- |
44+ -- Specify the namespace that PureScript modules will be exported to when running in the
45+ -- browser.
46+ --
47+ , optionsBrowserNamespace :: String
48+ -- |
49+ -- The modules to keep while enabling dead code elimination
50+ --
51+ , optionsModules :: [String]
52+ } deriving Show
53+
54+-- |
55+-- Default compiler options
56+--
57+defaultOptions :: Options
58+defaultOptions = Options False False False Nothing False "PS" []
src/Language/PureScript/Parser.hsnew file+35
@@ -0,0 +1,35 @@
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.Values as P
33+import Language.PureScript.Parser.State as P
34+import Language.PureScript.Parser.Kinds as P
35+import Language.PureScript.Parser.Declarations as P
src/Language/PureScript/Parser/Common.hsnew file+370
@@ -0,0 +1,370 @@
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+ , "class"
40+ , "instance"
41+ , "module"
42+ , "case"
43+ , "of"
44+ , "if"
45+ , "then"
46+ , "else"
47+ , "do"
48+ , "let"
49+ , "true"
50+ , "false"
51+ , "in"
52+ , "where"
53+ ]
54+
55+-- |
56+-- A list of reserved identifiers for types
57+--
58+reservedTypeNames :: [String]
59+reservedTypeNames = [ "forall"
60+ , "where" ]
61+
62+-- |
63+-- A list of reserved operators
64+--
65+reservedOpNames :: [String]
66+reservedOpNames = [ "=>", "->", "=", ".", "\\" ]
67+
68+-- |
69+-- Valid first characters for an identifier
70+--
71+identStart :: P.Parsec String u Char
72+identStart = P.lower <|> P.oneOf "_"
73+
74+-- |
75+-- Valid identifier characters
76+--
77+identLetter :: P.Parsec String u Char
78+identLetter = P.alphaNum <|> P.oneOf "_'"
79+
80+-- |
81+-- Valid first characters for an operator
82+--
83+opStart :: P.Parsec String u Char
84+opStart = P.oneOf ":!#$%&*+./<=>?@\\^|-~"
85+
86+-- |
87+-- Valid operators characters
88+--
89+opLetter :: P.Parsec String u Char
90+opLetter = P.oneOf ":!#$%&*+./<=>?@\\^|-~"
91+
92+-- |
93+-- The PureScript language definition
94+--
95+langDef :: PT.GenLanguageDef String u Identity
96+langDef = PT.LanguageDef
97+ { PT.reservedNames = reservedPsNames
98+ , PT.reservedOpNames = reservedOpNames
99+ , PT.commentStart = "{-"
100+ , PT.commentEnd = "-}"
101+ , PT.commentLine = "--"
102+ , PT.nestedComments = True
103+ , PT.identStart = identStart
104+ , PT.identLetter = identLetter
105+ , PT.opStart = opStart
106+ , PT.opLetter = opLetter
107+ , PT.caseSensitive = True
108+ }
109+
110+-- |
111+-- A token parser based on the language definition
112+--
113+tokenParser :: PT.GenTokenParser String u Identity
114+tokenParser = PT.makeTokenParser langDef
115+
116+-- |
117+-- Parse a token
118+--
119+lexeme :: P.Parsec String u a -> P.Parsec String u a
120+lexeme = PT.lexeme tokenParser
121+
122+-- |
123+-- Parse an identifier
124+--
125+identifier :: P.Parsec String u String
126+identifier = PT.identifier tokenParser
127+
128+-- |
129+-- Parse a reserved word
130+--
131+reserved :: String -> P.Parsec String u ()
132+reserved = PT.reserved tokenParser
133+
134+-- |
135+-- Parse a reserved operator
136+--
137+reservedOp :: String -> P.Parsec String u ()
138+reservedOp = PT.reservedOp tokenParser
139+
140+-- |
141+-- Parse an operator
142+--
143+operator :: P.Parsec String u String
144+operator = PT.operator tokenParser
145+
146+-- |
147+-- Parse a string literal
148+--
149+stringLiteral :: P.Parsec String u String
150+stringLiteral = PT.stringLiteral tokenParser
151+
152+-- |
153+-- Parse whitespace
154+--
155+whiteSpace :: P.Parsec String u ()
156+whiteSpace = PT.whiteSpace tokenParser
157+
158+-- |
159+-- Semicolon
160+--
161+semi :: P.Parsec String u String
162+semi = PT.semi tokenParser
163+
164+-- |
165+-- Colon
166+--
167+colon :: P.Parsec String u String
168+colon = PT.colon tokenParser
169+
170+-- |
171+-- Period
172+--
173+dot :: P.Parsec String u String
174+dot = PT.dot tokenParser
175+
176+-- |
177+-- Comma
178+--
179+comma :: P.Parsec String u String
180+comma = PT.comma tokenParser
181+
182+-- |
183+-- Backtick
184+--
185+tick :: P.Parsec String u Char
186+tick = lexeme $ P.char '`'
187+
188+-- |
189+-- Pipe character
190+--
191+pipe :: P.Parsec String u Char
192+pipe = lexeme $ P.char '|'
193+
194+-- |
195+-- Natural number
196+--
197+natural :: P.Parsec String u Integer
198+natural = PT.natural tokenParser
199+
200+-- |
201+-- Parse a proper name
202+--
203+properName :: P.Parsec String u ProperName
204+properName = lexeme $ ProperName <$> P.try ((:) <$> P.upper <*> many P.alphaNum P.<?> "name")
205+
206+-- |
207+-- Parse a module name
208+--
209+moduleName :: P.Parsec String ParseState ModuleName
210+moduleName = ModuleName <$> P.try (sepBy properName dot)
211+
212+-- |
213+-- Parse a qualified name, i.e. M.name or just name
214+--
215+parseQualified :: P.Parsec String ParseState a -> P.Parsec String ParseState (Qualified a)
216+parseQualified parser = part []
217+ where
218+ part path = (do name <- P.try (properName <* delimiter)
219+ part (updatePath path name))
220+ <|> (Qualified (qual path) <$> P.try parser)
221+ delimiter = indented *> dot <* P.notFollowedBy dot
222+ updatePath path name = path ++ [name]
223+ qual path = if null path then Nothing else Just $ ModuleName path
224+
225+-- |
226+-- Parse an integer or floating point value
227+--
228+integerOrFloat :: P.Parsec String u (Either Integer Double)
229+integerOrFloat = (Right <$> P.try (PT.float tokenParser) <|>
230+ Left <$> P.try (PT.natural tokenParser)) P.<?> "number"
231+
232+-- |
233+-- Parse an identifier or parenthesized operator
234+--
235+parseIdent :: P.Parsec String ParseState Ident
236+parseIdent = (Ident <$> identifier) <|> (Op <$> parens operator)
237+
238+-- |
239+-- Parse a token inside square brackets
240+--
241+squares :: P.Parsec String ParseState a -> P.Parsec String ParseState a
242+squares = P.between (lexeme $ P.char '[') (lexeme $ indented *> P.char ']') . (indented *>)
243+
244+-- |
245+-- Parse a token inside parentheses
246+--
247+parens :: P.Parsec String ParseState a -> P.Parsec String ParseState a
248+parens = P.between (lexeme $ P.char '(') (lexeme $ indented *> P.char ')') . (indented *>)
249+
250+-- |
251+-- Parse a token inside braces
252+--
253+braces :: P.Parsec String ParseState a -> P.Parsec String ParseState a
254+braces = P.between (lexeme $ P.char '{') (lexeme $ indented *> P.char '}') . (indented *>)
255+
256+-- |
257+-- Parse a token inside angle brackets
258+--
259+angles :: P.Parsec String ParseState a -> P.Parsec String ParseState a
260+angles = P.between (lexeme $ P.char '<') (lexeme $ indented *> P.char '>') . (indented *>)
261+
262+-- |
263+-- Parse zero or more values separated by a separator token
264+--
265+sepBy :: P.Parsec String ParseState a -> P.Parsec String ParseState sep -> P.Parsec String ParseState [a]
266+sepBy p s = P.sepBy (indented *> p) (indented *> s)
267+
268+-- |
269+-- Parse one or more values separated by a separator token
270+--
271+sepBy1 :: P.Parsec String ParseState a -> P.Parsec String ParseState sep -> P.Parsec String ParseState [a]
272+sepBy1 p s = P.sepBy1 (indented *> p) (indented *> s)
273+
274+-- |
275+-- Parse zero or more values separated by semicolons
276+--
277+semiSep :: P.Parsec String ParseState a -> P.Parsec String ParseState [a]
278+semiSep = flip sepBy semi
279+
280+-- |
281+-- Parse one or more values separated by semicolons
282+--
283+semiSep1 :: P.Parsec String ParseState a -> P.Parsec String ParseState [a]
284+semiSep1 = flip sepBy1 semi
285+
286+-- |
287+-- Parse zero or more values separated by commas
288+--
289+commaSep :: P.Parsec String ParseState a -> P.Parsec String ParseState [a]
290+commaSep = flip sepBy comma
291+
292+-- |
293+-- Parse one or more values separated by commas
294+--
295+commaSep1 :: P.Parsec String ParseState a -> P.Parsec String ParseState [a]
296+commaSep1 = flip sepBy1 comma
297+
298+-- |
299+-- Run the first parser, then match the second if possible, applying the specified function on a successful match
300+--
301+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
302+augment p q f = flip (maybe id $ flip f) <$> p <*> P.optionMaybe q
303+
304+-- |
305+-- Run the first parser, then match the second zero or more times, applying the specified function for each match
306+--
307+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
308+fold first more combine = do
309+ a <- first
310+ bs <- P.many more
311+ return $ foldl combine a bs
312+
313+-- |
314+-- Build a parser from a smaller parser and a list of parsers for postfix operators
315+--
316+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
317+buildPostfixParser fs first = do
318+ a <- first
319+ go a
320+ where
321+ go a = do
322+ maybeA <- P.optionMaybe $ P.choice (map ($ a) fs)
323+ case maybeA of
324+ Nothing -> return a
325+ Just a' -> go a'
326+
327+-- |
328+-- Parse an identifier in backticks or an operator
329+--
330+parseIdentInfix :: P.Parsec String ParseState (Qualified Ident)
331+parseIdentInfix = P.between tick tick (parseQualified (Ident <$> identifier)) <|> Qualified Nothing <$> (Op <$> operator)
332+
333+-- |
334+-- Mark the current indentation level
335+--
336+mark :: P.Parsec String ParseState a -> P.Parsec String ParseState a
337+mark p = do
338+ current <- indentationLevel <$> P.getState
339+ pos <- P.sourceColumn <$> P.getPosition
340+ P.modifyState $ \st -> st { indentationLevel = pos }
341+ a <- p
342+ P.modifyState $ \st -> st { indentationLevel = current }
343+ return a
344+
345+-- |
346+-- Check that the current identation level matches a predicate
347+--
348+checkIndentation :: (P.Column -> P.Column -> Bool) -> P.Parsec String ParseState ()
349+checkIndentation rel = do
350+ col <- P.sourceColumn <$> P.getPosition
351+ current <- indentationLevel <$> P.getState
352+ guard (col `rel` current)
353+
354+-- |
355+-- Check that the current indentation level is past the current mark
356+--
357+indented :: P.Parsec String ParseState ()
358+indented = checkIndentation (>) P.<?> "indentation"
359+
360+-- |
361+-- Check that the current indentation level is at the same indentation as the current mark
362+--
363+same :: P.Parsec String ParseState ()
364+same = checkIndentation (==) P.<?> "no indentation"
365+
366+-- |
367+-- Run a parser which supports indentation
368+--
369+runIndentParser :: FilePath -> P.Parsec String ParseState a -> String -> Either P.ParseError a
370+runIndentParser filePath p = P.runParser p (ParseState 0) filePath
src/Language/PureScript/Parser/Declarations.hsnew file+170
@@ -0,0 +1,170 @@
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+) where
21+
22+import Data.Maybe (isJust, fromMaybe)
23+import Control.Applicative
24+import qualified Text.Parsec as P
25+
26+import Language.PureScript.Parser.State
27+import Language.PureScript.Parser.Common
28+import Language.PureScript.Declarations
29+import Language.PureScript.Parser.Values
30+import Language.PureScript.Parser.Types
31+import Language.PureScript.Parser.Kinds
32+import Language.PureScript.CodeGen.JS.AST
33+import Language.PureScript.Environment
34+
35+parseDataDeclaration :: P.Parsec String ParseState Declaration
36+parseDataDeclaration = do
37+ reserved "data"
38+ name <- indented *> properName
39+ tyArgs <- many (indented *> identifier)
40+ ctors <- P.option [] $ do
41+ _ <- lexeme $ indented *> P.char '='
42+ sepBy1 ((,) <$> properName <*> P.many (indented *> parseTypeAtom)) pipe
43+ return $ DataDeclaration name tyArgs ctors
44+
45+parseTypeDeclaration :: P.Parsec String ParseState Declaration
46+parseTypeDeclaration =
47+ TypeDeclaration <$> P.try (parseIdent <* lexeme (indented *> P.string "::"))
48+ <*> parsePolyType
49+
50+parseTypeSynonymDeclaration :: P.Parsec String ParseState Declaration
51+parseTypeSynonymDeclaration =
52+ TypeSynonymDeclaration <$> (P.try (reserved "type") *> indented *> properName)
53+ <*> many (indented *> identifier)
54+ <*> (lexeme (indented *> P.char '=') *> parsePolyType)
55+
56+parseValueDeclaration :: P.Parsec String ParseState Declaration
57+parseValueDeclaration =
58+ ValueDeclaration <$> parseIdent
59+ <*> pure Value
60+ <*> P.many parseBinderNoParens
61+ <*> P.optionMaybe parseGuard
62+ <*> (lexeme (indented *> P.char '=') *> parseValue)
63+
64+parseExternDeclaration :: P.Parsec String ParseState Declaration
65+parseExternDeclaration = P.try (reserved "foreign") *> indented *> reserved "import" *> indented *>
66+ (ExternDataDeclaration <$> (P.try (reserved "data") *> indented *> properName)
67+ <*> (lexeme (indented *> P.string "::") *> parseKind)
68+ <|> (do reserved "instance"
69+ name <- parseIdent <* lexeme (indented *> P.string "::")
70+ deps <- P.option [] $ do
71+ deps <- parens (commaSep1 ((,) <$> parseQualified properName <*> P.many parseTypeAtom))
72+ indented
73+ reservedOp "=>"
74+ return deps
75+ className <- indented *> parseQualified properName
76+ tys <- P.many (indented *> parseTypeAtom)
77+ return $ ExternInstanceDeclaration name deps className tys)
78+ <|> (do ident <- parseIdent
79+ js <- P.optionMaybe (JSRaw <$> stringLiteral)
80+ ty <- lexeme (indented *> P.string "::") *> parsePolyType
81+ return $ ExternDeclaration (if isJust js then InlineJavascript else ForeignImport) ident js ty))
82+
83+parseAssociativity :: P.Parsec String ParseState Associativity
84+parseAssociativity =
85+ (P.try (reserved "infixl") >> return Infixl) <|>
86+ (P.try (reserved "infixr") >> return Infixr)
87+
88+parseFixity :: P.Parsec String ParseState Fixity
89+parseFixity = Fixity <$> parseAssociativity <*> (indented *> natural)
90+
91+parseFixityDeclaration :: P.Parsec String ParseState Declaration
92+parseFixityDeclaration = do
93+ fixity <- parseFixity
94+ indented
95+ name <- operator
96+ return $ FixityDeclaration fixity name
97+
98+parseImportDeclaration :: P.Parsec String ParseState Declaration
99+parseImportDeclaration = do
100+ reserved "import"
101+ indented
102+ moduleName' <- moduleName
103+ idents <- P.optionMaybe $ parens $ commaSep parseDeclarationRef
104+ return $ ImportDeclaration moduleName' idents
105+
106+parseDeclarationRef :: P.Parsec String ParseState DeclarationRef
107+parseDeclarationRef = ValueRef <$> parseIdent
108+ <|> do name <- properName
109+ dctors <- P.optionMaybe $ parens (lexeme (P.string "..") *> pure Nothing <|> Just <$> commaSep properName)
110+ return $ maybe (TypeClassRef name) (TypeRef name) dctors
111+
112+parseTypeClassDeclaration :: P.Parsec String ParseState Declaration
113+parseTypeClassDeclaration = do
114+ reserved "class"
115+ className <- indented *> properName
116+ idents <- P.many (indented *> identifier)
117+ members <- P.option [] . P.try $ do
118+ indented *> reserved "where"
119+ mark (P.many (same *> parseTypeDeclaration))
120+ return $ TypeClassDeclaration className idents members
121+
122+parseTypeInstanceDeclaration :: P.Parsec String ParseState Declaration
123+parseTypeInstanceDeclaration = do
124+ reserved "instance"
125+ name <- parseIdent <* lexeme (indented *> P.string "::")
126+ deps <- P.optionMaybe $ do
127+ deps <- parens (commaSep1 ((,) <$> parseQualified properName <*> P.many parseTypeAtom))
128+ indented
129+ reservedOp "=>"
130+ return deps
131+ className <- indented *> parseQualified properName
132+ ty <- P.many (indented *> parseTypeAtom)
133+ members <- P.option [] . P.try $ do
134+ indented *> reserved "where"
135+ mark (P.many (same *> parseValueDeclaration))
136+ return $ TypeInstanceDeclaration name (fromMaybe [] deps) className ty members
137+
138+-- |
139+-- Parse a single declaration
140+--
141+parseDeclaration :: P.Parsec String ParseState Declaration
142+parseDeclaration = P.choice
143+ [ parseDataDeclaration
144+ , parseTypeDeclaration
145+ , parseTypeSynonymDeclaration
146+ , parseValueDeclaration
147+ , parseExternDeclaration
148+ , parseFixityDeclaration
149+ , parseImportDeclaration
150+ , parseTypeClassDeclaration
151+ , parseTypeInstanceDeclaration ] P.<?> "declaration"
152+
153+-- |
154+-- Parse a module header and a collection of declarations
155+--
156+parseModule :: P.Parsec String ParseState Module
157+parseModule = do
158+ reserved "module"
159+ indented
160+ name <- moduleName
161+ exports <- P.optionMaybe $ parens $ commaSep1 parseDeclarationRef
162+ _ <- lexeme $ P.string "where"
163+ decls <- mark (P.many (same *> parseDeclaration))
164+ return $ Module name decls exports
165+
166+-- |
167+-- Parse a collection of modules
168+--
169+parseModules :: P.Parsec String ParseState [Module]
170+parseModules = whiteSpace *> mark (P.many (same *> parseModule)) <* P.eof
src/Language/PureScript/Parser/Kinds.hsnew file+45
@@ -0,0 +1,45 @@
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.hsnew file+30
@@ -0,0 +1,30 @@
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.hsnew file+128
@@ -0,0 +1,128 @@
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 $ Object <$> 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 <* 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/Parser/Values.hsnew file+246
@@ -0,0 +1,246 @@
1+-----------------------------------------------------------------------------
2+--
3+-- Module : Language.PureScript.Parser.Values
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 values, statements, binders and guards
13+--
14+-----------------------------------------------------------------------------
15+
16+module Language.PureScript.Parser.Values (
17+ parseValue,
18+ parseGuard,
19+ parseBinder,
20+ parseBinderNoParens,
21+) where
22+
23+import Control.Applicative
24+
25+import Language.PureScript.Values
26+import Language.PureScript.Parser.State
27+import Language.PureScript.Parser.Types
28+
29+import Text.Parsec.Expr
30+
31+import qualified Language.PureScript.Parser.Common as C
32+import qualified Text.Parsec as P
33+
34+booleanLiteral :: P.Parsec String ParseState Bool
35+booleanLiteral = (C.reserved "true" >> return True) P.<|> (C.reserved "false" >> return False)
36+
37+parseNumericLiteral :: P.Parsec String ParseState Value
38+parseNumericLiteral = NumericLiteral <$> C.integerOrFloat
39+
40+parseStringLiteral :: P.Parsec String ParseState Value
41+parseStringLiteral = StringLiteral <$> C.stringLiteral
42+
43+parseBooleanLiteral :: P.Parsec String ParseState Value
44+parseBooleanLiteral = BooleanLiteral <$> booleanLiteral
45+
46+parseArrayLiteral :: P.Parsec String ParseState Value
47+parseArrayLiteral = ArrayLiteral <$> C.squares (C.commaSep parseValue)
48+
49+parseObjectLiteral :: P.Parsec String ParseState Value
50+parseObjectLiteral = ObjectLiteral <$> C.braces (C.commaSep parseIdentifierAndValue)
51+
52+parseIdentifierAndValue :: P.Parsec String ParseState (String, Value)
53+parseIdentifierAndValue = (,) <$> (C.indented *> C.identifier <* C.indented <* C.colon)
54+ <*> (C.indented *> parseValue)
55+
56+parseAbs :: P.Parsec String ParseState Value
57+parseAbs = do
58+ C.reservedOp "\\"
59+ args <- P.many1 (C.indented *> (Abs <$> (Left <$> P.try C.parseIdent <|> Right <$> parseBinderNoParens)))
60+ C.indented *> C.reservedOp "->"
61+ value <- parseValue
62+ return $ toFunction args value
63+ where
64+ toFunction :: [Value -> Value] -> Value -> Value
65+ toFunction args value = foldr ($) value args
66+
67+parseVar :: P.Parsec String ParseState Value
68+parseVar = Var <$> C.parseQualified C.parseIdent
69+
70+parseConstructor :: P.Parsec String ParseState Value
71+parseConstructor = Constructor <$> C.parseQualified C.properName
72+
73+parseCase :: P.Parsec String ParseState Value
74+parseCase = Case <$> P.between (P.try (C.reserved "case")) (C.indented *> C.reserved "of") (return <$> parseValue)
75+ <*> (C.indented *> C.mark (P.many (C.same *> C.mark parseCaseAlternative)))
76+
77+parseCaseAlternative :: P.Parsec String ParseState CaseAlternative
78+parseCaseAlternative = CaseAlternative <$> (return <$> parseBinder)
79+ <*> P.optionMaybe parseGuard
80+ <*> (C.indented *> C.reservedOp "->" *> parseValue)
81+ P.<?> "case alternative"
82+
83+parseIfThenElse :: P.Parsec String ParseState Value
84+parseIfThenElse = IfThenElse <$> (P.try (C.reserved "if") *> C.indented *> parseValue)
85+ <*> (C.indented *> C.reserved "then" *> C.indented *> parseValue)
86+ <*> (C.indented *> C.reserved "else" *> C.indented *> parseValue)
87+
88+parseLet :: P.Parsec String ParseState Value
89+parseLet = do
90+ C.reserved "let"
91+ C.indented
92+ binder <- P.try (Right <$> ((,) <$> C.parseIdent <*> P.many (Left <$> P.try C.parseIdent <|> Right <$> parseBinderNoParens)))
93+ <|> (Left <$> parseBinder)
94+ C.indented
95+ C.reservedOp "="
96+ C.indented
97+ value <- parseValue
98+ C.indented
99+ C.reserved "in"
100+ result <- parseValue
101+ return $ Let binder value result
102+
103+parseValueAtom :: P.Parsec String ParseState Value
104+parseValueAtom = P.choice
105+ [ P.try parseNumericLiteral
106+ , P.try parseStringLiteral
107+ , P.try parseBooleanLiteral
108+ , parseArrayLiteral
109+ , P.try parseObjectLiteral
110+ , parseAbs
111+ , P.try parseConstructor
112+ , P.try parseVar
113+ , parseCase
114+ , parseIfThenElse
115+ , parseDo
116+ , parseLet
117+ , Parens <$> C.parens parseValue ]
118+
119+parsePropertyUpdate :: P.Parsec String ParseState (String, Value)
120+parsePropertyUpdate = do
121+ name <- C.lexeme C.identifier
122+ _ <- C.lexeme $ C.indented *> P.char '='
123+ value <- C.indented *> parseValue
124+ return (name, value)
125+
126+parseAccessor :: Value -> P.Parsec String ParseState Value
127+parseAccessor (Constructor _) = P.unexpected "constructor"
128+parseAccessor obj = P.try $ Accessor <$> (C.indented *> C.dot *> P.notFollowedBy C.opLetter *> C.indented *> C.identifier) <*> pure obj
129+
130+parseDo :: P.Parsec String ParseState Value
131+parseDo = do
132+ C.reserved "do"
133+ C.indented
134+ Do <$> C.mark (P.many (C.same *> C.mark parseDoNotationElement))
135+
136+parseDoNotationLet :: P.Parsec String ParseState DoNotationElement
137+parseDoNotationLet = DoNotationLet <$> (C.reserved "let" *> C.indented *> parseBinder)
138+ <*> (C.indented *> C.reservedOp "=" *> parseValue)
139+
140+parseDoNotationBind :: P.Parsec String ParseState DoNotationElement
141+parseDoNotationBind = DoNotationBind <$> parseBinder <*> (C.indented *> C.reservedOp "<-" *> parseValue)
142+
143+parseDoNotationElement :: P.Parsec String ParseState DoNotationElement
144+parseDoNotationElement = P.choice
145+ [ P.try parseDoNotationBind
146+ , parseDoNotationLet
147+ , P.try (DoNotationValue <$> parseValue) ]
148+
149+-- |
150+-- Parse a value
151+--
152+parseValue :: P.Parsec String ParseState Value
153+parseValue =
154+ (buildExpressionParser operators
155+ . C.buildPostfixParser postfixTable2
156+ $ indexersAndAccessors) P.<?> "expression"
157+ where
158+ indexersAndAccessors = C.buildPostfixParser postfixTable1 parseValueAtom
159+ postfixTable1 = [ parseAccessor
160+ , \v -> P.try $ flip ObjectUpdate <$> (C.indented *> C.braces (C.commaSep1 (C.indented *> parsePropertyUpdate))) <*> pure v ]
161+ postfixTable2 = [ \v -> P.try (flip App <$> (C.indented *> indexersAndAccessors)) <*> pure v
162+ , \v -> flip (TypedValue True) <$> (P.try (C.lexeme (C.indented *> P.string "::")) *> parsePolyType) <*> pure v
163+ ]
164+ operators = [ [ Infix (C.lexeme (P.try (C.indented *> C.parseIdentInfix P.<?> "operator") >>= \ident ->
165+ return (BinaryNoParens ident))) AssocRight ]
166+ ]
167+
168+parseStringBinder :: P.Parsec String ParseState Binder
169+parseStringBinder = StringBinder <$> C.stringLiteral
170+
171+parseBooleanBinder :: P.Parsec String ParseState Binder
172+parseBooleanBinder = BooleanBinder <$> booleanLiteral
173+
174+parseNumberBinder :: P.Parsec String ParseState Binder
175+parseNumberBinder = NumberBinder <$> C.integerOrFloat
176+
177+parseVarBinder :: P.Parsec String ParseState Binder
178+parseVarBinder = VarBinder <$> C.parseIdent
179+
180+parseNullaryConstructorBinder :: P.Parsec String ParseState Binder
181+parseNullaryConstructorBinder = ConstructorBinder <$> C.lexeme (C.parseQualified C.properName) <*> pure []
182+
183+parseConstructorBinder :: P.Parsec String ParseState Binder
184+parseConstructorBinder = ConstructorBinder <$> C.lexeme (C.parseQualified C.properName) <*> many (C.indented *> parseBinderNoParens)
185+
186+parseObjectBinder :: P.Parsec String ParseState Binder
187+parseObjectBinder = ObjectBinder <$> C.braces (C.commaSep (C.indented *> parseIdentifierAndBinder))
188+
189+parseArrayBinder :: P.Parsec String ParseState Binder
190+parseArrayBinder = C.squares $ ArrayBinder <$> C.commaSep (C.indented *> parseBinder)
191+
192+parseNamedBinder :: P.Parsec String ParseState Binder
193+parseNamedBinder = NamedBinder <$> (C.parseIdent <* C.indented <* C.lexeme (P.char '@'))
194+ <*> (C.indented *> parseBinder)
195+
196+parseNullBinder :: P.Parsec String ParseState Binder
197+parseNullBinder = C.lexeme (P.char '_') *> P.notFollowedBy C.identLetter *> return NullBinder
198+
199+parseIdentifierAndBinder :: P.Parsec String ParseState (String, Binder)
200+parseIdentifierAndBinder = do
201+ name <- C.lexeme C.identifier
202+ _ <- C.lexeme $ C.indented *> P.char '='
203+ binder <- C.indented *> parseBinder
204+ return (name, binder)
205+
206+-- |
207+-- Parse a binder
208+--
209+parseBinder :: P.Parsec String ParseState Binder
210+parseBinder = buildExpressionParser operators parseBinderAtom P.<?> "expression"
211+ where
212+ operators = [ [ Infix ( C.lexeme (P.try $ C.indented *> C.reservedOp ":") >> return ConsBinder) AssocRight ] ]
213+ parseBinderAtom :: P.Parsec String ParseState Binder
214+ parseBinderAtom = P.choice (map P.try
215+ [ parseNullBinder
216+ , parseStringBinder
217+ , parseBooleanBinder
218+ , parseNumberBinder
219+ , parseNamedBinder
220+ , parseVarBinder
221+ , parseConstructorBinder
222+ , parseObjectBinder
223+ , parseArrayBinder
224+ , C.parens parseBinder ]) P.<?> "binder"
225+
226+-- |
227+-- Parse a binder as it would appear in a top level declaration
228+--
229+parseBinderNoParens :: P.Parsec String ParseState Binder
230+parseBinderNoParens = P.choice (map P.try
231+ [ parseNullBinder
232+ , parseStringBinder
233+ , parseBooleanBinder
234+ , parseNumberBinder
235+ , parseNamedBinder
236+ , parseVarBinder
237+ , parseNullaryConstructorBinder
238+ , parseObjectBinder
239+ , parseArrayBinder
240+ , C.parens parseBinder ]) P.<?> "binder"
241+-- |
242+-- Parse a guard
243+--
244+parseGuard :: P.Parsec String ParseState Guard
245+parseGuard = C.indented *> C.pipe *> C.indented *> parseValue
246+
src/Language/PureScript/Pretty.hsnew file+32
@@ -0,0 +1,32 @@
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.hsnew file+22
@@ -0,0 +1,22 @@
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+-- |
19+-- Wrap a string in parentheses
20+--
21+parens :: String -> String
22+parens s = ('(':s) ++ ")"
src/Language/PureScript/Pretty/JS.hsnew file+259
@@ -0,0 +1,259 @@
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.AST
22+
23+import Data.List
24+import Data.Maybe (fromMaybe)
25+import qualified Control.Arrow as A
26+import Control.Arrow ((<+>))
27+import Control.PatternArrows
28+import Control.Applicative
29+import Control.Monad.State
30+
31+newtype PrinterState = PrinterState { indent :: Int } deriving (Show, Eq, Ord)
32+
33+-- |
34+-- Number of characters per identation level
35+--
36+blockIndent :: Int
37+blockIndent = 4
38+
39+-- |
40+-- Pretty print with a new indentation level
41+--
42+withIndent :: StateT PrinterState Maybe String -> StateT PrinterState Maybe String
43+withIndent action = do
44+ modify $ \st -> st { indent = indent st + blockIndent }
45+ result <- action
46+ modify $ \st -> st { indent = indent st - blockIndent }
47+ return result
48+
49+-- |
50+-- Get the current indentation level
51+--
52+currentIndent :: StateT PrinterState Maybe String
53+currentIndent = do
54+ current <- get
55+ return $ replicate (indent current) ' '
56+
57+literals :: Pattern PrinterState JS String
58+literals = mkPattern' match
59+ where
60+ match :: JS -> StateT PrinterState Maybe String
61+ match (JSNumericLiteral n) = return $ either show show n
62+ match (JSStringLiteral s) = return $ show s
63+ match (JSBooleanLiteral True) = return "true"
64+ match (JSBooleanLiteral False) = return "false"
65+ match (JSArrayLiteral xs) = fmap concat $ sequence
66+ [ return "[ "
67+ , fmap (intercalate ", ") $ forM xs prettyPrintJS'
68+ , return " ]"
69+ ]
70+ match (JSObjectLiteral []) = return "{}"
71+ match (JSObjectLiteral ps) = fmap concat $ sequence
72+ [ return "{\n"
73+ , withIndent $ do
74+ jss <- forM ps $ \(key, value) -> fmap ((key ++ ": ") ++) . prettyPrintJS' $ value
75+ indentString <- currentIndent
76+ return $ intercalate ", \n" $ map (indentString ++) jss
77+ , return "\n"
78+ , currentIndent
79+ , return "}"
80+ ]
81+ match (JSBlock sts) = fmap concat $ sequence
82+ [ return "{\n"
83+ , withIndent $ prettyStatements sts
84+ , return "\n"
85+ , currentIndent
86+ , return "}"
87+ ]
88+ match (JSVar ident) = return ident
89+ match (JSVariableIntroduction ident value) = fmap concat $ sequence
90+ [ return "var "
91+ , return ident
92+ , maybe (return "") (fmap (" = " ++) . prettyPrintJS') value
93+ ]
94+ match (JSAssignment target value) = fmap concat $ sequence
95+ [ prettyPrintJS' target
96+ , return " = "
97+ , prettyPrintJS' value
98+ ]
99+ match (JSWhile cond sts) = fmap concat $ sequence
100+ [ return "while ("
101+ , prettyPrintJS' cond
102+ , return ") "
103+ , prettyPrintJS' sts
104+ ]
105+ match (JSFor ident start end sts) = fmap concat $ sequence
106+ [ return $ "for (var " ++ ident ++ " = "
107+ , prettyPrintJS' start
108+ , return $ "; " ++ ident ++ " < "
109+ , prettyPrintJS' end
110+ , return $ "; " ++ ident ++ "++) "
111+ , prettyPrintJS' sts
112+ ]
113+ match (JSForIn ident obj sts) = fmap concat $ sequence
114+ [ return $ "for (var " ++ ident ++ " in "
115+ , prettyPrintJS' obj
116+ , return ") "
117+ , prettyPrintJS' sts
118+ ]
119+ match (JSIfElse cond thens elses) = fmap concat $ sequence
120+ [ return "if ("
121+ , prettyPrintJS' cond
122+ , return ") "
123+ , prettyPrintJS' thens
124+ , maybe (return "") (fmap (" else " ++) . prettyPrintJS') elses
125+ ]
126+ match (JSReturn value) = fmap concat $ sequence
127+ [ return "return "
128+ , prettyPrintJS' value
129+ ]
130+ match (JSThrow value) = fmap concat $ sequence
131+ [ return "throw "
132+ , prettyPrintJS' value
133+ ]
134+ match (JSBreak lbl) = return $ "break " ++ lbl
135+ match (JSContinue lbl) = return $ "continue " ++ lbl
136+ match (JSLabel lbl js) = fmap concat $ sequence
137+ [ return $ lbl ++ ": "
138+ , prettyPrintJS' js
139+ ]
140+ match (JSRaw js) = return js
141+ match _ = mzero
142+
143+conditional :: Pattern PrinterState JS ((JS, JS), JS)
144+conditional = mkPattern match
145+ where
146+ match (JSConditional cond th el) = Just ((th, el), cond)
147+ match _ = Nothing
148+
149+accessor :: Pattern PrinterState JS (String, JS)
150+accessor = mkPattern match
151+ where
152+ match (JSAccessor prop val) = Just (prop, val)
153+ match _ = Nothing
154+
155+indexer :: Pattern PrinterState JS (String, JS)
156+indexer = mkPattern' match
157+ where
158+ match (JSIndexer index val) = (,) <$> prettyPrintJS' index <*> pure val
159+ match _ = mzero
160+
161+lam :: Pattern PrinterState JS ((Maybe String, [String]), JS)
162+lam = mkPattern match
163+ where
164+ match (JSFunction name args ret) = Just ((name, args), ret)
165+ match _ = Nothing
166+
167+app :: Pattern PrinterState JS (String, JS)
168+app = mkPattern' match
169+ where
170+ match (JSApp val args) = do
171+ jss <- mapM prettyPrintJS' args
172+ return (intercalate ", " jss, val)
173+ match _ = mzero
174+
175+typeOf :: Pattern PrinterState JS ((), JS)
176+typeOf = mkPattern match
177+ where
178+ match (JSTypeOf val) = Just ((), val)
179+ match _ = Nothing
180+
181+unary :: UnaryOperator -> String -> Operator PrinterState JS String
182+unary op str = Wrap match (++)
183+ where
184+ match :: Pattern PrinterState JS (String, JS)
185+ match = mkPattern match'
186+ where
187+ match' (JSUnary op' val) | op' == op = Just (str, val)
188+ match' _ = Nothing
189+
190+binary :: BinaryOperator -> String -> Operator PrinterState JS String
191+binary op str = AssocR match (\v1 v2 -> v1 ++ " " ++ str ++ " " ++ v2)
192+ where
193+ match :: Pattern PrinterState JS (JS, JS)
194+ match = mkPattern match'
195+ where
196+ match' (JSBinary op' v1 v2) | op' == op = Just (v1, v2)
197+ match' _ = Nothing
198+
199+prettyStatements :: [JS] -> StateT PrinterState Maybe String
200+prettyStatements sts = do
201+ jss <- forM sts prettyPrintJS'
202+ indentString <- currentIndent
203+ return $ intercalate "\n" $ map ((++ ";") . (indentString ++)) jss
204+
205+-- |
206+-- Generate a pretty-printed string representing a Javascript expression
207+--
208+prettyPrintJS1 :: JS -> String
209+prettyPrintJS1 = fromMaybe (error "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyPrintJS'
210+
211+-- |
212+-- Generate a pretty-printed string representing a collection of Javascript expressions at the same indentation level
213+--
214+prettyPrintJS :: [JS] -> String
215+prettyPrintJS = fromMaybe (error "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyStatements
216+
217+-- |
218+-- Generate an indented, pretty-printed string representing a Javascript expression
219+--
220+prettyPrintJS' :: JS -> StateT PrinterState Maybe String
221+prettyPrintJS' = A.runKleisli $ runPattern matchValue
222+ where
223+ matchValue :: Pattern PrinterState JS String
224+ matchValue = buildPrettyPrinter operators (literals <+> fmap parens matchValue)
225+ operators :: OperatorTable PrinterState JS String
226+ operators =
227+ OperatorTable [ [ Wrap accessor $ \prop val -> val ++ "." ++ prop ]
228+ , [ Wrap indexer $ \index val -> val ++ "[" ++ index ++ "]" ]
229+ , [ Wrap app $ \args val -> val ++ "(" ++ args ++ ")" ]
230+ , [ Wrap lam $ \(name, args) ret -> "function "
231+ ++ fromMaybe "" name
232+ ++ "(" ++ intercalate ", " args ++ ") "
233+ ++ ret ]
234+ , [ Wrap conditional $ \(th, el) cond -> cond ++ " ? " ++ prettyPrintJS1 th ++ " : " ++ prettyPrintJS1 el ]
235+ , [ binary LessThan "<" ]
236+ , [ binary LessThanOrEqualTo "<=" ]
237+ , [ binary GreaterThan ">" ]
238+ , [ binary GreaterThanOrEqualTo ">=" ]
239+ , [ Wrap typeOf $ \_ s -> "typeof " ++ s ]
240+ , [ unary Not "!" ]
241+ , [ unary BitwiseNot "~" ]
242+ , [ unary Negate "-" ]
243+ , [ unary Positive "+" ]
244+ , [ binary Multiply "*" ]
245+ , [ binary Divide "/" ]
246+ , [ binary Modulus "%" ]
247+ , [ binary Add "+" ]
248+ , [ binary Subtract "-" ]
249+ , [ binary ShiftLeft "<<" ]
250+ , [ binary ShiftRight ">>" ]
251+ , [ binary ZeroFillShiftRight ">>>" ]
252+ , [ binary EqualTo "===" ]
253+ , [ binary NotEqualTo "!==" ]
254+ , [ binary BitwiseAnd "&" ]
255+ , [ binary BitwiseXor "^" ]
256+ , [ binary BitwiseOr "|" ]
257+ , [ binary And "&&" ]
258+ , [ binary Or "||" ]
259+ ]
src/Language/PureScript/Pretty/Kinds.hsnew file+60
@@ -0,0 +1,60 @@
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.hsnew file+122
@@ -0,0 +1,122 @@
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 (Object row) = Just $ "{ " ++ prettyPrintRow row ++ " }"
38+ match (TypeVar var) = Just var
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 (TUnknown (Unknown u)) = " | u" ++ show u
60+ tailToPs (TypeVar var) = " | " ++ var
61+ tailToPs (Skolem s _) = " | s" ++ show s
62+ tailToPs _ = error "Invalid row tail"
63+ toList :: [(String, Type)] -> Type -> ([(String, Type)], Type)
64+ toList tys (RCons name ty row) = toList ((name, ty):tys) row
65+ toList tys r = (tys, r)
66+
67+typeApp :: Pattern () Type (Type, Type)
68+typeApp = mkPattern match
69+ where
70+ match (TypeApp f x) = Just (f, x)
71+ match _ = Nothing
72+
73+appliedFunction :: Pattern () Type (Type, Type)
74+appliedFunction = mkPattern match
75+ where
76+ match (PrettyPrintFunction arg ret) = Just (arg, ret)
77+ match _ = Nothing
78+
79+insertPlaceholders :: Type -> Type
80+insertPlaceholders = everywhere' (mkT convertForAlls) . everywhere (mkT convert)
81+ where
82+ convert (TypeApp (TypeApp f arg) ret) | f == tyFunction = PrettyPrintFunction arg ret
83+ convert (TypeApp a el) | a == tyArray = PrettyPrintArray el
84+ convert other = other
85+ convertForAlls (ForAll ident ty _) = go [ident] ty
86+ where
87+ go idents (ForAll ident' ty' _) = go (ident' : idents) ty'
88+ go idents other = PrettyPrintForAll idents other
89+ convertForAlls other = other
90+
91+matchTypeAtom :: Pattern () Type String
92+matchTypeAtom = typeLiterals <+> fmap parens matchType
93+
94+matchType :: Pattern () Type String
95+matchType = buildPrettyPrinter operators matchTypeAtom
96+ where
97+ operators :: OperatorTable () Type String
98+ operators =
99+ OperatorTable [ [ AssocL typeApp $ \f x -> f ++ " " ++ x ]
100+ , [ AssocR appliedFunction $ \arg ret -> arg ++ " -> " ++ ret
101+ ]
102+ , [ Wrap forall_ $ \idents ty -> "forall " ++ unwords idents ++ ". " ++ ty ]
103+ ]
104+
105+forall_ :: Pattern () Type ([String], Type)
106+forall_ = mkPattern match
107+ where
108+ match (PrettyPrintForAll idents ty) = Just (idents, ty)
109+ match _ = Nothing
110+
111+-- |
112+-- Generate a pretty-printed string representing a Type, as it should appear inside parentheses
113+--
114+prettyPrintTypeAtom :: Type -> String
115+prettyPrintTypeAtom = fromMaybe (error "Incomplete pattern") . pattern matchTypeAtom () . insertPlaceholders
116+
117+
118+-- |
119+-- Generate a pretty-printed string representing a Type
120+--
121+prettyPrintType :: Type -> String
122+prettyPrintType = fromMaybe (error "Incomplete pattern") . pattern matchType () . insertPlaceholders
src/Language/PureScript/Pretty/Values.hsnew file+150
@@ -0,0 +1,150 @@
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+import Control.Arrow ((<+>))
24+import Control.PatternArrows
25+
26+import Language.PureScript.Types
27+import Language.PureScript.Values
28+import Language.PureScript.Pretty.Common
29+import Language.PureScript.Pretty.Types
30+
31+literals :: Pattern () Value String
32+literals = mkPattern match
33+ where
34+ match (NumericLiteral n) = Just $ either show show n
35+ match (StringLiteral s) = Just $ show s
36+ match (BooleanLiteral True) = Just "true"
37+ match (BooleanLiteral False) = Just "false"
38+ match (ArrayLiteral xs) = Just $ "[" ++ intercalate ", " (map prettyPrintValue xs) ++ "]"
39+ match (ObjectLiteral ps) = Just $ "{" ++ intercalate ", " (map (uncurry prettyPrintObjectProperty) ps) ++ "}"
40+ match (Constructor name) = Just $ show name
41+ match (Case values binders) = Just $ "case " ++ unwords (map prettyPrintValue values) ++
42+ " of { " ++ intercalate " ; " (map prettyPrintCaseAlternative binders) ++ " }"
43+ match (Var ident) = Just $ show ident
44+ match (Do els) = Just $ " do { " ++ intercalate "; " (map prettyPrintDoNotationElement els) ++ " }"
45+ match (TypeClassDictionary _ _) = error "Type class dictionary was not replaced"
46+ match _ = Nothing
47+
48+prettyPrintCaseAlternative :: CaseAlternative -> String
49+prettyPrintCaseAlternative (CaseAlternative binders grd val) =
50+ "(" ++ intercalate ", " (map prettyPrintBinder binders) ++ ") " ++
51+ maybe "" (("| " ++) . prettyPrintValue) grd ++ " -> " ++ prettyPrintValue val
52+
53+ifThenElse :: Pattern () Value ((Value, Value), Value)
54+ifThenElse = mkPattern match
55+ where
56+ match (IfThenElse cond th el) = Just ((th, el), cond)
57+ match _ = Nothing
58+
59+accessor :: Pattern () Value (String, Value)
60+accessor = mkPattern match
61+ where
62+ match (Accessor prop val) = Just (prop, val)
63+ match _ = Nothing
64+
65+objectUpdate :: Pattern () Value ([String], Value)
66+objectUpdate = mkPattern match
67+ where
68+ match (ObjectUpdate o ps) = Just (flip map ps $ \(key, val) -> key ++ " = " ++ prettyPrintValue val, o)
69+ match _ = Nothing
70+
71+app :: Pattern () Value (String, Value)
72+app = mkPattern match
73+ where
74+ match (App val arg) = Just (prettyPrintValue arg, val)
75+ match _ = Nothing
76+
77+lam :: Pattern () Value (String, Value)
78+lam = mkPattern match
79+ where
80+ match (Abs (Left arg) val) = Just (show arg, val)
81+ match _ = Nothing
82+
83+typed :: Pattern () Value (Type, Value)
84+typed = mkPattern match
85+ where
86+ match (TypedValue _ val ty) = Just (ty, val)
87+ match _ = Nothing
88+
89+prettyPrintDoNotationElement :: DoNotationElement -> String
90+prettyPrintDoNotationElement (DoNotationValue val) = prettyPrintValue val
91+prettyPrintDoNotationElement (DoNotationBind binder val) = prettyPrintBinder binder ++ " <- " ++ prettyPrintValue val
92+prettyPrintDoNotationElement (DoNotationLet binder val) = "let " ++ prettyPrintBinder binder ++ " = " ++ prettyPrintValue val
93+
94+-- |
95+-- Generate a pretty-printed string representing a Value
96+--
97+prettyPrintValue :: Value -> String
98+prettyPrintValue = fromMaybe (error "Incomplete pattern") . pattern matchValue ()
99+ where
100+ matchValue :: Pattern () Value String
101+ matchValue = buildPrettyPrinter operators (literals <+> fmap parens matchValue)
102+ operators :: OperatorTable () Value String
103+ operators =
104+ OperatorTable [ [ Wrap accessor $ \prop val -> val ++ "." ++ prop ]
105+ , [ Wrap objectUpdate $ \ps val -> val ++ "{ " ++ intercalate ", " ps ++ " }" ]
106+ , [ Wrap app $ \arg val -> val ++ "(" ++ arg ++ ")" ]
107+ , [ Split lam $ \arg val -> "\\" ++ arg ++ " -> " ++ prettyPrintValue val ]
108+ , [ Wrap ifThenElse $ \(th, el) cond -> "if " ++ cond ++ " then " ++ prettyPrintValue th ++ " else " ++ prettyPrintValue el ]
109+ , [ Wrap typed $ \ty val -> val ++ " :: " ++ prettyPrintType ty ]
110+ ]
111+
112+prettyPrintBinderAtom :: Pattern () Binder String
113+prettyPrintBinderAtom = mkPattern match
114+ where
115+ match :: Binder -> Maybe String
116+ match NullBinder = Just "_"
117+ match (StringBinder str) = Just $ show str
118+ match (NumberBinder num) = Just $ either show show num
119+ match (BooleanBinder True) = Just "true"
120+ match (BooleanBinder False) = Just "false"
121+ match (VarBinder ident) = Just $ show ident
122+ match (ConstructorBinder ctor args) = Just $ show ctor ++ " " ++ unwords (map (parens . prettyPrintBinder) args)
123+ match (ObjectBinder bs) = Just $ "{ " ++ intercalate ", " (map (uncurry prettyPrintObjectPropertyBinder) bs) ++ " }"
124+ match (ArrayBinder bs) = Just $ "[ " ++ intercalate ", " (map prettyPrintBinder bs) ++ " ]"
125+ match (NamedBinder ident binder) = Just $ show ident ++ "@" ++ prettyPrintBinder binder
126+ match _ = Nothing
127+
128+-- |
129+-- Generate a pretty-printed string representing a Binder
130+--
131+prettyPrintBinder :: Binder -> String
132+prettyPrintBinder = fromMaybe (error "Incomplete pattern") . pattern matchBinder ()
133+ where
134+ matchBinder :: Pattern () Binder String
135+ matchBinder = buildPrettyPrinter operators (prettyPrintBinderAtom <+> fmap parens matchBinder)
136+ operators :: OperatorTable () Binder String
137+ operators =
138+ OperatorTable [ [ AssocR matchConsBinder (\b1 b2 -> b1 ++ " : " ++ b2) ] ]
139+
140+matchConsBinder :: Pattern () Binder (Binder, Binder)
141+matchConsBinder = mkPattern match'
142+ where
143+ match' (ConsBinder b1 b2) = Just (b1, b2)
144+ match' _ = Nothing
145+
146+prettyPrintObjectPropertyBinder :: String -> Binder -> String
147+prettyPrintObjectPropertyBinder key binder = key ++ ": " ++ prettyPrintBinder binder
148+
149+prettyPrintObjectProperty :: String -> Value -> String
150+prettyPrintObjectProperty key value = key ++ ": " ++ prettyPrintValue value
src/Language/PureScript/Scope.hsnew file+62
@@ -0,0 +1,62 @@
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.Values
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.hsnew file+59
@@ -0,0 +1,59 @@
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+import Control.Arrow ((>>>))
20+
21+import Language.PureScript.Declarations
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.Let as S
30+import Language.PureScript.Sugar.Names as S
31+
32+-- |
33+-- The desugaring pipeline proceeds as follows:
34+--
35+-- * Desugar let bindings
36+--
37+-- * Introduce type synonyms for type class dictionaries
38+--
39+-- * Rebracket user-defined binary operators
40+--
41+-- * Desugar do-notation using the @Prelude.Monad@ type class
42+--
43+-- * Desugar top-level case declarations into explicit case expressions
44+--
45+-- * Desugar type declarations into value declarations with explicit type annotations
46+--
47+-- * Group mutually recursive value and data declarations into binding groups.
48+--
49+-- * Qualify any unqualified names and types
50+--
51+desugar :: [Module] -> Either String [Module]
52+desugar = rebracket
53+ >=> desugarDo
54+ >=> desugarLetBindings
55+ >>> desugarCasesModule
56+ >=> desugarImports
57+ >=> desugarTypeDeclarationsModule
58+ >=> desugarTypeClasses
59+ >=> createBindingGroupsModule
src/Language/PureScript/Sugar/BindingGroups.hsnew file+128
@@ -0,0 +1,128 @@
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.List (nub, intersect)
28+import Data.Maybe (mapMaybe)
29+import Control.Applicative ((<$>), (<*>), pure)
30+
31+import Language.PureScript.Declarations
32+import Language.PureScript.Names
33+import Language.PureScript.Values
34+import Language.PureScript.Types
35+import Language.PureScript.Environment
36+
37+-- |
38+-- Replace all sets of mutually-recursive declarations in a module with binding groups
39+--
40+createBindingGroupsModule :: [Module] -> Either String [Module]
41+createBindingGroupsModule = mapM $ \(Module name ds exps) -> Module name <$> createBindingGroups name ds <*> pure exps
42+
43+-- |
44+-- Collapse all binding groups in a module to individual declarations
45+--
46+collapseBindingGroupsModule :: [Module] -> [Module]
47+collapseBindingGroupsModule = map $ \(Module name ds exps) -> Module name (collapseBindingGroups ds) exps
48+
49+-- |
50+-- Replace all sets of mutually-recursive declarations with binding groups
51+--
52+createBindingGroups :: ModuleName -> [Declaration] -> Either String [Declaration]
53+createBindingGroups moduleName ds = do
54+ let values = filter isValueDecl ds
55+ dataDecls = filter isDataDecl ds
56+ allProperNames = map getProperName dataDecls
57+ dataVerts = map (\d -> (d, getProperName d, usedProperNames moduleName d `intersect` allProperNames)) dataDecls
58+ dataBindingGroupDecls <- mapM toDataBindingGroup $ stronglyConnComp dataVerts
59+ let allIdents = map getIdent values
60+ valueVerts = map (\d -> (d, getIdent d, usedIdents moduleName d `intersect` allIdents)) values
61+ bindingGroupDecls = map toBindingGroup $ stronglyConnComp valueVerts
62+ return $ filter isImportDecl ds ++
63+ filter isExternDataDecl ds ++
64+ filter isExternInstanceDecl ds ++
65+ dataBindingGroupDecls ++
66+ filter isTypeClassDeclaration ds ++
67+ filter isFixityDecl ds ++
68+ filter isExternDecl ds ++
69+ bindingGroupDecls
70+
71+-- |
72+-- Collapse all binding groups to individual declarations
73+--
74+collapseBindingGroups :: [Declaration] -> [Declaration]
75+collapseBindingGroups = concatMap go
76+ where
77+ go (DataBindingGroupDeclaration ds) = ds
78+ go (BindingGroupDeclaration ds) = map (\(ident, nameKind, val) -> ValueDeclaration ident nameKind [] Nothing val) ds
79+ go other = [other]
80+
81+usedIdents :: (Data d) => ModuleName -> d -> [Ident]
82+usedIdents moduleName = nub . everything (++) (mkQ [] usedNames)
83+ where
84+ usedNames :: Value -> [Ident]
85+ usedNames (Var (Qualified Nothing name)) = [name]
86+ usedNames (Var (Qualified (Just moduleName') name)) | moduleName == moduleName' = [name]
87+ usedNames _ = []
88+
89+usedProperNames :: (Data d) => ModuleName -> d -> [ProperName]
90+usedProperNames moduleName = nub . everything (++) (mkQ [] usedNames)
91+ where
92+ usedNames :: Type -> [ProperName]
93+ usedNames (ConstrainedType constraints _) = flip mapMaybe constraints $ \qual ->
94+ case qual of
95+ (Qualified (Just moduleName') name, _) | moduleName == moduleName' -> Just name
96+ _ -> Nothing
97+ usedNames (TypeConstructor (Qualified (Just moduleName') name)) | moduleName == moduleName' = [name]
98+ usedNames _ = []
99+
100+getIdent :: Declaration -> Ident
101+getIdent (ValueDeclaration ident _ _ _ _) = ident
102+getIdent _ = error "Expected ValueDeclaration"
103+
104+getProperName :: Declaration -> ProperName
105+getProperName (DataDeclaration pn _ _) = pn
106+getProperName (TypeSynonymDeclaration pn _ _) = pn
107+getProperName _ = error "Expected DataDeclaration"
108+
109+toBindingGroup :: SCC Declaration -> Declaration
110+toBindingGroup (AcyclicSCC d) = d
111+toBindingGroup (CyclicSCC [d]) = d
112+toBindingGroup (CyclicSCC ds') = BindingGroupDeclaration $ map fromValueDecl ds'
113+
114+toDataBindingGroup :: SCC Declaration -> Either String Declaration
115+toDataBindingGroup (AcyclicSCC d) = return d
116+toDataBindingGroup (CyclicSCC [TypeSynonymDeclaration pn _ _]) = Left $ "Cycle in type synonym " ++ show pn
117+toDataBindingGroup (CyclicSCC [d]) = return d
118+toDataBindingGroup (CyclicSCC ds')
119+ | all isTypeSynonym ds' = Left "Cycle in type synonyms"
120+ | otherwise = return $ DataBindingGroupDeclaration ds'
121+ where
122+ isTypeSynonym TypeSynonymDeclaration{} = True
123+ isTypeSynonym _ = False
124+
125+fromValueDecl :: Declaration -> (Ident, NameKind, Value)
126+fromValueDecl (ValueDeclaration ident nameKind [] Nothing val) = (ident, nameKind, val)
127+fromValueDecl ValueDeclaration{} = error "Binders should have been desugared"
128+fromValueDecl _ = error "Expected ValueDeclaration"
src/Language/PureScript/Sugar/CaseDeclarations.hsnew file+97
@@ -0,0 +1,97 @@
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.List (groupBy)
23+import Data.Generics (mkT, everywhere)
24+
25+import Control.Applicative
26+import Control.Monad ((<=<), forM, join, unless)
27+import Control.Monad.Error.Class
28+
29+import Language.PureScript.Names
30+import Language.PureScript.Values
31+import Language.PureScript.Declarations
32+import Language.PureScript.Scope
33+import Language.PureScript.Environment
34+
35+-- |
36+-- Replace all top-level binders in a module with case expressions.
37+--
38+desugarCasesModule :: [Module] -> Either String [Module]
39+desugarCasesModule ms = forM ms $ \(Module name ds exps) -> Module name <$> (desugarCases . desugarAbs $ ds) <*> pure exps
40+
41+desugarAbs :: [Declaration] -> [Declaration]
42+desugarAbs = everywhere (mkT replace)
43+ where
44+ replace (Abs (Right binder) val) =
45+ let
46+ ident = head $ unusedNames (binder, val)
47+ in
48+ Abs (Left ident) $ Case [Var (Qualified Nothing ident)] [CaseAlternative [binder] Nothing val]
49+ replace other = other
50+
51+-- |
52+-- Replace all top-level binders with case expressions.
53+--
54+desugarCases :: [Declaration] -> Either String [Declaration]
55+desugarCases = desugarRest <=< fmap join . mapM toDecls . groupBy inSameGroup
56+ where
57+ desugarRest :: [Declaration] -> Either String [Declaration]
58+ desugarRest (TypeInstanceDeclaration name constraints className tys ds : rest) =
59+ (:) <$> (TypeInstanceDeclaration name constraints className tys <$> desugarCases ds) <*> desugarRest rest
60+ desugarRest (d : ds) = (:) d <$> desugarRest ds
61+ desugarRest [] = pure []
62+
63+inSameGroup :: Declaration -> Declaration -> Bool
64+inSameGroup (ValueDeclaration ident1 _ _ _ _) (ValueDeclaration ident2 _ _ _ _) = ident1 == ident2
65+inSameGroup _ _ = False
66+
67+toDecls :: [Declaration] -> Either String [Declaration]
68+toDecls [ValueDeclaration ident nameKind bs Nothing val] | all isVarBinder bs = do
69+ let args = map (\(VarBinder arg) -> arg) bs
70+ body = foldr (Abs . Left) val args
71+ return [ValueDeclaration ident nameKind [] Nothing body]
72+toDecls ds@(ValueDeclaration ident _ bs _ _ : _) = do
73+ let tuples = map toTuple ds
74+ unless (all ((== length bs) . length . fst) tuples) $
75+ throwError $ "Argument list lengths differ in declaration " ++ show ident
76+ return [makeCaseDeclaration ident tuples]
77+toDecls ds = return ds
78+
79+isVarBinder :: Binder -> Bool
80+isVarBinder (VarBinder _) = True
81+isVarBinder _ = False
82+
83+toTuple :: Declaration -> ([Binder], (Maybe Guard, Value))
84+toTuple (ValueDeclaration _ _ bs g val) = (bs, (g, val))
85+toTuple _ = error "Not a value declaration"
86+
87+makeCaseDeclaration :: Ident -> [([Binder], (Maybe Guard, Value))] -> Declaration
88+makeCaseDeclaration ident alternatives =
89+ let
90+ argPattern = length . fst . head $ alternatives
91+ args = take argPattern $ unusedNames (ident, alternatives)
92+ vars = map (Var . Qualified Nothing) args
93+ binders = [ CaseAlternative bs g val | (bs, (g, val)) <- alternatives ]
94+ value = foldr (Abs . Left) (Case vars binders) args
95+ in
96+ ValueDeclaration ident Value [] Nothing value
97+
src/Language/PureScript/Sugar/DoNotation.hsnew file+62
@@ -0,0 +1,62 @@
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.Values
25+import Language.PureScript.Names
26+import Language.PureScript.Scope
27+
28+import qualified Language.PureScript.Constants as C
29+
30+-- |
31+-- Replace all @DoNotationBind@ and @DoNotationValue@ constructors with applications of the Prelude.(>>=) function,
32+-- and all @DoNotationLet@ constructors with let expressions.
33+--
34+desugarDo :: (Data d) => d -> Either String d
35+desugarDo = everywhereM (mkM replace)
36+ where
37+ prelude :: ModuleName
38+ prelude = ModuleName [ProperName C.prelude]
39+ bind :: Value
40+ bind = Var (Qualified (Just prelude) (Op (C.>>=)))
41+ replace :: Value -> Either String Value
42+ replace (Do els) = go els
43+ replace other = return other
44+ go :: [DoNotationElement] -> Either String Value
45+ go [] = error "The impossible happened in desugarDo"
46+ go [DoNotationValue val] = return val
47+ go (DoNotationValue val : rest) = do
48+ rest' <- go rest
49+ return $ App (App bind val) (Abs (Left (Ident "_")) rest')
50+ go [DoNotationBind _ _] = Left "Bind statement cannot be the last statement in a do block"
51+ go (DoNotationBind NullBinder val : rest) = go (DoNotationValue val : rest)
52+ go (DoNotationBind (VarBinder ident) val : rest) = do
53+ rest' <- go rest
54+ return $ App (App bind val) (Abs (Left ident) rest')
55+ go (DoNotationBind binder val : rest) = do
56+ rest' <- go rest
57+ let ident = head $ unusedNames rest'
58+ return $ App (App bind val) (Abs (Left ident) (Case [Var (Qualified Nothing ident)] [CaseAlternative [binder] Nothing rest']))
59+ go [DoNotationLet _ _] = Left "Let statement cannot be the last statement in a do block"
60+ go (DoNotationLet binder val : rest) = do
61+ rest' <- go rest
62+ return $ Case [val] [CaseAlternative [binder] Nothing rest']
src/Language/PureScript/Sugar/Let.hsnew file+34
@@ -0,0 +1,34 @@
1+-----------------------------------------------------------------------------
2+--
3+-- Module : Language.PureScript.Sugar.Let
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+-- This module implements the desugaring pass which turns let bindings into function applications.
13+--
14+-----------------------------------------------------------------------------
15+
16+module Language.PureScript.Sugar.Let (
17+ desugarLetBindings
18+) where
19+
20+import Data.Generics (mkT, everywhere)
21+
22+import Language.PureScript.Values
23+import Language.PureScript.Declarations
24+
25+-- |
26+-- Turn let bindings into function applications
27+--
28+desugarLetBindings :: [Module] -> [Module]
29+desugarLetBindings = everywhere (mkT go)
30+ where
31+ go (Let (Left (VarBinder ident)) value result) = App (Abs (Left ident) result) value
32+ go (Let (Left binder) value result) = Case [value] [CaseAlternative [binder] Nothing result]
33+ go (Let (Right (ident, binders)) value result) = App (Abs (Left ident) result) (foldr Abs value binders)
34+ go other = other
src/Language/PureScript/Sugar/Names.hsnew file+420
@@ -0,0 +1,420 @@
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.Maybe (fromMaybe)
20+import Data.Generics (extM, mkM, everywhereM)
21+import Data.Generics.Extras (mkS, extS, everywhereWithContextM')
22+
23+import Control.Applicative (Applicative(..), (<$>), (<*>))
24+import Control.Monad.Error
25+
26+import qualified Data.Map as M
27+
28+import Language.PureScript.Declarations
29+import Language.PureScript.Names
30+import Language.PureScript.Types
31+import Language.PureScript.Values
32+import Language.PureScript.Environment
33+
34+-- |
35+-- The global export environment - every declaration exported from every module.
36+--
37+type ExportEnvironment = M.Map ModuleName Exports
38+
39+-- |
40+-- The exported declarations from a module.
41+--
42+data Exports = Exports
43+ -- |
44+ -- The types exported from each module
45+ --
46+ { exportedTypes :: [(ProperName, [ProperName])]
47+ -- |
48+ -- The classes exported from each module
49+ --
50+ , exportedTypeClasses :: [ProperName]
51+ -- |
52+ -- The values exported from each module
53+ , exportedValues :: [Ident]
54+ --
55+ } deriving (Show)
56+
57+-- |
58+-- An imported environment for a particular module. This also contains the module's own members.
59+--
60+data ImportEnvironment = ImportEnvironment
61+ -- |
62+ -- Local names for types within a module mapped to to their qualified names
63+ --
64+ { importedTypes :: M.Map ProperName (Qualified ProperName)
65+ -- |
66+ -- Local names for data constructors within a module mapped to to their qualified names
67+ --
68+ , importedDataConstructors :: M.Map ProperName (Qualified ProperName)
69+ -- |
70+ -- Local names for classes within a module mapped to to their qualified names
71+ --
72+ , importedTypeClasses :: M.Map ProperName (Qualified ProperName)
73+ -- |
74+ -- Local names for values within a module mapped to to their qualified names
75+ --
76+ , importedValues :: M.Map Ident (Qualified Ident)
77+ } deriving (Show)
78+
79+-- |
80+-- Updates the exports for a module from the global environment. If the module was not previously
81+-- present in the global environment, it is created.
82+--
83+updateExportedModule :: ExportEnvironment -> ModuleName -> (Exports -> Either String Exports) -> Either String ExportEnvironment
84+updateExportedModule env mn update = do
85+ let exports = fromMaybe (error "Module was undefined in updateExportedModule") $ mn `M.lookup` env
86+ exports' <- update exports
87+ return $ M.insert mn exports' env
88+
89+-- |
90+-- Adds an empty module to an ExportEnvironment.
91+--
92+addEmptyModule :: ExportEnvironment -> ModuleName -> Either String ExportEnvironment
93+addEmptyModule env name =
94+ if name `M.member` env
95+ then throwError $ "Module '" ++ show name ++ "' has been defined more than once"
96+ else return $ M.insert name (Exports [] [] []) env
97+
98+-- |
99+-- Adds a type belonging to a module to the export environment.
100+--
101+addType :: ExportEnvironment -> ModuleName -> ProperName -> [ProperName] -> Either String ExportEnvironment
102+addType env mn name dctors = updateExportedModule env mn $ \m -> do
103+ types' <- addExport (exportedTypes m) (name, dctors)
104+ return $ m { exportedTypes = types' }
105+
106+-- |
107+-- Adds a class to the export environment.
108+--
109+addTypeClass :: ExportEnvironment -> ModuleName -> ProperName -> Either String ExportEnvironment
110+addTypeClass env mn name = updateExportedModule env mn $ \m -> do
111+ classes <- addExport (exportedTypeClasses m) name
112+ return $ m { exportedTypeClasses = classes }
113+
114+-- |
115+-- Adds a class to the export environment.
116+--
117+addValue :: ExportEnvironment -> ModuleName -> Ident -> Either String ExportEnvironment
118+addValue env mn name = updateExportedModule env mn $ \m -> do
119+ values <- addExport (exportedValues m) name
120+ return $ m { exportedValues = values }
121+
122+-- |
123+-- Adds an entry to a list of exports unless it is already present, in which case an error is
124+-- returned.
125+--
126+addExport :: (Eq a, Show a) => [a] -> a -> Either String [a]
127+addExport exports name =
128+ if name `elem` exports
129+ then throwError $ "Multiple definitions for '" ++ show name ++ "'"
130+ else return $ name : exports
131+
132+-- |
133+-- Replaces all local names with qualified names within a set of modules.
134+--
135+desugarImports :: [Module] -> Either String [Module]
136+desugarImports modules = do
137+ unfilteredExports <- findExports modules
138+ exports <- foldM filterModuleExports unfilteredExports modules
139+ mapM (renameInModule' unfilteredExports exports) modules
140+ where
141+
142+ -- Filters the exports for a module in the global exports environment so that only explicitly
143+ -- exported members remain. If the module does not explicitly export anything, everything is
144+ -- exported.
145+ filterModuleExports :: ExportEnvironment -> Module -> Either String ExportEnvironment
146+ filterModuleExports env (Module mn _ (Just exps)) = filterExports mn exps env
147+ filterModuleExports env _ = return env
148+
149+ -- Rename and check all the names within a module. We tweak the global exports environment so
150+ -- the module has access to an unfiltered list of its own members.
151+ renameInModule' :: ExportEnvironment -> ExportEnvironment -> Module -> Either String Module
152+ renameInModule' unfilteredExports exports m@(Module mn _ _) = rethrowForModule m $ do
153+ let env = M.update (\_ -> M.lookup mn unfilteredExports) mn exports
154+ let exps = fromMaybe (error "Module is missing in renameInModule'") $ M.lookup mn exports
155+ imports <- resolveImports env m
156+ renameInModule imports env (elaborateExports exps m)
157+
158+-- |
159+-- Rethrow an error with the name of the current module in the case of a failure
160+--
161+rethrowForModule :: Module -> Either String a -> Either String a
162+rethrowForModule (Module mn _ _) = flip catchError $ \e -> throwError ("Error in module '" ++ show mn ++ "':\n" ++ e)
163+
164+-- |
165+-- Make all exports for a module explicit. This may still effect modules that have an exports list,
166+-- as it will also make all data constructor exports explicit.
167+--
168+elaborateExports :: Exports -> Module -> Module
169+elaborateExports exps (Module mn decls _) = Module mn decls (Just $
170+ map (\(ctor, dctors) -> TypeRef ctor (Just dctors)) (exportedTypes exps) ++
171+ map TypeClassRef (exportedTypeClasses exps) ++
172+ map ValueRef (exportedValues exps))
173+
174+-- |
175+-- Replaces all local names with qualified names within a module and checks that all existing
176+-- qualified names are valid.
177+--
178+renameInModule :: ImportEnvironment -> ExportEnvironment -> Module -> Either String Module
179+renameInModule imports exports (Module mn decls exps) =
180+ Module mn <$> (mapM updateDecl decls >>= everywhereM (mkM updateType `extM` updateValue `extM` updateBinder `extM` updateVars)) <*> pure exps
181+ where
182+ updateDecl (TypeInstanceDeclaration name cs cn ts ds) =
183+ TypeInstanceDeclaration name <$> updateConstraints cs <*> updateClassName cn <*> pure ts <*> pure ds
184+ updateDecl (ExternInstanceDeclaration name cs cn ts) =
185+ ExternInstanceDeclaration name <$> updateConstraints cs <*> updateClassName cn <*> pure ts
186+ updateDecl d = return d
187+
188+ updateVars :: Declaration -> Either String Declaration
189+ updateVars (ValueDeclaration name nameKind [] Nothing val) =
190+ ValueDeclaration name nameKind [] Nothing <$> everywhereWithContextM' [] (mkS bindFunctionArgs `extS` bindBinders) val
191+ where
192+ bindFunctionArgs bound (Abs (Left arg) val') = return (arg : bound, Abs (Left arg) val')
193+ bindFunctionArgs bound (Var name'@(Qualified Nothing ident)) | ident `notElem` bound = (,) bound <$> (Var <$> updateValueName name')
194+ bindFunctionArgs bound (Var name'@(Qualified (Just _) _)) = (,) bound <$> (Var <$> updateValueName name')
195+ bindFunctionArgs bound other = return (bound, other)
196+ bindBinders :: [Ident] -> CaseAlternative -> Either String ([Ident], CaseAlternative)
197+ bindBinders bound c@(CaseAlternative bs _ _) = return (binderNames bs ++ bound, c)
198+ updateVars (ValueDeclaration name _ _ _ _) = error $ "Binders should have been desugared in " ++ show name
199+ updateVars other = return other
200+ updateValue (Constructor name) = Constructor <$> updateDataConstructorName name
201+ updateValue v = return v
202+ updateBinder (ConstructorBinder name b) = ConstructorBinder <$> updateDataConstructorName name <*> pure b
203+ updateBinder v = return v
204+ updateType (TypeConstructor name) = TypeConstructor <$> updateTypeName name
205+ updateType (SaturatedTypeSynonym name tys) = SaturatedTypeSynonym <$> updateTypeName name <*> mapM updateType tys
206+ updateType (ConstrainedType cs t) = ConstrainedType <$> updateConstraints cs <*> pure t
207+ updateType t = return t
208+ updateConstraints = mapM (\(name, ts) -> (,) <$> updateClassName name <*> pure ts)
209+
210+ updateTypeName (Qualified Nothing name) = update "type" importedTypes name
211+ updateTypeName (Qualified (Just mn') name) = do
212+ modExports <- getExports mn'
213+ case name `lookup` exportedTypes modExports of
214+ Nothing -> throwError $ "Unknown type '" ++ show (Qualified (Just mn') name) ++ "'"
215+ _ -> return $ Qualified (Just mn') name
216+
217+ updateDataConstructorName (Qualified Nothing name) = update "data constructor" importedDataConstructors name
218+ updateDataConstructorName (Qualified (Just mn') name) = do
219+ modExports <- getExports mn'
220+ let allDcons = join $ snd `map` exportedTypes modExports
221+ if name `elem` allDcons
222+ then return $ Qualified (Just mn') name
223+ else throwError $ "Unknown data constructor '" ++ show (Qualified (Just mn') name) ++ "'"
224+
225+ updateClassName (Qualified Nothing name) = update "type class" importedTypeClasses name
226+ updateClassName (Qualified (Just mn') name) = check "type class" exportedTypeClasses mn' name
227+
228+ updateValueName (Qualified Nothing name) = update "value" importedValues name
229+ updateValueName (Qualified (Just mn') name) = check "value" exportedValues mn' name
230+
231+ -- Replace an unqualified name with a qualified
232+ update :: (Ord a, Show a) => String -> (ImportEnvironment -> M.Map a (Qualified a)) -> a -> Either String (Qualified a)
233+ update t get name = maybe (throwError $ "Unknown " ++ t ++ " '" ++ show name ++ "'") return $ M.lookup name (get imports)
234+
235+ -- Check that a qualified name is valid
236+ check :: (Show a, Eq a) => String -> (Exports -> [a]) -> ModuleName -> a -> Either String (Qualified a)
237+ check t get mn' name = do
238+ modExports <- getExports mn'
239+ if name `elem` get modExports
240+ then return $ Qualified (Just mn') name
241+ else throwError $ "Unknown " ++ t ++ " '" ++ show (Qualified (Just mn') name) ++ "'"
242+
243+ -- Gets the exports for a module, or an error message if the module doesn't exist
244+ getExports :: ModuleName -> Either String Exports
245+ getExports mn' = maybe (throwError $ "Unknown module '" ++ show mn' ++ "'") return $ M.lookup mn' exports
246+
247+-- |
248+-- Finds all exported declarations in a set of modules.
249+--
250+findExports :: [Module] -> Either String ExportEnvironment
251+findExports = foldM addModule $ M.singleton (ModuleName [ProperName "Prim"]) primExports
252+ where
253+
254+ -- The exported types from the Prim module
255+ primExports = Exports (mkTypeEntry `map` M.keys primTypes) [] []
256+ where
257+ mkTypeEntry (Qualified _ name) = (name, [])
258+
259+ -- Add all of the exported declarations from a module to the global export environment
260+ addModule :: ExportEnvironment -> Module -> Either String ExportEnvironment
261+ addModule env m@(Module mn ds _) = do
262+ env' <- addEmptyModule env mn
263+ rethrowForModule m $ foldM (addDecl mn) env' ds
264+
265+ -- Add a declaration from a module to the global export environment
266+ addDecl :: ModuleName -> ExportEnvironment -> Declaration -> Either String ExportEnvironment
267+ addDecl mn env (TypeClassDeclaration tcn _ ds) = do
268+ env' <- addTypeClass env mn tcn
269+ foldM (\env'' (TypeDeclaration name _) -> addValue env'' mn name) env' ds
270+ addDecl mn env (DataDeclaration tn _ dcs) = addType env mn tn (map fst dcs)
271+ addDecl mn env (TypeSynonymDeclaration tn _ _) = addType env mn tn []
272+ addDecl mn env (ExternDataDeclaration tn _) = addType env mn tn []
273+ addDecl mn env (ValueDeclaration name _ _ _ _) = addValue env mn name
274+ addDecl mn env (ExternDeclaration _ name _ _) = addValue env mn name
275+ addDecl _ env _ = return env
276+
277+-- |
278+-- Filters the exports for a module to ensure only explicit exports are kept in the global exports
279+-- environment.
280+--
281+filterExports :: ModuleName -> [DeclarationRef] -> ExportEnvironment -> Either String ExportEnvironment
282+filterExports mn exps env = do
283+ let moduleExports = fromMaybe (error "Module is missing") (mn `M.lookup` env)
284+ moduleExports' <- filterModule moduleExports
285+ return $ M.insert mn moduleExports' env
286+ where
287+
288+ -- Filter the exports for the specific module
289+ filterModule :: Exports -> Either String Exports
290+ filterModule exported = do
291+ types' <- foldM (filterTypes $ exportedTypes exported) [] exps
292+ values <- foldM (filterValues $ exportedValues exported) [] exps
293+ classes <- foldM (filterClasses $ exportedTypeClasses exported) [] exps
294+ return exported { exportedTypes = types', exportedTypeClasses = classes, exportedValues = values }
295+
296+ -- Ensure the exported types and data constructors exist in the module and add them to the set of
297+ -- exports
298+ filterTypes :: [(ProperName, [ProperName])] -> [(ProperName, [ProperName])] -> DeclarationRef -> Either String [(ProperName, [ProperName])]
299+ filterTypes expTys result (TypeRef name expDcons) = do
300+ dcons <- maybe (throwError $ "Cannot export undefined type '" ++ show name ++ "'") return $ name `lookup` expTys
301+ dcons' <- maybe (return dcons) (foldM (filterDcons name dcons) []) expDcons
302+ return $ (name, dcons') : result
303+ filterTypes _ result _ = return result
304+
305+ -- Ensure the exported data constructors exists for a type and add them to the list of exports
306+ filterDcons :: ProperName -> [ProperName] -> [ProperName] -> ProperName -> Either String [ProperName]
307+ filterDcons tcon exps' result name =
308+ if name `elem` exps'
309+ then return $ name : result
310+ else throwError $ "Cannot export undefined data constructor '" ++ show name ++ "' for type '" ++ show tcon ++ "'"
311+
312+ -- Ensure the exported classes exist in the module and add them to the set of exports
313+ filterClasses :: [ProperName] -> [ProperName] -> DeclarationRef -> Either String [ProperName]
314+ filterClasses exps' result (TypeClassRef name) =
315+ if name `elem` exps'
316+ then return $ name : result
317+ else throwError $ "Cannot export undefined type class '" ++ show name ++ "'"
318+ filterClasses _ result _ = return result
319+
320+ -- Ensure the exported values exist in the module and add them to the set of exports
321+ filterValues :: [Ident] -> [Ident] -> DeclarationRef -> Either String [Ident]
322+ filterValues exps' result (ValueRef name) =
323+ if name `elem` exps'
324+ then return $ name : result
325+ else throwError $ "Cannot export undefined value '" ++ show name ++ "'"
326+ filterValues _ result _ = return result
327+
328+-- |
329+-- Type representing a set of declarations being explicitly imported from a module
330+--
331+type ExplicitImports = [DeclarationRef]
332+
333+-- |
334+-- Finds the imports within a module, mapping the imported module name to an optional set of
335+-- explicitly imported declarations.
336+--
337+findImports :: [Declaration] -> M.Map ModuleName (Maybe ExplicitImports)
338+findImports = foldl findImports' M.empty
339+ where
340+ findImports' result (ImportDeclaration mn expl) = M.insert mn expl result
341+ findImports' result _ = result
342+
343+-- |
344+-- Constructs a local environment for a module.
345+--
346+resolveImports :: ExportEnvironment -> Module -> Either String ImportEnvironment
347+resolveImports env (Module currentModule decls _) =
348+ foldM resolveImport' (ImportEnvironment M.empty M.empty M.empty M.empty) (M.toList scope)
349+ where
350+ -- A Map from module name to imports from that module, where Nothing indicates everything is to be imported
351+ scope :: M.Map ModuleName (Maybe ExplicitImports)
352+ scope = M.insert currentModule Nothing (findImports decls)
353+ resolveImport' imp (mn, i) = do
354+ m <- maybe (throwError $ "Cannot import unknown module '" ++ show mn ++ "'") return $ mn `M.lookup` env
355+ resolveImport currentModule mn m imp i
356+
357+-- |
358+-- Extends the local environment for a module by resolving an import of another module.
359+--
360+resolveImport :: ModuleName -> ModuleName -> Exports -> ImportEnvironment -> Maybe ExplicitImports -> Either String ImportEnvironment
361+resolveImport currentModule importModule exps imps = maybe importAll (foldM importExplicit imps)
362+ where
363+
364+ -- Import everything from a module
365+ importAll :: Either String ImportEnvironment
366+ importAll = do
367+ imp' <- foldM (\m (name, dctors) -> importExplicit m (TypeRef name (Just dctors))) imps (exportedTypes exps)
368+ imp'' <- foldM (\m name -> importExplicit m (ValueRef name)) imp' (exportedValues exps)
369+ foldM (\m name -> importExplicit m (TypeClassRef name)) imp'' (exportedTypeClasses exps)
370+
371+ -- Import something explicitly
372+ importExplicit :: ImportEnvironment -> DeclarationRef -> Either String ImportEnvironment
373+ importExplicit imp (ValueRef name) = do
374+ _ <- checkImportExists "value" values name
375+ values' <- updateImports (importedValues imp) name
376+ return $ imp { importedValues = values' }
377+ importExplicit imp (TypeRef name dctors) = do
378+ _ <- checkImportExists "type" availableTypes name
379+ types' <- updateImports (importedTypes imp) name
380+ let allDctors = allExportedDataConstructors name
381+ dctors' <- maybe (return allDctors) (mapM $ checkDctorExists allDctors) dctors
382+ dctors'' <- foldM updateImports (importedDataConstructors imp) dctors'
383+ return $ imp { importedTypes = types', importedDataConstructors = dctors'' }
384+ importExplicit imp (TypeClassRef name) = do
385+ _ <- checkImportExists "type class" classes name
386+ typeClasses' <- updateImports (importedTypeClasses imp) name
387+ return $ imp { importedTypeClasses = typeClasses' }
388+ importExplicit _ _ = error "Invalid argument to importExplicit"
389+
390+ -- Find all exported data constructors for a given type
391+ allExportedDataConstructors :: ProperName -> [ProperName]
392+ allExportedDataConstructors name = fromMaybe [] $ name `lookup` exportedTypes exps
393+
394+ -- Add something to the ImportEnvironment if it does not already exist there
395+ updateImports :: (Ord a, Show a) => M.Map a (Qualified a) -> a -> Either String (M.Map a (Qualified a))
396+ updateImports m name = case M.lookup name m of
397+ Nothing -> return $ M.insert name (Qualified (Just importModule) name) m
398+ Just (Qualified Nothing _) -> error "Invalid state in updateImports"
399+ Just x@(Qualified (Just mn) _) -> throwError $
400+ if mn == currentModule || importModule == currentModule
401+ then "Definition '" ++ show name ++ "' conflicts with import '" ++ show (Qualified (Just importModule) name) ++ "'"
402+ else "Conflicting imports for '" ++ show name ++ "': '" ++ show x ++ "', '" ++ show (Qualified (Just importModule) name) ++ "'"
403+
404+ -- The available values, types, and classes in the module being imported
405+ values = exportedValues exps
406+ availableTypes = fst `map` exportedTypes exps
407+ classes = exportedTypeClasses exps
408+
409+ -- Ensure that an explicitly imported data constructor exists for the type it is being imported
410+ -- from
411+ checkDctorExists :: [ProperName] -> ProperName -> Either String ProperName
412+ checkDctorExists = checkImportExists "data constructor"
413+
414+ -- Check that an explicitly imported item exists in the module it is being imported from
415+ checkImportExists :: (Eq a, Show a) => String -> [a] -> a -> Either String a
416+ checkImportExists t exports item =
417+ if item `elem` exports
418+ then return item
419+ else throwError $ "Unable to find " ++ t ++ " '" ++ show (Qualified (Just importModule) item) ++ "'"
420+
src/Language/PureScript/Sugar/Operators.hsnew file+118
@@ -0,0 +1,118 @@
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 #-}
21+
22+module Language.PureScript.Sugar.Operators (
23+ rebracket
24+) where
25+
26+import Language.PureScript.Names
27+import Language.PureScript.Declarations
28+import Language.PureScript.Values
29+
30+import Control.Applicative
31+import Control.Arrow (first)
32+import Control.Monad.State
33+
34+import Data.Function (on)
35+import Data.List (groupBy, sortBy)
36+
37+import qualified Data.Map as M
38+import qualified Data.Generics as G
39+import qualified Data.Generics.Extras as G
40+
41+import qualified Text.Parsec as P
42+import qualified Text.Parsec.Pos as P
43+import qualified Text.Parsec.Expr as P
44+
45+-- |
46+-- Remove explicit parentheses and reorder binary operator applications
47+--
48+rebracket :: [Module] -> Either String [Module]
49+rebracket = go M.empty []
50+ where
51+ go _ rb [] = return . reverse $ rb
52+ go m rb (Module name ds exps : ms) = do
53+ m' <- M.union m <$> collectFixities m name ds
54+ let opTable = customOperatorTable m'
55+ ds' <- G.everywhereM' (G.mkM (matchOperators name opTable)) ds
56+ go m' (Module name (G.everywhere (G.mkT removeParens) ds') exps : rb) ms
57+
58+removeParens :: Value -> Value
59+removeParens (Parens val) = val
60+removeParens val = val
61+
62+customOperatorTable :: M.Map (Qualified Ident) Fixity -> [[(Qualified Ident, Value -> Value -> Value, Associativity)]]
63+customOperatorTable fixities =
64+ let
65+ -- We make the assumption here that infix operators are not qualified. The parser currently enforces this.
66+ -- The fixity map can therefore map from module name/ident pairs to fixities, where the module name is the name
67+ -- of the module imported into, not from. This is useful in matchOp, but here we have to discard the module name to
68+ -- make sure that the generated code is correct.
69+ applyUserOp (Qualified _ name) t1 = App (App (Var (Qualified Nothing name)) t1)
70+ userOps = map (\(name, Fixity a p) -> (name, applyUserOp name, p, a)) . M.toList $ fixities
71+ sorted = sortBy (flip compare `on` (\(_, _, p, _) -> p)) userOps
72+ groups = groupBy ((==) `on` (\(_, _, p, _) -> p)) sorted
73+ in
74+ map (map (\(name, f, _, a) -> (name, f, a))) groups
75+
76+type Chain = [Either Value (Qualified Ident)]
77+
78+matchOperators :: ModuleName -> [[(Qualified Ident, Value -> Value -> Value, Associativity)]] -> Value -> Either String Value
79+matchOperators moduleName ops = G.everywhereM' (G.mkM parseChains)
80+ where
81+ parseChains :: Value -> Either String Value
82+ parseChains b@BinaryNoParens{} = bracketChain (extendChain b)
83+ parseChains other = return other
84+ extendChain :: Value -> Chain
85+ extendChain (BinaryNoParens name l r) = Left l : Right name : extendChain r
86+ extendChain other = [Left other]
87+ bracketChain :: Chain -> Either String Value
88+ bracketChain = either (Left . show) Right . P.parse (P.buildExpressionParser opTable parseValue <* P.eof) "operator expression"
89+ opTable = map (map (\(name, f, a) -> P.Infix (P.try (matchOp moduleName name) >> return f) (toAssoc a))) ops
90+ ++ [[P.Infix (P.try (parseOp >>= \ident -> return (\t1 t2 -> App (App (Var ident) t1) t2))) P.AssocLeft]]
91+
92+toAssoc :: Associativity -> P.Assoc
93+toAssoc Infixl = P.AssocLeft
94+toAssoc Infixr = P.AssocRight
95+
96+parseValue :: P.Parsec Chain () Value
97+parseValue = P.token show (const (P.initialPos "")) (either Just (const Nothing)) P.<?> "expression"
98+
99+parseOp :: P.Parsec Chain () (Qualified Ident)
100+parseOp = P.token show (const (P.initialPos "")) (either (const Nothing) Just) P.<?> "operator"
101+
102+matchOp :: ModuleName -> Qualified Ident -> P.Parsec Chain () ()
103+matchOp moduleName op = do
104+ ident <- parseOp
105+ guard (qualify moduleName ident == qualify moduleName op)
106+
107+collectFixities :: M.Map (Qualified Ident) Fixity -> ModuleName -> [Declaration] -> Either String (M.Map (Qualified Ident) Fixity)
108+collectFixities m _ [] = return m
109+collectFixities m moduleName (FixityDeclaration fixity name : rest) = do
110+ let qual = Qualified (Just moduleName) (Op name)
111+ when (qual `M.member` m) (Left $ "redefined fixity for " ++ show name)
112+ collectFixities (M.insert qual fixity m) moduleName rest
113+collectFixities m moduleName (ImportDeclaration importedModule _ : rest) = do
114+ let fs = [ (i, fixity) | (Qualified mn i, fixity) <- M.toList m, mn == Just importedModule ]
115+ let m' = M.fromList (map (first (Qualified (Just moduleName))) fs)
116+ collectFixities (m' `M.union` m) moduleName rest
117+collectFixities m moduleName (_:ds) = collectFixities m moduleName ds
118+
src/Language/PureScript/Sugar/TypeClasses.hsnew file+165
@@ -0,0 +1,165 @@
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+ mkDictionaryEntryName
20+) where
21+
22+import Language.PureScript.Declarations
23+import Language.PureScript.Names
24+import Language.PureScript.Types
25+import Language.PureScript.Values
26+import Language.PureScript.CodeGen.JS.AST
27+import Language.PureScript.Sugar.CaseDeclarations
28+import Language.PureScript.Environment
29+import Language.PureScript.CodeGen.Common (identToJs)
30+
31+import Control.Applicative
32+import Control.Monad.State
33+import Control.Arrow (second)
34+import Data.Maybe (catMaybes)
35+
36+import qualified Data.Map as M
37+
38+type MemberMap = M.Map (ModuleName, ProperName) ([String], [(String, Type)])
39+
40+type Desugar = StateT MemberMap (Either String)
41+
42+-- |
43+-- Add type synonym declarations for type class dictionary types, and value declarations for type class
44+-- instance dictionary expressions.
45+--
46+desugarTypeClasses :: [Module] -> Either String [Module]
47+desugarTypeClasses = flip evalStateT M.empty . mapM desugarModule
48+
49+desugarModule :: Module -> Desugar Module
50+desugarModule (Module name decls (Just exps)) = do
51+ (newExpss, declss) <- unzip <$> mapM (desugarDecl name) decls
52+ return $ Module name (concat declss) $ Just (exps ++ catMaybes newExpss)
53+desugarModule _ = error "Exports should have been elaborated in name desugaring"
54+
55+-- |
56+-- Desugar type class and type class instance declarations
57+--
58+-- Type classes become type synonyms for their dictionaries, and type instances become dictionary declarations.
59+-- Additional values are generated to access individual members of a dictionary, with the appropriate type.
60+--
61+-- E.g. the following
62+--
63+-- module Test where
64+--
65+-- class Foo a where
66+-- foo :: a -> a
67+--
68+-- instance Foo String where
69+-- foo s = s ++ s
70+--
71+-- instance (Foo a) => Foo [a] where
72+-- foo = map foo
73+--
74+-- becomes
75+--
76+-- type Foo a = { foo :: a -> a }
77+--
78+-- foreign import foo "function foo(dict) {\
79+-- \ return dict.foo;\
80+-- \}" :: forall a. (Foo a) => a -> a
81+--
82+-- __Test_Foo_string_foo = (\s -> s ++ s) :: String -> String
83+--
84+-- __Test_Foo_string :: {} -> Foo String
85+-- __Test_Foo_string = { foo: __Test_Foo_string_foo :: String -> String (unchecked) }
86+--
87+-- __Test_Foo_array_foo :: forall a. (Foo a) => [a] -> [a]
88+-- __Test_Foo_array_foo _1 = map (foo _1)
89+--
90+-- __Test_Foo_array :: forall a. Foo a -> Foo [a]
91+-- __Test_Foo_array _1 = { foo: __Test_Foo_array_foo _1 :: [a] -> [a] (unchecked) }
92+--
93+desugarDecl :: ModuleName -> Declaration -> Desugar (Maybe DeclarationRef, [Declaration])
94+desugarDecl mn d@(TypeClassDeclaration name args members) = do
95+ let tys = map memberToNameAndType members
96+ modify (M.insert (mn, name) (args, tys))
97+ return $ (Nothing, d : typeClassDictionaryDeclaration name args members : map (typeClassMemberToDictionaryAccessor mn name args) members)
98+desugarDecl mn d@(TypeInstanceDeclaration name deps className ty members) = do
99+ desugared <- lift $ desugarCases members
100+ entries <- mapM (typeInstanceDictionaryEntryDeclaration name mn deps className ty) desugared
101+ dictDecl <- typeInstanceDictionaryDeclaration name mn deps className ty desugared
102+ return $ (Just $ TypeInstanceRef name, d : entries ++ [dictDecl])
103+desugarDecl _ other = return (Nothing, [other])
104+
105+memberToNameAndType :: Declaration -> (String, Type)
106+memberToNameAndType (TypeDeclaration ident ty) = (identToJs ident, ty)
107+memberToNameAndType _ = error "Invalid declaration in type class definition"
108+
109+typeClassDictionaryDeclaration :: ProperName -> [String] -> [Declaration] -> Declaration
110+typeClassDictionaryDeclaration name args members =
111+ TypeSynonymDeclaration name args (Object $ rowFromList (map memberToNameAndType members, REmpty))
112+
113+typeClassMemberToDictionaryAccessor :: ModuleName -> ProperName -> [String] -> Declaration -> Declaration
114+typeClassMemberToDictionaryAccessor mn name args (TypeDeclaration ident ty) =
115+ ExternDeclaration TypeClassAccessorImport ident
116+ (Just (JSFunction (Just $ identToJs ident) ["dict"] (JSBlock [JSReturn (JSAccessor (identToJs ident) (JSVar "dict"))])))
117+ (quantify (ConstrainedType [(Qualified (Just mn) name, map TypeVar args)] ty))
118+typeClassMemberToDictionaryAccessor _ _ _ _ = error "Invalid declaration in type class definition"
119+
120+typeInstanceDictionaryDeclaration :: Ident -> ModuleName -> [(Qualified ProperName, [Type])] -> Qualified ProperName -> [Type] -> [Declaration] -> Desugar Declaration
121+typeInstanceDictionaryDeclaration name mn deps className tys decls = do
122+ m <- get
123+ (args, instanceTys) <- lift $ maybe (Left $ "Type class " ++ show className ++ " is undefined. Type class names must be qualified.") Right
124+ $ M.lookup (qualify mn className) m
125+ let memberTypes = map (second (replaceAllTypeVars (zip args tys))) instanceTys
126+ let entryName = Escaped (show name)
127+ memberNames <- mapM (memberToNameAndValue memberTypes) decls
128+ return $ ValueDeclaration entryName TypeInstanceDictionaryValue [] Nothing
129+ (TypedValue True
130+ (foldr (Abs . (\n -> Left . Ident $ '_' : show n)) (ObjectLiteral memberNames) [1..max 1 (length deps)])
131+ (quantify (if null deps then
132+ function unit (foldl TypeApp (TypeConstructor className) tys)
133+ else
134+ foldr (function . (\(pn, tys') -> foldl TypeApp (TypeConstructor pn) tys')) (foldl TypeApp (TypeConstructor className) tys) deps))
135+ )
136+ where
137+ memberToNameAndValue :: [(String, Type)] -> Declaration -> Desugar (String, Value)
138+ memberToNameAndValue tys' (ValueDeclaration ident _ _ _ _) = do
139+ memberType <- lift . maybe (Left "Type class member type not found") Right $ lookup (identToJs ident) tys'
140+ memberName <- mkDictionaryEntryName name ident
141+ return (identToJs ident, TypedValue False
142+ (foldl App (Var (Qualified Nothing memberName)) (map (\n -> Var (Qualified Nothing (Ident ('_' : show n)))) [1..length deps]))
143+ (quantify memberType))
144+ memberToNameAndValue _ _ = error "Invalid declaration in type instance definition"
145+
146+typeInstanceDictionaryEntryDeclaration :: Ident -> ModuleName -> [(Qualified ProperName, [Type])] -> Qualified ProperName -> [Type] -> Declaration -> Desugar Declaration
147+typeInstanceDictionaryEntryDeclaration name mn deps className tys (ValueDeclaration ident _ [] _ val) = do
148+ m <- get
149+ valTy <- lift $ do (args, members) <- lookupTypeClass m
150+ ty' <- lookupIdent members
151+ return $ replaceAllTypeVars (zip args tys) ty'
152+ entryName <- mkDictionaryEntryName name ident
153+ return $ ValueDeclaration entryName TypeInstanceMember [] Nothing
154+ (TypedValue True val (quantify (if null deps then valTy else ConstrainedType deps valTy)))
155+ where
156+ lookupTypeClass m = maybe (Left $ "Type class " ++ show className ++ " is undefined. Type class names must be qualified.") Right $ M.lookup (qualify mn className) m
157+ lookupIdent members = maybe (Left $ "Type class " ++ show className ++ " does not have method " ++ show ident) Right $ lookup (identToJs ident) members
158+typeInstanceDictionaryEntryDeclaration _ _ _ _ _ _ = error "Invalid declaration in type instance definition"
159+
160+-- |
161+-- Generate a name for a type class dictionary member, based on the module name, class name, type name and
162+-- member name
163+--
164+mkDictionaryEntryName :: Ident -> Ident -> Desugar Ident
165+mkDictionaryEntryName dictName ident = return $ Escaped $ show dictName ++ "_" ++ identToJs ident
src/Language/PureScript/Sugar/TypeDeclarations.hsnew file+43
@@ -0,0 +1,43 @@
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 Control.Applicative
23+import Control.Monad.Error.Class
24+import Control.Monad (forM)
25+
26+import Language.PureScript.Declarations
27+import Language.PureScript.Values
28+
29+-- |
30+-- Replace all top level type declarations in a module with type annotations
31+--
32+desugarTypeDeclarationsModule :: [Module] -> Either String [Module]
33+desugarTypeDeclarationsModule ms = forM ms $ \(Module name ds exps) -> Module name <$> desugarTypeDeclarations ds <*> pure exps
34+
35+-- |
36+-- Replace all top level type declarations with type annotations
37+--
38+desugarTypeDeclarations :: [Declaration] -> Either String [Declaration]
39+desugarTypeDeclarations (TypeDeclaration name ty : ValueDeclaration name' nameKind [] Nothing val : rest) | name == name' =
40+ desugarTypeDeclarations (ValueDeclaration name nameKind [] Nothing (TypedValue True val ty) : rest)
41+desugarTypeDeclarations (TypeDeclaration name _ : _) = throwError $ "Orphan type declaration for " ++ show name
42+desugarTypeDeclarations (d:ds) = (:) d <$> desugarTypeDeclarations ds
43+desugarTypeDeclarations [] = return []
src/Language/PureScript/TypeChecker.hsnew file+198
@@ -0,0 +1,198 @@
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 qualified Data.Map as M
30+import Control.Monad.State
31+import Control.Monad.Error
32+
33+import Language.PureScript.Types
34+import Language.PureScript.Names
35+import Language.PureScript.Values
36+import Language.PureScript.Kinds
37+import Language.PureScript.Declarations
38+import Language.PureScript.Environment
39+
40+addDataType :: ModuleName -> ProperName -> [String] -> [(ProperName, [Type])] -> Kind -> Check ()
41+addDataType moduleName name args dctors ctorKind = do
42+ env <- getEnv
43+ putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (ctorKind, DataType args dctors) (types env) }
44+ forM_ dctors $ \(dctor, tys) ->
45+ rethrow (("Error in data constructor " ++ show dctor ++ ":\n") ++) $
46+ addDataConstructor moduleName name args dctor tys
47+
48+addDataConstructor :: ModuleName -> ProperName -> [String] -> ProperName -> [Type] -> Check ()
49+addDataConstructor moduleName name args dctor tys = do
50+ env <- getEnv
51+ let retTy = foldl TypeApp (TypeConstructor (Qualified (Just moduleName) name)) (map TypeVar args)
52+ let dctorTy = foldr function retTy tys
53+ let polyType = mkForAll args dctorTy
54+ putEnv $ env { dataConstructors = M.insert (Qualified (Just moduleName) dctor) (name, polyType) (dataConstructors env) }
55+
56+addTypeSynonym :: ModuleName -> ProperName -> [String] -> Type -> Kind -> Check ()
57+addTypeSynonym moduleName name args ty kind = do
58+ env <- getEnv
59+ putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, TypeSynonym) (types env)
60+ , typeSynonyms = M.insert (Qualified (Just moduleName) name) (args, ty) (typeSynonyms env) }
61+
62+valueIsNotDefined :: ModuleName -> Ident -> Check ()
63+valueIsNotDefined moduleName name = do
64+ env <- getEnv
65+ case M.lookup (moduleName, name) (names env) of
66+ Just _ -> throwError $ show name ++ " is already defined"
67+ Nothing -> return ()
68+
69+addValue :: ModuleName -> Ident -> Type -> NameKind -> Check ()
70+addValue moduleName name ty nameKind = do
71+ env <- getEnv
72+ putEnv (env { names = M.insert (moduleName, name) (ty, nameKind) (names env) })
73+
74+addTypeClass :: ModuleName -> ProperName -> [String] -> [Declaration] -> Check ()
75+addTypeClass moduleName pn args ds =
76+ let members = map (\(TypeDeclaration ident ty) -> (ident, ty)) ds in
77+ modify $ \st -> st { checkEnv = (checkEnv st) { typeClasses = M.insert (Qualified (Just moduleName) pn) (args, members) (typeClasses . checkEnv $ st) } }
78+
79+addTypeClassDictionaries :: [TypeClassDictionaryInScope] -> Check ()
80+addTypeClassDictionaries entries =
81+ modify $ \st -> st { checkEnv = (checkEnv st) { typeClassDictionaries = entries ++ (typeClassDictionaries . checkEnv $ st) } }
82+
83+checkTypeClassInstance :: ModuleName -> Type -> Check ()
84+checkTypeClassInstance _ (TypeVar _) = return ()
85+checkTypeClassInstance _ (TypeConstructor ctor) = do
86+ env <- getEnv
87+ when (ctor `M.member` typeSynonyms env) $ throwError "Type synonym instances are disallowed"
88+ return ()
89+checkTypeClassInstance m (TypeApp ty (TypeVar _)) = checkTypeClassInstance m ty
90+checkTypeClassInstance _ _ = throwError "Type class instance must be of the form T a1 ... an"
91+
92+-- |
93+-- Type check all declarations in a module
94+--
95+-- At this point, many declarations will have been desugared, but it is still necessary to
96+--
97+-- * Kind-check all types and add them to the @Environment@
98+--
99+-- * Type-check all values and add them to the @Environment@
100+--
101+-- * Bring type class instances into scope
102+--
103+-- * Process module imports
104+--
105+typeCheckAll :: Maybe ModuleName -> ModuleName -> [Declaration] -> Check [Declaration]
106+typeCheckAll _ _ [] = return []
107+typeCheckAll mainModuleName moduleName (d@(DataDeclaration name args dctors) : rest) = do
108+ rethrow (("Error in type constructor " ++ show name ++ ":\n") ++) $ do
109+ ctorKind <- kindsOf moduleName name args (concatMap snd dctors)
110+ addDataType moduleName name args dctors ctorKind
111+ ds <- typeCheckAll mainModuleName moduleName rest
112+ return $ d : ds
113+typeCheckAll mainModuleName moduleName (d@(DataBindingGroupDeclaration tys) : rest) = do
114+ rethrow ("Error in data binding group:\n" ++) $ do
115+ let syns = mapMaybe toTypeSynonym tys
116+ let dataDecls = mapMaybe toDataDecl tys
117+ (syn_ks, data_ks) <- kindsOfAll moduleName syns (map (\(name, args, dctors) -> (name, args, concatMap snd dctors)) dataDecls)
118+ forM_ (zip dataDecls data_ks) $ \((name, args, dctors), ctorKind) ->
119+ addDataType moduleName name args dctors ctorKind
120+ forM_ (zip syns syn_ks) $ \((name, args, ty), kind) ->
121+ addTypeSynonym moduleName name args ty kind
122+ ds <- typeCheckAll mainModuleName moduleName rest
123+ return $ d : ds
124+ where
125+ toTypeSynonym (TypeSynonymDeclaration nm args ty) = Just (nm, args, ty)
126+ toTypeSynonym _ = Nothing
127+ toDataDecl (DataDeclaration nm args dctors) = Just (nm, args, dctors)
128+ toDataDecl _ = Nothing
129+typeCheckAll mainModuleName moduleName (d@(TypeSynonymDeclaration name args ty) : rest) = do
130+ rethrow (("Error in type synonym " ++ show name ++ ":\n") ++) $ do
131+ kind <- kindsOf moduleName name args [ty]
132+ addTypeSynonym moduleName name args ty kind
133+ ds <- typeCheckAll mainModuleName moduleName rest
134+ return $ d : ds
135+typeCheckAll _ _ (TypeDeclaration _ _ : _) = error "Type declarations should have been removed"
136+typeCheckAll mainModuleName moduleName (ValueDeclaration name nameKind [] Nothing val : rest) = do
137+ d <- rethrow (("Error in declaration " ++ show name ++ ":\n") ++) $ do
138+ valueIsNotDefined moduleName name
139+ [(_, (val', ty))] <- typesOf mainModuleName moduleName [(name, val)]
140+ addValue moduleName name ty nameKind
141+ return $ ValueDeclaration name nameKind [] Nothing val'
142+ ds <- typeCheckAll mainModuleName moduleName rest
143+ return $ d : ds
144+typeCheckAll _ _ (ValueDeclaration{} : _) = error "Binders were not desugared"
145+typeCheckAll mainModuleName moduleName (BindingGroupDeclaration vals : rest) = do
146+ d <- rethrow (("Error in binding group " ++ show (map (\(ident, _, _) -> ident) vals) ++ ":\n") ++) $ do
147+ forM_ (map (\(ident, _, _) -> ident) vals) $ \name ->
148+ valueIsNotDefined moduleName name
149+ tys <- typesOf mainModuleName moduleName $ map (\(ident, _, ty) -> (ident, ty)) vals
150+ vals' <- forM (zipWith (\(name, nameKind, _) (_, (val, ty)) -> (name, val, nameKind, ty)) vals tys) $ \(name, val, nameKind, ty) -> do
151+ addValue moduleName name ty nameKind
152+ return (name, nameKind, val)
153+ return $ BindingGroupDeclaration vals'
154+ ds <- typeCheckAll mainModuleName moduleName rest
155+ return $ d : ds
156+typeCheckAll mainModuleName moduleName (d@(ExternDataDeclaration name kind) : rest) = do
157+ env <- getEnv
158+ putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, ExternData) (types env) }
159+ ds <- typeCheckAll mainModuleName moduleName rest
160+ return $ d : ds
161+typeCheckAll mainModuleName moduleName (d@(ExternDeclaration importTy name _ ty) : rest) = do
162+ rethrow (("Error in foreign import declaration " ++ show name ++ ":\n") ++) $ do
163+ env <- getEnv
164+ kind <- kindOf moduleName ty
165+ guardWith "Expected kind *" $ kind == Star
166+ case M.lookup (moduleName, name) (names env) of
167+ Just _ -> throwError $ show name ++ " is already defined"
168+ Nothing -> putEnv (env { names = M.insert (moduleName, name) (ty, Extern importTy) (names env) })
169+ ds <- typeCheckAll mainModuleName moduleName rest
170+ return $ d : ds
171+typeCheckAll mainModuleName moduleName (d@(FixityDeclaration _ name) : rest) = do
172+ ds <- typeCheckAll mainModuleName moduleName rest
173+ env <- getEnv
174+ guardWith ("Fixity declaration with no binding: " ++ name) $ M.member (moduleName, Op name) $ names env
175+ return $ d : ds
176+typeCheckAll mainModuleName currentModule (d@(ImportDeclaration moduleName _) : rest) = do
177+ env <- getEnv
178+ let instances = filter (\tcd ->
179+ let Qualified (Just mn) _ = tcdName tcd in
180+ moduleName == mn && tcdType tcd == TCDRegular
181+ ) (typeClassDictionaries env)
182+ forM_ instances $ \tcd -> do
183+ let (Qualified _ ident) = tcdName tcd
184+ addTypeClassDictionaries [tcd { tcdName = Qualified (Just currentModule) ident, tcdType = TCDAlias (tcdName tcd) }]
185+ ds <- typeCheckAll mainModuleName currentModule rest
186+ return $ d : ds
187+typeCheckAll mainModuleName moduleName (d@(TypeClassDeclaration pn args tys) : rest) = do
188+ addTypeClass moduleName pn args tys
189+ ds <- typeCheckAll mainModuleName moduleName rest
190+ return $ d : ds
191+typeCheckAll mainModuleName moduleName (TypeInstanceDeclaration dictName deps className tys _ : rest) = do
192+ typeCheckAll mainModuleName moduleName (ExternInstanceDeclaration dictName deps className tys : rest)
193+typeCheckAll mainModuleName moduleName (d@(ExternInstanceDeclaration dictName deps className tys) : rest) = do
194+ mapM_ (checkTypeClassInstance moduleName) tys
195+ forM_ deps $ mapM_ (checkTypeClassInstance moduleName) . snd
196+ addTypeClassDictionaries [TypeClassDictionaryInScope (Qualified (Just moduleName) dictName) className tys (Just deps) TCDRegular]
197+ ds <- typeCheckAll mainModuleName moduleName rest
198+ return $ d : ds
src/Language/PureScript/TypeChecker/Kinds.hsnew file+166
@@ -0,0 +1,166 @@
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 #-}
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+
32+import Control.Monad.State
33+import Control.Monad.Error
34+import Control.Monad.Unify
35+
36+import Control.Applicative
37+
38+import qualified Data.Map as M
39+
40+instance Partial Kind where
41+ unknown = KUnknown
42+ isUnknown (KUnknown u) = Just u
43+ isUnknown _ = Nothing
44+
45+instance Unifiable Check Kind where
46+ KUnknown u1 =?= KUnknown u2 | u1 == u2 = return ()
47+ KUnknown u =?= k = u =:= k
48+ k =?= KUnknown u = u =:= k
49+ Star =?= Star = return ()
50+ Bang =?= Bang = return ()
51+ Row k1 =?= Row k2 = k1 =?= k2
52+ FunKind k1 k2 =?= FunKind k3 k4 = do
53+ k1 =?= k3
54+ k2 =?= k4
55+ k1 =?= k2 = UnifyT . lift . throwError $ "Cannot unify " ++ prettyPrintKind k1 ++ " with " ++ prettyPrintKind k2 ++ "."
56+
57+-- |
58+-- Infer the kind of a single type
59+--
60+kindOf :: ModuleName -> Type -> Check Kind
61+kindOf _ ty =
62+ rethrow (("Error checking kind of " ++ prettyPrintType ty ++ ":\n") ++) $
63+ fmap tidyUp . liftUnify $ starIfUnknown <$> infer ty
64+ where
65+ tidyUp (k, sub) = sub $? k
66+
67+-- |
68+-- Infer the kind of a type constructor with a collection of arguments and a collection of associated data constructors
69+--
70+kindsOf :: ModuleName -> ProperName -> [String] -> [Type] -> Check Kind
71+kindsOf moduleName name args ts = fmap tidyUp . liftUnify $ do
72+ tyCon <- fresh
73+ kargs <- replicateM (length args) fresh
74+ let dict = (name, tyCon) : zipWith (\arg kind -> (arg, kind)) (map ProperName args) kargs
75+ bindLocalTypeVariables moduleName dict $
76+ solveTypes ts kargs tyCon
77+ where
78+ tidyUp (k, sub) = starIfUnknown $ sub $? k
79+
80+-- |
81+-- Simultaneously infer the kinds of several mutually recursive type constructors
82+--
83+kindsOfAll :: ModuleName -> [(ProperName, [String], Type)] -> [(ProperName, [String], [Type])] -> Check ([Kind], [Kind])
84+kindsOfAll moduleName syns tys = fmap tidyUp . liftUnify $ do
85+ synVars <- replicateM (length syns) fresh
86+ let dict = zipWith (\(name, _, _) var -> (name, var)) syns synVars
87+ bindLocalTypeVariables moduleName dict $ do
88+ tyCons <- replicateM (length tys) fresh
89+ let dict' = zipWith (\(name, _, _) tyCon -> (name, tyCon)) tys tyCons
90+ bindLocalTypeVariables moduleName dict' $ do
91+ data_ks <- zipWithM (\tyCon (_, args, ts) -> do
92+ kargs <- replicateM (length args) fresh
93+ let argDict = zip (map ProperName args) kargs
94+ bindLocalTypeVariables moduleName argDict $
95+ solveTypes ts kargs tyCon) tyCons tys
96+ syn_ks <- zipWithM (\synVar (_, args, ty) -> do
97+ kargs <- replicateM (length args) fresh
98+ let argDict = zip (map ProperName args) kargs
99+ bindLocalTypeVariables moduleName argDict $
100+ solveTypes [ty] kargs synVar) synVars syns
101+ return (syn_ks, data_ks)
102+ where
103+ tidyUp ((ks1, ks2), sub) = (map (starIfUnknown . (sub $?)) ks1, map (starIfUnknown . (sub $?)) ks2)
104+
105+-- |
106+-- Solve the set of kind constraints associated with the data constructors for a type constructor
107+--
108+solveTypes :: [Type] -> [Kind] -> Kind -> UnifyT Kind Check Kind
109+solveTypes ts kargs tyCon = do
110+ ks <- mapM infer ts
111+ tyCon =?= foldr FunKind Star kargs
112+ forM_ ks $ \k -> k =?= Star
113+ return tyCon
114+
115+-- |
116+-- Default all unknown kinds to the Star kind of types
117+--
118+starIfUnknown :: Kind -> Kind
119+starIfUnknown (KUnknown _) = Star
120+starIfUnknown (FunKind k1 k2) = FunKind (starIfUnknown k1) (starIfUnknown k2)
121+starIfUnknown k = k
122+
123+-- |
124+-- Infer a kind for a type
125+--
126+infer :: Type -> UnifyT Kind Check Kind
127+infer (Object row) = do
128+ k <- infer row
129+ k =?= Row Star
130+ return Star
131+infer (TypeVar v) = do
132+ Just moduleName <- checkCurrentModule <$> get
133+ UnifyT . lift $ lookupTypeVariable moduleName (Qualified Nothing (ProperName v))
134+infer (TypeConstructor v) = do
135+ env <- liftCheck getEnv
136+ case M.lookup v (types env) of
137+ Nothing -> UnifyT . lift . throwError $ "Unknown type constructor '" ++ show v ++ "'"
138+ Just (kind, _) -> return kind
139+infer (TypeApp t1 t2) = do
140+ k0 <- fresh
141+ k1 <- infer t1
142+ k2 <- infer t2
143+ k1 =?= FunKind k2 k0
144+ return k0
145+infer (ForAll ident ty _) = do
146+ k1 <- fresh
147+ Just moduleName <- checkCurrentModule <$> get
148+ k2 <- bindLocalTypeVariables moduleName [(ProperName ident, k1)] $ infer ty
149+ k2 =?= Star
150+ return Star
151+infer REmpty = do
152+ k <- fresh
153+ return $ Row k
154+infer (RCons _ ty row) = do
155+ k1 <- infer ty
156+ k2 <- infer row
157+ k2 =?= Row k1
158+ return $ Row k1
159+infer (ConstrainedType deps ty) = do
160+ forM_ deps $ \(className, tys) -> do
161+ _ <- infer $ foldl TypeApp (TypeConstructor className) tys
162+ return ()
163+ k <- infer ty
164+ k =?= Star
165+ return Star
166+infer _ = error "Invalid argument to infer"
src/Language/PureScript/TypeChecker/Monad.hsnew file+202
@@ -0,0 +1,202 @@
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.Values
24+import Language.PureScript.Names
25+import Language.PureScript.Environment
26+
27+import Data.Maybe
28+
29+import Control.Applicative
30+import Control.Monad.State
31+import Control.Monad.Error
32+import Control.Monad.Unify
33+
34+import qualified Data.Map as M
35+
36+-- |
37+-- Temporarily bind a collection of names to values
38+--
39+bindNames :: (MonadState CheckState m) => M.Map (ModuleName, Ident) (Type, NameKind) -> m a -> m a
40+bindNames newNames action = do
41+ orig <- get
42+ modify $ \st -> st { checkEnv = (checkEnv st) { names = newNames `M.union` (names . checkEnv $ st) } }
43+ a <- action
44+ modify $ \st -> st { checkEnv = (checkEnv st) { names = names . checkEnv $ orig } }
45+ return a
46+
47+-- |
48+-- Temporarily bind a collection of names to types
49+--
50+bindTypes :: (MonadState CheckState m) => M.Map (Qualified ProperName) (Kind, TypeKind) -> m a -> m a
51+bindTypes newNames action = do
52+ orig <- get
53+ modify $ \st -> st { checkEnv = (checkEnv st) { types = newNames `M.union` (types . checkEnv $ st) } }
54+ a <- action
55+ modify $ \st -> st { checkEnv = (checkEnv st) { types = types . checkEnv $ orig } }
56+ return a
57+
58+-- |
59+-- Temporarily make a collection of type class dictionaries available
60+--
61+withTypeClassDictionaries :: (MonadState CheckState m) => [TypeClassDictionaryInScope] -> m a -> m a
62+withTypeClassDictionaries entries action = do
63+ orig <- get
64+ modify $ \st -> st { checkEnv = (checkEnv st) { typeClassDictionaries = entries ++ (typeClassDictionaries . checkEnv $ st) } }
65+ a <- action
66+ modify $ \st -> st { checkEnv = (checkEnv st) { typeClassDictionaries = typeClassDictionaries . checkEnv $ orig } }
67+ return a
68+
69+-- |
70+-- Get the currently available list of type class dictionaries
71+--
72+getTypeClassDictionaries :: (Functor m, MonadState CheckState m) => m [TypeClassDictionaryInScope]
73+getTypeClassDictionaries = typeClassDictionaries . checkEnv <$> get
74+
75+-- |
76+-- Temporarily bind a collection of names to local variables
77+--
78+bindLocalVariables :: (Functor m, MonadState CheckState m) => ModuleName -> [(Ident, Type)] -> m a -> m a
79+bindLocalVariables moduleName bindings =
80+ bindNames (M.fromList $ flip map bindings $ \(name, ty) -> ((moduleName, name), (ty, LocalVariable)))
81+
82+-- |
83+-- Temporarily bind a collection of names to local type variables
84+--
85+bindLocalTypeVariables :: (Functor m, MonadState CheckState m) => ModuleName -> [(ProperName, Kind)] -> m a -> m a
86+bindLocalTypeVariables moduleName bindings =
87+ bindTypes (M.fromList $ flip map bindings $ \(pn, kind) -> (Qualified (Just moduleName) pn, (kind, LocalTypeVariable)))
88+
89+-- |
90+-- Lookup the type of a value by name in the @Environment@
91+--
92+lookupVariable :: (Functor m, MonadState CheckState m, MonadError String m) => ModuleName -> Qualified Ident -> m Type
93+lookupVariable currentModule (Qualified moduleName var) = do
94+ env <- getEnv
95+ case M.lookup (fromMaybe currentModule moduleName, var) (names env) of
96+ Nothing -> throwError $ show var ++ " is undefined"
97+ Just (ty, _) -> return ty
98+
99+-- |
100+-- Lookup the kind of a type by name in the @Environment@
101+--
102+lookupTypeVariable :: (Functor m, MonadState CheckState m, MonadError String m) => ModuleName -> Qualified ProperName -> m Kind
103+lookupTypeVariable currentModule (Qualified moduleName name) = do
104+ env <- getEnv
105+ case M.lookup (Qualified (Just $ fromMaybe currentModule moduleName) name) (types env) of
106+ Nothing -> throwError $ "Type variable " ++ show name ++ " is undefined"
107+ Just (k, _) -> return k
108+
109+-- |
110+-- State required for type checking:
111+--
112+data CheckState = CheckState {
113+ -- |
114+ -- The current @Environment@
115+ --
116+ checkEnv :: Environment
117+ -- |
118+ -- The next fresh unification variable name
119+ --
120+ , checkNextVar :: Int
121+ -- |
122+ -- The next type class dictionary name
123+ --
124+ , checkNextDictName :: Int
125+ -- |
126+ -- The current module
127+ --
128+ , checkCurrentModule :: Maybe ModuleName
129+ }
130+
131+-- |
132+-- The type checking monad, which provides the state of the type checker, and error reporting capabilities
133+--
134+newtype Check a = Check { unCheck :: StateT CheckState (Either String) a }
135+ deriving (Functor, Monad, Applicative, MonadPlus, MonadState CheckState, MonadError String)
136+
137+-- |
138+-- Get the current @Environment@
139+--
140+getEnv :: (Functor m, MonadState CheckState m) => m Environment
141+getEnv = checkEnv <$> get
142+
143+-- |
144+-- Update the @Environment#
145+--
146+putEnv :: (MonadState CheckState m) => Environment -> m ()
147+putEnv env = modify (\s -> s { checkEnv = env })
148+
149+-- |
150+-- Modify the @Environment@
151+--
152+modifyEnv :: (MonadState CheckState m) => (Environment -> Environment) -> m ()
153+modifyEnv f = modify (\s -> s { checkEnv = f (checkEnv s) })
154+
155+-- |
156+-- Run a computation in the Check monad, failing with an error, or succeeding with a return value and the final @Environment@.
157+--
158+runCheck :: Check a -> Either String (a, Environment)
159+runCheck c = do
160+ (a, s) <- flip runStateT (CheckState initEnvironment 0 0 Nothing) $ unCheck c
161+ return (a, checkEnv s)
162+
163+-- |
164+-- Make an assertion, failing with an error message
165+--
166+guardWith :: (MonadError e m) => e -> Bool -> m ()
167+guardWith _ True = return ()
168+guardWith e False = throwError e
169+
170+-- |
171+-- Rethrow an error with a more detailed error message in the case of failure
172+--
173+rethrow :: (MonadError e m) => (e -> e) -> m a -> m a
174+rethrow f = flip catchError $ \e -> throwError (f e)
175+
176+-- |
177+-- Generate new type class dictionary name
178+--
179+freshDictionaryName :: Check Int
180+freshDictionaryName = do
181+ n <- checkNextDictName <$> get
182+ modify $ \s -> s { checkNextDictName = succ (checkNextDictName s) }
183+ return n
184+
185+-- |
186+-- Lift a computation in the @Check@ monad into the substitution monad.
187+--
188+liftCheck :: Check a -> UnifyT t Check a
189+liftCheck = UnifyT . lift . lift
190+
191+-- |
192+-- Run a computation in the substitution monad, generating a return value and the final substitution.
193+--
194+liftUnify :: (Partial t) => UnifyT t Check a -> Check (a, Substitution t)
195+liftUnify unify = do
196+ st <- get
197+ e <- runUnify (defaultUnifyState { unifyNextVar = checkNextVar st }) unify
198+ case e of
199+ Left err -> throwError err
200+ Right (a, ust) -> do
201+ modify $ \st' -> st' { checkNextVar = unifyNextVar ust }
202+ return (a, unifyCurrentSubstitution ust)
src/Language/PureScript/TypeChecker/Synonyms.hsnew file+59
@@ -0,0 +1,59 @@
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.hsnew file+929
@@ -0,0 +1,929 @@
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 FlexibleContexts #-}
18+{-# LANGUAGE MultiParamTypeClasses #-}
19+
20+module Language.PureScript.TypeChecker.Types (
21+ typesOf
22+) where
23+
24+{-
25+ The following functions represent the corresponding type checking judgements:
26+
27+ infer
28+ Synthesize a type for a value
29+
30+ check
31+ Check a value has a given type
32+
33+ checkProperties
34+ Check an object with a given type contains specified properties
35+
36+ checkFunctionApplication
37+ Check a function of a given type returns a value of another type when applied to its arguments
38+
39+ subsumes
40+ Check a type subsumes another type
41+-}
42+
43+import Data.List
44+import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
45+import qualified Data.Data as D
46+import Data.Generics
47+ (everythingWithContext, mkM, everywhereM, everything, mkT,
48+ something, everywhere, mkQ)
49+import Data.Generics.Extras
50+
51+import Language.PureScript.Values
52+import Language.PureScript.Types
53+import Language.PureScript.Kinds
54+import Language.PureScript.Names
55+import Language.PureScript.TypeChecker.Monad
56+import Language.PureScript.TypeChecker.Kinds
57+import Language.PureScript.TypeChecker.Synonyms
58+import Language.PureScript.Pretty
59+import Language.PureScript.Environment
60+import qualified Language.PureScript.Constants as C
61+
62+import Control.Monad.State
63+import Control.Monad.Error
64+import Control.Monad.Unify
65+
66+import Control.Applicative
67+import Control.Arrow (Arrow(..))
68+
69+import qualified Data.Map as M
70+import Data.Function (on)
71+import Data.Ord (comparing)
72+
73+instance Partial Type where
74+ unknown = TUnknown
75+ isUnknown (TUnknown u) = Just u
76+ isUnknown _ = Nothing
77+
78+instance Unifiable Check Type where
79+ (=?=) = unifyTypes
80+
81+-- |
82+-- Unify two types, updating the current substitution
83+--
84+unifyTypes :: Type -> Type -> UnifyT Type Check ()
85+unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $
86+ unifyTypes' t1 t2
87+ where
88+ unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
89+ unifyTypes' (TUnknown u) t = u =:= t
90+ unifyTypes' t (TUnknown u) = u =:= t
91+ unifyTypes' (SaturatedTypeSynonym name args) ty = do
92+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
93+ ty1 `unifyTypes` ty
94+ unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
95+ unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
96+ case (sc1, sc2) of
97+ (Just sc1', Just sc2') -> do
98+ sko <- newSkolemConstant
99+ let sk1 = skolemize ident1 sko sc1' ty1
100+ let sk2 = skolemize ident2 sko sc2' ty2
101+ sk1 `unifyTypes` sk2
102+ _ -> throwError (prettyPrintType ty1)
103+ unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
104+ sko <- newSkolemConstant
105+ let sk = skolemize ident sko sc ty1
106+ sk `unifyTypes` ty2
107+ unifyTypes' ForAll{} _ = throwError "Skolem variable scope is unspecified"
108+ unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
109+ unifyTypes' (Object row1) (Object row2) = row1 =?= row2
110+ unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
111+ unifyTypes' (TypeConstructor c1) (TypeConstructor c2) =
112+ guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (c1 == c2)
113+ unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
114+ t3 `unifyTypes` t5
115+ t4 `unifyTypes` t6
116+ unifyTypes' (Skolem s1 _) (Skolem s2 _) | s1 == s2 = return ()
117+ unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
118+ unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
119+ unifyTypes' r1@REmpty r2 = unifyRows r1 r2
120+ unifyTypes' r1 r2@REmpty = unifyRows r1 r2
121+ unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
122+
123+-- |
124+-- Unify two rows, updating the current substitution
125+--
126+-- Common labels are first identified, and unified. Remaining labels and types are unified with a
127+-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
128+-- error.
129+--
130+unifyRows :: Type -> Type -> UnifyT Type Check ()
131+unifyRows r1 r2 =
132+ let
133+ (s1, r1') = rowToList r1
134+ (s2, r2') = rowToList r2
135+ int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
136+ sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
137+ sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
138+ in do
139+ forM_ int (uncurry (=?=))
140+ unifyRows' sd1 r1' sd2 r2'
141+ where
142+ unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
143+ unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
144+ unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
145+ unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
146+ occursCheck un ty
147+ forM_ row $ \(_, t) -> occursCheck un t
148+ u' <- fresh
149+ u =?= RCons name ty u'
150+ unifyRows' row r others u'
151+ unifyRows' [] REmpty [] REmpty = return ()
152+ unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
153+ unifyRows' [] (Skolem s1 _) [] (Skolem s2 _) | s1 == s2 = return ()
154+ unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")."
155+
156+-- |
157+-- Infer the types of multiple mutually-recursive values, and return elaborated values including
158+-- type class dictionaries and type annotations.
159+--
160+typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
161+typesOf mainModuleName moduleName vals = do
162+ tys <- fmap tidyUp . liftUnify $ do
163+ let
164+ -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
165+ es = map isTyped vals
166+ -- Filter the typed and untyped declarations
167+ typed = filter (isJust . snd . snd) es
168+ untyped = filter (isNothing . snd . snd) es
169+ -- Make a map of names to typed declarations
170+ typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
171+ -- Create fresh unification variables for the types of untyped declarations
172+ untypedNames <- replicateM (length untyped) fresh
173+ let
174+ -- Make a map of names to the unification variables of untyped declarations
175+ untypedDict = zip (map fst untyped) untypedNames
176+ -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
177+ dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
178+ forM es $ \e@(_, (val, _)) -> do
179+ -- If the declaration is a function, it has access to other values in the binding group.
180+ -- If not, the generated code might fail at runtime since those values might be undefined.
181+ let dict' = if isFunction val then dict else M.empty
182+ triple@(_, (val', ty)) <- case e of
183+ -- Typed declarations
184+ (ident, (val', Just (ty, checkType))) -> do
185+ -- Kind check
186+ kind <- liftCheck $ kindOf moduleName ty
187+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
188+ -- Check the type with the new names in scope
189+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
190+ val'' <- bindNames dict' $ if checkType
191+ then TypedValue True <$> check val' ty' <*> pure ty'
192+ else return (TypedValue False val' ty')
193+ return (ident, (val'', ty'))
194+ -- Untyped declarations
195+ (ident, (val', Nothing)) -> do
196+ -- Infer the type with the new names in scope
197+ TypedValue _ val'' ty <- bindNames dict' $ infer val'
198+ ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
199+ return (ident, (TypedValue True val'' ty, ty))
200+ -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
201+ when (Just moduleName == mainModuleName && fst e == Ident C.main) $ do
202+ [eff, a] <- replicateM 2 fresh
203+ ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
204+ -- Make sure unification variables do not escape
205+ escapeCheck val' ty
206+ return triple
207+ forM tys $ \(ident, (val, ty)) -> do
208+ -- Replace type class dictionary placeholders with actual dictionaries
209+ val' <- replaceTypeClassDictionaries moduleName val
210+ -- Check skolem variables did not escape their scope
211+ skolemEscapeCheck val'
212+ -- Remove type synonyms placeholders, remove duplicate row fields, and replace
213+ -- top-level unification variables with named type variables.
214+ let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
215+ ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
216+ return (ident, (val'', ty'))
217+ where
218+ -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
219+ tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
220+
221+-- |
222+-- Check if a value introduces a function
223+--
224+isFunction :: Value -> Bool
225+isFunction (Abs _ _) = True
226+isFunction (TypedValue _ val _) = isFunction val
227+isFunction _ = False
228+
229+-- |
230+-- Check if a value contains a type annotation
231+--
232+isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
233+isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
234+isTyped (name, value) = (name, (value, Nothing))
235+
236+-- |
237+-- Map a function over type annotations appearing inside a value
238+--
239+overTypes :: (Type -> Type) -> Value -> Value
240+overTypes f = everywhere (mkT f)
241+
242+-- |
243+-- Replace type class dictionary placeholders with inferred type class dictionaries
244+--
245+replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
246+replaceTypeClassDictionaries mn = everywhereM' (mkM go)
247+ where
248+ go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
249+ go other = return other
250+
251+-- |
252+-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
253+-- return a type class dictionary reference.
254+--
255+entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Check Value
256+entails moduleName context goal@(className, tys) = do
257+ env <- getEnv
258+ case go env goal of
259+ [] -> throwError $ "No " ++ show className ++ " instance found for " ++ intercalate ", " (map prettyPrintType tys)
260+ (dict : _) -> return dict
261+ where
262+ go env (className', tys') =
263+ [ mkDictionary (canonicalizeDictionary tcd) args
264+ | tcd <- context
265+ -- Choose type class dictionaries in scope in the current module
266+ , filterModule tcd
267+ -- Make sure the type class name matches the one we are trying to satisfy
268+ , className' == tcdClassName tcd
269+ -- Make sure the type unifies with the type in the type instance definition
270+ , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
271+ -- Solve any necessary subgoals
272+ , args <- solveSubgoals env subst (tcdDependencies tcd) ]
273+ -- Create dictionaries for subgoals which still need to be solved by calling go recursively
274+ -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
275+ -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
276+ solveSubgoals :: Environment -> [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [Value]]
277+ solveSubgoals _ _ Nothing = return Nothing
278+ solveSubgoals env subst (Just subgoals) = do
279+ dict <- mapM (go env . second (map (replaceAllTypeVars subst))) subgoals
280+ return $ Just dict
281+ -- Make a dictionary from subgoal dictionaries by applying the correct function
282+ mkDictionary :: Qualified Ident -> Maybe [Value] -> Value
283+ mkDictionary fnName Nothing = Var fnName
284+ mkDictionary fnName (Just []) = App (Var fnName) (ObjectLiteral [])
285+ mkDictionary fnName (Just dicts) = foldl App (Var fnName) dicts
286+ -- Filter out type dictionaries which are in scope in the current module
287+ filterModule :: TypeClassDictionaryInScope -> Bool
288+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
289+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
290+ filterModule _ = False
291+ canonicalizeDictionary :: TypeClassDictionaryInScope -> Qualified Ident
292+ canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
293+ canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
294+ -- Ensure that a substitution is valid
295+ verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
296+ verifySubstitution subst = do
297+ let grps = groupBy ((==) `on` fst) subst
298+ guard (all ((==) 1 . length . nubBy ((==) `on` snd)) grps)
299+ return $ map head grps
300+
301+-- |
302+-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
303+-- and return a substitution from type variables to types which makes the type heads unify.
304+--
305+typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
306+typeHeadsAreEqual _ _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = Just []
307+typeHeadsAreEqual _ _ (TypeVar v) t = Just [(v, t)]
308+typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
309+typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
310+typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <$> typeHeadsAreEqual m e h1 h2
311+typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
312+typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
313+ Left _ -> Nothing
314+ Right t1 -> typeHeadsAreEqual m e t1 t2
315+typeHeadsAreEqual _ _ _ _ = Nothing
316+
317+-- |
318+-- Ensure unsolved unification variables do not escape
319+--
320+escapeCheck :: Value -> Type -> UnifyT Type Check ()
321+escapeCheck value ty = do
322+ subst <- unifyCurrentSubstitution <$> UnifyT get
323+ let visibleUnknowns = nub $ unknowns $ subst $? ty
324+ let allUnknowns = findAllTypes value
325+ forM_ allUnknowns $ \t -> do
326+ let unsolvedUnknowns = nub . unknowns $ subst $? t
327+ guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
328+
329+-- |
330+-- Find all type annotations occuring inside a value
331+--
332+findAllTypes :: Value -> [Type]
333+findAllTypes = everything (++) (mkQ [] go)
334+ where
335+ go (TypedValue _ _ ty) = [ty]
336+ go _ = []
337+
338+-- |
339+-- Ensure skolem variables do not escape their scope
340+--
341+skolemEscapeCheck :: Value -> Check ()
342+skolemEscapeCheck (TypedValue False _ _) = return ()
343+skolemEscapeCheck root@TypedValue{} =
344+ -- Every skolem variable is created when a ForAll type is skolemized.
345+ -- This determines the scope of that skolem variable, which is copied from the SkolemScope
346+ -- field of the ForAll constructor.
347+ -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
348+ -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
349+ -- an escaped skolem variable.
350+ case everythingWithContext [] (++) (mkQ ((,) []) go) root of
351+ [] -> return ()
352+ ((binding, val) : _) -> throwError $ "Rigid/skolem type variable bound by " ++ maybe "<unknown>" prettyPrintValue binding ++ " has escaped at " ++ prettyPrintValue val
353+ where
354+ go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
355+ go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
356+ go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
357+ (sco : _) -> ([(findBindingScope sco, val)], scos)
358+ _ -> ([], scos)
359+ where
360+ collectSkolems :: Type -> [SkolemScope]
361+ collectSkolems = nub . everything (++) (mkQ [] collect)
362+ where
363+ collect (Skolem _ scope) = [scope]
364+ collect _ = []
365+ go _ scos = ([], scos)
366+ findBindingScope :: SkolemScope -> Maybe Value
367+ findBindingScope sco = something (mkQ Nothing go') root
368+ where
369+ go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = Just val
370+ go' _ = Nothing
371+skolemEscapeCheck val = throwError $ "Untyped value passed to skolemEscapeCheck: " ++ prettyPrintValue val
372+
373+-- |
374+-- Ensure a row contains no duplicate labels
375+--
376+setify :: Type -> Type
377+setify = rowFromList . first (M.toList . M.fromList) . rowToList
378+
379+-- |
380+-- \"Setify\" all rows occuring inside a value
381+--
382+setifyAll :: (D.Data d) => d -> d
383+setifyAll = everywhere (mkT setify)
384+
385+-- |
386+-- Replace outermost unsolved unification variables with named type variables
387+--
388+varIfUnknown :: Type -> Type
389+varIfUnknown ty =
390+ let unks = nub $ unknowns ty
391+ toName = (:) 't' . show
392+ ty' = everywhere (mkT typeToVar) ty
393+ typeToVar :: Type -> Type
394+ typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
395+ typeToVar t = t
396+ in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
397+
398+-- |
399+-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
400+-- or TypeClassDictionary values.
401+--
402+-- This is necessary during type checking to avoid unifying a polymorphic type with a
403+-- unification variable.
404+--
405+instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
406+instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
407+ ty' <- replaceVarWithUnknown ident ty
408+ instantiatePolyTypeWithUnknowns val ty'
409+instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
410+ dicts <- getTypeClassDictionaries
411+ (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
412+ return (foldl App val (map (flip TypeClassDictionary dicts) constraints), ty')
413+instantiatePolyTypeWithUnknowns val ty = return (val, ty)
414+
415+-- |
416+-- Replace a single type variable with a new unification variable
417+--
418+replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
419+replaceVarWithUnknown ident ty = do
420+ tu <- fresh
421+ return $ replaceTypeVars ident tu ty
422+
423+-- |
424+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
425+-- better error messages during unification.
426+--
427+replaceAllTypeSynonyms' :: (D.Data d) => Environment -> d -> Either String d
428+replaceAllTypeSynonyms' env d =
429+ let
430+ syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
431+ in
432+ saturateAllTypeSynonyms syns d
433+
434+replaceAllTypeSynonyms :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
435+replaceAllTypeSynonyms d = do
436+ env <- getEnv
437+ either throwError return $ replaceAllTypeSynonyms' env d
438+
439+-- |
440+-- \"Desaturate\" @SaturatedTypeSynonym@s
441+--
442+desaturateAllTypeSynonyms :: (D.Data d) => d -> d
443+desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
444+ where
445+ replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
446+ replaceSaturatedTypeSynonym t = t
447+
448+-- |
449+-- Replace a type synonym and its arguments with the aliased type
450+--
451+expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
452+expandTypeSynonym' env name args =
453+ case M.lookup name (typeSynonyms env) of
454+ Just (synArgs, body) -> do
455+ let repl = replaceAllTypeVars (zip synArgs args) body
456+ replaceAllTypeSynonyms' env repl
457+ Nothing -> error "Type synonym was not defined"
458+
459+expandTypeSynonym :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => Qualified ProperName -> [Type] -> m Type
460+expandTypeSynonym name args = do
461+ env <- getEnv
462+ either throwError return $ expandTypeSynonym' env name args
463+
464+-- |
465+-- Ensure a set of property names and value does not contain duplicate labels
466+--
467+ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
468+ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
469+
470+-- |
471+-- Infer a type for a value, rethrowing any error to provide a more useful error message
472+--
473+infer :: Value -> UnifyT Type Check Value
474+infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
475+
476+-- |
477+-- Infer a type for a value
478+--
479+infer' :: Value -> UnifyT Type Check Value
480+infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
481+infer' v@(StringLiteral _) = return $ TypedValue True v tyString
482+infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
483+infer' (ArrayLiteral vals) = do
484+ ts <- mapM infer vals
485+ els <- fresh
486+ forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
487+ return $ TypedValue True (ArrayLiteral ts) els
488+infer' (ObjectLiteral ps) = do
489+ ensureNoDuplicateProperties ps
490+ ts <- mapM (infer . snd) ps
491+ let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
492+ ty = Object $ rowFromList (fields, REmpty)
493+ return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
494+infer' (ObjectUpdate o ps) = do
495+ ensureNoDuplicateProperties ps
496+ row <- fresh
497+ newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
498+ let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
499+ oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
500+ let oldTy = Object $ rowFromList (oldTys, row)
501+ o' <- TypedValue True <$> check o oldTy <*> pure oldTy
502+ return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
503+infer' (Accessor prop val) = do
504+ typed@(TypedValue _ _ objTy) <- infer val
505+ propTy <- inferProperty objTy prop
506+ case propTy of
507+ Nothing -> do
508+ field <- fresh
509+ rest <- fresh
510+ _ <- subsumes Nothing objTy (Object (RCons prop field rest))
511+ return $ TypedValue True (Accessor prop typed) field
512+ Just ty -> return $ TypedValue True (Accessor prop typed) ty
513+infer' (Abs (Left arg) ret) = do
514+ ty <- fresh
515+ Just moduleName <- checkCurrentModule <$> get
516+ bindLocalVariables moduleName [(arg, ty)] $ do
517+ body@(TypedValue _ _ bodyTy) <- infer' ret
518+ return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
519+infer' (Abs (Right _) _) = error "Binder was not desugared"
520+infer' (App f arg) = do
521+ f'@(TypedValue _ _ ft) <- infer f
522+ (ret, app) <- checkFunctionApplication f' ft arg Nothing
523+ return $ TypedValue True app ret
524+infer' (Var var) = do
525+ Just moduleName <- checkCurrentModule <$> get
526+ ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
527+ case ty of
528+ ConstrainedType constraints ty' -> do
529+ dicts <- getTypeClassDictionaries
530+ return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) constraints)) ty'
531+ _ -> return $ TypedValue True (Var var) ty
532+infer' v@(Constructor c) = do
533+ env <- getEnv
534+ case M.lookup c (dataConstructors env) of
535+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
536+ Just (_, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
537+ return $ TypedValue True v ty'
538+infer' (Case vals binders) = do
539+ ts <- mapM infer vals
540+ ret <- fresh
541+ binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
542+ return $ TypedValue True (Case ts binders') ret
543+infer' (IfThenElse cond th el) = do
544+ cond' <- check cond tyBoolean
545+ v2@(TypedValue _ _ t2) <- infer th
546+ v3@(TypedValue _ _ t3) <- infer el
547+ t2 =?= t3
548+ return $ TypedValue True (IfThenElse cond' v2 v3) t2
549+infer' (TypedValue checkType val ty) = do
550+ Just moduleName <- checkCurrentModule <$> get
551+ kind <- liftCheck $ kindOf moduleName ty
552+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
553+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
554+ val' <- if checkType then check val ty' else return val
555+ return $ TypedValue True val' ty'
556+infer' _ = error "Invalid argument to infer"
557+
558+-- |
559+-- Infer the type of a property inside a record with a given type
560+--
561+inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
562+inferProperty (Object row) prop = do
563+ let (props, _) = rowToList row
564+ return $ lookup prop props
565+inferProperty (SaturatedTypeSynonym name args) prop = do
566+ replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
567+ inferProperty replaced prop
568+inferProperty (ForAll ident ty _) prop = do
569+ replaced <- replaceVarWithUnknown ident ty
570+ inferProperty replaced prop
571+inferProperty _ _ = return Nothing
572+
573+-- |
574+-- Infer the types of variables brought into scope by a binder
575+--
576+inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
577+inferBinder _ NullBinder = return M.empty
578+inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
579+inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
580+inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
581+inferBinder val (VarBinder name) = return $ M.singleton name val
582+inferBinder val (ConstructorBinder ctor binders) = do
583+ env <- getEnv
584+ case M.lookup ctor (dataConstructors env) of
585+ Just (_, ty) -> do
586+ (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
587+ fn' <- replaceAllTypeSynonyms fn
588+ go binders fn'
589+ where
590+ go [] ty' = do
591+ _ <- subsumes Nothing val ty'
592+ return M.empty
593+ go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
594+ M.union <$> inferBinder obj binder <*> go binders' ret
595+ go _ _ = throwError $ "Wrong number of arguments to constructor " ++ show ctor
596+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
597+inferBinder val (ObjectBinder props) = do
598+ row <- fresh
599+ rest <- fresh
600+ m1 <- inferRowProperties row rest props
601+ val =?= Object row
602+ return m1
603+ where
604+ inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
605+ inferRowProperties nrow row [] = nrow =?= row >> return M.empty
606+ inferRowProperties nrow row ((name, binder):binders) = do
607+ propTy <- fresh
608+ m1 <- inferBinder propTy binder
609+ m2 <- inferRowProperties nrow (RCons name propTy row) binders
610+ return $ m1 `M.union` m2
611+inferBinder val (ArrayBinder binders) = do
612+ el <- fresh
613+ m1 <- M.unions <$> mapM (inferBinder el) binders
614+ val =?= TypeApp tyArray el
615+ return m1
616+inferBinder val (ConsBinder headBinder tailBinder) = do
617+ el <- fresh
618+ m1 <- inferBinder el headBinder
619+ m2 <- inferBinder val tailBinder
620+ val =?= TypeApp tyArray el
621+ return $ m1 `M.union` m2
622+inferBinder val (NamedBinder name binder) = do
623+ m <- inferBinder val binder
624+ return $ M.insert name val m
625+
626+-- |
627+-- Check the types of the return values in a set of binders in a case statement
628+--
629+checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
630+checkBinders _ _ [] = return []
631+checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
632+ Just moduleName <- checkCurrentModule <$> get
633+ m1 <- M.unions <$> zipWithM inferBinder nvals binders
634+ r <- bindLocalVariables moduleName (M.toList m1) $ do
635+ val' <- TypedValue True <$> check val ret <*> pure ret
636+ case grd of
637+ Nothing -> return $ CaseAlternative binders Nothing val'
638+ Just g -> do
639+ g' <- check g tyBoolean
640+ return $ CaseAlternative binders (Just g') val'
641+ rs <- checkBinders nvals ret bs
642+ return $ r : rs
643+
644+-- |
645+-- Generate a new skolem constant
646+--
647+newSkolemConstant :: UnifyT Type Check Int
648+newSkolemConstant = runUnknown <$> fresh'
649+
650+-- |
651+-- Generate a new skolem scope
652+--
653+newSkolemScope :: UnifyT Type Check SkolemScope
654+newSkolemScope = SkolemScope . runUnknown <$> fresh'
655+
656+-- |
657+-- Skolemize a type variable by replacing its instances with fresh skolem constants
658+--
659+skolemize :: String -> Int -> SkolemScope -> Type -> Type
660+skolemize ident sko scope = replaceTypeVars ident (Skolem sko scope)
661+
662+-- |
663+-- Introduce skolem scope at every occurence of a ForAll
664+--
665+introduceSkolemScope :: Type -> UnifyT Type Check Type
666+introduceSkolemScope = everywhereM (mkM go)
667+ where
668+ go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
669+ go other = return other
670+
671+-- |
672+-- Check the type of a value, rethrowing errors to provide a better error message
673+--
674+check :: Value -> Type -> UnifyT Type Check Value
675+check val ty = rethrow errorMessage $ check' val ty
676+ where
677+ errorMessage msg =
678+ "Error checking type of term " ++
679+ prettyPrintValue val ++
680+ " against type " ++
681+ prettyPrintType ty ++
682+ ":\n" ++
683+ msg
684+
685+-- |
686+-- Check the type of a value
687+--
688+check' :: Value -> Type -> UnifyT Type Check Value
689+check' val (ForAll ident ty _) = do
690+ scope <- newSkolemScope
691+ sko <- newSkolemConstant
692+ let sk = skolemize ident sko scope ty
693+ val' <- check val sk
694+ return $ TypedValue True val' (ForAll ident ty (Just scope))
695+check' val t@(ConstrainedType constraints ty) = do
696+ dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
697+ n <- liftCheck freshDictionaryName
698+ return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
699+ val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
700+ TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
701+ constraints) $ check val ty
702+ return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
703+check' val (SaturatedTypeSynonym name args) = do
704+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
705+ val' <- check val ty
706+ return $ TypedValue True val' ty
707+check' val u@(TUnknown _) = do
708+ val'@(TypedValue _ _ ty) <- infer val
709+ -- Don't unify an unknown with an inferred polytype
710+ (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
711+ ty' =?= u
712+ return $ TypedValue True val'' ty'
713+check' v@(NumericLiteral _) t | t == tyNumber =
714+ return $ TypedValue True v t
715+check' v@(StringLiteral _) t | t == tyString =
716+ return $ TypedValue True v t
717+check' v@(BooleanLiteral _) t | t == tyBoolean =
718+ return $ TypedValue True v t
719+check' (ArrayLiteral vals) t@(TypeApp a ty) = do
720+ a =?= tyArray
721+ array <- ArrayLiteral <$> forM vals (`check` ty)
722+ return $ TypedValue True array t
723+check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
724+ Just moduleName <- checkCurrentModule <$> get
725+ ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
726+ return $ TypedValue True (Abs (Left arg) ret') ty
727+check' (Abs (Right _) _) _ = error "Binder was not desugared"
728+check' (App f arg) ret = do
729+ f'@(TypedValue _ _ ft) <- infer f
730+ (_, app) <- checkFunctionApplication f' ft arg (Just ret)
731+ return $ TypedValue True app ret
732+check' v@(Var var) ty = do
733+ Just moduleName <- checkCurrentModule <$> get
734+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
735+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
736+ v' <- subsumes (Just v) repl ty'
737+ case v' of
738+ Nothing -> throwError "Unable to check type subsumption"
739+ Just v'' -> return $ TypedValue True v'' ty'
740+check' (TypedValue checkType val ty1) ty2 = do
741+ Just moduleName <- checkCurrentModule <$> get
742+ kind <- liftCheck $ kindOf moduleName ty1
743+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
744+ ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
745+ val' <- subsumes (Just val) ty1' ty2
746+ case val' of
747+ Nothing -> throwError "Unable to check type subsumption"
748+ Just val'' -> do
749+ val''' <- if checkType then check val'' ty1 else return val''
750+ return $ TypedValue checkType (TypedValue True val''' ty1) ty2
751+check' (Case vals binders) ret = do
752+ vals' <- mapM infer vals
753+ let ts = map (\(TypedValue _ _ t) -> t) vals'
754+ binders' <- checkBinders ts ret binders
755+ return $ TypedValue True (Case vals' binders') ret
756+check' (IfThenElse cond th el) ty = do
757+ cond' <- check cond tyBoolean
758+ th' <- check th ty
759+ el' <- check el ty
760+ return $ TypedValue True (IfThenElse cond' th' el') ty
761+check' (ObjectLiteral ps) t@(Object row) = do
762+ ensureNoDuplicateProperties ps
763+ ps' <- checkProperties ps row False
764+ return $ TypedValue True (ObjectLiteral ps') t
765+check' (ObjectUpdate obj ps) t@(Object row) = do
766+ ensureNoDuplicateProperties ps
767+ us <- zip (map fst ps) <$> replicateM (length ps) fresh
768+ let (propsToCheck, rest) = rowToList row
769+ propsToRemove = map fst ps
770+ remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
771+ obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
772+ ps' <- checkProperties ps row True
773+ return $ TypedValue True (ObjectUpdate obj' ps') t
774+check' (Accessor prop val) ty = do
775+ rest <- fresh
776+ val' <- check val (Object (RCons prop ty rest))
777+ return $ TypedValue True (Accessor prop val') ty
778+check' (Constructor c) ty = do
779+ env <- getEnv
780+ case M.lookup c (dataConstructors env) of
781+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
782+ Just (_, ty1) -> do
783+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
784+ _ <- subsumes Nothing repl ty
785+ return $ TypedValue True (Constructor c) ty
786+check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
787+
788+-- |
789+-- Check the type of a collection of named record fields
790+--
791+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
792+--
793+checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
794+checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
795+ go [] [] REmpty = return []
796+ go [] [] u@(TUnknown _) = do u =?= REmpty
797+ return []
798+ go [] [] (Skolem _ _) | lax = return []
799+ go [] ((p, _): _) _ | lax = return []
800+ | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
801+ go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
802+ go ((p,v):ps') [] u@(TUnknown _) = do
803+ v'@(TypedValue _ _ ty) <- infer v
804+ rest <- fresh
805+ u =?= RCons p ty rest
806+ ps'' <- go ps' [] rest
807+ return $ (p, v') : ps''
808+ go ((p,v):ps') ts r =
809+ case lookup p ts of
810+ Nothing -> do
811+ v'@(TypedValue _ _ ty) <- infer v
812+ rest <- fresh
813+ r =?= RCons p ty rest
814+ ps'' <- go ps' ts rest
815+ return $ (p, v') : ps''
816+ Just ty -> do
817+ v' <- check v ty
818+ ps'' <- go ps' (delete (p, ty) ts) r
819+ return $ (p, v') : ps''
820+ go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
821+
822+-- |
823+-- Check the type of a function application, rethrowing errors to provide a better error message
824+--
825+checkFunctionApplication :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
826+checkFunctionApplication fn fnTy arg ret = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg ret
827+ where
828+ errorMessage msg = "Error applying function of type "
829+ ++ prettyPrintType fnTy
830+ ++ " to argument " ++ prettyPrintValue arg
831+ ++ ":\n" ++ msg
832+
833+-- |
834+-- Check the type of a function application
835+--
836+checkFunctionApplication' :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
837+checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
838+ tyFunction' =?= tyFunction
839+ _ <- maybe (return Nothing) (subsumes Nothing retTy) ret
840+ subst <- unifyCurrentSubstitution <$> UnifyT get
841+ arg' <- check arg (subst $? argTy)
842+ return (retTy, App fn arg')
843+checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
844+ replaced <- replaceVarWithUnknown ident ty
845+ checkFunctionApplication fn replaced arg ret
846+checkFunctionApplication' fn u@(TUnknown _) arg ret = do
847+ arg' <- do
848+ TypedValue _ arg' t <- infer arg
849+ (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
850+ return $ TypedValue True arg'' t'
851+ let ty = (\(TypedValue _ _ t) -> t) arg'
852+ ret' <- maybe fresh return ret
853+ u =?= function ty ret'
854+ return (ret', App fn arg')
855+checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
856+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
857+ checkFunctionApplication fn ty arg ret
858+checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
859+ dicts <- getTypeClassDictionaries
860+ checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) constraints)) fnTy arg ret
861+checkFunctionApplication' _ fnTy arg _ = throwError $ "Cannot apply a function of type "
862+ ++ prettyPrintType fnTy
863+ ++ " to argument " ++ prettyPrintValue arg
864+
865+-- |
866+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
867+--
868+subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
869+subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
870+ where
871+ errorMessage msg = "Error checking that type "
872+ ++ prettyPrintType ty1
873+ ++ " subsumes type "
874+ ++ prettyPrintType ty2
875+ ++ ":\n" ++ msg
876+
877+-- |
878+-- Check whether one type subsumes another
879+--
880+subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
881+subsumes' val (ForAll ident ty1 _) ty2 = do
882+ replaced <- replaceVarWithUnknown ident ty1
883+ subsumes val replaced ty2
884+subsumes' val ty1 (ForAll ident ty2 sco) =
885+ case sco of
886+ Just sco' -> do
887+ sko <- newSkolemConstant
888+ let sk = skolemize ident sko sco' ty2
889+ subsumes val ty1 sk
890+ Nothing -> throwError "Skolem variable scope is unspecified"
891+subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
892+ _ <- subsumes Nothing arg2 arg1
893+ _ <- subsumes Nothing ret1 ret2
894+ return val
895+subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
896+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
897+ subsumes val ty1 ty2
898+subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
899+ ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
900+ subsumes val ty1 ty2
901+subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
902+ dicts <- getTypeClassDictionaries
903+ _ <- subsumes' Nothing ty1 ty2
904+ return . Just $ foldl App val (map (flip TypeClassDictionary dicts) constraints)
905+subsumes' val (Object r1) (Object r2) = do
906+ let
907+ (ts1, r1') = rowToList r1
908+ (ts2, r2') = rowToList r2
909+ ts1' = sortBy (comparing fst) ts1
910+ ts2' = sortBy (comparing fst) ts2
911+ go ts1' ts2' r1' r2'
912+ return val
913+ where
914+ go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
915+ go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
916+ go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
917+ | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
918+ go ts1 ts2 r1' r2'
919+ | p1 < p2 = do rest <- fresh
920+ r2' =?= RCons p1 ty1 rest
921+ go ts1 ((p2, ty2) : ts2) r1' rest
922+ | otherwise = do rest <- fresh
923+ r1' =?= RCons p2 ty2 rest
924+ go ((p1, ty1) : ts1) ts2 rest r2'
925+subsumes' val ty1 ty2@(Object _) = subsumes val ty2 ty1
926+subsumes' val ty1 ty2 = do
927+ ty1 =?= ty2
928+ return val
929+
src/Language/PureScript/Types.hsnew file+192
@@ -0,0 +1,192 @@
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+ -- Javascript numbers
44+ --
45+ | Object Type
46+ -- |
47+ -- A named type variable
48+ --
49+ | TypeVar String
50+ -- |
51+ -- A type constructor
52+ --
53+ | TypeConstructor (Qualified ProperName)
54+ -- |
55+ -- A type application
56+ --
57+ | TypeApp Type Type
58+ -- |
59+ -- A type synonym which is \"saturated\", i.e. fully applied
60+ --
61+ | SaturatedTypeSynonym (Qualified ProperName) [Type]
62+ -- |
63+ -- Forall quantifier
64+ --
65+ | ForAll String Type (Maybe SkolemScope)
66+ -- |
67+ -- A type with a set of type class constraints
68+ --
69+ | ConstrainedType [(Qualified ProperName, [Type])] Type
70+ -- |
71+ -- A skolem constant
72+ --
73+ | Skolem Int SkolemScope
74+ -- |
75+ -- An empty row
76+ --
77+ | REmpty
78+ -- |
79+ -- A non-empty row
80+ --
81+ | RCons String Type Type
82+ -- |
83+ -- A placeholder used in pretty printing
84+ --
85+ | PrettyPrintFunction Type Type
86+ -- |
87+ -- A placeholder used in pretty printing
88+ --
89+ | PrettyPrintArray 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+-- The empty record type
125+--
126+unit :: Type
127+unit = Object REmpty
128+
129+-- |
130+-- Replace a type variable, taking into account variable shadowing
131+--
132+replaceTypeVars :: String -> Type -> Type -> Type
133+replaceTypeVars = replaceTypeVars' []
134+ where
135+ replaceTypeVars' bound name replacement = go bound
136+ where
137+ go :: [String] -> Type -> Type
138+ go bs (Object r) = Object $ go bs r
139+ go _ (TypeVar v) | v == name = replacement
140+ go bs (TypeApp t1 t2) = TypeApp (go bs t1) (go bs t2)
141+ go bs (SaturatedTypeSynonym name' ts) = SaturatedTypeSynonym name' $ map (go bs) ts
142+ go bs f@(ForAll v t sco) | v == name = f
143+ | v `elem` usedTypeVariables replacement =
144+ let v' = genName v (name : bs ++ usedTypeVariables replacement)
145+ t' = replaceTypeVars' bs v (TypeVar v') t
146+ in ForAll v' (go (v' : bs) t') sco
147+ | otherwise = ForAll v (go (v : bs) t) sco
148+ go bs (ConstrainedType cs t) = ConstrainedType (map (second $ map (go bs)) cs) (go bs t)
149+ go bs (RCons name' t r) = RCons name' (go bs t) (go bs r)
150+ go _ ty = ty
151+ genName orig inUse = try 0
152+ where
153+ try :: Integer -> String
154+ try n | (orig ++ show n) `elem` inUse = try (n + 1)
155+ | otherwise = orig ++ show n
156+
157+-- |
158+-- Replace named type variables with types
159+--
160+replaceAllTypeVars :: [(String, Type)] -> Type -> Type
161+replaceAllTypeVars = foldl (\f (name, ty) -> replaceTypeVars name ty . f) id
162+
163+-- |
164+-- Collect all type variables appearing in a type
165+--
166+usedTypeVariables :: Type -> [String]
167+usedTypeVariables = nub . everything (++) (mkQ [] go)
168+ where
169+ go (TypeVar v) = [v]
170+ go _ = []
171+
172+-- |
173+-- Collect all free type variables appearing in a type
174+--
175+freeTypeVariables :: Type -> [String]
176+freeTypeVariables = nub . go []
177+ where
178+ go :: [String] -> Type -> [String]
179+ go bound (Object r) = go bound r
180+ go bound (TypeVar v) | v `notElem` bound = [v]
181+ go bound (TypeApp t1 t2) = go bound t1 ++ go bound t2
182+ go bound (SaturatedTypeSynonym _ ts) = concatMap (go bound) ts
183+ go bound (ForAll v t _) = go (v : bound) t
184+ go bound (ConstrainedType cs t) = concatMap (concatMap (go bound) . snd) cs ++ go bound t
185+ go bound (RCons _ t r) = go bound t ++ go bound r
186+ go _ _ = []
187+
188+-- |
189+-- Universally quantify over all type variables appearing free in a type
190+--
191+quantify :: Type -> Type
192+quantify ty = foldr (\arg t -> ForAll arg t Nothing) ty $ freeTypeVariables ty
src/Language/PureScript/Values.hsnew file+247
@@ -0,0 +1,247 @@
1+-----------------------------------------------------------------------------
2+--
3+-- Module : Language.PureScript.Values
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 values, statements, binders and do notation
13+--
14+-----------------------------------------------------------------------------
15+
16+{-# LANGUAGE DeriveDataTypeable #-}
17+
18+module Language.PureScript.Values where
19+
20+import Language.PureScript.Types
21+import Language.PureScript.Names
22+
23+import Data.Data
24+import Data.Generics (mkQ, everything)
25+
26+-- |
27+-- A guard is just a boolean-valued expression that appears alongside a set of binders
28+--
29+type Guard = Value
30+
31+-- |
32+-- Data type for values
33+--
34+data Value
35+ -- |
36+ -- A numeric literal
37+ --
38+ = NumericLiteral (Either Integer Double)
39+ -- |
40+ -- A string literal
41+ --
42+ | StringLiteral String
43+ -- |
44+ -- A boolean literal
45+ --
46+ | BooleanLiteral Bool
47+ -- |
48+ -- Binary operator application. During the rebracketing phase of desugaring, this data constructor
49+ -- will be removed.
50+ --
51+ | BinaryNoParens (Qualified Ident) Value Value
52+ -- |
53+ -- Explicit parentheses. During the rebracketing phase of desugaring, this data constructor
54+ -- will be removed.
55+ --
56+ | Parens Value
57+ -- |
58+ -- An array literal
59+ --
60+ | ArrayLiteral [Value]
61+ -- |
62+ -- An object literal
63+ --
64+ | ObjectLiteral [(String, Value)]
65+ -- |
66+ -- An record property accessor expression
67+ --
68+ | Accessor String Value
69+ -- |
70+ -- Partial record update
71+ --
72+ | ObjectUpdate Value [(String, Value)]
73+ -- |
74+ -- Function introduction
75+ --
76+ | Abs (Either Ident Binder) Value
77+ -- |
78+ -- Function application
79+ --
80+ | App Value Value
81+ -- |
82+ -- Variable
83+ --
84+ | Var (Qualified Ident)
85+ -- |
86+ -- Conditional (if-then-else expression)
87+ --
88+ | IfThenElse Value Value Value
89+ -- |
90+ -- A data constructor
91+ --
92+ | Constructor (Qualified ProperName)
93+ -- |
94+ -- A case expression. During the case expansion phase of desugaring, top-level binders will get
95+ -- desugared into case expressions, hence the need for guards and multiple binders per branch here.
96+ --
97+ | Case [Value] [CaseAlternative]
98+ -- |
99+ -- A value with a type annotation
100+ --
101+ | TypedValue Bool Value Type
102+ -- |
103+ -- A let binding
104+ --
105+ | Let (Either Binder (Ident, [Either Ident Binder])) Value Value
106+ -- |
107+ -- A do-notation block
108+ --
109+ | Do [DoNotationElement]
110+ -- |
111+ -- A placeholder for a type class dictionary to be inserted later. At the end of type checking, these
112+ -- placeholders will be replaced with actual expressions representing type classes dictionaries which
113+ -- can be evaluated at runtime. The constructor arguments represent (in order): the type class name and
114+ -- instance type, and the type class dictionaries in scope.
115+ --
116+ | TypeClassDictionary (Qualified ProperName, [Type]) [TypeClassDictionaryInScope] deriving (Show, Data, Typeable)
117+
118+-- |
119+-- An alternative in a case statement
120+--
121+data CaseAlternative = CaseAlternative
122+ { -- |
123+ -- A collection of binders with which to match the inputs
124+ --
125+ caseAlternativeBinders :: [Binder]
126+ -- |
127+ -- An optional guard
128+ --
129+ , caseAlternativeGuard :: Maybe Guard
130+ -- |
131+ -- The result expression
132+ --
133+ , caseAlternativeResult :: Value
134+ } deriving (Show, Data, Typeable)
135+
136+-- |
137+-- Data representing a type class dictionary which is in scope
138+--
139+data TypeClassDictionaryInScope
140+ = TypeClassDictionaryInScope {
141+ -- |
142+ -- The identifier with which the dictionary can be accessed at runtime
143+ --
144+ tcdName :: Qualified Ident
145+ -- |
146+ -- The name of the type class to which this type class instance applies
147+ --
148+ , tcdClassName :: Qualified ProperName
149+ -- |
150+ -- The types to which this type class instance applies
151+ --
152+ , tcdInstanceTypes :: [Type]
153+ -- |
154+ -- Type class dependencies which must be satisfied to construct this dictionary
155+ --
156+ , tcdDependencies :: Maybe [(Qualified ProperName, [Type])]
157+ -- |
158+ -- The type of this dictionary
159+ --
160+ , tcdType :: TypeClassDictionaryType
161+ } deriving (Show, Data, Typeable)
162+
163+-- |
164+-- The type of a type class dictionary
165+--
166+data TypeClassDictionaryType
167+ -- |
168+ -- A regular type class dictionary
169+ --
170+ = TCDRegular
171+ -- |
172+ -- A type class dictionary which is an alias for an imported dictionary from another module
173+ --
174+ | TCDAlias (Qualified Ident) deriving (Show, Eq, Data, Typeable)
175+
176+-- |
177+-- A statement in a do-notation block
178+--
179+data DoNotationElement
180+ -- |
181+ -- A monadic value without a binder
182+ --
183+ = DoNotationValue Value
184+ -- |
185+ -- A monadic value with a binder
186+ --
187+ | DoNotationBind Binder Value
188+ -- |
189+ -- A let statement, i.e. a pure value with a binder
190+ --
191+ | DoNotationLet Binder Value deriving (Show, Data, Typeable)
192+
193+-- |
194+-- Data type for binders
195+--
196+data Binder
197+ -- |
198+ -- Wildcard binder
199+ --
200+ = NullBinder
201+ -- |
202+ -- A binder which matches a boolean literal
203+ --
204+ | BooleanBinder Bool
205+ -- |
206+ -- A binder which matches a string literal
207+ --
208+ | StringBinder String
209+ -- |
210+ -- A binder which matches a numeric literal
211+ --
212+ | NumberBinder (Either Integer Double)
213+ -- |
214+ -- A binder which binds an identifier
215+ --
216+ | VarBinder Ident
217+ -- |
218+ -- A binder which matches a data constructor
219+ --
220+ | ConstructorBinder (Qualified ProperName) [Binder]
221+ -- |
222+ -- A binder which matches a record and binds its properties
223+ --
224+ | ObjectBinder [(String, Binder)]
225+ -- |
226+ -- A binder which matches an array and binds its elements
227+ --
228+ | ArrayBinder [Binder]
229+ -- |
230+ -- A binder which matches an array and binds its head and tail
231+ --
232+ | ConsBinder Binder Binder
233+ -- |
234+ -- A binder which binds its input to an identifier
235+ --
236+ | NamedBinder Ident Binder deriving (Show, Data, Typeable)
237+
238+
239+-- |
240+-- Collect all names introduced in binders in an expression
241+--
242+binderNames :: (Data d) => d -> [Ident]
243+binderNames = everything (++) (mkQ [] go)
244+ where
245+ go (VarBinder ident) = [ident]
246+ go (NamedBinder ident _) = [ident]
247+ go _ = []
src/Tests.hsdeleted−141
@@ -1,141 +0,0 @@
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.nixdeleted−23
@@ -1,23 +0,0 @@
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.yamldeleted−24
@@ -1,24 +0,0 @@
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.godeleted−30
@@ -1,30 +0,0 @@
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-loaderdeleted−2
@@ -1,2 +0,0 @@
1−module $PROJECT/purescript-native/ffi-loader
2−
support/go.mod.outputdeleted−2
@@ -1,2 +0,0 @@
1−module $PROJECT/purescript-native/output
2−
support/go.mod.workingdeleted−1
@@ -1 +0,0 @@
1−module $PROJECT/example
test/Spec.hsdeleted−2
@@ -1,2 +0,0 @@
1−main :: IO ()
2−main = putStrLn "Test suite not yet implemented"
tests/Main.hsnew file+99
@@ -0,0 +1,99 @@
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, 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)
42+compile opts inputFiles = do
43+ modules <- readInput inputFiles
44+ case modules of
45+ Left parseError ->
46+ return (Left $ show parseError)
47+ Right ms ->
48+ case P.compile opts ms of
49+ Left typeError ->
50+ return (Left typeError)
51+ Right (js, _, _) ->
52+ return (Right js)
53+
54+assert :: P.Options -> [FilePath] -> (Either String String -> IO (Maybe String)) -> IO ()
55+assert opts inputFiles f = do
56+ e <- compile opts inputFiles
57+ maybeErr <- f e
58+ case maybeErr of
59+ Just err -> putStrLn err >> exitFailure
60+ Nothing -> return ()
61+
62+assertCompiles :: FilePath -> IO ()
63+assertCompiles inputFile = do
64+ putStrLn $ "assert " ++ inputFile ++ " compiles successfully"
65+ prelude <- preludeFilename
66+ assert (P.defaultOptions { P.optionsMain = Just "Main", P.optionsModules = ["Main"] }) [prelude, inputFile] $ either (return . Just) $ \js -> do
67+ process <- findNodeProcess
68+ result <- traverse (\node -> readProcessWithExitCode node [] js) process
69+ case result of
70+ Just (ExitSuccess, out, _) -> putStrLn out >> return Nothing
71+ Just (ExitFailure _, _, err) -> return $ Just err
72+ Nothing -> return $ Just "Couldn't find node.js executable"
73+
74+findNodeProcess :: IO (Maybe String)
75+findNodeProcess = runMaybeT . msum $ map (MaybeT . findExecutable) names
76+ where names = ["nodejs", "node"]
77+
78+assertDoesNotCompile :: FilePath -> IO ()
79+assertDoesNotCompile inputFile = do
80+ putStrLn $ "assert " ++ inputFile ++ " does not compile"
81+ assert P.defaultOptions [inputFile] $ \e ->
82+ case e of
83+ Left _ -> return Nothing
84+ Right _ -> return $ Just "Should not have compiled"
85+
86+main :: IO ()
87+main = do
88+ cd <- getCurrentDirectory
89+ putStrLn cd
90+ let examples = cd ++ pathSeparator : "examples"
91+ let passing = examples ++ pathSeparator : "passing"
92+ passingTestCases <- getDirectoryContents passing
93+ forM_ passingTestCases $ \inputFile -> when (".purs" `isSuffixOf` inputFile) $
94+ assertCompiles (passing ++ pathSeparator : inputFile)
95+ let failing = examples ++ pathSeparator : "failing"
96+ failingTestCases <- getDirectoryContents failing
97+ forM_ failingTestCases $ \inputFile -> when (".purs" `isSuffixOf` inputFile) $
98+ assertDoesNotCompile (failing ++ pathSeparator : inputFile)
99+ exitSuccess