git.iko.soy/rowtype-yoga/purescript-native
on bd188c8 help sign in
24 files changed+535−716
since splitsnapshots
unifiedsplit
.gitignore+2−2 README-go.md−48 README.md+54−25 app/Main.hs+47−162 default.nix−23 package.yaml+5−6 psgo.cabal−145 runtime/purescript.go+54 src/CodeGen/IL.hs+63−21 src/CodeGen/IL/Common.hs+27−40 src/CodeGen/IL/Optimizer.hs+22−21 src/CodeGen/IL/Optimizer/Common.hs+3−1 src/CodeGen/IL/Optimizer/Inliner.hs+17−33 src/CodeGen/IL/Optimizer/MagicDo.hs+1−1 src/CodeGen/IL/Optimizer/TCO.hs+5−9 src/CodeGen/IL/Printer.hs+31−100 src/Tests.hs+12−11 stack.nix+3−18 stack.yaml+65−15 support/Makefile+124 support/ffi-loader.go−30 support/go.mod.ffi-loader−2 support/go.mod.output−2 support/go.mod.working−1
.gitignore+2−2
@@ -12,12 +12,12 @@ cabal.sandbox.config
1212.test_modules/
1313bower_components/
1414node_modules
15+pscpp.cabal
16+psgo.cabal
1517tmp/
1618.stack-work/
17−stack.yaml.lock
1819output
1920examples/docs/docs/
2021core-tests/full-core-docs.md
2122.psc-ide-port
2223.vscode/
23−result
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+54−25
@@ -1,41 +1,70 @@
11[![PureScript](https://raw.githubusercontent.com/purescript/purescript/master/logo.png)](http://purescript.org)
22
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.
3+This is an experimental C++11 (or later) compiler backend for [PureScript](https://github.com/purescript/purescript). It attempts to generate "sane", debuggable, and portable C++ code as an intermediate language, which is then compiled to a native executable binary. This enables easy interoperability with existing C/C++ frameworks and libraries on a number of platforms.
44
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).
5+---
6+
7+### **Please note that this project supersedes [pure11](https://github.com/pure11/pure11)**
8+
9+#### Please see [changes](https://github.com/andyarvanitis/purescript-native/wiki/changes) for more details.
10+
11+---
612
713#### 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`
14+* Generated C++ code and resulting binary executables tested (to at least some extent) on:
15+ * macOS Mojave, Xcode 10.1's clang (full test suite)
16+ * Windows 10 x64 and x86, Visual Studio 2017
17+ * Linux Debian 9.5 amd64, default versions of clang and gcc/g++ (full test suite)
18+ * Raspberry Pi 3 B+ Raspbian official build (ARM), default versions of clang and gcc/g++
19+
20+#### Performance
21+
22+* No runtime system beyond some support classes and the standard C++11 (or later) runtime library
23+* For automatic memory management, uses native C++11 reference counting (`std::shared_ptr`)
24+* Uses PureScript's normal tail call optimization techniques for generated C++ code
25+
26+#### Differences from PureScript:
27+
28+* Foreign imports/exports are C++ instead of JavaScript – see [FFI notes](https://github.com/andyarvanitis/purescript-native/wiki/FFI) and [standard library foreign implementations](https://github.com/andyarvanitis/purescript-native-ffi)
29+* No C++-specific REPL
30+
31+#### Other notes:
32+
33+* PureScript arrays are implemented using [`std::vector`](http://en.cppreference.com/w/cpp/container/vector)
34+* `String` types are implemented with C++11 `u8` literals (UTF-8) and `std::string`
35+* `Number` is C++ `double`, `Int` is C++ `int`, `Char` is `std::string` (single UTF-8 entity), `Boolean` is `bool`
36+
37+#### Future ideas:
38+
39+* Nice facilities (modules) for concurrency/parallelism, using `std::thread`, `std::async`, etc. under the hood (output is already generally thread-safe for immutable values, thanks to `std::shared_ptr`)
40+
41+#### Requirements for building the compiler itself
42+
43+* [Haskell Stack](https://docs.haskellstack.org/en/stable/README/) (if you're running macOS 10.13+, you can use pre-built binaries from [here](https://github.com/andyarvanitis/purescript-native/releases/))
44+
45+#### Requirements for using it
46+
47+* A recent version (0.12+) of [purescript](https://github.com/purescript/purescript/releases).
2048
49+* A C++11-capable toolchain, e.g. recent versions of clang, gcc, Microsoft Visual Studio
50+* GNU Make is the default supported build tool, but you should be able to use your favorite C++ build system, tools, debuggers, etc.
2151
22−#### Requirements for building `pscpp` and `psgo`
52+#### Getting Started
53+This assumes you are running macOS (OS X) or a Unix-like system (Linux, *BSD, etc.).
2354
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/))
55+1. Make sure you have developer tools for your system installed. For macOS, you'll need a recent version of Xcode. For Linux, etc., you can use clang 3.5 or later, or gcc/g++ 4.9.2 or later.
2556
26−#### Requirements for using PureScript + purescript-native
57+2. Create a working directory wherever you like, and a `src` subdirectory under it, which will be where you will place your own PureScript source files.
2758
28−* A recent version (0.13+) of [purescript](https://github.com/purescript/purescript/releases).
59+3. Under your working directory, also create an `ffi` subdirectory, which will be where you will place C/C++ FFI source files. You should at least add the contents of [purescript-native-ffi](https://github.com/andyarvanitis/purescript-native-ffi) into this directory, in addition to any of your own foreign implementations.
2960
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.
61+4. Generate the default GNU `Makefile` in your working directory by running `pscpp --makefile`.
3462
63+5. Use PureScript's standard [`psc-package`](https://psc-package.readthedocs.io/en/latest/) utility to add and manage package dependencies.
3564
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)
65+6. You should now be ready to build a PureScript program:
66+ * As stated above, place your source file(s) in the working directory's `src` subdirectory and execute `make debug` or `make release`. If your build machine has multiple cores, you might want to append `-jN` to your *make* command, where `N` is the number of cores.
3967
68+ * This will generate the C++ source tree for your program and then build an executable binary. The resulting executable will be in the `bin` subdirectory under the output directory and called `main` (so `output/bin/main`, by default). Source files will be under `src` (`output/src/` by default).
4069
4170---
app/Main.hs+47−162
@@ -10,7 +10,7 @@ import Data.Aeson
1010import Data.Aeson.Types
1111import Data.Char
1212import Data.FileEmbed (embedFile)
13−import Data.List (delete, intercalate, isPrefixOf, nub, partition, (\\))
13+import Data.List (delete, isPrefixOf, partition)
1414import Data.Maybe
1515import Data.Monoid ((<>))
1616import Data.Version
@@ -19,10 +19,8 @@ import Control.Monad.Supply.Class
1919import Text.Printf
2020
2121import System.Environment
22−import System.Directory (createDirectoryIfMissing, doesDirectoryExist, doesFileExist, getCurrentDirectory, getModificationTime)
22+import System.Directory (createDirectoryIfMissing, doesDirectoryExist, doesFileExist, getModificationTime)
2323import System.FilePath ((</>), joinPath, splitDirectories, takeDirectory)
24−import System.FilePath.Find
25−import System.Process
2624
2725import Data.Text (Text)
2826import qualified Data.Text as T
@@ -31,8 +29,6 @@ import qualified Data.Text.Lazy as L
3129import qualified Data.Text.Lazy.Encoding as L
3230import qualified Data.ByteString as B
3331
34−import Development.GitRev
35−
3632import Language.PureScript.AST.Literals
3733import Language.PureScript.CoreFn
3834import Language.PureScript.CoreFn.FromJSON
@@ -43,8 +39,6 @@ import CodeGen.IL.Printer
4339
4440import Tests
4541
46−data Command = Build | Run (Maybe String)
47−
4842parseJson :: Text -> Value
4943parseJson text
5044 | Just fileJson <- decode . L.encodeUtf8 $ L.fromStrict text = fileJson
@@ -54,102 +48,43 @@ jsonToModule :: Value -> Module Ann
5448jsonToModule value =
5549 case parse moduleFromJSON value of
5650 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')
51+ _ -> error "failed"
7752
7853main :: IO ()
7954main = do
8055 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
56+ if null args
57+ then return ()
8658 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 ""
59+ let (opts, files) = partition (isPrefixOf "--") args
60+ opts' = (map . map) toLower opts
61+ if "--tests" `elem` opts'
62+ then runTests
9663 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 ()
64+ when ("--makefile" `elem` opts') $
65+ B.writeFile "Makefile" $(embedFile "support/Makefile")
66+ when ("--help" `elem` opts') $
67+ putStrLn help
68+ when (not $ null files) $ do
69+ let filepath = takeDirectory (head files)
70+ baseOutpath = joinPath $ (init $ splitDirectories filepath) ++ [outdir]
71+ writeRuntimeFiles baseOutpath
72+ Par.mapM (generateCode opts' baseOutpath) files
73+ return ()
74+ return ()
13975
14076generateCode :: [String] -> FilePath -> FilePath -> IO ()
14177generateCode opts baseOutpath jsonFile = do
14278 jsonModTime <- getModificationTime jsonFile
14379 let filepath = takeDirectory jsonFile
14480 dirparts = splitDirectories $ filepath
145− mname = last dirparts
81+ mname = (\c -> if c == '.' then '_' else c) <$> last dirparts
14682 basedir = joinPath $ init dirparts
147− mname' = T.pack mname
148− possibleFileName = basedir </> (T.unpack mname') </> implFileName mname'
149− exists <- doesFileExist possibleFileName
83+ possInterfaceFilename = basedir </> outdir </> mname </> interfaceFileName mname
84+ exists <- doesFileExist possInterfaceFilename
15085 if exists
15186 then do
152− modTime <- getModificationTime possibleFileName
87+ modTime <- getModificationTime possInterfaceFilename
15388 when (modTime < jsonModTime) $
15489 transpile opts baseOutpath jsonFile
15590 else transpile opts baseOutpath jsonFile
@@ -157,94 +92,44 @@ generateCode opts baseOutpath jsonFile = do
15792transpile :: [String] -> FilePath -> FilePath -> IO ()
15893transpile opts baseOutpath jsonFile = do
15994 jsonText <- T.decodeUtf8 <$> B.readFile jsonFile
160− project <- projectEnv
16195 let module' = jsonToModule $ parseJson jsonText
162− ((_, foreigns, asts, implHeader, implFooter), _) <- runSupplyT 5 (moduleToIL module' project)
163− let mn = moduleNameToIL' $ moduleName module'
96+ ((interface, foreigns, asts, implHeader, implFooter), _) <- runSupplyT 5 (moduleToIL module' Nothing)
97+ let mn = moduleNameToIL $ moduleName module'
16498 implementation = prettyPrintIL asts
16599 outpath = joinPath [baseOutpath, T.unpack mn]
100+ interfacePath = outpath </> interfaceFileName (T.unpack mn)
166101 implPath = outpath </> implFileName mn
102+ putStrLn interfacePath
167103 createDirectoryIfMissing True outpath
104+ B.writeFile interfacePath $ T.encodeUtf8 interface
168105 putStrLn implPath
169106 B.writeFile implPath $ T.encodeUtf8 (implHeader <> implementation <> implFooter)
170107
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
108+writeRuntimeFiles :: FilePath -> IO ()
109+writeRuntimeFiles baseOutpath = do
110+ createDirectoryIfMissing True $ baseOutpath </> "purescript"
111+ let runtimeSource = baseOutpath </> "purescript" </> "purescript.go"
112+ runtimeExists <- doesFileExist runtimeSource
113+ when (not runtimeExists) $ do
114+ B.writeFile runtimeSource $(embedFile "runtime/purescript.go")
204115
205−implFileName :: Text -> FilePath
206−implFileName mn = ((\c -> if c == '.' then '_' else c) <$> T.unpack mn) <> ".go"
116+outdir :: FilePath
117+outdir = "src"
118+
119+interfaceFileName :: String -> FilePath
120+interfaceFileName mn = mn <> ".go"
207121
208−projectEnv :: IO Text
209−projectEnv = do
210− T.pack . fromMaybe defaultProject <$> lookupEnv goproject
122+implFileName :: Text -> FilePath
123+implFileName mn = T.unpack $ mn <> ".go"
211124
212125help :: String
213126help = "Usage: psgo OPTIONS COREFN-FILES\n\
214− \ PureScript to native (via go) compiler\n\n\
127+ \ PureScript-to-go compiler\n\n\
215128 \Available options:\n\
216129 \ --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\
130+ \ --makefile Generate a GNU Makefile which can be used for compiling\n\
131+ \ a PureScript program and libraries to a native binary via\n\
132+ \ purs corefn output and C++\n\n\
221133 \ --tests Run test cases (under construction)\n\n\
222134 \See also:\n\
223135 \ 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−}
package.yaml+5−6
@@ -10,6 +10,7 @@ extra-source-files:
1010- README.md
1111- ChangeLog.md
1212- stack.yaml
13+- runtime/*
1314- support/*
1415
1516# Metadata used when publishing your package
@@ -24,7 +25,7 @@ description: Please see the README on Github at <https://github.com/andy
2425dependencies:
2526- base >= 4.7 && < 5
2627- bytestring >= 0.10.8.2 && < 0.11
27−- purescript
28+- purescript -any
2829- base-compat >=0.6.0
2930- protolude >=0.1.6
3031- text
@@ -36,11 +37,9 @@ dependencies:
3637- transformers >=0.3.0 && <0.6
3738- mtl >=2.1.0 && <2.3.0
3839- aeson >=1.0 && <1.5
39−- directory
40−- process
41−- file-embed
42−- filemanip
43−- gitrev
40+- directory -any
41+- process -any
42+- file-embed -any
4443
4544library:
4645 source-dirs: src
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
runtime/purescript.gonew file+54
@@ -0,0 +1,54 @@
1+package purescript
2+
3+//go:generate purs --version
4+
5+import "sync"
6+
7+type Any interface{}
8+
9+type Fn = func(Any) Any
10+type EffFn = func() Any
11+
12+type Once = sync.Once
13+
14+type IGNORE_UNUSED_RUNTIME = bool
15+
16+const Undefined = "undefined"
17+
18+func Apply(f Any, args ...Any) Any {
19+ result := f
20+ for _, arg := range args {
21+ fn, _ := result.(Fn)
22+ result = fn(arg)
23+ }
24+ return result
25+}
26+
27+func Run(f Any, args ...Any) Any {
28+ fn, _ := f.(EffFn)
29+ return fn()
30+}
31+
32+func Get(dict Any, key string) Any {
33+ d, _ := dict.(map[string]Any)
34+ return d[key]
35+}
36+
37+func SafeGet(dict map[string]Any, key string) Any {
38+ value, ok := dict[key]
39+ if !ok {
40+ panic("Foreign value '" + key + "' not defined")
41+ }
42+ return value
43+}
44+
45+func Contains(dict Any, key string) bool {
46+ d, _ := dict.(map[string]Any)
47+ _, found := d[key]
48+ return found
49+}
50+
51+func Length(arr Any) Any {
52+ a, _ := arr.([]Any)
53+ return len(a)
54+}
src/CodeGen/IL.hs+63−21
@@ -40,6 +40,7 @@ import CodeGen.IL.Optimizer
4040import CodeGen.IL.Printer
4141
4242data DeclType = ModuleDecl | LetDecl | RecLetDecl deriving (Eq)
43+data ImportType = Imported | Ignored
4344
4445-- | Generate code in the simplified intermediate representation for all declarations in a
4546-- module.
@@ -48,19 +49,24 @@ moduleToIL
4849 -- . (Monad m, MonadReader Options m, MonadSupply m, MonadError MultipleErrors m)
4950 . (Monad m, MonadSupply m)
5051 => Module Ann
51− -> Text
52+ -> Maybe AST
5253 -> m (Text, [Text], [AST], Text, Text)
53−moduleToIL (Module _ coms mn _ imps _ foreigns decls) project =
54+moduleToIL (Module _ coms mn _ imps _ foreigns decls) _ =
5455 do
55− ilDecls <- mapM (bindToIL ModuleDecl) decls
56+ let usedNames = concatMap getNames decls
57+ let mnLookup = renameImports usedNames imps
58+ imports <- traverse (importToIL Imported mnLookup) . (\\ (mn : C.primModules)) . (\\ [mn]) $ ordNub $ map snd imps
59+ ignoredImports <- traverse (importToIL Ignored mnLookup) . delete (ModuleName [ProperName C.prim]) . (\\ (mn : C.primModules)) $ ordNub $ map snd imps
60+ interfaceImport <- importToIL Imported (renameImports [] [(emptyAnn, mn)]) mn
61+ let decls' = renameModules mnLookup decls
62+ ilDecls <- mapM (bindToIL ModuleDecl) decls'
5663 optimized <- traverse (traverse (optimize modName')) ilDecls
5764 let optimized' = concat optimized
5865 values = annotValue <$> optimized'
5966 foreigns' = moduleIdentToIL <$> foreigns
6067 interface = interfaceSource modName values foreigns
61− imports = nub . concat $ importToIL <$> optimized'
62− implHeader = implHeaderSource modName imports project
63− implFooter = implFooterSource (runModuleName mn) foreigns
68+ implHeader = implHeaderSource modName (imports ++ ignoredImports) interfaceImport
69+ implFooter = implFooterSource modName foreigns
6470 return $ (interface, foreigns', optimized', implHeader, implFooter)
6571 where
6672 modName = moduleNameToIL mn
@@ -77,16 +83,55 @@ moduleToIL (Module _ coms mn _ imps _ foreigns decls) project =
7783 getNames (NonRec _ ident _) = [ident]
7884 getNames (Rec vals) = map (snd . fst) vals
7985
80− -- | Generates IL code for a module import
81− --
82− importToIL :: AST -> [Text]
83− importToIL = AST.everything (++) modRef
86+ -- | Creates alternative names for each module to ensure they don't collide
87+ -- with declaration names.
88+ renameImports :: [Ident] -> [(Ann, ModuleName)] -> M.Map ModuleName (Ann, ModuleName)
89+ renameImports = go M.empty
90+ where
91+ go :: M.Map ModuleName (Ann, ModuleName) -> [Ident] -> [(Ann, ModuleName)] -> M.Map ModuleName (Ann, ModuleName)
92+ go acc used ((ann, mn') : mns') =
93+ let mni = Ident $ runModuleName mn'
94+ in if mn' /= mn && mni `elem` used
95+ then let newName = freshModuleName 1 mn' used
96+ in go (M.insert mn' (ann, newName) acc) (Ident (runModuleName newName) : used) mns'
97+ else go (M.insert mn' (ann, mn') acc) used mns'
98+ go acc _ [] = acc
99+
100+ freshModuleName :: Integer -> ModuleName -> [Ident] -> ModuleName
101+ freshModuleName i mn'@(ModuleName pns) used =
102+ let newName = ModuleName $ init pns ++ [ProperName $ runProperName (last pns) <> "_" <> T.pack (show i)]
103+ in if Ident (runModuleName newName) `elem` used
104+ then freshModuleName (i + 1) mn' used
105+ else newName
106+
107+ -- | Generates IL code for a module import, binding the required module
108+ -- to the alternative
109+ importToIL :: ImportType -> M.Map ModuleName (Ann, ModuleName) -> ModuleName -> m Text
110+ importToIL t mnLookup mn' = do
111+ let ((_, _, _, _), mnSafe) = fromMaybe (internalError "Missing value in mnLookup") $ M.lookup mn' mnLookup
112+ mname = moduleNameToIL mnSafe
113+ pure $ case t of
114+ Imported -> "import \"" <> mname <> "\"\n"
115+ Ignored -> "type _ = " <> mname <> ".IGNORE_UNUSED_IMPORTS\n"
116+
117+ -- | Replaces the `ModuleName`s in the AST so that the generated code refers to
118+ -- the collision-avoiding renamed module imports.
119+ renameModules :: M.Map ModuleName (Ann, ModuleName) -> [Bind Ann] -> [Bind Ann]
120+ renameModules mnLookup binds =
121+ let (f, _, _) = everywhereOnValues id ilExpr goBinder
122+ in map f binds
84123 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 (=='_')
124+ ilExpr :: Expr a -> Expr a
125+ ilExpr (Var ann q) = Var ann (renameQual q)
126+ ilExpr e = e
127+ goBinder :: Binder a -> Binder a
128+ goBinder (ConstructorBinder ann q1 q2 bs) = ConstructorBinder ann (renameQual q1) (renameQual q2) bs
129+ goBinder b = b
130+ renameQual :: Qualified a -> Qualified a
131+ renameQual (Qualified (Just mn') a) =
132+ let (_,mnSafe) = fromMaybe (internalError "Missing value in mnLookup") $ M.lookup mn' mnLookup
133+ in Qualified (Just mnSafe) a
134+ renameQual q = q
90135
91136 -- |
92137 -- Generate code in the simplified intermediate representation for a declaration
@@ -137,7 +182,7 @@ moduleToIL (Module _ coms mn _ imps _ foreigns decls) project =
137182 updates <- mapM (sndM valueToIL) ps
138183 obj' <- freshName'
139184 let objVar = AST.Var Nothing obj'
140− copy = AST.VariableIntroduction Nothing obj' (Just $ copyDict obj)
185+ copy = AST.VariableIntroduction Nothing obj' (Just $ AST.App Nothing (AST.StringLiteral Nothing (mkString dictType)) [obj])
141186 assign (k, v) = AST.Assignment Nothing (accessorString k objVar) v
142187 sts = copy : (assign <$> updates) ++ [AST.Return Nothing objVar]
143188 return $ AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing sts)) []
@@ -201,7 +246,7 @@ moduleToIL (Module _ coms mn _ imps _ foreigns decls) project =
201246 -- | Generate code in the simplified intermediate representation for a reference to a
202247 -- variable that may have a qualified name.
203248 qualifiedToIL :: (a -> Ident) -> Qualified a -> AST
204− qualifiedToIL f (Qualified (Just (ModuleName mn')) a) | mn' == C.prim = AST.Var Nothing . moduleIdentToIL $ f a
249+ qualifiedToIL f (Qualified (Just (ModuleName [ProperName mn'])) a) | mn' == C.prim = AST.Var Nothing . moduleIdentToIL $ f a
205250 qualifiedToIL f (Qualified (Just mn') a) | mn /= mn' = AST.Indexer Nothing (AST.Var Nothing . moduleIdentToIL $ f a) (AST.Var Nothing (moduleNameToIL mn'))
206251 qualifiedToIL f (Qualified _ a) = AST.Indexer Nothing (AST.Var Nothing . moduleIdentToIL $ f a) (AST.Var Nothing "")
207252
@@ -228,7 +273,7 @@ moduleToIL (Module _ coms mn _ imps _ foreigns decls) project =
228273 go _ _ _ = internalError "Invalid arguments to bindersToIL"
229274
230275 failedPatternMessage :: Text
231− failedPatternMessage = "Failed pattern match at " <> runModuleName mn <> " " <> displayStartEndPos ss
276+ failedPatternMessage = "Failed pattern match at " <> runModuleName mn <> " " <> displayStartEndPos ss <> ": "
232277
233278 guardsToIL :: Either [(Guard Ann, Expr Ann)] (Expr Ann) -> m [AST]
234279 guardsToIL (Left gs) = traverse genGuard gs where
@@ -316,6 +361,3 @@ emptyAnn = (SourceSpan "" (SourcePos 0 0) (SourcePos 0 0), [], Nothing, Nothing)
316361arrayLength :: AST -> AST
317362arrayLength a = AST.App Nothing (AST.Var Nothing arrayLengthFn) [a]
318363-- 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.hs+27−40
@@ -16,12 +16,13 @@ import Language.PureScript.Names
1616import qualified Language.PureScript.Constants as C
1717
1818moduleNameToIL :: ModuleName -> Text
19−moduleNameToIL (ModuleName mn) =
20− let name = T.replace "." "_" mn
21− in if nameIsILBuiltIn name then (name <> moduleRenamerMarker) else name
19+moduleNameToIL (ModuleName pns) =
20+ let name = T.intercalate "_" (runProperName `map` pns)
21+ in moduleNameToIL' name
2222
23−moduleNameToIL' :: ModuleName -> Text
24−moduleNameToIL' (ModuleName mn) = T.replace "_" "." mn
23+moduleNameToIL' :: Text -> Text
24+moduleNameToIL' name =
25+ if moduleIsReserved name then (name <> "_") else name
2526
2627-- | Convert an 'Ident' into a valid IL identifier:
2728--
@@ -32,7 +33,7 @@ moduleNameToIL' (ModuleName mn) = T.replace "_" "." mn
3233identToIL :: Ident -> Text
3334identToIL UnusedIdent = unusedName
3435identToIL (Ident "$__unused") = unusedName
35−identToIL (Ident name) | name == C.undefined = undefinedName -- Note: done in Printer.hs too
36+identToIL (Ident name) | name == C.undefined = undefinedName
3637identToIL (Ident name) = properToIL name
3738identToIL (GenIdent _ _) = internalError "GenIdent in identToIL"
3839
@@ -50,17 +51,16 @@ unusedName = "_"
5051
5152properToIL :: Text -> Text
5253properToIL name
53− | nameIsILReserved name = "ˉ" <> name
54+ | nameIsILReserved name || nameIsILBuiltIn name || prefixIsReserved name = name <> "ˉ"
5455 | otherwise = T.concatMap identCharToText name
5556
5657-- | Attempts to find a human-readable name for a symbol, if none has been specified returns the
5758-- ordinal value.
5859identCharToText :: Char -> Text
59−identCharToText 'ṩ' = "_ṩ"
6060identCharToText c | isAlphaNum c = T.singleton c
6161identCharToText '_' = "_"
62−identCharToText '\'' = "ꞌ" -- lowercase saltillo
63−identCharToText c = error (show (ord c)) -- TODO: should never occur now(?)
62+identCharToText '\'' = "ʹ"
63+identCharToText c = "ᵤ" <> T.pack (show (ord c))
6464
6565moduleProperToIL :: Text -> Text
6666moduleProperToIL = T.concatMap identCharToText
@@ -74,21 +74,7 @@ nameIsILReserved name =
7474nameIsILBuiltIn :: Text -> Bool
7575nameIsILBuiltIn name =
7676 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"
77+ [
9278 ]
9379
9480ilAnyReserved :: [Text]
@@ -127,6 +113,16 @@ ilKeywords =
127113 , "var"
128114 ]
129115
116+moduleIsReserved :: Text -> Bool
117+moduleIsReserved "Main" = False
118+moduleIsReserved name = not $ T.isInfixOf "_" name
119+
120+prefixIsReserved :: Text -> Bool
121+prefixIsReserved name =
122+ any (`T.isPrefixOf` name)
123+ [
124+ ]
125+
130126ilLiterals :: [Text]
131127ilLiterals =
132128 [ "init"
@@ -152,19 +148,16 @@ ilLiterals =
152148 ]
153149
154150withPrefix :: Text -> Text
155−withPrefix s = "Ꞌ" <> s -- uppercase saltillo
151+withPrefix s = "PS__" <> s
156152
157153anyType :: Text
158154anyType = "Any"
159155
160156dictType :: Text
161−dictType = "Dict"
157+dictType = "map[string]Any"
162158
163159arrayType :: Text
164−arrayType = "[]" <> anyType
165−
166−uncurriedFnType :: Int -> Text
167−uncurriedFnType i = "Fn" <> (T.pack . show $ i)
160+arrayType = "[]Any"
168161
169162int :: Text
170163int = "int"
@@ -181,16 +174,10 @@ string = "string"
181174arrayLengthFn :: Text
182175arrayLengthFn = "Length"
183176
184−indexFn :: Text
185−indexFn = "Index"
186−
187−copyDictFn :: Text
188−copyDictFn = "CopyDict"
177+tcoLoop :: Text
178+tcoLoop = "ᵗᶜloop"
189179
190180freshName' :: MonadSupply m => m Text
191181freshName' = do
192182 name <- freshName
193− return $ T.replace "$" "ṩ" name
194−
195−moduleRenamerMarker :: Text
196−moduleRenamerMarker = "__"
183+ return $ T.replace "$" "ᵗ" name
src/CodeGen/IL/Optimizer.hs+22−21
@@ -11,7 +11,7 @@ import Language.PureScript.CoreImp.Optimizer.Common hiding (isDict)
1111import Language.PureScript.CoreImp.Optimizer.Inliner (etaConvert, evaluateIifes, inlineVariables, unThunk)
1212import Language.PureScript.CoreImp.Optimizer.Unused
1313
14−import CodeGen.IL.Common (unusedName)
14+import CodeGen.IL.Common (moduleNameToIL', undefinedName, unusedName)
1515import CodeGen.IL.Optimizer.Inliner
1616import CodeGen.IL.Optimizer.MagicDo
1717import CodeGen.IL.Optimizer.TCO
@@ -21,19 +21,23 @@ import qualified Language.PureScript.Constants as C
2121-- | Apply a series of optimizer passes to simplified IL code
2222optimize :: MonadSupply m => AST -> AST -> m AST
2323optimize mn il = do
24− il' <- untilFixedPoint (inlineFnComposition . inlineUnsafeCoerce . inlineUnsafePartial . tidyUp) il
25− il'' <- untilFixedPoint (return . ignoreUnusedResults . inlineCommonValues . inlineCommonOperators . tidyUp) . tco mn . inlineST
24+ il' <- untilFixedPoint (inlineFnComposition . inlineUnsafeCoerce . inlineUnsafePartial . tidyUp . applyAll
25+ [ inlineCommonValues
26+ , inlineCommonOperators
27+ ]) il
28+ untilFixedPoint (return . tidyUp) . tco mn . inlineST
2629 =<< untilFixedPoint (return . magicDoST)
2730 =<< untilFixedPoint (return . magicDoEff)
2831 =<< untilFixedPoint (return . magicDoEffect) il'
29− untilFixedPoint (return . collapseVarDeclarations) il''
3032 where
3133 tidyUp :: AST -> AST
3234 tidyUp = applyAll
3335 [ collapseNestedBlocks
3436 , collapseNestedIfs
3537 , collapseIfChecks
38+ , ignoreUnusedResults
3639 , removeCodeAfterReturnStatements
40+ -- , removeUndefinedApp
3741 , unThunk
3842 , etaConvert
3943 , evaluateIifes
@@ -47,6 +51,18 @@ untilFixedPoint f = go
4751 a' <- f a
4852 if a' == a then return a' else go a'
4953
54+-- | Overridden from CoreImp
55+
56+-- inlineApply :: AST -> AST
57+-- inlineApply = everywhereTopDown convert where
58+-- convert (App ss (App _ (Indexer _ (Var _ apply) (Var _ dataFunction)) [ f ]) [ arg ])
59+-- | apply == C.apply && dataFunction == C.dataFunction
60+-- = App ss f [ arg ]
61+-- convert (App ss (App _ (Indexer _ (Var _ applyFlipped) (Var _ dataFunction)) [ arg ]) [ f ])
62+-- | applyFlipped == C.applyFlipped && dataFunction == C.dataFunction
63+-- = App ss f [ arg ]
64+-- convert other = other
65+
5066collapseIfChecks :: AST -> AST
5167collapseIfChecks = everywhere collapse where
5268 collapse :: AST -> AST
@@ -55,27 +71,12 @@ collapseIfChecks = everywhere collapse where
5571 | prop == "otherwise" && val == "Data_Boolean" = exprs
5672 collapse exprs = exprs
5773
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
7074
7175ignoreUnusedResults :: AST -> AST
7276ignoreUnusedResults = everywhere $ removeFromBlock go
7377 where
7478 go :: [AST] -> [AST]
7579 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
80+ go (VariableIntroduction ss var s@(Just _) : sts)
81+ | not $ any (everything (||) (isUsed var)) sts = (VariableIntroduction ss unusedName s) : sts
8182 go (s:sts) = s : go sts
src/CodeGen/IL/Optimizer/Common.hs+3−1
@@ -8,9 +8,11 @@ import Data.Text (Text)
88import Language.PureScript.CoreImp.AST
99import Language.PureScript.PSString (PSString, decodeString)
1010
11+import CodeGen.IL.Common (moduleNameToIL')
12+
1113isDict :: (Text, PSString) -> AST -> Bool
1214isDict (moduleName, dictName) (Indexer _ (Var _ x) (Var _ y)) =
13− Just x == decodeString dictName && y == moduleName
15+ Just x == decodeString dictName && y == moduleNameToIL' moduleName
1416isDict _ _ = False
1517
1618isDict' :: [(Text, PSString)] -> AST -> Bool
src/CodeGen/IL/Optimizer/Inliner.hs+17−33
@@ -48,7 +48,7 @@ inlineCommonValues = everywhere convert
4848 | isDict boundedBoolean dict && isDict fnBottom fn = BooleanLiteral ss False
4949 | isDict boundedBoolean dict && isDict fnTop fn = BooleanLiteral ss True
5050 convert (App ss (App _ fn [dict]) [x])
51− | isDict ringInt dict && isDict fnNegate fn = Unary ss Negate (unbox x $ snd ringInt)
51+ | isDict ringInt dict && isDict fnNegate fn = Unary ss Negate x -- (unbox x $ snd ringInt)
5252 convert (App ss (App _ (App _ fn [dict]) [x]) [y])
5353 | isDict semiringInt dict && isDict fnAdd fn = intOp ss Add semiringInt x y
5454 | isDict semiringInt dict && isDict fnMultiply fn = intOp ss Multiply semiringInt x y
@@ -117,11 +117,12 @@ inlineCommonOperators = everywhereTopDown $ applyAll $
117117 , binary' C.dataIntBits C.xor BitwiseXor
118118 , binary' C.dataIntBits C.shl ShiftLeft
119119 , binary' C.dataIntBits C.shr ShiftRight
120+ , binary' C.dataIntBits C.zshr ZeroFillShiftRight
120121 , unary' C.dataIntBits C.complement BitwiseNot
121122
122123 , inlineNonClassFunction (isModFn (C.dataFunction, C.apply)) $ \f x -> App Nothing f [x]
123124 , inlineNonClassFunction (isModFn (C.dataFunction, C.applyFlipped)) $ \x f -> App Nothing f [x]
124− , inlineUnsafeIndex (isModFnWithDict (C.dataArray, C.unsafeIndex)) $ flip (Indexer Nothing)
125+ , inlineNonClassFunction (isModFnWithDict (C.dataArray, C.unsafeIndex)) $ flip (Indexer Nothing)
125126 ] ++
126127 [ fn | i <- [0..10], fn <- [ mkFn i, runFn i ] ] ++
127128 [ fn | i <- [0..10], fn <- [ mkEffFn C.controlMonadEffUncurried C.mkEffFn i, runEffFn C.controlMonadEffUncurried C.runEffFn i ] ] ++
@@ -136,10 +137,8 @@ inlineCommonOperators = everywhereTopDown $ applyAll $
136137 binary' :: Text -> PSString -> BinaryOperator -> AST -> AST
137138 binary' moduleName opString op = convert where
138139 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 (App ss (App _ fn [x]) [y]) | isDict (moduleName, opString) fn = Binary ss op (unbox x opString) (unbox y opString)
140141 convert other = other
141− mn :: PSString
142− mn = mkString moduleName
143142 unary :: (Text, PSString) -> (Text, PSString) -> UnaryOperator -> AST -> AST
144143 unary dicts@(_, d) fns op = convert where
145144 convert :: AST -> AST
@@ -178,21 +177,16 @@ inlineCommonOperators = everywhereTopDown $ applyAll $
178177 collectArgs _ _ _ = Nothing
179178
180179 isNFn :: Text -> Text -> Int -> AST -> Bool
181− isNFn expectMod prefix n (Indexer _ (Var _ name) (Var _ modName)) | modName == expectMod =
180+ isNFn expectMod prefix n (Indexer _ (StringLiteral _ name) (Var _ modName)) | modName == expectMod =
182181 name == fromString (T.unpack prefix <> show n)
183182 isNFn _ _ _ _ = False
184183
185184 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)
185+ runFn = runFn' C.dataFunctionUncurried C.runFn App
186+
192187 runEffFn :: Text -> Text -> Int -> AST -> AST
193188 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)])
189+ Function ss Nothing [] (Block ss [Return ss (App ss fn acc)])
196190
197191 runFn' :: Text -> Text -> (Maybe SourceSpan -> AST -> [AST] -> AST) -> Int -> AST -> AST
198192 runFn' modName runFnName res n = convert where
@@ -211,23 +205,14 @@ inlineCommonOperators = everywhereTopDown $ applyAll $
211205 convert (App _ (App _ op' [x]) [y]) | p op' = f x y
212206 convert other = other
213207
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−
223208 isModFn :: (Text, PSString) -> AST -> Bool
224− isModFn (m, op) (Indexer _ (Var _ op') (Var _ m')) =
225− m == m' && decodeString op == Just op'
209+ isModFn (m, op) (Indexer _ (StringLiteral _ op') (Var _ m')) =
210+ m == m' && op == op'
226211 isModFn _ _ = False
227212
228213 isModFnWithDict :: (Text, PSString) -> AST -> Bool
229− isModFnWithDict (m, op) (App _ (Indexer _ (Var _ op') (Var _ m')) [Var _ _]) =
230− m == m' && decodeString op == Just op'
214+ isModFnWithDict (m, op) (App _ (Indexer _ (StringLiteral _ op') (Var _ m')) [Var _ _]) =
215+ m == m' && op == op'
231216 isModFnWithDict _ _ = False
232217
233218-- (f <<< g $ x) = f (g x)
@@ -280,12 +265,11 @@ inlineUnsafeCoerce = everywhereTopDown convert where
280265
281266inlineUnsafePartial :: AST -> AST
282267inlineUnsafePartial = 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)
268+ convert (App ss (Indexer _ (Var _ unsafePartial) (Var _ partialUnsafe)) [ comp ])
269+ | unsafePartial == C.unsafePartial && partialUnsafe == C.partialUnsafe
270+ -- Apply to undefined here, the application should be optimized away
271+ -- if it is safe to do so
272+ = App ss comp [ Var ss undefinedName ]
289273 convert other = other
290274
291275semiringNumber :: forall a b. (IsString a, IsString b) => (a, b)
src/CodeGen/IL/Optimizer/MagicDo.hs+1−1
@@ -13,7 +13,7 @@ import Language.PureScript.CoreImp.Optimizer.Common hiding (isDict)
1313import Language.PureScript.PSString (PSString, decodeString, mkString)
1414import qualified Language.PureScript.Constants as C
1515
16−import CodeGen.IL.Common (undefinedName, unusedName)
16+import CodeGen.IL.Common (moduleNameToIL', undefinedName, unusedName)
1717import CodeGen.IL.Optimizer.Common
1818
1919-- | Inline type class dictionaries for >>= and return for the Eff monad
src/CodeGen/IL/Optimizer/TCO.hs+5−9
@@ -1,4 +1,4 @@
1−module CodeGen.IL.Optimizer.TCO (tco, tcoLoop) where
1+module CodeGen.IL.Optimizer.TCO (tco) where
22
33import Prelude.Compat
44
@@ -11,22 +11,19 @@ import CodeGen.IL.Common
1111
1212import qualified Language.PureScript.Constants as C
1313
14−tcoLoop :: Text
15−tcoLoop = "ṩtco_loop"
16−
1714tco :: AST -> AST -> AST
1815tco mn = everywhere convert where
1916 tcoVar :: Text -> Text
20− tcoVar arg = "ṩtco_var_" <> arg
17+ tcoVar arg = "ᵗ" <> arg
2118
2219 copyVar :: Text -> Text
23− copyVar arg = "ṩcopy_" <> arg
20+ copyVar arg = "ᶜ" <> arg
2421
2522 tcoDone :: Text
26− tcoDone = "ṩtco_done"
23+ tcoDone = "ᵗᶜdone"
2724
2825 tcoResult :: Text
29− tcoResult = "ṩtco_result"
26+ tcoResult = "ᵗᶜresult"
3027
3128 convert :: AST -> AST
3229 convert fn@(Function ss (Just name) args _)
@@ -135,7 +132,6 @@ tco mn = everywhere convert where
135132
136133 isSelfCall :: Text -> AST -> Bool
137134 isSelfCall ident (App _ (Var _ ident') _) = ident == ident'
138− isSelfCall ident (App _ (Indexer _ (Var _ ident') (Var _ mn')) _) = mn' == "" && ident == ident'
139135 isSelfCall ident (App _ (Indexer _ (Var _ ident') mn') _) = mn' == mn && ident == ident'
140136 isSelfCall ident (App _ fn _) = isSelfCall ident fn
141137 isSelfCall _ _ = False
src/CodeGen/IL/Printer.hs+31−100
@@ -7,9 +7,6 @@ module CodeGen.IL.Printer
77 , implHeaderSource
88 , implFooterSource
99 , isLiteral
10− , modLabel
11− , modPrefix
12− , ffiLoader
1310 ) where
1411
1512import Prelude.Compat
@@ -33,9 +30,7 @@ import Language.PureScript.Crash
3330import Language.PureScript.Names (Ident, runIdent)
3431import Language.PureScript.Pretty.Common
3532import Language.PureScript.PSString (PSString, decodeString, mkString)
36−
3733import CodeGen.IL.Common
38−import CodeGen.IL.Optimizer.TCO (tcoLoop)
3934
4035import qualified Language.PureScript.Constants as C
4136
@@ -77,7 +72,6 @@ literals = mkPattern' match'
7772 , currentIndent
7873 , return $ emit "}"
7974 ]
80− match (Var _ ident) | ident == C.undefined = return $ emit undefinedName
8175 match (Var _ ident) = return $ emit ident
8276 match (VariableIntroduction _ ident value) = mconcat <$> sequence
8377 [ return . emit $ varDecl <> " " <> ident <> " " <> anyType
@@ -106,36 +100,12 @@ literals = mkPattern' match'
106100 , prettyPrintIL' arg
107101 , return $ emit ")"
108102 ]
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− ]
115103 match (App _ (Var _ fn) args) | fn == tcoLoop = mconcat <$> sequence
116104 [ return $ emit fn
117105 , return $ emit "("
118106 , intercalate (emit ", ") <$> forM args prettyPrintIL'
119107 , return $ emit ")"
120108 ]
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− ]
139109 match app@(App{})
140110 | (val, args) <- unApp app []
141111 , length args > 1
@@ -205,36 +175,15 @@ literals = mkPattern' match'
205175 , prettyPrintIL' (Var Nothing $ withPrefix name)
206176 , return $ emit "()"
207177 ]
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 ")["
178+ match (Indexer _ prop val) = mconcat <$> sequence
179+ [ return $ emit "Get("
180+ , prettyPrintIL' val
181+ , return $ emit ", "
219182 , 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 "]"
183+ , return $ emit ")"
235184 ]
236185 match (InstanceOf _ val ty) = mconcat <$> sequence
237− [ return $ emit "Is("
186+ [ return $ emit "Contains("
238187 , prettyPrintIL' val
239188 , return $ emit ", "
240189 , prettyPrintIL' ty
@@ -289,6 +238,8 @@ literals = mkPattern' match'
289238 -- match (Throw _ _) = return mempty
290239 match (Throw _ value) = mconcat <$> sequence
291240 [ return $ emit "panic("
241+ , return $ emit "\"PatternMatchFailure: \""
242+ , return $ emit " + "
292243 , prettyPrintIL' value
293244 , return $ emit ")"
294245 ]
@@ -396,7 +347,7 @@ prettyPrintIL' = A.runKleisli $ runPattern matchValue
396347 matchValue = buildPrettyPrinter operators (literals <+> fmap parensPos matchValue)
397348 operators :: (Emit gen) => OperatorTable PrinterState AST gen
398349 operators =
399− OperatorTable [ [ unary New "?" ]
350+ OperatorTable [ [ unary New "box" ]
400351 , [ unary Not "!"
401352 , unary BitwiseNot "~"
402353 , unary Positive "+"
@@ -407,7 +358,8 @@ prettyPrintIL' = A.runKleisli $ runPattern matchValue
407358 , [ binary Add "+"
408359 , binary Subtract "-" ]
409360 , [ binary ShiftLeft "<<"
410− , binary ShiftRight ">>" ]
361+ , binary ShiftRight ">>"
362+ , binary ZeroFillShiftRight ">>>" ]
411363 , [ binary LessThan "<"
412364 , binary LessThanOrEqualTo "<="
413365 , binary GreaterThan ">"
@@ -446,25 +398,19 @@ interfaceSource :: Text -> [(Text,Bool)] -> [Ident] -> Text
446398interfaceSource _ _ _ = ""
447399
448400implHeaderSource :: Text -> [Text] -> Text -> Text
449−implHeaderSource mn imports otherPrefix =
401+implHeaderSource mn imports _ =
450402 "// 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
403+ "package " <> (if mn == "Main" then "main" else mn) <> "\n\n" <>
404+ "import . \"purescript\"\n" <>
405+ (if mn == "Main"
406+ then "import \"ffi\"\n"
407+ else "") <>
408+ T.concat imports <> "\n" <>
409+ "type IGNORE_UNUSED_IMPORTS = bool\n" <>
410+ "type _ = IGNORE_UNUSED_RUNTIME\n" <>
411+ (if mn == "Main"
412+ then "\nconst _ = ffi.Loader\n\n"
413+ else "\n")
468414
469415implFooterSource :: Text -> [Ident] -> Text
470416implFooterSource mn foreigns =
@@ -472,7 +418,7 @@ implFooterSource mn foreigns =
472418 (if null foreigns
473419 then ""
474420 else ("// Foreign values\n\n" <>
475− "var " <> foreignDict <> " = "<> foreignMod <> "(\"" <> mn <> "\")\n\n" <>
421+ "var " <> foreignDict <> " = " <> dictType <> "{}\n\n" <>
476422 (T.concat $ (\foreign' ->
477423 let name = moduleIdentToIL foreign' in
478424 varDecl <> " " <> initName name <> " Once\n" <>
@@ -482,17 +428,17 @@ implFooterSource mn foreigns =
482428 "() Any { \n" <>
483429 " " <> initName name <> ".Do(func() {\n" <>
484430 " " <> valueName name <> " = " <>
485− "Get(" <> foreignDict <> ", " <>
486− (stringLiteral . mkString $ runIdent foreign') <> ")\n" <>
431+ "SafeGet(" <> foreignDict <> ", " <>
432+ (stringLiteral $ mkString name) <> ")\n" <>
487433 " })\n" <>
488434 " return " <> valueName name <> "\n" <>
489435 "}\n\n") <$> foreigns))) <>
490− if mn == "Main" || mn == "Test.Main" then mainSource else "\n"
436+ if mn == "Main" then mainSource else "\n"
491437 where
492438 mainSource :: Text
493439 mainSource = "\
494440 \func main() {\n\
495− \ Run(Ꞌmain())\n\
441+ \ Run(PS__main())\n\
496442 \}\n\n\
497443 \"
498444
@@ -502,26 +448,11 @@ varDecl = "var"
502448renderArg :: Text -> Text -> Text
503449renderArg decl arg = arg <> " " <> decl
504450
505−foreignMod :: Text
506−foreignMod = "Foreign"
507−
508451foreignDict :: 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"
452+foreignDict = "Foreign"
522453
523454initName :: Text -> Text
524−initName s = "ᛌ" <> s <> "_once"
455+initName s = "ₒ" <> s
525456
526457valueName :: Text -> Text
527−valueName s = "ᛧ" <> s
458+valueName s = "ₐ" <> s
src/Tests.hs+12−11
@@ -31,13 +31,18 @@ runTests = do
3131 let srcDir = outputDir </> "src"
3232 createDirectory srcDir
3333
34− callProcess "git" ["clone", "--branch", "v0.13.8", "--depth", "1", "https://github.com/purescript/purescript.git"]
34+ callProcess "git" ["clone", "--branch", "v0.13.0", "--depth", "1", "https://github.com/purescript/purescript.git"]
3535 let passingDir = baseDir </> "purescript" </> "tests" </> "purs" </> "passing"
3636 passingTestCases <- sort . filter (".purs" `isSuffixOf`) <$> getDirectoryContents passingDir
3737
3838 setCurrentDirectory outputDir
39+ callProcess "pscpp" ["--makefile"]
3940
4041 fetchPackages
42+ callProcess "git" ["clone", "--depth", "1", "https://github.com/andyarvanitis/purescript-cpp-ffi.git", "ffi"]
43+
44+ callProcess "rm" ["-rf", ".psc-package/psc-0.13.0/prelude/v4.1.0"]
45+ callProcess "git" ["clone", "--branch", "v4.1.1", "--depth", "1", "https://github.com/purescript/purescript-prelude.git", ".psc-package/psc-0.13.0/prelude/v4.1.0"]
4146
4247 let tests = filter (`notElem` skipped) passingTestCases
4348
@@ -60,15 +65,14 @@ runTests = do
6065 testCaseDirExists <- doesDirectoryExist testCaseDir
6166 when testCaseDirExists $ callProcess "cp" ["-R", testCaseDir, srcDir]
6267
63− callProcess "rm" ["-rf", "output"]
64− callProcess "rm" ["-rf", "Main"]
65− callProcess "spago" ["build"]
68+ callProcess "make" ["clean"]
69+ callProcess "make" ["debug", "-j8"]
6670 --
67− -- Run executable file
71+ -- Run C++ files
6872 --
6973 outputFile <- openFile (tmp </> logpath </> logfile) AppendMode
7074 hPutStrLn outputFile ("\n" ++ inputFile ++ ":")
71− proc <- runProcess ("./" </> "Main") [] Nothing Nothing Nothing (Just outputFile) Nothing
75+ proc <- runProcess ("output" </> "bin" </> "main") [] Nothing Nothing Nothing (Just outputFile) Nothing
7276
7377 removeFile (srcDir </> inputFile)
7478 when testCaseDirExists $ callProcess "rm" ["-rf", srcDir </> (takeWhile (/='.') inputFile)]
@@ -112,11 +116,8 @@ packages =
112116fetchPackages :: IO ()
113117-------------------------------------------------------------------------------
114118fetchPackages = 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
119+ callProcess "psc-package" ["init"]
120+ mapM (callProcess "psc-package" . (\p -> ["install", p])) packages
120121 return ()
121122
122123-------------------------------------------------------------------------------
stack.nix+3−18
@@ -1,23 +1,8 @@
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−}:
1+{ pkgs ? import <nixpkgs> {}, ghc ? pkgs.ghc }:
172
183pkgs.haskell.lib.buildStackProject {
194 name = "default-stack-shell";
20− ghc = pkgs.haskell.compiler.ghc865;
21− buildInputs = with pkgs; [git git-lfs gmp ncurses zlib];
5+ inherit ghc;
6+ buildInputs = with pkgs; [git git-lfs gmp zlib];
227 LANG = "en_US.UTF-8";
238}
stack.yaml+65−15
@@ -1,24 +1,74 @@
1−resolver: lts-13.26
1+# This file was automatically generated by 'stack init'
2+#
3+# Some commonly used options have been documented as comments in this file.
4+# For advanced use and comprehensive documentation of the format, please see:
5+# https://docs.haskellstack.org/en/stable/yaml_configuration/
26
7+# Resolver to choose a 'specific' stackage snapshot or a compiler version.
8+# A snapshot resolver dictates the compiler version and the set of packages
9+# to be used for project dependencies. For example:
10+#
11+# resolver: lts-3.5
12+# resolver: nightly-2015-09-21
13+# resolver: ghc-7.10.2
14+# resolver: ghcjs-0.1.0_ghc-7.10.2
15+# resolver:
16+# name: custom-snapshot
17+# location: "./custom-snapshot.yaml"
18+resolver: lts-13.12
19+
20+# User packages to be built.
21+# Various formats can be used as shown in the example below.
22+#
23+# packages:
24+# - some-directory
25+# - https://example.com/foo/bar/baz-0.0.2.tar.gz
26+# - location:
27+# git: https://github.com/commercialhaskell/stack.git
28+# commit: e7b331f14bcffb8367cd58fbfc8b40ec7642100a
29+# - location: https://github.com/commercialhaskell/stack/commit/e7b331f14bcffb8367cd58fbfc8b40ec7642100a
30+# extra-dep: true
31+# subdirs:
32+# - auto-update
33+# - wai
34+#
35+# A package marked 'extra-dep: true' will only be built if demanded by a
36+# non-dependency (i.e. a user package), and its test suites and benchmarks
37+# will not be run. This is useful for tweaking upstream packages.
338packages:
439- .
5−
40+# Dependency packages to be pulled from upstream that are not in the resolver
41+# (e.g., acme-missiles-0.3)
642extra-deps:
7−- git: https://github.com/purescript/purescript
8− commit: 9cad73ed8ea7df3011032ddbd2f3de5a0c08629c
9−- happy-1.19.9
10−- language-javascript-0.7.0.0
43+- git: https://github.com/purescript/purescript
44+ commit: 738aaa2f21097c7f18aa8100b16ae52316addb04
1145- network-3.0.1.1
12−- these-1.0.1
13−- semialign-1
46+- pipes-http-1.0.5
47+
48+# Override default flag values for local packages and extra-deps
49+# flags: {}
50+
51+# Extra package databases containing global packages
52+# extra-package-dbs: []
53+
54+# Control whether we use the GHC we find on the path
55+# system-ghc: true
56+#
57+# Require a specific version of stack, using version ranges
58+# require-stack-version: -any # Default
59+# require-stack-version: ">=1.6"
60+#
61+# Override the architecture used by stack, especially useful on Windows
62+# arch: i386
63+# arch: x86_64
64+#
65+# Extra directories used by stack for building
66+# extra-include-dirs: [/path/to/dir]
67+# extra-lib-dirs: [/path/to/dir]
68+#
69+# Allow a newer minor version of GHC than the snapshot specifies
70+# compiler-check: newer-minor
1471
1572nix:
16− enable: false
1773 shell-file: stack.nix
1874
19−flags:
20− aeson-pretty:
21− lib-only: true
22− these:
23− assoc: false
24− quickcheck: false
support/Makefilenew file+124
@@ -0,0 +1,124 @@
1+# PureScript to native binary (via C++) Makefile
2+#
3+# Run 'make' or 'make release' to build an optimized release build
4+# Run 'make debug' to build a non-optimized build suitable for debugging
5+#
6+# You can also perform a parallel build with 'make -jN', where N is the
7+# number of cores to use.
8+#
9+# PURS, SRC, OUTPUT, and BIN can all be overridden with the
10+# command itself. For example: 'make BIN=myutil'
11+#
12+# Flags can be added to either the codegen or native build phases.
13+# For example: 'make PURSFLAGS=--codegen,js CXXFLAGS=-DDEBUG LDFLAGS=lgmp'
14+#
15+# You can also edit the generated version of this file directly.
16+#
17+PURS := purs
18+PSC_PACKAGE := psc-package
19+PSGO := psgo
20+SRC := src
21+OUTPUT := output
22+CC_SRC := $(OUTPUT)/src
23+FFI_SRC := ffi
24+BIN := main
25+
26+override PURSFLAGS += compile --codegen corefn
27+override CXXFLAGS += --std=c++11
28+
29+DEBUG := "-DDEBUG -g"
30+RELEASE := "-DNDEBUG -O3"
31+
32+INCLUDES := -I $(CC_SRC)
33+BIN_DIR := $(OUTPUT)/bin
34+
35+PACKAGE_SOURCES = $(subst \,/,$(shell $(PSC_PACKAGE) sources))
36+PURESCRIPT_PKGS := $(firstword $(subst /, ,$(PACKAGE_SOURCES)))
37+
38+## Not all environments support globstar (** dir pattern)
39+rwildcard=$(wildcard $1$2) $(foreach d,$(wildcard $1*),$(call rwildcard,$d/,$2))
40+
41+unspecified:
42+ @echo
43+ @echo "Please specify the type of build you want: 'debug' or 'release'"
44+ @echo
45+ @echo " debug => not optimized (your app will run slower), good for"
46+ @echo " running in a source-level debugger, more (descriptive)"
47+ @echo " runtime exceptions"
48+ @echo
49+ @echo " release => optimized (your app will run faster), less helpful when debugging"
50+ @echo
51+
52+debug: codegen
53+ go build -o $(BIN_DIR)/$(BIN) $(BIN)
54+
55+release: codegen
56+ go build -o $(BIN_DIR)/$(BIN) $(BIN)
57+
58+.PHONY: corefn
59+corefn: PURESCRIPT_PKG_SRCS=$(foreach d,$(PACKAGE_SOURCES),$(call rwildcard,$(firstword $(subst *, ,$(d))),*.purs))
60+corefn: PURESCRIPT_SRCS=$(call rwildcard,$(SRC)/,*.purs)
61+corefn: $(PURESCRIPT_PKGS)
62+ @$(PURS) $(PURSFLAGS) --output $(OUTPUT) $(PURESCRIPT_PKG_SRCS) $(PURESCRIPT_SRCS)
63+
64+.PHONY: codegen
65+codegen: COREFN_SRCS=$(call rwildcard,$(OUTPUT)/,corefn.json)
66+codegen: corefn
67+ @$(PSGO) $(PSGOFLAGS) $(COREFN_SRCS)
68+
69+$(PURESCRIPT_PKGS):
70+ @echo "Getting packages using" $(PSC_PACKAGE) "..."
71+ @$(PSC_PACKAGE) update
72+
73+SRCS := $(call rwildcard,$(CC_SRC)/,*.cpp)
74+SRCS += $(call rwildcard,$(FFI_SRC)/,*.cpp)
75+SRCS += $(call rwildcard,$(FFI_SRC)/,*.cc)
76+SRCS += $(call rwildcard,$(FFI_SRC)/,*.mm)
77+SRCS += $(call rwildcard,$(FFI_SRC)/,*.c)
78+SRCS += $(call rwildcard,$(FFI_SRC)/,*.m)
79+
80+OBJS1 = $(SRCS:.cpp=.o)
81+OBJS2 = $(OBJS1:.cc=.o)
82+OBJS3 = $(OBJS2:.mm=.o)
83+OBJS4 = $(OBJS3:.c=.o)
84+OBJS = $(OBJS4:.m=.o)
85+DEPS = $(OBJS:.o=.d)
86+
87+$(BIN): $(OBJS)
88+ @echo "Linking" $(BIN_DIR)/$(BIN)
89+ @mkdir -p $(BIN_DIR)
90+ @$(CXX) $^ -o $(BIN_DIR)/$@ $(LDFLAGS)
91+
92+-include $(DEPS)
93+
94+%.o: %.cpp
95+ @echo "Creating" $@ "(C++)"
96+ @$(CXX) $(CXXFLAGS) $(INCLUDES) -MMD -MP -c $< -o $@
97+
98+%.o: %.cc
99+ @echo "Creating" $@ "(C++)"
100+ @$(CXX) $(CXXFLAGS) $(INCLUDES) -MMD -MP -c $< -o $@
101+
102+%.o: %.mm
103+ @echo "Creating" $@ "(Objective-C++)"
104+ @$(CXX) $(CXXFLAGS) $(INCLUDES) -MMD -MP -c $< -o $@
105+
106+%.o: %.c
107+ @echo "Creating" $@ "(C)"
108+ @$(CXX) $(CFLAGS) $(INCLUDES) -MMD -MP -c $< -o $@
109+
110+%.o: %.m
111+ @echo "Creating" $@ "(Objective-C)"
112+ @$(CXX) $(CFLAGS) $(INCLUDES) -MMD -MP -c $< -o $@
113+
114+.PHONY: all
115+all: release
116+
117+.PHONY: clean
118+clean:
119+ @-rm -f $(OBJS) $(DEPS)
120+ @-rm -rf $(OUTPUT)
121+
122+.PHONY: run
123+run:
124+ @$(BIN_DIR)/$(BIN) $(ARGS)
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