on master help sign in
158 files changed+6659−2413
since splitsnapshots
unifiedsplit
.github/CONTRIBUTING.md+18−20 .github/PULL_REQUEST_TEMPLATE.md+18 .github/workflows/set-issue-expectations.yml+21 .github/workflows/set-pull-expectations.yml+19 .gitignore+1 .travis.yml+28 ContributorAgreement.pdf LICENSE+6−25 README.md+10−5 builder/src/BackgroundWriter.hs+42 builder/src/Build.hs+331−257 builder/src/Deps/Registry.hs+1−5 builder/src/Deps/Solver.hs+27−24 builder/src/Elm/Details.hs+100−65 builder/src/Elm/Outline.hs+103−15 builder/src/File.hs+20−3 builder/src/Generate.hs+7−7 builder/src/Http.hs+1−1 builder/src/Reporting.hs+15−12 builder/src/Reporting/Exit.hs+275−93 builder/src/Reporting/Exit/Help.hs+5−5 builder/src/Stuff.hs+8−9 cabal.config+2 compiler/src/AST/Canonical.hs+2−2 compiler/src/AST/Optimized.hs+9−9 compiler/src/AST/Source.hs+5−5 compiler/src/AST/Utils/Binop.hs+5−6 compiler/src/AST/Utils/Shader.hs+2 compiler/src/AST/Utils/Type.hs−1 compiler/src/Canonicalize/Environment.hs+50−20 compiler/src/Canonicalize/Environment/Dups.hs+1−1 compiler/src/Canonicalize/Environment/Foreign.hs+49−37 compiler/src/Canonicalize/Environment/Local.hs+5−5 compiler/src/Canonicalize/Expression.hs+6−7 compiler/src/Canonicalize/Module.hs+7−7 compiler/src/Canonicalize/Pattern.hs+3−2 compiler/src/Data/Name.hs+53−43 compiler/src/Data/Utf8.hs+5−3 compiler/src/Elm/Compiler/Imports.hs+3−3 compiler/src/Elm/Compiler/Type/Extract.hs+1−1 compiler/src/Elm/Constraint.hs+1−1 compiler/src/Elm/Interface.hs+3−3 compiler/src/Elm/Kernel.hs+9−9 compiler/src/Elm/Licenses.hs+25−25 compiler/src/Elm/ModuleName.hs+2−6 compiler/src/Elm/Package.hs+2−9 compiler/src/Elm/String.hs−1 compiler/src/Generate/Html.hs+11−10 compiler/src/Generate/JavaScript.hs+45−10 compiler/src/Generate/Mode.hs−1 compiler/src/Json/Decode.hs+3−3 compiler/src/Json/Encode.hs+4−3 compiler/src/Json/String.hs+1−2 compiler/src/Optimize/DecisionTree.hs+2−2 compiler/src/Optimize/Port.hs+1−1 compiler/src/Parse/Expression.hs+40−32 compiler/src/Parse/Module.hs+81−35 compiler/src/Parse/Pattern.hs+1−1 compiler/src/Parse/Primitives.hs+2−2 compiler/src/Parse/Space.hs+2−2 compiler/src/Parse/String.hs+2−2 compiler/src/Parse/Variable.hs+3−3 compiler/src/Reporting/Annotation.hs+1−1 compiler/src/Reporting/Doc.hs+14−20 compiler/src/Reporting/Error.hs+20−16 compiler/src/Reporting/Error/Canonicalize.hs+41−40 compiler/src/Reporting/Error/Docs.hs+2−2 compiler/src/Reporting/Error/Import.hs+1−1 compiler/src/Reporting/Error/Json.hs+16−4 compiler/src/Reporting/Error/Pattern.hs+2−2 compiler/src/Reporting/Error/Syntax.hs+1024−449 compiler/src/Reporting/Error/Type.hs+44−23 compiler/src/Reporting/Render/Code.hs+67−26 compiler/src/Reporting/Render/Type/Localizer.hs+5−5 compiler/src/Reporting/Result.hs+9−1 compiler/src/Type/Error.hs+14−123 compiler/src/Type/Solve.hs+7 compiler/src/Type/Unify.hs+5−11 docs/elm.json/application.md+2−2 docs/elm.json/package.md+1−1 upgrade-docs/0.16.md → docs/upgrade-instructions/0.16.md upgrade-docs/0.17.md → docs/upgrade-instructions/0.17.md upgrade-docs/0.18.md → docs/upgrade-instructions/0.18.md upgrade-docs/0.19.md → docs/upgrade-instructions/0.19.0.md docs/upgrade-instructions/0.19.1.md+60 upgrade-docs/earlier.md → docs/upgrade-instructions/earlier.md elm.cabal+10−6 hints/bad-recursion.md+133 hints/comparing-custom-types.md+98 hints/comparing-records.md+85 hints/implicit-casts.md+50 hints/import-cycles.md+184 hints/imports.md+126 hints/infinite-type.md+42 hints/init.md+55 hints/missing-patterns.md+139 hints/optimize.md+59 hints/port-modules.md+32 hints/recursive-alias.md+162 hints/repl.md+73 hints/shadowing.md+70 hints/tuples.md+19 hints/type-annotations.md+60 installers/README.md+32 installers/linux/Dockerfile+39 installers/linux/README.md+93 installers/mac/Distribution.xml+5−3 installers/mac/README.md+93 installers/mac/Resources/en.lproj/background.png installers/mac/Resources/en.lproj/conclusion.rtf+13−6 installers/mac/Resources/en.lproj/welcome.rtf+9−4 installers/mac/helper-scripts/elm-startup.sh+1−1 installers/mac/make-installer.sh+30−3 installers/npm/PUBLISHING.md+29−141 installers/npm/README.md+30−23 installers/npm/bin/elm+42−16 installers/npm/download.js+68−67 installers/npm/install.js+1−7 installers/npm/package.json+6−7 installers/npm/troubleshooting.md+76 installers/win/Nsisfile.nsi+16−16 installers/win/README.md+18−3 installers/win/file.ico installers/win/inst.dat+1−2 installers/win/logo.ico installers/win/uninst.dat+1−2 installers/win/welcome.bmp reactor/src/Index.elm+20−15 reactor/src/Index/Navigator.elm+1−1 roadmap.md+29 terminal/src/Terminal/Args.hs → terminal/impl/Terminal.hs+28−25 terminal/src/Terminal/Args/Chomp.hs → terminal/impl/Terminal/Chomp.hs+4−5 terminal/src/Terminal/Args/Error.hs → terminal/impl/Terminal/Error.hs+28−18 terminal/src/Terminal/Args/Helpers.hs → terminal/impl/Terminal/Helpers.hs+20−7 terminal/src/Terminal/Args/Internal.hs → terminal/impl/Terminal/Internal.hs+8−8 terminal/src/Bump.hs+3−1 terminal/src/Develop.hs+23−9 terminal/src/Develop/Generate/Index.hs+51−1 terminal/src/Develop/StaticFiles/Build.hs+7−5 terminal/src/Diff.hs+4−3 terminal/src/Init.hs+1−1 terminal/src/Install.hs+17−15 terminal/src/Main.hs+22−22 terminal/src/Make.hs+72−60 terminal/src/Publish.hs+33−18 terminal/src/Repl.hs+188−60 worker/elm.cabal+25−3 worker/elm.json+26 worker/nginx.conf+22 worker/outlines/compile/elm.json+32 worker/outlines/repl/elm.json+19 worker/src/Artifacts.hs+155 worker/src/Cors.hs+48 worker/src/Endpoint/Compile.hs+323 worker/src/Endpoint/Quotes.hs+114 worker/src/Endpoint/Repl.hs+244 worker/src/Errors.elm+217 worker/src/Main.hs+36−241
.github/CONTRIBUTING.md+18−20
@@ -4,10 +4,15 @@ Thanks helping with the development of Elm! This document describes the basic
44standards for opening pull requests and making the review process as smooth as
55possible.
66
7−## Licensing
87
9−You need to sign the [contributor agreement](ContributorAgreement.pdf)
10−and send it to <info@elm-lang.org> before opening your pull request.
8+## Expectations
9+
10+- Pull requests are reviewed in [batches](https://github.com/elm/expectations/blob/master/batching.md), so it can take some time to get a response.
11+- Smaller pull requests are easier to review. To fix nine typos, nine specific issues will always go faster than one big one. Learn why [here](https://github.com/elm/expectations/blob/master/small-pull-requests.md).
12+- Reviewers may not know as much as you about certain situations, so add links to supporting evidence for important claims, especially regarding standards for CSS, HTTP, URI, etc.
13+
14+Finally, please be patient with the core team. They are trying their best with limited resources!
15+
1116
1217## Style Guide
1318
@@ -17,27 +22,20 @@ and send it to <info@elm-lang.org> before opening your pull request.
1722[haskell]: https://gist.github.com/evancz/0a1f3717c92fe71702be
1823[js]: https://google.github.io/styleguide/javascriptguide.xml
1924
20−## Branches
2125
22− * [The master branch][master] is the home of the next release of the compiler
23− so new features and improvements get merged there. Most pull requests
24− should target this branch!
26+## Branches
2527
26− * [The stable branch][stable] is for tagging releases and critical bug fixes.
27− This branch is handy for folks who want to build the most recent public
28− release from source.
28+[The master branch][master] is the home of the next release of the compiler
29+so new features and improvements get merged there. Most pull requests
30+should target this branch!
2931
3032[master]: http://github.com/elm-lang/elm/tree/master
31−[stable]: http://github.com/elm-lang/elm/tree/stable
3233
33−If you are working on a fairly large feature, we will probably want to merge it
34−in as its own branch and do some testing before bringing it into the master
35−branch. This way we can keep releases of the master branch independent of new
36−features.
3734
38−Note that the master branch of the compiler should always be in sync with the
39−master branch of the [website][], and the stable branch of the compiler should
40−always be in sync with the stable branch of the [website][]. Make sure that
41−your changes maintain this compatibility.
35+## Licensing
36+
37+Nothing extra to do for this. The default on GitHub described [here](https://docs.github.com/en/github/site-policy/github-terms-of-service#6-contributions-under-repository-license) is that:
38+
39+> Whenever you add Content to a repository containing notice of a license, you license that Content under the same terms, and you agree that you have the right to license that Content under those terms. If you have a separate agreement to license that Content under different terms, such as a contributor license agreement, that agreement will supersede.
40+
4241
43−[website]: https://github.com/elm-lang/elm-lang.org
.github/PULL_REQUEST_TEMPLATE.mdnew file+18
@@ -0,0 +1,18 @@
1+
2+**Quick Summary:** ???
3+
4+
5+## SSCCE
6+
7+```elm
8+
9+```
10+
11+- **Elm:** ???
12+- **Browser:** ???
13+- **Operating System:** ???
14+
15+
16+## Additional Details
17+
18+???
.github/workflows/set-issue-expectations.ymlnew file+21
@@ -0,0 +1,21 @@
1+name: Set Issue Expectations
2+on:
3+ issues:
4+ types: [opened]
5+jobs:
6+ comment-on-issue:
7+ name: Comment On Issue
8+ runs-on: ubuntu-latest
9+ steps:
10+ - uses: actions/github@v1.0.0
11+ env:
12+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
13+ with:
14+ args: |
15+ comment "Thanks for reporting this! To set expectations:
16+
17+ - Issues are reviewed in [batches](https://github.com/elm/expectations/blob/master/batching.md), so it can take some time to get a response.
18+ - Ask questions in a [community forum](https://elm-lang.org/community). You will get an answer quicker that way!
19+ - If you experience something similar, open a new issue. [We like duplicates](https://github.com/elm/expectations/blob/master/duplicates.md).
20+
21+ Finally, please be patient with the core team. They are trying their best with limited resources."
.github/workflows/set-pull-expectations.ymlnew file+19
@@ -0,0 +1,19 @@
1+on:
2+ pull_request_target:
3+ types: [opened]
4+
5+jobs:
6+ comment-on-pull:
7+ name: Comment On Pull
8+ runs-on: ubuntu-latest
9+ steps:
10+ - uses: actions/github-script@v3
11+ with:
12+ github-token: ${{secrets.GITHUB_TOKEN}}
13+ script: |
14+ github.issues.createComment({
15+ issue_number: context.issue.number,
16+ owner: context.repo.owner,
17+ repo: context.repo.repo,
18+ body: "Thanks for suggesting these code changes. To set expectations:\n\n- Pull requests are reviewed in [batches](https://github.com/elm/expectations/blob/master/batching.md), so it can take some time to get a response.\n- Smaller pull requests are easier to review. To fix nine typos, nine specific issues will always go faster than one big one. Learn why [here](https://github.com/elm/expectations/blob/master/small-pull-requests.md).\n- Reviewers may not know as much as you about certain situations, so add links to supporting evidence for important claims, especially regarding standards for CSS, HTTP, URI, etc.\n\nFinally, please be patient with the core team. They are trying their best with limited resources."
19+ })
.gitignore+1
@@ -5,3 +5,4 @@ cabal-dev
55cabal.sandbox.config
66.DS_Store
77*~
8+travis.log
.travis.ymlnew file+28
@@ -0,0 +1,28 @@
1+language: minimal
2+services: docker
3+
4+env:
5+ global:
6+ - LINUX_ARCHIVE=binary-for-linux-64-bit.gz
7+
8+before_install:
9+ - docker build -t elm -f installers/linux/Dockerfile .
10+ - docker cp $(docker create elm):/usr/local/bin/elm .
11+ - gzip -9 -c elm > $LINUX_ARCHIVE
12+
13+deploy:
14+ provider: releases
15+ api_key:
16+ secure: Yz2Lo4u9rZQ7Ee7ohAsrZpkqsYDUerCSMdSQIH8ryrf7phHhiloPEkTKsM+NupHqU/LEAVsunxbau4QrCEjA2vPavAPVk8cKomRUWK/YjbXHKa24hPkal2c+A2bnMQ6w3qYk/PjL9rW+Goq++/SNLcYZwHBV0Chl2blivMwWCSA=
17+ file: $LINUX_ARCHIVE
18+ skip_cleanup: true
19+ on:
20+ branch: master
21+ tags: true
22+
23+notifications:
24+ email:
25+ recipients:
26+ - rlefevre@dmy.fr
27+ on_success: change
28+ on_failure: change
ContributorAgreement.pdfdeleted

Binary file not shown.

LICENSE+6−25
@@ -1,30 +1,11 @@
1−Copyright (c) 2012-present, Evan Czaplicki
1+Copyright 2012-present Evan Czaplicki
22
3−All rights reserved.
3+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
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+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
76
8− * Redistributions of source code must retain the above copyright
9− notice, this list of conditions and the following disclaimer.
7+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
108
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.
9+3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
1510
16− * Neither the name of Evan Czaplicki 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.
11+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
README.md+10−5
@@ -1,17 +1,22 @@
1−# The Elm Compiler
1+# Elm
22
3−Learn about the Elm programming language at [elm-lang.org](http://elm-lang.org/).
3+A delightful language for reliable webapps.
44
5+Check out the [Home Page](http://elm-lang.org/), [Try Online](http://elm-lang.org/try), or [The Official Guide](http://guide.elm-lang.org/)
6+
7+
8+<br>
59
610## Install
711
8−Follow [these instructions][installer]!
12+✨ [Install](https://guide.elm-lang.org/install/elm.html) ✨
913
10− [installer]: https://guide.elm-lang.org/install.html
14+For multiple versions, previous versions, and uninstallation, see the instructions [here](https://github.com/elm/compiler/blob/master/installers/README.md).
1115
16+<br>
1217
1318## Help
1419
1520If you are stuck, ask around on [the Elm slack channel][slack]. Folks are friendly and happy to help with questions!
1621
17−[slack]: http://elmlang.herokuapp.com/
22+[slack]: http://elmlang.herokuapp.com/
builder/src/BackgroundWriter.hsnew file+42
@@ -0,0 +1,42 @@
1+{-# LANGUAGE BangPatterns #-}
2+module BackgroundWriter
3+ ( Scope
4+ , withScope
5+ , writeBinary
6+ )
7+ where
8+
9+
10+import Control.Concurrent (forkIO)
11+import Control.Concurrent.MVar (MVar, newEmptyMVar, newMVar, putMVar, takeMVar)
12+import qualified Data.Binary as Binary
13+import Data.Foldable (traverse_)
14+
15+import qualified File
16+
17+
18+
19+-- BACKGROUND WRITER
20+
21+
22+newtype Scope =
23+ Scope (MVar [MVar ()])
24+
25+
26+withScope :: (Scope -> IO a) -> IO a
27+withScope callback =
28+ do workList <- newMVar []
29+ result <- callback (Scope workList)
30+ mvars <- takeMVar workList
31+ traverse_ takeMVar mvars
32+ return result
33+
34+
35+writeBinary :: (Binary.Binary a) => Scope -> FilePath -> a -> IO ()
36+writeBinary (Scope workList) path value =
37+ do mvar <- newEmptyMVar
38+ _ <- forkIO (File.writeBinary path value >> putMVar mvar ())
39+ oldWork <- takeMVar workList
40+ let !newWork = mvar:oldWork
41+ putMVar workList newWork
42+
builder/src/Build.hs+331−257
@@ -2,15 +2,15 @@
22{-# LANGUAGE BangPatterns, GADTs, OverloadedStrings #-}
33module Build
44 ( fromExposed
5− , fromMains
5+ , fromPaths
66 , fromRepl
77 , Artifacts(..)
8− , Main(..)
8+ , Root(..)
99 , Module(..)
1010 , CachedInterface(..)
1111 , ReplArtifacts(..)
1212 , DocsGoal(..)
13− , getMainNames
13+ , getRootNames
1414 )
1515 where
1616
@@ -20,7 +20,6 @@ import Control.Concurrent.MVar
2020import Control.Monad (filterM, mapM_, sequence_)
2121import qualified Data.ByteString as B
2222import qualified Data.Char as Char
23−import qualified Data.Either as Either
2423import qualified Data.Graph as Graph
2524import qualified Data.List as List
2625import qualified Data.Map.Utils as Map
@@ -43,6 +42,7 @@ import qualified Elm.Details as Details
4342import qualified Elm.Docs as Docs
4443import qualified Elm.Interface as I
4544import qualified Elm.ModuleName as ModuleName
45+import qualified Elm.Outline as Outline
4646import qualified Elm.Package as Pkg
4747import qualified File
4848import qualified Json.Encode as E
@@ -50,6 +50,7 @@ import qualified Parse.Module as Parse
5050import qualified Reporting
5151import qualified Reporting.Annotation as A
5252import qualified Reporting.Error as Error
53+import qualified Reporting.Error.Docs as EDocs
5354import qualified Reporting.Error.Syntax as Syntax
5455import qualified Reporting.Error.Import as Import
5556import qualified Reporting.Exit as Exit
@@ -65,27 +66,57 @@ data Env =
6566 Env
6667 { _key :: Reporting.BKey
6768 , _root :: FilePath
68− , _pkg :: Pkg.Name
69− , _srcDirs :: [FilePath]
69+ , _project :: Parse.ProjectType
70+ , _srcDirs :: [AbsoluteSrcDir]
71+ , _buildID :: Details.BuildID
7072 , _locals :: Map.Map ModuleName.Raw Details.Local
7173 , _foreigns :: Map.Map ModuleName.Raw Details.Foreign
7274 }
7375
7476
75−makeEnv :: Reporting.BKey -> FilePath -> Details.Details -> Env
76−makeEnv key root (Details.Details _ validOutline locals foreigns _) =
77+makeEnv :: Reporting.BKey -> FilePath -> Details.Details -> IO Env
78+makeEnv key root (Details.Details _ validOutline buildID locals foreigns _) =
7779 case validOutline of
78− Details.ValidApp srcDirs ->
79− Env key root Pkg.dummyName (NE.toList srcDirs) locals foreigns
80+ Details.ValidApp givenSrcDirs ->
81+ do srcDirs <- traverse (toAbsoluteSrcDir root) (NE.toList givenSrcDirs)
82+ return $ Env key root Parse.Application srcDirs buildID locals foreigns
8083
81− Details.ValidPkg pkg _ ->
82− Env key root pkg ["src"] locals foreigns
84+ Details.ValidPkg pkg _ _ ->
85+ do srcDir <- toAbsoluteSrcDir root (Outline.RelativeSrcDir "src")
86+ return $ Env key root (Parse.Package pkg) [srcDir] buildID locals foreigns
87+
88+
89+
90+-- SOURCE DIRECTORY
91+
92+
93+newtype AbsoluteSrcDir =
94+ AbsoluteSrcDir FilePath
95+
96+
97+toAbsoluteSrcDir :: FilePath -> Outline.SrcDir -> IO AbsoluteSrcDir
98+toAbsoluteSrcDir root srcDir =
99+ AbsoluteSrcDir <$> Dir.canonicalizePath
100+ (
101+ case srcDir of
102+ Outline.AbsoluteSrcDir dir -> dir
103+ Outline.RelativeSrcDir dir -> root </> dir
104+ )
105+
106+
107+addRelative :: AbsoluteSrcDir -> FilePath -> FilePath
108+addRelative (AbsoluteSrcDir srcDir) path =
109+ srcDir </> path
83110
84111
85112
86113-- FORK
87114
88115
116+-- PERF try using IORef semephore on file crawl phase?
117+-- described in Chapter 13 of Parallel and Concurrent Programming in Haskell by Simon Marlow
118+-- https://www.oreilly.com/library/view/parallel-and-concurrent/9781449335939/ch13.html#sec_conc-par-overhead
119+--
89120fork :: IO a -> IO (MVar a)
90121fork work =
91122 do mvar <- newEmptyMVar
@@ -106,7 +137,7 @@ forkWithKey func dict =
106137fromExposed :: Reporting.Style -> FilePath -> Details.Details -> DocsGoal docs -> NE.List ModuleName.Raw -> IO (Either Exit.BuildProblem docs)
107138fromExposed style root details docsGoal exposed@(NE.List e es) =
108139 Reporting.trackBuild style $ \key ->
109− do let env = makeEnv key root details
140+ do env <- makeEnv key root details
110141 dmvar <- Details.loadInterfaces root details
111142
112143 -- crawl
@@ -129,18 +160,18 @@ fromExposed style root details docsGoal exposed@(NE.List e es) =
129160 putMVar rmvar resultMVars
130161 results <- traverse readMVar resultMVars
131162 writeDetails root details results
132− finalizeExposed docsGoal exposed results
163+ finalizeExposed root docsGoal exposed results
133164
134165
135166
136−-- FROM MAINS
167+-- FROM PATHS
137168
138169
139170data Artifacts =
140171 Artifacts
141172 { _name :: Pkg.Name
142173 , _deps :: Dependencies
143− , _mains :: NE.List Main
174+ , _roots :: NE.List Root
144175 , _modules :: [Module]
145176 }
146177
@@ -154,25 +185,25 @@ type Dependencies =
154185 Map.Map ModuleName.Canonical I.DependencyInterface
155186
156187
157−fromMains :: Reporting.Style -> FilePath -> Details.Details -> NE.List FilePath -> IO (Either Exit.BuildProblem Artifacts)
158−fromMains style root details paths =
188+fromPaths :: Reporting.Style -> FilePath -> Details.Details -> NE.List FilePath -> IO (Either Exit.BuildProblem Artifacts)
189+fromPaths style root details paths =
159190 Reporting.trackBuild style $ \key ->
160− do let env = makeEnv key root details
191+ do env <- makeEnv key root details
161192
162− elmains <- findMains env paths
163− case elmains of
193+ elroots <- findRoots env paths
194+ case elroots of
164195 Left problem ->
165196 return (Left (Exit.BuildProjectProblem problem))
166197
167− Right lmains ->
198+ Right lroots ->
168199 do -- crawl
169200 dmvar <- Details.loadInterfaces root details
170201 smvar <- newMVar Map.empty
171− smainMVars <- traverse (fork . crawlMain env smvar) lmains
172− smains <- traverse readMVar smainMVars
202+ srootMVars <- traverse (fork . crawlRoot env smvar) lroots
203+ sroots <- traverse readMVar srootMVars
173204 statuses <- traverse readMVar =<< readMVar smvar
174205
175− midpoint <- checkMainsMidpoint dmvar statuses smains
206+ midpoint <- checkMidpointAndRoots dmvar statuses sroots
176207 case midpoint of
177208 Left problem ->
178209 return (Left (Exit.BuildProjectProblem problem))
@@ -182,24 +213,24 @@ fromMains style root details paths =
182213 rmvar <- newEmptyMVar
183214 resultsMVars <- forkWithKey (checkModule env foreigns rmvar) statuses
184215 putMVar rmvar resultsMVars
185− rmainMVars <- traverse (fork . checkMain env resultsMVars) smains
216+ rrootMVars <- traverse (fork . checkRoot env resultsMVars) sroots
186217 results <- traverse readMVar resultsMVars
187218 writeDetails root details results
188− toArtifacts env foreigns results <$> traverse readMVar rmainMVars
219+ toArtifacts env foreigns results <$> traverse readMVar rrootMVars
189220
190221
191222
192−-- GET MAIN NAMES
223+-- GET ROOT NAMES
193224
194225
195−getMainNames :: Artifacts -> NE.List ModuleName.Raw
196−getMainNames (Artifacts _ _ mains _) =
197− fmap getMainName mains
226+getRootNames :: Artifacts -> NE.List ModuleName.Raw
227+getRootNames (Artifacts _ _ roots _) =
228+ fmap getRootName roots
198229
199230
200−getMainName :: Main -> ModuleName.Raw
201−getMainName main =
202− case main of
231+getRootName :: Root -> ModuleName.Raw
232+getRootName root =
233+ case root of
203234 Inside name -> name
204235 Outside name _ _ -> name
205236
@@ -235,11 +266,10 @@ crawlDeps env mvar deps blockedValue =
235266
236267
237268crawlModule :: Env -> MVar StatusDict -> DocsNeed -> ModuleName.Raw -> IO Status
238−crawlModule env@(Env _ root pkg srcDirs locals foreigns) mvar docsNeed name =
269+crawlModule env@(Env _ root projectType srcDirs buildID locals foreigns) mvar docsNeed name =
239270 do let fileName = ModuleName.toFilePath name <.> "elm"
240− let inRoot path = File.exists (root </> path)
241271
242− paths <- filterM inRoot (map (</> fileName) srcDirs)
272+ paths <- filterM File.exists (map (`addRelative` fileName) srcDirs)
243273
244274 case paths of
245275 [path] ->
@@ -248,21 +278,18 @@ crawlModule env@(Env _ root pkg srcDirs locals foreigns) mvar docsNeed name =
248278 return $ SBadImport $ Import.Ambiguous path [] dep deps
249279
250280 Nothing ->
251− case Map.lookup name locals of
252− Nothing ->
253− crawlFile env mvar docsNeed name path
281+ do newTime <- File.getTime path
282+ case Map.lookup name locals of
283+ Nothing ->
284+ crawlFile env mvar docsNeed name path newTime buildID
254285
255− Just local@(Details.Local oldPath oldTime deps _) ->
256− if path /= oldPath
257− then crawlFile env mvar docsNeed name path
258− else
259− do newTime <- File.getTime path
260− if oldTime < newTime || needsDocs docsNeed
261− then crawlFile env mvar docsNeed name path
262− else crawlDeps env mvar deps (SCached local)
286+ Just local@(Details.Local oldPath oldTime deps _ lastChange _) ->
287+ if path /= oldPath || oldTime /= newTime || needsDocs docsNeed
288+ then crawlFile env mvar docsNeed name path newTime lastChange
289+ else crawlDeps env mvar deps (SCached local)
263290
264291 p1:p2:ps ->
265− return $ SBadImport $ Import.AmbiguousLocal p1 p2 ps
292+ return $ SBadImport $ Import.AmbiguousLocal (FP.makeRelative root p1) (FP.makeRelative root p2) (map (FP.makeRelative root) ps)
266293
267294 [] ->
268295 case Map.lookup name foreigns of
@@ -275,19 +302,18 @@ crawlModule env@(Env _ root pkg srcDirs locals foreigns) mvar docsNeed name =
275302 return $ SBadImport $ Import.AmbiguousForeign dep d ds
276303
277304 Nothing ->
278− if Name.isKernel name && Pkg.isKernel pkg then
305+ if Name.isKernel name && Parse.isKernel projectType then
279306 do exists <- File.exists ("src" </> ModuleName.toFilePath name <.> "js")
280307 return $ if exists then SKernel else SBadImport Import.NotFound
281308 else
282309 return $ SBadImport Import.NotFound
283310
284311
285−crawlFile :: Env -> MVar StatusDict -> DocsNeed -> ModuleName.Raw -> FilePath -> IO Status
286−crawlFile env@(Env _ root pkg _ _ _) mvar docsNeed expectedName path =
287− do time <- File.getTime path
288− source <- File.readUtf8 (root </> path)
312+crawlFile :: Env -> MVar StatusDict -> DocsNeed -> ModuleName.Raw -> FilePath -> File.Time -> Details.BuildID -> IO Status
313+crawlFile env@(Env _ root projectType _ buildID _ _) mvar docsNeed expectedName path time lastChange =
314+ do source <- File.readUtf8 (root </> path)
289315
290− case Parse.fromByteString pkg source of
316+ case Parse.fromByteString projectType source of
291317 Left err ->
292318 return $ SBadSyntax path time source err
293319
@@ -300,7 +326,7 @@ crawlFile env@(Env _ root pkg _ _ _) mvar docsNeed expectedName path =
300326 if expectedName == actualName then
301327 let
302328 deps = map Src.getImportName imports
303− local = Details.Local path time deps (any isMain values)
329+ local = Details.Local path time deps (any isMain values) lastChange buildID
304330 in
305331 crawlDeps env mvar deps (SChanged local source modul docsNeed)
306332 else
@@ -323,7 +349,7 @@ type ResultDict =
323349data Result
324350 = RNew !Details.Local !I.Interface !Opt.LocalGraph !(Maybe Docs.Module)
325351 | RSame !Details.Local !I.Interface !Opt.LocalGraph !(Maybe Docs.Module)
326− | RCached Bool (MVar CachedInterface)
352+ | RCached Bool Details.BuildID (MVar CachedInterface)
327353 | RNotFound Import.Problem
328354 | RProblem Error.Module
329355 | RBlocked
@@ -338,15 +364,15 @@ data CachedInterface
338364
339365
340366checkModule :: Env -> Dependencies -> MVar ResultDict -> ModuleName.Raw -> Status -> IO Result
341−checkModule env@(Env _ root pkg _ _ _) foreigns resultsMVar name status =
367+checkModule env@(Env _ root projectType _ _ _ _) foreigns resultsMVar name status =
342368 case status of
343− SCached local@(Details.Local path time deps hasMain) ->
369+ SCached local@(Details.Local path time deps hasMain lastChange lastCompile) ->
344370 do results <- readMVar resultsMVar
345− depsStatus <- checkDeps root results deps
371+ depsStatus <- checkDeps root results deps lastCompile
346372 case depsStatus of
347373 DepsChange ifaces ->
348374 do source <- File.readUtf8 path
349− case Parse.fromByteString pkg source of
375+ case Parse.fromByteString projectType source of
350376 Right modul -> compile env (DocsNeed False) local source ifaces modul
351377 Left err ->
352378 return $ RProblem $
@@ -354,7 +380,7 @@ checkModule env@(Env _ root pkg _ _ _) foreigns resultsMVar name status =
354380
355381 DepsSame _ _ ->
356382 do mvar <- newMVar Unneeded
357− return (RCached hasMain mvar)
383+ return (RCached hasMain lastChange mvar)
358384
359385 DepsBlock ->
360386 return RBlocked
@@ -362,16 +388,16 @@ checkModule env@(Env _ root pkg _ _ _) foreigns resultsMVar name status =
362388 DepsNotFound problems ->
363389 do source <- File.readUtf8 path
364390 return $ RProblem $ Error.Module name path time source $
365− case Parse.fromByteString pkg source of
391+ case Parse.fromByteString projectType source of
366392 Right (Src.Module _ _ _ imports _ _ _ _ _) ->
367393 Error.BadImports (toImportErrors env results imports problems)
368394
369395 Left err ->
370396 Error.BadSyntax err
371397
372− SChanged local@(Details.Local path time deps _) source modul@(Src.Module _ _ _ imports _ _ _ _ _) docsNeed ->
398+ SChanged local@(Details.Local path time deps _ _ lastCompile) source modul@(Src.Module _ _ _ imports _ _ _ _ _) docsNeed ->
373399 do results <- readMVar resultsMVar
374− depsStatus <- checkDeps root results deps
400+ depsStatus <- checkDeps root results deps lastCompile
375401 case depsStatus of
376402 DepsChange ifaces ->
377403 compile env docsNeed local source ifaces modul
@@ -399,7 +425,7 @@ checkModule env@(Env _ root pkg _ _ _) foreigns resultsMVar name status =
399425 SForeign home ->
400426 case foreigns ! ModuleName.Canonical home name of
401427 I.Public iface -> return (RForeign iface)
402− I.Private _ _ _ -> error "loading private interface in Build"
428+ I.Private _ _ _ -> error $ "mistakenly seeing private interface for " ++ Pkg.toChars home ++ " " ++ ModuleName.toChars name
403429
404430 SKernel ->
405431 return RKernel
@@ -416,32 +442,48 @@ data DepsStatus
416442 | DepsNotFound (NE.List (ModuleName.Raw, Import.Problem))
417443
418444
419−checkDeps :: FilePath -> ResultDict -> [ModuleName.Raw] -> IO DepsStatus
420−checkDeps root results deps =
421− checkDepsHelp root results deps [] [] [] [] False
445+checkDeps :: FilePath -> ResultDict -> [ModuleName.Raw] -> Details.BuildID -> IO DepsStatus
446+checkDeps root results deps lastCompile =
447+ checkDepsHelp root results deps [] [] [] [] False 0 lastCompile
422448
423449
424450type Dep = (ModuleName.Raw, I.Interface)
425451type CDep = (ModuleName.Raw, MVar CachedInterface)
426452
427453
428−checkDepsHelp :: FilePath -> ResultDict -> [ModuleName.Raw] -> [Dep] -> [Dep] -> [CDep] -> [(ModuleName.Raw,Import.Problem)] -> Bool -> IO DepsStatus
429−checkDepsHelp root results deps new same cached importProblems isBlocked =
454+checkDepsHelp :: FilePath -> ResultDict -> [ModuleName.Raw] -> [Dep] -> [Dep] -> [CDep] -> [(ModuleName.Raw,Import.Problem)] -> Bool -> Details.BuildID -> Details.BuildID -> IO DepsStatus
455+checkDepsHelp root results deps new same cached importProblems isBlocked lastDepChange lastCompile =
430456 case deps of
431457 dep:otherDeps ->
432458 do result <- readMVar (results ! dep)
433459 case result of
434− RNew _ iface _ _ -> checkDepsHelp root results otherDeps ((dep,iface) : new) same cached importProblems isBlocked
435− RSame _ iface _ _ -> checkDepsHelp root results otherDeps new ((dep,iface) : same) cached importProblems isBlocked
436− RCached _ mvar -> checkDepsHelp root results otherDeps new same ((dep,mvar) : cached) importProblems isBlocked
437− RNotFound prob -> checkDepsHelp root results otherDeps new same cached ((dep,prob) : importProblems) True
438− RProblem _ -> checkDepsHelp root results otherDeps new same cached importProblems True
439− RBlocked -> checkDepsHelp root results otherDeps new same cached importProblems True
440− RForeign iface -> checkDepsHelp root results otherDeps new ((dep,iface) : same) cached importProblems isBlocked
441− RKernel -> checkDepsHelp root results otherDeps new same cached importProblems isBlocked
460+ RNew (Details.Local _ _ _ _ lastChange _) iface _ _ ->
461+ checkDepsHelp root results otherDeps ((dep,iface) : new) same cached importProblems isBlocked (max lastChange lastDepChange) lastCompile
462+
463+ RSame (Details.Local _ _ _ _ lastChange _) iface _ _ ->
464+ checkDepsHelp root results otherDeps new ((dep,iface) : same) cached importProblems isBlocked (max lastChange lastDepChange) lastCompile
465+
466+ RCached _ lastChange mvar ->
467+ checkDepsHelp root results otherDeps new same ((dep,mvar) : cached) importProblems isBlocked (max lastChange lastDepChange) lastCompile
468+
469+ RNotFound prob ->
470+ checkDepsHelp root results otherDeps new same cached ((dep,prob) : importProblems) True lastDepChange lastCompile
471+
472+ RProblem _ ->
473+ checkDepsHelp root results otherDeps new same cached importProblems True lastDepChange lastCompile
474+
475+ RBlocked ->
476+ checkDepsHelp root results otherDeps new same cached importProblems True lastDepChange lastCompile
477+
478+ RForeign iface ->
479+ checkDepsHelp root results otherDeps new ((dep,iface) : same) cached importProblems isBlocked lastDepChange lastCompile
480+
481+ RKernel ->
482+ checkDepsHelp root results otherDeps new same cached importProblems isBlocked lastDepChange lastCompile
483+
442484
443485 [] ->
444− case importProblems of
486+ case reverse importProblems of
445487 p:ps ->
446488 return $ DepsNotFound (NE.List p ps)
447489
@@ -449,7 +491,7 @@ checkDepsHelp root results deps new same cached importProblems isBlocked =
449491 if isBlocked then
450492 return $ DepsBlock
451493
452− else if null new then
494+ else if null new && lastDepChange <= lastCompile then
453495 return $ DepsSame same cached
454496
455497 else
@@ -464,7 +506,7 @@ checkDepsHelp root results deps new same cached importProblems isBlocked =
464506
465507
466508toImportErrors :: Env -> ResultDict -> [Src.Import] -> NE.List (ModuleName.Raw, Import.Problem) -> NE.List Import.Error
467−toImportErrors (Env _ _ _ _ locals foreigns) results imports problems =
509+toImportErrors (Env _ _ _ _ _ locals foreigns) results imports problems =
468510 let
469511 knownModules =
470512 Set.unions
@@ -543,11 +585,11 @@ checkMidpoint dmvar statuses =
543585 return (Left (Exit.BP_Cycle name names))
544586
545587
546−checkMainsMidpoint :: MVar (Maybe Dependencies) -> Map.Map ModuleName.Raw Status -> NE.List MainStatus -> IO (Either Exit.BuildProjectProblem Dependencies)
547−checkMainsMidpoint dmvar statuses smains =
588+checkMidpointAndRoots :: MVar (Maybe Dependencies) -> Map.Map ModuleName.Raw Status -> NE.List RootStatus -> IO (Either Exit.BuildProjectProblem Dependencies)
589+checkMidpointAndRoots dmvar statuses sroots =
548590 case checkForCycles statuses of
549591 Nothing ->
550− case checkUniqueMains statuses smains of
592+ case checkUniqueRoots statuses sroots of
551593 Nothing ->
552594 do maybeForeigns <- readMVar dmvar
553595 case maybeForeigns of
@@ -598,25 +640,25 @@ addToGraph name status graph =
598640 let
599641 dependencies =
600642 case status of
601− SCached (Details.Local _ _ deps _) -> deps
602− SChanged (Details.Local _ _ deps _) _ _ _ -> deps
603− SBadImport _ -> []
604− SBadSyntax _ _ _ _ -> []
605− SForeign _ -> []
606− SKernel -> []
643+ SCached (Details.Local _ _ deps _ _ _) -> deps
644+ SChanged (Details.Local _ _ deps _ _ _) _ _ _ -> deps
645+ SBadImport _ -> []
646+ SBadSyntax _ _ _ _ -> []
647+ SForeign _ -> []
648+ SKernel -> []
607649 in
608650 (name, name, dependencies) : graph
609651
610652
611653
612−-- CHECK UNIQUE MAINS
654+-- CHECK UNIQUE ROOTS
613655
614656
615−checkUniqueMains :: Map.Map ModuleName.Raw Status -> NE.List MainStatus -> Maybe Exit.BuildProjectProblem
616−checkUniqueMains insides smains =
657+checkUniqueRoots :: Map.Map ModuleName.Raw Status -> NE.List RootStatus -> Maybe Exit.BuildProjectProblem
658+checkUniqueRoots insides sroots =
617659 let
618660 outsidesDict =
619− Map.fromListWith OneOrMore.more (Maybe.mapMaybe mainStatusToNamePathPair (NE.toList smains))
661+ Map.fromListWith OneOrMore.more (Maybe.mapMaybe rootStatusToNamePathPair (NE.toList sroots))
620662 in
621663 case Map.traverseWithKey checkOutside outsidesDict of
622664 Left problem ->
@@ -628,30 +670,30 @@ checkUniqueMains insides smains =
628670 Left problem -> Just problem
629671
630672
631−mainStatusToNamePathPair :: MainStatus -> Maybe (ModuleName.Raw, OneOrMore.OneOrMore FilePath)
632−mainStatusToNamePathPair smain =
633− case smain of
634− SInside _ -> Nothing
635− SOutsideOk (Details.Local path _ _ _) _ modul -> Just (Src.getName modul, OneOrMore.one path)
636− SOutsideErr _ -> Nothing
673+rootStatusToNamePathPair :: RootStatus -> Maybe (ModuleName.Raw, OneOrMore.OneOrMore FilePath)
674+rootStatusToNamePathPair sroot =
675+ case sroot of
676+ SInside _ -> Nothing
677+ SOutsideOk (Details.Local path _ _ _ _ _) _ modul -> Just (Src.getName modul, OneOrMore.one path)
678+ SOutsideErr _ -> Nothing
637679
638680
639681checkOutside :: ModuleName.Raw -> OneOrMore.OneOrMore FilePath -> Either Exit.BuildProjectProblem FilePath
640682checkOutside name paths =
641683 case OneOrMore.destruct NE.List paths of
642684 NE.List p [] -> Right p
643− NE.List p1 (p2:_) -> Left (Exit.BP_MainNameDuplicate name p1 p2)
685+ NE.List p1 (p2:_) -> Left (Exit.BP_RootNameDuplicate name p1 p2)
644686
645687
646688checkInside :: ModuleName.Raw -> FilePath -> Status -> Either Exit.BuildProjectProblem ()
647689checkInside name p1 status =
648690 case status of
649− SCached (Details.Local p2 _ _ _) -> Left (Exit.BP_MainNameDuplicate name p1 p2)
650− SChanged (Details.Local p2 _ _ _) _ _ _ -> Left (Exit.BP_MainNameDuplicate name p1 p2)
651− SBadImport _ -> Right ()
652− SBadSyntax _ _ _ _ -> Right ()
653− SForeign _ -> Right ()
654− SKernel -> Right ()
691+ SCached (Details.Local p2 _ _ _ _ _) -> Left (Exit.BP_RootNameDuplicate name p1 p2)
692+ SChanged (Details.Local p2 _ _ _ _ _) _ _ _ -> Left (Exit.BP_RootNameDuplicate name p1 p2)
693+ SBadImport _ -> Right ()
694+ SBadSyntax _ _ _ _ -> Right ()
695+ SForeign _ -> Right ()
696+ SKernel -> Right ()
655697
656698
657699
@@ -659,31 +701,47 @@ checkInside name p1 status =
659701
660702
661703compile :: Env -> DocsNeed -> Details.Local -> B.ByteString -> Map.Map ModuleName.Raw I.Interface -> Src.Module -> IO Result
662−compile (Env key root pkg _ _ _) docsNeed local@(Details.Local path time _ _) source ifaces modul =
704+compile (Env key root projectType _ buildID _ _) docsNeed (Details.Local path time deps main lastChange _) source ifaces modul =
705+ let
706+ pkg = projectTypeToPkg projectType
707+ in
663708 case Compile.compile pkg ifaces modul of
664709 Right (Compile.Artifacts canonical annotations objects) ->
665− do let name = Src.getName modul
666− let iface = I.fromModule pkg canonical annotations
667− let docs = makeDocs docsNeed canonical
668− File.writeBinary (Stuff.elmo root name) objects
669− maybeOldi <- File.readBinary (Stuff.elmi root name)
670− case maybeOldi of
671− Just oldi | oldi == iface ->
672− do -- iface should be fully forced by equality check
673− Reporting.report key Reporting.BDone
674− return (RSame local iface objects docs)
675−
676− _ ->
677− do -- iface may be lazy still
678− -- TODO try adding forkIO here
679− File.writeBinary (Stuff.elmi root name) iface
680− Reporting.report key Reporting.BDone
681− return (RNew local iface objects docs)
710+ case makeDocs docsNeed canonical of
711+ Left err ->
712+ return $ RProblem $
713+ Error.Module (Src.getName modul) path time source (Error.BadDocs err)
714+
715+ Right docs ->
716+ do let name = Src.getName modul
717+ let iface = I.fromModule pkg canonical annotations
718+ let elmi = Stuff.elmi root name
719+ File.writeBinary (Stuff.elmo root name) objects
720+ maybeOldi <- File.readBinary elmi
721+ case maybeOldi of
722+ Just oldi | oldi == iface ->
723+ do -- iface should be fully forced by equality check
724+ Reporting.report key Reporting.BDone
725+ let local = Details.Local path time deps main lastChange buildID
726+ return (RSame local iface objects docs)
727+
728+ _ ->
729+ do -- iface may be lazy still
730+ File.writeBinary elmi iface
731+ Reporting.report key Reporting.BDone
732+ let local = Details.Local path time deps main buildID buildID
733+ return (RNew local iface objects docs)
682734
683735 Left err ->
684− do Reporting.report key Reporting.BDone
685− return $ RProblem $
686− Error.Module (Src.getName modul) path time source err
736+ return $ RProblem $
737+ Error.Module (Src.getName modul) path time source err
738+
739+
740+projectTypeToPkg :: Parse.ProjectType -> Pkg.Name
741+projectTypeToPkg projectType =
742+ case projectType of
743+ Parse.Package pkg -> pkg
744+ Parse.Application -> Pkg.dummyName
687745
688746
689747
@@ -691,9 +749,9 @@ compile (Env key root pkg _ _ _) docsNeed local@(Details.Local path time _ _) so
691749
692750
693751writeDetails :: FilePath -> Details.Details -> Map.Map ModuleName.Raw Result -> IO ()
694−writeDetails root (Details.Details time outline locals foreigns extras) results =
752+writeDetails root (Details.Details time outline buildID locals foreigns extras) results =
695753 File.writeBinary (Stuff.details root) $
696− Details.Details time outline (Map.foldrWithKey addNewLocal locals results) foreigns extras
754+ Details.Details time outline buildID (Map.foldrWithKey addNewLocal locals results) foreigns extras
697755
698756
699757addNewLocal :: ModuleName.Raw -> Result -> Map.Map ModuleName.Raw Details.Local -> Map.Map ModuleName.Raw Details.Local
@@ -701,7 +759,7 @@ addNewLocal name result locals =
701759 case result of
702760 RNew local _ _ _ -> Map.insert name local locals
703761 RSame local _ _ _ -> Map.insert name local locals
704− RCached _ _ -> locals
762+ RCached _ _ _ -> locals
705763 RNotFound _ -> locals
706764 RProblem _ -> locals
707765 RBlocked -> locals
@@ -713,8 +771,8 @@ addNewLocal name result locals =
713771-- FINALIZE EXPOSED
714772
715773
716−finalizeExposed :: DocsGoal docs -> NE.List ModuleName.Raw -> Map.Map ModuleName.Raw Result -> IO (Either Exit.BuildProblem docs)
717−finalizeExposed docsGoal exposed results =
774+finalizeExposed :: FilePath -> DocsGoal docs -> NE.List ModuleName.Raw -> Map.Map ModuleName.Raw Result -> IO (Either Exit.BuildProblem docs)
775+finalizeExposed root docsGoal exposed results =
718776 case foldr (addImportProblems results) [] (NE.toList exposed) of
719777 p:ps ->
720778 return $ Left $ Exit.BuildProjectProblem (Exit.BP_MissingExposed (NE.List p ps))
@@ -722,7 +780,7 @@ finalizeExposed docsGoal exposed results =
722780 [] ->
723781 case Map.foldr addErrors [] results of
724782 [] -> Right <$> finalizeDocs docsGoal results
725− e:es -> return $ Left $ Exit.BuildBadModules e es
783+ e:es -> return $ Left $ Exit.BuildBadModules root e es
726784
727785
728786addErrors :: Result -> [Error.Module] -> [Error.Module]
@@ -730,7 +788,7 @@ addErrors result errors =
730788 case result of
731789 RNew _ _ _ _ -> errors
732790 RSame _ _ _ _ -> errors
733− RCached _ _ -> errors
791+ RCached _ _ _ -> errors
734792 RNotFound _ -> errors
735793 RProblem e -> e:errors
736794 RBlocked -> errors
@@ -743,7 +801,7 @@ addImportProblems results name problems =
743801 case results ! name of
744802 RNew _ _ _ _ -> problems
745803 RSame _ _ _ _ -> problems
746− RCached _ _ -> problems
804+ RCached _ _ _ -> problems
747805 RNotFound p -> (name, p) : problems
748806 RProblem _ -> problems
749807 RBlocked -> problems
@@ -773,14 +831,14 @@ toDocsNeed goal =
773831 KeepDocs -> DocsNeed True
774832
775833
776−makeDocs :: DocsNeed -> Can.Module -> Maybe Docs.Module
834+makeDocs :: DocsNeed -> Can.Module -> Either EDocs.Error (Maybe Docs.Module)
777835makeDocs (DocsNeed isNeeded) modul =
778836 if isNeeded then
779837 case Docs.fromModule modul of
780− Right docs -> Just docs
781− Left _ -> Nothing
838+ Right docs -> Right (Just docs)
839+ Left err -> Left err
782840 else
783− Nothing
841+ Right Nothing
784842
785843
786844finalizeDocs :: DocsGoal docs -> Map.Map ModuleName.Raw Result -> IO docs
@@ -801,7 +859,7 @@ toDocs result =
801859 case result of
802860 RNew _ _ _ d -> d
803861 RSame _ _ _ d -> d
804− RCached _ _ -> Nothing
862+ RCached _ _ _ -> Nothing
805863 RNotFound _ -> Nothing
806864 RProblem _ -> Nothing
807865 RBlocked -> Nothing
@@ -829,40 +887,41 @@ data ReplArtifacts =
829887
830888fromRepl :: FilePath -> Details.Details -> B.ByteString -> IO (Either Exit.Repl ReplArtifacts)
831889fromRepl root details source =
832− let
833− env@(Env _ _ pkg _ _ _) = makeEnv Reporting.ignorer root details
834− in
835− case Parse.fromByteString pkg source of
836− Left syntaxError ->
837− return $ Left $ Exit.ReplBadInput source $ Error.BadSyntax syntaxError
890+ do env@(Env _ _ projectType _ _ _ _) <- makeEnv Reporting.ignorer root details
891+ case Parse.fromByteString projectType source of
892+ Left syntaxError ->
893+ return $ Left $ Exit.ReplBadInput source $ Error.BadSyntax syntaxError
838894
839− Right modul@(Src.Module _ _ _ imports _ _ _ _ _) ->
840− do dmvar <- Details.loadInterfaces root details
895+ Right modul@(Src.Module _ _ _ imports _ _ _ _ _) ->
896+ do dmvar <- Details.loadInterfaces root details
841897
842− let deps = map Src.getImportName imports
843− mvar <- newMVar Map.empty
844− crawlDeps env mvar deps ()
898+ let deps = map Src.getImportName imports
899+ mvar <- newMVar Map.empty
900+ crawlDeps env mvar deps ()
845901
846− statuses <- traverse readMVar =<< readMVar mvar
847− midpoint <- checkMidpoint dmvar statuses
902+ statuses <- traverse readMVar =<< readMVar mvar
903+ midpoint <- checkMidpoint dmvar statuses
848904
849− case midpoint of
850− Left problem ->
851− return $ Left $ Exit.ReplProjectProblem problem
905+ case midpoint of
906+ Left problem ->
907+ return $ Left $ Exit.ReplProjectProblem problem
852908
853− Right foreigns ->
854− do rmvar <- newEmptyMVar
855− resultMVars <- forkWithKey (checkModule env foreigns rmvar) statuses
856− putMVar rmvar resultMVars
857− results <- traverse readMVar resultMVars
858− writeDetails root details results
859− depsStatus <- checkDeps root resultMVars deps
860− finalizeReplArtifacts env source modul depsStatus resultMVars results
909+ Right foreigns ->
910+ do rmvar <- newEmptyMVar
911+ resultMVars <- forkWithKey (checkModule env foreigns rmvar) statuses
912+ putMVar rmvar resultMVars
913+ results <- traverse readMVar resultMVars
914+ writeDetails root details results
915+ depsStatus <- checkDeps root resultMVars deps 0
916+ finalizeReplArtifacts env source modul depsStatus resultMVars results
861917
862918
863919finalizeReplArtifacts :: Env -> B.ByteString -> Src.Module -> DepsStatus -> ResultDict -> Map.Map ModuleName.Raw Result -> IO (Either Exit.Repl ReplArtifacts)
864−finalizeReplArtifacts env@(Env _ root pkg _ _ _) source modul@(Src.Module _ _ _ imports _ _ _ _ _) depsStatus resultMVars results =
920+finalizeReplArtifacts env@(Env _ root projectType _ _ _ _) source modul@(Src.Module _ _ _ imports _ _ _ _ _) depsStatus resultMVars results =
865921 let
922+ pkg =
923+ projectTypeToPkg projectType
924+
866925 compileInput ifaces =
867926 case Compile.compile pkg ifaces modul of
868927 Right (Compile.Artifacts canonical annotations objects) ->
@@ -889,7 +948,7 @@ finalizeReplArtifacts env@(Env _ root pkg _ _ _) source modul@(Src.Module _ _ _
889948 DepsBlock ->
890949 case Map.foldr addErrors [] results of
891950 [] -> return $ Left $ Exit.ReplBlocked
892− e:es -> return $ Left $ Exit.ReplBadLocalDeps e es
951+ e:es -> return $ Left $ Exit.ReplBadLocalDeps root e es
893952
894953 DepsNotFound problems ->
895954 return $ Left $ Exit.ReplBadInput source $ Error.BadImports $
@@ -905,25 +964,25 @@ finalizeReplArtifacts env@(Env _ root pkg _ _ _) source modul@(Src.Module _ _ _
905964
906965
907966
908−-- FIND MAIN
967+-- FIND ROOT
909968
910969
911−data MainLocation
970+data RootLocation
912971 = LInside ModuleName.Raw
913972 | LOutside FilePath
914973
915974
916−findMains :: Env -> NE.List FilePath -> IO (Either Exit.BuildProjectProblem (NE.List MainLocation))
917−findMains env paths =
918− do mvars <- traverse (fork . findLocation env) paths
919− elocs <- traverse readMVar mvars
920− return $ checkLocations =<< sequence elocs
975+findRoots :: Env -> NE.List FilePath -> IO (Either Exit.BuildProjectProblem (NE.List RootLocation))
976+findRoots env paths =
977+ do mvars <- traverse (fork . getRootInfo env) paths
978+ einfos <- traverse readMVar mvars
979+ return $ checkRoots =<< sequence einfos
921980
922981
923−checkLocations :: NE.List Location -> Either Exit.BuildProjectProblem (NE.List MainLocation)
924−checkLocations locations =
982+checkRoots :: NE.List RootInfo -> Either Exit.BuildProjectProblem (NE.List RootLocation)
983+checkRoots infos =
925984 let
926− toOneOrMore loc@(Location absolute _ _) =
985+ toOneOrMore loc@(RootInfo absolute _ _) =
927986 (absolute, OneOrMore.one loc)
928987
929988 fromOneOrMore loc locs =
@@ -931,71 +990,83 @@ checkLocations locations =
931990 [] -> Right ()
932991 loc2:_ -> Left (Exit.BP_MainPathDuplicate (_relative loc) (_relative loc2))
933992 in
934− fmap (\_ -> fmap _location locations) $
993+ fmap (\_ -> fmap _location infos) $
935994 traverse (OneOrMore.destruct fromOneOrMore) $
936− Map.fromListWith OneOrMore.more $ map toOneOrMore (NE.toList locations)
995+ Map.fromListWith OneOrMore.more $ map toOneOrMore (NE.toList infos)
937996
938997
939998
940−-- LOCATIONS
999+-- ROOT INFO
9411000
9421001
943−data Location =
944− Location
1002+data RootInfo =
1003+ RootInfo
9451004 { _absolute :: FilePath
9461005 , _relative :: FilePath
947− , _location :: MainLocation
1006+ , _location :: RootLocation
9481007 }
9491008
9501009
951−findLocation :: Env -> FilePath -> IO (Either Exit.BuildProjectProblem Location)
952−findLocation env path =
1010+getRootInfo :: Env -> FilePath -> IO (Either Exit.BuildProjectProblem RootInfo)
1011+getRootInfo env path =
9531012 do exists <- File.exists path
9541013 if exists
955− then isInsideSrcDirs env path <$> Dir.canonicalizePath path
1014+ then getRootInfoHelp env path =<< Dir.canonicalizePath path
9561015 else return (Left (Exit.BP_PathUnknown path))
9571016
9581017
959−isInsideSrcDirs :: Env -> FilePath -> FilePath -> Either Exit.BuildProjectProblem Location
960−isInsideSrcDirs (Env _ root _ srcDirs _ _) path absolutePath =
1018+getRootInfoHelp :: Env -> FilePath -> FilePath -> IO (Either Exit.BuildProjectProblem RootInfo)
1019+getRootInfoHelp (Env _ _ _ srcDirs _ _ _) path absolutePath =
9611020 let
9621021 (dirs, file) = FP.splitFileName absolutePath
963− (final, ext) = break (=='.') file
1022+ (final, ext) = FP.splitExtension file
9641023 in
9651024 if ext /= ".elm"
966− then Left (Exit.BP_WithBadExtension path)
1025+ then
1026+ return $ Left $ Exit.BP_WithBadExtension path
9671027 else
9681028 let
969− roots = FP.splitDirectories root
970− segments = FP.splitDirectories dirs ++ [final]
1029+ absoluteSegments = FP.splitDirectories dirs ++ [final]
9711030 in
972− case dropPrefix roots segments of
973− Nothing ->
974− Right (Location absolutePath path (LOutside path))
975−
976− Just relativeSegments ->
977− let
978− (exits, maybes) =
979− Either.partitionEithers (map (isInsideSrcDirsHelp relativeSegments) srcDirs)
980− in
981− -- TODO make sure this is all correct
982− case (exits, Maybe.catMaybes maybes) of
983− (_, [(_,name)]) -> Right (Location absolutePath path (LInside name))
984− ([], []) -> Right (Location absolutePath path (LOutside path))
985− (_, (s1,_):(s2,_):_) -> Left (Exit.BP_WithAmbiguousSrcDir path s1 s2)
986− (exit:_, _) -> Left exit
987−
988−
989−isInsideSrcDirsHelp :: [String] -> FilePath -> Either Exit.BuildProjectProblem (Maybe (FilePath, ModuleName.Raw))
990−isInsideSrcDirsHelp segments srcDir =
1031+ case Maybe.mapMaybe (isInsideSrcDirByPath absoluteSegments) srcDirs of
1032+ [] ->
1033+ return $ Right $ RootInfo absolutePath path (LOutside path)
1034+
1035+ [(_, Right names)] ->
1036+ do let name = Name.fromChars (List.intercalate "." names)
1037+ matchingDirs <- filterM (isInsideSrcDirByName names) srcDirs
1038+ case matchingDirs of
1039+ d1:d2:_ ->
1040+ do let p1 = addRelative d1 (FP.joinPath names <.> "elm")
1041+ let p2 = addRelative d2 (FP.joinPath names <.> "elm")
1042+ return $ Left $ Exit.BP_RootNameDuplicate name p1 p2
1043+
1044+ _ ->
1045+ return $ Right $ RootInfo absolutePath path (LInside name)
1046+
1047+ [(s, Left names)] ->
1048+ return $ Left $ Exit.BP_RootNameInvalid path s names
1049+
1050+ (s1,_):(s2,_):_ ->
1051+ return $ Left $ Exit.BP_WithAmbiguousSrcDir path s1 s2
1052+
1053+
1054+
1055+isInsideSrcDirByName :: [String] -> AbsoluteSrcDir -> IO Bool
1056+isInsideSrcDirByName names srcDir =
1057+ File.exists (addRelative srcDir (FP.joinPath names <.> "elm"))
1058+
1059+
1060+isInsideSrcDirByPath :: [String] -> AbsoluteSrcDir -> Maybe (FilePath, Either [String] [String])
1061+isInsideSrcDirByPath segments (AbsoluteSrcDir srcDir) =
9911062 case dropPrefix (FP.splitDirectories srcDir) segments of
9921063 Nothing ->
993− Right Nothing
1064+ Nothing
9941065
9951066 Just names ->
9961067 if all isGoodName names
997− then Right (Just (srcDir, Name.fromChars (List.intercalate "." names)))
998− else Left (error "Exit.MakeWithInvalidModuleName" srcDir segments)
1068+ then Just (srcDir, Right names)
1069+ else Just (srcDir, Left names)
9991070
10001071
10011072isGoodName :: [Char] -> Bool
@@ -1008,6 +1079,8 @@ isGoodName name =
10081079 Char.isUpper char && all (\c -> Char.isAlphaNum c || c == '_') chars
10091080
10101081
1082+-- INVARIANT: Dir.canonicalizePath has been run on both inputs
1083+--
10111084dropPrefix :: [FilePath] -> [FilePath] -> Maybe [FilePath]
10121085dropPrefix roots paths =
10131086 case roots of
@@ -1016,23 +1089,23 @@ dropPrefix roots paths =
10161089
10171090 r:rs ->
10181091 case paths of
1019− [] -> Nothing
1092+ [] -> Nothing
10201093 p:ps -> if r == p then dropPrefix rs ps else Nothing
10211094
10221095
10231096
1024−-- CRAWL MAINS
1097+-- CRAWL ROOTS
10251098
10261099
1027−data MainStatus
1100+data RootStatus
10281101 = SInside ModuleName.Raw
10291102 | SOutsideOk Details.Local B.ByteString Src.Module
10301103 | SOutsideErr Error.Module
10311104
10321105
1033−crawlMain :: Env -> MVar StatusDict -> MainLocation -> IO MainStatus
1034−crawlMain env@(Env _ _ pkg _ _ _) mvar given =
1035− case given of
1106+crawlRoot :: Env -> MVar StatusDict -> RootLocation -> IO RootStatus
1107+crawlRoot env@(Env _ _ projectType _ buildID _ _) mvar root =
1108+ case root of
10361109 LInside name ->
10371110 do statusMVar <- newEmptyMVar
10381111 statusDict <- takeMVar mvar
@@ -1043,10 +1116,10 @@ crawlMain env@(Env _ _ pkg _ _ _) mvar given =
10431116 LOutside path ->
10441117 do time <- File.getTime path
10451118 source <- File.readUtf8 path
1046− case Parse.fromByteString pkg source of
1119+ case Parse.fromByteString projectType source of
10471120 Right modul@(Src.Module _ _ _ imports values _ _ _ _) ->
10481121 do let deps = map Src.getImportName imports
1049− let local = Details.Local path time deps (any isMain values)
1122+ let local = Details.Local path time deps (any isMain values) buildID buildID
10501123 crawlDeps env mvar deps (SOutsideOk local source modul)
10511124
10521125 Left syntaxError ->
@@ -1055,36 +1128,36 @@ crawlMain env@(Env _ _ pkg _ _ _) mvar given =
10551128
10561129
10571130
1058−-- CHECK MAINS
1131+-- CHECK ROOTS
10591132
10601133
1061−data MainResult
1134+data RootResult
10621135 = RInside ModuleName.Raw
10631136 | ROutsideOk ModuleName.Raw I.Interface Opt.LocalGraph
10641137 | ROutsideErr Error.Module
10651138 | ROutsideBlocked
10661139
10671140
1068−checkMain :: Env -> ResultDict -> MainStatus -> IO MainResult
1069−checkMain env@(Env _ root _ _ _ _) results pendingMain =
1070− case pendingMain of
1141+checkRoot :: Env -> ResultDict -> RootStatus -> IO RootResult
1142+checkRoot env@(Env _ root _ _ _ _ _) results rootStatus =
1143+ case rootStatus of
10711144 SInside name ->
10721145 return (RInside name)
10731146
10741147 SOutsideErr err ->
10751148 return (ROutsideErr err)
10761149
1077− SOutsideOk local@(Details.Local path time deps _) source modul@(Src.Module _ _ _ imports _ _ _ _ _) ->
1078− do depsStatus <- checkDeps root results deps
1150+ SOutsideOk local@(Details.Local path time deps _ _ lastCompile) source modul@(Src.Module _ _ _ imports _ _ _ _ _) ->
1151+ do depsStatus <- checkDeps root results deps lastCompile
10791152 case depsStatus of
10801153 DepsChange ifaces ->
1081− return $ compileOutside env local source ifaces modul
1154+ compileOutside env local source ifaces modul
10821155
10831156 DepsSame same cached ->
10841157 do maybeLoaded <- loadInterfaces root same cached
10851158 case maybeLoaded of
10861159 Nothing -> return ROutsideBlocked
1087− Just ifaces -> return $ compileOutside env local source ifaces modul
1160+ Just ifaces -> compileOutside env local source ifaces modul
10881161
10891162 DepsBlock ->
10901163 return ROutsideBlocked
@@ -1094,53 +1167,54 @@ checkMain env@(Env _ root _ _ _ _) results pendingMain =
10941167 Error.BadImports (toImportErrors env results imports problems)
10951168
10961169
1097−compileOutside :: Env -> Details.Local -> B.ByteString -> Map.Map ModuleName.Raw I.Interface -> Src.Module -> MainResult
1098−compileOutside (Env _ _ pkg _ _ _) (Details.Local path time _ _) source ifaces modul =
1170+compileOutside :: Env -> Details.Local -> B.ByteString -> Map.Map ModuleName.Raw I.Interface -> Src.Module -> IO RootResult
1171+compileOutside (Env key _ projectType _ _ _ _) (Details.Local path time _ _ _ _) source ifaces modul =
10991172 let
1173+ pkg = projectTypeToPkg projectType
11001174 name = Src.getName modul
11011175 in
11021176 case Compile.compile pkg ifaces modul of
11031177 Right (Compile.Artifacts canonical annotations objects) ->
1104− ROutsideOk name (I.fromModule pkg canonical annotations) objects
1178+ do Reporting.report key Reporting.BDone
1179+ return $ ROutsideOk name (I.fromModule pkg canonical annotations) objects
11051180
11061181 Left errors ->
1107− ROutsideErr $
1108− Error.Module name path time source errors
1182+ return $ ROutsideErr $ Error.Module name path time source errors
11091183
11101184
11111185
11121186-- TO ARTIFACTS
11131187
11141188
1115−data Main
1189+data Root
11161190 = Inside ModuleName.Raw
11171191 | Outside ModuleName.Raw I.Interface Opt.LocalGraph
11181192
11191193
1120−toArtifacts :: Env -> Dependencies -> Map.Map ModuleName.Raw Result -> NE.List MainResult -> Either Exit.BuildProblem Artifacts
1121−toArtifacts (Env _ _ pkg _ _ _) foreigns results mainResults =
1122− case gatherProblemsOrMains results mainResults of
1194+toArtifacts :: Env -> Dependencies -> Map.Map ModuleName.Raw Result -> NE.List RootResult -> Either Exit.BuildProblem Artifacts
1195+toArtifacts (Env _ root projectType _ _ _ _) foreigns results rootResults =
1196+ case gatherProblemsOrMains results rootResults of
11231197 Left (NE.List e es) ->
1124− Left (Exit.BuildBadModules e es)
1198+ Left (Exit.BuildBadModules root e es)
11251199
1126− Right mains ->
1127− Right $ Artifacts pkg foreigns mains $
1128− Map.foldrWithKey addInside (foldr addOutside [] mainResults) results
1200+ Right roots ->
1201+ Right $ Artifacts (projectTypeToPkg projectType) foreigns roots $
1202+ Map.foldrWithKey addInside (foldr addOutside [] rootResults) results
11291203
11301204
1131−gatherProblemsOrMains :: Map.Map ModuleName.Raw Result -> NE.List MainResult -> Either (NE.List Error.Module) (NE.List Main)
1132−gatherProblemsOrMains results (NE.List mainResult mainResults) =
1205+gatherProblemsOrMains :: Map.Map ModuleName.Raw Result -> NE.List RootResult -> Either (NE.List Error.Module) (NE.List Root)
1206+gatherProblemsOrMains results (NE.List rootResult rootResults) =
11331207 let
1134− sortMain result (es, mains) =
1208+ addResult result (es, roots) =
11351209 case result of
1136− RInside n -> ( es, Inside n : mains)
1137− ROutsideOk n i o -> ( es, Outside n i o : mains)
1138− ROutsideErr e -> (e:es, mains)
1139− ROutsideBlocked -> ( es, mains)
1210+ RInside n -> ( es, Inside n : roots)
1211+ ROutsideOk n i o -> ( es, Outside n i o : roots)
1212+ ROutsideErr e -> (e:es, roots)
1213+ ROutsideBlocked -> ( es, roots)
11401214
11411215 errors = Map.foldr addErrors [] results
11421216 in
1143− case (mainResult, foldr sortMain (errors, []) mainResults) of
1217+ case (rootResult, foldr addResult (errors, []) rootResults) of
11441218 (RInside n , ( [], ms)) -> Right (NE.List (Inside n) ms)
11451219 (RInside _ , (e:es, _ )) -> Left (NE.List e es)
11461220 (ROutsideOk n i o, ( [], ms)) -> Right (NE.List (Outside n i o) ms)
@@ -1155,7 +1229,7 @@ addInside name result modules =
11551229 case result of
11561230 RNew _ iface objs _ -> Fresh name iface objs : modules
11571231 RSame _ iface objs _ -> Fresh name iface objs : modules
1158− RCached main mvar -> Cached name main mvar : modules
1232+ RCached main _ mvar -> Cached name main mvar : modules
11591233 RNotFound _ -> error (badInside name)
11601234 RProblem _ -> error (badInside name)
11611235 RBlocked -> error (badInside name)
@@ -1168,9 +1242,9 @@ badInside name =
11681242 "Error from `" ++ Name.toChars name ++ "` should have been reported already."
11691243
11701244
1171−addOutside :: MainResult -> [Module] -> [Module]
1172−addOutside main modules =
1173− case main of
1245+addOutside :: RootResult -> [Module] -> [Module]
1246+addOutside root modules =
1247+ case root of
11741248 RInside _ -> modules
11751249 ROutsideOk name iface objs -> Fresh name iface objs : modules
11761250 ROutsideErr _ -> modules
builder/src/Deps/Registry.hs+1−5
@@ -54,11 +54,7 @@ data KnownVersions =
5454
5555read :: Stuff.PackageCache -> IO (Maybe Registry)
5656read cache =
57− do let path = Stuff.registry cache
58− exists <- File.exists path
59− if exists
60− then File.readBinary path
61− else return Nothing
57+ File.readBinary (Stuff.registry cache)
6258
6359
6460
builder/src/Deps/Solver.hs+27−24
@@ -94,6 +94,7 @@ data Details =
9494
9595verify :: Stuff.PackageCache -> Connection -> Registry.Registry -> Map.Map Pkg.Name C.Constraint -> IO (Result (Map.Map Pkg.Name Details))
9696verify cache connection registry constraints =
97+ Stuff.withRegistryLock cache $
9798 case try constraints of
9899 Solver solver ->
99100 solver (State cache connection registry Map.empty)
@@ -130,6 +131,7 @@ data AppSolution =
130131
131132addToApp :: Stuff.PackageCache -> Connection -> Registry.Registry -> Pkg.Name -> Outline.AppOutline -> IO (Result AppSolution)
132133addToApp cache connection registry pkg outline@(Outline.AppOutline _ _ direct indirect testDirect testIndirect) =
134+ Stuff.withRegistryLock cache $
133135 let
134136 allIndirects = Map.union indirect testIndirect
135137 allDirects = Map.union direct testDirect
@@ -349,30 +351,31 @@ data Env =
349351
350352initEnv :: IO (Either Exit.RegistryProblem Env)
351353initEnv =
352− do mvar <- newEmptyMVar
353− _ <- forkIO $ putMVar mvar =<< Http.getManager
354− cache <- Stuff.getPackageCache
355− maybeRegistry <- Registry.read cache
356− manager <- readMVar mvar
357−
358− case maybeRegistry of
359− Nothing ->
360− do eitherRegistry <- Registry.fetch manager cache
361− case eitherRegistry of
362− Right latestRegistry ->
363− return $ Right $ Env cache manager (Online manager) latestRegistry
364−
365− Left problem ->
366− return $ Left $ problem
367−
368− Just cachedRegistry ->
369− do eitherRegistry <- Registry.update manager cache cachedRegistry
370− case eitherRegistry of
371− Right latestRegistry ->
372− return $ Right $ Env cache manager (Online manager) latestRegistry
373−
374− Left _ ->
375− return $ Right $ Env cache manager Offline cachedRegistry
354+ do mvar <- newEmptyMVar
355+ _ <- forkIO $ putMVar mvar =<< Http.getManager
356+ cache <- Stuff.getPackageCache
357+ Stuff.withRegistryLock cache $
358+ do maybeRegistry <- Registry.read cache
359+ manager <- readMVar mvar
360+
361+ case maybeRegistry of
362+ Nothing ->
363+ do eitherRegistry <- Registry.fetch manager cache
364+ case eitherRegistry of
365+ Right latestRegistry ->
366+ return $ Right $ Env cache manager (Online manager) latestRegistry
367+
368+ Left problem ->
369+ return $ Left $ problem
370+
371+ Just cachedRegistry ->
372+ do eitherRegistry <- Registry.update manager cache cachedRegistry
373+ case eitherRegistry of
374+ Right latestRegistry ->
375+ return $ Right $ Env cache manager (Online manager) latestRegistry
376+
377+ Left _ ->
378+ return $ Right $ Env cache manager Offline cachedRegistry
376379
377380
378381
builder/src/Elm/Details.hs+100−65
@@ -2,6 +2,7 @@
22{-# LANGUAGE BangPatterns, OverloadedStrings #-}
33module Elm.Details
44 ( Details(..)
5+ , BuildID
56 , ValidOutline(..)
67 , Local(..)
78 , Foreign(..)
@@ -15,22 +16,26 @@ module Elm.Details
1516
1617import Control.Concurrent (forkIO)
1718import Control.Concurrent.MVar (MVar, newEmptyMVar, newMVar, putMVar, readMVar, takeMVar)
18−import Control.Monad (liftM, liftM2, liftM4)
19+import Control.Monad (liftM, liftM2, liftM3)
1920import Data.Binary (Binary, get, put, getWord8, putWord8)
21+import qualified Data.Either as Either
2022import qualified Data.Map as Map
2123import qualified Data.Map.Utils as Map
2224import qualified Data.Map.Merge.Strict as Map
25+import qualified Data.Maybe as Maybe
2326import qualified Data.Name as Name
2427import qualified Data.NonEmptyList as NE
2528import qualified Data.OneOrMore as OneOrMore
2629import qualified Data.Set as Set
2730import qualified Data.Utf8 as Utf8
31+import Data.Word (Word64)
2832import qualified System.Directory as Dir
2933import System.FilePath ((</>), (<.>))
3034
3135import qualified AST.Canonical as Can
3236import qualified AST.Source as Src
3337import qualified AST.Optimized as Opt
38+import qualified BackgroundWriter as BW
3439import qualified Compile
3540import qualified Deps.Registry as Registry
3641import qualified Deps.Solver as Solver
@@ -63,23 +68,42 @@ data Details =
6368 Details
6469 { _outlineTime :: File.Time
6570 , _outline :: ValidOutline
71+ , _buildID :: BuildID
6672 , _locals :: Map.Map ModuleName.Raw Local
6773 , _foreigns :: Map.Map ModuleName.Raw Foreign
6874 , _extras :: Extras
6975 }
7076
7177
72−data ValidOutline
73− = ValidApp (NE.List FilePath)
74− | ValidPkg Pkg.Name [ModuleName.Raw]
78+type BuildID = Word64
7579
7680
81+data ValidOutline
82+ = ValidApp (NE.List Outline.SrcDir)
83+ | ValidPkg Pkg.Name [ModuleName.Raw] (Map.Map Pkg.Name V.Version {- for docs in reactor -})
84+
85+
86+-- NOTE: we need two ways to detect if a file must be recompiled:
87+--
88+-- (1) _time is the modification time from the last time we compiled the file.
89+-- By checking EQUALITY with the current modification time, we can detect file
90+-- saves and `git checkout` of previous versions. Both need a recompile.
91+--
92+-- (2) _lastChange is the BuildID from the last time a new interface file was
93+-- generated, and _lastCompile is the BuildID from the last time the file was
94+-- compiled. These may be different if a file is recompiled but the interface
95+-- stayed the same. When the _lastCompile is LESS THAN the _lastChange of any
96+-- imports, we need to recompile. This can happen when a project has multiple
97+-- entrypoints and some modules are compiled less often than their imports.
98+--
7799data Local =
78100 Local
79101 { _path :: FilePath
80102 , _time :: File.Time
81103 , _deps :: [ModuleName.Raw]
82104 , _main :: Bool
105+ , _lastChange :: BuildID
106+ , _lastCompile :: BuildID
83107 }
84108
85109
@@ -101,14 +125,14 @@ type Interfaces =
101125
102126
103127loadObjects :: FilePath -> Details -> IO (MVar (Maybe Opt.GlobalGraph))
104−loadObjects root (Details _ _ _ _ extras) =
128+loadObjects root (Details _ _ _ _ _ extras) =
105129 case extras of
106130 ArtifactsFresh _ o -> newMVar (Just o)
107131 ArtifactsCached -> fork (File.readBinary (Stuff.objects root))
108132
109133
110134loadInterfaces :: FilePath -> Details -> IO (MVar (Maybe Interfaces))
111−loadInterfaces root (Details _ _ _ _ extras) =
135+loadInterfaces root (Details _ _ _ _ _ extras) =
112136 case extras of
113137 ArtifactsFresh i _ -> newMVar (Just i)
114138 ArtifactsCached -> fork (File.readBinary (Stuff.interfaces root))
@@ -118,11 +142,11 @@ loadInterfaces root (Details _ _ _ _ extras) =
118142-- VERIFY INSTALL -- used by Install
119143
120144
121−verifyInstall :: FilePath -> Solver.Env -> Outline.Outline -> IO (Either Exit.Details ())
122−verifyInstall root (Solver.Env cache manager connection registry) outline =
145+verifyInstall :: BW.Scope -> FilePath -> Solver.Env -> Outline.Outline -> IO (Either Exit.Details ())
146+verifyInstall scope root (Solver.Env cache manager connection registry) outline =
123147 do time <- File.getTime (root </> "elm.json")
124148 let key = Reporting.ignorer
125− let env = Env key root cache manager connection registry
149+ let env = Env key scope root cache manager connection registry
126150 case outline of
127151 Outline.Pkg pkg -> Task.run (verifyPkg env time pkg >> return ())
128152 Outline.App app -> Task.run (verifyApp env time app >> return ())
@@ -132,28 +156,28 @@ verifyInstall root (Solver.Env cache manager connection registry) outline =
132156-- LOAD -- used by Make, Repl, Reactor
133157
134158
135−load :: Reporting.Style -> FilePath -> IO (Either Exit.Details Details)
136−load style root =
159+load :: Reporting.Style -> BW.Scope -> FilePath -> IO (Either Exit.Details Details)
160+load style scope root =
137161 do newTime <- File.getTime (root </> "elm.json")
138162 maybeDetails <- File.readBinary (Stuff.details root)
139163 case maybeDetails of
140164 Nothing ->
141− generate style root newTime
165+ generate style scope root newTime
142166
143− Just details@(Details oldTime _ _ _ _) ->
167+ Just details@(Details oldTime _ buildID _ _ _) ->
144168 if oldTime == newTime
145− then return (Right details)
146− else generate style root newTime
169+ then return (Right details { _buildID = buildID + 1 })
170+ else generate style scope root newTime
147171
148172
149173
150174-- GENERATE
151175
152176
153−generate :: Reporting.Style -> FilePath -> File.Time -> IO (Either Exit.Details Details)
154−generate style root time =
177+generate :: Reporting.Style -> BW.Scope -> FilePath -> File.Time -> IO (Either Exit.Details Details)
178+generate style scope root time =
155179 Reporting.trackDetails style $ \key ->
156− do result <- initEnv key root
180+ do result <- initEnv key scope root
157181 case result of
158182 Left exit ->
159183 return (Left exit)
@@ -171,6 +195,7 @@ generate style root time =
171195data Env =
172196 Env
173197 { _key :: Reporting.DKey
198+ , _scope :: BW.Scope
174199 , _root :: FilePath
175200 , _cache :: Stuff.PackageCache
176201 , _manager :: Http.Manager
@@ -179,8 +204,8 @@ data Env =
179204 }
180205
181206
182−initEnv :: Reporting.DKey -> FilePath -> IO (Either Exit.Details (Env, Outline.Outline))
183−initEnv key root =
207+initEnv :: Reporting.DKey -> BW.Scope -> FilePath -> IO (Either Exit.Details (Env, Outline.Outline))
208+initEnv key scope root =
184209 do mvar <- fork Solver.initEnv
185210 eitherOutline <- Outline.read root
186211 case eitherOutline of
@@ -194,7 +219,7 @@ initEnv key root =
194219 return $ Left $ Exit.DetailsCannotGetRegistry problem
195220
196221 Right (Solver.Env cache manager connection registry) ->
197− return $ Right (Env key root cache manager connection registry, outline)
222+ return $ Right (Env key scope root cache manager connection registry, outline)
198223
199224
200225
@@ -210,7 +235,8 @@ verifyPkg env time (Outline.PkgOutline pkg _ _ _ exposed direct testDirect elm)
210235 then
211236 do solution <- verifyConstraints env =<< union noDups direct testDirect
212237 let exposedList = Outline.flattenExposed exposed
213− verifyDependencies env time (ValidPkg pkg exposedList) solution direct
238+ let exactDeps = Map.map (\(Solver.Details v _) -> v) solution -- for pkg docs in reactor
239+ verifyDependencies env time (ValidPkg pkg exposedList exactDeps) solution direct
214240 else
215241 Task.throw $ Exit.DetailsBadElmInPkg elm
216242
@@ -240,7 +266,7 @@ checkAppDeps (Outline.AppOutline _ _ direct indirect testDirect testIndirect) =
240266
241267
242268verifyConstraints :: Env -> Map.Map Pkg.Name Con.Constraint -> Task (Map.Map Pkg.Name Solver.Details)
243−verifyConstraints (Env _ _ cache _ connection registry) constraints =
269+verifyConstraints (Env _ _ _ cache _ connection registry) constraints =
244270 do result <- Task.io $ Solver.verify cache connection registry constraints
245271 case result of
246272 Solver.Ok details -> return details
@@ -286,27 +312,30 @@ fork work =
286312
287313
288314verifyDependencies :: Env -> File.Time -> ValidOutline -> Map.Map Pkg.Name Solver.Details -> Map.Map Pkg.Name a -> Task Details
289−verifyDependencies env@(Env key root _ _ _ _) time outline solution directDeps =
315+verifyDependencies env@(Env key scope root cache _ _ _) time outline solution directDeps =
290316 Task.eio id $
291317 do Reporting.report key (Reporting.DStart (Map.size solution))
292318 mvar <- newEmptyMVar
293− mvars <- Map.traverseWithKey (\k v -> fork (verifyDep env mvar solution k v)) solution
319+ mvars <- Stuff.withRegistryLock cache $
320+ Map.traverseWithKey (\k v -> fork (verifyDep env mvar solution k v)) solution
294321 putMVar mvar mvars
295322 deps <- traverse readMVar mvars
296323 case sequence deps of
297− Left problem ->
298− error "TODO verifyDependencies" problem
324+ Left _ ->
325+ do home <- Stuff.getElmHome
326+ return $ Left $ Exit.DetailsBadDeps home $
327+ Maybe.catMaybes $ Either.lefts $ Map.elems deps
299328
300329 Right artifacts ->
301330 let
302331 objs = Map.foldr addObjects Opt.empty artifacts
303332 ifaces = Map.foldrWithKey (addInterfaces directDeps) Map.empty artifacts
304− foreigns = Map.map (OneOrMore.destruct Foreign) $ Map.foldrWithKey gatherForeigns Map.empty artifacts
305− details = Details time outline Map.empty foreigns (ArtifactsFresh ifaces objs)
333+ foreigns = Map.map (OneOrMore.destruct Foreign) $ Map.foldrWithKey gatherForeigns Map.empty $ Map.intersection artifacts directDeps
334+ details = Details time outline 0 Map.empty foreigns (ArtifactsFresh ifaces objs)
306335 in
307− do File.writeBinary (Stuff.objects root) objs
308− File.writeBinary (Stuff.interfaces root) ifaces
309− File.writeBinary (Stuff.details root) details
336+ do BW.writeBinary scope (Stuff.objects root) objs
337+ BW.writeBinary scope (Stuff.interfaces root) ifaces
338+ BW.writeBinary scope (Stuff.details root) details
310339 return (Right details)
311340
312341
@@ -346,44 +375,36 @@ data Artifacts =
346375
347376
348377type Dep =
349− Either Problem Artifacts
350−
351−
352−data Problem
353− = BadDownload Exit.PackageProblem
354− | BadBuild
355− | BadDependency
378+ Either (Maybe Exit.DetailsBadDep) Artifacts
356379
357380
358381verifyDep :: Env -> MVar (Map.Map Pkg.Name (MVar Dep)) -> Map.Map Pkg.Name Solver.Details -> Pkg.Name -> Solver.Details -> IO Dep
359−verifyDep (Env key _ cache manager _ _) depsMVar solution pkg details@(Solver.Details vsn directDeps) =
360− let
361− fingerprint = Map.intersectionWith (\(Solver.Details v _) _ -> v) solution directDeps
362− in
363− do exists <- Dir.doesDirectoryExist (Stuff.package cache pkg vsn </> "src")
382+verifyDep (Env key _ _ cache manager _ _) depsMVar solution pkg details@(Solver.Details vsn directDeps) =
383+ do let fingerprint = Map.intersectionWith (\(Solver.Details v _) _ -> v) solution directDeps
384+ exists <- Dir.doesDirectoryExist (Stuff.package cache pkg vsn </> "src")
364385 if exists
365386 then
366387 do Reporting.report key Reporting.DCached
367388 maybeCache <- File.readBinary (Stuff.package cache pkg vsn </> "artifacts.dat")
368389 case maybeCache of
369390 Nothing ->
370− build key cache depsMVar pkg details (Set.singleton fingerprint)
391+ build key cache depsMVar pkg details fingerprint Set.empty
371392
372393 Just (ArtifactCache fingerprints artifacts) ->
373394 if Set.member fingerprint fingerprints
374395 then Reporting.report key Reporting.DBuilt >> return (Right artifacts)
375− else build key cache depsMVar pkg details (Set.insert fingerprint fingerprints)
396+ else build key cache depsMVar pkg details fingerprint fingerprints
376397 else
377398 do Reporting.report key Reporting.DRequested
378399 result <- downloadPackage cache manager pkg vsn
379400 case result of
380− Left p ->
401+ Left problem ->
381402 do Reporting.report key (Reporting.DFailed pkg vsn)
382− return (Left (BadDownload p))
403+ return $ Left $ Just $ Exit.BD_BadDownload pkg vsn problem
383404
384405 Right () ->
385406 do Reporting.report key (Reporting.DReceived pkg vsn)
386− build key cache depsMVar pkg details (Set.singleton fingerprint)
407+ build key cache depsMVar pkg details fingerprint Set.empty
387408
388409
389410
@@ -405,17 +426,17 @@ type Fingerprint =
405426-- BUILD
406427
407428
408−build :: Reporting.DKey -> Stuff.PackageCache -> MVar (Map.Map Pkg.Name (MVar Dep)) -> Pkg.Name -> Solver.Details -> Set.Set Fingerprint -> IO Dep
409−build key cache depsMVar pkg (Solver.Details vsn _) fingerprints =
429+build :: Reporting.DKey -> Stuff.PackageCache -> MVar (Map.Map Pkg.Name (MVar Dep)) -> Pkg.Name -> Solver.Details -> Fingerprint -> Set.Set Fingerprint -> IO Dep
430+build key cache depsMVar pkg (Solver.Details vsn _) f fs =
410431 do eitherOutline <- Outline.read (Stuff.package cache pkg vsn)
411432 case eitherOutline of
412433 Left _ ->
413434 do Reporting.report key Reporting.DBroken
414− return (Left BadBuild)
435+ return $ Left $ Just $ Exit.BD_BadBuild pkg vsn f
415436
416437 Right (Outline.App _) ->
417438 do Reporting.report key Reporting.DBroken
418− return (Left BadBuild)
439+ return $ Left $ Just $ Exit.BD_BadBuild pkg vsn f
419440
420441 Right (Outline.Pkg (Outline.PkgOutline _ _ _ _ exposed deps _ _)) ->
421442 do allDeps <- readMVar depsMVar
@@ -423,7 +444,7 @@ build key cache depsMVar pkg (Solver.Details vsn _) fingerprints =
423444 case sequence directDeps of
424445 Left _ ->
425446 do Reporting.report key Reporting.DBroken
426− return (Left BadDependency)
447+ return $ Left $ Nothing
427448
428449 Right directArtifacts ->
429450 do let src = Stuff.package cache pkg vsn </> "src"
@@ -438,7 +459,7 @@ build key cache depsMVar pkg (Solver.Details vsn _) fingerprints =
438459 case sequence maybeStatuses of
439460 Nothing ->
440461 do Reporting.report key Reporting.DBroken
441− return (Left BadBuild)
462+ return $ Left $ Just $ Exit.BD_BadBuild pkg vsn f
442463
443464 Just statuses ->
444465 do rmvar <- newEmptyMVar
@@ -448,7 +469,7 @@ build key cache depsMVar pkg (Solver.Details vsn _) fingerprints =
448469 case sequence maybeResults of
449470 Nothing ->
450471 do Reporting.report key Reporting.DBroken
451− return (Left BadBuild)
472+ return $ Left $ Just $ Exit.BD_BadBuild pkg vsn f
452473
453474 Just results ->
454475 let
@@ -456,6 +477,7 @@ build key cache depsMVar pkg (Solver.Details vsn _) fingerprints =
456477 ifaces = gatherInterfaces exposedDict results
457478 objects = gatherObjects results
458479 artifacts = Artifacts ifaces objects
480+ fingerprints = Set.insert f fs
459481 in
460482 do writeDocs cache pkg vsn docsStatus results
461483 File.writeBinary path (ArtifactCache fingerprints artifacts)
@@ -573,7 +595,7 @@ crawlModule foreignDeps mvar pkg src docsStatus name =
573595crawlFile :: Map.Map ModuleName.Raw ForeignInterface -> MVar StatusDict -> Pkg.Name -> FilePath -> DocsStatus -> ModuleName.Raw -> FilePath -> IO (Maybe Status)
574596crawlFile foreignDeps mvar pkg src docsStatus expectedName path =
575597 do bytes <- File.readUtf8 path
576− case Parse.fromByteString pkg bytes of
598+ case Parse.fromByteString (Parse.Package pkg) bytes of
577599 Right modul@(Src.Module (Just (A.At _ actualName)) _ _ imports _ _ _ _ _) | expectedName == actualName ->
578600 do deps <- crawlImports foreignDeps mvar pkg src imports
579601 return (Just (SLocal docsStatus deps modul))
@@ -760,27 +782,40 @@ endpointDecoder =
760782
761783
762784instance Binary Details where
763− get = do { a <- get; b <- get; c <- get; d <- get; return (Details a b c d ArtifactsCached) }
764− put (Details a b c d _) = put a >> put b >> put c >> put d
785+ put (Details a b c d e _) = put a >> put b >> put c >> put d >> put e
786+ get =
787+ do a <- get
788+ b <- get
789+ c <- get
790+ d <- get
791+ e <- get
792+ return (Details a b c d e ArtifactsCached)
765793
766794
767795instance Binary ValidOutline where
768796 put outline =
769797 case outline of
770− ValidApp a -> putWord8 0 >> put a
771− ValidPkg a b -> putWord8 1 >> put a >> put b
798+ ValidApp a -> putWord8 0 >> put a
799+ ValidPkg a b c -> putWord8 1 >> put a >> put b >> put c
772800
773801 get =
774802 do n <- getWord8
775803 case n of
776804 0 -> liftM ValidApp get
777− 1 -> liftM2 ValidPkg get get
778− _ -> error "binary encoding of ValidOutline was corrupted"
805+ 1 -> liftM3 ValidPkg get get get
806+ _ -> fail "binary encoding of ValidOutline was corrupted"
779807
780808
781809instance Binary Local where
782− get = liftM4 Local get get get get
783− put (Local a b c d) = put a >> put b >> put c >> put d
810+ put (Local a b c d e f) = put a >> put b >> put c >> put d >> put e >> put f
811+ get =
812+ do a <- get
813+ b <- get
814+ c <- get
815+ d <- get
816+ e <- get
817+ f <- get
818+ return (Local a b c d e f)
784819
785820
786821instance Binary Foreign where
builder/src/Elm/Outline.hs+103−15
@@ -5,6 +5,7 @@ module Elm.Outline
55 , AppOutline(..)
66 , PkgOutline(..)
77 , Exposed(..)
8+ , SrcDir(..)
89 , read
910 , write
1011 , encode
@@ -16,11 +17,14 @@ module Elm.Outline
1617
1718
1819import Prelude hiding (read)
19−import Control.Monad (filterM)
20+import Control.Monad (filterM, liftM)
21+import Data.Binary (Binary, get, put, getWord8, putWord8)
2022import qualified Data.Map as Map
2123import qualified Data.NonEmptyList as NE
24+import qualified Data.OneOrMore as OneOrMore
2225import Foreign.Ptr (minusPtr)
2326import qualified System.Directory as Dir
27+import qualified System.FilePath as FP
2428import System.FilePath ((</>))
2529
2630import qualified Elm.Constraint as Con
@@ -49,7 +53,7 @@ data Outline
4953data AppOutline =
5054 AppOutline
5155 { _app_elm_version :: V.Version
52− , _app_source_dirs :: NE.List FilePath
56+ , _app_source_dirs :: NE.List SrcDir
5357 , _app_deps_direct :: Map.Map Pkg.Name V.Version
5458 , _app_deps_indirect :: Map.Map Pkg.Name V.Version
5559 , _app_test_direct :: Map.Map Pkg.Name V.Version
@@ -75,6 +79,11 @@ data Exposed
7579 | ExposedDict [(Json.String, [ModuleName.Raw])]
7680
7781
82+data SrcDir
83+ = AbsoluteSrcDir FilePath
84+ | RelativeSrcDir FilePath
85+
86+
7887
7988-- DEFAULTS
8089
@@ -117,7 +126,7 @@ encode outline =
117126 App (AppOutline elm srcDirs depsDirect depsTrans testDirect testTrans) ->
118127 E.object
119128 [ "type" ==> E.chars "application"
120− , "source-directories" ==> E.list E.chars (NE.toList srcDirs)
129+ , "source-directories" ==> E.list encodeSrcDir (NE.toList srcDirs)
121130 , "elm-version" ==> V.encode elm
122131 , "dependencies" ==>
123132 E.object
@@ -165,6 +174,13 @@ encodeDeps encodeValue deps =
165174 E.dict Pkg.toJsonString encodeValue deps
166175
167176
177+encodeSrcDir :: SrcDir -> E.Value
178+encodeSrcDir srcDir =
179+ case srcDir of
180+ AbsoluteSrcDir dir -> E.chars dir
181+ RelativeSrcDir dir -> E.chars dir
182+
183+
168184
169185-- PARSE AND VERIFY
170186
@@ -184,19 +200,66 @@ read root =
184200 then Left Exit.OutlineNoPkgCore
185201 else Right outline
186202
187− App (AppOutline _ srcDirs deps _ _ _)
188− | Map.notMember Pkg.core deps -> return $ Left Exit.OutlineNoAppCore
189− | Map.notMember Pkg.json deps -> return $ Left Exit.OutlineNoAppJson
203+ App (AppOutline _ srcDirs direct indirect _ _)
204+ | Map.notMember Pkg.core direct ->
205+ return $ Left Exit.OutlineNoAppCore
206+
207+ | Map.notMember Pkg.json direct && Map.notMember Pkg.json indirect ->
208+ return $ Left Exit.OutlineNoAppJson
209+
190210 | otherwise ->
191− do badDirs <- filterM (isBadSrcDir root) (NE.toList srcDirs)
192− case badDirs of
193− [] -> return $ Right outline
194− d:ds -> return $ Left (Exit.OutlineHasBadSrcDirs d ds)
211+ do badDirs <- filterM (isSrcDirMissing root) (NE.toList srcDirs)
212+ case map toGiven badDirs of
213+ d:ds ->
214+ return $ Left (Exit.OutlineHasMissingSrcDirs d ds)
215+
216+ [] ->
217+ do maybeDups <- detectDuplicates root (NE.toList srcDirs)
218+ case maybeDups of
219+ Nothing ->
220+ return $ Right outline
221+
222+ Just (canonicalDir, (dir1,dir2)) ->
223+ return $ Left (Exit.OutlineHasDuplicateSrcDirs canonicalDir dir1 dir2)
224+
225+
226+isSrcDirMissing :: FilePath -> SrcDir -> IO Bool
227+isSrcDirMissing root srcDir =
228+ not <$> Dir.doesDirectoryExist (toAbsolute root srcDir)
229+
230+
231+toGiven :: SrcDir -> FilePath
232+toGiven srcDir =
233+ case srcDir of
234+ AbsoluteSrcDir dir -> dir
235+ RelativeSrcDir dir -> dir
236+
195237
238+toAbsolute :: FilePath -> SrcDir -> FilePath
239+toAbsolute root srcDir =
240+ case srcDir of
241+ AbsoluteSrcDir dir -> dir
242+ RelativeSrcDir dir -> root </> dir
196243
197−isBadSrcDir :: FilePath -> FilePath -> IO Bool
198−isBadSrcDir root dir =
199− not <$> Dir.doesDirectoryExist (root </> dir)
244+
245+detectDuplicates :: FilePath -> [SrcDir] -> IO (Maybe (FilePath, (FilePath, FilePath)))
246+detectDuplicates root srcDirs =
247+ do pairs <- traverse (toPair root) srcDirs
248+ return $ Map.lookupMin $ Map.mapMaybe isDup $
249+ Map.fromListWith OneOrMore.more pairs
250+
251+
252+toPair :: FilePath -> SrcDir -> IO (FilePath, OneOrMore.OneOrMore FilePath)
253+toPair root srcDir =
254+ do key <- Dir.canonicalizePath (toAbsolute root srcDir)
255+ return (key, OneOrMore.one (toGiven srcDir))
256+
257+
258+isDup :: OneOrMore.OneOrMore FilePath -> Maybe (FilePath, FilePath)
259+isDup paths =
260+ case paths of
261+ OneOrMore.One _ -> Nothing
262+ OneOrMore.More a b -> Just (OneOrMore.getFirstTwo a b)
200263
201264
202265
@@ -274,9 +337,16 @@ depsDecoder valueDecoder =
274337 D.dict (Pkg.keyDecoder Exit.OP_BadDependencyName) valueDecoder
275338
276339
277−dirsDecoder :: Decoder (NE.List FilePath)
340+dirsDecoder :: Decoder (NE.List SrcDir)
278341dirsDecoder =
279− fmap Json.toChars <$> D.nonEmptyList D.string Exit.OP_NoSrcDirs
342+ fmap (toSrcDir . Json.toChars) <$> D.nonEmptyList D.string Exit.OP_NoSrcDirs
343+
344+
345+toSrcDir :: FilePath -> SrcDir
346+toSrcDir path =
347+ if FP.isRelative path
348+ then RelativeSrcDir path
349+ else AbsoluteSrcDir path
280350
281351
282352
@@ -317,3 +387,21 @@ boundParser bound tooLong =
317387 if len < bound
318388 then cok (Json.fromPtr pos end) (P.State src end end indent row newCol)
319389 else cerr row newCol (\_ _ -> tooLong)
390+
391+
392+
393+-- BINARY
394+
395+
396+instance Binary SrcDir where
397+ put outline =
398+ case outline of
399+ AbsoluteSrcDir a -> putWord8 0 >> put a
400+ RelativeSrcDir a -> putWord8 1 >> put a
401+
402+ get =
403+ do n <- getWord8
404+ case n of
405+ 0 -> liftM AbsoluteSrcDir get
406+ 1 -> liftM RelativeSrcDir get
407+ _ -> fail "binary encoding of SrcDir was corrupted"
builder/src/File.hs+20−3
@@ -78,8 +78,21 @@ readBinary path =
7878 then
7979 do result <- Binary.decodeFileOrFail path
8080 case result of
81− Right a -> return (Just a)
82− Left _ -> return Nothing
81+ Right a ->
82+ return (Just a)
83+
84+ Left (offset, message) ->
85+ do IO.hPutStrLn IO.stderr $ unlines $
86+ [ "+-------------------------------------------------------------------------------"
87+ , "| Corrupt File: " ++ path
88+ , "| Byte Offset: " ++ show offset
89+ , "| Message: " ++ message
90+ , "|"
91+ , "| Please report this to https://github.com/elm/compiler/issues"
92+ , "| Trying to continue anyway."
93+ , "+-------------------------------------------------------------------------------"
94+ ]
95+ return Nothing
8396 else
8497 return Nothing
8598
@@ -177,7 +190,11 @@ writeEntry destination root entry =
177190 let
178191 path = drop root (Zip.eRelativePath entry)
179192 in
180− if path == "LICENSE" || List.isPrefixOf "src/" path then
193+ if List.isPrefixOf "src/" path
194+ || path == "LICENSE"
195+ || path == "README.md"
196+ || path == "elm.json"
197+ then
181198 if not (null path) && last path == '/'
182199 then Dir.createDirectoryIfMissing True (destination </> path)
183200 else LBS.writeFile (destination </> path) (Zip.fromEntry entry)
builder/src/Generate.hs+7−7
@@ -99,18 +99,18 @@ checkForDebugUses (Objects _ locals) =
9999-- GATHER MAINS
100100
101101
102−gatherMains :: Pkg.Name -> Objects -> NE.List Build.Main -> Map.Map ModuleName.Canonical Opt.Main
103−gatherMains pkg (Objects _ locals) buildMains =
104− Map.fromList $ Maybe.mapMaybe (lookupMain pkg locals) (NE.toList buildMains)
102+gatherMains :: Pkg.Name -> Objects -> NE.List Build.Root -> Map.Map ModuleName.Canonical Opt.Main
103+gatherMains pkg (Objects _ locals) roots =
104+ Map.fromList $ Maybe.mapMaybe (lookupMain pkg locals) (NE.toList roots)
105105
106106
107−lookupMain :: Pkg.Name -> Map.Map ModuleName.Raw Opt.LocalGraph -> Build.Main -> Maybe (ModuleName.Canonical, Opt.Main)
108−lookupMain pkg locals buildMain =
107+lookupMain :: Pkg.Name -> Map.Map ModuleName.Raw Opt.LocalGraph -> Build.Root -> Maybe (ModuleName.Canonical, Opt.Main)
108+lookupMain pkg locals root =
109109 let
110110 toPair name (Opt.LocalGraph maybeMain _ _) =
111111 (,) (ModuleName.Canonical pkg name) <$> maybeMain
112112 in
113− case buildMain of
113+ case root of
114114 Build.Inside name -> toPair name =<< Map.lookup name locals
115115 Build.Outside name _ g -> toPair name g
116116
@@ -200,7 +200,7 @@ loadTypesHelp root modul =
200200 Build.Unneeded ->
201201 do mvar <- newEmptyMVar
202202 _ <- forkIO $
203− do maybeIface <- File.readBinary (Stuff.elmo root name)
203+ do maybeIface <- File.readBinary (Stuff.elmi root name)
204204 putMVar mvar (Extract.fromInterface name <$> maybeIface)
205205 return mvar
206206
builder/src/Http.hs+1−1
@@ -241,4 +241,4 @@ jsonPart name filePath value =
241241
242242stringPart :: String -> String -> Multi.Part
243243stringPart name string =
244− Multi.partBS (String.fromString name) (BS.pack string)
244+ Multi.partBS (String.fromString name) (BS.pack string)
builder/src/Reporting.hs+15−12
@@ -33,7 +33,7 @@ import qualified Data.ByteString.Builder as B
3333import qualified Data.NonEmptyList as NE
3434import qualified System.Exit as Exit
3535import qualified System.Info as Info
36−import System.IO (hFlush, hPutStr, stderr, stdout)
36+import System.IO (hFlush, hPutStr, hPutStrLn, stderr, stdout)
3737
3838import qualified Elm.ModuleName as ModuleName
3939import qualified Elm.Package as Pkg
@@ -364,10 +364,10 @@ toFinalMessage done result =
364364
365365 Left problem ->
366366 case problem of
367− Exit.BuildBadModules _ [] ->
367+ Exit.BuildBadModules _ _ [] ->
368368 "Detected problems in 1 module."
369369
370− Exit.BuildBadModules _ (_:ps) ->
370+ Exit.BuildBadModules _ _ (_:ps) ->
371371 "Detected problems in " ++ show (2 + length ps) ++ " modules."
372372
373373 Exit.BuildProjectProblem _ ->
@@ -446,20 +446,23 @@ reportExceptionsNicely e =
446446
447447
448448putException :: SomeException -> IO ()
449−putException e =
449+putException e = do
450+ hPutStrLn stderr ""
450451 Help.toStderr $ D.stack $
451− [ D.reflow $
452− "Oh no! I ran into something that bypassed the normal error reporting process!\
452+ [ D.dullyellow "-- ERROR -----------------------------------------------------------------------"
453+ , D.reflow $
454+ "I ran into something that bypassed the normal error reporting process!\
453455 \ I extracted whatever information I could from the internal error:"
454456 , D.vcat $ map (\line -> D.red ">" <> " " <> D.fromChars line) (lines (show e))
455457 , D.reflow $
456− "These errors are usually pretty confusing, so start by asking around on Slack\
457− \ or Discourse to see if anyone can get you unstuck quickly."
458− , "------------------------------------------------------------"
458+ "These errors are usually pretty confusing, so start by asking around on one of\
459+ \ forums listed at https://elm-lang.org/community to see if anyone can get you\
460+ \ unstuck quickly."
461+ , D.dullyellow "-- REQUEST ---------------------------------------------------------------------"
459462 , D.reflow $
460− "From there, if you are feeling up to it, please try to get your code down to the\
461− \ smallest version that still triggers this message. Ideally in a single Main.elm\
462− \ and elm.json file."
463+ "If you are feeling up to it, please try to get your code down to the smallest\
464+ \ version that still triggers this message. Ideally in a single Main.elm and\
465+ \ elm.json file."
463466 , D.reflow $
464467 "From there open a NEW issue at https://github.com/elm/compiler/issues with\
465468 \ your reduced example pasted in directly. (Not a link to a repo or gist!) Do not\
builder/src/Reporting/Exit.hs+275−93
@@ -14,6 +14,7 @@ module Reporting.Exit
1414 , Outline(..)
1515 , OutlineProblem(..)
1616 , Details(..)
17+ , DetailsBadDep(..)
1718 , PackageProblem(..)
1819 , RegistryProblem(..)
1920 , BuildProblem(..)
@@ -29,16 +30,16 @@ module Reporting.Exit
2930
3031
3132import qualified Data.ByteString as BS
32−import qualified Data.ByteString.Builder as B
33−import qualified Data.ByteString.Char8 as BSC
34−import qualified Data.ByteString.Lazy as LBS
3533import qualified Data.ByteString.UTF8 as BS_UTF8
3634import qualified Data.List as List
35+import qualified Data.Map as Map
3736import qualified Data.Name as N
3837import qualified Data.NonEmptyList as NE
3938import qualified Network.HTTP.Client as HTTP
4039import qualified Network.HTTP.Types.Header as HTTP
4140import qualified Network.HTTP.Types.Status as HTTP
41+import qualified System.FilePath as FP
42+import System.FilePath ((</>), (<.>))
4243
4344import qualified Elm.Constraint as C
4445import qualified Elm.Magnitude as M
@@ -173,7 +174,7 @@ diffToReport diff =
173174 \ with packages. That way there are previously published versions of the API to\
174175 \ diff against!"
175176 [ D.reflow $ "If you are just curious to see a diff, try running this command:"
176− , D.indent 4 $ D.dullyellow $ "elm diff elm/http 1.0.0 2.0.0"
177+ , D.indent 4 $ D.dullyellow $ "elm diff elm/json 1.0.0 1.1.2"
177178 ]
178179
179180 DiffNoExposed ->
@@ -739,12 +740,14 @@ data Install
739740 | InstallBadOutline Outline
740741 | InstallBadRegistry RegistryProblem
741742 | InstallNoArgs FilePath
742− | InstallNoOnlineSolution
743− | InstallNoOfflineSolution
743+ | InstallNoOnlineAppSolution Pkg.Name
744+ | InstallNoOfflineAppSolution Pkg.Name
745+ | InstallNoOnlinePkgSolution Pkg.Name
746+ | InstallNoOfflinePkgSolution Pkg.Name
744747 | InstallHadSolverTrouble Solver
745748 | InstallUnknownPackageOnline Pkg.Name [Pkg.Name]
746749 | InstallUnknownPackageOffline Pkg.Name [Pkg.Name]
747− | InstallHasBadDetails Pkg.Name Encode.Value
750+ | InstallBadDetails Details
748751
749752
750753installToReport :: Install -> Help.Report
@@ -787,18 +790,75 @@ installToReport exit =
787790 ]
788791 ]
789792
790− InstallNoOnlineSolution ->
791− Help.report "UNSOLVABLE DEPENDENCIES" (Just "elm.json") -- TODO recommend using solver in `elm reactor`
792− "This usually happens if you try to modify dependency constraints by\
793− \ hand. I recommend deleting any dependency you added recently (or all\
794− \ of them if things are bad) and then adding them again with:"
795− [ D.indent 4 $ D.green "elm install"
793+ InstallNoOnlineAppSolution pkg ->
794+ Help.report "CANNOT FIND COMPATIBLE VERSION" (Just "elm.json")
795+ (
796+ "I cannot find a version of " ++ Pkg.toChars pkg ++ " that is compatible\
797+ \ with your existing dependencies."
798+ )
799+ [ D.reflow $
800+ "I checked all the published versions. When that failed, I tried to find any\
801+ \ compatible combination of these packages, even if it meant changing all your\
802+ \ existing dependencies! That did not work either!"
803+ , D.reflow $
804+ "This is most likely to happen when a package is not upgraded yet. Maybe a new\
805+ \ version of Elm came out recently? Maybe a common package was changed recently?\
806+ \ Maybe a better package came along, so there was no need to upgrade this one?\
807+ \ Try asking around https://elm-lang.org/community to learn what might be going on\
808+ \ with this package."
809+ , D.toSimpleNote $
810+ "Whatever the case, please be kind to the relevant package authors! Having\
811+ \ friendly interactions with users is great motivation, and conversely, getting\
812+ \ berated by strangers on the internet sucks your soul dry. Furthermore, package\
813+ \ authors are humans with families, friends, jobs, vacations, responsibilities,\
814+ \ goals, etc. They face obstacles outside of their technical work you will never\
815+ \ know about, so please assume the best and try to be patient and supportive!"
816+ ]
817+
818+ InstallNoOfflineAppSolution pkg ->
819+ Help.report "CANNOT FIND COMPATIBLE VERSION LOCALLY" (Just "elm.json")
820+ (
821+ "I cannot find a version of " ++ Pkg.toChars pkg ++ " that is compatible\
822+ \ with your existing dependencies."
823+ )
824+ [ D.reflow $
825+ "I was not able to connect to https://package.elm-lang.org/ though, so I was only\
826+ \ able to look through packages that you have downloaded in the past."
796827 , D.reflow $
797− "And do not be afaid to ask for help on Slack if you get stuck!"
828+ "Try again later when you have internet!"
798829 ]
799830
800− InstallNoOfflineSolution ->
801− error "TODO InstallNoOfflineSolution"
831+ InstallNoOnlinePkgSolution pkg ->
832+ Help.report "CANNOT FIND COMPATIBLE VERSION" (Just "elm.json")
833+ (
834+ "I cannot find a version of " ++ Pkg.toChars pkg ++ " that is compatible\
835+ \ with your existing constraints."
836+ )
837+ [ D.reflow $
838+ "With applications, I try to broaden the constraints to see if anything works,\
839+ \ but messing with package constraints is much more delicate business. E.g. making\
840+ \ your constraints stricter may make it harder for applications to find compatible\
841+ \ dependencies. So fixing something here may break it for a lot of other people!"
842+ , D.reflow $
843+ "So I recommend making an application with the same dependencies as your package.\
844+ \ See if there is a solution at all. From there it may be easier to figure out\
845+ \ how to proceed in a way that will disrupt your users as little as possible. And\
846+ \ the solution may be to help other package authors to get their packages updated,\
847+ \ or to drop a dependency entirely."
848+ ]
849+
850+ InstallNoOfflinePkgSolution pkg ->
851+ Help.report "CANNOT FIND COMPATIBLE VERSION LOCALLY" (Just "elm.json")
852+ (
853+ "I cannot find a version of " ++ Pkg.toChars pkg ++ " that is compatible\
854+ \ with your existing constraints."
855+ )
856+ [ D.reflow $
857+ "I was not able to connect to https://package.elm-lang.org/ though, so I was only\
858+ \ able to look through packages that you have downloaded in the past."
859+ , D.reflow $
860+ "Try again later when you have internet!"
861+ ]
802862
803863 InstallHadSolverTrouble solver ->
804864 toSolverReport solver
@@ -831,40 +891,8 @@ installToReport exit =
831891 , D.reflow $ "Maybe you want one of these instead?"
832892 ]
833893
834− InstallHasBadDetails pkg outline ->
835− Help.report "INSTALL PROBLEM" Nothing
836− (
837− "I found a version of " ++ Pkg.toChars pkg ++ " that claims to be compatible with\
838− \ your existing dependencies, but I ran into an error when I tried to build it locally."
839− )
840− [ D.reflow $
841− "Here is an elm.json that should reproduce the error with a bit more information:"
842− , D.indent 4 $ D.dullyellow $ D.vcat $ map D.fromChars $
843− map BS_UTF8.toString $ BSC.lines $ LBS.toStrict $ B.toLazyByteString $
844− Encode.encode outline
845− , D.reflow $
846− "Maybe that can help figure out what is going on here."
847− ]
848−
849−
850−{- TODO detect if library has no 0.19.0 version. Maybe do this on website though?
851− Help.report "OLD DEPENDENCIES" (Just "elm.json")
852− ( "The following packages do not work with Elm " ++ V.toChars V.compiler ++ " right now:"
853− )
854− [ D.indent 4 $ D.vcat $ map (D.red . D.fromPackage) badPackages
855− , D.reflow $
856− "This may be because it is not upgraded yet. It may be because a\
857− \ better solution came along, so there was no need to upgrade it.\
858− \ Etc. Try asking around on Slack to learn more about the topic."
859− , D.toSimpleNote
860− "Whatever the case, please be kind to the relevant package authors! Having\
861− \ friendly interactions with users is great motivation, and conversely, getting\
862− \ berated by strangers on the internet sucks your soul dry. Furthermore, package\
863− \ authors are humans with families, friends, jobs, vacations, responsibilities,\
864− \ goals, etc. They face obstacles outside of their technical work you will never\
865− \ know about, so please assume the best and try to be patient and supportive!"
866− ]
867−-}
894+ InstallBadDetails details ->
895+ toDetailsReport details
868896
869897
870898
@@ -919,7 +947,8 @@ toSolverReport problem =
919947
920948data Outline
921949 = OutlineHasBadStructure (Decode.Error OutlineProblem)
922− | OutlineHasBadSrcDirs FilePath [FilePath]
950+ | OutlineHasMissingSrcDirs FilePath [FilePath]
951+ | OutlineHasDuplicateSrcDirs FilePath FilePath FilePath
923952 | OutlineNoPkgCore
924953 | OutlineNoAppCore
925954 | OutlineNoAppJson
@@ -945,12 +974,12 @@ toOutlineReport problem =
945974 Json.toReport "elm.json" (Json.FailureToReport toOutlineProblemReport) decodeError $
946975 Json.ExplicitReason "I ran into a problem with your elm.json file."
947976
948− OutlineHasBadSrcDirs dir dirs ->
977+ OutlineHasMissingSrcDirs dir dirs ->
949978 case dirs of
950979 [] ->
951980 Help.report "MISSING SOURCE DIRECTORY" (Just "elm.json")
952981 "I need a valid elm.json file, but the \"source-directories\" field lists the following directory:"
953− [ D.indent 4 $ D.dullyellow $ D.fromChars dir
982+ [ D.indent 4 $ D.red $ D.fromChars dir
954983 , D.reflow $
955984 "I cannot find it though. Is it missing? Is there a typo?"
956985 ]
@@ -958,30 +987,61 @@ toOutlineReport problem =
958987 _:_ ->
959988 Help.report "MISSING SOURCE DIRECTORIES" (Just "elm.json")
960989 "I need a valid elm.json file, but the \"source-directories\" field lists the following directories:"
961− [ D.indent 4 $ D.dullyellow $ D.fromChars dir
990+ [ D.indent 4 $ D.vcat $
991+ map (D.red . D.fromChars) (dir:dirs)
962992 , D.reflow $
963993 "I cannot find them though. Are they missing? Are there typos?"
964994 ]
965995
996+ OutlineHasDuplicateSrcDirs canonicalDir dir1 dir2 ->
997+ if dir1 == dir2 then
998+ Help.report "REDUNDANT SOURCE DIRECTORIES" (Just "elm.json")
999+ "I need a valid elm.json file, but the \"source-directories\" field lists the same directory twice:"
1000+ [ D.indent 4 $ D.vcat $
1001+ map (D.red . D.fromChars) [dir1,dir2]
1002+ , D.reflow $
1003+ "Remove one of the entries!"
1004+ ]
1005+ else
1006+ Help.report "REDUNDANT SOURCE DIRECTORIES" (Just "elm.json")
1007+ "I need a valid elm.json file, but the \"source-directories\" field has some redundant directories:"
1008+ [ D.indent 4 $ D.vcat $
1009+ map (D.red . D.fromChars) [dir1,dir2]
1010+ , D.reflow $
1011+ "These are two different ways of refering to the same directory:"
1012+ , D.indent 4 $ D.dullyellow $ D.fromChars canonicalDir
1013+ , D.reflow $
1014+ "Remove one of the redundant entries from your \"source-directories\" field."
1015+ ]
1016+
9661017 OutlineNoPkgCore ->
9671018 Help.report "MISSING DEPENDENCY" (Just "elm.json")
968− "I need a valid elm.json file, so I need to see an \"elm/core\" dependency in there. Try running:"
969− [ D.indent 4 $ D.green $ "elm install elm/core"
970− , D.reflow "I need it for the default imports that make `List` and `Maybe` available."
1019+ "I need to see an \"elm/core\" dependency your elm.json file. The default imports\
1020+ \ of `List` and `Maybe` do not work without it."
1021+ [ D.reflow $
1022+ "If you modified your elm.json by hand, try to change it back! And if you are\
1023+ \ having trouble getting back to a working elm.json, it may be easier to find a\
1024+ \ working package and start fresh with their elm.json file."
9711025 ]
9721026
9731027 OutlineNoAppCore ->
9741028 Help.report "MISSING DEPENDENCY" (Just "elm.json")
975− "I need a valid elm.json file, so I need to see an \"elm/core\" dependency in there. Try running:"
976− [ D.indent 4 $ D.green $ "elm install elm/core"
977− , D.reflow "It has some supporting code that is needed by every Elm application!"
1029+ "I need to see an \"elm/core\" dependency your elm.json file. The default imports\
1030+ \ of `List` and `Maybe` do not work without it."
1031+ [ D.reflow $
1032+ "If you modified your elm.json by hand, try to change it back! And if you are\
1033+ \ having trouble getting back to a working elm.json, it may be easier to delete it\
1034+ \ and use `elm init` to start fresh."
9781035 ]
9791036
9801037 OutlineNoAppJson ->
9811038 Help.report "MISSING DEPENDENCY" (Just "elm.json")
982− "I need a valid elm.json file, so I need to see an \"elm/json\" dependency in there. Try running:"
983− [ D.indent 4 $ D.green $ "elm install elm/json"
984− , D.reflow "It helps me handle flags and ports."
1039+ "I need to see an \"elm/json\" dependency your elm.json file. It helps me handle\
1040+ \ flags and ports."
1041+ [ D.reflow $
1042+ "If you modified your elm.json by hand, try to change it back! And if you are\
1043+ \ having trouble getting back to a working elm.json, it may be easier to delete it\
1044+ \ and use `elm init` to start fresh."
9851045 ]
9861046
9871047
@@ -1115,10 +1175,16 @@ toOutlineProblemReport path source _ region problem =
11151175 toSnippet "HEADER TOO LONG" Nothing
11161176 ( D.reflow $
11171177 "I got stuck while reading your elm.json file. This section header is too long:"
1118− , D.fillSep
1119− ["I","need","it","to","be"
1120− ,D.green "under",D.green "20",D.green "characters"
1121− ,"so","it","renders","nicely","on","the","package","website!"
1178+ , D.stack
1179+ [ D.fillSep
1180+ ["I","need","it","to","be"
1181+ ,D.green "under",D.green "20",D.green "bytes"
1182+ ,"so","it","renders","nicely","on","the","package","website!"
1183+ ]
1184+ , D.toSimpleNote
1185+ "I count the length in bytes, so using non-ASCII characters costs extra.\
1186+ \ Please report your case at https://github.com/elm/compiler/issues if this seems\
1187+ \ overly restrictive for your needs."
11221188 ]
11231189 )
11241190
@@ -1163,10 +1229,16 @@ toOutlineProblemReport path source _ region problem =
11631229 toSnippet "SUMMARY TOO LONG" Nothing
11641230 ( D.reflow $
11651231 "I got stuck while reading your elm.json file. Your \"summary\" is too long:"
1166− , D.fillSep
1167− ["I","need","it","to","be"
1168− ,D.green "under",D.green "80",D.green "characters"
1169− ,"so","it","renders","nicely","on","the","package","website!"
1232+ , D.stack
1233+ [ D.fillSep
1234+ ["I","need","it","to","be"
1235+ ,D.green "under",D.green "80",D.green "bytes"
1236+ ,"so","it","renders","nicely","on","the","package","website!"
1237+ ]
1238+ , D.toSimpleNote
1239+ "I count the length in bytes, so using non-ASCII characters costs extra.\
1240+ \ Please report your case at https://github.com/elm/compiler/issues if this seems\
1241+ \ overly restrictive for your needs."
11701242 ]
11711243 )
11721244
@@ -1194,7 +1266,12 @@ data Details
11941266 | DetailsHandEditedDependencies
11951267 | DetailsBadOutline Outline
11961268 | DetailsCannotGetRegistry RegistryProblem
1197− | DetailsCannotBuildPackage Pkg.Name V.Version PackageProblem
1269+ | DetailsBadDeps FilePath [DetailsBadDep]
1270+
1271+
1272+data DetailsBadDep
1273+ = BD_BadDownload Pkg.Name V.Version PackageProblem
1274+ | BD_BadBuild Pkg.Name V.Version (Map.Map Pkg.Name V.Version)
11981275
11991276
12001277toDetailsReport :: Details -> Help.Report
@@ -1205,8 +1282,7 @@ toDetailsReport details =
12051282 "The dependencies in your elm.json are not compatible."
12061283 [ D.fillSep
12071284 ["Did","you","change","them","by","hand?","Try","to","change","it","back!"
1208− ,"It","is","much","more","reliable","to","add","dependencies","with",D.green "elm install"
1209− ,"or","the","dependency","management","tool","in",D.green "elm reactor" <> "."
1285+ ,"It","is","much","more","reliable","to","add","dependencies","with",D.green "elm install" <> "."
12101286 ]
12111287 , D.reflow $
12121288 "Please ask for help on the community forums if you try those paths and are still\
@@ -1223,8 +1299,7 @@ toDetailsReport details =
12231299 \ get access to the registry!"
12241300 , D.toFancyNote
12251301 ["If","you","changed","your","dependencies","by","hand,","try","to","change","them","back!"
1226− ,"It","is","much","more","reliable","to","add","dependencies","with",D.green "elm install"
1227− ,"or","the","dependency","management","tool","in",D.green "elm reactor" <> "."
1302+ ,"It","is","much","more","reliable","to","add","dependencies","with",D.green "elm install" <> "."
12281303 ]
12291304 ]
12301305
@@ -1260,8 +1335,7 @@ toDetailsReport details =
12601335 \ party tool) leaving them in an invalid state."
12611336 [ D.fillSep
12621337 ["Try","to","change","them","back","to","what","they","were","before!"
1263− ,"It","is","much","more","reliable","to","add","dependencies","with",D.green "elm install"
1264− ,"or","the","dependency","management","tool","in",D.green "elm reactor" <> "."
1338+ ,"It","is","much","more","reliable","to","add","dependencies","with",D.green "elm install" <> "."
12651339 ]
12661340 , D.reflow $
12671341 "Please ask for help on the community forums if you try those paths and are still\
@@ -1275,8 +1349,52 @@ toDetailsReport details =
12751349 toRegistryProblemReport "PROBLEM LOADING PACKAGE LIST" problem $
12761350 "I need the list of published packages to verify your dependencies"
12771351
1278− DetailsCannotBuildPackage pkg vsn problem ->
1279− toPackageProblemReport pkg vsn problem
1352+ DetailsBadDeps cacheDir deps ->
1353+ case List.sortOn toBadDepRank deps of
1354+ [] ->
1355+ Help.report "PROBLEM BUILDING DEPENDENCIES" Nothing
1356+ "I am not sure what is going wrong though."
1357+ [ D.reflow $
1358+ "I would try deleting the " ++ cacheDir ++ " and elm-stuff/ directories, then\
1359+ \ trying to build again. That will work if some cached files got corrupted\
1360+ \ somehow."
1361+ , D.reflow $
1362+ "If that does not work, go to https://elm-lang.org/community and ask for\
1363+ \ help. This is a weird case!"
1364+ ]
1365+
1366+ d:_ ->
1367+ case d of
1368+ BD_BadDownload pkg vsn packageProblem ->
1369+ toPackageProblemReport pkg vsn packageProblem
1370+
1371+ BD_BadBuild pkg vsn fingerprint ->
1372+ Help.report "PROBLEM BUILDING DEPENDENCIES" Nothing
1373+ "I ran into a compilation error when trying to build the following package:"
1374+ [ D.indent 4 $ D.red $ D.fromChars $ Pkg.toChars pkg ++ " " ++ V.toChars vsn
1375+ , D.reflow $
1376+ "This probably means it has package constraints that are too wide. It may be\
1377+ \ possible to tweak your elm.json to avoid the root problem as a stopgap. Head\
1378+ \ over to https://elm-lang.org/community to get help figuring out how to take\
1379+ \ this path!"
1380+ , D.toSimpleNote $
1381+ "To help with the root problem, please report this to the package author along\
1382+ \ with the following information:"
1383+ , D.indent 4 $ D.vcat $
1384+ map (\(p,v) -> D.fromChars $ Pkg.toChars p ++ " " ++ V.toChars v) $
1385+ Map.toList fingerprint
1386+ , D.reflow $
1387+ "If you want to help out even more, try building the package locally. That should\
1388+ \ give you much more specific information about why this package is failing to\
1389+ \ build, which will in turn make it easier for the package author to fix it!"
1390+ ]
1391+
1392+
1393+toBadDepRank :: DetailsBadDep -> Int -- lower is better
1394+toBadDepRank badDep =
1395+ case badDep of
1396+ BD_BadDownload _ _ _ -> 0
1397+ BD_BadBuild _ _ _ -> 1
12801398
12811399
12821400
@@ -1404,7 +1522,7 @@ toHttpErrorReport title err context =
14041522
14051523 Http.BadHttp url httpExceptionContent ->
14061524 case httpExceptionContent of
1407− HTTP.StatusCodeException response _ ->
1525+ HTTP.StatusCodeException response body ->
14081526 let
14091527 (HTTP.Status code message) = HTTP.responseStatus response
14101528 in
@@ -1412,6 +1530,7 @@ toHttpErrorReport title err context =
14121530 [ D.fillSep $
14131531 ["But","it","came","back","as",D.red (D.fromInt code)]
14141532 ++ map D.fromChars (words (BS_UTF8.toString message))
1533+ , D.indent 4 $ D.reflow $ BS_UTF8.toString body
14151534 , D.reflow $
14161535 "This may mean some online endpoint changed in an unexpected way, so if does not\
14171536 \ seem like something on your side is causing this (e.g. firewall) please report\
@@ -1531,10 +1650,27 @@ makeToReport make =
15311650 ]
15321651
15331652 MakeMultipleFilesIntoHtml ->
1534− error "MakeMultipleFilesIntoHtml"
1653+ Help.report "TOO MANY FILES" Nothing
1654+ (
1655+ "When producing an HTML file, I can only handle one file."
1656+ )
1657+ [ D.fillSep
1658+ ["Switch","to",D.dullyellow "--output=/dev/null","if","you","just","want"
1659+ ,"to","get","compile","errors.","This","skips","the","code","gen","phase,"
1660+ ,"so","it","can","be","a","bit","faster","than","other","options","sometimes."
1661+ ]
1662+ , D.fillSep
1663+ ["Switch","to",D.dullyellow "--output=elm.js","if","you","want","multiple"
1664+ ,"`main`","values","available","in","a","single","JavaScript","file.","Then"
1665+ ,"you","can","make","your","own","customized","HTML","file","that","embeds"
1666+ ,"multiple","Elm","nodes.","The","generated","JavaScript","also","shares"
1667+ ,"dependencies","between","modules,","so","it","should","be","smaller","than"
1668+ ,"compiling","each","module","separately."
1669+ ]
1670+ ]
15351671
15361672 MakeNoMain ->
1537− Help.docReport "NO MAIN" Nothing
1673+ Help.report "NO MAIN" Nothing
15381674 (
15391675 "When producing an HTML file, I require that the given file has a `main` value.\
15401676 \ That way I have something to show on screen!"
@@ -1620,7 +1756,7 @@ makeToReport make =
16201756
16211757
16221758data BuildProblem
1623− = BuildBadModules Error.Module [Error.Module]
1759+ = BuildBadModules FilePath Error.Module [Error.Module]
16241760 | BuildProjectProblem BuildProjectProblem
16251761
16261762
@@ -1629,7 +1765,8 @@ data BuildProjectProblem
16291765 | BP_WithBadExtension FilePath
16301766 | BP_WithAmbiguousSrcDir FilePath FilePath FilePath
16311767 | BP_MainPathDuplicate FilePath FilePath
1632− | BP_MainNameDuplicate ModuleName.Raw FilePath FilePath
1768+ | BP_RootNameDuplicate ModuleName.Raw FilePath FilePath
1769+ | BP_RootNameInvalid FilePath FilePath [String]
16331770 | BP_CannotLoadDependencies
16341771 | BP_Cycle ModuleName.Raw [ModuleName.Raw]
16351772 | BP_MissingExposed (NE.List (ModuleName.Raw, Import.Problem))
@@ -1638,8 +1775,8 @@ data BuildProjectProblem
16381775toBuildProblemReport :: BuildProblem -> Help.Report
16391776toBuildProblemReport problem =
16401777 case problem of
1641− BuildBadModules e es ->
1642− Help.compilerReport e es
1778+ BuildBadModules root e es ->
1779+ Help.compilerReport root e es
16431780
16441781 BuildProjectProblem projectProblem ->
16451782 toProjectProblemReport projectProblem
@@ -1696,7 +1833,7 @@ toProjectProblemReport projectProblem =
16961833 \ unstuck!"
16971834 ]
16981835
1699− BP_MainNameDuplicate name outsidePath otherPath ->
1836+ BP_RootNameDuplicate name outsidePath otherPath ->
17001837 Help.report "MODULE NAME CLASH" Nothing
17011838 "These two files are causing a module name clash:"
17021839 [ D.indent 4 $ D.red $ D.vcat $ map D.fromChars [ outsidePath, otherPath ]
@@ -1707,6 +1844,24 @@ toProjectProblemReport projectProblem =
17071844 "Try changing to a different module name in one of them!"
17081845 ]
17091846
1847+ BP_RootNameInvalid givenPath srcDir _ ->
1848+ Help.report "UNEXPECTED FILE NAME" Nothing
1849+ "I am having trouble with this file name:"
1850+ [ D.indent 4 $ D.red $ D.fromChars givenPath
1851+ , D.reflow $
1852+ "I found it in your " ++ FP.addTrailingPathSeparator srcDir ++ " directory\
1853+ \ which is good, but I expect all of the files in there to use the following\
1854+ \ module naming convention:"
1855+ , toModuleNameConventionTable srcDir [ "Main", "HomePage", "Http.Helpers" ]
1856+ , D.reflow $
1857+ "Notice that the names always start with capital letters! Can you make your file\
1858+ \ use this naming convention?"
1859+ , D.toSimpleNote $
1860+ "Having a strict naming convention like this makes it a lot easier to find\
1861+ \ things in large projects. If you see a module imported, you know where to look\
1862+ \ for the corresponding file every time!"
1863+ ]
1864+
17101865 BP_CannotLoadDependencies ->
17111866 corruptCacheReport
17121867
@@ -1762,6 +1917,33 @@ toProjectProblemReport projectProblem =
17621917 ]
17631918
17641919
1920+toModuleNameConventionTable :: FilePath -> [String] -> D.Doc
1921+toModuleNameConventionTable srcDir names =
1922+ let
1923+ toPair name =
1924+ ( name
1925+ , srcDir </> map (\c -> if c == '.' then FP.pathSeparator else c) name <.> "elm"
1926+ )
1927+
1928+ namePairs = map toPair names
1929+ nameWidth = maximum (11 : map (length . fst) namePairs)
1930+ pathWidth = maximum ( 9 : map (length . snd) namePairs)
1931+
1932+ padded width str =
1933+ str ++ replicate (width - length str) ' '
1934+
1935+ toRow (name, path) =
1936+ D.fromChars $
1937+ "| " ++ padded nameWidth name ++ " | " ++ padded pathWidth path ++ " |"
1938+
1939+ bar =
1940+ D.fromChars $
1941+ "+-" ++ replicate nameWidth '-' ++ "-+-" ++ replicate pathWidth '-' ++ "-+"
1942+ in
1943+ D.indent 4 $ D.vcat $
1944+ [ bar, toRow ("Module Name", "File Path"), bar ] ++ map toRow namePairs ++ [ bar ]
1945+
1946+
17651947
17661948-- GENERATE
17671949
@@ -1786,7 +1968,7 @@ toGenerateReport problem =
17861968 "The issue is that --optimize strips out info needed by `Debug` functions.\
17871969 \ Here are two examples:"
17881970 , D.indent 4 $ D.reflow $
1789− "(1) It shortens record field names. This makes the generated JavaScript is\
1971+ "(1) It shortens record field names. This makes the generated JavaScript\
17901972 \ smaller, but `Debug.toString` cannot know the real field names anymore."
17911973 , D.indent 4 $ D.reflow $
17921974 "(2) Values like `type Height = Height Float` are unboxed. This reduces\
@@ -1855,7 +2037,7 @@ reactorToReport problem =
18552037data Repl
18562038 = ReplBadDetails Details
18572039 | ReplBadInput BS.ByteString Error.Error
1858− | ReplBadLocalDeps Error.Module [Error.Module]
2040+ | ReplBadLocalDeps FilePath Error.Module [Error.Module]
18592041 | ReplProjectProblem BuildProjectProblem
18602042 | ReplBadGenerate Generate
18612043 | ReplBadCache
@@ -1869,10 +2051,10 @@ replToReport problem =
18692051 toDetailsReport details
18702052
18712053 ReplBadInput source err ->
1872− Help.compilerReport (Error.Module N.replModule "REPL" File.zeroTime source err) []
2054+ Help.compilerReport "/" (Error.Module N.replModule "REPL" File.zeroTime source err) []
18732055
1874− ReplBadLocalDeps e es ->
1875− Help.compilerReport e es
2056+ ReplBadLocalDeps root e es ->
2057+ Help.compilerReport root e es
18762058
18772059 ReplProjectProblem projectProblem ->
18782060 toProjectProblemReport projectProblem
builder/src/Reporting/Exit/Help.hs+5−5
@@ -29,7 +29,7 @@ import qualified Reporting.Error as Error
2929
3030
3131data Report
32− = CompilerReport Error.Module [Error.Module]
32+ = CompilerReport FilePath Error.Module [Error.Module]
3333 | Report
3434 { _title :: String
3535 , _path :: Maybe FilePath
@@ -52,7 +52,7 @@ jsonReport =
5252 Report
5353
5454
55−compilerReport :: Error.Module -> [Error.Module] -> Report
55+compilerReport :: FilePath -> Error.Module -> [Error.Module] -> Report
5656compilerReport =
5757 CompilerReport
5858
@@ -64,8 +64,8 @@ compilerReport =
6464reportToDoc :: Report -> D.Doc
6565reportToDoc report_ =
6666 case report_ of
67− CompilerReport e es ->
68− Error.toDoc e es
67+ CompilerReport root e es ->
68+ Error.toDoc root e es
6969
7070 Report title maybePath message ->
7171 let
@@ -94,7 +94,7 @@ reportToDoc report_ =
9494reportToJson :: Report -> E.Value
9595reportToJson report_ =
9696 case report_ of
97− CompilerReport e es ->
97+ CompilerReport _ e es ->
9898 E.object
9999 [ "type" ==> E.chars "compile-errors"
100100 , "errors" ==> E.list Error.toJson (e:es)
builder/src/Stuff.hs+8−9
@@ -8,8 +8,8 @@ module Stuff
88 , elmo
99 , temp
1010 , findRoot
11− , withProjectLock
12− , withCacheLock
11+ , withRootLock
12+ , withRegistryLock
1313 , PackageCache
1414 , getPackageCache
1515 , registry
@@ -120,17 +120,16 @@ findRootHelp dirs =
120120-- LOCKS
121121
122122
123−withProjectLock :: FilePath -> IO a -> IO a
124−withProjectLock root work =
123+withRootLock :: FilePath -> IO a -> IO a
124+withRootLock root work =
125125 do let dir = stuff root
126126 Dir.createDirectoryIfMissing True dir
127− Lock.withFileLock (dir </> "project.lock") Lock.Exclusive (\_ -> work)
127+ Lock.withFileLock (dir </> "lock") Lock.Exclusive (\_ -> work)
128128
129129
130−withCacheLock :: PackageCache -> IO a -> IO a
131−withCacheLock (PackageCache dir) work =
132− Lock.withFileLock (dir </> "cache.lock") Lock.Exclusive (\_ -> work)
133−
130+withRegistryLock :: PackageCache -> IO a -> IO a
131+withRegistryLock (PackageCache dir) work =
132+ Lock.withFileLock (dir </> "lock") Lock.Exclusive (\_ -> work)
134133
135134
136135
cabal.confignew file+2
@@ -0,0 +1,2 @@
1+profiling: False
2+library-profiling: True
compiler/src/AST/Canonical.hs+2−2
@@ -342,7 +342,7 @@ instance Binary CtorOpts where
342342 0 -> return Normal
343343 1 -> return Enum
344344 2 -> return Unbox
345− _ -> error "binary encoding of CtorOpts was corrupted"
345+ _ -> fail "binary encoding of CtorOpts was corrupted"
346346
347347
348348instance Binary Annotation where
@@ -393,7 +393,7 @@ instance Binary AliasType where
393393 case n of
394394 0 -> liftM Holey get
395395 1 -> liftM Filled get
396− _ -> error "binary encoding of AliasType was corrupted"
396+ _ -> fail "binary encoding of AliasType was corrupted"
397397
398398
399399instance Binary FieldType where
compiler/src/AST/Optimized.hs+9−9
@@ -135,7 +135,7 @@ data GlobalGraph =
135135data LocalGraph =
136136 LocalGraph
137137 { _l_main :: Maybe Main
138− , _l_nodes :: Map.Map Global Node -- TODO profile switching Global to Name
138+ , _l_nodes :: Map.Map Global Node -- PERF profile switching Global to Name
139139 , _l_fields :: Map.Map Name Int
140140 }
141141
@@ -308,7 +308,7 @@ instance Binary Expr where
308308 24 -> pure Unit
309309 25 -> liftM3 Tuple get get get
310310 26 -> liftM3 Shader get get get
311− _ -> error "problem getting Opt.Expr binary"
311+ _ -> fail "problem getting Opt.Expr binary"
312312
313313
314314instance Binary Def where
@@ -322,7 +322,7 @@ instance Binary Def where
322322 case word of
323323 0 -> liftM2 Def get get
324324 1 -> liftM3 TailDef get get get
325− _ -> error "problem getting Opt.Def binary"
325+ _ -> fail "problem getting Opt.Def binary"
326326
327327
328328instance Binary Destructor where
@@ -345,7 +345,7 @@ instance Binary Path where
345345 1 -> liftM2 Field get get
346346 2 -> liftM Unbox get
347347 3 -> liftM Root get
348− _ -> error "problem getting Opt.Path binary"
348+ _ -> fail "problem getting Opt.Path binary"
349349
350350
351351instance (Binary a) => Binary (Decider a) where
@@ -361,7 +361,7 @@ instance (Binary a) => Binary (Decider a) where
361361 0 -> liftM Leaf get
362362 1 -> liftM3 Chain get get get
363363 2 -> liftM3 FanOut get get get
364− _ -> error "problem getting Opt.Decider binary"
364+ _ -> fail "problem getting Opt.Decider binary"
365365
366366
367367instance Binary Choice where
@@ -375,7 +375,7 @@ instance Binary Choice where
375375 case word of
376376 0 -> liftM Inline get
377377 1 -> liftM Jump get
378− _ -> error "problem getting Opt.Choice binary"
378+ _ -> fail "problem getting Opt.Choice binary"
379379
380380
381381
@@ -400,7 +400,7 @@ instance Binary Main where
400400 case word of
401401 0 -> return Static
402402 1 -> liftM2 Dynamic get get
403− _ -> error "problem getting Opt.Main binary"
403+ _ -> fail "problem getting Opt.Main binary"
404404
405405
406406instance Binary Node where
@@ -432,7 +432,7 @@ instance Binary Node where
432432 8 -> liftM2 Kernel get get
433433 9 -> liftM2 PortIncoming get get
434434 10 -> liftM2 PortOutgoing get get
435− _ -> error "problem getting Opt.Node binary"
435+ _ -> fail "problem getting Opt.Node binary"
436436
437437
438438instance Binary EffectsType where
@@ -448,4 +448,4 @@ instance Binary EffectsType where
448448 0 -> return Cmd
449449 1 -> return Sub
450450 2 -> return Fx
451− _ -> error "problem getting Opt.EffectsType binary"
451+ _ -> fail "problem getting Opt.EffectsType binary"
compiler/src/AST/Source.hs+5−5
@@ -195,15 +195,15 @@ newtype Comment =
195195
196196data Exposing
197197 = Open
198− | Explicit [A.Located Exposed]
198+ | Explicit [Exposed]
199199
200200
201201data Exposed
202− = Lower Name
203− | Upper Name Privacy
204− | Operator Name
202+ = Lower (A.Located Name)
203+ | Upper (A.Located Name) Privacy
204+ | Operator A.Region Name
205205
206206
207207data Privacy
208− = Public
208+ = Public A.Region
209209 | Private
compiler/src/AST/Utils/Binop.hs+5−6
@@ -41,12 +41,11 @@ instance Binary Precedence where
4141instance Binary Associativity where
4242 get =
4343 do n <- getWord8
44− return $
45− case n of
46− 0 -> Left
47− 1 -> Non
48− 2 -> Right
49− _ -> error "Error reading valid associativity from serialized string"
44+ case n of
45+ 0 -> return Left
46+ 1 -> return Non
47+ 2 -> return Right
48+ _ -> fail "Error reading valid associativity from serialized string"
5049
5150 put assoc =
5251 putWord8 $
compiler/src/AST/Utils/Shader.hs+2
@@ -74,9 +74,11 @@ escape chars =
7474 []
7575
7676 c:cs
77+ | c == '\r' -> escape cs
7778 | c == '\n' -> '\\' : 'n' : escape cs
7879 | c == '\"' -> '\\' : '"' : escape cs
7980 | c == '\'' -> '\\' : '\'' : escape cs
81+ | c == '\\' -> '\\' : '\\' : escape cs
8082 | otherwise -> c : escape cs
8183
8284
compiler/src/AST/Utils/Type.hs−1
@@ -1,5 +1,4 @@
11{-# OPTIONS_GHC -Wall #-}
2−{-# LANGUAGE OverloadedStrings #-}
32module AST.Utils.Type
43 ( delambda
54 , dealias
compiler/src/Canonicalize/Environment.hs+50−20
@@ -4,6 +4,8 @@ module Canonicalize.Environment
44 ( Env(..)
55 , Exposed
66 , Qualified
7+ , Info(..)
8+ , mergeInfo
79 , Var(..)
810 , Type(..)
911 , Ctor(..)
@@ -20,8 +22,8 @@ module Canonicalize.Environment
2022
2123import qualified Data.Map.Merge.Strict as Map
2224import qualified Data.Map.Strict as Map
23−import qualified Data.Map.Strict.Internal as I
2425import qualified Data.Name as Name
26+import qualified Data.OneOrMore as OneOrMore
2527
2628import qualified AST.Utils.Binop as Binop
2729import qualified AST.Canonical as Can
@@ -58,11 +60,34 @@ data Env =
5860
5961
6062type Exposed a =
61− Map.Map Name.Name (Map.Map ModuleName.Canonical a)
63+ Map.Map Name.Name (Info a)
6264
6365
6466type Qualified a =
65− Map.Map Name.Name (Map.Map Name.Name (Map.Map ModuleName.Canonical a))
67+ Map.Map Name.Name (Map.Map Name.Name (Info a))
68+
69+
70+
71+-- INFO
72+
73+
74+data Info a
75+ = Specific ModuleName.Canonical a
76+ | Ambiguous ModuleName.Canonical (OneOrMore.OneOrMore ModuleName.Canonical)
77+
78+
79+mergeInfo :: Info a -> Info a -> Info a
80+mergeInfo info1 info2 =
81+ case info1 of
82+ Specific h1 _ ->
83+ case info2 of
84+ Specific h2 _ -> if h1 == h2 then info1 else Ambiguous h1 (OneOrMore.one h2)
85+ Ambiguous h2 hs2 -> Ambiguous h1 (OneOrMore.more (OneOrMore.one h2) hs2)
86+
87+ Ambiguous h1 hs1 ->
88+ case info2 of
89+ Specific h2 _ -> Ambiguous h1 (OneOrMore.more hs1 (OneOrMore.one h2))
90+ Ambiguous h2 hs2 -> Ambiguous h1 (OneOrMore.more hs1 (OneOrMore.more (OneOrMore.one h2) hs2))
6691
6792
6893
@@ -72,7 +97,8 @@ type Qualified a =
7297data Var
7398 = Local A.Region
7499 | TopLevel A.Region
75− | Foreign (Map.Map ModuleName.Canonical Can.Annotation)
100+ | Foreign ModuleName.Canonical Can.Annotation
101+ | Foreigns ModuleName.Canonical (OneOrMore.OneOrMore ModuleName.Canonical)
76102
77103
78104
@@ -139,7 +165,10 @@ addLocalLeft _ region =
139165addLocalBoth :: Name.Name -> A.Region -> Var -> Result i w Var
140166addLocalBoth name region var =
141167 case var of
142− Foreign _ ->
168+ Foreign _ _ ->
169+ Result.ok (Local region)
170+
171+ Foreigns _ _ ->
143172 Result.ok (Local region)
144173
145174 Local parentRegion ->
@@ -150,17 +179,18 @@ addLocalBoth name region var =
150179
151180
152181
182+
153183-- FIND TYPE
154184
155185
156186findType :: A.Region -> Env -> Name.Name -> Result i w Type
157187findType region (Env _ _ ts _ _ _ qts _) name =
158188 case Map.lookup name ts of
159− Just (I.Bin 1 _ tipe _ _) ->
189+ Just (Specific _ tipe) ->
160190 Result.ok tipe
161191
162− Just homes ->
163− Result.throw (Error.AmbiguousType region Nothing name (Map.keys homes))
192+ Just (Ambiguous h hs) ->
193+ Result.throw (Error.AmbiguousType region Nothing name h hs)
164194
165195 Nothing ->
166196 Result.throw (Error.NotFoundType region Nothing name (toPossibleNames ts qts))
@@ -171,11 +201,11 @@ findTypeQual region (Env _ _ ts _ _ _ qts _) prefix name =
171201 case Map.lookup prefix qts of
172202 Just qualified ->
173203 case Map.lookup name qualified of
174− Just (I.Bin 1 _ tipe _ _) ->
204+ Just (Specific _ tipe) ->
175205 Result.ok tipe
176206
177− Just homes ->
178− Result.throw (Error.AmbiguousType region (Just prefix) name (Map.keys homes))
207+ Just (Ambiguous h hs) ->
208+ Result.throw (Error.AmbiguousType region (Just prefix) name h hs)
179209
180210 Nothing ->
181211 Result.throw (Error.NotFoundType region (Just prefix) name (toPossibleNames ts qts))
@@ -191,11 +221,11 @@ findTypeQual region (Env _ _ ts _ _ _ qts _) prefix name =
191221findCtor :: A.Region -> Env -> Name.Name -> Result i w Ctor
192222findCtor region (Env _ _ _ cs _ _ _ qcs) name =
193223 case Map.lookup name cs of
194− Just (I.Bin 1 _ ctor _ _) ->
224+ Just (Specific _ ctor) ->
195225 Result.ok ctor
196226
197− Just homes ->
198− Result.throw (Error.AmbiguousVariant region Nothing name (Map.keys homes))
227+ Just (Ambiguous h hs) ->
228+ Result.throw (Error.AmbiguousVariant region Nothing name h hs)
199229
200230 Nothing ->
201231 Result.throw (Error.NotFoundVariant region Nothing name (toPossibleNames cs qcs))
@@ -206,11 +236,11 @@ findCtorQual region (Env _ _ _ cs _ _ _ qcs) prefix name =
206236 case Map.lookup prefix qcs of
207237 Just qualified ->
208238 case Map.lookup name qualified of
209− Just (I.Bin 1 _ pattern _ _) ->
239+ Just (Specific _ pattern) ->
210240 Result.ok pattern
211241
212− Just homes ->
213− Result.throw (Error.AmbiguousVariant region (Just prefix) name (Map.keys homes))
242+ Just (Ambiguous h hs) ->
243+ Result.throw (Error.AmbiguousVariant region (Just prefix) name h hs)
214244
215245 Nothing ->
216246 Result.throw (Error.NotFoundVariant region (Just prefix) name (toPossibleNames cs qcs))
@@ -226,11 +256,11 @@ findCtorQual region (Env _ _ _ cs _ _ _ qcs) prefix name =
226256findBinop :: A.Region -> Env -> Name.Name -> Result i w Binop
227257findBinop region (Env _ _ _ _ binops _ _ _) name =
228258 case Map.lookup name binops of
229− Just (I.Bin 1 _ binop _ _) ->
259+ Just (Specific _ binop) ->
230260 Result.ok binop
231261
232− Just homes ->
233− Result.throw (Error.AmbiguousBinop region name (Map.keys homes))
262+ Just (Ambiguous h hs) ->
263+ Result.throw (Error.AmbiguousBinop region name h hs)
234264
235265 Nothing ->
236266 Result.throw (Error.NotFoundBinop region name (Map.keysSet binops))
compiler/src/Canonicalize/Environment/Dups.hs+1−1
@@ -105,7 +105,7 @@ one name region value =
105105
106106insert :: Name.Name -> A.Region -> a -> Dict a -> Dict a
107107insert name region value dict =
108− Map.insertWith OneOrMore.more name (OneOrMore.one (Info region value)) dict
108+ Map.insertWith (\new old -> OneOrMore.more old new) name (OneOrMore.one (Info region value)) dict
109109
110110
111111union :: Dict a -> Dict a -> Dict a
compiler/src/Canonicalize/Environment/Foreign.hs+49−37
@@ -35,7 +35,14 @@ type Result i w a =
3535createInitialEnv :: ModuleName.Canonical -> Map.Map ModuleName.Raw I.Interface -> [Src.Import] -> Result i w Env.Env
3636createInitialEnv home ifaces imports =
3737 do (State vs ts cs bs qvs qts qcs) <- foldM (addImport ifaces) emptyState (toSafeImports home imports)
38− Result.ok (Env.Env home (Map.map Env.Foreign vs) ts cs bs qvs qts qcs)
38+ Result.ok (Env.Env home (Map.map infoToVar vs) ts cs bs qvs qts qcs)
39+
40+
41+infoToVar :: Env.Info Can.Annotation -> Env.Var
42+infoToVar info =
43+ case info of
44+ Env.Specific home tipe -> Env.Foreign home tipe
45+ Env.Ambiguous h hs -> Env.Foreigns h hs
3946
4047
4148
@@ -61,7 +68,7 @@ emptyState =
6168
6269emptyTypes :: Env.Exposed Env.Type
6370emptyTypes =
64− Map.singleton "List" (Map.singleton ModuleName.list (Env.Union 1 ModuleName.list))
71+ Map.singleton "List" (Env.Specific ModuleName.list (Env.Union 1 ModuleName.list))
6572
6673
6774
@@ -102,8 +109,8 @@ addImport ifaces (State vs ts cs bs qvs qts qcs) (Src.Import (A.At _ name) maybe
102109 (Map.mapMaybeWithKey (unionToType home) unions)
103110 (Map.mapMaybeWithKey (aliasToType home) aliases)
104111
105− !vars = Map.map (Map.singleton home) defs
106− !types = Map.map (Map.singleton home . fst) rawTypeInfo
112+ !vars = Map.map (Env.Specific home) defs
113+ !types = Map.map (Env.Specific home . fst) rawTypeInfo
107114 !ctors = Map.foldr (addExposed . snd) Map.empty rawTypeInfo
108115
109116 !qvs2 = addQualified prefix vars qvs
@@ -129,7 +136,7 @@ addImport ifaces (State vs ts cs bs qvs qts qcs) (Src.Import (A.At _ name) maybe
129136
130137addExposed :: Env.Exposed a -> Env.Exposed a -> Env.Exposed a
131138addExposed =
132− Map.unionWith Map.union
139+ Map.unionWith Env.mergeInfo
133140
134141
135142addQualified :: Name.Name -> Env.Exposed a -> Env.Qualified a -> Env.Qualified a
@@ -150,7 +157,7 @@ unionToTypeHelp :: ModuleName.Canonical -> Name.Name -> Can.Union -> (Env.Type,
150157unionToTypeHelp home name union@(Can.Union vars ctors _ _) =
151158 let
152159 addCtor dict (Can.Ctor ctor index _ args) =
153− Map.insert ctor (Map.singleton home (Env.Ctor home name union index args)) dict
160+ Map.insert ctor (Env.Specific home (Env.Ctor home name union index args)) dict
154161 in
155162 ( Env.Union (length vars) home
156163 , List.foldl' addCtor Map.empty ctors
@@ -181,7 +188,7 @@ aliasToTypeHelp home name (Can.Alias vars tipe) =
181188 (Can.TAlias home name avars (Can.Filled tipe))
182189 (Can.fieldsToList fields)
183190 in
184− Map.singleton name (Map.singleton home (Env.RecordCtor home vars alias))
191+ Map.singleton name (Env.Specific home (Env.RecordCtor home vars alias))
185192
186193 _ ->
187194 Map.empty
@@ -192,9 +199,9 @@ aliasToTypeHelp home name (Can.Alias vars tipe) =
192199-- BINOP
193200
194201
195−binopToBinop :: ModuleName.Canonical -> Name.Name -> I.Binop -> Map.Map ModuleName.Canonical Env.Binop
202+binopToBinop :: ModuleName.Canonical -> Name.Name -> I.Binop -> Env.Info Env.Binop
196203binopToBinop home op (I.Binop name annotation associativity precedence) =
197− Map.singleton home (Env.Binop op home name annotation associativity precedence)
204+ Env.Specific home (Env.Binop op home name annotation associativity precedence)
198205
199206
200207
@@ -207,19 +214,19 @@ addExposedValue
207214 -> Map.Map Name.Name (Env.Type, Env.Exposed Env.Ctor)
208215 -> Map.Map Name.Name I.Binop
209216 -> State
210− -> A.Located Src.Exposed
217+ -> Src.Exposed
211218 -> Result i w State
212−addExposedValue home vars types binops (State vs ts cs bs qvs qts qcs) (A.At region exposed) =
219+addExposedValue home vars types binops (State vs ts cs bs qvs qts qcs) exposed =
213220 case exposed of
214− Src.Lower name ->
221+ Src.Lower (A.At region name) ->
215222 case Map.lookup name vars of
216223 Just info ->
217− Result.ok (State (Map.insert name info vs) ts cs bs qvs qts qcs)
224+ Result.ok (State (Map.insertWith Env.mergeInfo name info vs) ts cs bs qvs qts qcs)
218225
219226 Nothing ->
220227 Result.throw (Error.ImportExposingNotFound region home name (Map.keys vars))
221228
222− Src.Upper name privacy ->
229+ Src.Upper (A.At region name) privacy ->
223230 case privacy of
224231 Src.Private ->
225232 case Map.lookup name types of
@@ -227,43 +234,43 @@ addExposedValue home vars types binops (State vs ts cs bs qvs qts qcs) (A.At reg
227234 case tipe of
228235 Env.Union _ _ ->
229236 let
230− !ts2 = Map.insert name (Map.singleton home tipe) ts
237+ !ts2 = Map.insert name (Env.Specific home tipe) ts
231238 in
232239 Result.ok (State vs ts2 cs bs qvs qts qcs)
233240
234241 Env.Alias _ _ _ _ ->
235242 let
236− !ts2 = Map.insert name (Map.singleton home tipe) ts
243+ !ts2 = Map.insert name (Env.Specific home tipe) ts
237244 !cs2 = addExposed cs ctors
238245 in
239246 Result.ok (State vs ts2 cs2 bs qvs qts qcs)
240247
241248 Nothing ->
242− case Map.lookup name (toCtors types) of
243− Just tipe ->
249+ case checkForCtorMistake name types of
250+ tipe:_ ->
244251 Result.throw $ Error.ImportCtorByName region name tipe
245252
246− Nothing ->
253+ [] ->
247254 Result.throw $ Error.ImportExposingNotFound region home name (Map.keys types)
248255
249− Src.Public ->
256+ Src.Public dotDotRegion ->
250257 case Map.lookup name types of
251258 Just (tipe, ctors) ->
252259 case tipe of
253260 Env.Union _ _ ->
254261 let
255− !ts2 = Map.insert name (Map.singleton home tipe) ts
262+ !ts2 = Map.insert name (Env.Specific home tipe) ts
256263 !cs2 = addExposed cs ctors
257264 in
258265 Result.ok (State vs ts2 cs2 bs qvs qts qcs)
259266
260267 Env.Alias _ _ _ _ ->
261− Result.throw (Error.ImportOpenAlias region name)
268+ Result.throw (Error.ImportOpenAlias dotDotRegion name)
262269
263270 Nothing ->
264271 Result.throw (Error.ImportExposingNotFound region home name (Map.keys types))
265272
266− Src.Operator op ->
273+ Src.Operator region op ->
267274 case Map.lookup op binops of
268275 Just binop ->
269276 let
@@ -275,18 +282,23 @@ addExposedValue home vars types binops (State vs ts cs bs qvs qts qcs) (A.At reg
275282 Result.throw (Error.ImportExposingNotFound region home op (Map.keys binops))
276283
277284
278−
279−toCtors :: Map.Map Name.Name (Env.Type, Env.Exposed Env.Ctor) -> Map.Map Name.Name Name.Name
280−toCtors types =
281− Map.foldr addCtors Map.empty types
285+checkForCtorMistake :: Name.Name -> Map.Map Name.Name (Env.Type, Env.Exposed Env.Ctor) -> [Name.Name]
286+checkForCtorMistake givenName types =
287+ Map.foldr addMatches [] types
282288 where
283− addCtors (_, exposedCtors) dict =
284− Map.foldrWithKey addCtor dict exposedCtors
285−
286− addCtor ctorName homes dict =
287− case Map.elems homes of
288− [Env.Ctor _ tipeName _ _ _] ->
289− Map.insert ctorName tipeName dict
290−
291− _ ->
292− dict
289+ addMatches (_, exposedCtors) matches =
290+ Map.foldrWithKey addMatch matches exposedCtors
291+
292+ addMatch ctorName info matches =
293+ if ctorName /= givenName
294+ then matches
295+ else
296+ case info of
297+ Env.Specific _ (Env.Ctor _ tipeName _ _ _) ->
298+ tipeName : matches
299+
300+ Env.Specific _ (Env.RecordCtor _ _ _) ->
301+ matches
302+
303+ Env.Ambiguous _ _ ->
304+ matches
compiler/src/Canonicalize/Environment/Local.hs+5−5
@@ -110,7 +110,7 @@ addTypes (Src.Module _ _ _ _ _ unions aliases _ _) (Env.Env home vs ts cs bs qvs
110110addUnion :: ModuleName.Canonical -> Env.Exposed Env.Type -> A.Located Src.Union -> Result i w (Env.Exposed Env.Type)
111111addUnion home types union@(A.At _ (Src.Union (A.At _ name) _ _)) =
112112 do arity <- checkUnionFreeVars union
113− let one = Map.singleton home (Env.Union arity home)
113+ let one = Env.Specific home (Env.Union arity home)
114114 Result.ok $ Map.insert name one types
115115
116116
@@ -133,7 +133,7 @@ addAlias env@(Env.Env home vs ts cs bs qvs qts qcs) scc =
133133 Graph.AcyclicSCC alias@(A.At _ (Src.Alias (A.At _ name) _ tipe)) ->
134134 do args <- checkAliasFreeVars alias
135135 ctype <- Type.canonicalize env tipe
136− let one = Map.singleton home (Env.Alias (length args) home args ctype)
136+ let one = Env.Specific home (Env.Alias (length args) home args ctype)
137137 let ts1 = Map.insert name one ts
138138 Result.ok $ Env.Env home vs ts1 cs bs qvs qts qcs
139139
@@ -281,7 +281,7 @@ addCtors (Src.Module _ _ _ _ _ unions aliases _ _) env@(Env.Env home vs ts cs bs
281281 )
282282
283283
284−type CtorDups = Dups.Dict (Map.Map ModuleName.Canonical Env.Ctor)
284+type CtorDups = Dups.Dict (Env.Info Env.Ctor)
285285
286286
287287
@@ -297,7 +297,7 @@ canonicalizeAlias env@(Env.Env home _ _ _ _ _ _ _) (A.At _ (Src.Alias (A.At regi
297297 ,
298298 case ctipe of
299299 Can.TRecord fields Nothing ->
300− Dups.one name region (Map.singleton home (toRecordCtor home name vars fields))
300+ Dups.one name region (Env.Specific home (toRecordCtor home name vars fields))
301301
302302 _ ->
303303 Dups.none
@@ -351,5 +351,5 @@ toOpts ctors =
351351
352352toCtor :: ModuleName.Canonical -> Name.Name -> Can.Union -> A.Located Can.Ctor -> CtorDups
353353toCtor home typeName union (A.At region (Can.Ctor name index _ args)) =
354− Dups.one name region $ Map.singleton home $
354+ Dups.one name region $ Env.Specific home $
355355 Env.Ctor home typeName union index args
compiler/src/Canonicalize/Expression.hs+6−7
@@ -14,7 +14,6 @@ import Control.Monad (foldM)
1414import qualified Data.Graph as Graph
1515import qualified Data.List as List
1616import qualified Data.Map.Strict as Map
17−import qualified Data.Map.Strict.Internal as I
1817import qualified Data.Name as Name
1918
2019import qualified AST.Canonical as Can
@@ -696,15 +695,15 @@ findVar region (Env.Env localHome vs _ _ _ qvs _ _) name =
696695 Env.TopLevel _ ->
697696 logVar name (Can.VarTopLevel localHome name)
698697
699− Env.Foreign (I.Bin 1 home annotation _ _) ->
698+ Env.Foreign home annotation ->
700699 Result.ok $
701700 if home == ModuleName.debug then
702701 Can.VarDebug localHome name annotation
703702 else
704703 Can.VarForeign home name annotation
705704
706− Env.Foreign homes ->
707− Result.throw (Error.AmbiguousVar region Nothing name (Map.keys homes))
705+ Env.Foreigns h hs ->
706+ Result.throw (Error.AmbiguousVar region Nothing name h hs)
708707
709708 Nothing ->
710709 Result.throw (Error.NotFoundVar region Nothing name (toPossibleNames vs qvs))
@@ -715,15 +714,15 @@ findVarQual region (Env.Env localHome vs _ _ _ qvs _ _) prefix name =
715714 case Map.lookup prefix qvs of
716715 Just qualified ->
717716 case Map.lookup name qualified of
718− Just (I.Bin 1 home annotation _ _) ->
717+ Just (Env.Specific home annotation) ->
719718 Result.ok $
720719 if home == ModuleName.debug then
721720 Can.VarDebug localHome name annotation
722721 else
723722 Can.VarForeign home name annotation
724723
725− Just homes ->
726− Result.throw (Error.AmbiguousVar region (Just prefix) name (Map.keys homes))
724+ Just (Env.Ambiguous h hs) ->
725+ Result.throw (Error.AmbiguousVar region (Just prefix) name h hs)
727726
728727 Nothing ->
729728 Result.throw (Error.NotFoundVar region (Just prefix) name (toPossibleNames vs qvs))
compiler/src/Canonicalize/Module.hs+7−7
@@ -236,11 +236,11 @@ checkExposed
236236 -> Map.Map Name.Name alias
237237 -> Map.Map Name.Name binop
238238 -> Can.Effects
239− -> A.Located Src.Exposed
239+ -> Src.Exposed
240240 -> Result i w (Dups.Dict (A.Located Can.Export))
241−checkExposed values unions aliases binops effects (A.At region exposed) =
241+checkExposed values unions aliases binops effects exposed =
242242 case exposed of
243− Src.Lower name ->
243+ Src.Lower (A.At region name) ->
244244 if Map.member name values then
245245 ok name region Can.ExportValue
246246 else
@@ -252,23 +252,23 @@ checkExposed values unions aliases binops effects (A.At region exposed) =
252252 Result.throw $ Error.ExportNotFound region Error.BadVar name $
253253 ports ++ Map.keys values
254254
255− Src.Operator name ->
255+ Src.Operator region name ->
256256 if Map.member name binops then
257257 ok name region Can.ExportBinop
258258 else
259259 Result.throw $ Error.ExportNotFound region Error.BadOp name $
260260 Map.keys binops
261261
262− Src.Upper name Src.Public ->
262+ Src.Upper (A.At region name) (Src.Public dotDotRegion) ->
263263 if Map.member name unions then
264264 ok name region Can.ExportUnionOpen
265265 else if Map.member name aliases then
266− Result.throw $ Error.ExportOpenAlias region name
266+ Result.throw $ Error.ExportOpenAlias dotDotRegion name
267267 else
268268 Result.throw $ Error.ExportNotFound region Error.BadType name $
269269 Map.keys unions ++ Map.keys aliases
270270
271− Src.Upper name Src.Private ->
271+ Src.Upper (A.At region name) Src.Private ->
272272 if Map.member name unions then
273273 ok name region Can.ExportUnionClosed
274274 else if Map.member name aliases then
compiler/src/Canonicalize/Pattern.hs+3−2
@@ -8,6 +8,7 @@ module Canonicalize.Pattern
88 where
99
1010
11+import qualified Data.List as List
1112import qualified Data.Map.Strict as Map
1213import qualified Data.Name as Name
1314
@@ -173,8 +174,8 @@ logVar name region value =
173174logFields :: [A.Located Name.Name] -> a -> Result DupsDict w a
174175logFields fields value =
175176 let
176− addField (A.At region name) dict =
177+ addField dict (A.At region name) =
177178 Dups.insert name region region dict
178179 in
179180 Result.Result $ \bindings warnings _ ok ->
180− ok (foldr addField bindings fields) warnings value
181+ ok (List.foldl' addField bindings fields) warnings value
compiler/src/Data/Name.hs+53−43
@@ -202,11 +202,11 @@ fromVarIndex :: Int -> Name
202202fromVarIndex n =
203203 runST
204204 (
205− do let !size = getIndexSize n
205+ do let !size = 2 + getIndexSize n
206206 mba <- newByteArray size
207207 writeWord8 mba 0 0x5F {- _ -}
208208 writeWord8 mba 1 0x76 {- v -}
209− writeDigits mba (size - 1) n
209+ writeDigitsAtEnd mba size n
210210 freeze mba
211211 )
212212
@@ -214,19 +214,20 @@ fromVarIndex n =
214214{-# INLINE getIndexSize #-}
215215getIndexSize :: Int -> Int
216216getIndexSize n
217− | n < 10 = 3
218− | n < 100 = 4
219− | True = 2 + ceiling (logBase 10 (fromIntegral n + 1) :: Float)
217+ | n < 10 = 1
218+ | n < 100 = 2
219+ | True = ceiling (logBase 10 (fromIntegral n + 1) :: Float)
220220
221221
222222
223−writeDigits :: MBA s -> Int -> Int -> ST s ()
224−writeDigits !mba !offset !n =
223+writeDigitsAtEnd :: MBA s -> Int -> Int -> ST s ()
224+writeDigitsAtEnd !mba !oldOffset !n =
225225 do let (q,r) = quotRem n 10
226− writeWord8 mba offset (0x30 + fromIntegral r)
226+ let !newOffset = oldOffset - 1
227+ writeWord8 mba newOffset (0x30 + fromIntegral r)
227228 if q <= 0
228229 then return ()
229− else writeDigits mba (offset-1) q
230+ else writeDigitsAtEnd mba newOffset q
230231
231232
232233
@@ -249,7 +250,7 @@ fromTypeVariable name@(Utf8.Utf8 ba#) index =
249250 mba <- newByteArray size
250251 copyToMBA name mba
251252 writeWord8 mba (I# len#) 0x5F {- _ -}
252− writeDigits mba (size - 1) index
253+ writeDigitsAtEnd mba size index
253254 freeze mba
254255 )
255256 else
@@ -258,7 +259,7 @@ fromTypeVariable name@(Utf8.Utf8 ba#) index =
258259 do let !size = I# len# + getIndexSize index
259260 mba <- newByteArray size
260261 copyToMBA name mba
261− writeDigits mba (size - 1) index
262+ writeDigitsAtEnd mba size index
262263 freeze mba
263264 )
264265
@@ -277,52 +278,61 @@ fromTypeVariableScheme scheme =
277278 freeze mba
278279 else
279280 do let (extra, letter) = quotRem scheme 26
280− let !size = getIndexSize extra
281+ let !size = 1 + getIndexSize extra
281282 mba <- newByteArray size
282283 writeWord8 mba 0 (0x61 + fromIntegral letter)
283− writeDigits mba (size - 1) extra
284+ writeDigitsAtEnd mba size extra
284285 freeze mba
285286 )
286287
287288
288289
289290-- FROM MANY NAMES
291+--
292+-- Creating a unique name by combining all the subnames can create names
293+-- longer than 256 bytes relatively easily. So instead, the first given name
294+-- (e.g. foo) is prefixed chars that are valid in JS but not Elm (e.g. _M$foo)
295+--
296+-- This should be a unique name since 0.19 disallows shadowing. It would not
297+-- be possible for multiple top-level cycles to include values with the same
298+-- name, so the important thing is to make the cycle name distinct from the
299+-- normal name. Same logic for destructuring patterns like (x,y)
290300
291301
292302fromManyNames :: [Name] -> Name
293303fromManyNames names =
294− let
295− !(I# size#) = sum (map (\(Utf8.Utf8 ba#) -> I# (sizeofByteArray# ba# +# 1#)) names)
296− in
297− runST
298− (
299− ST $ \s ->
300− case newByteArray# size# s of
301− (# s, mba# #) ->
302− case writeNames mba# 0# names s of
303− s ->
304− case unsafeFreezeByteArray# mba# s of
305− (# s, ba# #) -> (# s, Utf8.Utf8 ba# #)
306− )
307−
308−
309−writeNames :: MutableByteArray# s -> Int# -> [Name] -> State# s -> State# s
310−writeNames mba# !offset# names s =
311304 case names of
312305 [] ->
313− s
314−
315− (Utf8.Utf8 ba#) : names ->
316− case writeWord8Array# mba# offset# 0x24## {- $ -} s of
317− s ->
318− let
319− !offset1# = offset# +# 1#
320− !len# = sizeofByteArray# ba#
321− !newOffset# = offset1# +# len#
322− in
323− case copyByteArray# ba# 0# mba# offset1# len# s of
324− s ->
325− writeNames mba# newOffset# names s
306+ blank
307+ -- NOTE: this case is needed for (let _ = Debug.log "x" x in ...)
308+ -- but maybe unused patterns should be stripped out instead
309+
310+ Utf8.Utf8 ba# : _ ->
311+ let
312+ len# = sizeofByteArray# ba#
313+ in
314+ runST
315+ (
316+ ST $ \s ->
317+ case newByteArray# (len# +# 3#) s of
318+ (# s, mba# #) ->
319+ case writeWord8Array# mba# 0# 0x5F## {-_-} s of
320+ s ->
321+ case writeWord8Array# mba# 1# 0x4D## {-M-} s of
322+ s ->
323+ case writeWord8Array# mba# 2# 0x24## {-$-} s of
324+ s ->
325+ case copyByteArray# ba# 0# mba# 3# len# s of
326+ s ->
327+ case unsafeFreezeByteArray# mba# s of
328+ (# s, ba# #) -> (# s, Utf8.Utf8 ba# #)
329+ )
330+
331+
332+{-# NOINLINE blank #-}
333+blank :: Name
334+blank =
335+ fromWords [0x5F,0x4D,0x24] {-_M$-}
326336
327337
328338
compiler/src/Data/Utf8.hs+5−3
@@ -261,7 +261,9 @@ instance Eq (Utf8 t) where
261261
262262
263263-- COMPARE
264−
264+--
265+-- TODO: is it fine to sort by length and only compare bytes on length ties?
266+--
265267
266268instance Ord (Utf8 t) where
267269 compare (Utf8 ba1#) (Utf8 ba2#) =
@@ -455,7 +457,7 @@ toEscapedBuilderHelp before after !name@(Utf8 ba#) k =
455457 !bLen = minusPtr bEnd bOffset
456458 in
457459 if len <= bLen then
458− do -- TODO test if writing word-by-word is faster
460+ do -- PERF test if writing word-by-word is faster
459461 copyToPtr name offset bOffset len
460462 escape before after bOffset name offset len 0
461463 let !newBufferRange = B.BufferRange (plusPtr bOffset len) bEnd
@@ -565,7 +567,7 @@ data MBA s =
565567 MBA# (MutableByteArray# s)
566568
567569
568−newByteArray :: Int -> ST s (MBA s) -- TODO see if newPinnedByteArray for len > 256 is positive
570+newByteArray :: Int -> ST s (MBA s) -- PERF see if newPinnedByteArray for len > 256 is positive
569571newByteArray (I# len#) =
570572 ST $ \s ->
571573 case newByteArray# len# s of
compiler/src/Elm/Compiler/Imports.hs+3−3
@@ -49,14 +49,14 @@ closed =
4949
5050typeOpen :: Name.Name -> Src.Exposing
5151typeOpen name =
52− Src.Explicit [ A.At A.zero (Src.Upper name Src.Public) ]
52+ Src.Explicit [ Src.Upper (A.At A.zero name) (Src.Public A.zero) ]
5353
5454
5555typeClosed :: Name.Name -> Src.Exposing
5656typeClosed name =
57− Src.Explicit [ A.At A.zero (Src.Upper name Src.Private) ]
57+ Src.Explicit [ Src.Upper (A.At A.zero name) Src.Private ]
5858
5959
6060operator :: Name.Name -> Src.Exposing
6161operator op =
62− Src.Explicit [ A.At A.zero (Src.Operator op) ]
62+ Src.Explicit [ Src.Operator A.zero op ]
compiler/src/Elm/Compiler/Type/Extract.hs+1−1
@@ -87,7 +87,7 @@ toPublicName (ModuleName.Canonical _ home) name =
8787
8888newtype Types =
8989 Types (Map.Map ModuleName.Canonical Types_)
90− -- TODO profile Opt.Global representation
90+ -- PERF profile Opt.Global representation
9191 -- current representation needs less allocation
9292 -- but maybe the lookup is much worse
9393
compiler/src/Elm/Constraint.hs+1−1
@@ -216,7 +216,7 @@ instance Binary Op where
216216 case n of
217217 0 -> return Less
218218 1 -> return LessOrEqual
219− _ -> error "binary encoding of Op was corrupted"
219+ _ -> fail "binary encoding of Op was corrupted"
220220
221221
222222
compiler/src/Elm/Interface.hs+3−3
@@ -215,7 +215,7 @@ instance Binary Union where
215215 0 -> liftM OpenUnion get
216216 1 -> liftM ClosedUnion get
217217 2 -> liftM PrivateUnion get
218− _ -> error "binary encoding of Union was corrupted"
218+ _ -> fail "binary encoding of Union was corrupted"
219219
220220
221221instance Binary Alias where
@@ -229,7 +229,7 @@ instance Binary Alias where
229229 case n of
230230 0 -> liftM PublicAlias get
231231 1 -> liftM PrivateAlias get
232− _ -> error "binary encoding of Alias was corrupted"
232+ _ -> fail "binary encoding of Alias was corrupted"
233233
234234
235235instance Binary Binop where
@@ -251,4 +251,4 @@ instance Binary DependencyInterface where
251251 case n of
252252 0 -> liftM Public get
253253 1 -> liftM3 Private get get get
254− _ -> error "binary encoding of DependencyInterface was corrupted"
254+ _ -> fail "binary encoding of DependencyInterface was corrupted"
compiler/src/Elm/Kernel.hs+9−9
@@ -15,7 +15,7 @@ import qualified Data.ByteString.Internal as B
1515import qualified Data.List as List
1616import qualified Data.Map as Map
1717import qualified Data.Name as Name
18−import Data.Word (Word8, Word16)
18+import Data.Word (Word8)
1919import Foreign.Ptr (Ptr, plusPtr, minusPtr)
2020import Foreign.ForeignPtr (ForeignPtr)
2121import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
@@ -128,7 +128,7 @@ parseChunks vtable enums fields =
128128 cerr row col toError
129129
130130
131−chompChunks :: VarTable -> Enums -> Fields -> ForeignPtr Word8 -> Ptr Word8 -> Ptr Word8 -> Word16 -> Word16 -> Ptr Word8 -> [Chunk] -> (# [Chunk], Ptr Word8, Word16, Word16 #)
131+chompChunks :: VarTable -> Enums -> Fields -> ForeignPtr Word8 -> Ptr Word8 -> Ptr Word8 -> Row -> Col -> Ptr Word8 -> [Chunk] -> (# [Chunk], Ptr Word8, Row, Col #)
132132chompChunks vs es fs src pos end row col lastPos revChunks =
133133 if pos >= end then
134134 let !js = toByteString src lastPos end in
@@ -168,7 +168,7 @@ toByteString src pos end =
168168
169169
170170-- relies on external checks in chompChunks
171−chompTag :: VarTable -> Enums -> Fields -> ForeignPtr Word8 -> Ptr Word8 -> Ptr Word8 -> Word16 -> Word16 -> [Chunk] -> (# [Chunk], Ptr Word8, Word16, Word16 #)
171+chompTag :: VarTable -> Enums -> Fields -> ForeignPtr Word8 -> Ptr Word8 -> Ptr Word8 -> Row -> Col -> [Chunk] -> (# [Chunk], Ptr Word8, Row, Col #)
172172chompTag vs es fs src pos end row col revChunks =
173173 let
174174 (# newPos, newCol #) = Var.chompInnerChars pos end col
@@ -319,19 +319,19 @@ toNames exposing =
319319 map toName exposedList
320320
321321
322−toName :: A.Located Src.Exposed -> Name.Name
323−toName (A.At _ exposed) =
322+toName :: Src.Exposed -> Name.Name
323+toName exposed =
324324 case exposed of
325− Src.Lower name ->
325+ Src.Lower (A.At _ name) ->
326326 name
327327
328− Src.Upper name Src.Private ->
328+ Src.Upper (A.At _ name) Src.Private ->
329329 name
330330
331− Src.Upper _ Src.Public ->
331+ Src.Upper _ (Src.Public _) ->
332332 error "cannot have Maybe(..) syntax in kernel code header"
333333
334− Src.Operator _ ->
334+ Src.Operator _ _ ->
335335 error "cannot use binops in kernel code"
336336
337337
compiler/src/Elm/Licenses.hs+25−25
@@ -83,63 +83,61 @@ check givenCode =
8383osiApprovedSpdxLicenses :: Map.Map Json.String [Char]
8484osiApprovedSpdxLicenses =
8585 Map.fromList
86− [ "AFL-1.1" ==> "Academic Free License v1.1"
86+ [ "0BSD" ==> "BSD Zero Clause License"
87+ , "AAL" ==> "Attribution Assurance License"
88+ , "AFL-1.1" ==> "Academic Free License v1.1"
8789 , "AFL-1.2" ==> "Academic Free License v1.2"
8890 , "AFL-2.0" ==> "Academic Free License v2.0"
8991 , "AFL-2.1" ==> "Academic Free License v2.1"
9092 , "AFL-3.0" ==> "Academic Free License v3.0"
91− , "APL-1.0" ==> "Adaptive Public License 1.0"
93+ , "AGPL-3.0" ==> "GNU Affero General Public License v3.0"
9294 , "Apache-1.1" ==> "Apache License 1.1"
9395 , "Apache-2.0" ==> "Apache License 2.0"
96+ , "APL-1.0" ==> "Adaptive Public License 1.0"
9497 , "APSL-1.0" ==> "Apple Public Source License 1.0"
9598 , "APSL-1.1" ==> "Apple Public Source License 1.1"
9699 , "APSL-1.2" ==> "Apple Public Source License 1.2"
97100 , "APSL-2.0" ==> "Apple Public Source License 2.0"
98101 , "Artistic-1.0" ==> "Artistic License 1.0"
99− , "Artistic-1.0-Perl" ==> "Artistic License 1.0 (Perl)"
100102 , "Artistic-1.0-cl8" ==> "Artistic License 1.0 w/clause 8"
103+ , "Artistic-1.0-Perl" ==> "Artistic License 1.0 (Perl)"
101104 , "Artistic-2.0" ==> "Artistic License 2.0"
102− , "AAL" ==> "Attribution Assurance License"
103− , "BSL-1.0" ==> "Boost Software License 1.0"
104105 , "BSD-2-Clause" ==> "BSD 2-clause \"Simplified\" License"
105106 , "BSD-3-Clause" ==> "BSD 3-clause \"New\" or \"Revised\" License"
106− , "0BSD" ==> "BSD Zero Clause License"
107+ , "BSL-1.0" ==> "Boost Software License 1.0"
108+ , "CATOSL-1.1" ==> "Computer Associates Trusted Open Source License 1.1"
109+ , "CDDL-1.0" ==> "Common Development and Distribution License 1.0"
107110 , "CECILL-2.1" ==> "CeCILL Free Software License Agreement v2.1"
108111 , "CNRI-Python" ==> "CNRI Python License"
109− , "CDDL-1.0" ==> "Common Development and Distribution License 1.0"
110112 , "CPAL-1.0" ==> "Common Public Attribution License 1.0"
111113 , "CPL-1.0" ==> "Common Public License 1.0"
112− , "CATOSL-1.1" ==> "Computer Associates Trusted Open Source License 1.1"
113114 , "CUA-OPL-1.0" ==> "CUA Office Public License v1.0"
114− , "EPL-1.0" ==> "Eclipse Public License 1.0"
115115 , "ECL-1.0" ==> "Educational Community License v1.0"
116116 , "ECL-2.0" ==> "Educational Community License v2.0"
117117 , "EFL-1.0" ==> "Eiffel Forum License v1.0"
118118 , "EFL-2.0" ==> "Eiffel Forum License v2.0"
119119 , "Entessa" ==> "Entessa Public License v1.0"
120+ , "EPL-1.0" ==> "Eclipse Public License 1.0"
120121 , "EUDatagrid" ==> "EU DataGrid Software License"
121122 , "EUPL-1.1" ==> "European Union Public License 1.1"
122123 , "Fair" ==> "Fair License"
123124 , "Frameworx-1.0" ==> "Frameworx Open License 1.0"
124− , "AGPL-3.0" ==> "GNU Affero General Public License v3.0"
125125 , "GPL-2.0" ==> "GNU General Public License v2.0 only"
126126 , "GPL-3.0" ==> "GNU General Public License v3.0 only"
127− , "LGPL-2.1" ==> "GNU Lesser General Public License v2.1 only"
128− , "LGPL-3.0" ==> "GNU Lesser General Public License v3.0 only"
129− , "LGPL-2.0" ==> "GNU Library General Public License v2 only"
130127 , "HPND" ==> "Historic Permission Notice and Disclaimer"
131− , "IPL-1.0" ==> "IBM Public License v1.0"
132128 , "Intel" ==> "Intel Open Source License"
133129 , "IPA" ==> "IPA Font License"
130+ , "IPL-1.0" ==> "IBM Public License v1.0"
134131 , "ISC" ==> "ISC License"
135− , "LPPL-1.3c" ==> "LaTeX Project Public License v1.3c"
132+ , "LGPL-2.0" ==> "GNU Library General Public License v2 only"
133+ , "LGPL-2.1" ==> "GNU Lesser General Public License v2.1 only"
134+ , "LGPL-3.0" ==> "GNU Lesser General Public License v3.0 only"
136135 , "LiLiQ-P-1.1" ==> "Licence Libre du Québec – Permissive version 1.1"
137− , "LiLiQ-Rplus-1.1" ==> "Licence Libre du Québec – Réciprocité forte version 1.1"
138136 , "LiLiQ-R-1.1" ==> "Licence Libre du Québec – Réciprocité version 1.1"
139− , "LPL-1.02" ==> "Lucent Public License v1.02"
137+ , "LiLiQ-Rplus-1.1" ==> "Licence Libre du Québec – Réciprocité forte version 1.1"
140138 , "LPL-1.0" ==> "Lucent Public License Version 1.0"
141− , "MS-PL" ==> "Microsoft Public License"
142− , "MS-RL" ==> "Microsoft Reciprocal License"
139+ , "LPL-1.02" ==> "Lucent Public License v1.02"
140+ , "LPPL-1.3c" ==> "LaTeX Project Public License v1.3c"
143141 , "MirOS" ==> "MirOS Licence"
144142 , "MIT" ==> "MIT License"
145143 , "Motosoto" ==> "Motosoto License"
@@ -147,38 +145,40 @@ osiApprovedSpdxLicenses =
147145 , "MPL-1.1" ==> "Mozilla Public License 1.1"
148146 , "MPL-2.0" ==> "Mozilla Public License 2.0"
149147 , "MPL-2.0-no-copyleft-exception" ==> "Mozilla Public License 2.0 (no copyleft exception)"
148+ , "MS-PL" ==> "Microsoft Public License"
149+ , "MS-RL" ==> "Microsoft Reciprocal License"
150150 , "Multics" ==> "Multics License"
151151 , "NASA-1.3" ==> "NASA Open Source Agreement 1.3"
152152 , "Naumen" ==> "Naumen Public License"
153+ , "NCSA" ==> "University of Illinois/NCSA Open Source License"
153154 , "NGPL" ==> "Nethack General Public License"
154155 , "Nokia" ==> "Nokia Open Source License"
155156 , "NPOSL-3.0" ==> "Non-Profit Open Software License 3.0"
156157 , "NTP" ==> "NTP License"
157158 , "OCLC-2.0" ==> "OCLC Research Public License 2.0"
159+ , "OFL-1.1" ==> "SIL Open Font License 1.1"
158160 , "OGTSL" ==> "Open Group Test Suite License"
161+ , "OSET-PL-2.1" ==> "OSET Public License version 2.1"
159162 , "OSL-1.0" ==> "Open Software License 1.0"
160163 , "OSL-2.0" ==> "Open Software License 2.0"
161164 , "OSL-2.1" ==> "Open Software License 2.1"
162165 , "OSL-3.0" ==> "Open Software License 3.0"
163− , "OSET-PL-2.1" ==> "OSET Public License version 2.1"
164166 , "PHP-3.0" ==> "PHP License v3.0"
165167 , "PostgreSQL" ==> "PostgreSQL License"
166168 , "Python-2.0" ==> "Python License 2.0"
167169 , "QPL-1.0" ==> "Q Public License 1.0"
168− , "RPSL-1.0" ==> "RealNetworks Public Source License v1.0"
169170 , "RPL-1.1" ==> "Reciprocal Public License 1.1"
170171 , "RPL-1.5" ==> "Reciprocal Public License 1.5"
172+ , "RPSL-1.0" ==> "RealNetworks Public Source License v1.0"
171173 , "RSCPL" ==> "Ricoh Source Code Public License"
172− , "OFL-1.1" ==> "SIL Open Font License 1.1"
173174 , "SimPL-2.0" ==> "Simple Public License 2.0"
174− , "Sleepycat" ==> "Sleepycat License"
175175 , "SISSL" ==> "Sun Industry Standards Source License v1.1"
176+ , "Sleepycat" ==> "Sleepycat License"
176177 , "SPL-1.0" ==> "Sun Public License v1.0"
177− , "Watcom-1.0" ==> "Sybase Open Watcom Public License 1.0"
178178 , "UPL-1.0" ==> "Universal Permissive License v1.0"
179− , "NCSA" ==> "University of Illinois/NCSA Open Source License"
180179 , "VSL-1.0" ==> "Vovida Software License v1.0"
181180 , "W3C" ==> "W3C Software Notice and License (2002-12-31)"
181+ , "Watcom-1.0" ==> "Sybase Open Watcom Public License 1.0"
182182 , "Xnet" ==> "X.Net License"
183183 , "Zlib" ==> "zlib License"
184184 , "ZPL-2.0" ==> "Zope Public License 2.0"
compiler/src/Elm/ModuleName.hs+2−6
@@ -7,12 +7,13 @@ module Elm.ModuleName
77 --
88 , encode
99 , decoder
10+ , parser
1011 --
1112 , Canonical(..)
1213 , basics, char, string
1314 , maybe, result, list, array, dict, tuple
1415 , platform, cmd, sub
15− , debug, bitwise
16+ , debug
1617 , virtualDom
1718 , jsonDecode, jsonEncode
1819 , webgl, texture, vector2, vector3, vector4, matrix4
@@ -225,11 +226,6 @@ debug :: Canonical
225226debug = Canonical Pkg.core Name.debug
226227
227228
228−{-# NOINLINE bitwise #-}
229−bitwise :: Canonical
230−bitwise = Canonical Pkg.core Name.bitwise
231−
232−
233229
234230-- HTML
235231
compiler/src/Elm/Package.hs+2−9
@@ -58,6 +58,7 @@ data Name =
5858 { _author :: !Author
5959 , _project :: !Project
6060 }
61+ deriving (Ord)
6162
6263
6364type Author = Utf8.Utf8 AUTHOR
@@ -267,19 +268,11 @@ instance Eq Canonical where
267268 version1 == version2 && package1 == package2
268269
269270
270−instance Ord Name where
271− compare (Name author1 project1) (Name author2 project2) =
272− case compare project1 project2 of
273− LT -> LT
274− EQ -> compare author1 author2
275− GT -> GT
276−
277−
278271
279272-- BINARY
280273
281274
282−instance Binary Name where -- TODO try storing as a Word16
275+instance Binary Name where -- PERF try storing as a Word16
283276 get = liftM2 Name Utf8.getUnder256 Utf8.getUnder256
284277 put (Name a b) = Utf8.putUnder256 a >> Utf8.putUnder256 b
285278
compiler/src/Elm/String.hs−1
@@ -108,7 +108,6 @@ writeChunks mba offset chunks =
108108 writeChunks mba newOffset chunks
109109
110110
111−-- TODO see if it is faster to writeWord32 a block of hex-as-ascii
112111writeCode :: MBA RealWorld -> Int -> Int -> ST RealWorld ()
113112writeCode mba offset code =
114113 do writeWord8 mba offset 0x5C {- \ -}
compiler/src/Generate/Html.hs+11−10
@@ -29,22 +29,23 @@ sandwich moduleName javascript =
2929
3030<body>
3131
32−<pre id="elm">
33−This is a headless program, meaning there is nothing to show here.
34−
35−I started the program anyway though!
36−
37−You can access it as `app` in the developer console.
38−</pre>
32+<pre id="elm"></pre>
3933
4034<script>
35+try {
4136|] <> javascript <> [r|
4237
43−try {
4438 var app = Elm.|] <> name <> [r|.init({ node: document.getElementById("elm") });
45−} catch (e) {
39+}
40+catch (e)
41+{
4642 // display initialization errors (e.g. bad flags, infinite recursion)
47− document.getElementById("elm").innerText = e;
43+ var header = document.createElement("h1");
44+ header.style.fontFamily = "monospace";
45+ header.innerText = "Initialization Error";
46+ var pre = document.getElementById("elm");
47+ document.body.insertBefore(header, pre);
48+ pre.innerText = e;
4849 throw e;
4950}
5051</script>
compiler/src/Generate/JavaScript.hs+45−10
@@ -2,6 +2,7 @@
22module Generate.JavaScript
33 ( generate
44 , generateForRepl
5+ , generateForReplEndpoint
56 )
67 where
78
@@ -85,7 +86,8 @@ generateForRepl ansi localizer (Opt.GlobalGraph graph _) home name (Can.Forall _
8586 debugState = addGlobal mode graph emptyState (Opt.Global ModuleName.debug "toString")
8687 evalState = addGlobal mode graph debugState (Opt.Global home name)
8788 in
88− Functions.functions
89+ "process.on('uncaughtException', function(err) { process.stderr.write(err.toString() + '\\n'); process.exit(1); });"
90+ <> Functions.functions
8991 <> stateToBuilder evalState
9092 <> print ansi localizer home name tipe
9193
@@ -98,14 +100,47 @@ print ansi localizer home name tipe =
98100 tipeDoc = RT.canToDoc localizer RT.None tipe
99101 bool = if ansi then "true" else "false"
100102 in
101− "var _value = " <> toString <> "(" <> bool <> ", " <> value <> ");\n\
102− \var _type = " <> B.stringUtf8 (show (D.toString tipeDoc)) <> ";\n\
103− \function _print(t) { console.log(_value + (" <> bool <> " ? '\x1b[90m' + t + '\x1b[0m' : t)); }\n\
104− \if (_value.length + 3 + _type.length >= 80 || _type.indexOf('\\n') >= 0) {\n\
105− \ _print('\\n : ' + _type.split('\\n').join('\\n '));\n\
106− \} else {\n\
107− \ _print(' : ' + _type);\n\
108− \}\n"
103+ "var _value = " <> toString <> "(" <> bool <> ", " <> value <> ");\n\
104+ \var _type = " <> B.stringUtf8 (show (D.toString tipeDoc)) <> ";\n\
105+ \function _print(t) { console.log(_value + (" <> bool <> " ? '\x1b[90m' + t + '\x1b[0m' : t)); }\n\
106+ \if (_value.length + 3 + _type.length >= 80 || _type.indexOf('\\n') >= 0) {\n\
107+ \ _print('\\n : ' + _type.split('\\n').join('\\n '));\n\
108+ \} else {\n\
109+ \ _print(' : ' + _type);\n\
110+ \}\n"
111+
112+
113+
114+-- GENERATE FOR REPL ENDPOINT
115+
116+
117+generateForReplEndpoint :: L.Localizer -> Opt.GlobalGraph -> ModuleName.Canonical -> Maybe Name.Name -> Can.Annotation -> B.Builder
118+generateForReplEndpoint localizer (Opt.GlobalGraph graph _) home maybeName (Can.Forall _ tipe) =
119+ let
120+ name = maybe Name.replValueToPrint id maybeName
121+ mode = Mode.Dev Nothing
122+ debugState = addGlobal mode graph emptyState (Opt.Global ModuleName.debug "toString")
123+ evalState = addGlobal mode graph debugState (Opt.Global home name)
124+ in
125+ Functions.functions
126+ <> stateToBuilder evalState
127+ <> postMessage localizer home maybeName tipe
128+
129+
130+postMessage :: L.Localizer -> ModuleName.Canonical -> Maybe Name.Name -> Can.Type -> B.Builder
131+postMessage localizer home maybeName tipe =
132+ let
133+ name = maybe Name.replValueToPrint id maybeName
134+ value = JsName.toBuilder (JsName.fromGlobal home name)
135+ toString = JsName.toBuilder (JsName.fromKernel Name.debug "toAnsiString")
136+ tipeDoc = RT.canToDoc localizer RT.None tipe
137+ toName n = "\"" <> Name.toBuilder n <> "\""
138+ in
139+ "self.postMessage({\n\
140+ \ name: " <> maybe "null" toName maybeName <> ",\n\
141+ \ value: " <> toString <> "(true, " <> value <> "),\n\
142+ \ type: " <> B.stringUtf8 (show (D.toString tipeDoc)) <> "\n\
143+ \});\n"
109144
110145
111146
@@ -257,7 +292,7 @@ generateCycle mode (Opt.Global home _) names values functions =
257292 "Some top-level definitions from `" <> Name.toBuilder (ModuleName._module home) <> "` are causing infinite recursion:\\n"
258293 <> drawCycle names
259294 <> "\\n\\nThese errors are very tricky, so read "
260− <> B.stringUtf8 (D.makeNakedLink "halting-problem")
295+ <> B.stringUtf8 (D.makeNakedLink "bad-recursion")
261296 <> " to learn how to fix it!"
262297 ]
263298
compiler/src/Generate/Mode.hs−1
@@ -49,7 +49,6 @@ shortenFieldNames (Opt.GlobalGraph _ frequencies) =
4949
5050addToBuckets :: Name.Name -> Int -> Map.Map Int [Name.Name] -> Map.Map Int [Name.Name]
5151addToBuckets field frequency buckets =
52− -- TODO try using an IntMap for buckets
5352 Map.insertWith (++) frequency [field] buckets
5453
5554
compiler/src/Json/Decode.hs+3−3
@@ -32,7 +32,7 @@ module Json.Decode
3232import qualified Data.ByteString.Internal as B
3333import qualified Data.Map as Map
3434import qualified Data.NonEmptyList as NE
35−import Data.Word (Word8, Word16)
35+import Data.Word (Word8)
3636import Foreign.Ptr (Ptr, plusPtr, minusPtr)
3737import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
3838
@@ -630,7 +630,7 @@ data StringStatus
630630 | BadString StringProblem
631631
632632
633−pStringHelp :: Ptr Word8 -> Ptr Word8 -> Word16 -> Word16 -> (# StringStatus, Ptr Word8, Word16, Word16 #)
633+pStringHelp :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> (# StringStatus, Ptr Word8, Row, Col #)
634634pStringHelp pos end row col =
635635 if pos >= end then
636636 (# BadString BadStringEnd, pos, row, col #)
@@ -708,7 +708,7 @@ spaces =
708708 cok () newState
709709
710710
711−eatSpaces :: Ptr Word8 -> Ptr Word8 -> Word16 -> Word16 -> (# Ptr Word8, Word16, Word16 #)
711+eatSpaces :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> (# Ptr Word8, Row, Col #)
712712eatSpaces pos end row col =
713713 if pos >= end then
714714 (# pos, row, col #)
compiler/src/Json/Encode.hs+4−3
@@ -104,21 +104,22 @@ list encodeEntry entries =
104104-- CHARS
105105
106106
107−chars :: [Char] -> Value -- TODO can this be done better? Look for examples.
107+chars :: [Char] -> Value -- PERF can this be done better? Look for examples.
108108chars chrs =
109109 String (B.char7 '"' <> B.stringUtf8 (escape chrs) <> B.char7 '"')
110110
111111
112−escape :: [Char] -> [Char] -- TODO is this correct?
112+escape :: [Char] -> [Char]
113113escape chrs =
114114 case chrs of
115115 [] ->
116116 []
117117
118118 c:cs
119+ | c == '\r' -> '\\' : 'r' : escape cs
119120 | c == '\n' -> '\\' : 'n' : escape cs
120121 | c == '\"' -> '\\' : '"' : escape cs
121− | c == '\'' -> '\\' : '\'' : escape cs
122+ | c == '\\' -> '\\' : '\\' : escape cs
122123 | otherwise -> c : escape cs
123124
124125
compiler/src/Json/String.hs+1−2
@@ -37,7 +37,7 @@ import qualified Parse.Primitives as P
3737
3838
3939-- INVARIANT: any Json.String is appropriately escaped already
40−-- TODO: is this the right representation for Json.String? Maybe ByteString instead?
40+-- PERF: is this the right representation for Json.String? Maybe ByteString instead?
4141--
4242type String =
4343 Utf8.Utf8 JSON_STRING
@@ -116,7 +116,6 @@ chompChunks pos end start revChunks =
116116 case word of
117117 0x0A {-\n-} -> chompEscape 0x6E {-n-} pos end start revChunks
118118 0x22 {-"-} -> chompEscape 0x22 {-"-} pos end start revChunks
119− 0x27 {-'-} -> chompEscape 0x27 {-'-} pos end start revChunks
120119 0x5C {-\-} -> chompEscape 0x5C {-\-} pos end start revChunks
121120 0x0D {-\r-} ->
122121 let
compiler/src/Optimize/DecisionTree.hs+2−2
@@ -618,7 +618,7 @@ instance Binary Test where
618618 5 -> liftM IsStr get
619619 6 -> liftM IsInt get
620620 7 -> liftM IsBool get
621− _ -> error "problem getting DecisionTree.Test binary"
621+ _ -> fail "problem getting DecisionTree.Test binary"
622622
623623
624624instance Binary Path where
@@ -634,4 +634,4 @@ instance Binary Path where
634634 0 -> liftM2 Index get get
635635 1 -> liftM Unbox get
636636 2 -> pure Empty
637− _ -> error "problem getting DecisionTree.Path binary"
637+ _ -> fail "problem getting DecisionTree.Path binary"
compiler/src/Optimize/Port.hs+1−1
@@ -58,7 +58,7 @@ toEncoder tipe =
5858 | name == Name.array -> encodeArray arg
5959
6060 _ ->
61− error "toEncoder: bad union type"
61+ error "toEncoder: bad custom type"
6262
6363 Can.TRecord _ (Just _) ->
6464 error "toEncoder: bad record"
compiler/src/Parse/Expression.hs+40−32
@@ -128,38 +128,46 @@ chompListEnd start entries =
128128tuple :: A.Position -> Parser E.Expr Src.Expr
129129tuple start@(A.Position row col) =
130130 inContext E.Tuple (word1 0x28 {-(-} E.Start) $
131− oneOf E.TupleIndentExpr1
132− [
133− do op <- Symbol.operator E.TupleIndentExpr1 E.TupleOperatorReserved
134− if op == "-"
135− then
136− oneOf E.TupleOperatorClose
137− [
138− do word1 0x29 {-)-} E.TupleOperatorClose
139− addEnd start (Src.Op op)
140− ,
141− do (entry, end) <-
142− specialize E.TupleExpr $
143− do negatedExpr@(A.At (A.Region _ end) _) <- term
144− Space.chomp E.Space
145− let exprStart = A.Position row (col + 2)
146− let expr = A.at exprStart end (Src.Negate negatedExpr)
147− chompExprEnd exprStart (State [] expr [] end)
148− Space.checkIndent end E.TupleIndentEnd
149− chompTupleEnd start entry []
150− ]
151− else
152− do word1 0x29 {-)-} E.TupleOperatorClose
153− addEnd start (Src.Op op)
154− ,
155− do word1 0x29 {-)-} E.TupleIndentExpr1
156− addEnd start Src.Unit
157− ,
158− do Space.chompAndCheckIndent E.TupleSpace E.TupleIndentExpr1
159− (entry, end) <- specialize E.TupleExpr expression
160− Space.checkIndent end E.TupleIndentEnd
161− chompTupleEnd start entry []
162− ]
131+ do before <- getPosition
132+ Space.chompAndCheckIndent E.TupleSpace E.TupleIndentExpr1
133+ after <- getPosition
134+ if before /= after
135+ then
136+ do (entry, end) <- specialize E.TupleExpr expression
137+ Space.checkIndent end E.TupleIndentEnd
138+ chompTupleEnd start entry []
139+ else
140+ oneOf E.TupleIndentExpr1
141+ [
142+ do op <- Symbol.operator E.TupleIndentExpr1 E.TupleOperatorReserved
143+ if op == "-"
144+ then
145+ oneOf E.TupleOperatorClose
146+ [
147+ do word1 0x29 {-)-} E.TupleOperatorClose
148+ addEnd start (Src.Op op)
149+ ,
150+ do (entry, end) <-
151+ specialize E.TupleExpr $
152+ do negatedExpr@(A.At (A.Region _ end) _) <- term
153+ Space.chomp E.Space
154+ let exprStart = A.Position row (col + 2)
155+ let expr = A.at exprStart end (Src.Negate negatedExpr)
156+ chompExprEnd exprStart (State [] expr [] end)
157+ Space.checkIndent end E.TupleIndentEnd
158+ chompTupleEnd start entry []
159+ ]
160+ else
161+ do word1 0x29 {-)-} E.TupleOperatorClose
162+ addEnd start (Src.Op op)
163+ ,
164+ do word1 0x29 {-)-} E.TupleIndentExpr1
165+ addEnd start Src.Unit
166+ ,
167+ do (entry, end) <- specialize E.TupleExpr expression
168+ Space.checkIndent end E.TupleIndentEnd
169+ chompTupleEnd start entry []
170+ ]
163171
164172
165173chompTupleEnd :: A.Position -> Src.Expr -> [Src.Expr] -> Parser E.Tuple Src.Expr
compiler/src/Parse/Module.hs+81−35
@@ -2,6 +2,8 @@
22{-# LANGUAGE OverloadedStrings #-}
33module Parse.Module
44 ( fromByteString
5+ , ProjectType(..)
6+ , isKernel
57 , chompImports
68 , chompImport
79 )
@@ -29,14 +31,37 @@ import qualified Reporting.Error.Syntax as E
2931-- FROM BYTE STRING
3032
3133
32−fromByteString :: Pkg.Name -> BS.ByteString -> Either E.Error Src.Module
33−fromByteString pkg source =
34− case P.fromByteString (chompModule pkg) E.ModuleBadEnd source of
35− Right modul -> checkModule modul
34+fromByteString :: ProjectType -> BS.ByteString -> Either E.Error Src.Module
35+fromByteString projectType source =
36+ case P.fromByteString (chompModule projectType) E.ModuleBadEnd source of
37+ Right modul -> checkModule projectType modul
3638 Left err -> Left (E.ParseError err)
3739
3840
3941
42+-- PROJECT TYPE
43+
44+
45+data ProjectType
46+ = Package Pkg.Name
47+ | Application
48+
49+
50+isCore :: ProjectType -> Bool
51+isCore projectType =
52+ case projectType of
53+ Package pkg -> pkg == Pkg.core
54+ Application -> False
55+
56+
57+isKernel :: ProjectType -> Bool
58+isKernel projectType =
59+ case projectType of
60+ Package pkg -> Pkg.isKernel pkg
61+ Application -> False
62+
63+
64+
4065-- MODULE
4166
4267
@@ -49,11 +74,11 @@ data Module =
4974 }
5075
5176
52−chompModule :: Pkg.Name -> Parser E.Module Module
53−chompModule pkg =
77+chompModule :: ProjectType -> Parser E.Module Module
78+chompModule projectType =
5479 do header <- chompHeader
55− imports <- chompImports (if pkg == Pkg.core then [] else Imports.defaults)
56− infixes <- if Pkg.isKernel pkg then chompInfixes [] else return []
80+ imports <- chompImports (if isCore projectType then [] else Imports.defaults)
81+ infixes <- if isKernel projectType then chompInfixes [] else return []
5782 decls <- specialize E.Declarations $ chompDecls []
5883 return (Module header imports infixes decls)
5984
@@ -62,15 +87,15 @@ chompModule pkg =
6287-- CHECK MODULE
6388
6489
65−checkModule :: Module -> Either E.Error Src.Module
66−checkModule (Module maybeHeader imports infixes decls) =
90+checkModule :: ProjectType -> Module -> Either E.Error Src.Module
91+checkModule projectType (Module maybeHeader imports infixes decls) =
6792 let
6893 (values, unions, aliases, ports) = categorizeDecls [] [] [] [] decls
6994 in
7095 case maybeHeader of
7196 Just (Header name effects exports docs) ->
7297 Src.Module (Just name) exports (toDocs docs decls) imports values unions aliases infixes
73− <$> checkEffects ports effects
98+ <$> checkEffects projectType ports effects
7499
75100 Nothing ->
76101 Right $
@@ -80,23 +105,37 @@ checkModule (Module maybeHeader imports infixes decls) =
80105 _:_ -> Src.Ports ports
81106
82107
83−checkEffects :: [Src.Port] -> Effects -> Either E.Error Src.Effects
84−checkEffects ports effects =
108+checkEffects :: ProjectType -> [Src.Port] -> Effects -> Either E.Error Src.Effects
109+checkEffects projectType ports effects =
85110 case effects of
86111 NoEffects region ->
87112 case ports of
88− [] -> Right Src.NoEffects
89− _:_ -> Left (E.UnexpectedPort region)
113+ [] ->
114+ Right Src.NoEffects
115+
116+ Src.Port name _ : _ ->
117+ case projectType of
118+ Package _ -> Left (E.NoPortsInPackage name)
119+ Application -> Left (E.UnexpectedPort region)
90120
91121 Ports region ->
92− case ports of
93− [] -> Left (E.NoPorts region)
94− _:_ -> Right (Src.Ports ports)
122+ case projectType of
123+ Package _ ->
124+ Left (E.NoPortModulesInPackage region)
125+
126+ Application ->
127+ case ports of
128+ [] -> Left (E.NoPorts region)
129+ _:_ -> Right (Src.Ports ports)
95130
96131 Manager region manager ->
97− case ports of
98− [] -> Right (Src.Manager region manager)
99− _:_ -> Left (E.UnexpectedPort region)
132+ if isKernel projectType then
133+ case ports of
134+ [] -> Right (Src.Manager region manager)
135+ _:_ -> Left (E.UnexpectedPort region)
136+ else
137+ Left (E.NoEffectsOutsideKernel region)
138+
100139
101140
102141categorizeDecls :: [A.Located Src.Value] -> [A.Located Src.Union] -> [A.Located Src.Alias] -> [Src.Port] -> [Decl.Decl] -> ( [A.Located Src.Value], [A.Located Src.Union], [A.Located Src.Alias], [Src.Port] )
@@ -395,18 +434,18 @@ exposing =
395434 Space.chompAndCheckIndent E.ExposingSpace E.ExposingIndentEnd
396435 word1 0x29 {-)-} E.ExposingEnd
397436 return Src.Open
398− , do exposed <- addLocation chompExposed
437+ , do exposed <- chompExposed
399438 Space.chompAndCheckIndent E.ExposingSpace E.ExposingIndentEnd
400439 exposingHelp [exposed]
401440 ]
402441
403442
404−exposingHelp :: [A.Located Src.Exposed] -> Parser E.Exposing Src.Exposing
443+exposingHelp :: [Src.Exposed] -> Parser E.Exposing Src.Exposing
405444exposingHelp revExposed =
406445 oneOf E.ExposingEnd
407446 [ do word1 0x2C {-,-} E.ExposingEnd
408447 Space.chompAndCheckIndent E.ExposingSpace E.ExposingIndentValue
409− exposed <- addLocation chompExposed
448+ exposed <- chompExposed
410449 Space.chompAndCheckIndent E.ExposingSpace E.ExposingIndentEnd
411450 exposingHelp (exposed:revExposed)
412451 , do word1 0x29 {-)-} E.ExposingEnd
@@ -416,16 +455,21 @@ exposingHelp revExposed =
416455
417456chompExposed :: Parser E.Exposing Src.Exposed
418457chompExposed =
419− oneOf E.ExposingValue
420− [ Src.Lower <$> Var.lower E.ExposingValue
421− , do word1 0x28 {-(-} E.ExposingValue
422− op <- Symbol.operator E.ExposingOperator E.ExposingOperatorReserved
423− word1 0x29 {-)-} E.ExposingOperatorRightParen
424− return (Src.Operator op)
425− , do name <- Var.upper E.ExposingValue
426− Space.chompAndCheckIndent E.ExposingSpace E.ExposingIndentEnd
427− Src.Upper name <$> privacy
428− ]
458+ do start <- getPosition
459+ oneOf E.ExposingValue
460+ [ do name <- Var.lower E.ExposingValue
461+ end <- getPosition
462+ return $ Src.Lower $ A.at start end name
463+ , do word1 0x28 {-(-} E.ExposingValue
464+ op <- Symbol.operator E.ExposingOperator E.ExposingOperatorReserved
465+ word1 0x29 {-)-} E.ExposingOperatorRightParen
466+ end <- getPosition
467+ return $ Src.Operator (A.Region start end) op
468+ , do name <- Var.upper E.ExposingValue
469+ end <- getPosition
470+ Space.chompAndCheckIndent E.ExposingSpace E.ExposingIndentEnd
471+ Src.Upper (A.at start end name) <$> privacy
472+ ]
429473
430474
431475privacy :: Parser E.Exposing Src.Privacy
@@ -433,9 +477,11 @@ privacy =
433477 oneOfWithFallback
434478 [ do word1 0x28 {-(-} E.ExposingTypePrivacy
435479 Space.chompAndCheckIndent E.ExposingSpace E.ExposingTypePrivacy
480+ start <- getPosition
436481 word2 0x2E 0x2E {-..-} E.ExposingTypePrivacy
482+ end <- getPosition
437483 Space.chompAndCheckIndent E.ExposingSpace E.ExposingTypePrivacy
438484 word1 0x29 {-)-} E.ExposingTypePrivacy
439− return Src.Public
485+ return $ Src.Public (A.Region start end)
440486 ]
441487 Src.Private
compiler/src/Parse/Pattern.hs+1−1
@@ -129,7 +129,7 @@ recordHelp start vars =
129129 Space.chompAndCheckIndent E.PRecordSpace E.PRecordIndentEnd
130130 recordHelp start (var:vars)
131131 , do word1 0x7D {-}-} E.PRecordEnd
132− addEnd start (Src.PRecord vars)
132+ addEnd start (Src.PRecord (reverse vars))
133133 ]
134134
135135
compiler/src/Parse/Primitives.hs+2−2
@@ -46,7 +46,7 @@ newtype Parser x a =
4646 )
4747
4848
49−data State = -- TODO try taking some out to avoid allocation?
49+data State = -- PERF try taking some out to avoid allocation
5050 State
5151 { _src :: ForeignPtr Word8
5252 , _pos :: !(Ptr Word8)
@@ -145,7 +145,7 @@ oneOfHelp state cok eok cerr eerr toError parsers =
145145
146146
147147{-# INLINE oneOfWithFallback #-}
148−oneOfWithFallback :: [Parser x a] -> a -> Parser x a -- TODO is this function okay? Worried about allocation/laziness with fallback values.
148+oneOfWithFallback :: [Parser x a] -> a -> Parser x a -- PERF is this function okay? Worried about allocation/laziness with fallback values.
149149oneOfWithFallback parsers fallback =
150150 Parser $ \state cok eok cerr _ ->
151151 oowfHelp state cok eok cerr parsers fallback
compiler/src/Parse/Space.hs+2−2
@@ -157,7 +157,7 @@ eatSpaces pos end row col =
157157-- LINE COMMENTS
158158
159159
160−eatLineComment :: Ptr Word8 -> Ptr Word8 -> Word16 -> Word16 -> (# Status, Ptr Word8, Word16, Word16 #)
160+eatLineComment :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> (# Status, Ptr Word8, Row, Col #)
161161eatLineComment pos end row col =
162162 if pos >= end then
163163 (# Good, pos, row, col #)
@@ -208,7 +208,7 @@ data MultiStatus
208208 | MultiEndless
209209
210210
211−eatMultiCommentHelp :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> Word16 -> (# MultiStatus, Ptr Word8, Word16, Word16 #)
211+eatMultiCommentHelp :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> Word16 -> (# MultiStatus, Ptr Word8, Row, Col #)
212212eatMultiCommentHelp pos end row col openComments =
213213 if pos >= end then
214214 (# MultiEndless, pos, row, col #)
compiler/src/Parse/String.hs+2−2
@@ -165,7 +165,7 @@ addEscape chunk start end revChunks =
165165-- SINGLE STRINGS
166166
167167
168−singleString :: Ptr Word8 -> Ptr Word8 -> Word16 -> Word16 -> Ptr Word8 -> [ES.Chunk] -> StringResult
168+singleString :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> Ptr Word8 -> [ES.Chunk] -> StringResult
169169singleString pos end row col initialPos revChunks =
170170 if pos >= end then
171171 Err row col E.StringEndless_Single
@@ -211,7 +211,7 @@ singleString pos end row col initialPos revChunks =
211211-- MULTI STRINGS
212212
213213
214−multiString :: Ptr Word8 -> Ptr Word8 -> Word16 -> Word16 -> Ptr Word8 -> Word16 -> Word16 -> [ES.Chunk] -> StringResult
214+multiString :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> Ptr Word8 -> Row -> Col -> [ES.Chunk] -> StringResult
215215multiString pos end row col initialPos sr sc revChunks =
216216 if pos >= end then
217217 Err sr sc E.StringEndless_Multi
compiler/src/Parse/Variable.hs+3−3
@@ -67,7 +67,7 @@ lower toError =
6767
6868
6969{-# NOINLINE reservedWords #-}
70−reservedWords :: Set.Set Name.Name -- TODO try using a trie instead
70+reservedWords :: Set.Set Name.Name -- PERF try using a trie instead
7171reservedWords =
7272 Set.fromList
7373 [ "if", "then", "else"
@@ -149,14 +149,14 @@ foreignUpper toError =
149149 let
150150 !newState = P.State src upperEnd end indent row newCol
151151 !name = Name.fromPtr upperStart upperEnd
152− !foreign =
152+ !upperName =
153153 if upperStart == pos then
154154 Unqualified name
155155 else
156156 let !home = Name.fromPtr pos (plusPtr upperStart (-1)) in
157157 Qualified home name
158158 in
159− cok foreign newState
159+ cok upperName newState
160160
161161
162162foreignUpperHelp :: Ptr Word8 -> Ptr Word8 -> Col -> (# Ptr Word8, Ptr Word8, Col #)
compiler/src/Reporting/Annotation.hs+1−1
@@ -26,7 +26,7 @@ import Data.Word (Word16)
2626
2727
2828data Located a =
29− At Region a -- TODO see if unpacking region is helpful
29+ At Region a -- PERF see if unpacking region is helpful
3030
3131
3232instance Functor Located where
compiler/src/Reporting/Doc.hs+14−20
@@ -56,6 +56,7 @@ import qualified Text.PrettyPrint.ANSI.Leijen as P
5656import qualified Data.Index as Index
5757import qualified Elm.Package as Pkg
5858import qualified Elm.Version as V
59+import Json.Encode ((==>))
5960import qualified Json.Encode as E
6061import qualified Json.String as Json
6162
@@ -305,10 +306,8 @@ data Color
305306 | WHITE
306307
307308
308−toJsonHelp :: Style -> [a] -> P.SimpleDoc -> [E.Value]
309+toJsonHelp :: Style -> [String] -> P.SimpleDoc -> [E.Value]
309310toJsonHelp style revChunks simpleDoc =
310− error "TODO generate json on errors" style revChunks simpleDoc sgrToStyle encodeColor
311−{-
312311 case simpleDoc of
313312 P.SFail ->
314313 error $
@@ -319,23 +318,18 @@ toJsonHelp style revChunks simpleDoc =
319318 [ encodeChunks style revChunks ]
320319
321320 P.SChar char rest ->
322− toJsonHelp style (TB.singleton char : revChunks) rest
321+ toJsonHelp style ([char] : revChunks) rest
323322
324323 P.SText _ string rest ->
325− toJsonHelp style (TB.fromString string : revChunks) rest
324+ toJsonHelp style (string : revChunks) rest
326325
327326 P.SLine indent rest ->
328− toJsonHelp style (spaces indent : "\n" : revChunks) rest
327+ toJsonHelp style (replicate indent ' ' : "\n" : revChunks) rest
329328
330329 P.SSGR sgrs rest ->
331330 encodeChunks style revChunks : toJsonHelp (sgrToStyle sgrs style) [] rest
332331
333332
334−spaces :: Int -> TB.Builder
335−spaces n =
336− TB.fromText (Text.replicate n " ")
337−-}
338−
339333sgrToStyle :: [Ansi.SGR] -> Style -> Style
340334sgrToStyle sgrs style@(Style bold underline color) =
341335 case sgrs of
@@ -396,24 +390,24 @@ toColor layer intensity color =
396390 Ansi.White -> pick White WHITE
397391 Ansi.Black -> pick Black BLACK
398392
399−{-
400−encodeChunks :: Style -> [TB.Builder] -> E.Value
393+
394+encodeChunks :: Style -> [String] -> E.Value
401395encodeChunks (Style bold underline color) revChunks =
402396 let
403− !str = Utf8.concat (reverse revChunks)
397+ chars = concat (reverse revChunks)
404398 in
405399 case color of
406400 Nothing | not bold && not underline ->
407− E.string str
401+ E.chars chars
408402
409403 _ ->
410404 E.object
411− [ ("bold", E.bool bold)
412− , ("underline", E.bool underline)
413− , ("color", maybe E.null encodeColor color)
414− , ("string", E.string str)
405+ [ "bold" ==> E.bool bold
406+ , "underline" ==> E.bool underline
407+ , "color" ==> maybe E.null encodeColor color
408+ , "string" ==> E.chars chars
415409 ]
416−-}
410+
417411
418412encodeColor :: Color -> E.Value
419413encodeColor color =
compiler/src/Reporting/Error.hs+20−16
@@ -12,6 +12,7 @@ module Reporting.Error
1212import qualified Data.ByteString as B
1313import qualified Data.NonEmptyList as NE
1414import qualified Data.OneOrMore as OneOrMore
15+import qualified System.FilePath as FP
1516
1617import qualified Elm.ModuleName as ModuleName
1718import qualified File
@@ -38,8 +39,8 @@ import qualified Reporting.Report as Report
3839data Module =
3940 Module
4041 { _name :: ModuleName.Raw
41− , _path :: FilePath
42− , _time :: File.Time
42+ , _absolutePath :: FilePath
43+ , _modificationTime :: File.Time
4344 , _source :: B.ByteString
4445 , _error :: Error
4546 }
@@ -92,26 +93,26 @@ toReports source err =
9293-- TO DOC
9394
9495
95−toDoc :: Module -> [Module] -> D.Doc
96−toDoc err errs =
96+toDoc :: FilePath -> Module -> [Module] -> D.Doc
97+toDoc root err errs =
9798 let
98− (NE.List m ms) = NE.sortBy _time (NE.List err errs)
99+ (NE.List m ms) = NE.sortBy _modificationTime (NE.List err errs)
99100 in
100− D.vcat (toDocHelp m ms)
101+ D.vcat (toDocHelp root m ms)
101102
102103
103−toDocHelp :: Module -> [Module] -> [D.Doc]
104−toDocHelp module1 modules =
104+toDocHelp :: FilePath -> Module -> [Module] -> [D.Doc]
105+toDocHelp root module1 modules =
105106 case modules of
106107 [] ->
107− [moduleToDoc module1
108+ [moduleToDoc root module1
108109 ,""
109110 ]
110111
111112 module2 : otherModules ->
112− moduleToDoc module1
113+ moduleToDoc root module1
113114 : toSeparator module1 module2
114− : toDocHelp module2 otherModules
115+ : toDocHelp root module2 otherModules
115116
116117
117118toSeparator :: Module -> Module -> D.Doc
@@ -133,19 +134,22 @@ toSeparator beforeModule afterModule =
133134-- MODULE TO DOC
134135
135136
136−moduleToDoc :: Module -> D.Doc
137−moduleToDoc (Module _ path _ source err) =
137+moduleToDoc :: FilePath -> Module -> D.Doc
138+moduleToDoc root (Module _ absolutePath _ source err) =
138139 let
139140 reports =
140141 toReports (Code.toSource source) err
142+
143+ relativePath =
144+ FP.makeRelative root absolutePath
141145 in
142− D.vcat $ map (reportToDoc path) (NE.toList reports)
146+ D.vcat $ map (reportToDoc relativePath) (NE.toList reports)
143147
144148
145149reportToDoc :: FilePath -> Report.Report -> D.Doc
146−reportToDoc path (Report.Report title _ _ message) =
150+reportToDoc relativePath (Report.Report title _ _ message) =
147151 D.vcat
148− [ toMessageBar title path
152+ [ toMessageBar title relativePath
149153 , ""
150154 , message
151155 , ""
compiler/src/Reporting/Error/Canonicalize.hs+41−40
@@ -14,8 +14,10 @@ module Reporting.Error.Canonicalize
1414
1515
1616import qualified Data.Char as Char
17+import qualified Data.List as List
1718import qualified Data.Map as Map
1819import qualified Data.Name as Name
20+import qualified Data.OneOrMore as OneOrMore
1921import qualified Data.Set as Set
2022
2123import qualified AST.Canonical as Can
@@ -37,10 +39,10 @@ import qualified Reporting.Suggest as Suggest
3739
3840data Error
3941 = AnnotationTooShort A.Region Name.Name Index.ZeroBased Int
40− | AmbiguousVar A.Region (Maybe Name.Name) Name.Name [ModuleName.Canonical]
41− | AmbiguousType A.Region (Maybe Name.Name) Name.Name [ModuleName.Canonical]
42− | AmbiguousVariant A.Region (Maybe Name.Name) Name.Name [ModuleName.Canonical]
43− | AmbiguousBinop A.Region Name.Name [ModuleName.Canonical]
42+ | AmbiguousVar A.Region (Maybe Name.Name) Name.Name ModuleName.Canonical (OneOrMore.OneOrMore ModuleName.Canonical)
43+ | AmbiguousType A.Region (Maybe Name.Name) Name.Name ModuleName.Canonical (OneOrMore.OneOrMore ModuleName.Canonical)
44+ | AmbiguousVariant A.Region (Maybe Name.Name) Name.Name ModuleName.Canonical (OneOrMore.OneOrMore ModuleName.Canonical)
45+ | AmbiguousBinop A.Region Name.Name ModuleName.Canonical (OneOrMore.OneOrMore ModuleName.Canonical)
4446 | BadArity A.Region BadArityContext Name.Name Int Int
4547 | Binop A.Region Name.Name Name.Name
4648 | DuplicateDecl Name.Name A.Region A.Region
@@ -164,17 +166,17 @@ toReport source err =
164166 <> " be deleted? Maybe some parentheses are missing?"
165167 )
166168
167− AmbiguousVar region maybePrefix name possibleHomes ->
168− ambiguousName source region maybePrefix name possibleHomes "variable"
169+ AmbiguousVar region maybePrefix name h hs ->
170+ ambiguousName source region maybePrefix name h hs "variable"
169171
170− AmbiguousType region maybePrefix name possibleHomes ->
171− ambiguousName source region maybePrefix name possibleHomes "type"
172+ AmbiguousType region maybePrefix name h hs ->
173+ ambiguousName source region maybePrefix name h hs "type"
172174
173− AmbiguousVariant region maybePrefix name possibleHomes ->
174− ambiguousName source region maybePrefix name possibleHomes "variant"
175+ AmbiguousVariant region maybePrefix name h hs ->
176+ ambiguousName source region maybePrefix name h hs "variant"
175177
176− AmbiguousBinop region name possibleHomes ->
177− ambiguousName source region Nothing name possibleHomes "operator"
178+ AmbiguousBinop region name h hs ->
179+ ambiguousName source region Nothing name h hs "operator"
178180
179181 BadArity region badArityContext name expected actual ->
180182 let
@@ -242,11 +244,11 @@ toReport source err =
242244
243245 DuplicateAliasArg typeName name r1 r2 ->
244246 nameClash source r1 r2 $
245− "The `" <> Name.toChars typeName <> "` type alias has multilpe `" <> Name.toChars name <> "` type variables."
247+ "The `" <> Name.toChars typeName <> "` type alias has multiple `" <> Name.toChars name <> "` type variables."
246248
247249 DuplicateUnionArg typeName name r1 r2 ->
248250 nameClash source r1 r2 $
249− "The `" <> Name.toChars typeName <> "` type has multilpe `" <> Name.toChars name <> "` type variables."
251+ "The `" <> Name.toChars typeName <> "` type has multiple `" <> Name.toChars name <> "` type variables."
250252
251253 DuplicatePattern context name r1 r2 ->
252254 nameClash source r1 r2 $
@@ -274,7 +276,7 @@ toReport source err =
274276 "You have declared that `" ++ Name.toChars name ++ "` is an effect type:"
275277 ,
276278 D.reflow $
277− "But I cannot find a union type named `" ++ Name.toChars name ++ "` in this file!"
279+ "But I cannot find a custom type named `" ++ Name.toChars name ++ "` in this file!"
278280 )
279281
280282 EffectFunctionNotFound region name ->
@@ -342,7 +344,7 @@ toReport source err =
342344 Code.toSnippet source region Nothing
343345 (
344346 D.reflow $
345− "The (..) syntax is for exposing union type constructors. It cannot be used with a type alias like `"
347+ "The (..) syntax is for exposing variants of a custom type. It cannot be used with a type alias like `"
346348 ++ Name.toChars name ++ "` though."
347349 ,
348350 D.reflow $
@@ -355,12 +357,12 @@ toReport source err =
355357 (
356358 D.reflow $
357359 "You are trying to import the `" <> Name.toChars ctor
358− <> "` type constructor by name:"
360+ <> "` variant by name:"
359361 ,
360362 D.fillSep
361363 ["Try","importing",D.green (D.fromName tipe <> "(..)"),"instead."
362364 ,"The","dots","mean","“expose","the",D.fromName tipe,"type","and"
363− ,"all","its","constructors”","so","it","gives","you","access","to"
365+ ,"all","its","variants","so","it","gives","you","access","to"
364366 , D.fromName ctor <> "."
365367 ]
366368 )
@@ -386,13 +388,8 @@ toReport source err =
386388 D.reflow $
387389 "The `" <> Name.toChars name <> "` type alias cannot be followed by (..) like this:"
388390 ,
389− D.stack
390− [ "Remove the (..) and it should work."
391− , D.link "Hint"
392− "The distinction between `type` and `type alias` is important here. Read"
393− "types-vs-type-aliases"
394− "to learn more."
395− ]
391+ D.reflow $
392+ "Remove the (..) and it should work."
396393 )
397394
398395 ImportExposingNotFound region (ModuleName.Canonical _ home) value possibleNames ->
@@ -522,7 +519,7 @@ toReport source err =
522519 <> "` as a function, but it is not available in pattern matching like this:"
523520 ,
524521 D.reflow $
525− "I recommend matching matching the record as a variable and unpacking it later."
522+ "I recommend matching the record as a variable and unpacking it later."
526523 )
527524
528525 PortPayloadInvalid region portName _badType invalidPayload ->
@@ -682,7 +679,7 @@ toReport source err =
682679 "The `" <> Name.toChars name <> "` value is defined directly in terms of itself, causing an infinite loop."
683680 ,
684681 D.stack
685− [ makeTheory "Are you are trying to mutate a variable?" $
682+ [ makeTheory "Are you trying to mutate a variable?" $
686683 "Elm does not have mutation, so when I see " ++ Name.toChars name
687684 ++ " defined in terms of " ++ Name.toChars name
688685 ++ ", I treat it as a recursive definition. Try giving the new value a new name!"
@@ -728,7 +725,7 @@ toReport source err =
728725 "The `" <> Name.toChars name <> "` value is defined directly in terms of itself, causing an infinite loop."
729726 ,
730727 D.stack
731− [ makeTheory "Are you are trying to mutate a variable?" $
728+ [ makeTheory "Are you trying to mutate a variable?" $
732729 "Elm does not have mutation, so when I see " ++ Name.toChars name
733730 ++ " defined in terms of " ++ Name.toChars name
734731 ++ ", I treat it as a recursive definition. Try giving the new value a new name!"
@@ -979,28 +976,32 @@ nameClash source r1 r2 messageThatEndsWithPunctuation =
979976-- AMBIGUOUS NAME
980977
981978
982−ambiguousName :: Code.Source -> A.Region -> Maybe Name.Name -> Name.Name -> [ModuleName.Canonical] -> String -> Report.Report
983−ambiguousName source region maybePrefix name possibleHomes thing =
979+ambiguousName :: Code.Source -> A.Region -> Maybe Name.Name -> Name.Name -> ModuleName.Canonical -> OneOrMore.OneOrMore ModuleName.Canonical -> String -> Report.Report
980+ambiguousName source region maybePrefix name h hs thing =
981+ let
982+ possibleHomes = List.sort (h : OneOrMore.destruct (:) hs)
983+ in
984984 Report.Report "AMBIGUOUS NAME" region [] $
985985 Code.toSnippet source region Nothing $
986986 case maybePrefix of
987987 Nothing ->
988988 let
989989 homeToYellowDoc (ModuleName.Canonical _ home) =
990− D.dullyellow (D.fromName home)
991−
992− bothOrAll =
993− if length possibleHomes == 2 then "both" else "all"
990+ D.dullyellow (D.fromName home <> "." <> D.fromName name)
994991 in
995992 (
996− D.reflow $ "This usage of `" ++ Name.toChars name ++ "` is ambiguous."
993+ D.reflow $ "This usage of `" ++ Name.toChars name ++ "` is ambiguous:"
997994 ,
998995 D.stack
999996 [ D.reflow $
1000− "Check your imports. The following modules " ++ bothOrAll
1001− ++ " expose a `" ++ Name.toChars name ++ "` " ++ thing ++ ":"
997+ "This name is exposed by " ++ show (length possibleHomes) ++ " of your imports, so I am not\
998+ \ sure which one to use:"
1002999 , D.indent 4 $ D.vcat $ map homeToYellowDoc possibleHomes
1003− , D.reflowLink "Read" "imports" "to learn how to clarify which one you want."
1000+ , D.reflow $
1001+ "I recommend using qualified names for imported values. I also recommend having\
1002+ \ at most one `exposing (..)` per file to make name clashes like this less common\
1003+ \ in the long run."
1004+ , D.link "Note" "Check out" "imports" "for more info on the import syntax."
10041005 ]
10051006 )
10061007
@@ -1008,9 +1009,9 @@ ambiguousName source region maybePrefix name possibleHomes thing =
10081009 let
10091010 homeToYellowDoc (ModuleName.Canonical _ home) =
10101011 if prefix == home then
1011− D.blue "import" <+> D.dullyellow (D.fromName home)
1012+ D.cyan "import" <+> D.fromName home
10121013 else
1013− D.blue "import" <+> D.dullyellow (D.fromName home) <+> D.blue "as" <+> D.dullyellow (D.fromName prefix)
1014+ D.cyan "import" <+> D.fromName home <+> D.cyan "as" <+> D.fromName prefix
10141015
10151016 eitherOrAny =
10161017 if length possibleHomes == 2 then "either" else "any"
compiler/src/Reporting/Error/Docs.hs+2−2
@@ -69,7 +69,7 @@ toReports source err =
6969 \ declaration and the imports."
7070 ,
7171 D.reflow
72− "Learn more at <http://package.elm-lang.org/help/documentation-format>"
72+ "Learn more at <https://package.elm-lang.org/help/documentation-format>"
7373 )
7474
7575 ImplicitExposing region ->
@@ -116,7 +116,7 @@ toSyntaxProblemReport source problem =
116116 , D.stack $
117117 [ D.reflow details
118118 , D.toSimpleHint $
119− "Read through https://package.elm-lang.org/help/documentation-format for\
119+ "Read through <https://package.elm-lang.org/help/documentation-format> for\
120120 \ tips on how to write module documentation!"
121121 ]
122122 )
compiler/src/Reporting/Error/Import.hs+1−1
@@ -56,7 +56,7 @@ toReport source (Error region name unimportedModules problem) =
5656 D.stack
5757 [
5858 D.reflow $
59− "I checked the \"dependencies\" and \"source-directories\" listend in your elm.json,\
59+ "I checked the \"dependencies\" and \"source-directories\" listed in your elm.json,\
6060 \ but I cannot find it! Maybe it is a typo for one of these names?"
6161 ,
6262 D.dullyellow $ D.indent 4 $ D.vcat $
compiler/src/Reporting/Error/Json.hs+16−4
@@ -51,9 +51,13 @@ parseErrorToReport :: FilePath -> Code.Source -> ParseError -> Reason -> Help.Re
5151parseErrorToReport path source parseError reason =
5252 let
5353 toSnippet title row col (problem, details) =
54− let pos = A.Position row col in
54+ let
55+ pos = A.Position row col
56+ surroundings = A.Region (A.Position (max 1 (row - 2)) 1) pos
57+ region = A.Region pos pos
58+ in
5559 Help.jsonReport title (Just path) $
56− Code.toSnippet source (A.Region pos pos) Nothing
60+ Code.toSnippet source surroundings (Just region)
5761 ( D.reflow (because reason problem)
5862 , details
5963 )
@@ -77,12 +81,20 @@ parseErrorToReport path source parseError reason =
7781 )
7882
7983 ObjectField row col ->
80− toSnippet "UNFINISHED OBJECT" row col
84+ toSnippet "EXTRA COMMA" row col
8185 (
8286 "I was partway through parsing a JSON object when I got stuck here:"
8387 ,
8488 D.stack
85− [ D.reflow $ "I was expecting to see a field name next."
89+ [ D.fillSep
90+ ["I","saw","a","comma","right","before","I","got","stuck","here,"
91+ ,"so","I","was","expecting","to","see","a","field","name","like"
92+ ,D.dullyellow "\"type\"","or",D.dullyellow "\"dependencies\"","next."
93+ ]
94+ , D.reflow $
95+ "This error is commonly caused by trailing commas in JSON objects. Those are\
96+ \ actually disallowed by <https://json.org> so check the previous line for a\
97+ \ trailing comma that may need to be deleted."
8698 , objectNote
8799 ]
88100 )
compiler/src/Reporting/Error/Pattern.hs+2−2
@@ -41,7 +41,7 @@ toReport source err =
4141 Report.Report "UNSAFE PATTERN" region [] $
4242 Code.toSnippet source region Nothing
4343 (
44− "This pattern does not cover all possiblities:"
44+ "This pattern does not cover all possibilities:"
4545 ,
4646 D.stack
4747 [ "Other possibilities include:"
@@ -64,7 +64,7 @@ toReport source err =
6464 , unhandledPatternsToDocBlock unhandled
6565 , D.reflow $
6666 "I would have to crash if I saw one of those! You can use\
67− \ `let` to deconstruct values only if there is ONE possiblity.\
67+ \ `let` to deconstruct values only if there is ONE possibility.\
6868 \ Switch to a `case` expression to account for all possibilities."
6969 , D.toSimpleHint $
7070 "Are you calling a function that definitely returns values\
compiler/src/Reporting/Error/Syntax.hs+1024−449
@@ -69,6 +69,9 @@ data Error
6969 | ModuleNameMismatch ModuleName.Raw (A.Located ModuleName.Raw)
7070 | UnexpectedPort A.Region
7171 | NoPorts A.Region
72+ | NoPortsInPackage (A.Located Name.Name)
73+ | NoPortModulesInPackage A.Region
74+ | NoEffectsOutsideKernel A.Region
7275 | ParseError Module
7376
7477
@@ -517,7 +520,7 @@ toReport source err =
517520 ,
518521 D.stack
519522 [ D.reflow $
520− "I need it to match the file path, so I was expecting it to see `"
523+ "I need it to match the file path, so I was expecting to see `"
521524 ++ ModuleName.toChars expectedName
522525 ++ "` here. Make the following change, and you should be all set!"
523526 , D.indent 4 $
@@ -561,10 +564,84 @@ toReport source err =
561564 ]
562565 )
563566
567+ NoPortsInPackage (A.At region _) ->
568+ Report.Report "PACKAGES CANNOT HAVE PORTS" region [] $
569+ Code.toSnippet source region Nothing
570+ (
571+ D.reflow $
572+ "Packages cannot declare any ports, so I am getting stuck here:"
573+ ,
574+ D.stack
575+ [ D.reflow $
576+ "Remove this port declaration."
577+ , noteForPortsInPackage
578+ ]
579+ )
580+
581+ NoPortModulesInPackage region ->
582+ Report.Report "PACKAGES CANNOT HAVE PORTS" region [] $
583+ Code.toSnippet source region Nothing
584+ (
585+ D.reflow $
586+ "Packages cannot declare any ports, so I am getting stuck here:"
587+ ,
588+ D.stack
589+ [ D.fillSep $
590+ ["Remove","the",D.cyan "port","keyword","and","I"
591+ ,"should","be","able","to","continue."
592+ ]
593+ , noteForPortsInPackage
594+ ]
595+ )
596+
597+ NoEffectsOutsideKernel region ->
598+ Report.Report "INVALID EFFECT MODULE" region [] $
599+ Code.toSnippet source region Nothing
600+ (
601+ D.reflow $
602+ "It is not possible to declare an `effect module` outside the @elm organization,\
603+ \ so I am getting stuck here:"
604+ ,
605+ D.stack
606+ [ D.reflow $
607+ "Switch to a normal module declaration."
608+ , D.toSimpleNote $
609+ "Effect modules are designed to allow certain core functionality to be\
610+ \ defined separately from the compiler. So the @elm organization has access to\
611+ \ this so that certain changes, extensions, and fixes can be introduced without\
612+ \ needing to release new Elm binaries. For example, we want to make it possible\
613+ \ to test effects, but this may require changes to the design of effect modules.\
614+ \ By only having them defined in the @elm organization, that kind of design work\
615+ \ can proceed much more smoothly."
616+ ]
617+ )
618+
564619 ParseError modul ->
565620 toParseErrorReport source modul
566621
567622
623+noteForPortsInPackage :: D.Doc
624+noteForPortsInPackage =
625+ D.stack
626+ [ D.toSimpleNote $
627+ "One of the major goals of the package ecosystem is to be completely written\
628+ \ in Elm. This means when you install an Elm package, you can be sure you are safe\
629+ \ from security issues on install and that you are not going to get any runtime\
630+ \ exceptions coming from your new dependency. This design also sets the ecosystem\
631+ \ up to target other platforms more easily (like mobile phones, WebAssembly, etc.)\
632+ \ since no community code explicitly depends on JavaScript even existing."
633+ , D.reflow $
634+ "Given that overall goal, allowing ports in packages would lead to some pretty\
635+ \ surprising behavior. If ports were allowed in packages, you could install a\
636+ \ package but not realize that it brings in an indirect dependency that defines a\
637+ \ port. Now you have a program that does not work and the fix is to realize that\
638+ \ some JavaScript needs to be added for a dependency you did not even know about.\
639+ \ That would be extremely frustrating! \"So why not allow the package author to\
640+ \ include the necessary JS code as well?\" Now we are back in conflict with our\
641+ \ overall goal to keep all community packages free from runtime exceptions."
642+ ]
643+
644+
568645toParseErrorReport :: Code.Source -> Module -> Report.Report
569646toParseErrorReport source modul =
570647 case modul of
@@ -572,64 +649,9 @@ toParseErrorReport source modul =
572649 toSpaceReport source space row col
573650
574651 ModuleBadEnd row col ->
575− case Code.whatIsNext source row col of
576− Code.Keyword keyword ->
577− let
578− region = toKeywordRegion row col keyword
579− in
580− Report.Report "RESERVED WORD" region [] $
581− Code.toSnippet source region Nothing
582− (
583− D.reflow $
584− "I got stuck on this reserved word:"
585− ,
586− D.reflow $
587− "The name `" ++ keyword ++ "` is reserved, so try using a different name?"
588− )
589−
590− Code.Operator op ->
591− let
592− region = toKeywordRegion row col op
593− in
594− Report.Report "UNEXPECTED SYMBOL" region [] $
595− Code.toSnippet source region Nothing
596− (
597− D.reflow $
598− "I ran into an unexpected symbol:"
599− ,
600− D.reflow $
601− "I was not expecting to see a " ++ op ++ " here. Try deleting it? Maybe\
602− \ I can give a better hint from there?"
603− )
604−
605− Code.Close term bracket ->
606− let
607− region = toRegion row col
608− in
609− Report.Report ("UNEXPECTED " ++ map Char.toUpper term) region [] $
610− Code.toSnippet source region Nothing
611− (
612− D.reflow $
613− "I ran into an unexpected " ++ term ++ ":"
614− ,
615− D.reflow $
616− "This " ++ bracket : " does not match up with an earlier open " ++ term ++ ". Try deleting it?"
617− )
618−
619− Code.Other ->
620− let
621− region = toRegion row col
622− in
623− Report.Report "SYNTAX PROBLEM" region [] $
624− Code.toSnippet source region Nothing
625− (
626− D.reflow $
627− "I got stuck here:"
628− ,
629− D.reflow $
630− "Whatever I am running into is confusing me a lot! Normally I can give fairly\
631− \ specific hints, but something is really tripping me up this time."
632− )
652+ if col == 1
653+ then toDeclStartReport source row col
654+ else toWeirdEndReport source row col
633655
634656 ModuleProblem row col ->
635657 let
@@ -775,15 +797,15 @@ toParseErrorReport source modul =
775797 [ D.reflow $
776798 "I am not sure what is going on, but I recommend starting an Elm\
777799 \ file with the following lines:"
778− , D.vcat
800+ , D.indent 4 $ D.vcat $
779801 [ D.fillSep [D.cyan "import","Html"]
780802 , ""
781− , D.fillSep [D.green "main","="]
782− , D.indent 2 $ D.fillSep [D.cyan "Html" <> ".text",D.dullyellow "\"Hello!\""]
803+ , "main ="
804+ , " Html.text " <> D.dullyellow "\"Hello!\""
783805 ]
784806 , D.reflow $
785− "You should be able to copy those lines directly into your file. Check out\
786− \ some of the examples on https://elm-lang.org for more help getting started!"
807+ "You should be able to copy those lines directly into your file. Check out the\
808+ \ examples at <https://elm-lang.org/examples> for more help getting started!"
787809 , D.toSimpleNote $
788810 "This can also happen when something is indented too much!"
789811 ]
@@ -808,11 +830,12 @@ toParseErrorReport source modul =
808830 , D.indent 4 $ D.vcat $
809831 [ D.fillSep [D.cyan "import","Dict"]
810832 , D.fillSep [D.cyan "import","Maybe"]
811− , D.fillSep [D.cyan "import","Html.Attributes"]
812− , D.fillSep [D.cyan "import","Json.Decode"]
833+ , D.fillSep [D.cyan "import","Html.Attributes",D.cyan "as","A"]
834+ , D.fillSep [D.cyan "import","Json.Decode",D.cyan "exposing","(..)"]
813835 ]
814836 , D.reflow $
815837 "Notice that the module names all start with capital letters. That is required!"
838+ , D.reflowLink "Read" "imports" "to learn more."
816839 ]
817840 )
818841
@@ -823,7 +846,7 @@ toParseErrorReport source modul =
823846 let
824847 region = toRegion row col
825848 in
826− Report.Report "EXECTING IMPORT ALIAS" region [] $
849+ Report.Report "EXPECTING IMPORT ALIAS" region [] $
827850 Code.toSnippet source region Nothing
828851 (
829852 D.reflow $
@@ -839,6 +862,7 @@ toParseErrorReport source modul =
839862 ]
840863 , D.reflow $
841864 "Notice that the alias always starts with a capital letter. That is required!"
865+ , D.reflowLink "Read" "imports" "to learn more."
842866 ]
843867 )
844868
@@ -901,6 +925,192 @@ toParseErrorReport source modul =
901925
902926
903927
928+-- WEIRD END
929+
930+
931+toWeirdEndReport :: Code.Source -> Row -> Col -> Report.Report
932+toWeirdEndReport source row col =
933+ case Code.whatIsNext source row col of
934+ Code.Keyword keyword ->
935+ let
936+ region = toKeywordRegion row col keyword
937+ in
938+ Report.Report "RESERVED WORD" region [] $
939+ Code.toSnippet source region Nothing
940+ (
941+ D.reflow $
942+ "I got stuck on this reserved word:"
943+ ,
944+ D.reflow $
945+ "The name `" ++ keyword ++ "` is reserved, so try using a different name?"
946+ )
947+
948+ Code.Operator op ->
949+ let
950+ region = toKeywordRegion row col op
951+ in
952+ Report.Report "UNEXPECTED SYMBOL" region [] $
953+ Code.toSnippet source region Nothing
954+ (
955+ D.reflow $
956+ "I ran into an unexpected symbol:"
957+ ,
958+ D.reflow $
959+ "I was not expecting to see a " ++ op ++ " here. Try deleting it? Maybe\
960+ \ I can give a better hint from there?"
961+ )
962+
963+ Code.Close term bracket ->
964+ let
965+ region = toRegion row col
966+ in
967+ Report.Report ("UNEXPECTED " ++ map Char.toUpper term) region [] $
968+ Code.toSnippet source region Nothing
969+ (
970+ D.reflow $
971+ "I ran into an unexpected " ++ term ++ ":"
972+ ,
973+ D.reflow $
974+ "This " ++ bracket : " does not match up with an earlier open " ++ term ++ ". Try deleting it?"
975+ )
976+
977+ Code.Lower c cs ->
978+ let
979+ region = toKeywordRegion row col (c:cs)
980+ in
981+ Report.Report "UNEXPECTED NAME" region [] $
982+ Code.toSnippet source region Nothing
983+ (
984+ D.reflow $
985+ "I got stuck on this name:"
986+ ,
987+ D.reflow $
988+ "It is confusing me a lot! Normally I can give fairly specific hints, but\
989+ \ something is really tripping me up this time."
990+ )
991+
992+ Code.Upper c cs ->
993+ let
994+ region = toKeywordRegion row col (c:cs)
995+ in
996+ Report.Report "UNEXPECTED NAME" region [] $
997+ Code.toSnippet source region Nothing
998+ (
999+ D.reflow $
1000+ "I got stuck on this name:"
1001+ ,
1002+ D.reflow $
1003+ "It is confusing me a lot! Normally I can give fairly specific hints, but\
1004+ \ something is really tripping me up this time."
1005+ )
1006+
1007+ Code.Other maybeChar ->
1008+ let
1009+ region = toRegion row col
1010+ in
1011+ case maybeChar of
1012+ Just ';' ->
1013+ Report.Report "UNEXPECTED SEMICOLON" region [] $
1014+ Code.toSnippet source region Nothing
1015+ (
1016+ D.reflow $
1017+ "I got stuck on this semicolon:"
1018+ ,
1019+ D.stack
1020+ [ D.reflow $ "Try removing it?"
1021+ , D.toSimpleNote $
1022+ "Some languages require semicolons at the end of each statement. These are\
1023+ \ often called C-like languages, and they usually share a lot of language design\
1024+ \ choices. (E.g. side-effects, for loops, etc.) Elm manages effects with commands\
1025+ \ and subscriptions instead, so there is no special syntax for \"statements\" and\
1026+ \ therefore no need to use semicolons to separate them. I think this will make\
1027+ \ more sense as you work through <https://guide.elm-lang.org> though!"
1028+ ]
1029+ )
1030+
1031+ Just ',' ->
1032+ Report.Report "UNEXPECTED COMMA" region [] $
1033+ Code.toSnippet source region Nothing
1034+ (
1035+ D.reflow $
1036+ "I got stuck on this comma:"
1037+ ,
1038+ D.stack
1039+ [ D.reflow $
1040+ "I do not think I am parsing a list or tuple right now. Try deleting the comma?"
1041+ , D.toSimpleNote $
1042+ "If this is supposed to be part of a list, the problem may be a bit earlier.\
1043+ \ Perhaps the opening [ is missing? Or perhaps some value in the list has an extra\
1044+ \ closing ] that is making me think the list ended earlier? The same kinds of\
1045+ \ things could be going wrong if this is supposed to be a tuple."
1046+ ]
1047+ )
1048+
1049+ Just '`' ->
1050+ Report.Report "UNEXPECTED CHARACTER" region [] $
1051+ Code.toSnippet source region Nothing
1052+ (
1053+ D.reflow $
1054+ "I got stuck on this character:"
1055+ ,
1056+ D.stack
1057+ [ D.reflow $
1058+ "It is not used for anything in Elm syntax. It is used for multi-line strings in\
1059+ \ some languages though, so if you want a string that spans multiple lines, you\
1060+ \ can use Elm's multi-line string syntax like this:"
1061+ , D.dullyellow $ D.indent 4 $ D.vcat $
1062+ [ "\"\"\""
1063+ , "# Multi-line Strings"
1064+ , ""
1065+ , "- start with triple double quotes"
1066+ , "- write whatever you want"
1067+ , "- no need to escape newlines or double quotes"
1068+ , "- end with triple double quotes"
1069+ , "\"\"\""
1070+ ]
1071+ , D.reflow $
1072+ "Otherwise I do not know what is going on! Try removing the character?"
1073+ ]
1074+ )
1075+
1076+ Just '$' ->
1077+ Report.Report "UNEXPECTED SYMBOL" region [] $
1078+ Code.toSnippet source region Nothing
1079+ (
1080+ D.reflow $
1081+ "I got stuck on this dollar sign:"
1082+ ,
1083+ D.reflow $
1084+ "It is not used for anything in Elm syntax. Are you coming from a language where\
1085+ \ dollar signs can be used in variable names? If so, try a name that (1) starts\
1086+ \ with a letter and (2) only contains letters, numbers, and underscores."
1087+ )
1088+
1089+ Just c | elem c ['#','@','!','%','~'] ->
1090+ Report.Report "UNEXPECTED SYMBOL" region [] $
1091+ Code.toSnippet source region Nothing
1092+ (
1093+ D.reflow $
1094+ "I got stuck on this symbol:"
1095+ ,
1096+ D.reflow $
1097+ "It is not used for anything in Elm syntax. Try removing it?"
1098+ )
1099+
1100+ _ ->
1101+ Report.Report "SYNTAX PROBLEM" region [] $
1102+ Code.toSnippet source region Nothing
1103+ (
1104+ D.reflow $
1105+ "I got stuck here:"
1106+ ,
1107+ D.reflow $
1108+ "Whatever I am running into is confusing me a lot! Normally I can give fairly\
1109+ \ specific hints, but something is really tripping me up this time."
1110+ )
1111+
1112+
1113+
9041114-- IMPORTS
9051115
9061116
@@ -926,6 +1136,7 @@ toImportReport source row col =
9261136 ]
9271137 , D.reflow $
9281138 "You are probably trying to import a different module, but try to make it look like one of these examples!"
1139+ , D.reflowLink "Read" "imports" "to learn more."
9291140 ]
9301141 )
9311142
@@ -1232,106 +1443,7 @@ toDeclarationsReport :: Code.Source -> Decl -> Report.Report
12321443toDeclarationsReport source decl =
12331444 case decl of
12341445 DeclStart row col ->
1235− case Code.whatIsNext source row col of
1236− Code.Close term bracket ->
1237− let
1238− region = toRegion row col
1239− in
1240− Report.Report ("STRAY " ++ map Char.toUpper term) region [] $
1241− Code.toSnippet source region Nothing
1242− (
1243− D.reflow $
1244− "I was not expecting to see a " ++ term ++ " here:"
1245− , D.reflow $
1246− "This " ++ bracket : " does not match up with an earlier open " ++ term ++ ". Try deleting it?"
1247− )
1248−
1249− Code.Keyword keyword ->
1250− let
1251− region = toKeywordRegion row col keyword
1252− in
1253− Report.Report "RESERVED WORD" region [] $
1254− Code.toSnippet source region Nothing
1255− (
1256− D.reflow $
1257− "I was not expecting to run into the `" ++ keyword ++ "` keyword here:"
1258− ,
1259− case keyword of
1260− "import" ->
1261− D.reflow $
1262− "It is reserved for declaring imports at the top of your module. If you want\
1263− \ another import, try moving it up top with the other imports. If you want to\
1264− \ define a value or function, try changing the name to something else!"
1265−
1266− "case" ->
1267− D.stack
1268− [ D.reflow $
1269− "It is reserved for writing `case` expressions. Try using a different name?"
1270− , D.toSimpleNote $
1271− "If you are trying to write a `case` expression, it needs to be part of a\
1272− \ definition. So you could write something like this instead:"
1273− , D.vcat $
1274− [ D.indent 0 $ D.fillSep [D.green "getWidth","maybeWidth","="]
1275− , D.indent 2 $ D.fillSep [D.cyan "case","maybeWidth",D.cyan "of"]
1276− , D.indent 4 $ D.fillSep [D.blue "Just","width","->"]
1277− , D.indent 6 $ D.fillSep ["width","+",D.dullyellow "200"]
1278− , ""
1279− , D.indent 4 $ D.fillSep [D.blue "Nothing","->"]
1280− , D.indent 6 $ D.fillSep [D.dullyellow "400"]
1281− ]
1282− , D.reflow $
1283− "This defines a `getWidth` function that we can use elsewhere in our program."
1284− ]
1285−
1286− "if" ->
1287− D.stack
1288− [ D.reflow $
1289− "It is reserved for writing `if` expressions. Try using a different name?"
1290− , D.toSimpleNote $
1291− "If you are trying to write an `if` expression, it needs to be part of a\
1292− \ definition. So you could write something like this instead:"
1293− , D.vcat $
1294− [ D.indent 0 $ D.fillSep [D.green "reviewPowerLevel","powerLevel","="]
1295− , D.indent 2 $ D.fillSep $
1296− [D.cyan "if","powerLevel",">",D.dullyellow "9000"
1297− ,D.cyan "then",D.dullyellow "\"OVER 9000!!!\""
1298− ,D.cyan "else",D.dullyellow "\"not bad\""
1299− ]
1300− ]
1301− , D.reflow $
1302− "This defines a `reviewPowerLevel` function that we can use elsewhere in our program."
1303− ]
1304−
1305− _ ->
1306− D.reflow $
1307− "It is a reserved word. Try changing the name to something else?"
1308− )
1309−
1310− _ ->
1311− let
1312− region = toRegion row col
1313− in
1314− Report.Report "SYNTAX PROBLEM" region [] $
1315− Code.toSnippet source region Nothing
1316− (
1317− D.reflow $
1318− "I was expecting to see a new declaration here:"
1319− ,
1320− D.stack
1321− [ D.reflow $
1322− "I am not sure what is going wrong exactly, but here are a couple valid\
1323− \ declarations for reference:"
1324− , D.vcat
1325− [ D.fillSep [D.green "add",":","Int","->","Int","->","Int"]
1326− , D.fillSep [D.green "add","x","y","="]
1327− , D.fillSep [" ","x","+","y"]
1328− ]
1329− , D.fillSep [D.cyan "type",D.green "User","=","Anonymous","|","LoggedIn String"]
1330− , D.reflow $
1331− "Note that all declarations start with lower-case letters in Elm. Capitalization\
1332− \ makes a difference, so be consious of that if you are working from examples!"
1333− ]
1334− )
1446+ toDeclStartReport source row col
13351447
13361448 DeclSpace space row col ->
13371449 toSpaceReport source space row col
@@ -1361,6 +1473,165 @@ toDeclarationsReport source decl =
13611473 )
13621474
13631475
1476+toDeclStartReport :: Code.Source -> Row -> Col -> Report.Report
1477+toDeclStartReport source row col =
1478+ case Code.whatIsNext source row col of
1479+ Code.Close term bracket ->
1480+ let
1481+ region = toRegion row col
1482+ in
1483+ Report.Report ("STRAY " ++ map Char.toUpper term) region [] $
1484+ Code.toSnippet source region Nothing
1485+ (
1486+ D.reflow $
1487+ "I was not expecting to see a " ++ term ++ " here:"
1488+ , D.reflow $
1489+ "This " ++ bracket : " does not match up with an earlier open " ++ term ++ ". Try deleting it?"
1490+ )
1491+
1492+ Code.Keyword keyword ->
1493+ let
1494+ region = toKeywordRegion row col keyword
1495+ in
1496+ Report.Report "RESERVED WORD" region [] $
1497+ Code.toSnippet source region Nothing
1498+ (
1499+ D.reflow $
1500+ "I was not expecting to run into the `" ++ keyword ++ "` keyword here:"
1501+ ,
1502+ case keyword of
1503+ "import" ->
1504+ D.reflow $
1505+ "It is reserved for declaring imports at the top of your module. If you want\
1506+ \ another import, try moving it up top with the other imports. If you want to\
1507+ \ define a value or function, try changing the name to something else!"
1508+
1509+ "case" ->
1510+ D.stack
1511+ [ D.reflow $
1512+ "It is reserved for writing `case` expressions. Try using a different name?"
1513+ , D.toSimpleNote $
1514+ "If you are trying to write a `case` expression, it needs to be part of a\
1515+ \ definition. So you could write something like this instead:"
1516+ , D.indent 4 $ D.vcat $
1517+ [ D.indent 0 $ D.fillSep ["getWidth","maybeWidth","="]
1518+ , D.indent 2 $ D.fillSep [D.cyan "case","maybeWidth",D.cyan "of"]
1519+ , D.indent 4 $ D.fillSep [D.blue "Just","width","->"]
1520+ , D.indent 6 $ D.fillSep ["width","+",D.dullyellow "200"]
1521+ , ""
1522+ , D.indent 4 $ D.fillSep [D.blue "Nothing","->"]
1523+ , D.indent 6 $ D.fillSep [D.dullyellow "400"]
1524+ ]
1525+ , D.reflow $
1526+ "This defines a `getWidth` function that you can use elsewhere in your program."
1527+ ]
1528+
1529+ "if" ->
1530+ D.stack
1531+ [ D.reflow $
1532+ "It is reserved for writing `if` expressions. Try using a different name?"
1533+ , D.toSimpleNote $
1534+ "If you are trying to write an `if` expression, it needs to be part of a\
1535+ \ definition. So you could write something like this instead:"
1536+ , D.indent 4 $ D.vcat $
1537+ [ "greet name ="
1538+ , D.fillSep $
1539+ [" "
1540+ ,D.cyan "if","name","==",D.dullyellow "\"Abraham Lincoln\""
1541+ ,D.cyan "then",D.dullyellow "\"Greetings Mr. President.\""
1542+ ,D.cyan "else",D.dullyellow "\"Hey!\""
1543+ ]
1544+ ]
1545+ , D.reflow $
1546+ "This defines a `reviewPowerLevel` function that you can use elsewhere in your program."
1547+ ]
1548+
1549+ _ ->
1550+ D.reflow $
1551+ "It is a reserved word. Try changing the name to something else?"
1552+ )
1553+
1554+ Code.Upper c cs ->
1555+ let
1556+ region = toRegion row col
1557+ in
1558+ Report.Report "UNEXPECTED CAPITAL LETTER" region [] $
1559+ Code.toSnippet source region Nothing
1560+ (
1561+ D.reflow $
1562+ "Declarations always start with a lower-case letter, so I am getting stuck here:"
1563+ ,
1564+ D.stack
1565+ [ D.fillSep $
1566+ ["Try","a","name","like"
1567+ ,D.green (D.fromChars (Char.toLower c : cs))
1568+ ,"instead?"
1569+ ]
1570+ , D.toSimpleNote $
1571+ "Here are a couple valid declarations for reference:"
1572+ , D.indent 4 $ D.vcat $
1573+ [ "greet : String -> String"
1574+ , "greet name ="
1575+ , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
1576+ , ""
1577+ , D.cyan "type" <> " User = Anonymous | LoggedIn String"
1578+ ]
1579+ , D.reflow $
1580+ "Notice that they always start with a lower-case letter. Capitalization matters!"
1581+ ]
1582+ )
1583+
1584+ Code.Other (Just char) | elem char ['(', '{', '[', '+', '-', '*', '/', '^', '&', '|', '"', '\'', '!', '@', '#', '$', '%'] ->
1585+ let
1586+ region = toRegion row col
1587+ in
1588+ Report.Report "UNEXPECTED SYMBOL" region [] $
1589+ Code.toSnippet source region Nothing
1590+ (
1591+ D.reflow $
1592+ "I am getting stuck because this line starts with the " ++ [char] ++ " symbol:"
1593+ ,
1594+ D.stack
1595+ [ D.reflow $
1596+ "When a line has no spaces at the beginning, I expect it to be a declaration like one of these:"
1597+ , D.indent 4 $ D.vcat $
1598+ [ "greet : String -> String"
1599+ , "greet name ="
1600+ , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
1601+ , ""
1602+ , D.cyan "type" <> " User = Anonymous | LoggedIn String"
1603+ ]
1604+ , D.reflow $
1605+ "If this is not supposed to be a declaration, try adding some spaces before it?"
1606+ ]
1607+ )
1608+
1609+ _ ->
1610+ let
1611+ region = toRegion row col
1612+ in
1613+ Report.Report "WEIRD DECLARATION" region [] $
1614+ Code.toSnippet source region Nothing
1615+ (
1616+ D.reflow $
1617+ "I am trying to parse a declaration, but I am getting stuck here:"
1618+ ,
1619+ D.stack
1620+ [ D.reflow $
1621+ "When a line has no spaces at the beginning, I expect it to be a declaration like one of these:"
1622+ , D.indent 4 $ D.vcat $
1623+ [ "greet : String -> String"
1624+ , "greet name ="
1625+ , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
1626+ , ""
1627+ , D.cyan "type" <> " User = Anonymous | LoggedIn String"
1628+ ]
1629+ , D.reflow $
1630+ "Try to make your declaration look like one of those? Or if this is not\
1631+ \ supposed to be a declaration, try adding some spaces before it?"
1632+ ]
1633+ )
1634+
13641635
13651636-- PORT
13661637
@@ -1487,7 +1758,7 @@ toPortReport source port_ startRow startCol =
14871758 [ D.reflow $
14881759 "I was expecting to see a type next. Here are examples of outgoing and\
14891760 \ incoming ports for reference:"
1490− , D.vcat
1761+ , D.indent 4 $ D.vcat $
14911762 [ D.fillSep [D.cyan "port","send",":","String -> Cmd msg"]
14921763 , D.fillSep [D.cyan "port","receive",":","(String -> msg) -> Sub msg"]
14931764 ]
@@ -1506,7 +1777,7 @@ portNote =
15061777 D.stack
15071778 [ D.toSimpleNote $
15081779 "Here are some example `port` declarations for reference:"
1509− , D.vcat
1780+ , D.indent 4 $ D.vcat $
15101781 [ D.fillSep [D.cyan "port","send",":","String -> Cmd msg"]
15111782 , D.fillSep [D.cyan "port","receive",":","(String -> msg) -> Sub msg"]
15121783 ]
@@ -1636,7 +1907,7 @@ toTypeAliasReport source typeAlias startRow startCol =
16361907 ,
16371908 D.stack
16381909 [ D.reflow $
1639− "I was expecting to see a type variable or an an equals sign next."
1910+ "I was expecting to see a type variable or an equals sign next."
16401911 , typeAliasNote
16411912 ]
16421913 )
@@ -1657,7 +1928,7 @@ toTypeAliasReport source typeAlias startRow startCol =
16571928 ,
16581929 D.stack
16591930 [ D.reflow $
1660− "I was expecting to see a type variable or an an equals sign next."
1931+ "I was expecting to see a type variable or an equals sign next."
16611932 , typeAliasNote
16621933 ]
16631934 )
@@ -1689,8 +1960,8 @@ typeAliasNote =
16891960 [ D.toSimpleNote $
16901961 "Here is an example of a valid `type alias` for reference:"
16911962 , D.vcat $
1692− [ D.indent 0 $ D.fillSep [D.cyan "type",D.cyan "alias",D.green "Person","="]
1693− , D.indent 2 $ D.vcat $
1963+ [ D.indent 4 $ D.fillSep [D.cyan "type",D.cyan "alias","Person","="]
1964+ , D.indent 6 $ D.vcat $
16941965 ["{ name : String"
16951966 ,", age : Int"
16961967 ,", height : Float"
@@ -1764,7 +2035,7 @@ toCustomTypeReport source customType startRow startCol =
17642035 ,
17652036 D.stack
17662037 [ D.reflow $
1767− "I was expecting to see a type variable or an an equals sign next."
2038+ "I was expecting to see a type variable or an equals sign next."
17682039 , customTypeNote
17692040 ]
17702041 )
@@ -1824,7 +2095,7 @@ toCustomTypeReport source customType startRow startCol =
18242095 ,
18252096 D.stack
18262097 [ D.reflow $
1827− "I was expecting to see a type variable or an an equals sign next."
2098+ "I was expecting to see a type variable or an equals sign next."
18282099 , customTypeNote
18292100 ]
18302101 )
@@ -1890,10 +2161,10 @@ customTypeNote =
18902161 [ D.toSimpleNote $
18912162 "Here is an example of a valid `type` declaration for reference:"
18922163 , D.vcat $
1893− [ D.indent 0 $ D.fillSep [D.cyan "type",D.green "Status"]
1894− , D.indent 2 $ D.fillSep ["=","Failure"]
1895− , D.indent 2 $ D.fillSep ["|","Waiting"]
1896− , D.indent 2 $ D.fillSep ["|","Success","String"]
2164+ [ D.indent 4 $ D.fillSep [D.cyan "type","Status"]
2165+ , D.indent 6 $ D.fillSep ["=","Failure"]
2166+ , D.indent 6 $ D.fillSep ["|","Waiting"]
2167+ , D.indent 6 $ D.fillSep ["|","Success","String"]
18972168 ]
18982169 , D.reflow $
18992170 "This defines a new `Status` type with three variants. This could be useful if\
@@ -1924,11 +2195,55 @@ toDeclDefReport source name declDef startRow startCol =
19242195 Report.Report "RESERVED WORD" region [] $
19252196 Code.toSnippet source surroundings (Just region)
19262197 (
1927− D.reflow $
1928− "It looks like you are trying to use `" ++ keyword ++ "` as an argument:"
2198+ D.fillSep
2199+ ["The","name"
2200+ ,"`" <> D.cyan (D.fromChars keyword) <> "`"
2201+ ,"is","reserved","in","Elm,","so","it","cannot"
2202+ ,"be","used","as","an","argument","here:"
2203+ ]
19292204 ,
2205+ D.stack
2206+ [ D.reflow $
2207+ "Try renaming it to something else."
2208+ , case keyword of
2209+ "as" ->
2210+ D.toFancyNote
2211+ ["This","keyword","is","reserved","for","pattern","matches","like"
2212+ ,"((x,y)",D.cyan "as","point)","where","you","want","to","name","a","tuple","and"
2213+ ,"the","values","it","contains."
2214+ ]
2215+
2216+ _ ->
2217+ D.toSimpleNote $
2218+ "The `" ++ keyword ++ "` keyword has a special meaning in Elm, so it can only be used in certain situations."
2219+ ]
2220+ )
2221+
2222+ Code.Operator "->" ->
2223+ let
2224+ surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
2225+ region = toWiderRegion row col 2
2226+ in
2227+ Report.Report "MISSING COLON?" region [] $
2228+ Code.toSnippet source surroundings (Just region)
2229+ (
19302230 D.reflow $
1931− "This is a reserved word! Try using some other name?"
2231+ "I was not expecting to see an arrow here:"
2232+ ,
2233+ D.stack
2234+ [ D.fillSep
2235+ ["This","usually","means","a",D.green ":","is","missing","a","bit","earlier","in"
2236+ ,"a","type","annotation.","It","could","be","something","else","though,","so"
2237+ ,"here","is","a","valid","definition","for","reference:"
2238+ ]
2239+ , D.indent 4 $ D.vcat $
2240+ [ "greet : String -> String"
2241+ , "greet name ="
2242+ , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
2243+ ]
2244+ , D.reflow $
2245+ "Try to use that format with your `" ++ Name.toChars name ++ "` definition!"
2246+ ]
19322247 )
19332248
19342249 Code.Operator op ->
@@ -1946,10 +2261,10 @@ toDeclDefReport source name declDef startRow startCol =
19462261 [ D.reflow $
19472262 "I am not sure what is going wrong exactly, so here is a valid\
19482263 \ definition (with an optional type annotation) for reference:"
1949− , D.vcat
1950− [ D.fillSep [D.green "add",":","Int","->","Int","->","Int"]
1951− , D.fillSep [D.green "add","x","y","="]
1952− , D.fillSep [" ","x","+","y"]
2264+ , D.indent 4 $ D.vcat $
2265+ [ "greet : String -> String"
2266+ , "greet name ="
2267+ , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
19532268 ]
19542269 , D.reflow $
19552270 "Try to use that format with your `" ++ Name.toChars name ++ "` definition!"
@@ -1971,10 +2286,10 @@ toDeclDefReport source name declDef startRow startCol =
19712286 [ D.reflow $
19722287 "I am not sure what is going wrong exactly, so here is a valid\
19732288 \ definition (with an optional type annotation) for reference:"
1974− , D.vcat
1975− [ D.fillSep [D.green "add",":","Int","->","Int","->","Int"]
1976− , D.fillSep [D.green "add","x","y","="]
1977− , D.fillSep [" ","x","+","y"]
2289+ , D.indent 4 $ D.vcat $
2290+ [ "greet : String -> String"
2291+ , "greet name ="
2292+ , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
19782293 ]
19792294 , D.reflow $
19802295 "Try to use that format!"
@@ -2089,10 +2404,10 @@ declDefNote =
20892404 D.stack
20902405 [ D.reflow $
20912406 "Here is a valid definition (with a type annotation) for reference:"
2092− , D.vcat
2093− [ D.fillSep [D.green "add",":","Int","->","Int","->","Int"]
2094− , D.fillSep [D.green "add","x","y","="]
2095− , D.fillSep [" ","x","+","y"]
2407+ , D.indent 4 $ D.vcat $
2408+ [ "greet : String -> String"
2409+ , "greet name ="
2410+ , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
20962411 ]
20972412 , D.reflow $
20982413 "The top line (called a \"type annotation\") is optional. You can leave it off\
@@ -2204,25 +2519,40 @@ toExprReport source context expr startRow startCol =
22042519 )
22052520
22062521 OperatorRight op row col ->
2207− let region = toRegion row col in
2522+ let
2523+ surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
2524+ region = toRegion row col
2525+ isMath = elem op ["-","+","*","/","^"]
2526+ in
22082527 Report.Report "MISSING EXPRESSION" region [] $
2209− Code.toSnippet source region Nothing
2528+ Code.toSnippet source surroundings (Just region)
22102529 (
22112530 D.reflow $
2212− "I was expecting to see an expression after this " ++ Name.toChars op ++ " operator:"
2531+ "I just saw a " ++ Name.toChars op ++ " "
2532+ ++ (if isMath then "sign" else "operator")
2533+ ++ ", so I am getting stuck here:"
22132534 ,
2214− D.stack
2215− [ D.fillSep $
2216− ["You","can","just","put","anything","for","now,","like"
2217− ,D.dullyellow "42","or",D.dullyellow"\"hello\"" <> "."
2218− ,"Once","there","is","something","there,","I","can","probably"
2219− ,"give","a","more","specific","hint!"
2220− ]
2221− , D.toSimpleNote $
2222− "This can also happen if run into reserved words like `let` or `as` unexpectedly.\
2223− \ Or if I run into operators in unexpected spots. Point is, there are a\
2224− \ couple ways I can get confused and give sort of weird advice!"
2225− ]
2535+ if isMath then
2536+ D.fillSep
2537+ ["I","was","expecting","to","see","an","expression","next."
2538+ ,"Something","like",D.dullyellow "42","or",D.dullyellow "1000"
2539+ ,"that","makes","sense","with","a",D.fromName op,"sign."
2540+ ]
2541+ else if op == "&&" || op == "||" then
2542+ D.fillSep
2543+ ["I","was","expecting","to","see","an","expression","next."
2544+ ,"Something","like",D.dullyellow "True","or",D.dullyellow "False"
2545+ ,"that","makes","sense","with","boolean","logic."
2546+ ]
2547+ else if op == "|>" then
2548+ D.reflow $
2549+ "I was expecting to see a function next."
2550+ else if op == "<|" then
2551+ D.reflow $
2552+ "I was expecting to see an argument next."
2553+ else
2554+ D.reflow $
2555+ "I was expecting to see an expression next."
22262556 )
22272557
22282558 OperatorReserved operator row col ->
@@ -2243,7 +2573,6 @@ toExprReport source context expr startRow startCol =
22432573 InNode NElse r c _ -> (r, c, "an `if` expression")
22442574 InNode NCase r c _ -> (r, c, "a `case` expression")
22452575 InNode NBranch r c _ -> (r, c, "a `case` expression")
2246− -- TODO check if this is actually the best way to get error messages here
22472576
22482577 surroundings = A.Region (A.Position contextRow contextCol) (A.Position row col)
22492578 region = toRegion row col
@@ -2262,7 +2591,7 @@ toExprReport source context expr startRow startCol =
22622591 ,"give","a","more","specific","hint!"
22632592 ]
22642593 , D.toSimpleNote $
2265− "This can also happen if run into reserved words like `let` or `as` unexpectedly.\
2594+ "This can also happen if I run into reserved words like `let` or `as` unexpectedly.\
22662595 \ Or if I run into operators in unexpected spots. Point is, there are a\
22672596 \ couple ways I can get confused and give sort of weird advice!"
22682597 ]
@@ -2408,7 +2737,19 @@ toStringReport source string row col =
24082737 ,"quotes","on","each","end.","Is","the","closing","double"
24092738 ,"quote","missing","in","your","code?"
24102739 ]
2411− , D.link "Note" "Read" "TODO" "if you want a string that spans multiple lines."
2740+ , D.toSimpleNote $
2741+ "For a string that spans multiple lines, you can use the multi-line string\
2742+ \ syntax like this:"
2743+ , D.dullyellow $ D.indent 4 $ D.vcat $
2744+ [ "\"\"\""
2745+ , "# Multi-line Strings"
2746+ , ""
2747+ , "- start with triple double quotes"
2748+ , "- write whatever you want"
2749+ , "- no need to escape newlines or double quotes"
2750+ , "- end with triple double quotes"
2751+ , "\"\"\""
2752+ ]
24122753 ]
24132754 )
24142755
@@ -2424,7 +2765,18 @@ toStringReport source string row col =
24242765 ,
24252766 D.stack
24262767 [ D.reflow "Add a \"\"\" somewhere after this to end the string."
2427− , D.link "Hint" "Read" "TODO" "for more information on strings and multi-line strings."
2768+ , D.toSimpleNote $
2769+ "Here is a valid multi-line string for reference:"
2770+ , D.dullyellow $ D.indent 4 $ D.vcat $
2771+ [ "\"\"\""
2772+ , "# Multi-line Strings"
2773+ , ""
2774+ , "- start with triple double quotes"
2775+ , "- write whatever you want"
2776+ , "- no need to escape newlines or double quotes"
2777+ , "- end with triple double quotes"
2778+ , "\"\"\""
2779+ ]
24282780 ]
24292781 )
24302782
@@ -2657,33 +3009,41 @@ toOperatorReport source context operator row col =
26573009 in
26583010 Report.Report "UNEXPECTED ARROW" region [] $
26593011 Code.toSnippet source region Nothing $
2660− if isWithin NBranch context then
3012+ if isWithin NCase context then
26613013 (
26623014 D.reflow $
2663− "I was not expecting to see an arrow here:"
3015+ "I am parsing a `case` expression right now, but this arrow is confusing me:"
26643016 ,
26653017 D.stack
2666− [
2667− D.reflow $
2668− "I think I am parsing a `case` expression right now, so it makes sense to\
2669− \ see arrows around here. This one is confusing me though!"
2670− ,
2671− D.toSimpleHint $
2672− "I may be getting confused by the indentation. Every pattern in a `case` must be\
2673− \ exactly aligned (with exactly the same amount of indentation) so maybe this arrow\
2674− \ appears after the next `case` pattern (correctly!) but the pattern itself is\
2675− \ indented too far?"
3018+ [ D.reflow "Maybe the `of` keyword is missing on a previous line?"
3019+ , noteForCaseError
26763020 ]
26773021 )
26783022
2679− else
3023+ else if isWithin NBranch context then
26803024 (
26813025 D.reflow $
2682− "I was not expecting an arrow here:"
3026+ "I am parsing a `case` expression right now, but this arrow is confusing me:"
26833027 ,
3028+ D.stack
3029+ [ D.reflow $
3030+ "It makes sense to see arrows around here, so I suspect it is something earlier. Maybe this pattern is indented a bit farther than the previous patterns?"
3031+ , noteForCaseIndentError
3032+ ]
3033+ )
3034+
3035+ else
3036+ (
26843037 D.reflow $
2685− "Arrows should only appear in `case` expressions and anonymous functions. Maybe\
2686− \ you want > or >= instead?"
3038+ "I was partway through parsing an expression when I got stuck on this arrow:"
3039+ ,
3040+ D.stack
3041+ [ "Arrows should only appear in `case` expressions and anonymous functions.\n\
3042+ \Maybe it was supposed to be a > sign instead?"
3043+ , D.toSimpleNote $
3044+ "The syntax for anonymous functions is (\\x -> x + 1) so the arguments all appear\
3045+ \ after the backslash and before the arrow. Maybe a backslash is missing earlier?"
3046+ ]
26873047 )
26883048
26893049 BadEquals ->
@@ -2810,7 +3170,7 @@ toLetReport source context let_ startRow startCol =
28103170 , D.toSimpleNote $
28113171 "This can also happen if you are trying to define another value within the `let` but\
28123172 \ it is not indented enough. Make sure each definition has exactly the same amount of\
2813− \ spaces before it. The should line up exactly!"
3173+ \ spaces before it. They should line up exactly!"
28143174 ]
28153175 )
28163176
@@ -2880,8 +3240,8 @@ toUnfinishLetReport source row col startRow startCol message =
28803240 [ message
28813241 , D.toSimpleNote $
28823242 "Here is an example with a valid `let` expression for reference:"
2883− , D.vcat $
2884− [ D.indent 0 $ D.fillSep [D.green "viewPerson","person","="]
3243+ , D.indent 4 $ D.vcat $
3244+ [ D.indent 0 $ D.fillSep ["viewPerson","person","="]
28853245 , D.indent 2 $ D.fillSep [D.cyan "let"]
28863246 , D.indent 4 $ D.fillSep ["fullName","="]
28873247 , D.indent 6 $ D.fillSep ["person.firstName","++",D.dullyellow "\" \"","++","person.lastName"]
@@ -2958,11 +3318,55 @@ toLetDefReport source name def startRow startCol =
29583318 Report.Report "RESERVED WORD" region [] $
29593319 Code.toSnippet source surroundings (Just region)
29603320 (
2961− D.reflow $
2962− "It looks like you are trying to use `" ++ keyword ++ "` as an argument:"
3321+ D.fillSep
3322+ ["The","name"
3323+ ,"`" <> D.cyan (D.fromChars keyword) <> "`"
3324+ ,"is","reserved","in","Elm,","so","it","cannot"
3325+ ,"be","used","as","an","argument","here:"
3326+ ]
29633327 ,
3328+ D.stack
3329+ [ D.reflow $
3330+ "Try renaming it to something else."
3331+ , case keyword of
3332+ "as" ->
3333+ D.toFancyNote
3334+ ["This","keyword","is","reserved","for","pattern","matches","like"
3335+ ,"((x,y)",D.cyan "as","point)","where","you","want","to","name","a","tuple","and"
3336+ ,"the","values","it","contains."
3337+ ]
3338+
3339+ _ ->
3340+ D.toSimpleNote $
3341+ "The `" ++ keyword ++ "` keyword has a special meaning in Elm, so it can only be used in certain situations."
3342+ ]
3343+ )
3344+
3345+ Code.Operator "->" ->
3346+ let
3347+ surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
3348+ region = toWiderRegion row col 2
3349+ in
3350+ Report.Report "MISSING COLON?" region [] $
3351+ Code.toSnippet source surroundings (Just region)
3352+ (
29643353 D.reflow $
2965− "This is a reserved word! Try using some other name?"
3354+ "I was not expecting to see an arrow here:"
3355+ ,
3356+ D.stack
3357+ [ D.fillSep
3358+ ["This","usually","means","a",D.green ":","is","missing","a","bit","earlier","in"
3359+ ,"a","type","annotation.","It","could","be","something","else","though,","so"
3360+ ,"here","is","a","valid","definition","for","reference:"
3361+ ]
3362+ , D.indent 4 $ D.vcat $
3363+ [ "greet : String -> String"
3364+ , "greet name ="
3365+ , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
3366+ ]
3367+ , D.reflow $
3368+ "Try to use that format with your `" ++ Name.toChars name ++ "` definition!"
3369+ ]
29663370 )
29673371
29683372 Code.Operator op ->
@@ -2980,10 +3384,10 @@ toLetDefReport source name def startRow startCol =
29803384 [ D.reflow $
29813385 "I am not sure what is going wrong exactly, so here is a valid\
29823386 \ definition (with an optional type annotation) for reference:"
2983− , D.vcat
2984− [ D.indent 4 $ D.fillSep [D.green "add",":","Int","->","Int","->","Int"]
2985− , D.indent 4 $ D.fillSep [D.green "add","x","y","="]
2986− , D.indent 6 $ D.fillSep ["x","+","y"]
3387+ , D.indent 4 $ D.vcat $
3388+ [ "greet : String -> String"
3389+ , "greet name ="
3390+ , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
29873391 ]
29883392 , D.reflow $
29893393 "Try to use that format with your `" ++ Name.toChars name ++ "` definition!"
@@ -3005,10 +3409,10 @@ toLetDefReport source name def startRow startCol =
30053409 [ D.reflow $
30063410 "I am not sure what is going wrong exactly, so here is a valid\
30073411 \ definition (with an optional type annotation) for reference:"
3008− , D.vcat
3009− [ D.indent 4 $ D.fillSep [D.green "add",":","Int","->","Int","->","Int"]
3010− , D.indent 4 $ D.fillSep [D.green "add","x","y","="]
3011− , D.indent 4 $ D.fillSep ["x","+","y"]
3412+ , D.indent 4 $ D.vcat $
3413+ [ "greet : String -> String"
3414+ , "greet name ="
3415+ , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
30123416 ]
30133417 , D.reflow $
30143418 "Try to use that format!"
@@ -3098,10 +3502,10 @@ defNote =
30983502 D.stack
30993503 [ D.reflow $
31003504 "Here is a valid definition (with a type annotation) for reference:"
3101− , D.vcat
3102− [ D.indent 4 $ D.fillSep [D.green "add",":","Int","->","Int","->","Int"]
3103− , D.indent 4 $ D.fillSep [D.green "add","x","y","="]
3104− , D.indent 6 $ D.fillSep ["x","+","y"]
3505+ , D.indent 4 $ D.vcat $
3506+ [ "greet : String -> String"
3507+ , "greet name ="
3508+ , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
31053509 ]
31063510 , D.reflow $
31073511 "The top line (called a \"type annotation\") is optional. You can leave it off\
@@ -3264,9 +3668,10 @@ toCaseReport source context case_ startRow startCol =
32643668 D.reflow $
32653669 "I am partway through parsing a `case` expression, but I got stuck here:"
32663670 ,
3267− addNoteForCaseIndentError $
3268− D.reflow $
3269− "I was expecting to see an arrow next."
3671+ D.stack
3672+ [ D.reflow "I was expecting to see an arrow next."
3673+ , noteForCaseIndentError
3674+ ]
32703675 )
32713676
32723677 CaseExpr expr row col ->
@@ -3320,28 +3725,33 @@ toUnfinishCaseReport source row col startRow startCol message =
33203725 ,
33213726 D.stack
33223727 [ message
3323− , D.toSimpleNote $
3324− "Here is an example of a valid `case` expression for reference."
3325− , D.vcat $
3326− [ D.indent 4 $ D.fillSep [D.cyan "case","maybeWidth",D.cyan "of"]
3327− , D.indent 6 $ D.fillSep [D.blue "Just","width","->"]
3328− , D.indent 8 $ D.fillSep ["width","+",D.dullyellow "200"]
3329− , ""
3330− , D.indent 6 $ D.fillSep [D.blue "Nothing","->"]
3331− , D.indent 8 $ D.fillSep [D.dullyellow "400"]
3332− ]
3333− , D.reflow $
3334− "Notice the indentation. Each pattern is aligned, and each branch is indented\
3335− \ a bit more than the corresponding pattern. That is important!"
3728+ , noteForCaseError
33363729 ]
33373730 )
33383731
33393732
3340−addNoteForCaseIndentError :: D.Doc -> D.Doc
3341−addNoteForCaseIndentError message =
3342− D.stack $
3343− message
3344− :
3733+noteForCaseError :: D.Doc
3734+noteForCaseError =
3735+ D.stack
3736+ [ D.toSimpleNote $
3737+ "Here is an example of a valid `case` expression for reference."
3738+ , D.vcat $
3739+ [ D.indent 4 $ D.fillSep [D.cyan "case","maybeWidth",D.cyan "of"]
3740+ , D.indent 6 $ D.fillSep [D.blue "Just","width","->"]
3741+ , D.indent 8 $ D.fillSep ["width","+",D.dullyellow "200"]
3742+ , ""
3743+ , D.indent 6 $ D.fillSep [D.blue "Nothing","->"]
3744+ , D.indent 8 $ D.fillSep [D.dullyellow "400"]
3745+ ]
3746+ , D.reflow $
3747+ "Notice the indentation. Each pattern is aligned, and each branch is indented\
3748+ \ a bit more than the corresponding pattern. That is important!"
3749+ ]
3750+
3751+
3752+noteForCaseIndentError :: D.Doc
3753+noteForCaseIndentError =
3754+ D.stack
33453755 [ D.toSimpleNote $
33463756 "Sometimes I get confused by indentation, so try to make your `case` look\
33473757 \ something like this:"
@@ -3354,8 +3764,9 @@ addNoteForCaseIndentError message =
33543764 , D.indent 8 $ D.fillSep [D.dullyellow "400"]
33553765 ]
33563766 , D.reflow $
3357− "Notice the indentation! Each pattern is aligned, and each branch is indented\
3358− \ a bit more than the corresponding pattern. That is important!"
3767+ "Notice the indentation! Patterns are aligned with each other. Same indentation.\
3768+ \ The expressions after each arrow are all indented a bit more than the patterns.\
3769+ \ That is important!"
33593770 ]
33603771
33613772
@@ -3507,23 +3918,43 @@ toIfReport source context if_ startRow startCol =
35073918 )
35083919
35093920 IfIndentElse row col ->
3510− let
3511− surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
3512− region = toRegion row col
3513− in
3514− Report.Report "UNFINISHED IF" region [] $
3515− Code.toSnippet source surroundings (Just region)
3516− (
3517− D.reflow $
3518− "I was expecting to see an `else` branch after this:"
3519− ,
3520− D.stack
3521− [ D.reflow $
3522− "I know what to do when the condition is `True`, but not when it is `False`."
3523− , D.fillSep
3524− ["Add","an",D.cyan "else","branch","to","handle","that","scenario!"]
3525− ]
3526− )
3921+ case Code.nextLineStartsWithKeyword "else" source row of
3922+ Just (elseRow, elseCol) ->
3923+ let
3924+ surroundings = A.Region (A.Position startRow startCol) (A.Position elseRow elseCol)
3925+ region = toWiderRegion elseRow elseCol 4
3926+ in
3927+ Report.Report "WEIRD ELSE BRANCH" region [] $
3928+ Code.toSnippet source surroundings (Just region)
3929+ (
3930+ D.reflow $
3931+ "I was partway through an `if` expression when I got stuck here:"
3932+ ,
3933+ D.fillSep $
3934+ ["I","think","this",D.cyan "else","keyword","needs","to","be","indented","more."
3935+ ,"Try","adding","some","spaces","before","it."
3936+ ]
3937+ )
3938+
3939+ Nothing ->
3940+ let
3941+ surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
3942+ region = toRegion row col
3943+ in
3944+ Report.Report "UNFINISHED IF" region [] $
3945+ Code.toSnippet source surroundings (Just region)
3946+ (
3947+ D.reflow $
3948+ "I was expecting to see an `else` branch after this:"
3949+ ,
3950+ D.stack
3951+ [ D.fillSep
3952+ ["I","know","what","to","do","when","the","condition","is","True,"
3953+ ,"but","what","happens","when","it","is","False?"
3954+ ,"Add","an",D.cyan "else","branch","to","handle","that","scenario!"
3955+ ]
3956+ ]
3957+ )
35273958
35283959
35293960
@@ -3556,15 +3987,22 @@ toRecordReport source context record startRow startCol =
35563987 surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
35573988 region = toRegion row col
35583989 in
3559− Report.Report "UNFINISHED RECORD" region [] $
3990+ Report.Report "PROBLEM IN RECORD" region [] $
35603991 Code.toSnippet source surroundings (Just region)
35613992 (
35623993 D.reflow $
35633994 "I just started parsing a record, but I got stuck here:"
35643995 ,
3565− D.fillSep
3566− ["Records","look","like",D.dullyellow "{ x = 3, y = 4 },"
3567− ,"so","I","was","expecting","to","see","a","field","name","next."
3996+ D.stack
3997+ [ D.fillSep
3998+ ["I","was","expecting","to","see","a","record","field","defined","next,"
3999+ ,"so","I","am","looking","for","a","name","like"
4000+ ,D.dullyellow "userName","or",D.dullyellow "plantHeight" <> "."
4001+ ]
4002+ , D.toSimpleNote $
4003+ "Field names must start with a lower-case letter. After that, you can use\
4004+ \ any sequence of letters, numbers, and underscores."
4005+ , noteForRecordError
35684006 ]
35694007 )
35704008
@@ -3573,7 +4011,7 @@ toRecordReport source context record startRow startCol =
35734011 surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
35744012 region = toRegion row col
35754013 in
3576− Report.Report "UNFINISHED RECORD" region [] $
4014+ Report.Report "PROBLEM IN RECORD" region [] $
35774015 Code.toSnippet source surroundings (Just region)
35784016 (
35794017 D.reflow $
@@ -3608,22 +4046,67 @@ toRecordReport source context record startRow startCol =
36084046 \ that is a reserved word. Try using a different name!"
36094047 )
36104048
4049+ Code.Other (Just ',') ->
4050+ let
4051+ surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
4052+ region = toRegion row col
4053+ in
4054+ Report.Report "EXTRA COMMA" region [] $
4055+ Code.toSnippet source surroundings (Just region)
4056+ (
4057+ D.reflow $
4058+ "I am partway through parsing a record, but I got stuck here:"
4059+ ,
4060+ D.stack
4061+ [ D.reflow $
4062+ "I am seeing two commas in a row. This is the second one!"
4063+ , D.reflow $
4064+ "Just delete one of the commas and you should be all set!"
4065+ , noteForRecordError
4066+ ]
4067+ )
4068+
4069+ Code.Close _ '}' ->
4070+ let
4071+ surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
4072+ region = toRegion row col
4073+ in
4074+ Report.Report "EXTRA COMMA" region [] $
4075+ Code.toSnippet source surroundings (Just region)
4076+ (
4077+ D.reflow $
4078+ "I am partway through parsing a record, but I got stuck here:"
4079+ ,
4080+ D.stack
4081+ [ D.reflow $
4082+ "Trailing commas are not allowed in records. Try deleting the comma that appears\
4083+ \ before this closing curly brace."
4084+ , noteForRecordError
4085+ ]
4086+ )
4087+
36114088 _ ->
36124089 let
36134090 surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
36144091 region = toRegion row col
36154092 in
3616− Report.Report "UNFINISHED RECORD" region [] $
4093+ Report.Report "PROBLEM IN RECORD" region [] $
36174094 Code.toSnippet source surroundings (Just region)
36184095 (
36194096 D.reflow $
3620− "I am partway through parsing a record, but I got stuck after that last comma:"
4097+ "I am partway through parsing a record, but I got stuck here:"
36214098 ,
3622− addNoteForRecordError $
3623− D.reflow $
3624− "Trailing commas are not allowed in records, so I was expecting to see another\
3625− \ record field defined next. If you are done defining the record, the fix may\
3626− \ be to delete that last comma?"
4099+ D.stack
4100+ [ D.fillSep
4101+ ["I","was","expecting","to","see","another","record","field","defined","next,"
4102+ ,"so","I","am","looking","for","a","name","like"
4103+ ,D.dullyellow "userName","or",D.dullyellow "plantHeight" <> "."
4104+ ]
4105+ , D.toSimpleNote $
4106+ "Field names must start with a lower-case letter. After that, you can use\
4107+ \ any sequence of letters, numbers, and underscores."
4108+ , noteForRecordError
4109+ ]
36274110 )
36284111
36294112 RecordEquals row col ->
@@ -3631,17 +4114,19 @@ toRecordReport source context record startRow startCol =
36314114 surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
36324115 region = toRegion row col
36334116 in
3634− Report.Report "UNFINISHED RECORD" region [] $
4117+ Report.Report "PROBLEM IN RECORD" region [] $
36354118 Code.toSnippet source surroundings (Just region)
36364119 (
36374120 D.reflow $
36384121 "I am partway through parsing a record, but I got stuck here:"
36394122 ,
3640− addNoteForRecordError $
3641− D.fillSep $
3642− ["I","just","saw","a","field","name,","so","I","was","expecting","to","see"
3643− ,"an","equals","sign","next.","So","try","putting","an",D.green "=","sign","here?"
3644− ]
4123+ D.stack
4124+ [ D.fillSep $
4125+ ["I","just","saw","a","field","name,","so","I","was","expecting","to","see"
4126+ ,"an","equals","sign","next.","So","try","putting","an",D.green "=","sign","here?"
4127+ ]
4128+ , noteForRecordError
4129+ ]
36454130 )
36464131
36474132 RecordExpr expr row col ->
@@ -3661,29 +4146,54 @@ toRecordReport source context record startRow startCol =
36614146 D.reflow $
36624147 "I just saw the opening curly brace of a record, but then I got stuck here:"
36634148 ,
3664− addNoteForRecordIndentError $
3665− D.fillSep $
3666− ["I","am","expecting","a","record","like",D.dullyellow "{ x = 3, y = 4 }","here."
3667− ,"Try","defining","some","fields","of","your","own?"
3668− ]
4149+ D.stack
4150+ [ D.fillSep $
4151+ ["I","am","expecting","a","record","like",D.dullyellow "{ x = 3, y = 4 }","here."
4152+ ,"Try","defining","some","fields","of","your","own?"
4153+ ]
4154+ , noteForRecordIndentError
4155+ ]
36694156 )
36704157
36714158 RecordIndentEnd row col ->
3672− let
3673− surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
3674− region = toRegion row col
3675− in
3676− Report.Report "UNFINISHED RECORD" region [] $
3677− Code.toSnippet source surroundings (Just region)
3678− (
3679− D.reflow $
3680− "I was expecting to see a closing curly brace next:"
3681− ,
3682− addNoteForRecordIndentError $
3683− D.fillSep $
3684− ["Try","putting","an",D.green "}","and","see","if","that","helps?"
3685− ]
3686− )
4159+ case Code.nextLineStartsWithCloseCurly source row of
4160+ Just (curlyRow, curlyCol) ->
4161+ let
4162+ surroundings = A.Region (A.Position startRow startCol) (A.Position curlyRow curlyCol)
4163+ region = toRegion curlyRow curlyCol
4164+ in
4165+ Report.Report "NEED MORE INDENTATION" region [] $
4166+ Code.toSnippet source surroundings (Just region)
4167+ (
4168+ D.reflow $
4169+ "I was partway through parsing a record, but I got stuck here:"
4170+ ,
4171+ D.stack
4172+ [ D.reflow $
4173+ "I need this curly brace to be indented more. Try adding some spaces before it!"
4174+ , noteForRecordError
4175+ ]
4176+ )
4177+
4178+ Nothing ->
4179+ let
4180+ surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
4181+ region = toRegion row col
4182+ in
4183+ Report.Report "UNFINISHED RECORD" region [] $
4184+ Code.toSnippet source surroundings (Just region)
4185+ (
4186+ D.reflow $
4187+ "I was partway through parsing a record, but I got stuck here:"
4188+ ,
4189+ D.stack
4190+ [ D.fillSep $
4191+ ["I","was","expecting","to","see","a","closing","curly","brace","next."
4192+ ,"Try","putting","a",D.green "}","next","and","see","if","that","helps?"
4193+ ]
4194+ , noteForRecordIndentError
4195+ ]
4196+ )
36874197
36884198 RecordIndentField row col ->
36894199 let
@@ -3696,11 +4206,13 @@ toRecordReport source context record startRow startCol =
36964206 D.reflow $
36974207 "I am partway through parsing a record, but I got stuck after that last comma:"
36984208 ,
3699− addNoteForRecordError $
3700− D.reflow $
3701− "Trailing commas are not allowed in records, so the fix may be to\
3702− \ delete that last comma? Or maybe you were in the middle of defining\
3703− \ an additional field?"
4209+ D.stack
4210+ [ D.reflow $
4211+ "Trailing commas are not allowed in records, so the fix may be to\
4212+ \ delete that last comma? Or maybe you were in the middle of defining\
4213+ \ an additional field?"
4214+ , noteForRecordError
4215+ ]
37044216 )
37054217
37064218 RecordIndentEquals row col ->
@@ -3715,10 +4227,12 @@ toRecordReport source context record startRow startCol =
37154227 "I am partway through parsing a record. I just saw a record\
37164228 \ field, so I was expecting to see an equals sign next:"
37174229 ,
3718− addNoteForRecordIndentError $
3719− D.fillSep $
3720− ["Try","putting","an",D.green "=","followed","by","an","expression?"
3721− ]
4230+ D.stack
4231+ [ D.fillSep $
4232+ ["Try","putting","an",D.green "=","followed","by","an","expression?"
4233+ ]
4234+ , noteForRecordIndentError
4235+ ]
37224236 )
37234237
37244238 RecordIndentExpr row col ->
@@ -3732,52 +4246,48 @@ toRecordReport source context record startRow startCol =
37324246 D.reflow $
37334247 "I am partway through parsing a record, and I was expecting to run into an expression next:"
37344248 ,
3735− addNoteForRecordIndentError $
3736− D.fillSep $
3737− ["Try","putting","something","like"
3738− ,D.dullyellow "42","or",D.dullyellow"\"hello\"","for","now?"
3739− ]
4249+ D.stack
4250+ [ D.fillSep $
4251+ ["Try","putting","something","like"
4252+ ,D.dullyellow "42","or",D.dullyellow"\"hello\"","for","now?"
4253+ ]
4254+ , noteForRecordIndentError
4255+ ]
37404256 )
37414257
37424258
3743−addNoteForRecordError :: D.Doc -> D.Doc
3744−addNoteForRecordError normalRecommendation =
4259+noteForRecordError :: D.Doc
4260+noteForRecordError =
37454261 D.stack $
3746− normalRecommendation
3747− :
37484262 [ D.toSimpleNote
37494263 "If you are trying to define a record across multiple lines, I recommend using this format:"
37504264 , D.indent 4 $ D.vcat $
3751− [ "{ name = \"Alice\""
3752− , ", age = 42"
3753− , ", height = 1.75"
4265+ [ "{ name = " <> D.dullyellow "\"Alice\""
4266+ , ", age = " <> D.dullyellow "42"
4267+ , ", height = " <> D.dullyellow "1.75"
37544268 , "}"
37554269 ]
37564270 , D.reflow $
3757− "Notice that each line starts with some indentation. Usually two or four spaces. I\
3758− \ know this style can be jarring for people coming from C-like syntax, but folks generally\
3759− \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
4271+ "Notice that each line starts with some indentation. Usually two or four spaces.\
4272+ \ This is the stylistic convention in the Elm ecosystem."
37604273 ]
37614274
37624275
3763−addNoteForRecordIndentError :: D.Doc -> D.Doc
3764−addNoteForRecordIndentError normalRecommendation =
3765− D.stack $
3766− normalRecommendation
3767− :
4276+noteForRecordIndentError :: D.Doc
4277+noteForRecordIndentError =
4278+ D.stack
37684279 [ D.toSimpleNote
37694280 "I may be confused by indentation. For example, if you are trying to define\
37704281 \ a record across multiple lines, I recommend using this format:"
37714282 , D.indent 4 $ D.vcat $
3772− [ "{ name = \"Alice\""
3773− , ", age = 42"
3774− , ", height = 1.75"
4283+ [ "{ name = " <> D.dullyellow "\"Alice\""
4284+ , ", age = " <> D.dullyellow "42"
4285+ , ", height = " <> D.dullyellow "1.75"
37754286 , "}"
37764287 ]
37774288 , D.reflow $
3778− "Notice that each line starts with some indentation. Usually two or four spaces. I\
3779− \ know this style can be jarring for people coming from C-like syntax, but folks generally\
3780− \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
4289+ "Notice that each line starts with some indentation. Usually two or four spaces.\
4290+ \ This is the stylistic convention in the Elm ecosystem!"
37814291 ]
37824292
37834293
@@ -3966,15 +4476,14 @@ toListReport source context list startRow startCol =
39664476 , D.toSimpleNote
39674477 "I recommend using the following format for lists that span multiple lines:"
39684478 , D.indent 4 $ D.vcat $
3969− [ "[ \"Alice\""
3970− , ", \"Bob\""
3971− , ", \"Chuck\""
4479+ [ "[ " <> D.dullyellow "\"Alice\""
4480+ , ", " <> D.dullyellow "\"Bob\""
4481+ , ", " <> D.dullyellow "\"Chuck\""
39724482 , "]"
39734483 ]
39744484 , D.reflow $
3975− "Notice that nothing comes directly after a newline. Each line starts with some spaces.\
3976− \ This style can be jarring for people coming from C-like syntax, but folks generally\
3977− \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
4485+ "Notice that each line starts with some indentation. Usually two or four spaces.\
4486+ \ This is the stylistic convention in the Elm ecosystem."
39784487 ]
39794488 )
39804489
@@ -4027,15 +4536,14 @@ toListReport source context list startRow startCol =
40274536 "I may be confused by indentation. For example, if you are trying to define\
40284537 \ a list across multiple lines, I recommend using this format:"
40294538 , D.indent 4 $ D.vcat $
4030− [ "[ \"Alice\""
4031− , ", \"Bob\""
4032− , ", \"Chuck\""
4539+ [ "[ " <> D.dullyellow "\"Alice\""
4540+ , ", " <> D.dullyellow "\"Bob\""
4541+ , ", " <> D.dullyellow "\"Chuck\""
40334542 , "]"
40344543 ]
40354544 , D.reflow $
4036− "Notice that nothing comes directly after a newline. Each line starts with some spaces.\
4037− \ This style can be jarring for people coming from C-like syntax, but folks generally\
4038− \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
4545+ "Notice that each line starts with some indentation. Usually two or four spaces.\
4546+ \ This is the stylistic convention in the Elm ecosystem."
40394547 ]
40404548 )
40414549
@@ -4059,15 +4567,14 @@ toListReport source context list startRow startCol =
40594567 "I may be confused by indentation. For example, if you are trying to define\
40604568 \ a list across multiple lines, I recommend using this format:"
40614569 , D.indent 4 $ D.vcat $
4062− [ "[ \"Alice\""
4063− , ", \"Bob\""
4064− , ", \"Chuck\""
4570+ [ "[ " <> D.dullyellow "\"Alice\""
4571+ , ", " <> D.dullyellow "\"Bob\""
4572+ , ", " <> D.dullyellow "\"Chuck\""
40654573 , "]"
40664574 ]
40674575 , D.reflow $
4068− "Notice that nothing comes directly after a newline. Each line starts with some spaces.\
4069− \ This style can be jarring for people coming from C-like syntax, but folks generally\
4070− \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
4576+ "Notice that each line starts with some indentation. Usually two or four spaces.\
4577+ \ This is the stylistic convention in the Elm ecosystem."
40714578 ]
40724579 )
40734580
@@ -4088,15 +4595,14 @@ toListReport source context list startRow startCol =
40884595 , D.toSimpleNote
40894596 "I recommend using the following format for lists that span multiple lines:"
40904597 , D.indent 4 $ D.vcat $
4091− [ "[ \"Alice\""
4092− , ", \"Bob\""
4093− , ", \"Chuck\""
4598+ [ "[ " <> D.dullyellow "\"Alice\""
4599+ , ", " <> D.dullyellow "\"Bob\""
4600+ , ", " <> D.dullyellow "\"Chuck\""
40944601 , "]"
40954602 ]
40964603 , D.reflow $
4097− "Notice that nothing comes directly after a newline. Each line starts with some spaces.\
4098− \ This style can be jarring for people coming from C-like syntax, but folks generally\
4099− \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
4604+ "Notice that each line starts with some indentation. Usually two or four spaces.\
4605+ \ This is the stylistic convention in the Elm ecosystem."
41004606 ]
41014607 )
41024608
@@ -4345,7 +4851,7 @@ toPatternReport source context pattern startRow startCol =
43454851 ,"((" <> D.dullyellow "x" <> "," <> D.dullyellow "y" <> ") " <> D.cyan "as" <> D.dullyellow " point" <> ")"
43464852 ,"so","you","can","refer","to","individual","parts","of","the","tuple","with"
43474853 ,D.dullyellow "x","and",D.dullyellow "y","or","you","refer","to","the","whole"
4348− ,"thing","with",D.dullyellow "point."
4854+ ,"thing","with",D.dullyellow "point" <> "."
43494855 ]
43504856 , D.reflow $
43514857 "So I was expecting to see a variable name after the `as` keyword here. Sometimes\
@@ -4537,7 +5043,7 @@ toPTupleReport source context tuple startRow startCol =
45375043 "I just saw an open parenthesis, but I got stuck here:"
45385044 ,
45395045 D.fillSep
4540− ["I","was","expecting","so","see","a","pattern","next."
5046+ ["I","was","expecting","to","see","a","pattern","next."
45415047 ,"Maybe","it","will","end","up","being","something"
45425048 ,"like",D.dullyellow "(x,y)","or",D.dullyellow "(name, _)" <> "?"
45435049 ]
@@ -4646,7 +5152,7 @@ toPTupleReport source context tuple startRow startCol =
46465152 "I just saw an open parenthesis, but then I got stuck here:"
46475153 ,
46485154 D.fillSep
4649− ["I","was","expecting","so","see","a","pattern","next."
5155+ ["I","was","expecting","to","see","a","pattern","next."
46505156 ,"Maybe","it","will","end","up","being","something"
46515157 ,"like",D.dullyellow "(x,y)","or",D.dullyellow "(name, _)" <> "?"
46525158 ]
@@ -4665,7 +5171,7 @@ toPTupleReport source context tuple startRow startCol =
46655171 ,
46665172 D.stack
46675173 [ D.fillSep
4668− ["I","was","expecting","so","see","a","pattern","next."
5174+ ["I","was","expecting","to","see","a","pattern","next."
46695175 ,"I","am","expecting","the","final","result","to","be","something"
46705176 ,"like",D.dullyellow "(x,y)","or",D.dullyellow "(name, _)" <> "."
46715177 ]
@@ -4969,22 +5475,64 @@ toTRecordReport source context record startRow startCol =
49695475 \ that is a reserved word. Try using a different name!"
49705476 )
49715477
5478+ Code.Other (Just ',') ->
5479+ let
5480+ surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
5481+ region = toRegion row col
5482+ in
5483+ Report.Report "EXTRA COMMA" region [] $
5484+ Code.toSnippet source surroundings (Just region)
5485+ (
5486+ D.reflow $
5487+ "I am partway through parsing a record type, but I got stuck here:"
5488+ ,
5489+ D.stack
5490+ [ D.reflow $
5491+ "I am seeing two commas in a row. This is the second one!"
5492+ , D.reflow $
5493+ "Just delete one of the commas and you should be all set!"
5494+ , noteForRecordTypeError
5495+ ]
5496+ )
5497+
5498+ Code.Close _ '}' ->
5499+ let
5500+ surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
5501+ region = toRegion row col
5502+ in
5503+ Report.Report "EXTRA COMMA" region [] $
5504+ Code.toSnippet source surroundings (Just region)
5505+ (
5506+ D.reflow $
5507+ "I am partway through parsing a record type, but I got stuck here:"
5508+ ,
5509+ D.stack
5510+ [ D.reflow $
5511+ "Trailing commas are not allowed in record types. Try deleting the comma that\
5512+ \ appears before this closing curly brace."
5513+ , noteForRecordTypeError
5514+ ]
5515+ )
5516+
49725517 _ ->
49735518 let
49745519 surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
49755520 region = toRegion row col
49765521 in
4977− Report.Report "UNFINISHED RECORD TYPE" region [] $
5522+ Report.Report "PROBLEM IN RECORD TYPE" region [] $
49785523 Code.toSnippet source surroundings (Just region)
49795524 (
49805525 D.reflow $
4981− "I am partway through parsing a record type, but I got stuck after that last comma:"
5526+ "I am partway through parsing a record type, but I got stuck here:"
49825527 ,
4983− addNoteForRecordTypeError $
4984− D.reflow $
4985− "Trailing commas are not allowed in records, so I was expecting to see another\
4986− \ record field defined next. If you are done defining the record, the fix may\
4987− \ be to delete that last comma?"
5528+ D.stack
5529+ [ D.fillSep
5530+ ["I","was","expecting","to","see","another","record","field","defined","next,"
5531+ ,"so","I","am","looking","for","a","name","like"
5532+ ,D.dullyellow "userName","or",D.dullyellow "plantHeight" <> "."
5533+ ]
5534+ , noteForRecordTypeError
5535+ ]
49885536 )
49895537
49905538 TRecordColon row col ->
@@ -4998,11 +5546,13 @@ toTRecordReport source context record startRow startCol =
49985546 D.reflow $
49995547 "I am partway through parsing a record type, but I got stuck here:"
50005548 ,
5001− addNoteForRecordTypeError $
5002− D.fillSep $
5003− ["I","just","saw","a","field","name,","so","I","was","expecting","to","see"
5004− ,"a","colon","next.","So","try","putting","an",D.green ":","sign","here?"
5005− ]
5549+ D.stack
5550+ [ D.fillSep $
5551+ ["I","just","saw","a","field","name,","so","I","was","expecting","to","see"
5552+ ,"a","colon","next.","So","try","putting","an",D.green ":","sign","here?"
5553+ ]
5554+ , noteForRecordTypeError
5555+ ]
50065556 )
50075557
50085558 TRecordType tipe row col ->
@@ -5022,29 +5572,54 @@ toTRecordReport source context record startRow startCol =
50225572 D.reflow $
50235573 "I just saw the opening curly brace of a record type, but then I got stuck here:"
50245574 ,
5025− addNoteForRecordTypeIndentError $
5026− D.fillSep $
5027− ["I","am","expecting","a","record","like",D.dullyellow "{ name : String, age : Int }","here."
5028− ,"Try","defining","some","fields","of","your","own?"
5029− ]
5575+ D.stack
5576+ [ D.fillSep $
5577+ ["I","am","expecting","a","record","like",D.dullyellow "{ name : String, age : Int }","here."
5578+ ,"Try","defining","some","fields","of","your","own?"
5579+ ]
5580+ , noteForRecordTypeIndentError
5581+ ]
50305582 )
50315583
50325584 TRecordIndentEnd row col ->
5033− let
5034− surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
5035− region = toRegion row col
5036− in
5037− Report.Report "UNFINISHED RECORD TYPE" region [] $
5038− Code.toSnippet source surroundings (Just region)
5039− (
5040− D.reflow $
5041− "I was expecting to see a closing curly brace next:"
5042− ,
5043− addNoteForRecordTypeIndentError $
5044− D.fillSep $
5045− ["Try","putting","an",D.green "}","and","see","if","that","helps?"
5046− ]
5047− )
5585+ case Code.nextLineStartsWithCloseCurly source row of
5586+ Just (curlyRow, curlyCol) ->
5587+ let
5588+ surroundings = A.Region (A.Position startRow startCol) (A.Position curlyRow curlyCol)
5589+ region = toRegion curlyRow curlyCol
5590+ in
5591+ Report.Report "NEED MORE INDENTATION" region [] $
5592+ Code.toSnippet source surroundings (Just region)
5593+ (
5594+ D.reflow $
5595+ "I was partway through parsing a record type, but I got stuck here:"
5596+ ,
5597+ D.stack
5598+ [ D.reflow $
5599+ "I need this curly brace to be indented more. Try adding some spaces before it!"
5600+ , noteForRecordTypeError
5601+ ]
5602+ )
5603+
5604+ Nothing ->
5605+ let
5606+ surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
5607+ region = toRegion row col
5608+ in
5609+ Report.Report "UNFINISHED RECORD TYPE" region [] $
5610+ Code.toSnippet source surroundings (Just region)
5611+ (
5612+ D.reflow $
5613+ "I was partway through parsing a record type, but I got stuck here:"
5614+ ,
5615+ D.stack
5616+ [ D.fillSep $
5617+ ["I","was","expecting","to","see","a","closing","curly","brace","next."
5618+ ,"Try","putting","a",D.green "}","next","and","see","if","that","helps?"
5619+ ]
5620+ , noteForRecordTypeIndentError
5621+ ]
5622+ )
50485623
50495624 TRecordIndentField row col ->
50505625 let
@@ -5057,11 +5632,13 @@ toTRecordReport source context record startRow startCol =
50575632 D.reflow $
50585633 "I am partway through parsing a record type, but I got stuck after that last comma:"
50595634 ,
5060− addNoteForRecordTypeIndentError $
5061− D.reflow $
5062− "Trailing commas are not allowed in record types, so the fix may be to\
5063− \ delete that last comma? Or maybe you were in the middle of defining\
5064− \ an additional field?"
5635+ D.stack
5636+ [ D.reflow $
5637+ "Trailing commas are not allowed in record types, so the fix may be to\
5638+ \ delete that last comma? Or maybe you were in the middle of defining\
5639+ \ an additional field?"
5640+ , noteForRecordTypeIndentError
5641+ ]
50655642 )
50665643
50675644 TRecordIndentColon row col ->
@@ -5076,10 +5653,12 @@ toTRecordReport source context record startRow startCol =
50765653 "I am partway through parsing a record type. I just saw a record\
50775654 \ field, so I was expecting to see a colon next:"
50785655 ,
5079− addNoteForRecordTypeIndentError $
5080− D.fillSep $
5081− ["Try","putting","an",D.green ":","followed","by","a","type?"
5082− ]
5656+ D.stack
5657+ [ D.fillSep $
5658+ ["Try","putting","an",D.green ":","followed","by","a","type?"
5659+ ]
5660+ , noteForRecordTypeIndentError
5661+ ]
50835662 )
50845663
50855664 TRecordIndentType row col ->
@@ -5093,19 +5672,19 @@ toTRecordReport source context record startRow startCol =
50935672 D.reflow $
50945673 "I am partway through parsing a record type, and I was expecting to run into a type next:"
50955674 ,
5096− addNoteForRecordTypeIndentError $
5097− D.fillSep $
5098− ["Try","putting","something","like"
5099− ,D.dullyellow "Int","or",D.dullyellow "String","for","now?"
5100− ]
5675+ D.stack
5676+ [ D.fillSep $
5677+ ["Try","putting","something","like"
5678+ ,D.dullyellow "Int","or",D.dullyellow "String","for","now?"
5679+ ]
5680+ , noteForRecordTypeIndentError
5681+ ]
51015682 )
51025683
51035684
5104−addNoteForRecordTypeError :: D.Doc -> D.Doc
5105−addNoteForRecordTypeError normalRecommendation =
5685+noteForRecordTypeError :: D.Doc
5686+noteForRecordTypeError =
51065687 D.stack $
5107− normalRecommendation
5108− :
51095688 [ D.toSimpleNote
51105689 "If you are trying to define a record type across multiple lines, I recommend using this format:"
51115690 , D.indent 4 $ D.vcat $
@@ -5115,17 +5694,14 @@ addNoteForRecordTypeError normalRecommendation =
51155694 , "}"
51165695 ]
51175696 , D.reflow $
5118− "Notice that each line starts with some indentation. Usually two or four spaces. I\
5119− \ know this style can be jarring for people coming from C-like syntax, but folks generally\
5120− \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
5697+ "Notice that each line starts with some indentation. Usually two or four spaces.\
5698+ \ This is the stylistic convention in the Elm ecosystem."
51215699 ]
51225700
51235701
5124−addNoteForRecordTypeIndentError :: D.Doc -> D.Doc
5125−addNoteForRecordTypeIndentError normalRecommendation =
5702+noteForRecordTypeIndentError :: D.Doc
5703+noteForRecordTypeIndentError =
51265704 D.stack $
5127− normalRecommendation
5128− :
51295705 [ D.toSimpleNote
51305706 "I may be confused by indentation. For example, if you are trying to define\
51315707 \ a record type across multiple lines, I recommend using this format:"
@@ -5136,9 +5712,8 @@ addNoteForRecordTypeIndentError normalRecommendation =
51365712 , "}"
51375713 ]
51385714 , D.reflow $
5139− "Notice that each line starts with some indentation. Usually two or four spaces. I\
5140− \ know this style can be jarring for people coming from C-like syntax, but folks generally\
5141− \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
5715+ "Notice that each line starts with some indentation. Usually two or four spaces.\
5716+ \ This is the stylistic convention in the Elm ecosystem."
51425717 ]
51435718
51445719
@@ -5190,7 +5765,7 @@ toTTupleReport source context tuple startRow startCol =
51905765 Code.toSnippet source surroundings (Just region)
51915766 (
51925767 D.reflow $
5193− "I was expecting to see a closing parentheses next, but I got stuck here:"
5768+ "I was expecting to see a closing parenthesis next, but I got stuck here:"
51945769 ,
51955770 D.stack
51965771 [ D.fillSep ["Try","adding","a",D.dullyellow ")","to","see","if","that","helps?"]
compiler/src/Reporting/Error/Type.hs+44−23
@@ -231,7 +231,7 @@ toPatternReport source localizer patternRegion category tipe expected =
231231 "But all the previous patterns match:"
232232 [ D.link "Note"
233233 "A `case` expression can only handle one type of value, so you may want to use"
234− "union-types"
234+ "custom-types"
235235 "to handle “mixing” types."
236236 ]
237237 )
@@ -253,11 +253,11 @@ toPatternReport source localizer patternRegion category tipe expected =
253253 , patternTypeComparison localizer tipe expectedType
254254 (addPatternCategory ("The " <> D.ordinal index <> " pattern is trying to match") category)
255255 "But all the previous patterns in the list are:"
256− [ D.toSimpleHint $
257− "Everything in the list needs to be the same type of value.\
258− \ This way you never run into unexpected values partway through.\
259− \ To mix different types in a single list, create a \"union type\" as\
260− \ described in: <http://guide.elm-lang.org/types/union_types.html>"
256+ [ D.link "Hint"
257+ "Everything in a list must be the same type of value. This way, we never\
258+ \ run into unexpected values partway through a List.map, List.foldl, etc. Read"
259+ "custom-types"
260+ "to learn how to “mix” types."
261261 ]
262262 )
263263
@@ -431,13 +431,14 @@ problemToHint problem =
431431 ]
432432 ]
433433
434− T.AnythingToList ->
435− [ D.toSimpleHint "Did you forget to add [] around it?"
434+ T.ArityMismatch x y ->
435+ [ D.toSimpleHint $
436+ if x < y then
437+ "It looks like it takes too few arguments. I was expecting " ++ show (y - x) ++ " more."
438+ else
439+ "It looks like it takes too many arguments. I see " ++ show (x - y) ++ " extra."
436440 ]
437441
438− T.MissingArgs _ -> []
439− T.ReturnMismatch -> []
440−
441442 T.BadFlexSuper direction super _ tipe ->
442443 case tipe of
443444 T.Lambda _ _ _ -> badFlexSuper direction super tipe
@@ -558,11 +559,31 @@ badFlexSuper :: T.Direction -> T.Super -> T.Type -> [D.Doc]
558559badFlexSuper direction super tipe =
559560 case super of
560561 T.Comparable ->
561− [ D.toSimpleHint "Only ints, floats, chars, strings, lists, and tuples are comparable."
562− ]
562+ case tipe of
563+ T.Record _ _ ->
564+ [ D.link "Hint"
565+ "I do not know how to compare records. I can only compare ints, floats,\
566+ \ chars, strings, lists of comparable values, and tuples of comparable values.\
567+ \ Check out" "comparing-records" "for ideas on how to proceed."
568+ ]
569+
570+ T.Type _ name _ ->
571+ [ D.toSimpleHint $
572+ "I do not know how to compare `" ++ Name.toChars name ++ "` values. I can only\
573+ \ compare ints, floats, chars, strings, lists of comparable values, and tuples\
574+ \ of comparable values."
575+ , D.reflowLink
576+ "Check out" "comparing-custom-types" "for ideas on how to proceed."
577+ ]
578+
579+ _ ->
580+ [ D.toSimpleHint $
581+ "I only know how to compare ints, floats, chars, strings, lists of\
582+ \ comparable values, and tuples of comparable values."
583+ ]
563584
564585 T.Appendable ->
565− [ D.toSimpleHint "Only strings and lists are appendable."
586+ [ D.toSimpleHint "I only know how to append strings and lists."
566587 ]
567588
568589 T.CompAppend ->
@@ -689,11 +710,11 @@ toExprReport source localizer exprRegion category tipe expected =
689710 , "The " <> ith <> " element of this list does not match all the previous elements:"
690711 , "The " <> ith <> " element is"
691712 , "But all the previous elements in the list are:"
692− , [ D.toSimpleHint $
693− "Everything in the list needs to be the same type of value.\
694− \ This way you never run into unexpected values partway through.\
695− \ To mix different types in a single list, create a \"union type\" as\
696− \ described in: <http://guide.elm-lang.org/types/union_types.html>"
713+ , [ D.link "Hint"
714+ "Everything in a list must be the same type of value. This way, we never\
715+ \ run into unexpected values partway through a List.map, List.foldl, etc. Read"
716+ "custom-types"
717+ "to learn how to “mix” types."
697718 ]
698719 )
699720
@@ -740,7 +761,7 @@ toExprReport source localizer exprRegion category tipe expected =
740761 , [ D.link "Hint"
741762 "All branches in an `if` must produce the same type of values. This way, no\
742763 \ matter which branch we take, the result is always a consistent shape. Read"
743− "union-types"
764+ "custom-types"
744765 "to learn how to “mix” types."
745766 ]
746767 )
@@ -755,7 +776,7 @@ toExprReport source localizer exprRegion category tipe expected =
755776 , [ D.link "Hint"
756777 "All branches in a `case` must produce the same type of values. This way, no\
757778 \ matter which branch we take, the result is always a consistent shape. Read"
758− "union-types"
779+ "custom-types"
759780 "to learn how to “mix” types."
760781 ]
761782 )
@@ -1072,7 +1093,7 @@ opRightToDocs localizer category op tipe expected =
10721093 ( D.reflow $ "I cannot send this through the (<|) pipe:"
10731094 , typeComparison localizer tipe expected
10741095 "The argument is:"
1075− "But (<|) is piping it a function that expects:"
1096+ "But (<|) is piping it to a function that expects:"
10761097 []
10771098 )
10781099
@@ -1083,7 +1104,7 @@ opRightToDocs localizer category op tipe expected =
10831104 ( D.reflow $ "This function cannot handle the argument sent through the (|>) pipe:"
10841105 , typeComparison localizer argType expectedArgType
10851106 "The argument is:"
1086− "But (|>) is piping it a function that expects:"
1107+ "But (|>) is piping it to a function that expects:"
10871108 []
10881109 )
10891110
compiler/src/Reporting/Render/Code.hs+67−26
@@ -7,6 +7,8 @@ module Reporting.Render.Code
77 , toPair
88 , Next(..)
99 , whatIsNext
10+ , nextLineStartsWithKeyword
11+ , nextLineStartsWithCloseCurly
1012 )
1113 where
1214
@@ -120,7 +122,7 @@ makeUnderline width realEndLine (A.Region (A.Position start c1) (A.Position end
120122 spaces = replicate (fromIntegral c1 + width + 1) ' '
121123 zigzag = replicate (max 1 (fromIntegral (c2 - c1))) '^'
122124 in
123− Just (D.fromChars spaces <> D.dullred (D.fromChars zigzag))
125+ Just (D.fromChars spaces <> D.red (D.fromChars zigzag))
124126
125127
126128drawLines :: Bool -> Int -> A.Region -> [(Word16, String)] -> Doc -> Doc
@@ -146,7 +148,7 @@ addLineNumber addZigZag width start end n line =
146148
147149 spacer =
148150 if addZigZag && start <= n && n <= end then
149− D.dullred ">"
151+ D.red ">"
150152 else
151153 " "
152154 in
@@ -181,8 +183,8 @@ renderPair source@(Source sourceLines) region1 region2 =
181183 OneLine $
182184 D.vcat
183185 [ D.fromChars lineNumber <> "| " <> D.fromChars line
184− , D.fromChars spaces1 <> D.dullred (D.fromChars zigzag1) <>
185− D.fromChars spaces2 <> D.dullred (D.fromChars zigzag2)
186+ , D.fromChars spaces1 <> D.red (D.fromChars zigzag1) <>
187+ D.fromChars spaces2 <> D.red (D.fromChars zigzag2)
186188 ]
187189
188190 else
@@ -199,35 +201,46 @@ data Next
199201 = Keyword [Char]
200202 | Operator [Char]
201203 | Close [Char] Char
202− | Other
204+ | Upper Char [Char]
205+ | Lower Char [Char]
206+ | Other (Maybe Char)
203207
204208
205209whatIsNext :: Source -> Row -> Col -> Next
206210whatIsNext (Source sourceLines) row col =
207211 case List.lookup row sourceLines of
208212 Nothing ->
209− Other
213+ Other Nothing
210214
211215 Just line ->
212− let
213− chars = drop (fromIntegral col - 1) line
214− keywords = map Name.toChars (Set.toList reservedWords)
215− in
216− case List.find (startsWithKeyword chars) keywords of
217− Just keyword ->
218− Keyword keyword
219−
220− Nothing ->
221− case chars of
222− [] ->
223− Other
224−
225− c:cs
226− | isSymbol c -> Operator (c : takeWhile isSymbol cs)
227− | c == ')' -> Close "parenthesis" ')'
228− | c == ']' -> Close "square bracket" ']'
229− | c == '}' -> Close "curly brace" '}'
230− | otherwise -> Other
216+ case drop (fromIntegral col - 1) line of
217+ [] ->
218+ Other Nothing
219+
220+ c:cs
221+ | Char.isUpper c -> Upper c (takeWhile isInner cs)
222+ | Char.isLower c -> detectKeywords c cs
223+ | isSymbol c -> Operator (c : takeWhile isSymbol cs)
224+ | c == ')' -> Close "parenthesis" ')'
225+ | c == ']' -> Close "square bracket" ']'
226+ | c == '}' -> Close "curly brace" '}'
227+ | otherwise -> Other (Just c)
228+
229+
230+detectKeywords :: Char -> [Char] -> Next
231+detectKeywords c rest =
232+ let
233+ cs = takeWhile isInner rest
234+ name = c : cs
235+ in
236+ if Set.member (Name.fromChars name) reservedWords
237+ then Keyword name
238+ else Lower c name
239+
240+
241+isInner :: Char -> Bool
242+isInner char =
243+ Char.isAlphaNum char || char == '_'
231244
232245
233246isSymbol :: Char -> Bool
@@ -244,4 +257,32 @@ startsWithKeyword restOfLine keyword =
244257 True
245258
246259 c:_ ->
247− not (Char.isAlphaNum c || c == '_')
260+ not (isInner c)
261+
262+
263+nextLineStartsWithKeyword :: [Char] -> Source -> Row -> Maybe (Row, Col)
264+nextLineStartsWithKeyword keyword (Source sourceLines) row =
265+ case List.lookup (row + 1) sourceLines of
266+ Nothing ->
267+ Nothing
268+
269+ Just line ->
270+ if startsWithKeyword (dropWhile (==' ') line) keyword then
271+ Just (row + 1, 1 + fromIntegral (length (takeWhile (==' ') line)))
272+ else
273+ Nothing
274+
275+
276+nextLineStartsWithCloseCurly :: Source -> Row -> Maybe (Row, Col)
277+nextLineStartsWithCloseCurly (Source sourceLines) row =
278+ case List.lookup (row + 1) sourceLines of
279+ Nothing ->
280+ Nothing
281+
282+ Just line ->
283+ case dropWhile (==' ') line of
284+ '}':_ ->
285+ Just (row + 1, 1 + fromIntegral (length (takeWhile (==' ') line)))
286+
287+ _ ->
288+ Nothing
compiler/src/Reporting/Render/Type/Localizer.hs+5−5
@@ -112,9 +112,9 @@ toExposing exposing =
112112 Only (foldr addType Set.empty exposedList)
113113
114114
115−addType :: A.Located Src.Exposed -> Set.Set Name.Name -> Set.Set Name.Name
116−addType (A.At _ exposed) types =
115+addType :: Src.Exposed -> Set.Set Name.Name -> Set.Set Name.Name
116+addType exposed types =
117117 case exposed of
118− Src.Lower _ -> types
119− Src.Upper name _ -> Set.insert name types
120− Src.Operator _ -> types
118+ Src.Lower _ -> types
119+ Src.Upper (A.At _ name) _ -> Set.insert name types
120+ Src.Operator _ _ -> types
compiler/src/Reporting/Result.hs+9−1
@@ -118,4 +118,12 @@ instance Monad (Result i w e) where
118118 in
119119 ka i w bad good1
120120
121− -- TODO PERF add more specialized definitions?
121+ (>>) (Result ka) (Result kb) =
122+ Result $ \i w bad good ->
123+ let
124+ good1 i1 w1 _ =
125+ kb i1 w1 bad good
126+ in
127+ ka i w bad good1
128+
129+ -- PERF add INLINE to these?
compiler/src/Type/Error.hs+14−123
@@ -175,9 +175,7 @@ data Problem
175175 | StringToFloat
176176 | AnythingToBool
177177 | AnythingFromMaybe
178− | AnythingToList
179− | MissingArgs Int
180− | ReturnMismatch
178+ | ArityMismatch Int Int
181179 | BadFlexSuper Direction Super Name.Name Type
182180 | BadRigidVar Name.Name Type
183181 | BadRigidSuper Super Name.Name Type
@@ -255,7 +253,11 @@ toDiff localizer ctx tipe1 tipe2 =
255253 <*> toDiff localizer RT.Func b y
256254 <*> sequenceA (zipWith (toDiff localizer RT.Func) cs zs)
257255 else
258− diffLambda localizer ctx a b cs x y zs
256+ let f = toDoc localizer RT.Func in
257+ different
258+ (D.dullyellow (RT.lambda ctx (f a) (f b) (map f cs)))
259+ (D.dullyellow (RT.lambda ctx (f x) (f y) (map f zs)))
260+ (Bag.one (ArityMismatch (2 + length cs) (2 + length zs)))
259261
260262 (Tuple a b Nothing, Tuple x y Nothing) ->
261263 RT.tuple
@@ -298,7 +300,7 @@ toDiff localizer ctx tipe1 tipe2 =
298300 different
299301 (toDoc localizer ctx t1)
300302 (RT.apply ctx (D.dullyellow (L.toDoc localizer home name)) [toDoc localizer RT.App t2])
301− (Bag.one AnythingToList)
303+ Bag.empty
302304
303305 (Alias home1 name1 args1 t1, t2) ->
304306 case diffAliasedRecord localizer t1 t2 of
@@ -447,6 +449,13 @@ isSuper super tipe =
447449 Appendable -> isString h n || isList h n
448450 CompAppend -> isString h n || isList h n && isSuper Comparable (head args)
449451
452+ Tuple a b maybeC ->
453+ case super of
454+ Number -> False
455+ Comparable -> isSuper super a && isSuper super b && maybe True (isSuper super) maybeC
456+ Appendable -> False
457+ CompAppend -> False
458+
450459 _ ->
451460 False
452461
@@ -477,124 +486,6 @@ diffAliasedRecord localizer t1 t2 =
477486
478487
479488
480−-- DIFF LAMBDAS
481−
482−
483−--
484−-- INVARIANTS:
485−-- length cs1 /= length cs2
486−--
487−diffLambda :: L.Localizer -> RT.Context -> Type -> Type -> [Type] -> Type -> Type -> [Type] -> Diff D.Doc
488−diffLambda localizer ctx a1 b1 cs1 a2 b2 cs2 =
489− let
490− (result1:revArgs1) = reverse (a1:b1:cs1)
491− (result2:revArgs2) = reverse (a2:b2:cs2)
492−
493− numArgs1 = length revArgs1
494− numArgs2 = length revArgs2
495− in
496− case toDiff localizer RT.Func result1 result2 of
497− Diff resultDoc1 resultDoc2 Similar ->
498− if numArgs1 < numArgs2 then
499− diffArgMismatch localizer ctx revArgs1 resultDoc1 revArgs2 resultDoc2
500−
501− else
502− diffArgMismatch localizer ctx revArgs2 resultDoc2 revArgs1 resultDoc1
503−
504− Diff resultDoc1 resultDoc2 (Different problems) ->
505− let
506− (a:b:cs) = reverse (resultDoc1 : map (toDoc localizer RT.Func) revArgs1)
507− (x:y:zs) = reverse (resultDoc2 : map (toDoc localizer RT.Func) revArgs2)
508− in
509− different
510− (D.dullyellow (RT.lambda ctx a b cs))
511− (D.dullyellow (RT.lambda ctx x y zs))
512− (Bag.append problems (Bag.one ReturnMismatch))
513−
514−
515−--
516−-- INVARIANTS:
517−-- length shortRevArgs >= 2
518−-- length longRevArgs >= 2
519−-- length shortRevArgs < length longRevArgs
520−--
521−diffArgMismatch :: L.Localizer -> RT.Context -> [Type] -> D.Doc -> [Type] -> D.Doc -> Diff D.Doc
522−diffArgMismatch localizer ctx shortRevArgs shortResult longRevArgs longResult =
523− let
524− (a:b:cs, x:y:zs) =
525− case toGreedyMatch localizer shortRevArgs longRevArgs of
526− Just (GreedyMatch shortRevArgDocs longRevArgDocs) ->
527− ( reverse (shortResult:shortRevArgDocs)
528− , reverse (longResult:longRevArgDocs)
529− )
530−
531− Nothing ->
532− case toGreedyMatch localizer (reverse shortRevArgs) (reverse longRevArgs) of
533− Just (GreedyMatch shortArgDocs longArgDocs) ->
534− ( shortArgDocs ++ [shortResult]
535− , longArgDocs ++ [longResult]
536− )
537−
538− Nothing ->
539− let
540− toYellowDoc tipe =
541− D.dullyellow (toDoc localizer RT.Func tipe)
542− in
543− ( reverse (shortResult : map toYellowDoc shortRevArgs)
544− , reverse (longResult : map toYellowDoc longRevArgs )
545− )
546− in
547− different
548− (RT.lambda ctx a b cs)
549− (RT.lambda ctx x y zs)
550− (Bag.one (MissingArgs (length longRevArgs - length shortRevArgs)))
551−
552−
553−
554−-- GREEDY ARG MATCHER
555−
556−
557−data GreedyMatch =
558− GreedyMatch [D.Doc] [D.Doc]
559−
560−
561−--
562−-- INVARIANTS:
563−-- length shorterArgs < length longerArgs
564−--
565−toGreedyMatch :: L.Localizer -> [Type] -> [Type] -> Maybe GreedyMatch
566−toGreedyMatch localizer shorterArgs longerArgs =
567− toGreedyMatchHelp localizer shorterArgs longerArgs (GreedyMatch [] [])
568−
569−
570−toGreedyMatchHelp :: L.Localizer -> [Type] -> [Type] -> GreedyMatch -> Maybe GreedyMatch
571−toGreedyMatchHelp localizer shorterArgs longerArgs match@(GreedyMatch shorterDocs longerDocs) =
572− let
573− toYellowDoc tipe =
574− D.dullyellow (toDoc localizer RT.Func tipe)
575− in
576− case (shorterArgs, longerArgs) of
577− (x:xs, y:ys) ->
578− case toDiff localizer RT.Func x y of
579− Diff a b Similar ->
580− toGreedyMatchHelp localizer xs ys $
581− GreedyMatch (a:shorterDocs) (b:longerDocs)
582−
583− Diff _ _ (Different _) ->
584− toGreedyMatchHelp localizer shorterArgs ys $
585− GreedyMatch shorterDocs (toYellowDoc y : longerDocs)
586−
587− ([], []) ->
588− Just match
589−
590− ([], _:_) ->
591− Just (GreedyMatch shorterDocs (map toYellowDoc longerArgs))
592−
593− (_:_, []) ->
594− Nothing
595−
596−
597−
598489-- RECORD DIFFS
599490
600491
compiler/src/Type/Solve.hs+7
@@ -427,6 +427,13 @@ typeToVariable rank pools tipe =
427427 typeToVar rank pools Map.empty tipe
428428
429429
430+-- PERF working with @mgriffith we noticed that a 784 line entry in a `let` was
431+-- causing a ~1.5 second slowdown. Moving it to the top-level to be a function
432+-- saved all that time. The slowdown seems to manifest in `typeToVar` and in
433+-- `register` in particular. Have not explored further yet. Top-level definitions
434+-- are recommended in cases like this anyway, so there is at least a safety
435+-- valve for now.
436+--
430437typeToVar :: Int -> Pools -> Map.Map Name.Name Variable -> Type -> IO Variable
431438typeToVar rank pools aliasDict tipe =
432439 let go = typeToVar rank pools aliasDict in
compiler/src/Type/Unify.hs+5−11
@@ -90,7 +90,6 @@ instance Applicative Unify where
9090
9191
9292instance Monad Unify where
93− -- TODO PERF add INLINE here?
9493 return a =
9594 Unify $ \vars ok _ ->
9695 ok vars a
@@ -220,8 +219,6 @@ unifyFlex context content otherContent =
220219 Error ->
221220 merge context Error
222221
223− -- TODO see if wildcarding makes a noticable perf difference
224−
225222 FlexVar maybeName ->
226223 merge context $
227224 case maybeName of
@@ -394,13 +391,13 @@ unifyFlexSuperStructure context super flatType =
394391
395392 Comparable ->
396393 do comparableOccursCheck context
397− merge context (Structure flatType)
398394 unifyComparableRecursive variable
395+ merge context (Structure flatType)
399396
400397 CompAppend ->
401398 do comparableOccursCheck context
402− merge context (Structure flatType)
403399 unifyComparableRecursive variable
400+ merge context (Structure flatType)
404401
405402 Tuple1 a b maybeC ->
406403 case super of
@@ -412,15 +409,12 @@ unifyFlexSuperStructure context super flatType =
412409
413410 Comparable ->
414411 do comparableOccursCheck context
415− merge context (Structure flatType)
416412 unifyComparableRecursive a
417413 unifyComparableRecursive b
418414 case maybeC of
419− Nothing ->
420− return ()
421−
422− Just c ->
423− unifyComparableRecursive c
415+ Nothing -> return ()
416+ Just c -> unifyComparableRecursive c
417+ merge context (Structure flatType)
424418
425419 CompAppend ->
426420 mismatch
docs/elm.json/application.md+2−2
@@ -8,7 +8,7 @@ This is a decent baseline for pretty much any applications made with Elm. You wi
88 "source-directories": [
99 "src"
1010 ],
11− "elm-version": "0.19.0",
11+ "elm-version": "0.19.1",
1212 "dependencies": {
1313 "direct": {
1414 "elm/browser": "1.0.0",
@@ -48,7 +48,7 @@ A list of directories where Elm code lives. Most projects just use `"src"` for e
4848
4949## `"elm-version"`
5050
51−The exact version of Elm this builds with. Should be `"0.19.0"` for most people!
51+The exact version of Elm this builds with. Should be `"0.19.1"` for most people!
5252
5353<br>
5454
docs/elm.json/package.md+1−1
@@ -49,7 +49,7 @@ A short summary that will appear on [`package.elm-lang.org`](https://package.elm
4949
5050## `"license"`
5151
52−An OSI approved SPDX code like `"BSD-3-Clause"` or `"MIT"`. These are the two most common licenses in the Elm ecosystem, but you can see the full list of options [here](https://spdx.org/licenses/).
52+An OSI approved SPDX code like `"BSD-3-Clause"` or `"MIT"`. These are the two most common licenses in the Elm ecosystem, and BSD-3-Clause is a good default. But you can see the full list of options [here](https://spdx.org/licenses/).
5353
5454<br>
5555
upgrade-docs/0.16.md → docs/upgrade-instructions/0.16.mdrenamed

The content is the same.

upgrade-docs/0.17.md → docs/upgrade-instructions/0.17.mdrenamed

The content is the same.

upgrade-docs/0.18.md → docs/upgrade-instructions/0.18.mdrenamed

The content is the same.

upgrade-docs/0.19.md → docs/upgrade-instructions/0.19.0.mdrenamed

The content is the same.

docs/upgrade-instructions/0.19.1.mdnew file+60
@@ -0,0 +1,60 @@
1+# Upgrading to 0.19.1
2+
3+**There are no language changes**, so once you swap to `"elm-version": "0.19.1"` in your `elm.json`, most users should be able to proceed without any further code changes. **You may run into a handful of bugfixes though!** These cases are outlined below!
4+
5+
6+<br>
7+
8+## Improvements
9+
10+- Parse error message quality (like [this](https://github.com/elm/error-message-catalog/issues/255) and [this](https://github.com/elm/error-message-catalog/issues/225))
11+- Faster compilation, especially for incremental compiles
12+- Uses filelocks so that cached files are not corrupted when plugins run `elm make` multiple times on the same project at the same time. (Still worth avoiding that though!)
13+- More intuitive multiline declarations in REPL
14+- Various bug fixes (e.g. `--debug`, `x /= 0`, `type Height = Height Float` in `--optimize`)
15+
16+
17+<br>
18+
19+## Detectable Bug Fixes
20+
21+There are three known cases where code that compiled with 0.19.0 will not compile with 0.19.1 due to bug fixes:
22+
23+
24+### 1. Ambiguous Imports
25+
26+Say you have an import like this:
27+
28+```elm
29+import Html exposing (min)
30+import Regex exposing (never)
31+
32+x = min
33+y = never
34+```
35+
36+These should be reported as ambiguous usages since the names are also exposed by `Basics`, but there was a regression in 0.19.0 described [here](https://github.com/elm/compiler/issues/1945) such that they weren't caught in specific circumstances.
37+
38+The fix is to use a qualified name like `Html.min` or `Regex.never` to make it unambiguous.
39+
40+We found a couple instances of this in packages and have submitted PRs to the relevant authors in August 2019. You may run into this in your own code as well.
41+
42+For more details on why this is considered a regression, check out the details [here](https://github.com/elm/compiler/issues/1945#issuecomment-507871919) or try it in 0.18.0 to see how it worked before.
43+
44+
45+### 2. Tabs in Comments
46+
47+The 0.19.0 binaries did not catch tab characters in comments. The new parser is better at checking for tabs, so it will object when it finds these.
48+
49+Again, we found this in some packages and reached out to the relevant authors with PRs so patches would be published before the 0.19.1 release.
50+
51+
52+### 3. Port Module with no Ports
53+
54+If you have any files that start with:
55+
56+```elm
57+port module Main exposing (..)
58+```
59+
60+But they do not actually have any `port` declarations, the 0.19.1 binary will ask you to switch to a normal module declaration like `module Main exposing (..)`
upgrade-docs/earlier.md → docs/upgrade-instructions/earlier.mdrenamed

The content is the same.

elm.cabal+10−6
@@ -38,11 +38,14 @@ Executable elm
3838 if flag(dev)
3939 ghc-options: -O0 -Wall -Werror
4040 else
41− ghc-options: -O2 -rtsopts -threaded "-with-rtsopts=-N -qg"
41+ ghc-options: -O2 -rtsopts -threaded "-with-rtsopts=-N -qg -A128m"
42+ -- add -eventlog for (elm make src/Main.elm +RTS -l; threadscope elm.eventlog)
43+ -- https://www.oreilly.com/library/view/parallel-and-concurrent/9781449335939/
4244
4345 Hs-Source-Dirs:
4446 compiler/src
4547 builder/src
48+ terminal/impl
4649 terminal/src
4750
4851 other-extensions:
@@ -62,11 +65,11 @@ Executable elm
6265 Repl
6366
6467 -- terminal args
65− Terminal.Args
66− Terminal.Args.Chomp
67− Terminal.Args.Error
68− Terminal.Args.Helpers
69− Terminal.Args.Internal
68+ Terminal
69+ Terminal.Chomp
70+ Terminal.Error
71+ Terminal.Helpers
72+ Terminal.Internal
7073
7174 -- from terminal/
7275 Develop.Generate.Help
@@ -76,6 +79,7 @@ Executable elm
7679
7780 -- from builder/
7881 Build
82+ BackgroundWriter
7983 Deps.Bump
8084 Deps.Diff
8185 Deps.Registry
hints/bad-recursion.mdnew file+133
@@ -0,0 +1,133 @@
1+
2+# Hints for Bad Recursion
3+
4+There are two problems that will lead you here, both of them pretty tricky:
5+
6+ 1. [**No Mutation**](#no-mutation) &mdash; Defining values in Elm is slightly different than defining values in languages like JavaScript.
7+
8+ 2. [**Tricky Recursion**](#tricky-recursion) &mdash; Sometimes you need to define recursive values when creating generators, decoders, and parsers. A common case is a JSON decoder a discussion forums where a comment may have replies, which may have replies, which may have replies, etc.
9+
10+
11+## No Mutation
12+
13+Languages like JavaScript let you “reassign” variables. When you say `x = x + 1` it means: whatever `x` was pointing to, have it point to `x + 1` instead. This is called *mutating* a variable. All values are immutable in Elm, so reassigning variables does not make any sense! Okay, so what *should* `x = x + 1` mean in Elm?
14+
15+Well, what does it mean with functions? In Elm, we write recursive functions like this:
16+
17+```elm
18+factorial : Int -> Int
19+factorial n =
20+ if n <= 0 then 1 else n * factorial (n - 1)
21+```
22+
23+One cool thing about Elm is that whenever you see `factorial 3`, you can always replace that expression with `if 3 <= 0 then 1 else 3 * factorial (3 - 1)` and it will work exactly the same. So when Elm code gets evaluated, we will keep expanding `factorial` until the `if` produces a 1. At that point, we are done expanding and move on.
24+
25+The thing that surprises newcomers is that recursion works the same way with values too. So take the following definition:
26+
27+```elm
28+x = x + 1
29+```
30+
31+We are actually defining `x` in terms of itself. So it would expand out to `x = ... + 1 + 1 + 1 + 1`, trying to add one to `x` an infinite number of times! This means your program would just run forever, endlessly expanding `x`. In practice, this means the page freezes and the computer starts to get kind of warm. No good! We can detect cases like this with the compiler, so we give an error at compile time so this does not happen in the wild.
32+
33+The fix is usually to just give the new value a new name. So you could rewrite it to:
34+
35+```elm
36+x1 = x + 1
37+```
38+
39+Now `x` is the old value and `x1` is the new value. Again, one cool thing about Elm is that whenever you see a `factorial 3` you can safely replace it with its definition. Well, the same is true of values. Wherever I see `x1`, I can replace it with `x + 1`. Thanks to the way definitions work in Elm, this is always safe!
40+
41+
42+## Tricky Recursion
43+
44+Now, there are some cases where you *do* want a recursive value. Say you are building a website with comments and replies. You may define a comment like this:
45+
46+```elm
47+type alias Comment =
48+ { message : String
49+ , upvotes : Int
50+ , downvotes : Int
51+ , responses : Responses
52+ }
53+
54+type Responses =
55+ Responses (List Comment)
56+```
57+
58+You may have run into this definition in the [hints for recursive aliases](recursive-alias.md)! Anyway, once you have comments, you may want to turn them into JSON to send back to your server or to store in your database or whatever. So you will probably write some code like this:
59+
60+```elm
61+import Json.Decode as Decode exposing (Decoder)
62+
63+decodeComment : Decoder Comment
64+decodeComment =
65+ Decode.map4 Comment
66+ (Decode.field "message" Decode.string)
67+ (Decode.field "upvotes" Decode.int)
68+ (Decode.field "downvotes" Decode.int)
69+ (Decode.field "responses" decodeResponses)
70+
71+-- PROBLEM
72+decodeResponses : Decoder Responses
73+decodeResponses =
74+ Decode.map Responses (Decode.list decodeComment)
75+```
76+
77+The problem is that now `decodeComment` is defined in terms of itself! To know what `decodeComment` is, I need to expand `decodeResponses`. To know what `decodeResponses` is, I need to expand `decodeComment`. This loop will repeat endlessly!
78+
79+In this case, the trick is to use `Json.Decode.lazy` which delays the evaluation of a decoder until it is needed. So the valid definition would look like this:
80+
81+```elm
82+import Json.Decode as Decode exposing (Decoder)
83+
84+decodeComment : Decoder Comment
85+decodeComment =
86+ Decode.map4 Comment
87+ (Decode.field "message" Decode.string)
88+ (Decode.field "upvotes" Decode.int)
89+ (Decode.field "downvotes" Decode.int)
90+ (Decode.field "responses" decodeResponses)
91+
92+-- SOLUTION
93+decodeResponses : Decoder Responses
94+decodeResponses =
95+ Decode.map Responses (Decode.list (Decode.lazy (\_ -> decodeComment)))
96+```
97+
98+Notice that in `decodeResponses`, we hide `decodeComment` behind an anonymous function. Elm cannot evaluate an anonymous function until it is given arguments, so it allows us to delay evaluation until it is needed. If there are no comments, we will not need to expand it!
99+
100+This saves us from expanding the value infinitely. Instead we only expand the value if we need to.
101+
102+> **Note:** The same kind of logic can be applied to tasks, random value generators, and parsers. Use `lazy` or `andThen` to make sure a recursive value is only expanded if needed.
103+
104+
105+## Understanding “Bad Recursion”
106+
107+The compiler tries to detect bad recursion, but how does it know the difference between good and bad situations? Writing `factorial` is fine, but writing `x = x + 1` is not. One version of `decodeComment` was bad, but the other was fine. What is the rule?
108+
109+**Elm will allow recursive definitions as long as there is at least one lambda before you get back to yourself.** So if we write `factorial` without any pretty syntax, it looks like this:
110+
111+```elm
112+factorial =
113+ \n -> if n <= 0 then 1 else n * factorial (n - 1)
114+```
115+
116+There is technically a lambda between the definition and the use, so it is okay! The same is true with the good version of `decodeComment`. There is a lambda between the definition and the use. As long as there is a lambda before you get back to yourself, the compiler will let it through.
117+
118+**This rule is nice, but it does not catch everything.** It is pretty easy to write a definition where the recursion is hidden behind a lambda, but it still immediately expands forever:
119+
120+```elm
121+x =
122+ (\_ -> x) () + 1
123+```
124+
125+This follows the rules, but it immediately expands until our program runs out of stack space. It leads to a runtime error as soon as you start your program. It is nice to fail fast, but why not have the compiler detect this as well? It turns out this is much harder than it sounds!
126+
127+This is called [the halting problem](https://en.wikipedia.org/wiki/Halting_problem) in computer science. Computational theorists were asking:
128+
129+> Can we determine if a program will finish running (i.e. halt) or if it will continue to run forever?
130+
131+It turns out that Alan Turing wrote a proof in 1936 showing that (1) in some cases you just have to check by running the program and (2) this check will take forever for programs that do not halt!
132+
133+**So we cannot solve the halting problem *in general*, but our simple rule about lambdas can detect the majority of bad cases *in practice*.**
hints/comparing-custom-types.mdnew file+98
@@ -0,0 +1,98 @@
1+# Comparing Custom Types
2+
3+The built-in comparison operators work on a fixed set of types, like `Int` and `String`. That covers a lot of cases, but what happens when you want to compare custom types?
4+
5+This page aims to catalog these scenarios and offer alternative paths that can get you unstuck.
6+
7+
8+## Wrapped Types
9+
10+It is common to try to get some extra type safety by creating really simple custom types:
11+
12+```elm
13+type Id = Id Int
14+type Age = Age Int
15+
16+type Comment = Comment String
17+type Description = Description String
18+```
19+
20+By wrapping the primitive values like this, the type system can now help you make sure that you never mix up a `Id` and an `Age`. Those are different types! This trick is extra cool because it has no runtime cost in `--optimize` mode. The compiler can just use an `Int` or `String` directly when you use that flag!
21+
22+The problem arises when you want to use a `Id` as a key in a dictionary. This is a totally reasonable thing to do, but the current version of Elm cannot handle this scenario.
23+
24+Instead of creating a `Dict Id Info` type, one thing you can do is create a custom data structure like this:
25+
26+```elm
27+module User exposing (Id, Table, empty, get, add)
28+
29+import Dict exposing (Dict)
30+
31+
32+-- USER
33+
34+type Id = Id Int
35+
36+
37+-- TABLE
38+
39+type Table info =
40+ Table Int (Dict Int info)
41+
42+empty : Table info
43+empty =
44+ Table 0 Dict.empty
45+
46+get : Id -> Table info -> Maybe info
47+get (Id id) (Table _ dict) =
48+ Dict.get id dict
49+
50+add : info -> Table info -> (Table info, Id)
51+add info (Table nextId dict) =
52+ ( Table (nextId + 1) (Dict.insert nextId info dict)
53+ , Id nextId
54+ )
55+```
56+
57+There are a couple nice things about this approach:
58+
59+1. The only way to get a new `User.Id` is to `add` information to a `User.Table`.
60+2. All the operations on a `User.Table` are explicit. Does it make sense to remove users? To merge two tables together? Are there any special details to consider in those cases? This will always be captured explicitly in the interface of the `User` module.
61+3. If you ever want to switch the internal representation from `Dict` to `Array` or something else, it is no problem. All the changes will be within the `User` module.
62+
63+So while this approach is not as convenient as using a `Dict` directly, it has some benefits of its own that can be helpful in some cases.
64+
65+
66+## Enumerations to Ints
67+
68+Say you need to define a `trafficLightToInt` function:
69+
70+```elm
71+type TrafficLight = Green | Yellow | Red
72+
73+trafficLightToInt : TrafficLight -> Int
74+trafficLightToInt trafficLight =
75+ ???
76+```
77+
78+We have heard that some people would prefer to use a dictionary for this sort of thing. That way you do not need to write the numbers yourself, they can be generated such that you never have a typo.
79+
80+I would recommend using a `case` expression though:
81+
82+```elm
83+type TrafficLight = Green | Yellow | Red
84+
85+trafficLightToInt : TrafficLight -> Int
86+trafficLightToInt trafficLight =
87+ case trafficLight of
88+ Green -> 1
89+ Yellow -> 2
90+ Red -> 3
91+```
92+
93+This is really straight-forward while avoiding questions like “is `Green` less than or greater than `Red`?”
94+
95+
96+## Something else?
97+
98+If you have some other situation, please tell us about it [here](https://github.com/elm/error-message-catalog/issues). That is a log of error messages that can be improved, and we can use the particulars of your scenario to add more advice on this page!
hints/comparing-records.mdnew file+85
@@ -0,0 +1,85 @@
1+# Comparing Records
2+
3+The built-in comparison operators work on a fixed set of types, like `Int` and `String`. That covers a lot of cases, but what happens when you want to compare records?
4+
5+This page aims to catalog these scenarios and offer alternative paths that can get you unstuck.
6+
7+
8+## Sorting Records
9+
10+Say we want a `view` function that can show a list of students sorted by different characteristics.
11+
12+We could create something like this:
13+
14+```elm
15+import Html exposing (..)
16+
17+type alias Student =
18+ { name : String
19+ , age : Int
20+ , gpa : Float
21+ }
22+
23+type Order = Name | Age | GPA
24+
25+viewStudents : Order -> List Student -> Html msg
26+viewStudents order students =
27+ let
28+ orderlyStudents =
29+ case order of
30+ Name -> List.sortBy .name students
31+ Age -> List.sortBy .age students
32+ GPA -> List.sortBy .gpa students
33+ in
34+ ul [] (List.map viewStudent orderlyStudents)
35+
36+viewStudent : Student -> Html msg
37+viewStudent student =
38+ li [] [ text student.name ]
39+```
40+
41+If you are worried about the performance of changing the order or updating information about particular students, you can start using the [`Html.Lazy`](https://package.elm-lang.org/packages/elm/html/latest/Html-Lazy) and [`Html.Keyed`](https://package.elm-lang.org/packages/elm/html/latest/Html-Keyed) modules. The updated code would look something like this:
42+
43+```elm
44+import Html exposing (..)
45+import Html.Lazy exposing (lazy)
46+import Html.Keyed as Keyed
47+
48+type Order = Name | Age | GPA
49+
50+type alias Student =
51+ { name : String
52+ , age : Int
53+ , gpa : Float
54+ }
55+
56+viewStudents : Order -> List Student -> Html msg
57+viewStudents order students =
58+ let
59+ orderlyStudents =
60+ case order of
61+ Name -> List.sortBy .name students
62+ Age -> List.sortBy .age students
63+ GPA -> List.sortBy .gpa students
64+ in
65+ Keyed.ul [] (List.map viewKeyedStudent orderlyStudents)
66+
67+viewKeyedStudent : Student -> (String, Html msg)
68+viewKeyedStudent student =
69+ ( student.name, lazy viewStudent student )
70+
71+viewStudent : Student -> Html msg
72+viewStudent student =
73+ li [] [ text student.name ]
74+```
75+
76+By using `Keyed.ul` we help the renderer move the DOM nodes around based on their key. This makes it much cheaper to reorder a bunch of students. And by using `lazy` we help the renderer skip a bunch of work. If the `Student` is the same as last time, the render can skip over it.
77+
78+> **Note:** Some people are skeptical of having logic like this in `view` functions, but I think the alternative (maintaining sort order in your `Model`) has some serious downsides. Say a colleague is adding a message to `Add` students, but they do not know about the sort order rules needed for presentation. Bug! So in this alternate design, you must diligently test your `update` function to make sure that no message disturbs the sort order. This is bound to lead to bugs over time!
79+>
80+> With all the optimizations possible with `Html.Lazy` and `Html.Keyed`, I would always be inclined to work on optimizing my `view` functions rather than making my `update` functions more complicated and error prone.
81+
82+
83+## Something else?
84+
85+If you have some other situation, please tell us about it [here](https://github.com/elm/error-message-catalog/issues). That is a log of error messages that can be improved, and we can use the particulars of your scenario to add more advice on this page!
hints/implicit-casts.mdnew file+50
@@ -0,0 +1,50 @@
1+
2+# Implicit Casts
3+
4+Many languages automatically convert from `Int` to `Float` when they think it is necessary. This conversion is often called an [implicit cast](https://en.wikipedia.org/wiki/Type_conversion).
5+
6+Languages that will add in implicit casts for addition include:
7+
8+ - JavaScript
9+ - Python
10+ - Ruby
11+ - C
12+ - C++
13+ - C#
14+ - Java
15+ - Scala
16+
17+These languages generally agree that an `Int` may be implicitly cast to a `Float` when necessary. So everyone is doing it, why not Elm?!
18+
19+## Type Inference + Implicit Casts
20+
21+Elm comes from the ML-family of languages. Languages in the ML-family that **never** do implicit casts include:
22+
23+ - Standard ML
24+ - OCaml
25+ - Elm
26+ - F#
27+ - Haskell
28+
29+Why would so many languages from this lineage require explicit conversions though?
30+
31+Well, we have to go back to the 1970s for some background. J. Roger Hindley and Robin Milner independently discovered an algorithm that could _efficiently_ figure out the type of everything in your program without any type annotations. Type Inference! Every ML-family language has some variation of this algorithm at the center of its design.
32+
33+For decades, the problem was that nobody could figure out how to combine type inference with implicit casts AND make the resulting algorithm efficient enough for daily use. As far as I know, Scala was the first widely known language to figure out how to combine these two things! Its creator, Martin Odersky did a lot of work on combining type inference and subtyping to make this possible.
34+
35+So for any ML-family language designed before Scala, it is safe to assume that implicit conversions just was not an option. Okay, but what about Elm?! It comes after Scala, so why not do it like them?!
36+
37+ 1. You pay performance cost to mix type inference and implicit conversions. At least as far as anyone knows, it defeats an optimization that is crucial to getting _reliably_ good performance. It is fine in most cases, but it can be a real issue in very large code bases.
38+
39+ 2. Based on experience reports from Scala users, it seemed like the convenience was not worth the hidden cost. Yes, you can convert `n` in `(n + 1.5)` and everything is nice, but when you are in larger programs that are sparsely annotated, it can be quite difficult to figure out what is going on.
40+
41+This user data may be confounded by the fact that Scala allows quite extensive conversions, not just from `Int` to `Float`, but I think it is worth taking seriously nonetheless. So it is _possible_, but it has tradeoffs.
42+
43+
44+## Conclusion
45+
46+First, based on the landscape of design possibilities, it seems like requiring _explicit_ conversions is a pretty nice balance. We can have type inference, it can produce friendly error messages, the algorithm is snappy, and an unintended implicit cast will not flow hundreds of lines before manifesting to the user.
47+
48+Second, Elm very much favors explicit code, so this also fits in with the overall spirit of the language and libraries.
49+
50+I hope that clarifies why you have to add those `toFloat` and `round` functions! It definitely can take some getting used to, but there are tons of folks who get past that acclimation period and really love the tradeoffs!
hints/import-cycles.mdnew file+184
@@ -0,0 +1,184 @@
1+
2+# Import Cycles
3+
4+What is an import cycle? In practice you may see it if you create two modules with interrelated `User` and `Comment` types like this:
5+
6+```elm
7+module Comment exposing (..)
8+
9+import User
10+
11+type alias Comment =
12+ { comment : String
13+ , author : User.User
14+ }
15+```
16+
17+```elm
18+module User exposing (..)
19+
20+import Comment
21+
22+type alias User =
23+ { name : String
24+ , comments : List Comment.Comment
25+ }
26+```
27+
28+Notice that to compile `Comment` we need to `import User`. And notice that to compile `User` we need to `import Comment`. We need both to compile either!
29+
30+Now this is *possible* if the compiler figures out any module cycles and puts them all in one big file to compile them together. That seems fine in our small example, but imagine we have a cycle of 20 modules. If you change *one* of them, you must now recompile *all* of them. In a large code base, this causes extremely long compile times. It is also very hard to disentangle them in practice, so you just end up with slow builds. That is your life now.
31+
32+The thing is that you can always write the code *without* cycles by shuffling declarations around, and the resulting code is often much clearer.
33+
34+
35+# How to Break Cycles
36+
37+There are quite a few ways to break our `Comment` and `User` cycle from above, so let’s go through four useful strategies. The first one is by far the most common solution!
38+
39+
40+## 1. Combine the Modules
41+
42+One approach is to just combine the two modules. If we check out the resulting code, we have actually revealed a problem in how we are representing our data:
43+
44+```elm
45+module BadCombination1 exposing (..)
46+
47+type alias Comment =
48+ { comment : String
49+ , author : User
50+ }
51+
52+type alias User =
53+ { name : String
54+ , comments : List Comment
55+ }
56+```
57+
58+Notice that the `Comment` type alias is defined in terms of the `User` type alias and vice versa. Having recursive type aliases like this does not work! That problem is described in depth [here](recursive-alias.md), but the quick takeaway is that one `type alias` needs to become a `type` to break the recursion. So let’s try again:
59+
60+```elm
61+module BadCombination2 exposing (..)
62+
63+type alias Comment =
64+ { comment : String
65+ , author : User
66+ }
67+
68+type alias User =
69+ { name : String
70+ , comments : AllUserComments
71+ }
72+
73+type AllUserComments = AllUserComments (List Comment)
74+```
75+
76+Okay, now we have broken the recursion, but we need to ask ourselves, how are we going to actually instantiate these `Comment` and `User` types that we have described. A `Comment` will always have an author, and that `User` will always refer back to the `Comment`. So we seem to want cyclic data here. If we were in JavaScript we might instantiate all the comments in one pass, and then go back through and mutate the users to point to all the relevant comments. In other words, we need *mutation* to create this cyclic data!
77+
78+All values are immutable in Elm, so we need to use a more functional strategy. One common approach is to use unique identifiers. Instead of referring directly to “the user object” we can refer to a user ID:
79+
80+```elm
81+module GoodCombination exposing (..)
82+
83+import Dict
84+
85+type alias Comment =
86+ { comment : String
87+ , author : UserId
88+ }
89+
90+type alias UserId = String
91+
92+type alias AllComments =
93+ Dict.Dict UserId (List Comment)
94+```
95+
96+Now in this world, we do not even have cycles in our types anymore! That means we can actually break these out into separate modules again:
97+
98+```elm
99+module Comment exposing (..)
100+
101+import Dict
102+import User
103+
104+type alias Comment =
105+ { comment : String
106+ , author : User.Id
107+ }
108+
109+type alias AllComments =
110+ Dict.Dict User.Id (List Comment)
111+```
112+
113+```elm
114+module User exposing (..)
115+
116+type alias Id = String
117+```
118+
119+So now we are back to the two modules we wanted, but we have data structures that are going to work much better in a functional language like Elm! **This is the common approach, and it is what you hope will happen!**
120+
121+
122+## 2. Make a New Module
123+
124+Now say there are actually a ton of functions and values in the `Comment` and `User` modules. Combining them into one does not seem like a good strategy. Instead you can create a *third* module that just has the shared types and functions. Let’s pretend we call that third module `GoodCombination`. So rather than having `Comment` and `User` depend on each other, they now both depend on `GoodCombination`. We broke our cycle!
125+
126+**This strategy is less common.** You generally want to keep the core `type` of a module with all the functions that act upon it directly, so separating a `type` from everything else is a bad sign. So maybe there is a `User` module that contains a bunch of helper functions, but you *use* all those helper functions in a bunch of other modules that interact with users in various ways. In that scenario, it is still more sophisticated than “just throw the types in a module together” and hope it turns out alright.
127+
128+
129+## 3. Use Type Variables
130+
131+Another way to avoid module cycles is to be more generic in how you represent your data:
132+
133+```elm
134+module Comment exposing (..)
135+
136+type alias Comment author =
137+ { comment : String
138+ , author : author
139+ }
140+```
141+
142+```elm
143+module User exposing (..)
144+
145+type alias User comment =
146+ { name : String
147+ , comments : List comment
148+ }
149+```
150+
151+Notice that `Comment` and `User` no longer need to import each other! Instead, whenever we use these modules, we need to fill in the type variable. So we may import both `Comment` and `User` and try to combine them into a `Comment (User (Comment (User ...)))`. Gah, we ran into the recursive type alias thing again!
152+
153+So this strategy fails pretty badly with our particular example. The code is more complicated and it still does not work! So **this strategy is rarely useful**, but when it works, it can simplify things quite a lot.
154+
155+
156+## 4. Hiding Implementation Details in Packages
157+
158+This gets a little bit trickier when you are creating a package like `elm-lang/parser` which is built around the `Parser` type.
159+
160+That package has a couple exposed modules: `Parser`, `Parser.LanguageKit`, and `Parser.LowLevel`. All of these modules want access to the internal details of the `Parser` type, but we do not want to ever expose those internal details to the *users* of this package. So where should the `Parser` type live?!
161+
162+Usually you know which module should expose the type for the best public API. In this case, it makes sense for it to live in the `Parser` module. The way to manage this is to create a `Parser.Internal` module with a definition like:
163+
164+```elm
165+module Parser.Internal exposing (..)
166+
167+type Parser a =
168+ Parser ...
169+```
170+
171+Now we can `import Parser.Internal` and use it in any of the modules in our package. The trick is that we never expose the `Parser.Internal` module to the *users* of our package. We can see what is inside, but they cannot! Then in the `Parser` module we can say:
172+
173+```elm
174+module Parser exposing (..)
175+
176+import Parser.Internal as Internal
177+
178+type alias Parser a =
179+ Internal.Parser a
180+```
181+
182+So now folks see a `Parser` type exposed by the `Parser` module, and it is the one that is used throughout all the modules in the package. Do not screw up your data representation to avoid this trick! I think we can improve how this appears in documentation, but overall this is the best way to go.
183+
184+Now again, this strategy is particularly useful in packages. It is not as worthwhile in application code.
hints/imports.mdnew file+126
@@ -0,0 +1,126 @@
1+
2+# Hints for Imports
3+
4+When getting started with Elm, it is pretty common to have questions about how the `import` declarations work exactly. These questions usually arise when you start playing with the `Html` library so we will focus on that.
5+
6+
7+<br>
8+
9+## `import`
10+
11+An Elm file is called a **module**. To access code in other files, you need to `import` it!
12+
13+So say you want to use the [`div`](http://package.elm-lang.org/packages/elm-lang/html/latest/Html#div) function from the [`elm-lang/html`](http://package.elm-lang.org/packages/elm-lang/html/latest) package. The simplest way is to import it like this:
14+
15+```elm
16+import Html
17+
18+main =
19+ Html.div [] []
20+```
21+
22+After saying `import Html` we can refer to anything inside that module as long as it is *qualified*. This works for:
23+
24+ - **Values** &mdash; we can refer to `Html.text`, `Html.h1`, etc.
25+ - **Types** &mdash; We can refer to [`Attribute`](http://package.elm-lang.org/packages/elm-lang/html/latest/Html#Attribute) as `Html.Attribute`.
26+
27+So if we add a type annotation to `main` it would look like this:
28+
29+```elm
30+import Html
31+
32+main : Html.Html msg
33+main =
34+ Html.div [] []
35+```
36+
37+We are referring to the [`Html`](http://package.elm-lang.org/packages/elm-lang/html/latest/Html#Html) type, using its *qualified* name `Html.Html`. This can feel weird at first, but it starts feeling natural quite quickly!
38+
39+> **Note:** Modules do not contain other modules. So the `Html` module *does not* contain the `Html.Attributes` module. Those are separate names that happen to have some overlap. So if you say `import Html` you *do not* get access to `Html.Attributes.style`. You must `import Html.Attributes` module separately.
40+
41+
42+<br>
43+
44+## `as`
45+
46+It is best practice to always use *qualified* names, but sometimes module names are so long that it becomes unwieldy. This is common for the `Html.Attributes` module. We can use the `as` keyword to help with this:
47+
48+```elm
49+import Html
50+import Html.Attributes as A
51+
52+main =
53+ Html.div [ A.style "color" "red" ] [ Html.text "Hello!" ]
54+```
55+
56+Saying `import Html.Attributes as A` lets us refer to any value or type in `Html.Attributes` as long as it is qualified with an `A`. So now we can refer to [`style`](http://package.elm-lang.org/packages/elm-lang/html/latest/Html-Attributes#style) as `A.style`.
57+
58+
59+<br>
60+
61+## `exposing`
62+
63+In quick drafts, maybe you want to use *unqualified* names. You can do that with the `exposing` keyword like this:
64+
65+```elm
66+import Html exposing (..)
67+import Html.Attributes exposing (style)
68+
69+main : Html msg
70+main =
71+ div [ style "color" "red" ] [ text "Hello!" ]
72+```
73+
74+Saying `import Html exposing (..)` means I can refer to any value or type from the `Html` module without qualification. Notice that I use the `Html` type, the `div` function, and the `text` function without qualification in the example above.
75+
76+> **Note:** It seems neat to expose types and values directly, but it can get out of hand. Say you `import` ten modules `exposing` all of their content. It quickly becomes difficult to figure out what is going on in your code. “Wait, where is this function from?” And then trying to sort through all the imports to find it. Point is, use `exposing (..)` sparingly!
77+
78+Saying `import Html.Attributes exposing (style)` is a bit more reasonable. It means I can refer to the `style` function without qualification, but that is it. You are still importing the `Html.Attributes` module like normal though, so you would say `Html.Attributes.class` or `Html.Attributes.id` to refer to other values and types from that module.
79+
80+
81+<br>
82+
83+## `as` and `exposing`
84+
85+There is one last way to import a module. You can combine `as` and `exposing` to try to get a nice balance of qualified names:
86+
87+```elm
88+import Html exposing (Html, div, text)
89+import Html.Attributes as A exposing (style)
90+
91+main : Html msg
92+main =
93+ div [ A.class "greeting", style "color" "red" ] [ text "Hello!" ]
94+```
95+
96+Notice that I refer to `A.class` which is qualified and `style` which is unqualified.
97+
98+
99+<br>
100+
101+## Default Imports
102+
103+We just learned all the variations of the `import` syntax in Elm. You will use some version of that syntax to `import` any module you ever write.
104+
105+It would be the best policy to make it so every module in the whole ecosystem works this way. We thought so in the past at least, but there are some modules that are so commonly used that the Elm compiler automatically adds the imports to every file. These default imports include:
106+
107+```elm
108+import Basics exposing (..)
109+import List exposing (List, (::))
110+import Maybe exposing (Maybe(..))
111+import Result exposing (Result(..))
112+import String
113+import Tuple
114+
115+import Debug
116+
117+import Platform exposing (Program)
118+import Platform.Cmd as Cmd exposing (Cmd)
119+import Platform.Sub as Sub exposing (Sub)
120+```
121+
122+You can think of these imports being at the top of any module you write.
123+
124+One could argue that `Maybe` is so fundamental to how we handle errors in Elm code that it is *basically* part of the language. One could also argue that it is extraordinarily annoying to have to import `Maybe` once you get past your first couple weeks with Elm. Either way, we know that default imports are not ideal in some sense, so we have tried to keep the default imports as minimal as possible.
125+
126+> **Note:** Elm performs dead code elimination, so if you do not use something from a module, it is not included in the generated code. So if you `import` a module with hundreds of functions, you do not need to worry about the size of your assets. You will only get what you use!
hints/infinite-type.mdnew file+42
@@ -0,0 +1,42 @@
1+
2+# Hints for Infinite Types
3+
4+Infinite types are probably the trickiest kind of bugs to track down. **Writing down type annotations is usually the fastest way to figure them out.** Let's work through an example to get a feel for how these errors usually work though!
5+
6+
7+## Example
8+
9+A common way to get an infinite type error is very small typos. For example, do you see the problem in the following code?
10+
11+```elm
12+incrementNumbers list =
13+ List.map incrementNumbers list
14+
15+incrementNumber n =
16+ n + 1
17+```
18+
19+The issue is that `incrementNumbers` calls itself, not the `incrementNumber` function defined below. So there is an extra `s` in this program! Let's focus on that:
20+
21+```elm
22+incrementNumbers list =
23+ List.map incrementNumbers list -- BUG extra `s` makes this self-recursive
24+```
25+
26+Now the compiler does not know that anything is wrong yet. It just tries to figure out the types like normal. It knows that `incrementNumbers` is a function. The definition uses `List.map` so we can deduce that `list : List t1` and the result of this function call should be some other `List t2`. This also means that `incrementNumbers : List t1 -> List t2`.
27+
28+The issue is that `List.map` uses `incrementNumbers` on `list`! That means that each element of `list` (which has type `t1`) must be fed into `incrementNumbers` (which takes `List t1`)
29+
30+That means that `t1 = List t1`, which is an infinite type! If we start expanding this, we get `List (List (List (List (List ...))))` out to infinity!
31+
32+The point is mainly that we are in a confusing situation. The types are confusing. This explanation is confusing. The compiler is confused. It is a bad time. But luckily, the more type annotations you add, the better chance there is that you and the compiler can figure things out! So say we change our definition to:
33+
34+```elm
35+incrementNumbers : List Int -> List Int
36+incrementNumbers list =
37+ List.map incrementNumbers list -- STILL HAS BUG
38+```
39+
40+Now we are going to get a pretty normal type error. Hey, you said that each element in the `list` is an `Int` but I cannot feed that into a `List Int -> List Int` function! Something like that.
41+
42+In summary, the root issue is often some small typo, and the best way out is to start adding type annotations on everything!
hints/init.mdnew file+55
@@ -0,0 +1,55 @@
1+
2+# Creating an Elm project
3+
4+The main goal of `elm init` is to get you to this page!
5+
6+It just creates an `elm.json` file and a `src/` directory for your code.
7+
8+
9+## What is `elm.json`?
10+
11+This file describes your project. It lists all of the packages you depend upon, so it will say the particular version of [`elm/core`](https://package.elm-lang.org/packages/elm/core/latest/) and [`elm/html`](https://package.elm-lang.org/packages/elm/html/latest/) that you are using. It makes builds reproducible! You can read a bit more about it [here](https://github.com/elm/compiler/blob/master/docs/elm.json/application.md).
12+
13+You should generally not edit it by hand. It is better to add new dependencies with commands like `elm install elm/http` or `elm install elm/json`.
14+
15+
16+## What goes in `src/`?
17+
18+This is where all of your Elm files live. It is best to start with a file called `src/Main.elm`. As you work through [the official guide](https://guide.elm-lang.org/), you can put the code examples in that `src/Main.elm` file.
19+
20+
21+## How do I compile it?
22+
23+Run `elm reactor` in your project. Now you can go to [`http://localhost:8000`](http://localhost:8000) and browse through all the files in your project. If you navigate to `.elm` files, it will compile them for you!
24+
25+If you want to do things more manually, you can run `elm make src/Main.elm` and it will produce an `index.html` file that you can look at in your browser.
26+
27+
28+## How do I structure my directories?
29+
30+Many folks get anxious about their project structure. “If I get it wrong, I am doomed!” This anxiety makes sense in languages where refactoring is risky, but Elm is not one of those languages!
31+
32+So we recommend that newcomers staying in one file until you get into the 600 to 1000 range. Push out of your comfort zone. Having the experience of being fine in large files will help you understand the boundaries in Elm, rather than just defaulting to the boundaries you learned in another language.
33+
34+The talk [The Life of a File](https://youtu.be/XpDsk374LDE) gets into this a lot more. The advice about building modules around a specific [custom type](https://guide.elm-lang.org/types/custom_types.html) is particularly important! You will see that emphasized a lot as you work through the official guide.
35+
36+
37+## How do I write tests?
38+
39+Elm will catch a bunch of errors statically, and I think it is worth skipping tests at first to get a feeling for when tests will actually help you _in Elm_.
40+
41+From there, we have a great testing package called [`elm-explorations/test`](https://github.com/elm-explorations/test) that can help you out! It is particularly helpful for teams working on a large codebase. When you are editing code you have never seen before, tests can capture additional details and constraints that are not otherwise apparent!
42+
43+
44+## How do I start fancier projects?
45+
46+I wanted `elm init` to generate as little code as possible. It is mainly meant to get you to this page! If you would like a more elaborate starting point, I recommend starting projects with commands like these:
47+
48+```bash
49+git clone https://github.com/evancz/elm-todomvc.git
50+git clone https://github.com/rtfeldman/elm-spa-example.git
51+```
52+
53+The idea is that Elm projects should be so simple that nobody needs a tool to generate a bunch of stuff. This also captures the fact that project structure _should_ evolve organically as your application develops, never ending up exactly the same as other projects.
54+
55+But if you have something particular you want, I recommend creating your own starter recipe and using `git clone` when you start new projects. That way (1) you can get exactly what you want and (2) we do not end up with a complex `elm init` that ends up being confusing for beginners!
hints/missing-patterns.mdnew file+139
@@ -0,0 +1,139 @@
1+
2+# Hints for Missing Patterns
3+
4+Elm checks to make sure that all possible inputs to a function or `case` are handled. This gives us the guarantee that no Elm code is ever going to crash because data had an unexpected shape.
5+
6+There are a couple techniques for making this work for you in every scenario.
7+
8+
9+## The danger of wildcard patterns
10+
11+A common scenario is that you want to add a tag to a custom type that is used in a bunch of places. For example, maybe you are working different variations of users in a chat room:
12+
13+```elm
14+type User
15+ = Regular String Int
16+ | Anonymous
17+
18+toName : User -> String
19+toName user =
20+ case user of
21+ Regular name _ ->
22+ name
23+
24+ _ ->
25+ "anonymous"
26+```
27+
28+Notice the wildcard pattern in `toName`. This will hurt us! Say we add a `Visitor String` variant to `User` at some point. Now we have a bug that visitor names are reported as `"anonymous"`, and the compiler cannot help us!
29+
30+So instead, it is better to explicitly list all possible variants, like this:
31+
32+```elm
33+type User
34+ = Regular String Int
35+ | Visitor String
36+ | Anonymous
37+
38+toName : User -> String
39+toName user =
40+ case user of
41+ Regular name _ ->
42+ name
43+
44+ Anonymous ->
45+ "anonymous"
46+```
47+
48+Now the compiler will say "hey, what should `toName` do when it sees a `Visitor`?" This is a tiny bit of extra work, but it is very worth it!
49+
50+
51+## I want to go fast!
52+
53+Imagine that the `User` type appears in 20 or 30 functions across your project. When we add a `Visitor` variant, the compiler points out all the places that need to be updated. That is very convenient, but in a big project, maybe you want to get through it extra quickly.
54+
55+In that case, it can be helpful to use [`Debug.todo`](https://package.elm-lang.org/packages/elm-lang/core/latest/Debug#todo) to leave some code incomplete:
56+
57+```elm
58+type User
59+ = Regular String Int
60+ | Visitor String
61+ | Anonymous
62+
63+toName : User -> String
64+toName user =
65+ case user of
66+ Regular name _ ->
67+ name
68+
69+ Visitor _ ->
70+ Debug.todo "give the visitor name"
71+
72+ Anonymous ->
73+ "anonymous"
74+
75+-- and maybe a bunch of other things
76+```
77+
78+In this case it is easier to just write the implementation, but the point is that on more complex functions, you can put things off a bit.
79+
80+The Elm compiler is actually aware of `Debug.todo` so when it sees it in a `case` like this, it will crash with a bunch of helpful information. It will tell you:
81+
82+ 1. The name of the module that contains the code.
83+ 2. The line numbers of the `case` containing the TODO.
84+ 3. The particular value that led to this TODO.
85+
86+From that information you have a pretty good idea of what went wrong and can go fix it.
87+
88+I tend to use `Debug.todo` as the message when my goal is to go quick because it makes it easy to go and find all remaining todos in my code before a release.
89+
90+
91+## A list that definitely is not empty
92+
93+This can come up from time to time, but Elm **will not** let you write code like this:
94+
95+```elm
96+last : List a -> a
97+last list =
98+ case list of
99+ [x] ->
100+ x
101+
102+ _ :: rest ->
103+ last rest
104+```
105+
106+This is no good. It does not handle the empty list. There are two ways to handle this. One is to make the function return a `Maybe` like this:
107+
108+```elm
109+last : List a -> Maybe a
110+last list =
111+ case list of
112+ [] ->
113+ Nothing
114+
115+ [x] ->
116+ Just x
117+
118+ _ :: rest ->
119+ last rest
120+```
121+
122+This is nice because it lets users know that there might be a failure, so they can recover from it however they want.
123+
124+The other option is to “unroll the list” one level to ensure that no one can ever provide an empty list in the first place:
125+
126+```elm
127+last : a -> List a -> a
128+last first rest =
129+ case rest of
130+ [] ->
131+ first
132+
133+ newFirst :: newRest ->
134+ last newFirst newRest
135+```
136+
137+By demanding the first element of the list as an argument, it becomes impossible to call this function if you have an empty list!
138+
139+This “unroll the list” trick is quite useful. I recommend using it directly, not through some external library. It is nothing special. Just a useful idea!
hints/optimize.mdnew file+59
@@ -0,0 +1,59 @@
1+
2+# How to optimize Elm code
3+
4+When you are serving a website, there are two kinds of optimizations you want to do:
5+
6+1. **Asset Size** &mdash; How can we send as few bits as possible?
7+2. **Performance** &mdash; How can those bits run as quickly as possible?
8+
9+It turns out that Elm does really well on both! We have [very small assets](https://elm-lang.org/news/small-assets-without-the-headache) and [very fast code](https://elm-lang.org/news/blazing-fast-html-round-two) when compared to the popular alternatives.
10+
11+Okay, but how do we get those numbers?
12+
13+
14+## Instructions
15+
16+Step one is to compile with the `--optimize` flag. This does things like shortening record field names and unboxing values.
17+
18+Step two is to call `uglifyjs` with a bunch of special flags. The flags unlock optimizations that are unreliable in normal JS code, but because Elm does not have side-effects, they work fine for us!
19+
20+Putting those together, here is how I would optimize `src/Main.elm` with two terminal commands:
21+
22+```bash
23+elm make src/Main.elm --optimize --output=elm.js
24+uglifyjs elm.js --compress "pure_funcs=[F2,F3,F4,F5,F6,F7,F8,F9,A2,A3,A4,A5,A6,A7,A8,A9],pure_getters,keep_fargs=false,unsafe_comps,unsafe" | uglifyjs --mangle --output elm.min.js
25+```
26+
27+After this you will have an `elm.js` and a significantly smaller `elm.min.js` file!
28+
29+**Note 1:** `uglifyjs` is called twice there. First to `--compress` and second to `--mangle`. This is necessary! Otherwise `uglifyjs` will ignore our `pure_funcs` flag.
30+
31+**Note 2:** If the `uglifyjs` command is not available in your terminal, you can run the command `npm install uglify-js --global` to download it. You probably already have `npm` from getting `elm repl` working, but if not, it is bundled with [nodejs](https://nodejs.org/).
32+
33+## Scripts
34+
35+It is hard to remember all that, so it is probably a good idea to write a script that does it.
36+
37+I would maybe want to run `./optimize.sh src/Main.elm` and get out `elm.js` and `elm.min.js`, so on Mac or Linux, I would make a script called `optimize.sh` like this:
38+
39+```bash
40+#!/bin/sh
41+
42+set -e
43+
44+js="elm.js"
45+min="elm.min.js"
46+
47+elm make --optimize --output=$js $@
48+
49+uglifyjs $js --compress "pure_funcs=[F2,F3,F4,F5,F6,F7,F8,F9,A2,A3,A4,A5,A6,A7,A8,A9],pure_getters,keep_fargs=false,unsafe_comps,unsafe" | uglifyjs --mangle --output $min
50+
51+echo "Initial size: $(cat $js | wc -c) bytes ($js)"
52+echo "Minified size:$(cat $min | wc -c) bytes ($min)"
53+echo "Gzipped size: $(cat $min | gzip -c | wc -c) bytes"
54+```
55+
56+It also prints out all the asset sizes for you! Your server should be configured to gzip the assets it sends, so the last line is telling you how many bytes would _actually_ get sent to the user.
57+
58+Again, the important commands are `elm` and `uglifyjs` which work on any platform, so it should not be too tough to do something similar on Windows.
59+
hints/port-modules.mdnew file+32
@@ -0,0 +1,32 @@
1+
2+# No Ports in Packages
3+
4+The package ecosystem is one of the most important parts of Elm. Right now, our ecosystem has some compelling benefits:
5+
6+ - There are many obvious default packages that work well.
7+ - Adding dependencies cannot introduce runtime exceptions.
8+ - Patch changes cannot lead to surprise build failures.
9+
10+These are really important factors if you want to *quickly* create *reliable* applications. The Elm community thinks this is valuable.
11+
12+Other communities think that the *number* of packages is a better measure of ecosystem health. That is a fine metric to use, but it is not the one we use for Elm. We would rather have 50 great packages than 100k packages of wildly varying quality.
13+
14+
15+## So what about ports?
16+
17+Imagine you install a new package that claims to support `localStorage`. You get it set up, working through any compile errors. You run it, but it does not seem to work! After trying to figure it out for hours, you realize there is some poorly documented `port` to hook up...
18+
19+Okay, now you need to hook up some JavaScript code. Is that JS file in the Elm package? Or is it on `npm`? Wait, what version on `npm` though? And is this patch version going to work as well? Also, how does this file fit into my build process? And assuming we get through all that, maybe the `port` has the same name as one of the ports in your project. Or it clashes with a `port` name in another package.
20+
21+**Suddenly adding dependencies is much more complicated and risky!** An experienced developer would always check for ports up front, spending a bunch of time manually classifying unacceptable packages. Most people would not know to do that and learn all the pitfalls through personal experience, ultimately spending even *more* time than the person who defensively checks to avoid these issues.
22+
23+So “ports in packages” would impose an enormous cost on application developers, and in the end, we would have a less reliable package ecosystem overall.
24+
25+
26+## Conclusion
27+
28+Our wager with the Elm package ecosystem is that it is better to get a package *right* than to get it *right now*. So while we could use “ports in packages” as a way to get twenty `localStorage` packages of varying quality *right now*, we are choosing not to go that route. Instead we ask that developers use ports directly in their application code, getting the same result a different way.
29+
30+Now this may not be the right choice for your particular project, and that is okay! We will be expanding our core libraries over time, as explained [here](https://github.com/elm-lang/projects/blob/master/roadmap.md#where-is-the-localstorage-package), and we hope you will circle back later to see if Elm has grown into a better fit!
31+
32+If you have more questions about this choice or what it means for your application, please come ask in [the Elm slack](http://elmlang.herokuapp.com/). Folks are friendly and happy to help out! Chances are that a `port` in your application will work great for your case once you learn more about how they are meant to be used.
hints/recursive-alias.mdnew file+162
@@ -0,0 +1,162 @@
1+
2+# Hints for Recursive Type Aliases
3+
4+At the root of this issue is the distinction between a `type` and a `type alias`.
5+
6+
7+## What is a type alias?
8+
9+When you create a type alias, you are just creating a shorthand to refer to an existing type. So when you say the following:
10+
11+```elm
12+type alias Time = Float
13+
14+type alias Degree = Float
15+
16+type alias Weight = Float
17+```
18+
19+You have not created any *new* types, you just made some alternate names for `Float`. You can write down things like this and it'll work fine:
20+
21+```elm
22+add : Time -> Degree -> Weight
23+add time degree =
24+ time + degree
25+```
26+
27+This is kind of a weird way to use type aliases though. The typical usage would be for records, where you do not want to write out the whole thing every time. Stuff like this:
28+
29+```elm
30+type alias Person =
31+ { name : String
32+ , age : Int
33+ , height : Float
34+ }
35+```
36+
37+It is much easier to write down `Person` in a type, and then it will just expand out to the underlying type when the compiler checks the program.
38+
39+
40+## Recursive type aliases?
41+
42+Okay, so let's say you have some type that may contain itself. In Elm, a common example of this is a comment that might have subcomments:
43+
44+```elm
45+type alias Comment =
46+ { message : String
47+ , upvotes : Int
48+ , downvotes : Int
49+ , responses : List Comment
50+ }
51+```
52+
53+Now remember that type *aliases* are just alternate names for the real type. So to make `Comment` into a concrete type, the compiler would start expanding it out.
54+
55+```elm
56+ { message : String
57+ , upvotes : Int
58+ , downvotes : Int
59+ , responses :
60+ List
61+ { message : String
62+ , upvotes : Int
63+ , downvotes : Int
64+ , responses :
65+ List
66+ { message : String
67+ , upvotes : Int
68+ , downvotes : Int
69+ , responses : List ...
70+ }
71+ }
72+ }
73+```
74+
75+The compiler cannot deal with values like this. It would just keep expanding forever.
76+
77+
78+## Recursive types!
79+
80+In cases where you want a recursive type, you need to actually create a brand new type. This is what the `type` keyword is for. A simple example of this can be seen when defining a linked list:
81+
82+```elm
83+type List
84+ = Empty
85+ | Node Int List
86+```
87+
88+No matter what, the type of `Node n xs` is going to be `List`. There is no expansion to be done. This means you can represent recursive structures with types that do not explode into infinity.
89+
90+So let's return to wanting to represent a `Comment` that may have responses. There are a couple ways to do this:
91+
92+
93+### Obvious, but kind of annoying
94+
95+```elm
96+type Comment =
97+ Comment
98+ { message : String
99+ , upvotes : Int
100+ , downvotes : Int
101+ , responses : List Comment
102+ }
103+```
104+
105+Now let's say you want to register an upvote on a comment:
106+
107+```elm
108+upvote : Comment -> Comment
109+upvote (Comment comment) =
110+ Comment { comment | upvotes = 1 + comment.upvotes }
111+```
112+
113+It is kind of annoying that we now have to unwrap and wrap the record to do anything with it.
114+
115+
116+### Less obvious, but nicer
117+
118+```elm
119+type alias Comment =
120+ { message : String
121+ , upvotes : Int
122+ , downvotes : Int
123+ , responses : Responses
124+ }
125+
126+type Responses = Responses (List Comment)
127+```
128+
129+In this world, we introduce the `Responses` type to capture the recursion, but `Comment` is still an alias for a record. This means the `upvote` function looks nice again:
130+
131+```elm
132+upvote : Comment -> Comment
133+upvote comment =
134+ { comment | upvotes = 1 + comment.upvotes }
135+```
136+
137+So rather than having to unwrap a `Comment` to do *anything* to it, you only have to do some unwrapping in the cases where you are doing something recursive. In practice, this means you will do less unwrapping which is nice.
138+
139+
140+## Mutually recursive type aliases
141+
142+It is also possible to build type aliases that are *mutually* recursive. That might be something like this:
143+
144+```elm
145+type alias Comment =
146+ { message : String
147+ , upvotes : Int
148+ , downvotes : Int
149+ , responses : Responses
150+ }
151+
152+type alias Responses =
153+ { sortBy : SortBy
154+ , responses : List Comment
155+ }
156+
157+type SortBy = Time | Score | MostResponses
158+```
159+
160+When you try to expand `Comment` you have to expand `Responses` which needs to expand `Comment` which needs to expand `Responses`, etc.
161+
162+So this is just a fancy case of a self-recursive type alias. The solution is the same. Somewhere in that cycle, you need to define an actual `type` to end the infinite expansion.
hints/repl.mdnew file+73
@@ -0,0 +1,73 @@
1+
2+# REPL
3+
4+The REPL lets you interact with Elm values and functions in your terminal.
5+
6+
7+## Use
8+
9+You can type in expressions, definitions, custom types, and module imports using normal Elm syntax.
10+
11+```elm
12+> 1 + 1
13+2 : number
14+
15+> "hello" ++ "world"
16+"helloworld" : String
17+```
18+
19+The same can be done with definitions and custom types:
20+
21+```elm
22+> fortyTwo = 42
23+42 : number
24+
25+> increment n = n + 1
26+<function> : number -> number
27+
28+> increment 41
29+42 : number
30+
31+> factorial n =
32+| if n < 1 then
33+| 1
34+| else
35+| n * factorial (n-1)
36+|
37+<function> : number -> number
38+
39+> factorial 5
40+120 : number
41+
42+> type User
43+| = Regular String
44+| | Visitor String
45+|
46+
47+> case Regular "Tom" of
48+| Regular name -> "Hey again!"
49+| Visitor name -> "Nice to meet you!"
50+|
51+"Hey again!" : String
52+```
53+
54+When you run `elm repl` in a project with an [`elm.json`](https://github.com/elm/compiler/blob/master/docs/elm.json/application.md) file, you can import any module available in the project. So if your project has an `elm/html` dependency, you could say:
55+
56+```elm
57+> import Html exposing (Html)
58+
59+> Html.text "hello"
60+<internals> : Html msg
61+
62+> Html.text
63+<function> : String -> Html msg
64+```
65+
66+If you create a module in your project named `MyThing` in your project, you can say `import MyThing` in the REPL as well. Any module that is accessible in your project should be accessible in the REPL.
67+
68+
69+## Exit
70+
71+To exit the REPL, you can type `:exit`.
72+
73+You can also press `ctrl-d` or `ctrl-c` on some platforms.
hints/shadowing.mdnew file+70
@@ -0,0 +1,70 @@
1+
2+# Variable Shadowing
3+
4+Variable shadowing is when you define the same variable name twice in an ambiguous way. Here is a pretty reasonable use of shadowing:
5+
6+```elm
7+viewName : Maybe String -> Html msg
8+viewName name =
9+ case name of
10+ Nothing ->
11+ ...
12+
13+ Just name ->
14+ ...
15+```
16+
17+I define a `name` with type `Maybe String` and then in that second branch, I define a `name` that is a `String`. Now that there are two `name` values, it is not 100% obvious which one you want in that second branch.
18+
19+Most linters produce warnings on variable shadowing, so Elm makes “best practices” the default. Just rename the first one to `maybeName` and move on.
20+
21+This choice is relatively uncommon in programming languages though, so I want to provide the reasoning behind it.
22+
23+
24+## The Cost of Shadowing
25+
26+The code snippet from above is the best case scenario for variable shadowing. It is pretty clear really. But that is because it is a fake example. It does not even compile.
27+
28+In a large module that is evolving over time, this is going to cause bugs in a very predictable way. You will have two definitions, separated by hundreds of lines. For example:
29+
30+```elm
31+name : String
32+name =
33+ "Tom"
34+
35+-- hundreds of lines
36+
37+viewName : String -> Html msg
38+viewName name =
39+ ... name ... name ... name ...
40+```
41+
42+Okay, so the `viewName` function has an argument `name` and it uses it three times. Maybe the `viewName` function is 50 lines long in total, so those uses are not totally easy to see. This is fine so far, but say your colleague comes along five months later and wants to support first and last names. They refactor the code like this:
43+
44+```elm
45+viewName : String -> String -> Html msg
46+viewName firstName lastName =
47+ ... name ... name ... name ...
48+```
49+
50+The code compiles, but it does not work as intended. They forgot to change all the uses of `name`, and because it shadows the top-level `name` value, it always shows up as `"Tom"`. It is a simple mistake, but it is always the last thing I think of.
51+
52+> Is the data being fetched properly? Let me log all of the JSON requests. Maybe the JSON decoders are messed up? Hmm. Maybe someone is transforming the name in a bad way at some point? Let me check my `update` code.
53+
54+Basically, a bunch of time gets wasted on something that could easily be detected by the compiler. But this bug is rare, right?
55+
56+
57+## Aggregate Cost
58+
59+Thinking of a unique and helpful name takes some extra time. Maybe 30 seconds. But it means that:
60+
61+ 1. Your code is easier to read and understand later on. So you spend 30 seconds once `O(1)` rather than spending 10 seconds each time someone reads that code in the future `O(n)`.
62+
63+ 2. The tricky shadowing bug described above is impossible. Say there is a 5% chance that any given edit produces a shadowing bug, and that resolving that shadowing bug takes one hour. That means the expected time for each edit increases by three minutes.
64+
65+If you are still skeptical, I encourage you can play around with the number of edits, time costs, and probabilities here. When shadowing is not allowed, the resulting overhead for the entire lifetime of the code is the 30 seconds it takes to pick a better name, so that is what you need to beat!
66+
67+
68+## Summary
69+
70+Without shadowing, the code easier to read and folks spend less time on pointless debugging. The net outcome is that folks have more time to make something wonderful with Elm!
hints/tuples.mdnew file+19
@@ -0,0 +1,19 @@
1+
2+# From Tuples to Records
3+
4+The largest tuple possible in Elm has three entries. Once you get to four, it is best to make a record with named entries.
5+
6+For example, it is _conceivable_ to represent a rectangle as four numbers like `(10,10,100,100)` but it would be more self-documenting to use a record like this:
7+
8+```elm
9+type alias Rectangle =
10+ { x : Float
11+ , y : Float
12+ , width : Float
13+ , height : Float
14+ }
15+```
16+
17+Now it is clear that the dimensions should be `Float` values. It is also clear that we are not using the convention of specifying the top-left and bottom-right corners. It could be clearer about whether the `x` and `y` is the point in the top-left or in the middle though!
18+
19+Anyway, using records like this also gives you access to syntax like `rect.x`, `.x`, and `{ rect | x = 40 }`. It is not clear how to design features like that for arbitrarily sized tuples, so we did not. We already have a way, and it is more self-documenting!
hints/type-annotations.mdnew file+60
@@ -0,0 +1,60 @@
1+
2+# Hints for Type Annotation Problems
3+
4+At the root of this kind of issue is always the fact that a type annotation in your code does not match the corresponding definition. Now that may mean that the type annotation is "wrong" or it may mean that the definition is "wrong". The compiler cannot figure out your intent, only that there is some mismatch.
5+
6+This document is going to outline the various things that can go wrong and show some examples.
7+
8+
9+## Annotation vs. Definition
10+
11+The most common issue is with user-defined type variables that are too general. So let's say you have defined a function like this:
12+
13+```elm
14+addPair : (a, a) -> a
15+addPair (x, y) =
16+ x + y
17+```
18+
19+The issue is that the type annotation is saying "I will accept a tuple containing literally *anything*" but the definition is using `(+)` which requires things to be numbers. So the compiler is going to infer that the true type of the definition is this:
20+
21+```elm
22+addPair : (number, number) -> number
23+```
24+
25+So you will probably see an error saying "I cannot match `a` with `number`" which is essentially saying, you are trying to provide a type annotation that is **too general**. You are saying `addPair` accepts anything, but in fact, it can only handle numbers.
26+
27+In cases like this, you want to go with whatever the compiler inferred. It is good at figuring this kind of stuff out ;)
28+
29+
30+## Annotation vs. Itself
31+
32+It is also possible to have a type annotation that clashes with itself. This is probably more rare, but someone will run into it eventually. Let's use another version of `addPair` with problems:
33+
34+```elm
35+addPair : (Int, Int) -> number
36+addPair (x, y) =
37+ x + y
38+```
39+
40+In this case the annotation says we should get a `number` out, but because we were specific about the inputs being `Int`, the output should also be an `Int`.
41+
42+
43+## Annotation vs. Internal Annotation
44+
45+A quite tricky case is when an outer type annotation clashes with an inner type annotation. Here is an example of this:
46+
47+```elm
48+filter : (a -> Bool) -> List a -> List a
49+filter isOkay list =
50+ let
51+ keepIfOkay : a -> Maybe a
52+ keepIfOkay x =
53+ if isOkay x then Just x else Nothing
54+ in
55+ List.filterMap keepIfOkay list
56+```
57+
58+This case is very unfortunate because all the type annotations are correct, but there is a detail of how type inference works right now that **user-defined type variables are not shared between annotations**. This can lead to probably the worst type error messages we have because the problem here is that `a` in the outer annotation does not equal `a` in the inner annotation.
59+
60+For now the best route is to leave off the inner annotation. It is unfortunate, and hopefully we will be able to do a nicer thing in future releases.
installers/README.mdnew file+32
@@ -0,0 +1,32 @@
1+# Installing Elm
2+
3+The normal path is to work through [the guide](https://guide.elm-lang.org/) until you need to install, but you can skip to installation directly by going [here](https://guide.elm-lang.org/install/terminal.html).
4+
5+
6+<br/>
7+
8+## Installing Multiple Versions
9+
10+The secret is that Elm is just a single executable file. If you are developing a project in `~/Desktop/project/` you can download this file into that directory and run commands like `~/Desktop/project/elm make src/Main.elm` or `./elm make src/Main.elm`. You just run the local copy of the executable file!
11+
12+The instructions for [Mac][mac] and [Linux][lin] explain how to do this in more detail. You can follow the same steps on Windows, but you need to do each step by hand. (E.g. download the file through your browser rather than with a terminal command.)
13+
14+[mac]: https://github.com/elm/compiler/blob/master/installers/mac/README.md
15+[lin]: https://github.com/elm/compiler/blob/master/installers/linux/README.md
16+
17+<br/>
18+
19+## Installing Previous Versions
20+
21+The past binaries for Mac, Linux, and Windows are hosted [here](https://github.com/elm/compiler/releases).
22+
23+You can download the executable files directly and use them locally.
24+
25+
26+<br/>
27+
28+## Uninstall
29+
30+- [Mac](https://github.com/elm/compiler/blob/master/installers/mac/README.md#uninstall)
31+- [Linux](https://github.com/elm/compiler/blob/master/installers/linux/README.md#uninstall)
32+- [Windows](https://github.com/elm/compiler/blob/master/installers/win/README.md#uninstall)
installers/linux/Dockerfilenew file+39
@@ -0,0 +1,39 @@
1+# Based initially on https://gist.github.com/rlefevre/1523f47e75310e28eee243c9c5651ac9
2+#
3+# Build Linux x64 binary from elm compiler top-level directory:
4+# $ docker build -t elm -f installers/linux/Dockerfile .
5+#
6+# Retrieve elm Linux binary:
7+# $ docker cp $(docker create elm):/usr/local/bin/elm DESTINATION_DIRECTORY
8+#
9+# Delete docker elm image:
10+# $ docker rmi elm
11+#
12+# Display all images:
13+# $ docker images -a
14+#
15+# Delete all unused docker images:
16+# $ docker system prune -a
17+
18+# Use Alpine 3.11 with GHC 8.6.5
19+FROM alpine:3.11
20+
21+# Install packages required to build elm
22+RUN apk add --no-cache ghc cabal wget musl-dev zlib-dev zlib-static ncurses-dev ncurses-static
23+
24+WORKDIR /elm
25+
26+# Import source code
27+COPY builder builder
28+COPY compiler compiler
29+COPY reactor reactor
30+COPY terminal terminal
31+COPY cabal.config elm.cabal LICENSE ./
32+
33+# Build statically linked elm binary
34+RUN cabal new-update
35+RUN cabal new-build --ghc-option=-optl=-static --ghc-option=-split-sections
36+RUN cp ./dist-newstyle/build/x86_64-linux/ghc-*/elm-*/x/elm/build/elm/elm /usr/local/bin/elm
37+
38+# Remove debug symbols to optimize the binary size
39+RUN strip -s /usr/local/bin/elm
installers/linux/README.mdnew file+93
@@ -0,0 +1,93 @@
1+# Install Instructions
2+
3+The pre-compiled binary for Linux works on a very wide range of distributions.
4+
5+It should be possible to install it by running the following commands in your terminal:
6+
7+```bash
8+# Move to your Desktop so you can see what is going on easier.
9+#
10+cd ~/Desktop/
11+
12+# Download the 0.19.1 binary for Linux.
13+#
14+# +-----------+----------------------+
15+# | FLAG | MEANING |
16+# +-----------+----------------------+
17+# | -L | follow redirects |
18+# | -o elm.gz | name the file elm.gz |
19+# +-----------+----------------------+
20+#
21+curl -L -o elm.gz https://github.com/elm/compiler/releases/download/0.19.1/binary-for-linux-64-bit.gz
22+
23+# There should now be a file named `elm.gz` on your Desktop.
24+#
25+# The downloaded file is compressed to make it faster to download.
26+# This next command decompresses it, replacing `elm.gz` with `elm`.
27+#
28+gunzip elm.gz
29+
30+# There should now be a file named `elm` on your Desktop!
31+#
32+# Every file has "permissions" about whether it can be read, written, or executed.
33+# So before we use this file, we need to mark this file as executable:
34+#
35+chmod +x elm
36+
37+# The `elm` file is now executable. That means running `~/Desktop/elm --help`
38+# should work. Saying `./elm --help` works the same.
39+#
40+# But we want to be able to say `elm --help` without specifying the full file
41+# path every time. We can do this by moving the `elm` binary to one of the
42+# directories listed in your `PATH` environment variable:
43+#
44+sudo mv elm /usr/local/bin/
45+
46+# Now it should be possible to run the `elm` binary just by saying its name!
47+#
48+elm --help
49+```
50+
51+<br/>
52+
53+## Wait, what is the `PATH` variable?
54+
55+When you run a command like `elm make src/Main.elm`, your computer starts by trying to find an executable file called `elm`.
56+
57+The `PATH` is the list of directories that get searched. You can see these directories by running:
58+
59+```bash
60+echo $PATH
61+```
62+
63+This prints `/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin` on my computer. The directories are separated by a `:` so there are five possibilities listed here.
64+
65+When I run `elm make src/Main.elm`, my terminal starts by searching these five directories for an executable file named `elm`. It finds `/usr/local/bin/elm` and then runs `/usr/local/bin/elm make src/Main.elm` with whatever arguments I gave.
66+
67+So the `PATH` environment variable is a convention that allows you to refer to a specific executable file without knowing exactly where it lives on your computer. This is actually how all "terminal commands" work! Commands like `ls` are really executable files that live in directories listed in your `PATH` variable.
68+
69+So the point of running `sudo mv elm /usr/local/bin/` is to turn the `elm` binary into a terminal command, allowing us to call it just like `ls` and `cd`.
70+
71+**Note:** Why do we need to use `sudo` for that one command? Imagine if some program was able to add executables named `ls` or `cd` to `/usr/local/bin` that did something tricky and unexpected. That would be a security problem! Many distributions make this scenario less likely by requiring special permissions to modify the `/usr/local/bin/` directory.
72+
73+
74+<br/>
75+
76+## Uninstall
77+
78+The following commands should remove everything:
79+
80+```bash
81+# Remove the `elm` executable.
82+#
83+sudo rm /usr/local/bin/elm
84+
85+# Remove any cached files. The files here reduce compile times when
86+# starting new projects and make it possible to work offline in more
87+# cases. No need to keep it around if you are uninstalling though!
88+#
89+rm -r ~/.elm/
90+```
91+
92+If you have any Elm projects still on your computer, you can remove their `elm-stuff/` directories as well.
93+
installers/mac/Distribution.xml+5−3
@@ -1,6 +1,6 @@
11<?xml version="1.0" encoding="utf-8" standalone="no"?>
22<installer-script minSpecVersion="1.000000" authoringTool="com.apple.PackageMaker" authoringToolVersion="3.0.6" authoringToolBuild="201">
3− <title>Elm Platform</title>
3+ <title>Elm</title>
44 <options customize="allow" allow-external-scripts="no"/>
55 <domains enable_localSystem="true"/>
66 <volume-check script="pm_volume_check();"/>
@@ -10,7 +10,7 @@
1010function pm_volume_check() {
1111 if(!(my.target.systemVersion &amp;&amp; /* >= */ system.compareVersions(my.target.systemVersion.ProductVersion, '10.6.0') >= 0)) {
1212 my.result.title = 'Failure';
13− my.result.message = 'This version of Elm Platform requires Mac OS X 10.6 or later.';
13+ my.result.message = 'This version of Elm requires Mac OS X 10.6 or later.';
1414 my.result.type = 'Fatal';
1515 return false;
1616 }
@@ -18,13 +18,15 @@ function pm_volume_check() {
1818}
1919
2020</script>
21+ <!--
2122 <background file="background.png" alignment="bottomleft" scaling="none" mime-type="image/png"/>
23+ -->
2224 <welcome mime-type="text/rtf" file="welcome.rtf" />
2325 <conclusion mime-type="text/rtf" file="conclusion.rtf" />
2426 <choices-outline>
2527 <line choice="choice2"/>
2628 </choices-outline>
27− <choice id="choice2" title="Elm Platform ">
29+ <choice id="choice2" title="Elm">
2830 <pkg-ref id="org.elm-lang.binaries.pkg"/>
2931 </choice>
3032 <pkg-ref id="org.elm-lang.binaries.pkg" installKBytes="19444" version="1" auth="Root">binaries.pkg</pkg-ref>
installers/mac/README.mdnew file+93
@@ -0,0 +1,93 @@
1+# Install Instructions
2+
3+The easiest way to install is to to use [the Mac installer](https://github.com/elm/compiler/releases/download/0.19.1/installer-for-mac.pkg)!
4+
5+But it is also possible to install by running the following commands in your terminal:
6+
7+```bash
8+# Move to your Desktop so you can see what is going on easier.
9+#
10+cd ~/Desktop/
11+
12+# Download the 0.19.1 binary for Linux.
13+#
14+# +-----------+----------------------+
15+# | FLAG | MEANING |
16+# +-----------+----------------------+
17+# | -L | follow redirects |
18+# | -o elm.gz | name the file elm.gz |
19+# +-----------+----------------------+
20+#
21+curl -L -o elm.gz https://github.com/elm/compiler/releases/download/0.19.1/binary-for-mac-64-bit.gz
22+
23+# There should now be a file named `elm.gz` on your Desktop.
24+#
25+# The downloaded file is compressed to make it faster to download.
26+# This next command decompresses it, replacing `elm.gz` with `elm`.
27+#
28+gunzip elm.gz
29+
30+# There should now be a file named `elm` on your Desktop!
31+#
32+# Every file has "permissions" about whether it can be read, written, or executed.
33+# So before we use this file, we need to mark this file as executable:
34+#
35+chmod +x elm
36+
37+# The `elm` file is now executable. That means running `~/Desktop/elm --help`
38+# should work. Saying `./elm --help` works the same.
39+#
40+# But we want to be able to say `elm --help` without specifying the full file
41+# path every time. We can do this by moving the `elm` binary to one of the
42+# directories listed in your `PATH` environment variable:
43+#
44+sudo mv elm /usr/local/bin/
45+
46+# Now it should be possible to run the `elm` binary just by saying its name!
47+#
48+elm --help
49+```
50+
51+<br/>
52+
53+## What is the `PATH` variable?
54+
55+When you run a command like `elm make src/Main.elm`, your computer starts by trying to find an executable file called `elm`.
56+
57+The `PATH` is the list of directories that get searched. You can see these directories by running:
58+
59+```bash
60+echo $PATH
61+```
62+
63+This prints `/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin` on my computer. The directories are separated by a `:` so there are five possibilities listed here.
64+
65+When I run `elm make src/Main.elm`, my terminal starts by searching these five directories for an executable file named `elm`. It finds `/usr/local/bin/elm` and then runs `/usr/local/bin/elm make src/Main.elm` with whatever arguments I gave.
66+
67+So the `PATH` environment variable is a convention that allows you to refer to a specific executable file without knowing exactly where it lives on your computer. This is actually how all "terminal commands" work! Commands like `ls` are really executable files that live in directories listed in your `PATH` variable.
68+
69+So the point of running `sudo mv elm /usr/local/bin/` is to turn the `elm` binary into a terminal command, allowing us to call it just like `ls` and `cd`.
70+
71+**Note:** Why do we need to use `sudo` for that one command? Imagine if some program was able to add executables named `ls` or `cd` to `/usr/local/bin` that did something tricky and unexpected. That would be a security problem! Many distributions make this scenario less likely by requiring special permissions to modify the `/usr/local/bin/` directory.
72+
73+
74+<br/>
75+
76+## Uninstall
77+
78+The following commands should remove everything:
79+
80+```bash
81+# Remove the `elm` executable.
82+#
83+sudo rm /usr/local/bin/elm
84+
85+# Remove any cached files. The files here reduce compile times when
86+# starting new projects and make it possible to work offline in more
87+# cases. No need to keep it around if you are uninstalling though!
88+#
89+rm -r ~/.elm/
90+```
91+
92+If you have any Elm projects still on your computer, you can remove their `elm-stuff/` directories as well.
93+
installers/mac/Resources/en.lproj/background.pngdeleted

Binary file not shown.

installers/mac/Resources/en.lproj/conclusion.rtf+13−6
@@ -1,9 +1,16 @@
1−{\rtf1\ansi\ansicpg1252\cocoartf1187\cocoasubrtf400
2−{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
1+{\rtf1\ansi\ansicpg1252\cocoartf2509
2+\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fmodern\fcharset0 CourierNewPSMT;}
33{\colortbl;\red255\green255\blue255;}
4−\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
5−\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
4+{\*\expandedcolortbl;;}
5+\paperw11900\paperh16840\margl1440\margr1440\vieww11180\viewh8400\viewkind0
6+\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\partightenfactor0
67
7−\f0\fs26 \cf0 A bunch of useful programs were just placed in /usr/local/bin/\
8+\f0\fs28 \cf0 Try opening the terminal and running commands like:\
89\
9−Check out {\field{\*\fldinst HYPERLINK "http://elm-lang.org/Get-Started.elm"}{\fldrslt this tutorial}} to learn how to use them!}
10+
11+\f1 elm init\
12+elm make src/Main.elm --optimize\
13+elm repl
14+\f0 \
15+\
16+Check out {\field{\*\fldinst{HYPERLINK "https://guide.elm-lang.org/"}}{\fldrslt this tutorial}} for more advice!}
installers/mac/Resources/en.lproj/welcome.rtf+9−4
@@ -1,7 +1,12 @@
1−{\rtf1\ansi\ansicpg1252\cocoartf1187\cocoasubrtf400
2−{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
1+{\rtf1\ansi\ansicpg1252\cocoartf2509
2+\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fmodern\fcharset0 CourierNewPSMT;}
33{\colortbl;\red255\green255\blue255;}
4+{\*\expandedcolortbl;;}
45\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
5−\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
6+\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0
67
7−\f0\fs28 \cf0 This package will install Elm on your machine.}
8+\f0\fs28 \cf0 Thank you for trying out Elm!\
9+\
10+This installer makes
11+\f1 elm
12+\f0 available in your terminal.}
installers/mac/helper-scripts/elm-startup.sh+1−1
@@ -1,3 +1,3 @@
11#!/bin/sh
22
3−open 'http://elm-lang.org'
3+open 'http://guide.elm-lang.org'
installers/mac/make-installer.sh+30−3
@@ -29,7 +29,8 @@ cp $(pwd)/preinstall $pkg_scripts
2929cp $(pwd)/postinstall $pkg_scripts
3030
3131pkgbuild \
32− --identifier org.elm-lang.binaries.pkg \
32+ --sign "Developer ID Installer: <NAME>" \
33+ --identifier org.elm-lang.binary \
3334 --install-location $usr_binaries \
3435 --scripts $pkg_scripts \
3536 --filter 'Scripts.*' \
@@ -39,16 +40,42 @@ pkgbuild \
3940
4041#### BUNDLE ASSETS ####
4142
42−rm -f Elm.pkg
43+rm -f installer-for-mac.pkg
4344
4445productbuild \
46+ --sign "Developer ID Installer: <NAME>" \
47+ --identifier org.elm-lang.installer \
4548 --distribution Distribution.xml \
4649 --package-path . \
4750 --resources Resources \
48− Elm.pkg
51+ installer-for-mac.pkg
4952
5053
5154#### CLEAN UP ####
5255
5356rm binaries.pkg
5457rm -rf $pkg_root
58+
59+
60+#### BEGIN NOTARIZATION ####
61+
62+xcrun altool \
63+ --notarize-app \
64+ --primary-bundle-id "org.elm-lang.installer" \
65+ --username "<EMAIL>" \
66+ --password "@keychain:Developer-altool" \
67+ --file "installer-for-mac.pkg"
68+
69+# From https://scriptingosx.com/2019/09/notarize-a-command-line-tool/
70+#
71+#### Check on notarization:
72+#
73+# xcrun altool \
74+# --notarization-info "<RequestUUID>" \
75+# --username "<EMAIL>" \
76+# --password "@keychain:Developer-altool"
77+#
78+#
79+#### Staple Notarization:
80+#
81+# xcrun stapler staple installer-for-mac.pkg
installers/npm/PUBLISHING.md+29−141
@@ -1,171 +1,59 @@
1−# Publishing a new release
1+# Publishing
22
3−A new version of Elm came out. Huzzah! Here's how to update the `npm` installer.
3+Here's how to update the `npm` installer.
44
5−## 1. Create tarballs of binaries
65
7−You can find a list of what binaries we'll need to tar up in `index.js`.
6+## 1. GitHub Release
87
9−For example:
8+Create a [GitHub Release](https://github.com/elm/compiler/releases) with the following files:
109
11−```javascript
12−var root =
13− "https://github.com/elm/compiler/releases/download/" +
14− binVersion +
15− "/binaries-for-";
10+1. `binary-for-mac-64-bit.gz`
11+2. `binary-for-windows-64-bit.gz`
12+3. `binary-for-linux-64-bit.gz`
1613
17−module.exports = binwrap({
18− binaries: ["elm"],
19− urls: {
20− "darwin-x64": root + "mac.tar.gz",
21− "win32-x64": root + "windows.tar.gz",
22− "win32-ia32": root + "windows.tar.gz",
23− "linux-x64": root + "linux.tar.gz"
24− }
25−});
26−```
27−
28−If this is the end of your `index.js`, you'll need to create these files:
14+Create each of these by running the `elm` executable for each platform through `gzip elm`.
2915
30−1. `binaries-for-mac.tar.gz`
31−2. `binaries-for-windows.tar.gz`
32−3. `binaries-for-linux.tar.gz`
3316
34−Each of these tarballs should have **only the Elm binary** inside them - no
35−directories!
17+## 2. Try a beta release
3618
37−So create them by making a directory, putting all the binaries in it, `cd`-ing
38−into that directory, and then running something like this:
19+In `package.json`, bump the version to `"0.19.2-beta"`.
3920
40−```shell
41−$ tar cvzf binaries-for-linux.tar.gz elm
21+```bash
22+npm publish --tag beta
4223```
4324
44−Make sure each tarball contains all the binaries listed in that `binaries:` list
45−in `index.js`. (The Windows ones should have `.exe` at the end; `binwrap`
46−expects that they will, for Windows only.)
47−
48−## 2. Update the `bin/` binary wrappers
49−
50−Inside the npm installer's `bin/` directory, there should be a file for each of
51−the binaries that will be included in this release.
52−
53−Each of these must be executable! If you're not sure whether they are,
54−run `chmod +x` on them just to be sure.
55−
56−Their paths must also must all be listed in `package.json` in two places:
57−
58−1. The `"files":` field
59−2. The `"bin":` field
60−
61−If the executables are the same as they were for the last release, great!
62−You can proceed to the next step. If any binaries were removed, make sure to
63−remove them from these lists!
64−
65−## 3. Update `package.json` for a beta release
66−
67−In `package.json`, bump the version to the next applicable release, and add
68−a `"-beta"` suffix to it.
69−
70−For example, if it was on `"0.18.0"` you might bump it to `"0.19.0-beta"`.
71−The version number should match the release of Elm, such that if people do
72−`npm install elm@0.19.0@beta` they get what they would expect.
73−
74−## 4. Tag the beta release
75−
76−Commit this change and tag it with the name of the release **without** the
77−`-beta` suffix. (We will overwrite this tag later.)
78−
79−For example:
25+To test that it works, run these commands:
8026
81−```shell
82−$ git tag 0.19.0
83−$ git push origin 0.19.0
27+```bash
28+npm dist-tags ls elm
29+npm install elm@beta --ignore-scripts
8430```
8531
86−Now this tag should exist on GitHub, allowing us to upload binaries to it.
32+The `latest` tag should not be changed, and there should be an additional `beta` tag.
8733
88−## 5. Upload binaries
34+Try this on Windows, Linux, and Mac.
8935
90−Visit the [Create a New Release](https://github.com/elm-lang/elm-platform/releases/new)
91−page and use the `Tag version` dropdown to select the tag you just pushed. Give
92−it a title like `0.19.0`. Don't mention the `-beta` in it. The "beta" concept
93−is for `npm` only.
9436
95−Upload the tarballs you created in step 1.
37+## 3. Publish final release
9638
97−## 6. Publish beta release
39+Remove the `-beta` suffix from the version in `package.json`. Then run:
9840
99−Run this to publish the beta release. The `--tag beta` is **crucial** here.
100−Without it, `npm` will by default publish a new top-level release, which would
101−mean that what you just published would become what everyone gets when they
102−`npm install -g elm` without any additional qualifiers.
103−
104−```shell
105−$ npm publish --tag beta
41+```bash
42+npm publish
10643```
10744
108−Afterwards you should be able to do `npm info elm | less` and see something
109−like this in the JSON:
110−
111−```
112−'dist-tags': { latest: '0.18.0', beta: '0.19.0-beta' }
113−```
11445
115−If you messed this up, and the `latest` tag now points to the beta you just
116−published, don't panic - it's fixable! `dist-tags` can always be modified after
117−the fact. Read up on `npm` [dist-tags](https://docs.npmjs.com/cli/dist-tag)
118−to learn how to fix things.
46+## 4. Tag the `latest-0.19.1` version
11947
120−## 7. Verify beta installer
48+Many compiler releases have needed multiple `npm` publications. Maybe something does not work on Windows or some dependency becomes insecure. Normal `npm` problems.
12149
122−Make an empty directory and run `npm init` inside it.
50+The convention for each Elm release is to create a tag the latest one.
12351
124−Then run this:
125−
126−```shell
127−$ npm install elm@beta --ignore-scripts
52+```bash
53+npm dist-tag add elm@0.19.1-3 latest-0.19.1
12854```
12955
130−This should succeed with an exit code of `0`.
131−If it did, look in `node_modules/.bin/` for the binaries you expect.
132−They should be present, and they should also work as expected when you run them.
133−Because you installed them with `--ignore-scripts`, the first thing they should
134−do is to download themselves and then execute whatever command you requested
135−(e.g. `node_modules/.bin/elm make Main.elm`). If you run the same command a
136−second time, it should run faster because it doesn't have to download the binary
137−first.
138−
139−Now try it again with `--ignore-scripts` turned off:
140−
141−```shell
142−$ rm -r node_modules
143−$ npm install elm@beta --ignore-scripts=false
144−```
145−
146−This time it should download the binaries during the installation phase. Once
147−again you should be able to run the binaries from `node_modules/.bin/`, and
148−this time they should be fast from the first run because they're already
149−downloaded.
150−
151−## 8. Publish for real
152−
153−It's a good idea to ask others to try out the beta installer before doing this!
154−Especially on multiple operating systems.
155−
156−To publish the real version:
157−
158−1. Edit `package.json` to remove the `-beta` suffix from the version.
159−2. Commit that change and push it.
160−3. Use `git tag --force` to overwrite the previous tag (e.g. `0.19.0` - whatever you used before).
161−4. Force push the tag, e.g. `git push origin 0.19.0 --force-with-lease`.
162−5. `npm publish`
56+That way people who want a specific version can point to `latest-0.19.1` or `latest-0.18.0` instead of knowing the particular names of all the various publications.
16357
164−You're done! Now whenever anyone does `npm install -g elm` they'll get the
165−version you just uploaded.
58+You can read more about dist-tags [here](https://docs.npmjs.com/cli/dist-tag).
16659
167−The reason we only used the `-beta` suffix for `npm` was so that when we ran
168−tests on the beta version, it was all against the same (non-beta) URLs we'd end
169−up using for the real version. This means there's no opportunity for us to
170−introduce some sort of mismatch between the beta that we verified and the real
171−version.
installers/npm/README.md+30−23
@@ -1,38 +1,45 @@
1−npm install elm [![Travis build Status](https://travis-ci.org/elm-lang/elm-platform.svg?branch=master)](http://travis-ci.org/elm-lang/elm-platform) [![AppVeyor build status](https://ci.appveyor.com/api/projects/status/6mcub79i04ianpm9/branch/master?svg=true)](https://ci.appveyor.com/project/rtfeldman/elm-platform/branch/master)
2−===============
1+# Elm Installer
32
4−Install the [Elm Platform](https://github.com/elm-lang/elm-platform) via [`npm`](https://www.npmjs.com).
3+[Elm](https://elm-lang.org) is a functional programming language that compiles to JavaScript.
54
6−## Installing
5+Head over to [The Official Guide](https://guide.elm-lang.org/) to start learning Elm!
76
8−Run this to get the binaries:
97
10−```
11−$ npm install -g elm
12−```
8+<br/>
139
14−## Installing behind a proxy server
10+## What is this package for?
1511
16−If you are behind a proxy server, set the environment variable "HTTPS_PROXY".
12+**Normal installs** ❌
1713
18−```
19−$ export HTTPS_PROXY=$YourProxyServer$
20−$ npm install -g elm
21−```
14+Use the instructions [here](https://guide.elm-lang.org/install/elm.html) instead.
15+
16+**Multiple versions** ✅
17+
18+People using Elm at work may use different versions of Elm in different projects. They can run `npm install elm@latest-0.19.1` in each project and use the binary at `./node_modules/.bin/elm` for compilation.
19+
20+**Continuous integration** ⚠️
21+
22+This works, but there are usually faster and more reliable options:
23+
24+1. You can download `elm` directly from GitHub with [this script](https://github.com/elm/compiler/blob/master/installers/linux/README.md). This is all the `npm` installer does, but with extra HTTP requests to `npmjs.com` servers, making it slower and adding more failure points.
25+2. Many continuous integration have ways to cache files ([example](https://docs.travis-ci.com/user/caching/)) to make builds faster and more reliable.
26+
27+That said, it will definitely work to use the `npm` installer on CI if you prefer that option.
28+
29+
30+<br/>
31+
32+## Install Locally
2233
23−Or on Windows:
34+The following command should download the latest Elm 0.19.1 binary:
2435
2536```
26−$ set HTTPS_PROXY=$YourProxyServer$
27−$ npm install -g elm
37+npm install elm@latest-0.19.1
2838```
2939
30−## Troubleshooting
40+You should be able to run `./node_modules/bin/elm --version` within your project and see `0.19.1`. Now you can compile with `./node_modules/bin/elm make src/Main.elm` and not disrupt other packages.
3141
32−1. [Troubleshooting npm](https://github.com/npm/npm/wiki/Troubleshooting)
33−2. On Debian/Ubuntu systems, you may have to install the nodejs-legacy package: `apt-get install nodejs-legacy`.
34−3. If the installer says that it cannot find any usable binaries for your operating system and architecture, check the [Build from Source](https://github.com/elm-lang/elm-platform/blob/master/README.md#build-from-source) documentation.
42+Use `npm install elm@latest-0.19.0` or `npm install elm@latest-0.18.0` for earlier versions.
3543
36−## Getting Started
44+**Note:** The `latest-X.Y.Z` convention is used in case we need to publish patches for the `npm` installer within a given Elm release. For example, say `npm` decides that some transitive dependency is not secure. Nothing is changing about Elm or the binaries, but we need to publish a new `npm` installer that fixes this issue.
3745
38−Once everything has installed successfully, head over to the [Get Started](http://elm-lang.org/Get-Started.elm) page!
installers/npm/bin/elm+42−16
@@ -1,28 +1,54 @@
11#!/usr/bin/env node
22
33var child_process = require('child_process');
4−var download = require('../download.js');
4+var path = require('path');
55var fs = require('fs');
66
77
8−// Some npm users enable --ignore-scripts (a good security measure)
8+// Some npm users enable --ignore-scripts (a good security measure) so
9+// they do not run the post-install hook and install.js does not run.
10+// Instead they will run this script.
911//
10−// They do not run the post-install hook, so install.js does not run.
12+// On Mac and Linux, we download the elm executable into the exact same
13+// location as this file. Since npm uses symlinks on these platforms,
14+// that means that the first run will invoke this file and subsequent
15+// runs will call the elm binary directly.
1116//
12−// This file pretends to be the downloaded binary. It then downloads
13−// the real binary over itself. So in that case, the first run would
14−// also make an HTTPS request to fetch the real binary.
17+// On Windows, we must download a file named elm.exe for it to run properly.
18+// Instead of symlinks, npm creates two files:
19+//
20+// - node_modules/.bin/elm (a bash file)
21+// - node_modules/.bin/elm.cmd (a batch file)
22+//
23+// Both files specifically invoke `node` to run the file listed at package.bin,
24+// so there is no way around instantiating node for no reason on Windows. So
25+// the existsSync check is needed so that it is not downloaded more than once.
1526
1627
28+// figure out where to put the binary (calls path.resolve() to get path separators right on Windows)
29+//
30+var binaryPath = path.resolve(__dirname, 'elm') + (process.platform === 'win32' ? '.exe' : '');
31+
32+// Run the command directly if possible, otherwise download and then run.
33+// This check is important for Windows where this file will be run all the time.
34+//
35+if (process.platform === 'win32')
36+{
37+ fs.existsSync(binaryPath)
38+ ? runCommand()
39+ : require('../download.js')(runCommand);
40+}
41+else
42+{
43+ require('../download.js')(runCommand);
44+}
1745
18−// Make sure we get the right path even if we're executing from the symlinked
19−// node_modules/.bin/ executable
20−var pathToThisFile = fs.realpathSync(process.argv[1]);
2146
22−download(pathToThisFile, function() {
23− // Need double quotes and { shell: true } when there are spaces in the path on windows:
24− // https://github.com/nodejs/node/issues/7367#issuecomment-229721296
25− child_process
26− .spawn('"' + pathToThisFile + '"', process.argv.slice(2), { stdio: 'inherit', shell: true })
27− .on('exit', process.exit);
28−});
47+function runCommand()
48+{
49+ // Need double quotes and { shell: true } when there are spaces in the path on windows:
50+ // https://github.com/nodejs/node/issues/7367#issuecomment-229721296
51+ child_process
52+ .spawn('"' + binaryPath + '"', process.argv.slice(2), { stdio: 'inherit', shell: true })
53+ .on('exit', process.exit);
54+}
installers/npm/download.js+68−67
@@ -1,7 +1,7 @@
11var fs = require('fs');
22var package = require('./package.json');
3−var URL = require('url').URL;
4−var https = require('https');
3+var path = require('path');
4+var request = require('request');
55var zlib = require('zlib');
66
77
@@ -12,87 +12,72 @@ var zlib = require('zlib');
1212// called when --ignore-scripts is enabled. That's why install.js is so weird.
1313
1414
15−module.exports = function(destinationPath, callback)
15+module.exports = function(callback)
1616{
17+ // figure out URL of binary
1718 var version = package.version.replace(/^(\d+\.\d+\.\d+).*$/, '$1'); // turn '1.2.3-alpha' into '1.2.3'
18− var os = { 'darwin': 'mac', 'win32': 'windows', 'linux': 'linux' }[process.platform];
19− var arch = { 'x64': '64-bit', 'ia32': '32-bit' }[process.arch];
2019
21− download(
22− process.platform === 'win32' ? destinationPath + '.exe' : destinationPath,
23− 'https://github.com/elm/compiler/releases/download/' + version + '/binary-for-' + os + '-' + arch + '.gz',
24− callback
25− );
26−};
20+ var platform = {
21+ darwin_x64: 'mac-64-bit',
22+ darwin_arm64: 'mac-64-bit',
23+ win32_x64: 'windows-64-bit',
24+ linux_x64: 'linux-64-bit'
25+ }[process.platform + '_' + process.arch];
2726
27+ verifyPlatform(version, platform);
2828
29+ var url = 'https://github.com/elm/compiler/releases/download/' + version + '/binary-for-' + platform + '.gz';
2930
30−// DOWNLOAD
31+ reportDownload(version, url);
3132
33+ // figure out where to put the binary (calls path.resolve() to get path separators right on Windows)
34+ var binaryPath = path.resolve(__dirname, package.bin.elm) + (process.platform === 'win32' ? '.exe' : '');
3235
33−function download(destinationPath, url, callback)
34−{
35− requestWithRedirects(url, 10,
36− function(error) {
37− exitFailure(url, 'I ran into trouble while fetching ' + url + '\n\n' + error);
38− },
39− function(response) {
40− if (response.statusCode == 404)
41− {
42− exitFailure(url, 'I got a "404 Not Found" trying to download from the following URL:\n'
43− + url
44− + '\n\nThis may mean you are trying to install on an unsupported platform. (e.g. some 32-bit systems?)'
45− );
46− }
47−
48− response.on('error', function() {
49− exitFailure(url, 'Something went wrong while receiving the following URL:\n\n' + url);
50− });
51−
52− var gunzip = zlib.createGunzip().on('error', function(error) {
53− exitFailure(url, 'I ran into trouble decompressing the downloaded binary. It is saying:\n\n' + error);
54− });
55− var write = fs.createWriteStream(destinationPath, {
56− encoding: 'binary',
57− mode: 0o755
58− }).on('finish', callback).on('error', function(error) {
59− exitFailure(url, 'I had some trouble writing file to disk. It is saying:\n\n' + error);
60− });
61−
62− response.pipe(gunzip).pipe(write);
63− }
64− );
36+ // set up handler for request failure
37+ function reportDownloadFailure(error)
38+ {
39+ exitFailure(url,'Something went wrong while fetching the following URL:\n\n' + url + '\n\nIt is saying:\n\n' + error);
40+ }
41+
42+ // set up decompression pipe
43+ var gunzip = zlib.createGunzip().on('error', function(error) {
44+ exitFailure(url, 'I ran into trouble decompressing the downloaded binary. It is saying:\n\n' + error);
45+ });
46+
47+ // set up file write pipe
48+ var write = fs.createWriteStream(binaryPath, {
49+ encoding: 'binary',
50+ mode: 0o755
51+ }).on('finish', callback).on('error', function(error) {
52+ exitFailure(url, 'I had some trouble writing file to disk. It is saying:\n\n' + error);
53+ });
54+
55+ // put it all together
56+ request(url).on('error', reportDownloadFailure).pipe(gunzip).pipe(write);
6557}
6658
6759
6860
69−// HANDLE REDIRECTS
61+// VERIFY PLATFORM
7062
7163
72−function requestWithRedirects(url, maxRedirects, failure, success)
64+function verifyPlatform(version, platform)
7365{
74− var req = https.request(url);
75−
76− req.on('response', function(response) {
77− // Check for redirects
78−
79− var redirectUrl = new URL(response.headers['location'], new URL(url).origin).href;
80−
81− if (typeof redirectUrl === 'string' && response.statusCode >= 300 && response.statusCode < 400)
82− {
83− return (maxRedirects <= 0)
84− ? failure(new Error('followed 10 redirects and gave up'))
85− : requestWithRedirects(redirectUrl, maxRedirects - 1, failure, success);
86− }
87− else
88− {
89− return success(response);
90− }
91− });
92−
93− req.on('error', failure);
66+ if (platform) return;
9467
95− req.end();
68+ var situation = process.platform + '_' + process.arch;
69+ console.error(
70+ '-- ERROR -----------------------------------------------------------------------\n\n'
71+ + 'I am detecting that your computer (' + situation + ') may not be compatible with any\n'
72+ + 'of the official pre-built binaries.\n\n'
73+ + 'I recommend against using the npm installer for your situation. Check out the\n'
74+ + 'alternative installers at https://github.com/elm/compiler/releases/tag/' + version + '\n'
75+ + 'to see if there is something that will work better for you.\n\n'
76+ + 'From there I recommend asking for guidance on Slack or Discourse to find someone\n'
77+ + 'who can help with your specific situation.\n\n'
78+ + '--------------------------------------------------------------------------------\n'
79+ );
80+ process.exit(1);
9681}
9782
9883
@@ -111,3 +96,19 @@ function exitFailure(url, message)
11196 );
11297 process.exit(1);
11398}
99+
100+
101+
102+// REPORT DOWNLOAD
103+
104+
105+function reportDownload(version, url)
106+{
107+ console.log(
108+ '--------------------------------------------------------------------------------\n\n'
109+ + 'Downloading Elm ' + version + ' from GitHub.'
110+ + '\n\nNOTE: You can avoid npm entirely by downloading directly from:\n'
111+ + url + '\nAll this package does is download that file and put it somewhere.\n\n'
112+ + '--------------------------------------------------------------------------------\n'
113+ );
114+}
installers/npm/install.js+1−7
@@ -1,10 +1,4 @@
11
22var download = require('./download.js');
3−var package = require('./package.json');
4−var path = require('path');
53
6−
7−// get slashes right for Windows
8−var targetPath = path.resolve(__dirname, Object.values(package.bin)[0]);
9−
10−download(targetPath, function() {});
4+download(function() {});
installers/npm/package.json+6−7
@@ -1,6 +1,6 @@
11{
22 "name": "elm",
3− "version": "0.19.0-no-deps",
3+ "version": "0.19.1-5",
44 "description": "Installer for Elm: just downloads the binary into node_modules",
55 "preferGlobal": true,
66 "license": "BSD-3-Clause",
@@ -11,9 +11,9 @@
1111 "homepage": "https://github.com/elm/compiler/tree/master/installers/npm",
1212 "bugs": "https://github.com/elm/compiler/issues",
1313 "author": {
14− "name": "Richard Feldman",
15− "email": "richard.t.feldman@gmail.com",
16− "url": "https://github.com/rtfeldman"
14+ "name": "Evan Czaplicki",
15+ "email": "evan@elm-lang.org",
16+ "url": "https://github.com/evancz"
1717 },
1818 "engines": {
1919 "node": ">=7.0.0"
@@ -35,9 +35,8 @@
3535 "install",
3636 "installer"
3737 ],
38− "bin": {
39− "elm": "bin/elm"
40− },
38+ "bin": { "elm": "bin/elm" },
4139 "dependencies": {
40+ "request": "^2.88.0"
4241 }
4342}
installers/npm/troubleshooting.mdnew file+76
@@ -0,0 +1,76 @@
1+# Troubleshooting
2+
3+I very highly recommend asking for help on [the Elm slack](https://elmlang.herokuapp.com).
4+
5+There are a lot of things that can go wrong when installing software, and it can really help to have a second pair of eyes on your situation!
6+
7+This document goes through a couple options that may help you out.
8+
9+<br/>
10+
11+
12+## Can you skip npm entirely?
13+
14+The most reliable way to get Elm installed using the official installers for Mac and Windows [here][download].
15+
16+You can also download the binaries directly. On Linux, you could do it in the terminal like this:
17+
18+```bash
19+cd ~/Desktop/
20+curl -L -o elm.gz https://github.com/elm/compiler/releases/download/0.19.1/binary-for-linux-64-bit.gz
21+gunzip elm.gz # unzip the file
22+chmod +x elm # make the file executable
23+sudo mv elm /usr/local/bin/ # put the executable in a directory likely to be listed in your PATH variable
24+```
25+
26+If these exact commands do not work for you, you can try to do the same thing by hand.
27+
28+Read the section below on `PATH` variables if you are not sure what that is!
29+
30+[download]: https://github.com/elm/compiler/releases/tag/0.19.1
31+
32+<br/>
33+
34+
35+## Do you need to use npm for some reason?
36+
37+The company running npm has a list of common troubleshooting situations [here](https://npm.community/c/support/troubleshooting), but it may be better to just try to find your specific case on Stack Overflow. Often there are permissions issues where you may need to use `sudo` with some command.
38+
39+### Firewalls
40+
41+Some companies have a firewall.
42+
43+These companies usually have set the `HTTP_PROXY` or `HTTPS_PROXY` environment variable on your computer. This is more common with Windows computers.
44+
45+The result is that the request for `https://github.com/elm/compiler/releases/download/0.19.1/binary-for-windows-64-bit.gz` is being sent to a "proxy server" where they monitor traffic. Maybe they rule out certain domains, maybe they check data when it comes back from the actual URL, etc.
46+
47+It is probably best to ask someone about the situation on this, but you can test things out by temporarily using an alternate `HTTPS_PROXY` value with something like this:
48+
49+```
50+# Mac and Linux
51+HTTPS_PROXY=http://proxy.example.com npm install -g elm
52+
53+# Windows
54+set HTTPS_PROXY=http://proxy.example.com
55+npm install -g elm
56+```
57+
58+Check out [this document](https://www.npmjs.com/package/request#controlling-proxy-behaviour-using-environment-variables) for more information on how environment variables like `NO_PROXY`, `HTTP_PROXY`, and `HTTPS_PROXY` are handled by the npm.
59+
60+<br/>
61+
62+
63+## Do you know what a `PATH` variable is?
64+
65+When you run a command like `elm make src/Main.elm`, your computer starts by trying to find a file called `elm`.
66+
67+The `PATH` is a list of directories to search within. On Mac and Linux, you can see these directories by running:
68+
69+```
70+$ echo $PATH
71+/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin
72+```
73+
74+The are separated by `:` for some reason. So running `elm make src/Main.elm` starts by searching the `PATH` for files named `elm`. On my computer, it finds `/usr/local/bin/elm` and then can actually run the command.
75+
76+Is `elm` in one of the directories listed in your `PATH` variable? I recommend asking for help if you are in this scenario and unsure how to proceed.
installers/win/Nsisfile.nsi+16−16
@@ -75,7 +75,7 @@ Function un.onInit
7575FunctionEnd
7676
7777Function LaunchLink
78− ExecShell "open" "http://elm-lang.org/get-started"
78+ ExecShell "open" "https://guide.elm-lang.org"
7979FunctionEnd
8080
8181;--------------------------------
@@ -135,20 +135,20 @@ SectionEnd
135135
136136SectionGroup "Update system settings" SecGr
137137
138−Section "Associate with .elm files" SecAssoc
139−
140− SectionIn 1
141−
142− ; File associations
143− WriteRegStr HKCR ".elm" "" "elm"
144− WriteRegStr HKCR "elm" "" "Elm Source File"
145− WriteRegStr HKCR "elm\DefaultIcon" "" "$INSTDIR\file.ico"
146− ;WriteRegStr HKCR "elm\shell\open\command" "" '"$INSTDIR\bin\elm.exe" "%1"'
147−
148− ;Remember that we registered associations
149− WriteRegDWORD HKLM "${PRODUCT_DIR_REG_KEY}" Assocs 0x1
150−
151−SectionEnd
138+;Section "Associate with .elm files" SecAssoc
139+;
140+; SectionIn 1
141+;
142+; ; File associations
143+; WriteRegStr HKCR ".elm" "" "elm"
144+; WriteRegStr HKCR "elm" "" "Elm Source File"
145+; WriteRegStr HKCR "elm\DefaultIcon" "" "$INSTDIR\file.ico"
146+; WriteRegStr HKCR "elm\shell\open\command" "" '"$INSTDIR\bin\elm.exe" "%1"'
147+;
148+; ;Remember that we registered associations
149+; WriteRegDWORD HKLM "${PRODUCT_DIR_REG_KEY}" Assocs 0x1
150+;
151+;SectionEnd
152152
153153Section "Update the PATH environment variable" SecPath
154154
@@ -261,4 +261,4 @@ Section "Uninstall"
261261 ; Update environment variables
262262 SendMessage ${HWND_BROADCAST} ${WM_SETTINGCHANGE} 0 "STR:Environment" /TIMEOUT=5000
263263
264−SectionEnd
264+SectionEnd
installers/win/README.md+18−3
@@ -1,9 +1,24 @@
1−# Building Windows installer
1+# Installing on Windows
2+
3+The installer for Windows is available [here](https://guide.elm-lang.org/install.html).
4+
5+
6+<br/>
7+
8+## Uninstall
9+
10+First run the `C:\Program Files (x86)\Elm\0.19\uninstall.exe` file. This will remove Elm stuff from your `PATH`.
11+
12+Then remove the whole `C:\Users\<username>\AppData\Roaming\elm` directory. Elm caches some packages and build artifacts to reduce compile times and to help you work offline. Getting rid of this directory will clear that information out!
13+
14+<br/>
15+
16+## Building the Windows installer
217
318You will need the [NSIS installer](http://nsis.sourceforge.net/Download) to be installed.
419
520Once everything is installed, run something like this command:
621
7− make_installer.cmd 0.19
22+ make_installer.cmd 0.19.0
823
9−It will build an installer called `Elm-0.19-setup.exe`.
24+It will build an installer called `Elm-0.19.0-setup.exe`.
installers/win/file.icodeleted

Binary file not shown.

installers/win/inst.dat+1−2
@@ -2,6 +2,5 @@ SetOutPath "$INSTDIR\bin"
22File "${FILES_SOURCE_PATH}\bin\elm.exe"
33
44SetOutPath "$INSTDIR"
5−File "file.ico"
65File "updatepath.vbs"
7−File "removefrompath.vbs"
6+File "removefrompath.vbs"
installers/win/logo.ico

Binary file not shown.

installers/win/uninst.dat+1−2
@@ -1,7 +1,6 @@
11Delete "$INSTDIR\bin\elm.exe"
22RmDir "$INSTDIR\bin"
33
4−Delete "$INSTDIR\file.ico"
54Delete "$INSTDIR\updatepath.vbs"
65Delete "$INSTDIR\removefrompath.vbs"
7−RmDir "$INSTDIR"
6+RmDir "$INSTDIR"
installers/win/welcome.bmp

Binary file not shown.

reactor/src/Index.elm+20−15
@@ -64,7 +64,7 @@ decoder =
6464 (D.field "dirs" (D.list D.string))
6565 (D.field "files" (D.list fileDecoder))
6666 (D.field "readme" (D.nullable D.string))
67− (D.field "project" (D.nullable Project.decoder))
67+ (D.field "outline" (D.nullable Project.decoder))
6868 (D.field "exactDeps" (D.dict Version.decoder))
6969
7070
@@ -219,10 +219,10 @@ viewDeps exactDeps project =
219219 dependencies =
220220 case project of
221221 Project.Application info ->
222− List.map (viewDependency exactDeps) info.depsDirect
222+ List.map viewVersion info.depsDirect
223223
224224 Project.Package info ->
225− List.map (viewDependency exactDeps) info.deps
225+ List.map (viewConstraint exactDeps) info.deps
226226 in
227227 Skeleton.box
228228 { title = "Dependencies"
@@ -237,10 +237,10 @@ viewTestDeps exactDeps project =
237237 dependencies =
238238 case project of
239239 Project.Application info ->
240− List.map (viewDependency exactDeps) info.testDepsDirect
240+ List.map viewVersion info.testDepsDirect
241241
242242 Project.Package info ->
243− List.map (viewDependency exactDeps) info.testDeps
243+ List.map (viewConstraint exactDeps) info.testDeps
244244 in
245245 Skeleton.box
246246 { title = "Test Dependencies"
@@ -249,9 +249,22 @@ viewTestDeps exactDeps project =
249249 }
250250
251251
252−viewDependency : ExactDeps -> (Package.Name, vsn) -> List (Html msg)
253−viewDependency exactDeps (pkg, _) =
252+viewVersion : (Package.Name, Version.Version) -> List (Html msg)
253+viewVersion (pkg, version) =
254+ [ div [ style "float" "left" ]
255+ [ Icon.package
256+ , a [ href (toPackageUrl pkg version) ] [ text (Package.toString pkg) ]
257+ ]
258+ , div [ style "float" "right" ] [ text (Version.toString version) ]
259+ ]
260+
261+
262+viewConstraint : ExactDeps -> (Package.Name, constraint) -> List (Html msg)
263+viewConstraint exactDeps (pkg, _) =
254264 case Dict.get (Package.toString pkg) exactDeps of
265+ Just vsn ->
266+ viewVersion (pkg, vsn)
267+
255268 Nothing ->
256269 [ div [ style "float" "left" ]
257270 [ Icon.package
@@ -260,14 +273,6 @@ viewDependency exactDeps (pkg, _) =
260273 , div [ style "float" "right" ] [ text "???" ]
261274 ]
262275
263− Just version ->
264− [ div [ style "float" "left" ]
265− [ Icon.package
266− , a [ href (toPackageUrl pkg version) ] [ text (Package.toString pkg) ]
267− ]
268− , div [ style "float" "right" ] [ text (Version.toString version) ]
269− ]
270−
271276
272277toPackageUrl : Package.Name -> Version.Version -> String
273278toPackageUrl name version =
reactor/src/Index/Navigator.elm+1−1
@@ -19,7 +19,7 @@ view root dirs =
1919 , style "align-items" "center"
2020 , style "height" "40px"
2121 ]
22− (makeLinks root dirs "/" [])
22+ (makeLinks root dirs "" [])
2323
2424
2525makeLinks : String -> List String -> String -> List (Html msg) -> List (Html msg)
roadmap.mdnew file+29
@@ -0,0 +1,29 @@
1+# Roadmap
2+
3+If you like what you see now, that's pretty much what Elm is going to be for a while.
4+
5+I'm currently doing some exploratory work with compiler techniques and targets, but it is still too early to tell which parts of that might work out. I know many readers take "exploring X" as a promise that "X will definitely happen", so I want to be careful in setting expectations low since there is still so much uncertainty in the work. So while there is no real news to share at this point, I can give some expectations about future stability of Elm:
6+
7+**If this exploratory work goes well**, even in the wildest version of success, I wouldn't expect the language or core packages to change very much. Maybe two or three years down the line it could reveal something that'd be good to fix up, but I don't really foresee notable changes right now.
8+
9+**If this exploratory work does not work out**, I have some more conservative projects that are good ideas that I want to circle back to at some point. Things like:
10+
11+- add a constrained type variable `eq` to get rid of the runtime error for `(==)` on functions
12+- try to integrate `elm test` so it can run only tests that changed
13+- try to get `elm format` using the latest parsing infrastructure so it's not a perf bottleneck during development anymore
14+- do another round on perf because I have one last idea that can squeeze out a bit more speed
15+
16+These are all nice quality of life things, but with 0.19.0 and 0.19.1 taking so long, I got pretty burnt out on "incremental improvements that are good ideas, but take a very long time and aren't very exciting to non-Elm users." Without getting too into the details, I really needed to change things up before returning to these particular ideas.
17+
18+If someone has a security issue from the compiler or core libraries, please DM me about it on the Elm Slack. Outside of security issues, I think capacity for more discretionary changes will increase once the lessons from the compiler explorations become more clear. Hopefully the discussion [here](https://discourse.elm-lang.org/t/costs-funding-in-open-source-languages/5722) clarifies the thinking on these capacity questions a bit.
19+
20+<br>
21+<br>
22+
23+**Taking a step back**, I have found that working in this looser style has produced a high baseline of quality, and I think that is an important part of Elm. For example, all the error message work in Elm began as a project to implement the `--report=json` flag. That work happened to reveal some cool ideas on improving error messages, and if I had been using a rigid roadmap, I might have skipped those ideas to meet the publicly-stated arbitrary deadline. We'd have a clearer roadmap, but error messages no different than other type-inferred languages.
24+
25+So I think having more flexibility in planning is a competitive advantage for Elm in certain ways, but it is obviously a trade off that does not work for everyone. If someone needs more certainty, I generally recommend looking into other languages to see if they have a balance that works better for their needs. For example, languages made by big corporations are generally "less risky" on things like this, but I think you see the fruits of that kind of process in the design decisions as well. Trade offs!
26+
27+Anyway, like I said at the beginning, if you like what you see now, that's what it's going to be for a while. Even in the best case scenario with my current explorations!
28+
29+I hope this is helpful information, and I hope you have a good experience with Elm, even if you ultimately find a different language that works better for you!
terminal/src/Terminal/Args.hs → terminal/impl/Terminal.hsrenamed+28−25
@@ -1,8 +1,7 @@
1−module Terminal.Args
2− ( simple
3− , Interface(..)
1+module Terminal
2+ ( app
3+ , Command(..)
44 , Summary(..)
5− , complex
65 , Flags, noFlags, flags, (|--)
76 , Flag, flag, onOff
87 , Parser(..)
@@ -26,17 +25,17 @@ import qualified Text.PrettyPrint.ANSI.Leijen as P
2625import qualified Text.Read as Read
2726
2827import qualified Elm.Version as V
29−import Terminal.Args.Internal
30−import qualified Terminal.Args.Chomp as Chomp
31−import qualified Terminal.Args.Error as Error
28+import Terminal.Internal
29+import qualified Terminal.Chomp as Chomp
30+import qualified Terminal.Error as Error
3231
3332
3433
35−-- GET
34+-- COMMAND
3635
3736
38−simple :: String -> P.Doc -> Args args -> Flags flags -> (args -> flags -> IO ()) -> IO ()
39−simple details example args_ flags_ callback =
37+_command :: String -> P.Doc -> Args args -> Flags flags -> (args -> flags -> IO ()) -> IO ()
38+_command details example args_ flags_ callback =
4039 do setLocaleEncoding utf8
4140 argStrings <- Env.getArgs
4241 case argStrings of
@@ -57,34 +56,38 @@ simple details example args_ flags_ callback =
5756 Error.exitWithError err
5857
5958
60−complex :: P.Doc -> P.Doc -> [Interface] -> IO ()
61−complex intro outro interfaces =
59+
60+-- APP
61+
62+
63+app :: P.Doc -> P.Doc -> [Command] -> IO ()
64+app intro outro commands =
6265 do setLocaleEncoding utf8
6366 argStrings <- Env.getArgs
6467 case argStrings of
6568 [] ->
66− Error.exitWithOverview intro outro interfaces
69+ Error.exitWithOverview intro outro commands
6770
6871 ["--help"] ->
69− Error.exitWithOverview intro outro interfaces
72+ Error.exitWithOverview intro outro commands
7073
7174 ["--version"] ->
7275 do hPutStrLn stdout (V.toChars V.compiler)
7376 Exit.exitSuccess
7477
7578 command : chunks ->
76− do case List.find (\iface -> toName iface == command) interfaces of
79+ do case List.find (\cmd -> toName cmd == command) commands of
7780 Nothing ->
78− Error.exitWithUnknown command (map toName interfaces)
81+ Error.exitWithUnknown command (map toName commands)
7982
80− Just (Interface _ _ details example args_ flags_ callback) ->
83+ Just (Command _ _ details example args_ flags_ callback) ->
8184 if elem "--help" chunks then
8285 Error.exitWithHelp (Just command) details example args_ flags_
8386
8487 else
8588 case snd $ Chomp.chomp Nothing chunks args_ flags_ of
86− Right (argsValue, flagValue) ->
87− callback argsValue flagValue
89+ Right (argsValue, flagsValue) ->
90+ callback argsValue flagsValue
8891
8992 Left err ->
9093 Error.exitWithError err
@@ -159,21 +162,21 @@ findIndex index point chunks =
159162 findIndex (index + 1) point cs
160163
161164
162−_complexSuggest :: [Interface] -> Int -> [String] -> IO [String]
163−_complexSuggest interfaces index strings =
165+_complexSuggest :: [Command] -> Int -> [String] -> IO [String]
166+_complexSuggest commands index strings =
164167 case strings of
165168 [] ->
166− return (map toName interfaces)
169+ return (map toName commands)
167170
168171 command : chunks ->
169172 if index == 1 then
170− return (filter (List.isPrefixOf command) (map toName interfaces))
173+ return (filter (List.isPrefixOf command) (map toName commands))
171174 else
172− case List.find (\iface -> toName iface == command) interfaces of
175+ case List.find (\cmd -> toName cmd == command) commands of
173176 Nothing ->
174177 return []
175178
176− Just (Interface _ _ _ _ args_ flags_ _) ->
179+ Just (Command _ _ _ _ args_ flags_ _) ->
177180 fst $ Chomp.chomp (Just (index-1)) chunks args_ flags_
178181
179182
terminal/src/Terminal/Args/Chomp.hs → terminal/impl/Terminal/Chomp.hsrenamed+4−5
@@ -1,6 +1,5 @@
1−{-# LANGUAGE GADTs #-}
2−{-# LANGUAGE Rank2Types #-}
3−module Terminal.Args.Chomp
1+{-# LANGUAGE GADTs, Rank2Types #-}
2+module Terminal.Chomp
43 ( chomp
54 )
65 where
@@ -8,8 +7,8 @@ module Terminal.Args.Chomp
87
98import qualified Data.List as List
109
11−import Terminal.Args.Error
12−import Terminal.Args.Internal
10+import Terminal.Error
11+import Terminal.Internal
1312
1413
1514
terminal/src/Terminal/Args/Error.hs → terminal/impl/Terminal/Error.hsrenamed+28−18
@@ -1,6 +1,5 @@
1−{-# LANGUAGE GADTs #-}
2−{-# LANGUAGE OverloadedStrings #-}
3−module Terminal.Args.Error
1+{-# LANGUAGE GADTs, OverloadedStrings #-}
2+module Terminal.Error
43 ( Error(..)
54 , ArgError(..)
65 , FlagError(..)
@@ -24,7 +23,7 @@ import System.IO (hPutStrLn, stderr)
2423import qualified Text.PrettyPrint.ANSI.Leijen as P
2524
2625import Reporting.Suggest as Suggest
27−import Terminal.Args.Internal
26+import Terminal.Internal
2827
2928
3029
@@ -187,22 +186,22 @@ flagsToDocs flags docs =
187186-- OVERVIEW
188187
189188
190−exitWithOverview :: P.Doc -> P.Doc -> [Interface] -> IO a
191−exitWithOverview intro outro interfaces =
189+exitWithOverview :: P.Doc -> P.Doc -> [Command] -> IO a
190+exitWithOverview intro outro commands =
192191 do exeName <- getExeName
193192 exitSuccess
194193 [ intro
195194 , "The most common commands are:"
196− , P.indent 4 $ stack $ Maybe.mapMaybe (toSummary exeName) interfaces
195+ , P.indent 4 $ stack $ Maybe.mapMaybe (toSummary exeName) commands
197196 , "There are a bunch of other commands as well though. Here is a full list:"
198− , P.indent 4 $ P.dullcyan $ toCommandList exeName interfaces
197+ , P.indent 4 $ P.dullcyan $ toCommandList exeName commands
199198 , "Adding the --help flag gives a bunch of additional details about each one."
200199 , outro
201200 ]
202201
203202
204−toSummary :: String -> Interface -> Maybe P.Doc
205−toSummary exeName (Interface name summary _ _ (Args args) _ _) =
203+toSummary :: String -> Command -> Maybe P.Doc
204+toSummary exeName (Command name summary _ _ (Args args) _ _) =
206205 case summary of
207206 Uncommon ->
208207 Nothing
@@ -215,10 +214,10 @@ toSummary exeName (Interface name summary _ _ (Args args) _ _) =
215214 ]
216215
217216
218−toCommandList :: String -> [Interface] -> P.Doc
219−toCommandList exeName interfaces =
217+toCommandList :: String -> [Command] -> P.Doc
218+toCommandList exeName commands =
220219 let
221− names = map toName interfaces
220+ names = map toName commands
222221 width = maximum (map length names)
223222
224223 toExample name =
@@ -272,13 +271,24 @@ exitWithError err =
272271 BadArgs argErrors ->
273272 case argErrors of
274273 [] ->
275− error "TODO no possible args"
274+ return
275+ [ reflow $ "I was not expecting any arguments for this command."
276+ , reflow $ "Try removing them?"
277+ ]
276278
277279 [(_args, argError)] ->
278280 argErrorToDocs argError
279281
280282 _:_:_ ->
281− error "TODO show possible arg configurations"
283+ argErrorToDocs $ head $ List.sortOn toArgErrorRank (map snd argErrors)
284+
285+
286+toArgErrorRank :: ArgError -> Int -- lower is better
287+toArgErrorRank err =
288+ case err of
289+ ArgBad _ _ -> 0
290+ ArgMissing _ -> 1
291+ ArgExtras _ -> 2
282292
283293
284294toGreen :: String -> P.Doc
@@ -318,10 +328,10 @@ argErrorToDocs argError =
318328 return
319329 [ "I am having trouble with this argument:"
320330 , P.indent 4 $ toRed string
321− , P.fillSep
331+ , P.fillSep $
322332 ["It","is","supposed","to","be","a"
323− ,toYellow (toToken tipe),"value,","like","this:"
324− ]
333+ ,toYellow (toToken tipe),"value,","like"
334+ ] ++ if length examples == 1 then ["this:"] else ["one","of","these:"]
325335 , P.indent 4 $ P.green $ P.vcat $ map P.text examples
326336 ]
327337
terminal/src/Terminal/Args/Helpers.hs → terminal/impl/Terminal/Helpers.hsrenamed+20−7
@@ -1,5 +1,5 @@
11{-# LANGUAGE OverloadedStrings #-}
2−module Terminal.Args.Helpers
2+module Terminal.Helpers
33 ( version
44 , elmFile
55 , package
@@ -14,12 +14,13 @@ import qualified Data.Map as Map
1414import qualified Data.Utf8 as Utf8
1515import qualified System.FilePath as FP
1616
17−import Terminal.Args (Parser(..))
17+import Terminal (Parser(..))
1818import qualified Deps.Registry as Registry
1919import qualified Elm.Package as Pkg
2020import qualified Elm.Version as V
2121import qualified Parse.Primitives as P
2222import qualified Stuff
23+import qualified Reporting.Suggest as Suggest
2324
2425
2526
@@ -117,8 +118,17 @@ parsePackage chars =
117118
118119
119120suggestPackages :: String -> IO [String]
120−suggestPackages _ =
121− return []
121+suggestPackages given =
122+ do cache <- Stuff.getPackageCache
123+ maybeRegistry <- Registry.read cache
124+ return $
125+ case maybeRegistry of
126+ Nothing ->
127+ []
128+
129+ Just (Registry.Registry _ versions) ->
130+ filter (List.isPrefixOf given) $
131+ map Pkg.toChars (Map.keys versions)
122132
123133
124134examplePackages :: String -> IO [String]
@@ -128,8 +138,11 @@ examplePackages given =
128138 return $
129139 case maybeRegistry of
130140 Nothing ->
131− []
141+ [ "elm/json"
142+ , "elm/http"
143+ , "elm/random"
144+ ]
132145
133146 Just (Registry.Registry _ versions) ->
134− filter (List.isPrefixOf given) $
135− map Pkg.toChars (Map.keys versions)
147+ map Pkg.toChars $ take 4 $
148+ Suggest.sort given Pkg.toChars (Map.keys versions)
terminal/src/Terminal/Args/Internal.hs → terminal/impl/Terminal/Internal.hsrenamed+8−8
@@ -1,6 +1,6 @@
11{-# LANGUAGE GADTs #-}
2−module Terminal.Args.Internal
3− ( Interface(..)
2+module Terminal.Internal
3+ ( Command(..)
44 , toName
55 , Summary(..)
66 , Flags(..)
@@ -17,11 +17,11 @@ import Text.PrettyPrint.ANSI.Leijen (Doc)
1717
1818
1919
20−-- INTERFACE
20+-- COMMAND
2121
2222
23−data Interface where
24− Interface
23+data Command where
24+ Command
2525 :: String
2626 -> Summary
2727 -> String
@@ -29,11 +29,11 @@ data Interface where
2929 -> Args args
3030 -> Flags flags
3131 -> (args -> flags -> IO ())
32− -> Interface
32+ -> Command
3333
3434
35−toName :: Interface -> String
36−toName (Interface name _ _ _ _ _ _) =
35+toName :: Command -> String
36+toName (Command name _ _ _ _ _ _) =
3737 name
3838
3939
terminal/src/Bump.hs+3−1
@@ -8,6 +8,7 @@ module Bump
88import qualified Data.List as List
99import qualified Data.NonEmptyList as NE
1010
11+import qualified BackgroundWriter as BW
1112import qualified Build
1213import qualified Deps.Bump as Bump
1314import qualified Deps.Diff as Diff
@@ -135,7 +136,8 @@ suggestVersion (Env root cache manager _ outline@(Outline.PkgOutline pkg _ _ vsn
135136generateDocs :: FilePath -> Outline.PkgOutline -> Task.Task Exit.Bump Docs.Documentation
136137generateDocs root (Outline.PkgOutline _ _ _ _ exposed _ _ _) =
137138 do details <-
138− Task.eio Exit.BumpBadDetails $ Details.load Reporting.silent root
139+ Task.eio Exit.BumpBadDetails $ BW.withScope $ \scope ->
140+ Details.load Reporting.silent scope root
139141
140142 case Outline.flattenExposed exposed of
141143 [] ->
terminal/src/Develop.hs+23−9
@@ -20,6 +20,7 @@ import Snap.Core hiding (path)
2020import Snap.Http.Server
2121import Snap.Util.FileServe
2222
23+import qualified BackgroundWriter as BW
2324import qualified Build
2425import qualified Elm.Details as Details
2526import qualified Develop.Generate.Help as Help
@@ -138,7 +139,7 @@ serveElm :: FilePath -> Snap ()
138139serveElm path =
139140 do guard (takeExtension path == ".elm")
140141 modifyResponse (setContentType "text/html")
141− result <- liftIO $ Task.run $ compile path
142+ result <- liftIO $ compile path
142143 case result of
143144 Right builder ->
144145 writeBuilder builder
@@ -148,14 +149,20 @@ serveElm path =
148149 Exit.toJson $ Exit.reactorToReport exit
149150
150151
151−compile :: FilePath -> Task.Task Exit.Reactor B.Builder
152+compile :: FilePath -> IO (Either Exit.Reactor B.Builder)
152153compile path =
153− do root <- Task.mio Exit.ReactorNoOutline Stuff.findRoot
154− details <- Task.eio Exit.ReactorBadDetails $ Details.load Reporting.silent root
155− artifacts <- Task.eio Exit.ReactorBadBuild $ Build.fromMains Reporting.silent root details (NE.List path [])
156− javascript <- Task.mapError Exit.ReactorBadGenerate $ Generate.dev root details artifacts
157− let (NE.List name _) = Build.getMainNames artifacts
158− return $ Html.sandwich name javascript
154+ do maybeRoot <- Stuff.findRoot
155+ case maybeRoot of
156+ Nothing ->
157+ return $ Left $ Exit.ReactorNoOutline
158+
159+ Just root ->
160+ BW.withScope $ \scope -> Stuff.withRootLock root $ Task.run $
161+ do details <- Task.eio Exit.ReactorBadDetails $ Details.load Reporting.silent scope root
162+ artifacts <- Task.eio Exit.ReactorBadBuild $ Build.fromPaths Reporting.silent root details (NE.List path [])
163+ javascript <- Task.mapError Exit.ReactorBadGenerate $ Generate.dev root details artifacts
164+ let (NE.List name _) = Build.getRootNames artifacts
165+ return $ Html.sandwich name javascript
159166
160167
161168
@@ -211,13 +218,16 @@ mimeTypeDict =
211218 , ".m3u" ==> "audio/x-mpegurl"
212219 , ".mov" ==> "video/quicktime"
213220 , ".mp3" ==> "audio/mpeg"
221+ , ".mp4" ==> "video/mp4"
214222 , ".mpeg" ==> "video/mpeg"
215223 , ".mpg" ==> "video/mpeg"
216224 , ".ogg" ==> "application/ogg"
225+ , ".otf" ==> "font/otf"
217226 , ".pac" ==> "application/x-ns-proxy-autoconfig"
218227 , ".pdf" ==> "application/pdf"
219228 , ".png" ==> "image/png"
220229 , ".qt" ==> "video/quicktime"
230+ , ".sfnt" ==> "font/sfnt"
221231 , ".sig" ==> "application/pgp-signature"
222232 , ".spl" ==> "application/futuresplash"
223233 , ".svg" ==> "image/svg+xml"
@@ -228,12 +238,16 @@ mimeTypeDict =
228238 , ".tbz" ==> "application/x-bzip-compressed-tar"
229239 , ".text" ==> "text/plain"
230240 , ".tgz" ==> "application/x-tgz"
231− , ".ttf" ==> "application/x-font-truetype"
241+ , ".ttf" ==> "font/ttf"
232242 , ".txt" ==> "text/plain"
233243 , ".wav" ==> "audio/x-wav"
234244 , ".wax" ==> "audio/x-ms-wax"
245+ , ".webm" ==> "video/webm"
246+ , ".webp" ==> "image/webp"
235247 , ".wma" ==> "audio/x-ms-wma"
236248 , ".wmv" ==> "video/x-ms-wmv"
249+ , ".woff" ==> "font/woff"
250+ , ".woff2" ==> "font/woff2"
237251 , ".xbm" ==> "image/x-xbitmap"
238252 , ".xml" ==> "text/xml"
239253 , ".xpm" ==> "image/x-xpixmap"
terminal/src/Develop/Generate/Index.hs+51−1
@@ -9,13 +9,19 @@ module Develop.Generate.Index
99import Control.Monad (filterM)
1010import qualified Data.ByteString.Builder as B
1111import qualified Data.List as List
12+import qualified Data.Map as Map
1213import qualified System.Directory as Dir
1314import System.FilePath ((</>), splitDirectories, takeExtension)
1415
16+import qualified BackgroundWriter as BW
1517import qualified Develop.Generate.Help as Help
18+import qualified Elm.Details as Details
1619import qualified Elm.Outline as Outline
20+import qualified Elm.Package as Pkg
21+import qualified Elm.Version as V
1722import qualified Json.Encode as E
1823import Json.Encode ((==>))
24+import qualified Reporting
1925import qualified Stuff
2026
2127
@@ -41,6 +47,7 @@ data Flags =
4147 , _files :: [File]
4248 , _readme :: Maybe String
4349 , _outline :: Maybe Outline.Outline
50+ , _exactDeps :: Map.Map Pkg.Name V.Version
4451 }
4552
4653
@@ -63,6 +70,7 @@ getFlags pwd =
6370 files <- getFiles pwd contents
6471 readme <- getReadme pwd
6572 outline <- getOutline
73+ exactDeps <- getExactDeps outline
6674 return $
6775 Flags
6876 { _root = root
@@ -71,6 +79,7 @@ getFlags pwd =
7179 , _files = files
7280 , _readme = readme
7381 , _outline = outline
82+ , _exactDeps = exactDeps
7483 }
7584
7685
@@ -135,11 +144,51 @@ getOutline =
135144
136145
137146
147+-- GET EXACT DEPS
148+
149+
150+-- TODO revamp how `elm reactor` works so that this can go away.
151+-- I am trying to "just get it working again" at this point though.
152+--
153+getExactDeps :: Maybe Outline.Outline -> IO (Map.Map Pkg.Name V.Version)
154+getExactDeps maybeOutline =
155+ case maybeOutline of
156+ Nothing ->
157+ return Map.empty
158+
159+ Just outline ->
160+ case outline of
161+ Outline.App _ ->
162+ return Map.empty
163+
164+ Outline.Pkg _ ->
165+ do maybeRoot <- Stuff.findRoot
166+ case maybeRoot of
167+ Nothing ->
168+ return Map.empty
169+
170+ Just root ->
171+ BW.withScope $ \scope ->
172+ do result <- Details.load Reporting.silent scope root
173+ case result of
174+ Left _ ->
175+ return Map.empty
176+
177+ Right (Details.Details _ validOutline _ _ _ _) ->
178+ case validOutline of
179+ Details.ValidApp _ ->
180+ return Map.empty
181+
182+ Details.ValidPkg _ _ solution ->
183+ return solution
184+
185+
186+
138187-- ENCODE
139188
140189
141190encode :: Flags -> E.Value
142−encode (Flags root pwd dirs files readme outline) =
191+encode (Flags root pwd dirs files readme outline exactDeps) =
143192 E.object
144193 [ "root" ==> encodeFilePath root
145194 , "pwd" ==> E.list encodeFilePath pwd
@@ -147,6 +196,7 @@ encode (Flags root pwd dirs files readme outline) =
147196 , "files" ==> E.list encodeFile files
148197 , "readme" ==> maybe E.null E.chars readme
149198 , "outline" ==> maybe E.null Outline.encode outline
199+ , "exactDeps" ==> E.dict Pkg.toJsonString V.encode exactDeps
150200 ]
151201
152202
terminal/src/Develop/StaticFiles/Build.hs+7−5
@@ -13,12 +13,13 @@ import qualified Data.NonEmptyList as NE
1313import qualified System.Directory as Dir
1414import System.FilePath ((</>))
1515
16−import qualified Reporting.Task as Task
16+import qualified BackgroundWriter as BW
1717import qualified Build
1818import qualified Elm.Details as Details
1919import qualified Generate
2020import qualified Reporting
2121import qualified Reporting.Exit as Exit
22+import qualified Reporting.Task as Task
2223
2324
2425
@@ -36,17 +37,18 @@ readAsset path =
3637
3738buildReactorFrontEnd :: IO BS.ByteString
3839buildReactorFrontEnd =
40+ BW.withScope $ \scope ->
3941 Dir.withCurrentDirectory "reactor" $
4042 do root <- Dir.getCurrentDirectory
4143 runTaskUnsafe $
42− do details <- Task.eio Exit.ReactorBadDetails $ Details.load Reporting.silent root
43− artifacts <- Task.eio Exit.ReactorBadBuild $ Build.fromMains Reporting.silent root details mains
44+ do details <- Task.eio Exit.ReactorBadDetails $ Details.load Reporting.silent scope root
45+ artifacts <- Task.eio Exit.ReactorBadBuild $ Build.fromPaths Reporting.silent root details paths
4446 javascript <- Task.mapError Exit.ReactorBadGenerate $ Generate.prod root details artifacts
4547 return (LBS.toStrict (B.toLazyByteString javascript))
4648
4749
48−mains :: NE.List FilePath
49−mains =
50+paths :: NE.List FilePath
51+paths =
5052 NE.List
5153 ("src" </> "NotFound.elm")
5254 [ "src" </> "Errors.elm"
terminal/src/Diff.hs+4−3
@@ -13,6 +13,7 @@ import qualified Data.Maybe as Maybe
1313import qualified Data.Name as Name
1414import qualified Data.NonEmptyList as NE
1515
16+import qualified BackgroundWriter as BW
1617import qualified Build
1718import Deps.Diff (PackageChanges(..), ModuleChanges(..), Changes(..))
1819import qualified Deps.Diff as DD
@@ -171,14 +172,14 @@ generateDocs (Env maybeRoot _ _ _) =
171172
172173 Just root ->
173174 do details <-
174− Task.eio Exit.DiffBadDetails $
175− Details.load Reporting.silent root
175+ Task.eio Exit.DiffBadDetails $ BW.withScope $ \scope ->
176+ Details.load Reporting.silent scope root
176177
177178 case Details._outline details of
178179 Details.ValidApp _ ->
179180 Task.throw $ Exit.DiffApplication
180181
181− Details.ValidPkg _ exposed ->
182+ Details.ValidPkg _ exposed _ ->
182183 case exposed of
183184 [] ->
184185 Task.throw $ Exit.DiffNoExposed
terminal/src/Init.hs+1−1
@@ -90,7 +90,7 @@ init =
9090 in
9191 do Dir.createDirectoryIfMissing True "src"
9292 Outline.write "." $ Outline.App $
93− Outline.AppOutline V.compiler (NE.List "src" []) directs indirects Map.empty Map.empty
93+ Outline.AppOutline V.compiler (NE.List (Outline.RelativeSrcDir "src") []) directs indirects Map.empty Map.empty
9494 putStrLn "Okay, I created it. Now read that link!"
9595 return (Right ())
9696
terminal/src/Install.hs+17−15
@@ -10,6 +10,7 @@ import Data.Map ((!))
1010import qualified Data.Map as Map
1111import qualified Data.Map.Merge.Strict as Map
1212
13+import qualified BackgroundWriter as BW
1314import qualified Deps.Solver as Solver
1415import qualified Deps.Registry as Registry
1516import qualified Elm.Constraint as C
@@ -55,11 +56,11 @@ run args () =
5556 case oldOutline of
5657 Outline.App outline ->
5758 do changes <- makeAppPlan env pkg outline
58− attemptChanges root env pkg oldOutline V.toChars changes
59+ attemptChanges root env oldOutline V.toChars changes
5960
6061 Outline.Pkg outline ->
6162 do changes <- makePkgPlan env pkg outline
62− attemptChanges root env pkg oldOutline C.toChars changes
63+ attemptChanges root env oldOutline C.toChars changes
6364
6465
6566
@@ -76,14 +77,14 @@ data Changes vsn
7677type Task = Task.Task Exit.Install
7778
7879
79−attemptChanges :: FilePath -> Solver.Env -> Pkg.Name -> Outline.Outline -> (a -> String) -> Changes a -> Task ()
80−attemptChanges root env pkg oldOutline toChars changes =
80+attemptChanges :: FilePath -> Solver.Env -> Outline.Outline -> (a -> String) -> Changes a -> Task ()
81+attemptChanges root env oldOutline toChars changes =
8182 case changes of
8283 AlreadyInstalled ->
8384 Task.io $ putStrLn "It is already installed!"
8485
8586 PromoteIndirect newOutline ->
86− attemptChangesHelp root env pkg oldOutline newOutline $
87+ attemptChangesHelp root env oldOutline newOutline $
8788 D.vcat
8889 [ D.fillSep
8990 ["I","found","it","in","your","elm.json","file,"
@@ -96,7 +97,7 @@ attemptChanges root env pkg oldOutline toChars changes =
9697 ]
9798
9899 PromoteTest newOutline ->
99− attemptChangesHelp root env pkg oldOutline newOutline $
100+ attemptChangesHelp root env oldOutline newOutline $
100101 D.vcat
101102 [ D.fillSep
102103 ["I","found","it","in","your","elm.json","file,"
@@ -113,7 +114,7 @@ attemptChanges root env pkg oldOutline toChars changes =
113114 widths = Map.foldrWithKey (widen toChars) (Widths 0 0 0) changeDict
114115 changeDocs = Map.foldrWithKey (addChange toChars widths) (Docs [] [] []) changeDict
115116 in
116− attemptChangesHelp root env pkg oldOutline newOutline $ D.vcat $
117+ attemptChangesHelp root env oldOutline newOutline $ D.vcat $
117118 [ "Here is my plan:"
118119 , viewChangeDocs changeDocs
119120 , ""
@@ -121,14 +122,15 @@ attemptChanges root env pkg oldOutline toChars changes =
121122 ]
122123
123124
124−attemptChangesHelp :: FilePath -> Solver.Env -> Pkg.Name -> Outline.Outline -> Outline.Outline -> D.Doc -> Task ()
125−attemptChangesHelp root env pkg oldOutline newOutline question =
126− Task.eio (\_ -> Exit.InstallHasBadDetails pkg (Outline.encode newOutline)) $
125+attemptChangesHelp :: FilePath -> Solver.Env -> Outline.Outline -> Outline.Outline -> D.Doc -> Task ()
126+attemptChangesHelp root env oldOutline newOutline question =
127+ Task.eio Exit.InstallBadDetails $
128+ BW.withScope $ \scope ->
127129 do approved <- Reporting.ask question
128130 if approved
129131 then
130132 do Outline.write root newOutline
131− result <- Details.verifyInstall root env newOutline
133+ result <- Details.verifyInstall scope root env newOutline
132134 case result of
133135 Left exit ->
134136 do Outline.write root oldOutline
@@ -196,10 +198,10 @@ makeAppPlan (Solver.Env cache _ connection registry) pkg outline@(Outline.AppOut
196198 return (Changes (detectChanges old new) (Outline.App app))
197199
198200 Solver.NoSolution ->
199− Task.throw Exit.InstallNoOnlineSolution
201+ Task.throw (Exit.InstallNoOnlineAppSolution pkg)
200202
201203 Solver.NoOfflineSolution ->
202− Task.throw Exit.InstallNoOfflineSolution
204+ Task.throw (Exit.InstallNoOfflineAppSolution pkg)
203205
204206 Solver.Err exit ->
205207 Task.throw (Exit.InstallHadSolverTrouble exit)
@@ -252,10 +254,10 @@ makePkgPlan (Solver.Env cache _ connection registry) pkg outline@(Outline.PkgOut
252254 }
253255
254256 Solver.NoSolution ->
255− Task.throw Exit.InstallNoOnlineSolution
257+ Task.throw (Exit.InstallNoOnlinePkgSolution pkg)
256258
257259 Solver.NoOfflineSolution ->
258− Task.throw Exit.InstallNoOfflineSolution
260+ Task.throw (Exit.InstallNoOfflinePkgSolution pkg)
259261
260262 Solver.Err exit ->
261263 Task.throw (Exit.InstallHadSolverTrouble exit)
terminal/src/Main.hs+22−22
@@ -12,8 +12,8 @@ import Text.PrettyPrint.ANSI.Leijen ((<>))
1212import Text.Read (readMaybe)
1313
1414import qualified Elm.Version as V
15−import Terminal.Args
16−import Terminal.Args.Helpers
15+import Terminal
16+import Terminal.Helpers
1717
1818import qualified Bump
1919import qualified Develop
@@ -31,7 +31,7 @@ import qualified Repl
3131
3232main :: IO ()
3333main =
34− complex intro outro
34+ Terminal.app intro outro
3535 [ repl
3636 , init
3737 , reactor
@@ -72,7 +72,7 @@ outro =
7272-- INIT
7373
7474
75−init :: Interface
75+init :: Terminal.Command
7676init =
7777 let
7878 summary =
@@ -87,14 +87,14 @@ init =
8787 "It will ask permission to create an elm.json file, the one thing common\
8888 \ to all Elm projects. It also provides a link explaining what to do from there."
8989 in
90− Interface "init" (Common summary) details example noArgs noFlags Init.run
90+ Terminal.Command "init" (Common summary) details example noArgs noFlags Init.run
9191
9292
9393
9494-- REPL
9595
9696
97−repl :: Interface
97+repl :: Terminal.Command
9898repl =
9999 let
100100 summary =
@@ -115,7 +115,7 @@ repl =
115115 |-- flag "interpreter" interpreter "Path to a alternate JS interpreter, like node or nodejs."
116116 |-- onOff "no-colors" "Turn off the colors in the REPL. This can help if you are having trouble reading the values. Some terminals use a custom color scheme that diverges significantly from the standard ANSI colors, so another path may be to pick a more standard color scheme."
117117 in
118− Interface "repl" (Common summary) details example noArgs replFlags Repl.run
118+ Terminal.Command "repl" (Common summary) details example noArgs replFlags Repl.run
119119
120120
121121interpreter :: Parser String
@@ -133,7 +133,7 @@ interpreter =
133133-- REACTOR
134134
135135
136−reactor :: Interface
136+reactor :: Terminal.Command
137137reactor =
138138 let
139139 summary =
@@ -154,7 +154,7 @@ reactor =
154154 flags Develop.Flags
155155 |-- flag "port" port_ "The port of the server (default: 8000)"
156156 in
157− Interface "reactor" (Common summary) details example noArgs reactorFlags Develop.run
157+ Terminal.Command "reactor" (Common summary) details example noArgs reactorFlags Develop.run
158158
159159
160160port_ :: Parser Int
@@ -172,7 +172,7 @@ port_ =
172172-- MAKE
173173
174174
175−make :: Interface
175+make :: Terminal.Command
176176make =
177177 let
178178 details =
@@ -184,8 +184,8 @@ make =
184184 "For example:"
185185 , P.indent 4 $ P.green "elm make src/Main.elm"
186186 , reflow
187− "This tries to compile an Elm file named src/Main.elm, putting the resulting\
188− \ JavaScript code in an elm.js file."
187+ "This tries to compile an Elm file named src/Main.elm, generating an index.html\
188+ \ file if possible."
189189 ]
190190
191191 makeFlags =
@@ -196,14 +196,14 @@ make =
196196 |-- flag "report" Make.reportType "You can say --report=json to get error messages as JSON. This is only really useful if you are an editor plugin. Humans should avoid it!"
197197 |-- flag "docs" Make.docsFile "Generate a JSON file of documentation for a package. Eventually it will be possible to preview docs with `reactor` because it is quite hard to deal with these JSON files directly."
198198 in
199− Interface "make" Uncommon details example (zeroOrMore elmFile) makeFlags Make.run
199+ Terminal.Command "make" Uncommon details example (zeroOrMore elmFile) makeFlags Make.run
200200
201201
202202
203203-- INSTALL
204204
205205
206−install :: Interface
206+install :: Terminal.Command
207207install =
208208 let
209209 details =
@@ -232,14 +232,14 @@ install =
232232 , require1 Install.Install package
233233 ]
234234 in
235− Interface "install" Uncommon details example installArgs noFlags Install.run
235+ Terminal.Command "install" Uncommon details example installArgs noFlags Install.run
236236
237237
238238
239239-- PUBLISH
240240
241241
242−publish :: Interface
242+publish :: Terminal.Command
243243publish =
244244 let
245245 details =
@@ -266,17 +266,17 @@ publish =
266266 \ it ends up as an experiment on GitHub only. Point is, try to be\
267267 \ respectful of the community and package ecosystem!"
268268 , reflow
269− "Check out https://package.elm-lang.org/help/design-guidelines for guidance on how to create great packages!"
269+ "Check out <https://package.elm-lang.org/help/design-guidelines> for guidance on how to create great packages!"
270270 ]
271271 in
272− Interface "publish" Uncommon details example noArgs noFlags Publish.run
272+ Terminal.Command "publish" Uncommon details example noArgs noFlags Publish.run
273273
274274
275275
276276-- BUMP
277277
278278
279−bump :: Interface
279+bump :: Terminal.Command
280280bump =
281281 let
282282 details =
@@ -289,14 +289,14 @@ bump =
289289 \ it is a MAJOR change, and bump your version number to 2.0.0. I do this with\
290290 \ all packages, so there cannot be MAJOR changes hiding in PATCH releases in Elm!"
291291 in
292− Interface "bump" Uncommon details example noArgs noFlags Bump.run
292+ Terminal.Command "bump" Uncommon details example noArgs noFlags Bump.run
293293
294294
295295
296296-- DIFF
297297
298298
299−diff :: Interface
299+diff :: Terminal.Command
300300diff =
301301 let
302302 details =
@@ -321,7 +321,7 @@ diff =
321321 , require3 Diff.GlobalInquiry package version version
322322 ]
323323 in
324− Interface "diff" Uncommon details example diffArgs noFlags Diff.run
324+ Terminal.Command "diff" Uncommon details example diffArgs noFlags Diff.run
325325
326326
327327
terminal/src/Make.hs+72−60
@@ -14,9 +14,11 @@ module Make
1414import qualified Data.ByteString.Builder as B
1515import qualified Data.Maybe as Maybe
1616import qualified Data.NonEmptyList as NE
17+import qualified System.Directory as Dir
1718import qualified System.FilePath as FP
1819
1920import qualified AST.Optimized as Opt
21+import qualified BackgroundWriter as BW
2022import qualified Build
2123import qualified Elm.Details as Details
2224import qualified Elm.ModuleName as ModuleName
@@ -27,7 +29,7 @@ import qualified Reporting
2729import qualified Reporting.Exit as Exit
2830import qualified Reporting.Task as Task
2931import qualified Stuff
30−import Terminal.Args (Parser(..))
32+import Terminal (Parser(..))
3133
3234
3335
@@ -62,49 +64,58 @@ type Task a = Task.Task Exit.Make a
6264
6365
6466run :: [FilePath] -> Flags -> IO ()
65−run paths (Flags debug optimize maybeOutput report maybeDocs) =
67+run paths flags@(Flags _ _ _ report _) =
6668 do style <- getStyle report
67− Reporting.attemptWithStyle style Exit.makeToReport $ Task.run $
68− do root <- Task.mio Exit.MakeNoOutline Stuff.findRoot
69− desiredMode <- getMode debug optimize
70− details <- Task.eio Exit.MakeBadDetails (Details.load style root)
71− case paths of
72− [] ->
73− do exposed <- getExposed details
74− buildExposed style root details maybeDocs exposed
75−
76− p:ps ->
77− do artifacts <- buildPaths style root details (NE.List p ps)
78− case maybeOutput of
79− Nothing ->
80− case getMains artifacts of
81− [] ->
82− return ()
83−
84− [name] ->
85− do builder <- toBuilder root details desiredMode artifacts
86− generate style "index.html" (Html.sandwich name builder) (NE.List name [])
87−
88− name:names ->
89− do builder <- toBuilder root details desiredMode artifacts
90− generate style "elm.js" builder (NE.List name names)
91−
92− Just DevNull ->
93− return ()
94−
95− Just (JS target) ->
96− case getNoMains artifacts of
97− [] ->
98− do builder <- toBuilder root details desiredMode artifacts
99− generate style target builder (Build.getMainNames artifacts)
100−
101− name:names ->
102− Task.throw (Exit.MakeNonMainFilesIntoJavaScript name names)
103−
104− Just (Html target) ->
105− do name <- hasOneMain artifacts
106− builder <- toBuilder root details desiredMode artifacts
107− generate style target (Html.sandwich name builder) (NE.List name [])
69+ maybeRoot <- Stuff.findRoot
70+ Reporting.attemptWithStyle style Exit.makeToReport $
71+ case maybeRoot of
72+ Just root -> runHelp root paths style flags
73+ Nothing -> return $ Left $ Exit.MakeNoOutline
74+
75+
76+runHelp :: FilePath -> [FilePath] -> Reporting.Style -> Flags -> IO (Either Exit.Make ())
77+runHelp root paths style (Flags debug optimize maybeOutput _ maybeDocs) =
78+ BW.withScope $ \scope ->
79+ Stuff.withRootLock root $ Task.run $
80+ do desiredMode <- getMode debug optimize
81+ details <- Task.eio Exit.MakeBadDetails (Details.load style scope root)
82+ case paths of
83+ [] ->
84+ do exposed <- getExposed details
85+ buildExposed style root details maybeDocs exposed
86+
87+ p:ps ->
88+ do artifacts <- buildPaths style root details (NE.List p ps)
89+ case maybeOutput of
90+ Nothing ->
91+ case getMains artifacts of
92+ [] ->
93+ return ()
94+
95+ [name] ->
96+ do builder <- toBuilder root details desiredMode artifacts
97+ generate style "index.html" (Html.sandwich name builder) (NE.List name [])
98+
99+ name:names ->
100+ do builder <- toBuilder root details desiredMode artifacts
101+ generate style "elm.js" builder (NE.List name names)
102+
103+ Just DevNull ->
104+ return ()
105+
106+ Just (JS target) ->
107+ case getNoMains artifacts of
108+ [] ->
109+ do builder <- toBuilder root details desiredMode artifacts
110+ generate style target builder (Build.getRootNames artifacts)
111+
112+ name:names ->
113+ Task.throw (Exit.MakeNonMainFilesIntoJavaScript name names)
114+
115+ Just (Html target) ->
116+ do name <- hasOneMain artifacts
117+ builder <- toBuilder root details desiredMode artifacts
118+ generate style target (Html.sandwich name builder) (NE.List name [])
108119
109120
110121
@@ -128,12 +139,12 @@ getMode debug optimize =
128139
129140
130141getExposed :: Details.Details -> Task (NE.List ModuleName.Raw)
131−getExposed (Details.Details _ validOutline _ _ _) =
142+getExposed (Details.Details _ validOutline _ _ _ _) =
132143 case validOutline of
133144 Details.ValidApp _ ->
134145 Task.throw Exit.MakeAppNeedsFileNames
135146
136− Details.ValidPkg _ exposed ->
147+ Details.ValidPkg _ exposed _ ->
137148 case exposed of
138149 [] -> Task.throw Exit.MakePkgNeedsExposing
139150 m:ms -> return (NE.List m ms)
@@ -155,7 +166,7 @@ buildExposed style root details maybeDocs exposed =
155166buildPaths :: Reporting.Style -> FilePath -> Details.Details -> NE.List FilePath -> Task Build.Artifacts
156167buildPaths style root details paths =
157168 Task.eio Exit.MakeCannotBuild $
158− Build.fromMains style root details paths
169+ Build.fromPaths style root details paths
159170
160171
161172
@@ -163,13 +174,13 @@ buildPaths style root details paths =
163174
164175
165176getMains :: Build.Artifacts -> [ModuleName.Raw]
166−getMains (Build.Artifacts _ _ mains modules) =
167− Maybe.mapMaybe (getMain modules) (NE.toList mains)
177+getMains (Build.Artifacts _ _ roots modules) =
178+ Maybe.mapMaybe (getMain modules) (NE.toList roots)
168179
169180
170−getMain :: [Build.Module] -> Build.Main -> Maybe ModuleName.Raw
171−getMain modules main =
172− case main of
181+getMain :: [Build.Module] -> Build.Root -> Maybe ModuleName.Raw
182+getMain modules root =
183+ case root of
173184 Build.Inside name ->
174185 if any (isMain name) modules
175186 then Just name
@@ -196,9 +207,9 @@ isMain targetName modul =
196207
197208
198209hasOneMain :: Build.Artifacts -> Task ModuleName.Raw
199−hasOneMain (Build.Artifacts _ _ mains modules) =
200− case mains of
201− NE.List main [] -> Task.mio Exit.MakeNoMain (return $ getMain modules main)
210+hasOneMain (Build.Artifacts _ _ roots modules) =
211+ case roots of
212+ NE.List root [] -> Task.mio Exit.MakeNoMain (return $ getMain modules root)
202213 NE.List _ (_:_) -> Task.throw Exit.MakeMultipleFilesIntoHtml
203214
204215
@@ -207,13 +218,13 @@ hasOneMain (Build.Artifacts _ _ mains modules) =
207218
208219
209220getNoMains :: Build.Artifacts -> [ModuleName.Raw]
210−getNoMains (Build.Artifacts _ _ mains modules) =
211− Maybe.mapMaybe (getNoMain modules) (NE.toList mains)
221+getNoMains (Build.Artifacts _ _ roots modules) =
222+ Maybe.mapMaybe (getNoMain modules) (NE.toList roots)
212223
213224
214−getNoMain :: [Build.Module] -> Build.Main -> Maybe ModuleName.Raw
215−getNoMain modules main =
216− case main of
225+getNoMain :: [Build.Module] -> Build.Root -> Maybe ModuleName.Raw
226+getNoMain modules root =
227+ case root of
217228 Build.Inside name ->
218229 if any (isMain name) modules
219230 then Nothing
@@ -232,7 +243,8 @@ getNoMain modules main =
232243generate :: Reporting.Style -> FilePath -> B.Builder -> NE.List ModuleName.Raw -> Task ()
233244generate style target builder names =
234245 Task.io $
235− do File.writeBuilder target builder
246+ do Dir.createDirectoryIfMissing True (FP.takeDirectory target)
247+ File.writeBuilder target builder
236248 Reporting.reportGenerate style names target
237249
238250
terminal/src/Publish.hs+33−18
@@ -17,6 +17,7 @@ import qualified System.Info as Info
1717import qualified System.IO as IO
1818import qualified System.Process as Process
1919
20+import qualified BackgroundWriter as BW
2021import qualified Build
2122import qualified Deps.Bump as Bump
2223import qualified Deps.Diff as Diff
@@ -170,16 +171,17 @@ verifyLicense root =
170171
171172verifyBuild :: FilePath -> Task.Task Exit.Publish Docs.Documentation
172173verifyBuild root =
173− reportBuildCheck $ Task.run $
174− do details@(Details.Details _ outline _ _ _) <-
174+ reportBuildCheck $ BW.withScope $ \scope ->
175+ Task.run $
176+ do details@(Details.Details _ outline _ _ _ _) <-
175177 Task.eio Exit.PublishBadDetails $
176− Details.load Reporting.silent root
178+ Details.load Reporting.silent scope root
177179
178180 exposed <-
179181 case outline of
180− Details.ValidApp _ -> Task.throw Exit.PublishApplication
181− Details.ValidPkg _ [] -> Task.throw Exit.PublishNoExposed
182− Details.ValidPkg _ (e:es) -> return (NE.List e es)
182+ Details.ValidApp _ -> Task.throw Exit.PublishApplication
183+ Details.ValidPkg _ [] _ -> Task.throw Exit.PublishNoExposed
184+ Details.ValidPkg _ (e:es) _ -> return (NE.List e es)
183185
184186 Task.eio Exit.PublishBuildProblem $
185187 Build.fromExposed Reporting.silent root details Build.KeepDocs exposed
@@ -196,8 +198,21 @@ getGit :: Task.Task Exit.Publish Git
196198getGit =
197199 do maybeGit <- Task.io $ Dir.findExecutable "git"
198200 case maybeGit of
199− Just git -> return (Git (Process.rawSystem git))
200− Nothing -> Task.throw Exit.PublishNoGit
201+ Nothing ->
202+ Task.throw Exit.PublishNoGit
203+
204+ Just git ->
205+ return $ Git $ \args ->
206+ let
207+ process =
208+ (Process.proc git args)
209+ { Process.std_in = Process.CreatePipe
210+ , Process.std_out = Process.CreatePipe
211+ , Process.std_err = Process.CreatePipe
212+ }
213+ in
214+ Process.withCreateProcess process $ \_ _ _ handle ->
215+ Process.waitForProcess handle
201216
202217
203218
@@ -215,7 +230,7 @@ verifyTag git manager pkg vsn =
215230
216231 Exit.ExitSuccess ->
217232 let url = toTagUrl pkg vsn in
218− Http.post manager url [Http.accept "application/json"] (Exit.PublishCannotGetTag vsn) $ \body ->
233+ Http.get manager url [Http.accept "application/json"] (Exit.PublishCannotGetTag vsn) $ \body ->
219234 case D.fromByteString commitHashDecoder body of
220235 Right hash ->
221236 return $ Right hash
@@ -255,7 +270,7 @@ verifyNoChanges git commitHash vsn =
255270
256271verifyZip :: Env -> Pkg.Name -> V.Version -> Task.Task Exit.Publish Http.Sha
257272verifyZip (Env root _ manager _ _) pkg vsn =
258− withTempDir root $ \prepublishDir ->
273+ withPrepublishDir root $ \prepublishDir ->
259274 do let url = toZipUrl pkg vsn
260275
261276 (sha, archive) <-
@@ -279,8 +294,8 @@ toZipUrl pkg vsn =
279294 "https://github.com/" ++ Pkg.toUrl pkg ++ "/zipball/" ++ V.toChars vsn ++ "/"
280295
281296
282−withTempDir :: FilePath -> (FilePath -> Task.Task x a) -> Task.Task x a
283−withTempDir root callback =
297+withPrepublishDir :: FilePath -> (FilePath -> Task.Task x a) -> Task.Task x a
298+withPrepublishDir root callback =
284299 let
285300 dir = Stuff.prepublishDir root
286301 in
@@ -293,16 +308,16 @@ withTempDir root callback =
293308
294309verifyZipBuild :: FilePath -> IO (Either Exit.Publish ())
295310verifyZipBuild root =
296− Task.run $
297− do details@(Details.Details _ outline _ _ _) <-
311+ BW.withScope $ \scope -> Task.run $
312+ do details@(Details.Details _ outline _ _ _ _) <-
298313 Task.eio Exit.PublishZipBadDetails $
299− Details.load Reporting.silent root
314+ Details.load Reporting.silent scope root
300315
301316 exposed <-
302317 case outline of
303− Details.ValidApp _ -> Task.throw Exit.PublishZipApplication
304− Details.ValidPkg _ [] -> Task.throw Exit.PublishZipNoExposed
305− Details.ValidPkg _ (e:es) -> return (NE.List e es)
318+ Details.ValidApp _ -> Task.throw Exit.PublishZipApplication
319+ Details.ValidPkg _ [] _ -> Task.throw Exit.PublishZipNoExposed
320+ Details.ValidPkg _ (e:es) _ -> return (NE.List e es)
306321
307322 _ <- Task.eio Exit.PublishZipBuildProblem $
308323 Build.fromExposed Reporting.silent root details Build.KeepDocs exposed
terminal/src/Repl.hs+188−60
@@ -3,6 +3,16 @@
33module Repl
44 ( Flags(..)
55 , run
6+ --
7+ , Lines(..)
8+ , Input(..)
9+ , Prefill(..)
10+ , CategorizedInput(..)
11+ , categorize
12+ --
13+ , State(..)
14+ , Output(..)
15+ , toByteString
616 )
717 where
818
@@ -29,6 +39,7 @@ import qualified System.IO as IO
2939import qualified System.Process as Proc
3040
3141import qualified AST.Source as Src
42+import qualified BackgroundWriter as BW
3243import qualified Build
3344import qualified Elm.Constraint as C
3445import qualified Elm.Details as Details
@@ -42,6 +53,9 @@ import qualified Parse.Expression as PE
4253import qualified Parse.Declaration as PD
4354import qualified Parse.Module as PM
4455import qualified Parse.Primitives as P
56+import qualified Parse.Space as PS
57+import qualified Parse.Type as PT
58+import qualified Parse.Variable as PV
4559import Parse.Primitives (Row, Col)
4660import qualified Reporting
4761import qualified Reporting.Annotation as A
@@ -160,31 +174,110 @@ data Input
160174
161175read :: Repl.InputT M Input
162176read =
163− do line <- Repl.getInputLine "> "
164− case line of
177+ do maybeLine <- Repl.getInputLine "> "
178+ case maybeLine of
165179 Nothing ->
166180 return Exit
167181
168182 Just chars ->
169− case categorize chars of
183+ let
184+ lines = Lines (stripLegacyBackslash chars) []
185+ in
186+ case categorize lines of
170187 Done input -> return input
171− Continue -> readMore chars
188+ Continue p -> readMore lines p
172189
173190
174−readMore :: [Char] -> Repl.InputT M Input
175−readMore previousLines =
176− do input <- Repl.getInputLineWithInitial "| " (" ","")
191+readMore :: Lines -> Prefill -> Repl.InputT M Input
192+readMore previousLines prefill =
193+ do input <- Repl.getInputLineWithInitial "| " (renderPrefill prefill, "")
177194 case input of
178195 Nothing ->
179196 return Skip
180197
181198 Just chars ->
182199 let
183− allLines = previousLines ++ '\n' : chars
200+ lines = addLine (stripLegacyBackslash chars) previousLines
184201 in
185− case categorize allLines of
202+ case categorize lines of
186203 Done input -> return input
187− Continue -> readMore allLines
204+ Continue p -> readMore lines p
205+
206+
207+-- For compatibility with 0.19.0 such that readers of "Programming Elm" by @jfairbank
208+-- can get through the REPL section successfully.
209+--
210+-- TODO: remove stripLegacyBackslash in next MAJOR release
211+--
212+stripLegacyBackslash :: [Char] -> [Char]
213+stripLegacyBackslash chars =
214+ case chars of
215+ [] ->
216+ []
217+
218+ _:_ ->
219+ if last chars == '\\'
220+ then init chars
221+ else chars
222+
223+
224+data Prefill
225+ = Indent
226+ | DefStart N.Name
227+
228+
229+renderPrefill :: Prefill -> String
230+renderPrefill lineStart =
231+ case lineStart of
232+ Indent ->
233+ " "
234+
235+ DefStart name ->
236+ N.toChars name ++ " "
237+
238+
239+
240+-- LINES
241+
242+
243+data Lines =
244+ Lines
245+ { _prevLine :: String
246+ , _revLines :: [String]
247+ }
248+
249+
250+addLine :: [Char] -> Lines -> Lines
251+addLine line (Lines x xs) =
252+ Lines line (x:xs)
253+
254+
255+isBlank :: Lines -> Bool
256+isBlank (Lines prev rev) =
257+ null rev && all (==' ') prev
258+
259+
260+isSingleLine :: Lines -> Bool
261+isSingleLine (Lines _ rev) =
262+ null rev
263+
264+
265+endsWithBlankLine :: Lines -> Bool
266+endsWithBlankLine (Lines prev _) =
267+ all (==' ') prev
268+
269+
270+linesToByteString :: Lines -> BS_UTF8.ByteString
271+linesToByteString (Lines prev rev) =
272+ BS_UTF8.fromString (unlines (reverse (prev:rev)))
273+
274+
275+getFirstLine :: Lines -> String
276+getFirstLine (Lines x xs) =
277+ case xs of
278+ [] -> x
279+ y:ys -> getFirstLine (Lines y ys)
280+
188281
189282
190283
@@ -193,21 +286,21 @@ readMore previousLines =
193286
194287data CategorizedInput
195288 = Done Input
196− | Continue
289+ | Continue Prefill
197290
198291
199−categorize :: [Char] -> CategorizedInput
200−categorize chars
201− | all (==' ') chars = Done Skip
202− | startsWithColon chars = Done (toCommand chars)
203− | startsWithKeyword "import" chars = attemptImport chars
204− | otherwise = attemptDeclOrExpr chars
292+categorize :: Lines -> CategorizedInput
293+categorize lines
294+ | isBlank lines = Done Skip
295+ | startsWithColon lines = Done (toCommand lines)
296+ | startsWithKeyword "import" lines = attemptImport lines
297+ | otherwise = attemptDeclOrExpr lines
205298
206299
207−attemptImport :: [Char] -> CategorizedInput
208−attemptImport chars =
300+attemptImport :: Lines -> CategorizedInput
301+attemptImport lines =
209302 let
210− src = BS_UTF8.fromString (chars ++ "\n")
303+ src = linesToByteString lines
211304 parser = P.specialize (\_ _ _ -> ()) PM.chompImport
212305 in
213306 case P.fromByteString parser (\_ _ -> ()) src of
@@ -215,63 +308,69 @@ attemptImport chars =
215308 Done (Import name src)
216309
217310 Left () ->
218− if endsWithBlankLine chars
219− then Done (Import "ERR" src)
220− else Continue
311+ ifFail lines (Import "ERR" src)
312+
313+
314+ifFail :: Lines -> Input -> CategorizedInput
315+ifFail lines input =
316+ if endsWithBlankLine lines
317+ then Done input
318+ else Continue Indent
221319
222320
223−attemptDeclOrExpr :: [Char] -> CategorizedInput
224−attemptDeclOrExpr chars =
321+ifDone :: Lines -> Input -> CategorizedInput
322+ifDone lines input =
323+ if isSingleLine lines || endsWithBlankLine lines
324+ then Done input
325+ else Continue Indent
326+
327+
328+attemptDeclOrExpr :: Lines -> CategorizedInput
329+attemptDeclOrExpr lines =
225330 let
226− src = BS_UTF8.fromString (chars ++ "\n")
331+ src = linesToByteString lines
227332 exprParser = P.specialize (toExprPosition src) PE.expression
228333 declParser = P.specialize (toDeclPosition src) PD.declaration
229334 in
230335 case P.fromByteString declParser (,) src of
231336 Right (decl, _) ->
232337 case decl of
233− PD.Value _ (A.At _ (Src.Value (A.At _ name) _ _ _)) -> Done (Decl name src)
234− PD.Union _ (A.At _ (Src.Union (A.At _ name) _ _ )) -> Done (Type name src)
235− PD.Alias _ (A.At _ (Src.Alias (A.At _ name) _ _ )) -> Done (Type name src)
338+ PD.Value _ (A.At _ (Src.Value (A.At _ name) _ _ _)) -> ifDone lines (Decl name src)
339+ PD.Union _ (A.At _ (Src.Union (A.At _ name) _ _ )) -> ifDone lines (Type name src)
340+ PD.Alias _ (A.At _ (Src.Alias (A.At _ name) _ _ )) -> ifDone lines (Type name src)
236341 PD.Port _ _ -> Done Port
237342
238343 Left declPosition
239− | startsWithKeyword "type" chars ->
240− if endsWithBlankLine chars
241− then Done (Type "ERR" src)
242− else Continue
344+ | startsWithKeyword "type" lines ->
345+ ifFail lines (Type "ERR" src)
243346
244− | startsWithKeyword "port" chars ->
347+ | startsWithKeyword "port" lines ->
245348 Done Port
246349
247350 | otherwise ->
248351 case P.fromByteString exprParser (,) src of
249352 Right _ ->
250− Done (Expr src)
353+ ifDone lines (Expr src)
251354
252355 Left exprPosition ->
253− if endsWithBlankLine chars
254− then Done (if declPosition <= exprPosition then Expr src else Decl "ERR" src)
255− else Continue
256−
356+ if exprPosition >= declPosition then
357+ ifFail lines (Expr src)
358+ else
359+ case P.fromByteString annotation (\_ _ -> ()) src of
360+ Right name -> Continue (DefStart name)
361+ Left () -> ifFail lines (Decl "ERR" src)
257362
258−endsWithBlankLine :: [Char] -> Bool
259−endsWithBlankLine chars =
260− case reverse (List.lines chars) of
261− [] -> False
262− cs:_ -> all (==' ') cs
263363
264−
265−startsWithColon :: [Char] -> Bool
266−startsWithColon chars =
267− case dropWhile (==' ') chars of
364+startsWithColon :: Lines -> Bool
365+startsWithColon lines =
366+ case dropWhile (==' ') (getFirstLine lines) of
268367 [] -> False
269368 c:_ -> c == ':'
270369
271370
272−toCommand :: [Char] -> Input
273−toCommand chars =
274− case drop 1 $ dropWhile (==' ') chars of
371+toCommand :: Lines -> Input
372+toCommand lines =
373+ case drop 1 $ dropWhile (==' ') (getFirstLine lines) of
275374 "reset" -> Reset
276375 "exit" -> Exit
277376 "quit" -> Exit
@@ -279,8 +378,11 @@ toCommand chars =
279378 rest -> Help (Just (takeWhile (/=' ') rest))
280379
281380
282−startsWithKeyword :: [Char] -> [Char] -> Bool
283−startsWithKeyword keyword line =
381+startsWithKeyword :: [Char] -> Lines -> Bool
382+startsWithKeyword keyword lines =
383+ let
384+ line = getFirstLine lines
385+ in
284386 List.isPrefixOf keyword line &&
285387 case drop (length keyword) line of
286388 [] -> True
@@ -306,6 +408,21 @@ toDeclPosition src decl r c =
306408 (row, col)
307409
308410
411+annotation :: P.Parser () N.Name
412+annotation =
413+ let
414+ err _ _ = ()
415+ err_ _ _ _ = ()
416+ in
417+ do name <- PV.lower err
418+ PS.chompAndCheckIndent err_ err
419+ P.word1 0x3A {-:-} err
420+ PS.chompAndCheckIndent err_ err
421+ (_, _) <- P.specialize err_ PT.expression
422+ PS.checkFreshLine err
423+ return name
424+
425+
309426
310427-- STATE
311428
@@ -377,10 +494,12 @@ data Output
377494
378495attemptEval :: Env -> State -> State -> Output -> IO State
379496attemptEval (Env root interpreter ansi) oldState newState output =
380− do result <- Task.run $
497+ do result <-
498+ BW.withScope $ \scope ->
499+ Stuff.withRootLock root $ Task.run $
381500 do details <-
382501 Task.eio Exit.ReplBadDetails $
383− Details.load Reporting.silent root
502+ Details.load Reporting.silent scope root
384503
385504 artifacts <-
386505 Task.eio id $
@@ -432,16 +551,16 @@ toByteString (State imports types decls) output =
432551
433552outputToBuilder :: Output -> B.Builder
434553outputToBuilder output =
554+ N.toBuilder N.replValueToPrint <> " =" <>
435555 case output of
436556 OutputNothing ->
437− mempty
557+ " ()\n"
438558
439559 OutputDecl _ ->
440− mempty
560+ " ()\n"
441561
442562 OutputExpr expr ->
443− N.toBuilder N.replValueToPrint <> " ="
444− <> foldr (\line rest -> "\n " <> B.byteString line <> rest) "\n" (BSC.lines expr)
563+ foldr (\line rest -> "\n " <> B.byteString line <> rest) "\n" (BSC.lines expr)
445564
446565
447566
@@ -503,13 +622,22 @@ getRoot =
503622 Licenses.bsd3
504623 V.one
505624 (Outline.ExposedList [])
506− (Map.singleton Pkg.core C.anything)
625+ defaultDeps
507626 Map.empty
508627 C.defaultElm
509628
510629 return root
511630
512631
632+defaultDeps :: Map.Map Pkg.Name C.Constraint
633+defaultDeps =
634+ Map.fromList
635+ [ (Pkg.core, C.anything)
636+ , (Pkg.json, C.anything)
637+ , (Pkg.html, C.anything)
638+ ]
639+
640+
513641
514642-- GET INTERPRETER
515643
worker/elm.cabal+25−3
@@ -43,17 +43,26 @@ Executable worker
4343 src
4444 ../compiler/src
4545 ../builder/src
46+ ../terminal/src
4647
4748 Main-Is:
4849 Main.hs
4950
5051 other-modules:
52+ Artifacts
53+ Cors
54+ Endpoint.Compile
55+ Endpoint.Quotes
56+ Endpoint.Repl
57+
5158 AST.Canonical
5259 AST.Optimized
5360 AST.Source
5461 AST.Utils.Binop
5562 AST.Utils.Shader
5663 AST.Utils.Type
64+ BackgroundWriter
65+ Build
5766 Canonicalize.Effects
5867 Canonicalize.Environment
5968 Canonicalize.Environment.Dups
@@ -79,6 +88,8 @@ Executable worker
7988 Elm.Compiler.Type.Extract
8089 Elm.Constraint
8190 Elm.Details
91+ Elm.Docs
92+ Elm.Float
8293 Elm.Interface
8394 Elm.Kernel
8495 Elm.Licenses
@@ -86,8 +97,10 @@ Executable worker
8697 Elm.ModuleName
8798 Elm.Outline
8899 Elm.Package
100+ Elm.String
89101 Elm.Version
90102 File
103+ Generate
91104 Generate.Html
92105 Generate.JavaScript
93106 Generate.JavaScript.Builder
@@ -98,6 +111,8 @@ Executable worker
98111 Http
99112 Json.Decode
100113 Json.Encode
114+ Json.String
115+ Nitpick.Debug
101116 Nitpick.PatternMatches
102117 Optimize.Case
103118 Optimize.DecisionTree
@@ -114,16 +129,18 @@ Executable worker
114129 Parse.Primitives
115130 Parse.Shader
116131 Parse.Space
132+ Parse.String
117133 Parse.Symbol
118134 Parse.Type
119− Parse.Utf8
120135 Parse.Variable
121136 Paths_elm
137+ Repl
122138 Reporting
123139 Reporting.Annotation
124140 Reporting.Doc
125141 Reporting.Error
126142 Reporting.Error.Canonicalize
143+ Reporting.Error.Docs
127144 Reporting.Error.Import
128145 Reporting.Error.Json
129146 Reporting.Error.Main
@@ -153,18 +170,20 @@ Executable worker
153170 Type.UnionFind
154171
155172 Build-depends:
173+ aeson,
156174 ansi-terminal >= 0.8 && < 0.9,
157175 ansi-wl-pprint >= 0.6.8 && < 0.7,
158176 base >=4.11 && <5,
177+ base64-bytestring,
159178 binary >= 0.8 && < 0.9,
160179 bytestring >= 0.9 && < 0.11,
161180 containers >= 0.5.8.2 && < 0.6,
162181 directory >= 1.2.3.0 && < 2.0,
163182 edit-distance >= 0.2 && < 0.3,
164− file-embed,
165183 filelock,
166184 filepath >= 1 && < 2.0,
167185 ghc-prim >= 0.5.2,
186+ haskeline,
168187 HTTP >= 4000.2.5 && < 4000.4,
169188 http-client >= 0.6 && < 0.7,
170189 http-client-tls >= 0.3 && < 0.4,
@@ -175,13 +194,16 @@ Executable worker
175194 network >= 2.4 && < 2.7,
176195 network-uri,
177196 parsec,
197+ process,
198+ random,
178199 raw-strings-qq,
179200 scientific,
180201 SHA,
181202 snap-core,
182203 snap-server,
183204 template-haskell,
184− time,
205+ text,
206+ time >= 1.9.1,
185207 unordered-containers,
186208 utf8-string,
187209 vector,
worker/elm.jsonnew file+26
@@ -0,0 +1,26 @@
1+{
2+ "type": "application",
3+ "source-directories": [
4+ "src"
5+ ],
6+ "elm-version": "0.19.1",
7+ "dependencies": {
8+ "direct": {
9+ "elm/browser": "1.0.1",
10+ "elm/core": "1.0.2",
11+ "elm/html": "1.0.0",
12+ "elm/json": "1.1.3",
13+ "elm/project-metadata-utils": "1.0.0"
14+ },
15+ "indirect": {
16+ "elm/parser": "1.1.0",
17+ "elm/time": "1.0.0",
18+ "elm/url": "1.0.0",
19+ "elm/virtual-dom": "1.0.2"
20+ }
21+ },
22+ "test-dependencies": {
23+ "direct": {},
24+ "indirect": {}
25+ }
26+}
worker/nginx.confnew file+22
@@ -0,0 +1,22 @@
1+server {
2+ listen 80;
3+ server_name worker.elm-lang.org;
4+
5+ location / {
6+ proxy_pass http://localhost:8000;
7+ }
8+}
9+
10+server {
11+ listen 443 ssl;
12+ server_name worker.elm-lang.org;
13+
14+ location / {
15+ proxy_pass http://localhost:8000;
16+ }
17+
18+ ssl_certificate /etc/letsencrypt/live/worker.elm-lang.org/fullchain.pem; # managed by Certbot
19+ ssl_certificate_key /etc/letsencrypt/live/worker.elm-lang.org/privkey.pem; # managed by Certbot
20+ include /etc/letsencrypt/options-ssl-nginx.conf;
21+ ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
22+}
worker/outlines/compile/elm.jsonnew file+32
@@ -0,0 +1,32 @@
1+{
2+ "type": "application",
3+ "source-directories": [
4+ "../../src"
5+ ],
6+ "elm-version": "0.19.1",
7+ "dependencies": {
8+ "direct": {
9+ "elm/browser": "1.0.1",
10+ "elm/core": "1.0.2",
11+ "elm/file": "1.0.5",
12+ "elm/html": "1.0.0",
13+ "elm/http": "2.0.0",
14+ "elm/json": "1.1.3",
15+ "elm/random": "1.0.0",
16+ "elm/svg": "1.0.1",
17+ "elm/time": "1.0.0",
18+ "elm-explorations/linear-algebra": "1.0.3",
19+ "elm-explorations/webgl": "1.1.0",
20+ "evancz/elm-playground": "1.0.2"
21+ },
22+ "indirect": {
23+ "elm/bytes": "1.0.8",
24+ "elm/url": "1.0.0",
25+ "elm/virtual-dom": "1.0.2"
26+ }
27+ },
28+ "test-dependencies": {
29+ "direct": {},
30+ "indirect": {}
31+ }
32+}
worker/outlines/repl/elm.jsonnew file+19
@@ -0,0 +1,19 @@
1+{
2+ "type": "application",
3+ "source-directories": [
4+ "../../src"
5+ ],
6+ "elm-version": "0.19.1",
7+ "dependencies": {
8+ "direct": {
9+ "elm/core": "1.0.2"
10+ },
11+ "indirect": {
12+ "elm/json": "1.1.3"
13+ }
14+ },
15+ "test-dependencies": {
16+ "direct": {},
17+ "indirect": {}
18+ }
19+}
worker/src/Artifacts.hsnew file+155
@@ -0,0 +1,155 @@
1+{-# OPTIONS_GHC -Wall #-}
2+module Artifacts
3+ ( Artifacts(..)
4+ , loadCompile
5+ , loadRepl
6+ , toDepsInfo
7+ )
8+ where
9+
10+
11+import Control.Concurrent (readMVar)
12+import Control.Monad (liftM2)
13+import qualified Data.ByteString as BS
14+import qualified Data.ByteString.Builder as B
15+import qualified Data.ByteString.Lazy as LBS
16+import qualified Data.Map as Map
17+import qualified Data.Name as N
18+import qualified Data.OneOrMore as OneOrMore
19+import qualified System.Directory as Dir
20+import System.FilePath ((</>))
21+
22+import qualified AST.Canonical as Can
23+import qualified AST.Optimized as Opt
24+import qualified BackgroundWriter as BW
25+import qualified Elm.Details as Details
26+import qualified Elm.Interface as I
27+import qualified Elm.ModuleName as ModuleName
28+import qualified Elm.Package as Pkg
29+import Json.Encode ((==>))
30+import qualified Json.Encode as E
31+import qualified Json.String as Json
32+import qualified Reporting
33+
34+
35+
36+-- ARTIFACTS
37+
38+
39+data Artifacts =
40+ Artifacts
41+ { _ifaces :: Map.Map ModuleName.Raw I.Interface
42+ , _graph :: Opt.GlobalGraph
43+ }
44+
45+
46+loadCompile :: IO Artifacts
47+loadCompile =
48+ load ("outlines" </> "compile")
49+
50+
51+loadRepl :: IO Artifacts
52+loadRepl =
53+ load ("outlines" </> "repl")
54+
55+
56+
57+-- LOAD
58+
59+
60+load :: FilePath -> IO Artifacts
61+load dir =
62+ BW.withScope $ \scope ->
63+ do putStrLn $ "Loading " ++ dir </> "elm.json"
64+ style <- Reporting.terminal
65+ root <- fmap (</> dir) Dir.getCurrentDirectory
66+ result <- Details.load style scope root
67+ case result of
68+ Left _ ->
69+ error $ "Ran into some problem loading elm.json\nTry running `elm make` in: " ++ dir
70+
71+ Right details ->
72+ do omvar <- Details.loadObjects root details
73+ imvar <- Details.loadInterfaces root details
74+ mdeps <- readMVar imvar
75+ mobjs <- readMVar omvar
76+ case liftM2 (,) mdeps mobjs of
77+ Nothing ->
78+ error $ "Ran into some weird problem loading elm.json\nTry running `elm make` in: " ++ dir
79+
80+ Just (deps, objs) ->
81+ return $ Artifacts (toInterfaces deps) objs
82+
83+
84+toInterfaces :: Map.Map ModuleName.Canonical I.DependencyInterface -> Map.Map ModuleName.Raw I.Interface
85+toInterfaces deps =
86+ Map.mapMaybe toUnique $ Map.fromListWith OneOrMore.more $
87+ Map.elems (Map.mapMaybeWithKey getPublic deps)
88+
89+
90+getPublic :: ModuleName.Canonical -> I.DependencyInterface -> Maybe (ModuleName.Raw, OneOrMore.OneOrMore I.Interface)
91+getPublic (ModuleName.Canonical _ name) dep =
92+ case dep of
93+ I.Public iface -> Just (name, OneOrMore.one iface)
94+ I.Private _ _ _ -> Nothing
95+
96+
97+toUnique :: OneOrMore.OneOrMore a -> Maybe a
98+toUnique oneOrMore =
99+ case oneOrMore of
100+ OneOrMore.One value -> Just value
101+ OneOrMore.More _ _ -> Nothing
102+
103+
104+
105+-- TO DEPS INFO
106+
107+
108+toDepsInfo :: Artifacts -> BS.ByteString
109+toDepsInfo (Artifacts ifaces _) =
110+ LBS.toStrict $ B.toLazyByteString $ E.encodeUgly $ encode ifaces
111+
112+
113+
114+-- ENCODE
115+
116+
117+encode :: Map.Map ModuleName.Raw I.Interface -> E.Value
118+encode ifaces =
119+ E.dict Json.fromName encodeInterface ifaces
120+
121+
122+encodeInterface :: I.Interface -> E.Value
123+encodeInterface (I.Interface pkg values unions aliases binops) =
124+ E.object
125+ [ "pkg" ==> E.chars (Pkg.toChars pkg)
126+ , "ops" ==> E.list E.name (Map.keys binops)
127+ , "values" ==> E.list E.name (Map.keys values)
128+ , "aliases" ==> E.list E.name (Map.keys (Map.filter isPublicAlias aliases))
129+ , "types" ==> E.dict Json.fromName (E.list E.name) (Map.mapMaybe toPublicUnion unions)
130+ ]
131+
132+
133+isPublicAlias :: I.Alias -> Bool
134+isPublicAlias alias =
135+ case alias of
136+ I.PublicAlias _ -> True
137+ I.PrivateAlias _ -> False
138+
139+
140+toPublicUnion :: I.Union -> Maybe [N.Name]
141+toPublicUnion union =
142+ case union of
143+ I.OpenUnion (Can.Union _ variants _ _) ->
144+ Just (map getVariantName variants)
145+
146+ I.ClosedUnion _ ->
147+ Just []
148+
149+ I.PrivateUnion _ ->
150+ Nothing
151+
152+
153+getVariantName :: Can.Ctor -> N.Name
154+getVariantName (Can.Ctor name _ _ _) =
155+ name
worker/src/Cors.hsnew file+48
@@ -0,0 +1,48 @@
1+{-# OPTIONS_GHC -Wall #-}
2+module Cors
3+ ( allow
4+ )
5+ where
6+
7+
8+import qualified Data.HashSet as HashSet
9+import Network.URI (parseURI)
10+import Snap.Core (Snap, Method, method)
11+import Snap.Util.CORS (CORSOptions(..), HashableMethod(..), OriginList(Origins), applyCORS, mkOriginSet)
12+
13+
14+
15+-- ALLOW
16+
17+
18+allow :: Method -> [String] -> Snap () -> Snap ()
19+allow method_ origins snap =
20+ applyCORS (toOptions method_ origins) $ method method_ $
21+ snap
22+
23+
24+
25+-- TO OPTIONS
26+
27+
28+toOptions :: (Monad m) => Method -> [String] -> CORSOptions m
29+toOptions method_ origins =
30+ let
31+ allowedOrigins = toOriginList origins
32+ allowedMethods = HashSet.singleton (HashableMethod method_)
33+ in
34+ CORSOptions
35+ { corsAllowOrigin = return allowedOrigins
36+ , corsAllowCredentials = return True
37+ , corsExposeHeaders = return HashSet.empty
38+ , corsAllowedMethods = return allowedMethods
39+ , corsAllowedHeaders = return
40+ }
41+
42+
43+toOriginList :: [String] -> OriginList
44+toOriginList origins =
45+ Origins $ mkOriginSet $
46+ case traverse parseURI origins of
47+ Just uris -> uris
48+ Nothing -> error "invalid entry given to toOriginList list"
worker/src/Endpoint/Compile.hsnew file+323
@@ -0,0 +1,323 @@
1+{-# OPTIONS_GHC -Wall #-}
2+{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
3+module Endpoint.Compile
4+ ( endpoint_V1
5+ , endpoint_V2
6+ , loadErrorJS
7+ )
8+ where
9+
10+
11+import qualified Data.ByteString as B
12+import qualified Data.ByteString.Builder as B
13+import qualified Data.ByteString.Lazy as LBS
14+import qualified Data.Map as Map
15+import qualified Data.Map.Utils as Map
16+import qualified Data.Name as N
17+import qualified Data.NonEmptyList as NE
18+import Snap.Core
19+import Snap.Util.FileUploads
20+import qualified System.Directory as Dir
21+import qualified System.IO.Streams as Stream
22+import Text.RawString.QQ (r)
23+
24+import qualified Artifacts as A
25+import qualified Cors
26+
27+import qualified AST.Source as Src
28+import qualified AST.Canonical as Can
29+import qualified AST.Optimized as Opt
30+import qualified BackgroundWriter as BW
31+import qualified Build
32+import qualified Compile
33+import qualified Elm.Details as Details
34+import qualified Elm.Interface as I
35+import qualified Elm.ModuleName as ModuleName
36+import qualified Elm.Package as Pkg
37+import qualified File
38+import qualified Generate
39+import qualified Generate.Html as Html
40+import qualified Generate.JavaScript as JS
41+import qualified Generate.Mode as Mode
42+import qualified Json.Encode as Encode
43+import qualified Parse.Module as Parse
44+import qualified Reporting
45+import qualified Reporting.Annotation as A
46+import Reporting.Doc ((<>))
47+import qualified Reporting.Doc as D
48+import qualified Reporting.Error as Error
49+import qualified Reporting.Error.Import as Import
50+import qualified Reporting.Exit as Exit
51+import qualified Reporting.Exit.Help as Help
52+import qualified Reporting.Task as Task
53+
54+
55+
56+-- ALLOWED ORIGINS
57+
58+
59+allowedOrigins :: [String]
60+allowedOrigins =
61+ [ "https://elm-lang.org"
62+ , "https://package.elm-lang.org"
63+ ]
64+
65+
66+
67+-- ENDPOINT (V1)
68+
69+
70+endpoint_V1 :: A.Artifacts -> Snap ()
71+endpoint_V1 artifacts =
72+ endpoint artifacts $ \result ->
73+ case result of
74+ Ok name js -> writeBuilder $ Html.sandwich name js
75+ Err report -> writeBuilder $ renderProblem_V1 report
76+
77+
78+
79+-- ENDPOINT (V2)
80+
81+
82+endpoint_V2 :: A.Artifacts -> Snap ()
83+endpoint_V2 artifacts =
84+ endpoint artifacts $ \result ->
85+ case result of
86+ Ok name js -> writeBuilder $ renderSuccess_V2 name js
87+ Err report -> writeBuilder $ renderProblem_V2 report
88+
89+
90+
91+-- ENDPOINT
92+
93+
94+data Result
95+ = Ok N.Name B.Builder
96+ | Err Help.Report
97+
98+
99+endpoint :: A.Artifacts -> (Result -> Snap ()) -> Snap ()
100+endpoint artifacts callback =
101+ Cors.allow POST allowedOrigins $
102+ do result <- foldMultipart defaultUploadPolicy ignoreFile 0
103+ case result of
104+ ([("code",source)], 0) ->
105+ do modifyResponse $ setContentType "text/html; charset=utf-8"
106+ callback $
107+ case compile artifacts source of
108+ Success name js -> Ok name js
109+ NoMain -> Err noMain
110+ BadInput name err -> Err $ Help.compilerReport "/" (Error.Module name "/try" File.zeroTime source err) []
111+
112+ _ ->
113+ do modifyResponse $ setResponseStatus 400 "Bad Request"
114+ modifyResponse $ setContentType "text/html; charset=utf-8"
115+ writeBS
116+ "<p>Unexpected request format. This should not be possible!</p>\
117+ \<p>Please report this\
118+ \ <a href=\"https://github.com/elm/compiler/issues\">here</a>\
119+ \ along with the URL and your browser version.</p>"
120+
121+
122+ignoreFile :: PartInfo -> Stream.InputStream B.ByteString -> Int -> IO Int
123+ignoreFile _ _ count =
124+ return (count + 1)
125+
126+
127+
128+-- COMPILE
129+
130+
131+data Outcome
132+ = Success N.Name B.Builder
133+ | NoMain
134+ | BadInput ModuleName.Raw Error.Error
135+
136+
137+compile :: A.Artifacts -> B.ByteString -> Outcome
138+compile (A.Artifacts interfaces objects) source =
139+ case Parse.fromByteString Parse.Application source of
140+ Left err ->
141+ BadInput N._Main (Error.BadSyntax err)
142+
143+ Right modul@(Src.Module _ _ _ imports _ _ _ _ _) ->
144+ case checkImports interfaces imports of
145+ Left err ->
146+ BadInput (Src.getName modul) (Error.BadImports err)
147+
148+ Right ifaces ->
149+ case Compile.compile Pkg.dummyName ifaces modul of
150+ Left err ->
151+ BadInput (Src.getName modul) err
152+
153+ Right (Compile.Artifacts canModule _ locals) ->
154+ case locals of
155+ Opt.LocalGraph Nothing _ _ ->
156+ NoMain
157+
158+ Opt.LocalGraph (Just main_) _ _ ->
159+ let
160+ mode = Mode.Dev Nothing
161+ home = Can._name canModule
162+ name = ModuleName._module home
163+ mains = Map.singleton home main_
164+ graph = Opt.addLocalGraph locals objects
165+ in
166+ Success name $ JS.generate mode graph mains
167+
168+
169+checkImports :: Map.Map ModuleName.Raw I.Interface -> [Src.Import] -> Either (NE.List Import.Error) (Map.Map ModuleName.Raw I.Interface)
170+checkImports interfaces imports =
171+ let
172+ importDict = Map.fromValues Src.getImportName imports
173+ missing = Map.difference importDict interfaces
174+ in
175+ case Map.elems missing of
176+ [] ->
177+ Right (Map.intersection interfaces importDict)
178+
179+ i:is ->
180+ let
181+ unimported =
182+ Map.keysSet (Map.difference interfaces importDict)
183+
184+ toError (Src.Import (A.At region name) _ _) =
185+ Import.Error region name unimported Import.NotFound
186+ in
187+ Left (fmap toError (NE.List i is))
188+
189+
190+
191+-- RENDER PROBLEM (V1)
192+
193+
194+renderProblem_V1 :: Help.Report -> B.Builder
195+renderProblem_V1 report =
196+ [r|<!DOCTYPE HTML>
197+<html>
198+<head>
199+ <meta charset="UTF-8">
200+ <style>body { padding: 0; margin: 0; background-color: black; }</style>
201+ <script src="https://worker.elm-lang.org/compile/errors.js"></script>
202+</head>
203+<body>
204+ <script>
205+ var app = Elm.Errors.init({flags:|] <> Encode.encodeUgly (Exit.toJson report) <> [r|});
206+ app.ports.jumpTo.subscribe(function(region) {
207+ window.parent.postMessage(JSON.stringify(region), "*");
208+ });
209+ </script>
210+</body>
211+</html>|]
212+
213+
214+
215+-- RENDER SUCCESS (V2)
216+
217+
218+renderSuccess_V2 :: N.Name -> B.Builder -> B.Builder
219+renderSuccess_V2 moduleName javascript =
220+ let name = N.toBuilder moduleName in
221+ [r|<!DOCTYPE HTML>
222+<html>
223+<head>
224+ <meta charset="UTF-8">
225+ <title>|] <> name <> [r|</title>
226+ <style>body { padding: 0; margin: 0; }</style>
227+</head>
228+
229+<body>
230+
231+<pre id="elm"></pre>
232+
233+<script>
234+window.parent.postMessage("SUCCESS", "*");
235+
236+try {
237+|] <> javascript <> [r|
238+
239+ var app = Elm.|] <> name <> [r|.init({ node: document.getElementById("elm") });
240+}
241+catch (e)
242+{
243+ // display initialization errors (e.g. bad flags, infinite recursion)
244+ var header = document.createElement("h1");
245+ header.style.fontFamily = "monospace";
246+ header.innerText = "Initialization Error";
247+ var pre = document.getElementById("elm");
248+ document.body.insertBefore(header, pre);
249+ pre.innerText = e;
250+ throw e;
251+}
252+</script>
253+
254+</body>
255+</html>|]
256+
257+
258+
259+-- RENDER PROBLEM (V2)
260+
261+
262+renderProblem_V2 :: Help.Report -> B.Builder
263+renderProblem_V2 report =
264+ [r|<!DOCTYPE HTML>
265+<html>
266+<head>
267+ <meta charset="UTF-8">
268+ <style>body { padding: 0; margin: 0; display: none; }</style>
269+</head>
270+<body>
271+ <script>
272+ var errors = |] <> Encode.encodeUgly (Exit.toJson report) <> [r|;
273+ window.parent.postMessage(JSON.stringify(errors), "*");
274+ </script>
275+</body>
276+</html>|]
277+
278+
279+
280+-- NO MAIN
281+
282+
283+noMain :: Help.Report
284+noMain =
285+ Help.report "NO MAIN" Nothing
286+ (
287+ "Without a `main` value, I do not know what to show on screen!"
288+ )
289+ [ D.reflow $
290+ "Adding a `main` value can be as brief as:"
291+ , D.vcat
292+ [ D.fillSep [D.cyan "import","Html"]
293+ , ""
294+ , D.fillSep [D.green "main","="]
295+ , D.indent 2 $ D.fillSep [D.cyan "Html" <> ".text",D.dullyellow "\"Hello!\""]
296+ ]
297+ , D.reflow $
298+ "Try adding something like that!"
299+ , D.toSimpleNote $
300+ "I recommend looking through https://guide.elm-lang.org for more advice on\
301+ \ how to fill in `main` values."
302+ ]
303+
304+
305+
306+-- LOAD ERROR JS
307+
308+
309+loadErrorJS :: IO B.ByteString
310+loadErrorJS =
311+ let
312+ run work =
313+ do result <- work
314+ case result of
315+ Right a -> return a
316+ Left _ -> error "problem building src/Errors.elm"
317+ in
318+ BW.withScope $ \scope ->
319+ do root <- Dir.getCurrentDirectory
320+ details <- run $ Details.load Reporting.silent scope root
321+ artifacts <- run $ Build.fromPaths Reporting.silent root details (NE.List "src/Errors.elm" [])
322+ javascript <- run $ Task.run $ Generate.prod root details artifacts
323+ return $ LBS.toStrict $ B.toLazyByteString javascript
worker/src/Endpoint/Quotes.hsnew file+114
@@ -0,0 +1,114 @@
1+{-# LANGUAGE BangPatterns, MagicHash, OverloadedStrings, UnboxedTuples #-}
2+module Endpoint.Quotes
3+ ( endpoint
4+ )
5+ where
6+
7+
8+import Control.Monad.IO.Class (liftIO)
9+import qualified Data.ByteString as BS
10+import GHC.Int (Int(I#))
11+import GHC.Prim
12+import GHC.ST (ST(ST), runST)
13+import qualified System.Random as Random
14+
15+import Snap.Core
16+
17+
18+
19+-- ENDPOINT
20+
21+
22+endpoint :: Snap ()
23+endpoint =
24+ do modifyResponse
25+ $ setContentType "application/json"
26+ . setHeader "Access-Control-Allow-Origin" "*"
27+ writeBS =<< liftIO getQuote
28+
29+
30+getQuote :: IO BS.ByteString
31+getQuote =
32+ let
33+ (Quotes sa#) = quotes
34+ in
35+ do (I# i#) <- Random.randomRIO (0, I# (sizeofSmallArray# sa# -# 1#))
36+ case indexSmallArray# sa# i# of
37+ (# json #) ->
38+ return json
39+
40+
41+
42+-- QUOTES
43+
44+
45+data Quotes =
46+ Quotes (SmallArray# BS.ByteString)
47+
48+
49+quotes :: Quotes
50+quotes =
51+ let
52+ !(I# len#) = length quoteList
53+ in
54+ runST $ ST $ \s ->
55+ case newSmallArray# len# "" s of
56+ (# s, sma# #) ->
57+ case quotesHelp# sma# quoteList s of
58+ s ->
59+ case unsafeFreezeSmallArray# sma# s of
60+ (# s, sa# #) ->
61+ (# s, Quotes sa# #)
62+
63+
64+quotesHelp# :: SmallMutableArray# s a -> [a] -> State# s -> State# s
65+quotesHelp# sma# =
66+ go 0#
67+ where
68+ go i# list s =
69+ case list of
70+ [] ->
71+ s
72+
73+ x:xs ->
74+ case writeSmallArray# sma# i# x s of
75+ s ->
76+ go (i# +# 1#) xs s
77+
78+
79+quoteList :: [BS.ByteString]
80+quoteList =
81+ [ "{\"source\":\"Civilization and its Discontents\",\"author\":\"Sigmund Freud\",\"year\":1902,\"quote\":\"The enormous expansion of communications, due to the world-wide telegraph and telephone networks, has entirely transformed the conditions of trade and commerce. Everything is done in haste, at fever pitch. The night is used for travel, the day for business; even \\u201Choliday trips\\u201D put a strain on the nervous system. Great political, industrial and financial crises carry this excitement into far wider areas of the population than ever before. Interest in political life has become universal: tempers are inflamed by political, religious and social struggles, party politics, electioneering and the immense growth of trade-unionism; people are forced to engage in constant mental activity and robbed of the time the need for relaxation, sleep and rest.\"}"
82+ , "{\"source\":\"A Preface to Politics\",\"author\":\"Walter Lippmann\",\"year\":1913,\"quote\":\"The Economic Man\\u2014that lazy abstraction\\u2014is still paraded in the lecture room.\"}"
83+ , "{\"source\":\"Letters from a Stoic\",\"author\":\"Seneca\",\"year\":54,\"quote\":\"You ask me to say what you should consider it particularly important to avoid. My answer is this: a mass crowd. It is something to which you cannot entrust yourself yet without risk. I at any rate am ready to confess my own frailty in this respect. I never come back home with quite the same moral character as I went out with.\"}"
84+ , "{\"source\":\"Letters from a Stoic\",\"author\":\"Seneca\",\"year\":54,\"quote\":\"December used to be a month but it is now a year\"}"
85+ , "{\"source\":\"Letters from a Stoic\",\"author\":\"Seneca\",\"year\":54,\"quote\":\"But nothing is as ruinous to the character as sitting away one\\u2019s time at a show - for it is then, through the medium of entertainment, that vices creep into one with more than usual ease.\"}"
86+ , "{\"source\":\"Letters from a Stoic\",\"author\":\"Seneca\",\"year\":54,\"quote\":\"All this hurrying from place to place won\\u2019t bring you any relief, for you\\u2019re travelling in the company of your own emotions, followed by your troubles all the way. If only they were really following you! They\\u2019d be farther away from you: as it is they\\u2019re not at your back, but on it! That\\u2019s why they weigh you down with just the same uncomfortable chafing wherever you are. It\\u2019s medicine, not a particular part of the world, that a person needs if he\\u2019s ill. Suppose someone has broken his leg or dislocated a joint; he doesn\\u2019t get into a carriage or board a ship: he calls in a doctor to have the fracture set or the dislocation reduced. Well then, when a person\\u2019s spirit is wrenched or broken at so many points, do you imagine that it can be put right by a change of scenery, that that sort of trouble isn\\u2019t so serious that it can\\u2019t be cured by an outing?\"}"
87+ , "{\"source\":\"Progress and Poverty\",\"author\":\"Henry George\",\"year\":1879,\"quote\":\"The present century has been marked by a prodigious increase in wealth-producing power. The utilization of steam and electricity, the introduction of improved processes and laborsaving machinery, the greater subdivision and grander scale of production, the wonderful facilitation of exchanges, have multiplied enormously the effectiveness of labor. At the beginning of this marvelous era it was natural to expect, and it was expected, that laborsaving inventions would lighten the toil and improve the condition of the laborer; that the enormous increase in the power of producing wealth would make real poverty a thing of the past.\"}"
88+ , "{\"source\":\"Imperialism\",\"author\":\"John Hobson\",\"year\":1902,\"quote\":\"Although the new Imperialism has been bad business for the nation, it has been good business for certain classes and certain trades within the nation. The vast expenditure on armaments, the costly wars, the grave risks and embarrassments of foreign policy, the stoppage of political and social reforms within Great Britain, though fraught with great injury to the nation, have served well the present business interests of certain industries and professions.\"}"
89+ , "{\"source\":\"Neo-Colonialism\",\"author\":\"Kwame Nkrumah\",\"year\":1965,\"quote\":\"The essence of neo-colonialism is that the State which is subject to it is, in theory, independent and has all the outward trappings of international sovereignty. In reality its economic system and thus its political policy is directed from the outside. The methods and form of this direction can take various shapes. For example, in an extreme case the troops of the imperial power may garrison the territory of the neo-colonial State and control the government of it. More often, however, neo-colonialist control is exercised through economic or monetary means. The neo-colonial State may be obliged to take the manufactured products of the imperialist power to the exclusion of competing products from elsewhere. Control over government policy in the neo-colonial State may be secured by payments towards the cost of running the State, by the provision of civil servants in positions where they can dictate policy, and by monetary control over foreign exchange through the imposition of a banking system controlled by the imperial power.\"}"
90+ , "{\"source\":\"Neo-Colonialism\",\"author\":\"Kwame Nkrumah\",\"year\":1965,\"quote\":\"In the end the situation arises that the only type of aid which the neo-colonialist masters consider as safe is \\u2018military aid\\u2019. Once a neo-colonialist territory is brought to such a state of economic chaos and misery that revolt actually breaks out then, and only then, is there no limit to the generosity of the neo-colonial overlord, provided, of course, that the funds supplied are utilised exclusively for military purposes. Military aid in fact marks the last stage of neo-colonialism and its effect is self-destructive. Sooner or later the weapons supplied pass into the hands of the opponents of the neo-colonialist regime and the war itself increases the social misery which originally provoked it.\"}"
91+ , "{\"source\":\"Barnyard in your Backyard\",\"author\":\"Gail Damerow\",\"year\":2002,\"quote\":\"Wild jungle fowl, the ancestors of modern chickens, met their nutritional needs by consuming a variety of plants and insects. Given enough room to roam, some of today\\u2019s breeds remain active foragers.\"}"
92+ , "{\"source\":\"Barnyard in your Backyard\",\"author\":\"Gail Damerow\",\"year\":2002,\"quote\":\"Another way to reduce the cost of feed is to let your chickens roam on a lawn or in a pasture for part of the day. By eating plants, seeds, and insects, they will balance their diet and eat less of the expensive commercial stuff. Take care not to put your chickens on grass or around buildings that have been sprayed with toxins.\"}"
93+ , "{\"source\":\"Co-operation in Danish Agriculture\",\"author\":\"Harald Faber\",\"year\":1918,\"quote\":\"A plan for improving the butter made from the milk from peasant farms by collecting the milk to be worked at one place was submitted to the Royal Agricultural Society of Denmark as early as 1852, and it pointed out that this could be done on co-operative lines, the peasants being the owners of the factory and sharing the proceeds.\"}"
94+ , "{\"source\":\"Co-operation in Danish Agriculture\",\"author\":\"Harald Faber\",\"year\":1918,\"quote\":\"It was the Danish peasants themselves who found a practical way of developing the dairy industry, and they found this by applying the co-operative principles introduced by the Rochdale weavers. They received no support and only lukewarm sympathy from large farmers and estate owners, until later on when the co-operative dairies were doing so well that even owners of estates with two to three hundred cows found it to their advantage to close their private dairies and to join co-operative dairies.\"}"
95+ , "{\"source\":\"Beekeeping: A Practical Guide\",\"author\":\"Richard Bonney\",\"year\":1993,\"quote\":\"How many of you have been in a classroom or a training program where the instructor says at the outset, \\u201CLook at the person on your right; now look at the person on your left. One of you won\\u2019t be here next year.\\u201D Beekeeping is like that. Furthermore, not all beekeepers are truly beekeepers. Some are beehavers.\"}"
96+ , "{\"source\":\"The Rodale Book of Composting\",\"author\":\"Deborah Martin and Grace Gershuny\",\"year\":1992,\"quote\":\"Earthworms. If bacteria are the champion microscopic decomposers, then the heavyweight champion is doubtless the earthworm. Pages of praise have been written to the earthworm, ever since it became known that this creature spends most of its time tilling and enriching the soil.\"}"
97+ , "{\"source\":\"War is a Racket\",\"author\":\"General Smedley Butler\",\"year\":1935,\"quote\":\"There are 40,000,000 men under arms in the world today, and our statesmen and diplomats have the temerity to say that war is not in the making. Hell\\u2019s bells! Are these 40,000,000 men being trained to be dancers?\"}"
98+ , "{\"source\":\"Root Cellaring\",\"author\":\"Mike and Nancy Bubel\",\"year\":1991,\"quote\":\"What is not so widely acknowledged is that the soil in which your plants grow can influence the keeping quality of the vegetables you harvest. According to studies reported in E. P. Shirakov\\u2019s \\u201CPractical Course in Storage and Processing of Fruits and Vegetables\\u201D, abundant potash in the soil promotes long storage life of fruits and vegetables grown on that soil.\"}"
99+ , "{\"source\":\"Angora Goats the Northern Way\",\"author\":\"Susan Black Drummond\",\"year\":1985,\"quote\":\"Because of its long wearing qualities and resistance to soil, mohair was once a major upholstery fabric in this country, and was the seat cover material in many cars and in British Railroad seats. The synthetic fiber craze put an end to mohair use as upholstery fabric here.\"}"
100+ , "{\"source\":\"Making a Newspaper\",\"author\":\"John Given\",\"year\":1912,\"quote\":\"Yellow journalism originated through a desire to gain readers and advertisers, and it produced results. Its original disciples have readers by the hundred thousand and they have about all the advertising that they can well handle.\"}"
101+ , "{\"source\":\"Making a Newspaper\",\"author\":\"John Given\",\"year\":1912,\"quote\":\"With the adding of every new train and the improvement of every new time-table, the building of every new trolley road, and the establishment of every new mail route, the big city papers are enabled to reach out further, and, wherever they reach, the local papers suffer [...] There is not a paper published in any city between New York and Boston that has not in the last ten years been hurt by the papers of these two cities.\"}"
102+ , "{\"source\":\"Muscles: Testing and Function (4th Edition)\",\"author\":\"Florence Kendall, Elizabeth McCreary, Patricia Provance\",\"year\":1993,\"quote\":\"The mechanics of the low back is inseparable from that of the overall posture but especially that of the pelvis and the lower extremities. Pain manifested in the leg may be due to an underlying problem in the back. Conversely, the symptoms appearing in the low back may be due to underlying faulty mechanics of the feet, legs, or pelvis.\"}"
103+ , "{\"source\":\"Farmers of Forty Centuries\",\"author\":\"F. H. King\",\"year\":1911,\"quote\":\"The Sikiang is one of the great rivers of China and indeed of the world. Its width at Wuchow at low water was nearly a mile and our steamer anchored in twenty-four feet of water to a floating dock made fast by huge iron chains reaching three hundred feet up the slop to the city proper, thus providing for a rise of twenty-six feet in the river at its flood stage during the rainy season.\"}"
104+ , "{\"source\":\"How to Grow More Vegetables\",\"author\":\"John Jeavons\",\"year\":1974,\"quote\":\"If you are having trouble with birds eating the berries in your berry patch, you could erect a wren house in the middle of it. Wrens are insectivores, and they will not bother the berries. But they will attack any bird, however large, that comes near their nest.\"}"
105+ , "{\"source\":\"Confidence Men and Painted Women\",\"author\":\"Karen Halttunen\",\"year\":1982,\"quote\":\"Even one\\u2019s neighbor next door, as a visitor to Pittsburgh commented in 1818, might be a stranger: \\u201CA next door neighbor is, with them, frequently unknown, and months and years pass, without their exchanging with each other the ordinary compliments of friendship and goodwill.\\u201D\"}"
106+ , "{\"source\":\"Secondhand Time\",\"author\":\"Svetlana Alexievich\",\"year\":2016,\"quote\":\"I couldn\\u2019t understand what was going on. I remember seeing Gaidar on TV saying, \\u201Clearn how to sell... The market will save us...\\u201D You buy a bottle of mineral water on one corner and sell it on another\\u2014that\\u2019s business. The people listened, bewildered. I would come home, lock the door, and weep.\"}"
107+ , "{\"source\":\"Hiroshima\",\"author\":\"John Hersey\",\"year\":1985,\"quote\":\"At exactly fifteen minutes past eight in the morning, on August 6, 1945, Japanese time, at the moment when the atomic bomb flashed above Hiroshima, Miss Toshiko Sasaki, a clerk in the personnel department of the East Asia Tin Works, had just sat down at her place in the plant office and was turning her head to speak to the girl at the next desk.\"}"
108+ , "{\"source\":\"The Orphan\",\"author\":\"Maxim Gorky\",\"year\":1899,\"quote\":\"On a foggy and rainy day, by the cemetery gate, a small group of people standing in a muddy puddle were bargaining with the cabman. \\u201CFifteen kopeks!\\u201D The tall and heavy-set priest exclaimed in a deep bass, in response to the cabman\\u2019s shouts asking for twenty-five kopecks.\"}"
109+ , "{\"source\":\"Shah of Shahs\",\"author\":\"Ryszard Kapuściński\",\"year\":1982,\"quote\":\"This plane flies out of Teheran every day and lands at Munich at noon. Waiting limousines carry the passengers to elegant restaurants for lunch. After lunch they all fly back to Teheran in the same airplane and eat their suppers at home. Hardly an expensive entertainment, the jaunt costs only two thousand dollars a head. For people in the Shah\\u2019s favor, such a sum is nothing.\"}"
110+ , "{\"source\":\"Introduction to Fortran IV\",\"author\":\"Paul Chirlian\",\"year\":1973,\"quote\":\"There are many programming languages that can be used. We shall discuss a language that is almost universally used, and which is particularly applicable to mathematical and scientific computations. This language is FORTRAN IV.\"}"
111+ ]
112+
113+
114+
worker/src/Endpoint/Repl.hsnew file+244
@@ -0,0 +1,244 @@
1+{-# OPTIONS_GHC -Wall #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+module Endpoint.Repl
4+ ( endpoint
5+ )
6+ where
7+
8+
9+import Data.Aeson ((.:))
10+import qualified Data.Aeson as Aeson
11+import qualified Data.Aeson.Types as Aeson
12+import qualified Data.ByteString as BS
13+import qualified Data.ByteString.Builder as B
14+import qualified Data.ByteString.Lazy as LBS
15+import Data.Map ((!))
16+import qualified Data.Map as Map
17+import qualified Data.Map.Utils as Map
18+import qualified Data.Name as N
19+import qualified Data.NonEmptyList as NE
20+import Snap.Core
21+
22+import qualified Artifacts as A
23+import qualified Cors
24+
25+import qualified AST.Source as Src
26+import qualified AST.Canonical as Can
27+import qualified AST.Optimized as Opt
28+import qualified Compile
29+import qualified Elm.Interface as I
30+import qualified Elm.ModuleName as ModuleName
31+import qualified Elm.Package as Pkg
32+import qualified File
33+import qualified Generate.JavaScript as JS
34+import qualified Json.Encode as Encode
35+import qualified Parse.Module as Parse
36+import qualified Repl
37+import qualified Reporting.Annotation as A
38+import qualified Reporting.Error as Error
39+import qualified Reporting.Error.Import as Import
40+import qualified Reporting.Exit as Exit
41+import qualified Reporting.Exit.Help as Help
42+import qualified Reporting.Render.Type.Localizer as L
43+
44+
45+
46+-- ALLOWED ORIGINS
47+
48+
49+allowedOrigins :: [String]
50+allowedOrigins =
51+ [ "https://guide.elm-lang.org"
52+ , "https://guide.elm-lang.jp"
53+ , "http://localhost:8007"
54+ ]
55+
56+
57+
58+-- ENDPOINT
59+
60+
61+endpoint :: A.Artifacts -> Snap ()
62+endpoint artifacts =
63+ Cors.allow POST allowedOrigins $
64+ do body <- readRequestBody (64 * 1024)
65+ case decodeBody body of
66+ Just (state, entry) ->
67+ serveOutcome (toOutcome artifacts state entry)
68+
69+ Nothing ->
70+ do modifyResponse $ setResponseStatus 400 "Bad Request"
71+ modifyResponse $ setContentType "text/html; charset=utf-8"
72+ writeBS "Received unexpected JSON body."
73+
74+
75+
76+-- TO OUTCOME
77+
78+
79+data Outcome
80+ = NewImport N.Name
81+ | NewType N.Name
82+ | NewWork B.Builder
83+ --
84+ | Skip
85+ | Indent
86+ | DefStart N.Name
87+ --
88+ | NoPorts
89+ | InvalidCommand
90+ | Failure BS.ByteString Error.Error
91+
92+
93+toOutcome :: A.Artifacts -> Repl.State -> String -> Outcome
94+toOutcome artifacts state entry =
95+ case reverse (lines entry) of
96+ [] ->
97+ Skip
98+
99+ prev : rev ->
100+ case Repl.categorize (Repl.Lines prev rev) of
101+ Repl.Done input ->
102+ case input of
103+ Repl.Import name src -> compile artifacts state (ImportEntry name src)
104+ Repl.Type name src -> compile artifacts state (TypeEntry name src)
105+ Repl.Decl name src -> compile artifacts state (DeclEntry name src)
106+ Repl.Expr src -> compile artifacts state (ExprEntry src)
107+ Repl.Port -> NoPorts
108+ Repl.Skip -> Skip
109+ Repl.Reset -> InvalidCommand
110+ Repl.Exit -> InvalidCommand
111+ Repl.Help _ -> InvalidCommand
112+
113+ Repl.Continue prefill ->
114+ case prefill of
115+ Repl.Indent -> Indent
116+ Repl.DefStart name -> DefStart name
117+
118+
119+
120+-- SERVE OUTCOME
121+
122+
123+serveOutcome :: Outcome -> Snap ()
124+serveOutcome outcome =
125+ let
126+ serveString = serveBuilder "text/plain"
127+ in
128+ case outcome of
129+ NewImport name -> serveString $ "add-import:" <> N.toBuilder name
130+ NewType name -> serveString $ "add-type:" <> N.toBuilder name
131+ NewWork js -> serveBuilder "application/javascript" js
132+ Skip -> serveString $ "skip"
133+ Indent -> serveString $ "indent"
134+ DefStart name -> serveString $ "def-start:" <> N.toBuilder name
135+ NoPorts -> serveString $ "no-ports"
136+ InvalidCommand -> serveString $ "invalid-command"
137+ Failure source err ->
138+ serveBuilder "application/json" $ Encode.encodeUgly $ Exit.toJson $
139+ Help.compilerReport "/" (Error.Module N.replModule "/repl" File.zeroTime source err) []
140+
141+
142+serveBuilder :: BS.ByteString -> B.Builder -> Snap ()
143+serveBuilder mime builder =
144+ do modifyResponse (setContentType mime)
145+ writeBuilder builder
146+
147+
148+
149+-- COMPILE
150+
151+
152+data EntryType
153+ = ImportEntry N.Name BS.ByteString
154+ | TypeEntry N.Name BS.ByteString
155+ | DeclEntry N.Name BS.ByteString
156+ | ExprEntry BS.ByteString
157+
158+
159+compile :: A.Artifacts -> Repl.State -> EntryType -> Outcome
160+compile (A.Artifacts interfaces objects) state@(Repl.State imports types decls) entryType =
161+ let
162+ source =
163+ case entryType of
164+ ImportEntry name src -> Repl.toByteString (state { Repl._imports = Map.insert name (B.byteString src) imports }) Repl.OutputNothing
165+ TypeEntry name src -> Repl.toByteString (state { Repl._types = Map.insert name (B.byteString src) types }) Repl.OutputNothing
166+ DeclEntry name src -> Repl.toByteString (state { Repl._decls = Map.insert name (B.byteString src) decls }) (Repl.OutputDecl name)
167+ ExprEntry src -> Repl.toByteString state (Repl.OutputExpr src)
168+ in
169+ case
170+ do modul <- mapLeft Error.BadSyntax $ Parse.fromByteString Parse.Application source
171+ ifaces <- mapLeft Error.BadImports $ checkImports interfaces (Src._imports modul)
172+ artifacts <- Compile.compile Pkg.dummyName ifaces modul
173+ return ( modul, artifacts, objects )
174+ of
175+ Left err ->
176+ Failure source err
177+
178+ Right info ->
179+ case entryType of
180+ ImportEntry name _ -> NewImport name
181+ TypeEntry name _ -> NewType name
182+ DeclEntry name _ -> NewWork (toJavaScript info (Just name))
183+ ExprEntry _ -> NewWork (toJavaScript info Nothing)
184+
185+
186+toJavaScript :: (Src.Module, Compile.Artifacts, Opt.GlobalGraph) -> Maybe N.Name -> B.Builder
187+toJavaScript (modul, Compile.Artifacts canModule types locals, objects) maybeName =
188+ let
189+ localizer = L.fromModule modul
190+ graph = Opt.addLocalGraph locals objects
191+ home = Can._name canModule
192+ tipe = types ! maybe N.replValueToPrint id maybeName
193+ in
194+ JS.generateForReplEndpoint localizer graph home maybeName tipe
195+
196+
197+mapLeft :: (x -> y) -> Either x a -> Either y a
198+mapLeft func result =
199+ either (Left . func) Right result
200+
201+
202+checkImports :: Map.Map ModuleName.Raw I.Interface -> [Src.Import] -> Either (NE.List Import.Error) (Map.Map ModuleName.Raw I.Interface)
203+checkImports interfaces imports =
204+ let
205+ importDict = Map.fromValues Src.getImportName imports
206+ missing = Map.difference importDict interfaces
207+ in
208+ case Map.elems missing of
209+ [] ->
210+ Right (Map.intersection interfaces importDict)
211+
212+ i:is ->
213+ let
214+ unimported =
215+ Map.keysSet (Map.difference interfaces importDict)
216+
217+ toError (Src.Import (A.At region name) _ _) =
218+ Import.Error region name unimported Import.NotFound
219+ in
220+ Left (fmap toError (NE.List i is))
221+
222+
223+
224+-- DECODE BODY
225+
226+
227+decodeBody :: LBS.ByteString -> Maybe ( Repl.State, String )
228+decodeBody body =
229+ Aeson.parseMaybe decodeBodyHelp =<< Aeson.decode' body
230+
231+
232+decodeBodyHelp :: Aeson.Object -> Aeson.Parser ( Repl.State, String )
233+decodeBodyHelp obj =
234+ let
235+ get key =
236+ do dict <- obj .: key
237+ let f (k,v) = (N.fromChars k, B.stringUtf8 v)
238+ return $ Map.fromList $ map f $ Map.toList dict
239+ in
240+ do imports <- get "imports"
241+ types <- get "types"
242+ decls <- get "decls"
243+ entry <- obj .: "entry"
244+ return ( Repl.State imports types decls, entry )
worker/src/Errors.elmnew file+217
@@ -0,0 +1,217 @@
1+port module Errors exposing (main)
2+
3+
4+import Browser
5+import Char
6+import Html exposing (..)
7+import Html.Attributes exposing (..)
8+import Html.Events exposing (onClick)
9+import String
10+import Json.Decode as D
11+import Elm.Error as Error
12+
13+
14+
15+-- PORTS
16+
17+
18+port jumpTo : Error.Region -> Cmd msg
19+
20+
21+
22+-- MAIN
23+
24+
25+main =
26+ Browser.document
27+ { init = \flags -> (D.decodeValue Error.decoder flags, Cmd.none)
28+ , update = \region result -> (result, jumpTo region)
29+ , view = view
30+ , subscriptions = \_ -> Sub.none
31+ }
32+
33+
34+type alias Msg = Error.Region
35+
36+
37+
38+-- VIEW
39+
40+
41+view : Result D.Error Error.Error -> Browser.Document Msg
42+view result =
43+ { title = "Problem!"
44+ , body =
45+ case result of
46+ Err err ->
47+ [ text (D.errorToString err) ]
48+
49+ Ok error ->
50+ [ viewError error ]
51+ }
52+
53+
54+viewError : Error.Error -> Html Msg
55+viewError error =
56+ div
57+ [ style "width" "calc(100% - 4em)"
58+ , style "min-height" "calc(100% - 4em)"
59+ , style "font-family" "monospace"
60+ , style "white-space" "pre-wrap"
61+ , style "background-color" "black"
62+ , style "color" "rgb(233,235,235)"
63+ , style "padding" "2em"
64+ ]
65+ (viewErrorHelp error)
66+
67+
68+viewErrorHelp : Error.Error -> List (Html Msg)
69+viewErrorHelp error =
70+ case error of
71+ Error.GeneralProblem { title, message } ->
72+ viewHeader title Nothing :: viewMessage message
73+
74+ Error.ModuleProblems badModules ->
75+ viewBadModules badModules
76+
77+
78+
79+-- VIEW HEADER
80+
81+
82+viewHeader : String -> Maybe Error.Region -> Html Msg
83+viewHeader title maybeRegion =
84+ case maybeRegion of
85+ Nothing ->
86+ span [ style "color" "rgb(51,187,200)" ]
87+ [ text <| "-- " ++ title ++ " "
88+ , text <| String.repeat (76 - String.length title) "-"
89+ , text <| "\n\n"
90+ ]
91+
92+ Just region ->
93+ span [ style "color" "rgb(51,187,200)" ]
94+ [ text <| "-- " ++ title ++ " "
95+ , text <| String.repeat (60 - String.length title) "-"
96+ , text " "
97+ , span
98+ [ style "cursor" "pointer"
99+ , style "text-decoration" "underline"
100+ , onClick region
101+ ]
102+ [ text "Jump To Problem"
103+ ]
104+ , text <| "\n\n"
105+ ]
106+
107+
108+
109+-- VIEW BAD MODULES
110+
111+
112+viewBadModules : List Error.BadModule -> List (Html Msg)
113+viewBadModules badModules =
114+ case badModules of
115+ [] ->
116+ []
117+
118+ [badModule] ->
119+ [viewBadModule badModule]
120+
121+ a :: b :: cs ->
122+ viewBadModule a :: viewSeparator a.name b.name :: viewBadModules (b :: cs)
123+
124+
125+viewBadModule : Error.BadModule -> Html Msg
126+viewBadModule { problems } =
127+ span [] (List.map viewProblem problems)
128+
129+
130+viewProblem : Error.Problem -> Html Msg
131+viewProblem problem =
132+ span [] (viewHeader problem.title (Just problem.region) :: viewMessage problem.message)
133+
134+
135+viewSeparator : String -> String -> Html msg
136+viewSeparator before after =
137+ span [ style "color" "rgb(211,56,211)" ]
138+ [ text <|
139+ String.padLeft 80 ' ' (before ++ " ↑ ") ++ "\n" ++
140+ "====o======================================================================o====\n" ++
141+ " ↓ " ++ after ++ "\n\n\n"
142+ ]
143+
144+
145+
146+-- VIEW MESSAGE
147+
148+
149+viewMessage : List Error.Chunk -> List (Html msg)
150+viewMessage chunks =
151+ case chunks of
152+ [] ->
153+ [ text "\n\n\n" ]
154+
155+ chunk :: others ->
156+ let
157+ htmlChunk =
158+ case chunk of
159+ Error.Unstyled string ->
160+ text string
161+
162+ Error.Styled style string ->
163+ span (styleToAttrs style) [ text string ]
164+ in
165+ htmlChunk :: viewMessage others
166+
167+
168+styleToAttrs : Error.Style -> List (Attribute msg)
169+styleToAttrs { bold, underline, color } =
170+ addBold bold <| addUnderline underline <| addColor color []
171+
172+
173+addBold : Bool -> List (Attribute msg) -> List (Attribute msg)
174+addBold bool attrs =
175+ if bool then
176+ style "font-weight" "bold" :: attrs
177+ else
178+ attrs
179+
180+
181+addUnderline : Bool -> List (Attribute msg) -> List (Attribute msg)
182+addUnderline bool attrs =
183+ if bool then
184+ style "text-decoration" "underline" :: attrs
185+ else
186+ attrs
187+
188+
189+addColor : Maybe Error.Color -> List (Attribute msg) -> List (Attribute msg)
190+addColor maybeColor attrs =
191+ case maybeColor of
192+ Nothing ->
193+ attrs
194+
195+ Just color ->
196+ style "color" (colorToCss color) :: attrs
197+
198+
199+colorToCss : Error.Color -> String
200+colorToCss color =
201+ case color of
202+ Error.Red -> "rgb(194,54,33)"
203+ Error.RED -> "rgb(252,57,31)"
204+ Error.Magenta -> "rgb(211,56,211)"
205+ Error.MAGENTA -> "rgb(249,53,248)"
206+ Error.Yellow -> "rgb(173,173,39)"
207+ Error.YELLOW -> "rgb(234,236,35)"
208+ Error.Green -> "rgb(37,188,36)"
209+ Error.GREEN -> "rgb(49,231,34)"
210+ Error.Cyan -> "rgb(51,187,200)"
211+ Error.CYAN -> "rgb(20,240,240)"
212+ Error.Blue -> "rgb(73,46,225)"
213+ Error.BLUE -> "rgb(88,51,255)"
214+ Error.White -> "rgb(203,204,205)"
215+ Error.WHITE -> "rgb(233,235,235)"
216+ Error.Black -> "rgb(0,0,0)"
217+ Error.BLACK -> "rgb(129,131,131)"
worker/src/Main.hs+36−241
@@ -1,49 +1,21 @@
1−{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
1+{-# OPTIONS_GHC -Wall #-}
2+{-# LANGUAGE OverloadedStrings #-}
23module Main
34 ( main
45 )
56 where
67
78
8−import Control.Applicative ((<|>))
9−import Control.Concurrent (readMVar)
10−import Control.Monad (liftM2, msum)
11−import qualified Data.ByteString as B
12−import qualified Data.ByteString.Builder as B
13−import qualified Data.ByteString.Lazy as LBS
14−import qualified Data.HashSet as HashSet
15−import qualified Data.Map as Map
16−import qualified Data.Map.Utils as Map
17−import qualified Data.NonEmptyList as NE
18−import qualified Data.OneOrMore as OneOrMore
19−import Network.URI (parseURI)
9+import Control.Monad (msum)
10+import qualified Data.ByteString as BS
2011import Snap.Core
2112import Snap.Http.Server
22−import Snap.Util.CORS
23−import Snap.Util.FileServe (serveFile)
24−import Snap.Util.FileUploads
25−import qualified System.Directory as Dir
26−import qualified System.IO.Streams as Stream
27−import Text.RawString.QQ (r)
2813
29−import qualified AST.Source as Src
30−import qualified AST.Canonical as Can
31−import qualified AST.Optimized as Opt
32−import qualified Compile
33−import qualified Elm.Details as Details
34−import qualified Elm.Interface as I
35−import qualified Elm.ModuleName as ModuleName
36−import qualified Elm.Package as Pkg
37−import qualified Generate.Html as Html
38−import qualified Generate.JavaScript as Generate
39−import qualified Generate.Mode as Mode
40−import qualified Json.Encode as Encode
41−import qualified Parse.Module as Parse
42−import qualified Reporting
43−import qualified Reporting.Annotation as A
44−import qualified Reporting.Error as Error
45−import qualified Reporting.Error.Import as Import
46−import qualified Reporting.Render.Code as Code
14+import qualified Artifacts
15+import qualified Cors
16+import qualified Endpoint.Compile as Compile
17+import qualified Endpoint.Quotes as Quotes
18+import qualified Endpoint.Repl as Repl
4719
4820
4921
@@ -52,227 +24,50 @@ import qualified Reporting.Render.Code as Code
5224
5325main :: IO ()
5426main =
55− do artifacts <- loadArtifacts
56− errorHtml <- compileErrorViewer artifacts
27+ do rArtifacts <- Artifacts.loadRepl
28+ cArtifacts <- Artifacts.loadCompile
29+ errorJS <- Compile.loadErrorJS
30+ let depsInfo = Artifacts.toDepsInfo cArtifacts
31+
5732 httpServe config $ msum $
58− [ path "compile" $ compile artifacts
59− , path "compile/error.js" $ writeBS errorHtml
33+ [ ifTop $ status
34+ , path "repl" $ Repl.endpoint rArtifacts
35+ , path "compile" $ Compile.endpoint_V1 cArtifacts
36+ , path "compile/v2" $ Compile.endpoint_V2 cArtifacts
37+ , path "compile/errors.js" $ serveJavaScript errorJS
38+ , path "compile/deps-info.json" $ serveDepsInfo depsInfo
39+ , path "quotes" $ Quotes.endpoint
6040 , notFound
6141 ]
6242
6343
6444config :: Config Snap a
6545config =
66− defaultConfig
67− |> setVerbose False
68− |> setPort 8000
69− |> setAccessLog ConfigNoLog
70− |> setErrorLog ConfigNoLog
71−
72−
73−(|>) :: a -> (a -> b) -> b
74−(|>) value func =
75− func value
46+ setPort 8000 $ setAccessLog ConfigNoLog $ setErrorLog ConfigNoLog $ defaultConfig
7647
7748
78−
79−-- NOT FOUND
49+status :: Snap ()
50+status =
51+ do modifyResponse $ setContentType "text/plain"
52+ writeBuilder "Status: OK"
8053
8154
8255notFound :: Snap ()
8356notFound =
8457 do modifyResponse $ setResponseStatus 404 "Not Found"
8558 modifyResponse $ setContentType "text/html; charset=utf-8"
86− writeBS "Not Found"
87−
88−
89−
90−-- COMPILE
91−
92−
93−compile :: Artifacts -> Snap ()
94−compile artifacts =
95− applyCORS corsOptions $ method POST $
96− do parts <- handleMultipart defaultUploadPolicy handlePart
97− case parts of
98− [Just source] ->
99− case compileToBuilder artifacts source of
100− Left err ->
101− writeBuilder $ errorToHtmlBuilder source err
102−
103− Right builder ->
104− writeBuilder builder
105−
106− _ ->
107− pass
108−
109−
110−handlePart :: PartInfo -> Stream.InputStream B.ByteString -> IO (Maybe B.ByteString)
111−handlePart info stream =
112− if partFieldName info == "code" && partDisposition info == DispositionFormData
113− then Just . LBS.toStrict <$> storeAsLazyByteString stream
114− else return Nothing
115−
116−
117−errorToHtmlBuilder :: B.ByteString -> Error.Error -> B.Builder
118−errorToHtmlBuilder source err =
119− let
120− json = Encode.encodeUgly (Error.errorToJson (Code.toSource source) err)
121− in
122− [r|<!DOCTYPE HTML>
123−<html>
124−<head>
125− <meta charset="UTF-8">
126− <style>body { padding: 0; margin: 0; }</style>
127− <script src="https://worker.elm-lang.org/compile/error.js"></script>
128− <script>Elm.Error.init({flags:|] <> json <> [r|})</script>
129−</head>
130−<body></body>
131−</html>|]
132−
133−
134−
135−compileToBuilder :: Artifacts -> B.ByteString -> Either Error.Error B.Builder
136−compileToBuilder (Artifacts interfaces objects) source =
137− case Parse.fromByteString Pkg.dummyName source of
138− Left err ->
139− Left (Error.BadSyntax err)
140−
141− Right modul@(Src.Module _ _ _ imports _ _ _ _ _) ->
142− case checkImports interfaces imports of
143− Left err ->
144− Left err
145−
146− Right ifaces ->
147− case Compile.compile Pkg.dummyName ifaces modul of
148− Left err ->
149− Left err
150−
151− Right artifacts@(Compile.Artifacts modul _ locals@(Opt.LocalGraph maybeMain _ _)) ->
152− case maybeMain of
153− Nothing ->
154− Left (error "TODO no main")
155−
156− Just main ->
157− let
158− mode = Mode.Dev Nothing
159− home = Can._name modul
160− name = ModuleName._module home
161− mains = Map.singleton home main
162− graph = Opt.addLocalGraph locals objects
163− in
164− Right $ Html.sandwich name $ Generate.generate mode graph mains
165−
166−
167−checkImports :: Map.Map ModuleName.Raw I.Interface -> [Src.Import] -> Either Error.Error (Map.Map ModuleName.Raw I.Interface)
168−checkImports interfaces imports =
169− let
170− importDict = Map.fromValues Src.getImportName imports
171− missing = Map.difference importDict interfaces
172− in
173− case Map.elems missing of
174− [] ->
175− Right (Map.intersection interfaces importDict)
176−
177− i:is ->
178− let
179− unimported = Map.keysSet (Map.difference interfaces importDict)
180− toError (Src.Import (A.At region name) _ _) =
181− Import.Error region name unimported Import.NotFound
182− in
183− Left (Error.BadImports (fmap toError (NE.List i is)))
184−
185−
186−
187−-- COMPILE ERROR VIEWER
188−
189−
190−compileErrorViewer :: Artifacts -> B.ByteString
191−compileErrorViewer artifacts =
192− do source <- File.readUtf8 "src/Error.elm"
193− case compileToBuilder artifacts source of
194− Left err ->
195− error "problem compiling src/Error.elm"
196−
197− Right builder ->
198− return (LBS.toStrict (B.toLazyByteString builder))
199−
200−
201−
202−-- CORS OPTIONS
203−
204−
205−corsOptions :: (Monad m) => CORSOptions m
206−corsOptions =
207− let
208− allowedOrigins = toOriginList [ "https://elm-lang.org", "https://package.elm-lang.org" ]
209− allowedMethods = HashSet.singleton (HashableMethod POST)
210− in
211− CORSOptions
212− { corsAllowOrigin = return allowedOrigins
213− , corsAllowCredentials = return True
214− , corsExposeHeaders = return HashSet.empty
215− , corsAllowedMethods = return allowedMethods
216− , corsAllowedHeaders = return
217− }
218−
219−
220−toOriginList :: [String] -> OriginList
221−toOriginList origins =
222− Origins $ mkOriginSet $
223− case traverse parseURI origins of
224− Just uris -> uris
225− Nothing -> error "invalid entry given to toOriginList list"
226−
227−
228−
229−-- ARTIFACTS
230−
231−
232−data Artifacts =
233− Artifacts
234− { _ifaces :: Map.Map ModuleName.Raw I.Interface
235− , _graph :: Opt.GlobalGraph
236− }
237−
238−
239−loadArtifacts :: IO Artifacts
240−loadArtifacts =
241− do style <- Reporting.terminal
242− root <- Dir.getCurrentDirectory
243− result <- Details.load style root
244− case result of
245− Left _ ->
246− error "Ran into some problem loading elm.json details"
247−
248− Right details ->
249− do omvar <- Details.loadObjects root details
250− imvar <- Details.loadInterfaces root details
251− mdeps <- readMVar imvar
252− mobjs <- readMVar omvar
253− case liftM2 (,) mdeps mobjs of
254− Nothing ->
255− error "Ran into some weird problem loading elm.json details"
256−
257− Just (deps, objs) ->
258− return $ Artifacts (toInterfaces deps) objs
259−
59+ writeBuilder "Not Found"
26060
261−toInterfaces :: Map.Map ModuleName.Canonical I.DependencyInterface -> Map.Map ModuleName.Raw I.Interface
262−toInterfaces deps =
263− Map.mapMaybe toUnique $ Map.fromListWith OneOrMore.more $
264− Map.elems (Map.mapMaybeWithKey getPublic deps)
26561
62+serveJavaScript :: BS.ByteString -> Snap ()
63+serveJavaScript javascript =
64+ do modifyResponse $ setContentType "application/javascript"
65+ writeBS javascript
26666
267−getPublic :: ModuleName.Canonical -> I.DependencyInterface -> Maybe (ModuleName.Raw, OneOrMore.OneOrMore I.Interface)
268−getPublic (ModuleName.Canonical _ name) dep =
269− case dep of
270− I.Public iface -> Just (name, OneOrMore.one iface)
271− I.Private _ _ _ -> Nothing
27267
68+serveDepsInfo :: BS.ByteString -> Snap ()
69+serveDepsInfo json =
70+ Cors.allow GET ["https://elm-lang.org"] $
71+ do modifyResponse $ setContentType "application/json"
72+ writeBS json
27373
274−toUnique :: OneOrMore.OneOrMore a -> Maybe a
275−toUnique oneOrMore =
276− case oneOrMore of
277− OneOrMore.One value -> Just value
278− OneOrMore.More _ _ -> Nothing