on 18820a0 help sign in
183 files changed+6300−11524
since splitsnapshots
unifiedsplit
.github/CONTRIBUTING.md+20−18 .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+25−6 README.md+5−10 builder/src/BackgroundWriter.hs−42 builder/src/Build.hs+294−531 builder/src/Deps/Bump.hs−37 builder/src/Deps/Diff.hs+5−7 builder/src/Deps/Registry.hs+68−35 builder/src/Deps/Solver.hs+29−31 builder/src/Elm/Bump.hs+137 builder/src/Elm/Details.hs+96−193 builder/src/Elm/Diff.hs+284 builder/src/Elm/Outline.hs+117−146 builder/src/Elm/Publish.hs+255 builder/src/File.hs+5−28 builder/src/Generate.hs−211 builder/src/Http.hs+1−14 builder/src/Reporting.hs+22−43 builder/src/Reporting/Exit.hs+375−1616 builder/src/Reporting/Exit/Assets.hs+227 builder/src/Reporting/Exit/Crawl.hs+345 builder/src/Reporting/Exit/Deps.hs+123 builder/src/Reporting/Exit/Help.hs+10−9 builder/src/Reporting/Exit/Http.hs+104 builder/src/Reporting/Task.hs−17 builder/src/Stuff.hs+9−8 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+6−5 compiler/src/AST/Utils/Shader.hs+4−51 compiler/src/AST/Utils/Type.hs+1 compiler/src/Canonicalize/Environment.hs+20−50 compiler/src/Canonicalize/Environment/Dups.hs+1−1 compiler/src/Canonicalize/Environment/Foreign.hs+37−49 compiler/src/Canonicalize/Environment/Local.hs+5−5 compiler/src/Canonicalize/Expression.hs+7−6 compiler/src/Canonicalize/Module.hs+7−7 compiler/src/Canonicalize/Pattern.hs+2−3 compiler/src/Data/Name.hs+60−60 compiler/src/Data/NonEmptyList.hs+2−6 compiler/src/Data/Utf8.hs+4−6 compiler/src/Elm/Compiler/Imports.hs+3−3 compiler/src/Elm/Compiler/Type/Extract.hs+1−1 compiler/src/Elm/Constraint.hs+77−55 compiler/src/Elm/Docs.hs+158−218 compiler/src/Elm/Interface.hs+3−3 compiler/src/Elm/Kernel.hs+46−48 compiler/src/Elm/Licenses.hs+25−25 compiler/src/Elm/ModuleName.hs+39−65 compiler/src/Elm/Package.hs+15−5 compiler/src/Elm/String.hs+1 compiler/src/Generate/Html.hs+10−11 compiler/src/Generate/JavaScript.hs+19−51 compiler/src/Generate/JavaScript/Builder.hs−13 compiler/src/Generate/JavaScript/Expression.hs+3−5 compiler/src/Generate/JavaScript/Name.hs+12−22 compiler/src/Generate/Mode.hs+1 compiler/src/Json/Decode.hs+73−78 compiler/src/Json/Encode.hs+5−23 compiler/src/Json/String.hs+3−8 compiler/src/Nitpick/PatternMatches.hs+3−3 compiler/src/Optimize/DecisionTree.hs+5−5 compiler/src/Optimize/Module.hs+3−3 compiler/src/Optimize/Port.hs+3−3 compiler/src/Parse/Docs.hs+275 compiler/src/Parse/Expression.hs+38−46 compiler/src/Parse/Module.hs+107−156 compiler/src/Parse/Number.hs+8−8 compiler/src/Parse/Pattern.hs+7−7 compiler/src/Parse/Primitives.hs+4−4 compiler/src/Parse/Repl.hs+117 compiler/src/Parse/Shader.hs+14−16 compiler/src/Parse/Space.hs+4−4 compiler/src/Parse/String.hs+5−5 compiler/src/Parse/Symbol.hs+1−1 compiler/src/Parse/Variable.hs+14−15 compiler/src/Reporting/Annotation.hs+1−1 compiler/src/Reporting/Doc.hs+47−79 compiler/src/Reporting/Error.hs+26−32 compiler/src/Reporting/Error/Canonicalize.hs+40−41 compiler/src/Reporting/Error/Docs.hs+18−127 compiler/src/Reporting/Error/Import.hs+1−1 compiler/src/Reporting/Error/Json.hs+269−281 compiler/src/Reporting/Error/Pattern.hs+4−5 compiler/src/Reporting/Error/Syntax.hs+460−1036 compiler/src/Reporting/Error/Type.hs+23−44 compiler/src/Reporting/Render/Code.hs+26−67 compiler/src/Reporting/Render/Type/Localizer.hs+25−5 compiler/src/Reporting/Result.hs−10 compiler/src/Type/Error.hs+123−14 compiler/src/Type/Solve.hs−7 compiler/src/Type/Unify.hs+10−12 docs/elm.json/application.md+2−2 docs/elm.json/package.md+1−1 docs/upgrade-instructions/0.19.1.md−60 elm.cabal+12−31 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+3−5 installers/mac/README.md−93 installers/mac/Resources/en.lproj/background.png installers/mac/Resources/en.lproj/conclusion.rtf+6−13 installers/mac/Resources/en.lproj/welcome.rtf+4−9 installers/mac/helper-scripts/elm-startup.sh+1−1 installers/mac/make-installer.sh+3−30 installers/npm/PUBLISHING.md+141−29 installers/npm/README.md+23−30 installers/npm/bin/elm+16−42 installers/npm/download.js+67−68 installers/npm/install.js+7−1 installers/npm/package.json+7−6 installers/npm/troubleshooting.md−76 installers/win/Nsisfile.nsi+16−16 installers/win/README.md+3−18 installers/win/file.ico installers/win/inst.dat+2−1 installers/win/logo.ico installers/win/uninst.dat+2−1 installers/win/welcome.bmp reactor/assets/waiting.gif reactor/elm.json+2−2 reactor/src/Index.elm+15−20 reactor/src/Index/Navigator.elm+1−1 roadmap.md−29 terminal/src/Bump.hs+8−158 terminal/src/Develop.hs+77−70 terminal/src/Develop/Generate/Index.hs+74−149 terminal/src/Develop/StaticFiles.hs+7−1 terminal/src/Develop/StaticFiles/Build.hs+29−46 terminal/src/Diff.hs+6−348 terminal/src/Init.hs+1−1 terminal/src/Install.hs+31−16 terminal/src/Main.hs+36−32 terminal/src/Make.hs+268−113 terminal/src/Publish.hs+8−529 terminal/src/Repl.hs+197−522 terminal/impl/Terminal.hs → terminal/src/Terminal/Args.hs+27−33 terminal/impl/Terminal/Chomp.hs → terminal/src/Terminal/Args/Chomp.hs+5−4 terminal/impl/Terminal/Error.hs → terminal/src/Terminal/Args/Error.hs+18−28 terminal/impl/Terminal/Helpers.hs → terminal/src/Terminal/Args/Helpers.hs+19−41 terminal/impl/Terminal/Internal.hs → terminal/src/Terminal/Args/Internal.hs+8−8 docs/upgrade-instructions/0.16.md → upgrade-docs/0.16.md docs/upgrade-instructions/0.17.md → upgrade-docs/0.17.md docs/upgrade-instructions/0.18.md → upgrade-docs/0.18.md docs/upgrade-instructions/0.19.0.md → upgrade-docs/0.19.md docs/upgrade-instructions/earlier.md → upgrade-docs/earlier.md worker/elm.cabal+3−25 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+241−36
.github/CONTRIBUTING.md+20−18
@@ -4,15 +4,10 @@ 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
78
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−
9+You need to sign the [contributor agreement](ContributorAgreement.pdf)
10+and send it to <info@elm-lang.org> before opening your pull request.
1611
1712## Style Guide
1813
@@ -22,20 +17,27 @@ Finally, please be patient with the core team. They are trying their best with l
2217[haskell]: https://gist.github.com/evancz/0a1f3717c92fe71702be
2318[js]: https://google.github.io/styleguide/javascriptguide.xml
2419
25−
2620## Branches
2721
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!
31−
32−[master]: http://github.com/elm-lang/elm/tree/master
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!
3325
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.
3429
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:
30+[master]: http://github.com/elm-lang/elm/tree/master
31+[stable]: http://github.com/elm-lang/elm/tree/stable
3832
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.
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.
4037
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.
4142
43+[website]: https://github.com/elm-lang/elm-lang.org
.github/PULL_REQUEST_TEMPLATE.mddeleted−18
@@ -1,18 +0,0 @@
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.ymldeleted−21
@@ -1,21 +0,0 @@
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.ymldeleted−19
@@ -1,19 +0,0 @@
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,4 +5,3 @@ cabal-dev
55cabal.sandbox.config
66.DS_Store
77*~
8−travis.log
.travis.ymldeleted−28
@@ -1,28 +0,0 @@
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.pdfnew file

Binary file not shown.

LICENSE+25−6
@@ -1,11 +1,30 @@
1−Copyright 2012-present Evan Czaplicki
1+Copyright (c) 2012-present, Evan Czaplicki
22
3−Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
3+All rights reserved.
44
5−1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
5+Redistribution and use in source and binary forms, with or without
6+modification, are permitted provided that the following conditions are met:
67
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.
8+ * Redistributions of source code must retain the above copyright
9+ notice, this list of conditions and the following disclaimer.
810
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.
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.
1015
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.
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.
README.md+5−10
@@ -1,22 +1,17 @@
1−# Elm
1+# The Elm Compiler
22
3−A delightful language for reliable webapps.
3+Learn about the Elm programming language at [elm-lang.org](http://elm-lang.org/).
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>
95
106## Install
117
12−✨ [Install](https://guide.elm-lang.org/install/elm.html) ✨
8+Follow [these instructions][installer]!
139
14−For multiple versions, previous versions, and uninstallation, see the instructions [here](https://github.com/elm/compiler/blob/master/installers/README.md).
10+ [installer]: https://guide.elm-lang.org/install.html
1511
16−<br>
1712
1813## Help
1914
2015If you are stuck, ask around on [the Elm slack channel][slack]. Folks are friendly and happy to help with questions!
2116
22−[slack]: http://elmlang.herokuapp.com/
17+[slack]: http://elmlang.herokuapp.com/
builder/src/BackgroundWriter.hsdeleted−42
@@ -1,42 +0,0 @@
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+294−531
@@ -1,16 +1,12 @@
11{-# OPTIONS_GHC -Wno-unused-do-bind #-}
2−{-# LANGUAGE BangPatterns, GADTs, OverloadedStrings #-}
2+{-# LANGUAGE BangPatterns, OverloadedStrings #-}
33module Build
44 ( fromExposed
5− , fromPaths
6− , fromRepl
5+ , fromMains
76 , Artifacts(..)
8− , Root(..)
7+ , Main(..)
98 , Module(..)
109 , CachedInterface(..)
11− , ReplArtifacts(..)
12− , DocsGoal(..)
13− , getRootNames
1410 )
1511 where
1612
@@ -20,6 +16,7 @@ import Control.Concurrent.MVar
2016import Control.Monad (filterM, mapM_, sequence_)
2117import qualified Data.ByteString as B
2218import qualified Data.Char as Char
19+import qualified Data.Either as Either
2320import qualified Data.Graph as Graph
2421import qualified Data.List as List
2522import qualified Data.Map.Utils as Map
@@ -34,27 +31,22 @@ import qualified System.Directory as Dir
3431import qualified System.FilePath as FP
3532import System.FilePath ((</>), (<.>))
3633
37−import qualified AST.Canonical as Can
3834import qualified AST.Source as Src
3935import qualified AST.Optimized as Opt
4036import qualified Compile
4137import qualified Elm.Details as Details
42−import qualified Elm.Docs as Docs
4338import qualified Elm.Interface as I
4439import qualified Elm.ModuleName as ModuleName
4540import qualified Elm.Outline as Outline
4641import qualified Elm.Package as Pkg
4742import qualified File
48−import qualified Json.Encode as E
4943import qualified Parse.Module as Parse
5044import qualified Reporting
5145import qualified Reporting.Annotation as A
5246import qualified Reporting.Error as Error
53−import qualified Reporting.Error.Docs as EDocs
5447import qualified Reporting.Error.Syntax as Syntax
5548import qualified Reporting.Error.Import as Import
5649import qualified Reporting.Exit as Exit
57−import qualified Reporting.Render.Type.Localizer as L
5850import qualified Stuff
5951
6052
@@ -66,57 +58,27 @@ data Env =
6658 Env
6759 { _key :: Reporting.BKey
6860 , _root :: FilePath
69− , _project :: Parse.ProjectType
70− , _srcDirs :: [AbsoluteSrcDir]
71− , _buildID :: Details.BuildID
61+ , _pkg :: Pkg.Name
62+ , _srcDirs :: [FilePath]
7263 , _locals :: Map.Map ModuleName.Raw Details.Local
7364 , _foreigns :: Map.Map ModuleName.Raw Details.Foreign
7465 }
7566
7667
77−makeEnv :: Reporting.BKey -> FilePath -> Details.Details -> IO Env
78−makeEnv key root (Details.Details _ validOutline buildID locals foreigns _) =
68+makeEnv :: Reporting.BKey -> FilePath -> Details.Details -> Env
69+makeEnv key root (Details.Details _ validOutline locals foreigns _) =
7970 case validOutline of
80− Details.ValidApp givenSrcDirs ->
81− do srcDirs <- traverse (toAbsoluteSrcDir root) (NE.toList givenSrcDirs)
82− return $ Env key root Parse.Application srcDirs buildID locals foreigns
71+ Details.ValidApp (Outline.AppOutline _ srcDirs _ _ _ _) ->
72+ Env key root Pkg.dummyName (NE.toList srcDirs) locals foreigns
8373
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
74+ Details.ValidPkg (Outline.PkgOutline pkg _ _ _ _ _ _ _) _ ->
75+ Env key root pkg ["src"] locals foreigns
11076
11177
11278
11379-- FORK
11480
11581
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−--
12082fork :: IO a -> IO (MVar a)
12183fork work =
12284 do mvar <- newEmptyMVar
@@ -134,22 +96,21 @@ forkWithKey func dict =
13496-- FROM EXPOSED
13597
13698
137−fromExposed :: Reporting.Style -> FilePath -> Details.Details -> DocsGoal docs -> NE.List ModuleName.Raw -> IO (Either Exit.BuildProblem docs)
138−fromExposed style root details docsGoal exposed@(NE.List e es) =
99+fromExposed :: Reporting.Style -> FilePath -> Details.Details -> NE.List ModuleName.Raw -> IO (Either Exit.BuildProblem ())
100+fromExposed style root details exposed@(NE.List e es) =
139101 Reporting.trackBuild style $ \key ->
140− do env <- makeEnv key root details
102+ do let env = makeEnv key root details
141103 dmvar <- Details.loadInterfaces root details
142104
143105 -- crawl
144106 mvar <- newEmptyMVar
145− let docsNeed = toDocsNeed docsGoal
146− roots <- Map.fromKeysA (fork . crawlModule env mvar docsNeed) (e:es)
107+ roots <- Map.fromKeysA (fork . crawlModule env mvar) (e:es)
147108 putMVar mvar roots
148109 mapM_ readMVar roots
149110 statuses <- traverse readMVar =<< readMVar mvar
150111
151112 -- compile
152− midpoint <- checkMidpoint dmvar statuses
113+ midpoint <- checkExposedMidpoint dmvar statuses
153114 case midpoint of
154115 Left problem ->
155116 return (Left (Exit.BuildProjectProblem problem))
@@ -160,18 +121,18 @@ fromExposed style root details docsGoal exposed@(NE.List e es) =
160121 putMVar rmvar resultMVars
161122 results <- traverse readMVar resultMVars
162123 writeDetails root details results
163− finalizeExposed root docsGoal exposed results
124+ return (detectExposedProblems exposed results)
164125
165126
166127
167−-- FROM PATHS
128+-- FROM MAINS
168129
169130
170131data Artifacts =
171132 Artifacts
172133 { _name :: Pkg.Name
173134 , _deps :: Dependencies
174− , _roots :: NE.List Root
135+ , _mains :: NE.List Main
175136 , _modules :: [Module]
176137 }
177138
@@ -185,25 +146,25 @@ type Dependencies =
185146 Map.Map ModuleName.Canonical I.DependencyInterface
186147
187148
188−fromPaths :: Reporting.Style -> FilePath -> Details.Details -> NE.List FilePath -> IO (Either Exit.BuildProblem Artifacts)
189−fromPaths style root details paths =
149+fromMains :: Reporting.Style -> FilePath -> Details.Details -> NE.List FilePath -> IO (Either Exit.BuildProblem Artifacts)
150+fromMains style root details paths =
190151 Reporting.trackBuild style $ \key ->
191− do env <- makeEnv key root details
152+ do let env = makeEnv key root details
192153
193− elroots <- findRoots env paths
194− case elroots of
154+ elmains <- findMains env paths
155+ case elmains of
195156 Left problem ->
196157 return (Left (Exit.BuildProjectProblem problem))
197158
198− Right lroots ->
159+ Right lmains ->
199160 do -- crawl
200161 dmvar <- Details.loadInterfaces root details
201162 smvar <- newMVar Map.empty
202− srootMVars <- traverse (fork . crawlRoot env smvar) lroots
203− sroots <- traverse readMVar srootMVars
163+ smainMVars <- traverse (fork . crawlMain env smvar) lmains
164+ smains <- traverse readMVar smainMVars
204165 statuses <- traverse readMVar =<< readMVar smvar
205166
206− midpoint <- checkMidpointAndRoots dmvar statuses sroots
167+ midpoint <- checkMainsMidpoint dmvar statuses smains
207168 case midpoint of
208169 Left problem ->
209170 return (Left (Exit.BuildProjectProblem problem))
@@ -213,26 +174,10 @@ fromPaths style root details paths =
213174 rmvar <- newEmptyMVar
214175 resultsMVars <- forkWithKey (checkModule env foreigns rmvar) statuses
215176 putMVar rmvar resultsMVars
216− rrootMVars <- traverse (fork . checkRoot env resultsMVars) sroots
177+ rmainMVars <- traverse (fork . checkMain env resultsMVars) smains
217178 results <- traverse readMVar resultsMVars
218179 writeDetails root details results
219− toArtifacts env foreigns results <$> traverse readMVar rrootMVars
220−
221−
222−
223−-- GET ROOT NAMES
224−
225−
226−getRootNames :: Artifacts -> NE.List ModuleName.Raw
227−getRootNames (Artifacts _ _ roots _) =
228− fmap getRootName roots
229−
230−
231−getRootName :: Root -> ModuleName.Raw
232−getRootName root =
233− case root of
234− Inside name -> name
235− Outside name _ _ -> name
180+ toArtifacts env foreigns results <$> traverse readMVar rmainMVars
236181
237182
238183
@@ -245,7 +190,7 @@ type StatusDict =
245190
246191data Status
247192 = SCached Details.Local
248− | SChanged Details.Local B.ByteString Src.Module DocsNeed
193+ | SChanged Details.Local B.ByteString Src.Module
249194 | SBadImport Import.Problem
250195 | SBadSyntax FilePath File.Time B.ByteString Syntax.Error
251196 | SForeign Pkg.Name
@@ -262,14 +207,15 @@ crawlDeps env mvar deps blockedValue =
262207 mapM_ readMVar statuses
263208 return blockedValue
264209 where
265− crawlNew name () = fork (crawlModule env mvar (DocsNeed False) name)
210+ crawlNew name () = fork (crawlModule env mvar name)
266211
267212
268−crawlModule :: Env -> MVar StatusDict -> DocsNeed -> ModuleName.Raw -> IO Status
269−crawlModule env@(Env _ root projectType srcDirs buildID locals foreigns) mvar docsNeed name =
213+crawlModule :: Env -> MVar StatusDict -> ModuleName.Raw -> IO Status
214+crawlModule env@(Env _ root pkg srcDirs locals foreigns) mvar name =
270215 do let fileName = ModuleName.toFilePath name <.> "elm"
216+ let inRoot path = File.exists (root </> path)
271217
272− paths <- filterM File.exists (map (`addRelative` fileName) srcDirs)
218+ paths <- filterM inRoot (map (</> fileName) srcDirs)
273219
274220 case paths of
275221 [path] ->
@@ -278,18 +224,21 @@ crawlModule env@(Env _ root projectType srcDirs buildID locals foreigns) mvar do
278224 return $ SBadImport $ Import.Ambiguous path [] dep deps
279225
280226 Nothing ->
281− do newTime <- File.getTime path
282− case Map.lookup name locals of
283− Nothing ->
284− crawlFile env mvar docsNeed name path newTime buildID
227+ case Map.lookup name locals of
228+ Nothing ->
229+ crawlFile env mvar name path
285230
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)
231+ Just local@(Details.Local oldPath oldTime deps _) ->
232+ if path /= oldPath
233+ then crawlFile env mvar name path
234+ else
235+ do newTime <- File.getTime path
236+ if oldTime < newTime
237+ then crawlFile env mvar name path
238+ else crawlDeps env mvar deps (SCached local)
290239
291240 p1:p2:ps ->
292− return $ SBadImport $ Import.AmbiguousLocal (FP.makeRelative root p1) (FP.makeRelative root p2) (map (FP.makeRelative root) ps)
241+ return $ SBadImport $ Import.AmbiguousLocal p1 p2 ps
293242
294243 [] ->
295244 case Map.lookup name foreigns of
@@ -302,18 +251,19 @@ crawlModule env@(Env _ root projectType srcDirs buildID locals foreigns) mvar do
302251 return $ SBadImport $ Import.AmbiguousForeign dep d ds
303252
304253 Nothing ->
305− if Name.isKernel name && Parse.isKernel projectType then
254+ if Name.isKernel name && Pkg.isKernel pkg then
306255 do exists <- File.exists ("src" </> ModuleName.toFilePath name <.> "js")
307256 return $ if exists then SKernel else SBadImport Import.NotFound
308257 else
309258 return $ SBadImport Import.NotFound
310259
311260
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)
261+crawlFile :: Env -> MVar StatusDict -> ModuleName.Raw -> FilePath -> IO Status
262+crawlFile env@(Env _ root pkg _ _ _) mvar expectedName path =
263+ do time <- File.getTime path
264+ source <- File.readUtf8 (root </> path)
315265
316− case Parse.fromByteString projectType source of
266+ case Parse.fromByteString pkg source of
317267 Left err ->
318268 return $ SBadSyntax path time source err
319269
@@ -326,16 +276,16 @@ crawlFile env@(Env _ root projectType _ buildID _ _) mvar docsNeed expectedName
326276 if expectedName == actualName then
327277 let
328278 deps = map Src.getImportName imports
329− local = Details.Local path time deps (any isMain values) lastChange buildID
279+ local = Details.Local path time deps (any isMain values)
330280 in
331− crawlDeps env mvar deps (SChanged local source modul docsNeed)
281+ crawlDeps env mvar deps (SChanged local source modul)
332282 else
333283 return $ SBadSyntax path time source (Syntax.ModuleNameMismatch expectedName name)
334284
335285
336286isMain :: A.Located Src.Value -> Bool
337287isMain (A.At _ (Src.Value (A.At _ name) _ _ _)) =
338− name == Name._main
288+ name == Name.main
339289
340290
341291
@@ -347,9 +297,9 @@ type ResultDict =
347297
348298
349299data Result
350− = RNew !Details.Local !I.Interface !Opt.LocalGraph !(Maybe Docs.Module)
351− | RSame !Details.Local !I.Interface !Opt.LocalGraph !(Maybe Docs.Module)
352− | RCached Bool Details.BuildID (MVar CachedInterface)
300+ = RNew Details.Local I.Interface Opt.LocalGraph
301+ | RSame Details.Local I.Interface Opt.LocalGraph
302+ | RCached Bool (MVar CachedInterface)
353303 | RNotFound Import.Problem
354304 | RProblem Error.Module
355305 | RBlocked
@@ -364,23 +314,23 @@ data CachedInterface
364314
365315
366316checkModule :: Env -> Dependencies -> MVar ResultDict -> ModuleName.Raw -> Status -> IO Result
367−checkModule env@(Env _ root projectType _ _ _ _) foreigns resultsMVar name status =
317+checkModule env@(Env _ root pkg _ _ _) foreigns resultsMVar name status =
368318 case status of
369− SCached local@(Details.Local path time deps hasMain lastChange lastCompile) ->
319+ SCached local@(Details.Local path time deps hasMain) ->
370320 do results <- readMVar resultsMVar
371− depsStatus <- checkDeps root results deps lastCompile
321+ depsStatus <- checkDeps root results deps
372322 case depsStatus of
373323 DepsChange ifaces ->
374324 do source <- File.readUtf8 path
375− case Parse.fromByteString projectType source of
376− Right modul -> compile env (DocsNeed False) local source ifaces modul
325+ case Parse.fromByteString pkg source of
326+ Right modul -> compile env local source ifaces modul
377327 Left err ->
378328 return $ RProblem $
379329 Error.Module name path time source (Error.BadSyntax err)
380330
381331 DepsSame _ _ ->
382332 do mvar <- newMVar Unneeded
383− return (RCached hasMain lastChange mvar)
333+ return (RCached hasMain mvar)
384334
385335 DepsBlock ->
386336 return RBlocked
@@ -388,25 +338,29 @@ checkModule env@(Env _ root projectType _ _ _ _) foreigns resultsMVar name statu
388338 DepsNotFound problems ->
389339 do source <- File.readUtf8 path
390340 return $ RProblem $ Error.Module name path time source $
391− case Parse.fromByteString projectType source of
341+ case Parse.fromByteString pkg source of
392342 Right (Src.Module _ _ _ imports _ _ _ _ _) ->
393343 Error.BadImports (toImportErrors env results imports problems)
394344
395345 Left err ->
396346 Error.BadSyntax err
397347
398− SChanged local@(Details.Local path time deps _ _ lastCompile) source modul@(Src.Module _ _ _ imports _ _ _ _ _) docsNeed ->
348+ SChanged local@(Details.Local path time deps _) source modul@(Src.Module _ _ _ imports _ _ _ _ _) ->
399349 do results <- readMVar resultsMVar
400− depsStatus <- checkDeps root results deps lastCompile
350+ depsStatus <- checkDeps root results deps
401351 case depsStatus of
402352 DepsChange ifaces ->
403− compile env docsNeed local source ifaces modul
353+ compile env local source ifaces modul
404354
405355 DepsSame same cached ->
406− do maybeLoaded <- loadInterfaces root same cached
356+ do maybeLoaded <- checkCachedInterfaces root cached
407357 case maybeLoaded of
408− Nothing -> return RBlocked
409− Just ifaces -> compile env docsNeed local source ifaces modul
358+ Nothing ->
359+ return RBlocked
360+
361+ Just loaded ->
362+ do let ifaces = Map.union loaded (Map.fromList same)
363+ compile env local source ifaces modul
410364
411365 DepsBlock ->
412366 return RBlocked
@@ -425,7 +379,7 @@ checkModule env@(Env _ root projectType _ _ _ _) foreigns resultsMVar name statu
425379 SForeign home ->
426380 case foreigns ! ModuleName.Canonical home name of
427381 I.Public iface -> return (RForeign iface)
428− I.Private _ _ _ -> error $ "mistakenly seeing private interface for " ++ Pkg.toChars home ++ " " ++ ModuleName.toChars name
382+ I.Private _ _ _ -> error "loading private interface in Build"
429383
430384 SKernel ->
431385 return RKernel
@@ -442,48 +396,32 @@ data DepsStatus
442396 | DepsNotFound (NE.List (ModuleName.Raw, Import.Problem))
443397
444398
445−checkDeps :: FilePath -> ResultDict -> [ModuleName.Raw] -> Details.BuildID -> IO DepsStatus
446−checkDeps root results deps lastCompile =
447− checkDepsHelp root results deps [] [] [] [] False 0 lastCompile
399+checkDeps :: FilePath -> ResultDict -> [ModuleName.Raw] -> IO DepsStatus
400+checkDeps root results deps =
401+ checkDepsHelp root results deps [] [] [] [] False
448402
449403
450404type Dep = (ModuleName.Raw, I.Interface)
451405type CDep = (ModuleName.Raw, MVar CachedInterface)
452406
453407
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 =
408+checkDepsHelp :: FilePath -> ResultDict -> [ModuleName.Raw] -> [Dep] -> [Dep] -> [CDep] -> [(ModuleName.Raw,Import.Problem)] -> Bool -> IO DepsStatus
409+checkDepsHelp root results deps new same cached importProblems isBlocked =
456410 case deps of
457411 dep:otherDeps ->
458412 do result <- readMVar (results ! dep)
459413 case result of
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−
414+ RNew _ iface _ -> checkDepsHelp root results otherDeps ((dep,iface) : new) same cached importProblems isBlocked
415+ RSame _ iface _ -> checkDepsHelp root results otherDeps new ((dep,iface) : same) cached importProblems isBlocked
416+ RCached _ mvar -> checkDepsHelp root results otherDeps new same ((dep,mvar) : cached) importProblems isBlocked
417+ RNotFound prob -> checkDepsHelp root results otherDeps new same cached ((dep,prob) : importProblems) True
418+ RProblem _ -> checkDepsHelp root results otherDeps new same cached importProblems True
419+ RBlocked -> checkDepsHelp root results otherDeps new same cached importProblems True
420+ RForeign iface -> checkDepsHelp root results otherDeps new ((dep,iface) : same) cached importProblems isBlocked
421+ RKernel -> checkDepsHelp root results otherDeps new same cached importProblems isBlocked
484422
485423 [] ->
486− case reverse importProblems of
424+ case importProblems of
487425 p:ps ->
488426 return $ DepsNotFound (NE.List p ps)
489427
@@ -491,14 +429,18 @@ checkDepsHelp root results deps new same cached importProblems isBlocked lastDep
491429 if isBlocked then
492430 return $ DepsBlock
493431
494− else if null new && lastDepChange <= lastCompile then
432+ else if null new then
495433 return $ DepsSame same cached
496434
497435 else
498− do maybeLoaded <- loadInterfaces root same cached
436+ do maybeLoaded <- checkCachedInterfaces root cached
499437 case maybeLoaded of
500− Nothing -> return DepsBlock
501− Just ifaces -> return $ DepsChange $ Map.union (Map.fromList new) ifaces
438+ Nothing ->
439+ return DepsBlock
440+
441+ Just loaded ->
442+ return $ DepsChange $
443+ Map.union loaded (Map.union (Map.fromList new) (Map.fromList same))
502444
503445
504446
@@ -506,7 +448,7 @@ checkDepsHelp root results deps new same cached importProblems isBlocked lastDep
506448
507449
508450toImportErrors :: Env -> ResultDict -> [Src.Import] -> NE.List (ModuleName.Raw, Import.Problem) -> NE.List Import.Error
509−toImportErrors (Env _ _ _ _ _ locals foreigns) results imports problems =
451+toImportErrors (Env _ _ _ _ locals foreigns) results imports problems =
510452 let
511453 knownModules =
512454 Set.unions
@@ -528,23 +470,18 @@ toImportErrors (Env _ _ _ _ _ locals foreigns) results imports problems =
528470
529471
530472
531−-- LOAD CACHED INTERFACES
473+-- CACHED INTERFACE
532474
533475
534−loadInterfaces :: FilePath -> [Dep] -> [CDep] -> IO (Maybe (Map.Map ModuleName.Raw I.Interface))
535−loadInterfaces root same cached =
536− do loading <- traverse (fork . loadInterface root) cached
537− maybeLoaded <- traverse readMVar loading
538− case sequence maybeLoaded of
539− Nothing ->
540− return Nothing
541−
542− Just loaded ->
543− return $ Just $ Map.union (Map.fromList loaded) (Map.fromList same)
476+checkCachedInterfaces :: FilePath -> [(ModuleName.Raw, MVar CachedInterface)] -> IO (Maybe (Map.Map ModuleName.Raw I.Interface))
477+checkCachedInterfaces root deps =
478+ do loading <- traverse (fork . checkCache root) deps
479+ loaded <- traverse readMVar loading
480+ return $ Map.fromList <$> sequence loaded
544481
545482
546−loadInterface :: FilePath -> CDep -> IO (Maybe Dep)
547−loadInterface root (name, ciMvar) =
483+checkCache :: FilePath -> (ModuleName.Raw, MVar CachedInterface) -> IO (Maybe Dep)
484+checkCache root (name, ciMvar) =
548485 do cachedInterface <- takeMVar ciMvar
549486 case cachedInterface of
550487 Corrupted ->
@@ -571,8 +508,8 @@ loadInterface root (name, ciMvar) =
571508-- CHECK PROJECT
572509
573510
574−checkMidpoint :: MVar (Maybe Dependencies) -> Map.Map ModuleName.Raw Status -> IO (Either Exit.BuildProjectProblem Dependencies)
575−checkMidpoint dmvar statuses =
511+checkExposedMidpoint :: MVar (Maybe Dependencies) -> Map.Map ModuleName.Raw Status -> IO (Either Exit.BuildProjectProblem Dependencies)
512+checkExposedMidpoint dmvar statuses =
576513 case checkForCycles statuses of
577514 Nothing ->
578515 do maybeForeigns <- readMVar dmvar
@@ -585,11 +522,11 @@ checkMidpoint dmvar statuses =
585522 return (Left (Exit.BP_Cycle name names))
586523
587524
588−checkMidpointAndRoots :: MVar (Maybe Dependencies) -> Map.Map ModuleName.Raw Status -> NE.List RootStatus -> IO (Either Exit.BuildProjectProblem Dependencies)
589−checkMidpointAndRoots dmvar statuses sroots =
525+checkMainsMidpoint :: MVar (Maybe Dependencies) -> Map.Map ModuleName.Raw Status -> NE.List MainStatus -> IO (Either Exit.BuildProjectProblem Dependencies)
526+checkMainsMidpoint dmvar statuses smains =
590527 case checkForCycles statuses of
591528 Nothing ->
592− case checkUniqueRoots statuses sroots of
529+ case checkUniqueMains statuses smains of
593530 Nothing ->
594531 do maybeForeigns <- readMVar dmvar
595532 case maybeForeigns of
@@ -640,25 +577,25 @@ addToGraph name status graph =
640577 let
641578 dependencies =
642579 case status of
643− SCached (Details.Local _ _ deps _ _ _) -> deps
644− SChanged (Details.Local _ _ deps _ _ _) _ _ _ -> deps
645− SBadImport _ -> []
646− SBadSyntax _ _ _ _ -> []
647− SForeign _ -> []
648− SKernel -> []
580+ SCached (Details.Local _ _ deps _) -> deps
581+ SChanged (Details.Local _ _ deps _) _ _ -> deps
582+ SBadImport _ -> []
583+ SBadSyntax _ _ _ _ -> []
584+ SForeign _ -> []
585+ SKernel -> []
649586 in
650587 (name, name, dependencies) : graph
651588
652589
653590
654−-- CHECK UNIQUE ROOTS
591+-- CHECK UNIQUE MAINS
655592
656593
657−checkUniqueRoots :: Map.Map ModuleName.Raw Status -> NE.List RootStatus -> Maybe Exit.BuildProjectProblem
658−checkUniqueRoots insides sroots =
594+checkUniqueMains :: Map.Map ModuleName.Raw Status -> NE.List MainStatus -> Maybe Exit.BuildProjectProblem
595+checkUniqueMains insides smains =
659596 let
660597 outsidesDict =
661− Map.fromListWith OneOrMore.more (Maybe.mapMaybe rootStatusToNamePathPair (NE.toList sroots))
598+ Map.fromListWith OneOrMore.more (Maybe.mapMaybe mainStatusToNamePathPair (NE.toList smains))
662599 in
663600 case Map.traverseWithKey checkOutside outsidesDict of
664601 Left problem ->
@@ -670,78 +607,61 @@ checkUniqueRoots insides sroots =
670607 Left problem -> Just problem
671608
672609
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
610+mainStatusToNamePathPair :: MainStatus -> Maybe (ModuleName.Raw, OneOrMore.OneOrMore FilePath)
611+mainStatusToNamePathPair smain =
612+ case smain of
613+ SInside _ -> Nothing
614+ SOutsideOk (Details.Local path _ _ _) _ modul -> Just (Src.getName modul, OneOrMore.one path)
615+ SOutsideErr _ -> Nothing
679616
680617
681618checkOutside :: ModuleName.Raw -> OneOrMore.OneOrMore FilePath -> Either Exit.BuildProjectProblem FilePath
682619checkOutside name paths =
683620 case OneOrMore.destruct NE.List paths of
684621 NE.List p [] -> Right p
685− NE.List p1 (p2:_) -> Left (Exit.BP_RootNameDuplicate name p1 p2)
622+ NE.List p1 (p2:_) -> Left (Exit.BP_MainNameDuplicate name p1 p2)
686623
687624
688625checkInside :: ModuleName.Raw -> FilePath -> Status -> Either Exit.BuildProjectProblem ()
689626checkInside name p1 status =
690627 case status of
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 ()
628+ SCached (Details.Local p2 _ _ _) -> Left (Exit.BP_MainNameDuplicate name p1 p2)
629+ SChanged (Details.Local p2 _ _ _) _ _ -> Left (Exit.BP_MainNameDuplicate name p1 p2)
630+ SBadImport _ -> Right ()
631+ SBadSyntax _ _ _ _ -> Right ()
632+ SForeign _ -> Right ()
633+ SKernel -> Right ()
697634
698635
699636
700637-- COMPILE MODULE
701638
702639
703−compile :: Env -> DocsNeed -> Details.Local -> B.ByteString -> Map.Map ModuleName.Raw I.Interface -> Src.Module -> IO Result
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
640+compile :: Env -> Details.Local -> B.ByteString -> Map.Map ModuleName.Raw I.Interface -> Src.Module -> IO Result
641+compile (Env key root pkg _ _ _) local@(Details.Local path time _ _) source ifaces modul =
708642 case Compile.compile pkg ifaces modul of
709643 Right (Compile.Artifacts canonical annotations objects) ->
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)
644+ do let name = Src.getName modul
645+ let iface = I.fromModule pkg canonical annotations
646+ File.writeBinary (Stuff.elmo root name) objects
647+ maybeOldi <- File.readBinary (Stuff.elmi root name)
648+ case maybeOldi of
649+ Just oldi | oldi == iface ->
650+ do -- iface should be fully forced by equality check
651+ Reporting.report key Reporting.BDone
652+ return (RSame local iface objects)
653+
654+ _ ->
655+ do -- iface may be lazy still
656+ -- TODO try adding forkIO here
657+ File.writeBinary (Stuff.elmi root name) iface
658+ Reporting.report key Reporting.BDone
659+ return (RNew local iface objects)
734660
735661 Left 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
662+ do Reporting.report key Reporting.BDone
663+ return $ RProblem $
664+ Error.Module (Src.getName modul) path time source err
745665
746666
747667
@@ -749,210 +669,64 @@ projectTypeToPkg projectType =
749669
750670
751671writeDetails :: FilePath -> Details.Details -> Map.Map ModuleName.Raw Result -> IO ()
752−writeDetails root (Details.Details time outline buildID locals foreigns extras) results =
672+writeDetails root (Details.Details time outline locals foreigns extras) results =
753673 File.writeBinary (Stuff.details root) $
754− Details.Details time outline buildID (Map.foldrWithKey addNewLocal locals results) foreigns extras
674+ Details.Details time outline (Map.foldrWithKey addNewLocal locals results) foreigns extras
755675
756676
757677addNewLocal :: ModuleName.Raw -> Result -> Map.Map ModuleName.Raw Details.Local -> Map.Map ModuleName.Raw Details.Local
758678addNewLocal name result locals =
759679 case result of
760− RNew local _ _ _ -> Map.insert name local locals
761− RSame local _ _ _ -> Map.insert name local locals
762− RCached _ _ _ -> locals
763− RNotFound _ -> locals
764− RProblem _ -> locals
765− RBlocked -> locals
766− RForeign _ -> locals
767− RKernel -> locals
680+ RNew local _ _ -> Map.insert name local locals
681+ RSame local _ _ -> Map.insert name local locals
682+ RCached _ _ -> locals
683+ RNotFound _ -> locals
684+ RProblem _ -> locals
685+ RBlocked -> locals
686+ RForeign _ -> locals
687+ RKernel -> locals
768688
769689
770690
771−-- FINALIZE EXPOSED
691+-- DETECT EXPOSED PROBLEMS
772692
773693
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 =
694+detectExposedProblems :: NE.List ModuleName.Raw -> Map.Map ModuleName.Raw Result -> Either Exit.BuildProblem ()
695+detectExposedProblems exposed results =
776696 case foldr (addImportProblems results) [] (NE.toList exposed) of
777697 p:ps ->
778− return $ Left $ Exit.BuildProjectProblem (Exit.BP_MissingExposed (NE.List p ps))
698+ Left (Exit.BuildProjectProblem (Exit.BP_MissingExposed (NE.List p ps)))
779699
780700 [] ->
781701 case Map.foldr addErrors [] results of
782− [] -> Right <$> finalizeDocs docsGoal results
783− e:es -> return $ Left $ Exit.BuildBadModules root e es
702+ [] -> Right ()
703+ e:es -> Left (Exit.BuildModuleProblems e es)
784704
785705
786706addErrors :: Result -> [Error.Module] -> [Error.Module]
787707addErrors result errors =
788708 case result of
789− RNew _ _ _ _ -> errors
790− RSame _ _ _ _ -> errors
791− RCached _ _ _ -> errors
792− RNotFound _ -> errors
793− RProblem e -> e:errors
794− RBlocked -> errors
795− RForeign _ -> errors
796− RKernel -> errors
709+ RNew _ _ _ -> errors
710+ RSame _ _ _ -> errors
711+ RCached _ _ -> errors
712+ RNotFound _ -> errors
713+ RProblem e -> e:errors
714+ RBlocked -> errors
715+ RForeign _ -> errors
716+ RKernel -> errors
797717
798718
799719addImportProblems :: Map.Map ModuleName.Raw Result -> ModuleName.Raw -> [(ModuleName.Raw, Import.Problem)] -> [(ModuleName.Raw, Import.Problem)]
800720addImportProblems results name problems =
801721 case results ! name of
802− RNew _ _ _ _ -> problems
803− RSame _ _ _ _ -> problems
804− RCached _ _ _ -> problems
805− RNotFound p -> (name, p) : problems
806− RProblem _ -> problems
807− RBlocked -> problems
808− RForeign _ -> problems
809− RKernel -> problems
810−
811−
812−
813−-- DOCS
814−
815−
816−data DocsGoal a where
817− KeepDocs :: DocsGoal Docs.Documentation
818− WriteDocs :: FilePath -> DocsGoal ()
819− IgnoreDocs :: DocsGoal ()
820−
821−
822−newtype DocsNeed =
823− DocsNeed { needsDocs :: Bool }
824−
825−
826−toDocsNeed :: DocsGoal a -> DocsNeed
827−toDocsNeed goal =
828− case goal of
829− IgnoreDocs -> DocsNeed False
830− WriteDocs _ -> DocsNeed True
831− KeepDocs -> DocsNeed True
832−
833−
834−makeDocs :: DocsNeed -> Can.Module -> Either EDocs.Error (Maybe Docs.Module)
835−makeDocs (DocsNeed isNeeded) modul =
836− if isNeeded then
837− case Docs.fromModule modul of
838− Right docs -> Right (Just docs)
839− Left err -> Left err
840− else
841− Right Nothing
842−
843−
844−finalizeDocs :: DocsGoal docs -> Map.Map ModuleName.Raw Result -> IO docs
845−finalizeDocs goal results =
846− case goal of
847− KeepDocs ->
848− return $ Map.mapMaybe toDocs results
849−
850− WriteDocs path ->
851− E.writeUgly path $ Docs.encode $ Map.mapMaybe toDocs results
852−
853− IgnoreDocs ->
854− return ()
855−
856−
857−toDocs :: Result -> Maybe Docs.Module
858−toDocs result =
859− case result of
860− RNew _ _ _ d -> d
861− RSame _ _ _ d -> d
862− RCached _ _ _ -> Nothing
863− RNotFound _ -> Nothing
864− RProblem _ -> Nothing
865− RBlocked -> Nothing
866− RForeign _ -> Nothing
867− RKernel -> Nothing
868−
869−
870−
871−--------------------------------------------------------------------------------
872−------ NOW FOR SOME REPL STUFF -------------------------------------------------
873−--------------------------------------------------------------------------------
874−
875−
876−-- FROM REPL
877−
878−
879−data ReplArtifacts =
880− ReplArtifacts
881− { _repl_home :: ModuleName.Canonical
882− , _repl_modules :: [Module]
883− , _repl_localizer :: L.Localizer
884− , _repl_annotations :: Map.Map Name.Name Can.Annotation
885− }
886−
887−
888−fromRepl :: FilePath -> Details.Details -> B.ByteString -> IO (Either Exit.Repl ReplArtifacts)
889−fromRepl root details source =
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
894−
895− Right modul@(Src.Module _ _ _ imports _ _ _ _ _) ->
896− do dmvar <- Details.loadInterfaces root details
897−
898− let deps = map Src.getImportName imports
899− mvar <- newMVar Map.empty
900− crawlDeps env mvar deps ()
901−
902− statuses <- traverse readMVar =<< readMVar mvar
903− midpoint <- checkMidpoint dmvar statuses
904−
905− case midpoint of
906− Left problem ->
907− return $ Left $ Exit.ReplProjectProblem problem
908−
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
917−
918−
919−finalizeReplArtifacts :: Env -> B.ByteString -> Src.Module -> DepsStatus -> ResultDict -> Map.Map ModuleName.Raw Result -> IO (Either Exit.Repl ReplArtifacts)
920−finalizeReplArtifacts env@(Env _ root projectType _ _ _ _) source modul@(Src.Module _ _ _ imports _ _ _ _ _) depsStatus resultMVars results =
921− let
922− pkg =
923− projectTypeToPkg projectType
924−
925− compileInput ifaces =
926− case Compile.compile pkg ifaces modul of
927− Right (Compile.Artifacts canonical annotations objects) ->
928− let
929− h = Can._name canonical
930− m = Fresh (Src.getName modul) (I.fromModule pkg canonical annotations) objects
931− ms = Map.foldrWithKey addInside [] results
932− in
933− return $ Right $ ReplArtifacts h (m:ms) (L.fromModule modul) annotations
934−
935− Left errors ->
936− return $ Left $ Exit.ReplBadInput source errors
937− in
938− case depsStatus of
939− DepsChange ifaces ->
940− compileInput ifaces
941−
942− DepsSame same cached ->
943− do maybeLoaded <- loadInterfaces root same cached
944− case maybeLoaded of
945− Just ifaces -> compileInput ifaces
946− Nothing -> return $ Left $ Exit.ReplBadCache
947−
948− DepsBlock ->
949− case Map.foldr addErrors [] results of
950− [] -> return $ Left $ Exit.ReplBlocked
951− e:es -> return $ Left $ Exit.ReplBadLocalDeps root e es
952−
953− DepsNotFound problems ->
954− return $ Left $ Exit.ReplBadInput source $ Error.BadImports $
955− toImportErrors env resultMVars imports problems
722+ RNew _ _ _ -> problems
723+ RSame _ _ _ -> problems
724+ RCached _ _ -> problems
725+ RNotFound p -> (name, p) : problems
726+ RProblem _ -> problems
727+ RBlocked -> problems
728+ RForeign _ -> problems
729+ RKernel -> problems
956730
957731
958732
@@ -964,25 +738,25 @@ finalizeReplArtifacts env@(Env _ root projectType _ _ _ _) source modul@(Src.Mod
964738
965739
966740
967−-- FIND ROOT
741+-- FIND MAIN
968742
969743
970−data RootLocation
744+data MainLocation
971745 = LInside ModuleName.Raw
972746 | LOutside FilePath
973747
974748
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
749+findMains :: Env -> NE.List FilePath -> IO (Either Exit.BuildProjectProblem (NE.List MainLocation))
750+findMains env paths =
751+ do mvars <- traverse (fork . findLocation env) paths
752+ elocs <- traverse readMVar mvars
753+ return $ checkLocations =<< sequence elocs
980754
981755
982−checkRoots :: NE.List RootInfo -> Either Exit.BuildProjectProblem (NE.List RootLocation)
983−checkRoots infos =
756+checkLocations :: NE.List Location -> Either Exit.BuildProjectProblem (NE.List MainLocation)
757+checkLocations locations =
984758 let
985− toOneOrMore loc@(RootInfo absolute _ _) =
759+ toOneOrMore loc@(Location absolute _ _) =
986760 (absolute, OneOrMore.one loc)
987761
988762 fromOneOrMore loc locs =
@@ -990,83 +764,71 @@ checkRoots infos =
990764 [] -> Right ()
991765 loc2:_ -> Left (Exit.BP_MainPathDuplicate (_relative loc) (_relative loc2))
992766 in
993− fmap (\_ -> fmap _location infos) $
767+ fmap (\_ -> fmap _location locations) $
994768 traverse (OneOrMore.destruct fromOneOrMore) $
995− Map.fromListWith OneOrMore.more $ map toOneOrMore (NE.toList infos)
769+ Map.fromListWith OneOrMore.more $ map toOneOrMore (NE.toList locations)
996770
997771
998772
999−-- ROOT INFO
773+-- LOCATIONS
1000774
1001775
1002−data RootInfo =
1003− RootInfo
776+data Location =
777+ Location
1004778 { _absolute :: FilePath
1005779 , _relative :: FilePath
1006− , _location :: RootLocation
780+ , _location :: MainLocation
1007781 }
1008782
1009783
1010−getRootInfo :: Env -> FilePath -> IO (Either Exit.BuildProjectProblem RootInfo)
1011−getRootInfo env path =
784+findLocation :: Env -> FilePath -> IO (Either Exit.BuildProjectProblem Location)
785+findLocation env path =
1012786 do exists <- File.exists path
1013787 if exists
1014− then getRootInfoHelp env path =<< Dir.canonicalizePath path
788+ then isInsideSrcDirs env path <$> Dir.canonicalizePath path
1015789 else return (Left (Exit.BP_PathUnknown path))
1016790
1017791
1018−getRootInfoHelp :: Env -> FilePath -> FilePath -> IO (Either Exit.BuildProjectProblem RootInfo)
1019−getRootInfoHelp (Env _ _ _ srcDirs _ _ _) path absolutePath =
792+isInsideSrcDirs :: Env -> FilePath -> FilePath -> Either Exit.BuildProjectProblem Location
793+isInsideSrcDirs (Env _ root _ srcDirs _ _) path absolutePath =
1020794 let
1021795 (dirs, file) = FP.splitFileName absolutePath
1022− (final, ext) = FP.splitExtension file
796+ (final, ext) = break (=='.') file
1023797 in
1024798 if ext /= ".elm"
1025− then
1026− return $ Left $ Exit.BP_WithBadExtension path
799+ then Left (Exit.BP_WithBadExtension path)
1027800 else
1028801 let
1029− absoluteSegments = FP.splitDirectories dirs ++ [final]
802+ roots = FP.splitDirectories root
803+ segments = FP.splitDirectories dirs ++ [final]
1030804 in
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) =
805+ case dropPrefix roots segments of
806+ Nothing ->
807+ Right (Location absolutePath path (LOutside path))
808+
809+ Just relativeSegments ->
810+ let
811+ (exits, maybes) =
812+ Either.partitionEithers (map (isInsideSrcDirsHelp relativeSegments) srcDirs)
813+ in
814+ -- TODO make sure this is all correct
815+ case (exits, Maybe.catMaybes maybes) of
816+ (_, [(_,name)]) -> Right (Location absolutePath path (LInside name))
817+ ([], []) -> Right (Location absolutePath path (LOutside path))
818+ (_, (s1,_):(s2,_):_) -> Left (Exit.BP_WithAmbiguousSrcDir s1 s2)
819+ (exit:_, _) -> Left exit
820+
821+
822+isInsideSrcDirsHelp :: [String] -> FilePath -> Either Exit.BuildProjectProblem (Maybe (FilePath, ModuleName.Raw))
823+isInsideSrcDirsHelp segments srcDir =
1062824 case dropPrefix (FP.splitDirectories srcDir) segments of
1063825 Nothing ->
1064− Nothing
826+ Right Nothing
1065827
1066828 Just names ->
1067829 if all isGoodName names
1068− then Just (srcDir, Right names)
1069− else Just (srcDir, Left names)
830+ then Right (Just (srcDir, Name.fromChars (List.intercalate "." names)))
831+ else Left (error "Exit.MakeWithInvalidModuleName" srcDir segments)
1070832
1071833
1072834isGoodName :: [Char] -> Bool
@@ -1079,8 +841,6 @@ isGoodName name =
1079841 Char.isUpper char && all (\c -> Char.isAlphaNum c || c == '_') chars
1080842
1081843
1082−-- INVARIANT: Dir.canonicalizePath has been run on both inputs
1083−--
1084844dropPrefix :: [FilePath] -> [FilePath] -> Maybe [FilePath]
1085845dropPrefix roots paths =
1086846 case roots of
@@ -1089,37 +849,37 @@ dropPrefix roots paths =
1089849
1090850 r:rs ->
1091851 case paths of
1092− [] -> Nothing
852+ [] -> Nothing
1093853 p:ps -> if r == p then dropPrefix rs ps else Nothing
1094854
1095855
1096856
1097−-- CRAWL ROOTS
857+-- CRAWL MAINS
1098858
1099859
1100−data RootStatus
860+data MainStatus
1101861 = SInside ModuleName.Raw
1102862 | SOutsideOk Details.Local B.ByteString Src.Module
1103863 | SOutsideErr Error.Module
1104864
1105865
1106−crawlRoot :: Env -> MVar StatusDict -> RootLocation -> IO RootStatus
1107−crawlRoot env@(Env _ _ projectType _ buildID _ _) mvar root =
1108− case root of
866+crawlMain :: Env -> MVar StatusDict -> MainLocation -> IO MainStatus
867+crawlMain env@(Env _ _ pkg _ _ _) mvar given =
868+ case given of
1109869 LInside name ->
1110870 do statusMVar <- newEmptyMVar
1111871 statusDict <- takeMVar mvar
1112872 putMVar mvar (Map.insert name statusMVar statusDict)
1113− putMVar statusMVar =<< crawlModule env mvar (DocsNeed False) name
873+ putMVar statusMVar =<< crawlModule env mvar name
1114874 return (SInside name)
1115875
1116876 LOutside path ->
1117877 do time <- File.getTime path
1118878 source <- File.readUtf8 path
1119− case Parse.fromByteString projectType source of
879+ case Parse.fromByteString pkg source of
1120880 Right modul@(Src.Module _ _ _ imports values _ _ _ _) ->
1121881 do let deps = map Src.getImportName imports
1122− let local = Details.Local path time deps (any isMain values) buildID buildID
882+ let local = Details.Local path time deps (any isMain values)
1123883 crawlDeps env mvar deps (SOutsideOk local source modul)
1124884
1125885 Left syntaxError ->
@@ -1128,36 +888,40 @@ crawlRoot env@(Env _ _ projectType _ buildID _ _) mvar root =
1128888
1129889
1130890
1131−-- CHECK ROOTS
891+-- CHECK MAINS
1132892
1133893
1134−data RootResult
894+data MainResult
1135895 = RInside ModuleName.Raw
1136896 | ROutsideOk ModuleName.Raw I.Interface Opt.LocalGraph
1137897 | ROutsideErr Error.Module
1138898 | ROutsideBlocked
1139899
1140900
1141−checkRoot :: Env -> ResultDict -> RootStatus -> IO RootResult
1142−checkRoot env@(Env _ root _ _ _ _ _) results rootStatus =
1143− case rootStatus of
901+checkMain :: Env -> ResultDict -> MainStatus -> IO MainResult
902+checkMain env@(Env _ root _ _ _ _) results pendingMain =
903+ case pendingMain of
1144904 SInside name ->
1145905 return (RInside name)
1146906
1147907 SOutsideErr err ->
1148908 return (ROutsideErr err)
1149909
1150− SOutsideOk local@(Details.Local path time deps _ _ lastCompile) source modul@(Src.Module _ _ _ imports _ _ _ _ _) ->
1151− do depsStatus <- checkDeps root results deps lastCompile
910+ SOutsideOk local@(Details.Local path time deps _) source modul@(Src.Module _ _ _ imports _ _ _ _ _) ->
911+ do depsStatus <- checkDeps root results deps
1152912 case depsStatus of
1153913 DepsChange ifaces ->
1154− compileOutside env local source ifaces modul
914+ return $ compileOutside env local source ifaces modul
1155915
1156916 DepsSame same cached ->
1157− do maybeLoaded <- loadInterfaces root same cached
917+ do maybeLoaded <- checkCachedInterfaces root cached
1158918 case maybeLoaded of
1159− Nothing -> return ROutsideBlocked
1160− Just ifaces -> compileOutside env local source ifaces modul
919+ Nothing ->
920+ return ROutsideBlocked
921+
922+ Just loaded ->
923+ do let ifaces = Map.union loaded (Map.fromList same)
924+ return $ compileOutside env local source ifaces modul
1161925
1162926 DepsBlock ->
1163927 return ROutsideBlocked
@@ -1167,54 +931,53 @@ checkRoot env@(Env _ root _ _ _ _ _) results rootStatus =
1167931 Error.BadImports (toImportErrors env results imports problems)
1168932
1169933
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 =
934+compileOutside :: Env -> Details.Local -> B.ByteString -> Map.Map ModuleName.Raw I.Interface -> Src.Module -> MainResult
935+compileOutside (Env _ _ pkg _ _ _) (Details.Local path time _ _) source ifaces modul =
1172936 let
1173− pkg = projectTypeToPkg projectType
1174937 name = Src.getName modul
1175938 in
1176939 case Compile.compile pkg ifaces modul of
1177940 Right (Compile.Artifacts canonical annotations objects) ->
1178− do Reporting.report key Reporting.BDone
1179− return $ ROutsideOk name (I.fromModule pkg canonical annotations) objects
941+ ROutsideOk name (I.fromModule pkg canonical annotations) objects
1180942
1181943 Left errors ->
1182− return $ ROutsideErr $ Error.Module name path time source errors
944+ ROutsideErr $
945+ Error.Module name path time source errors
1183946
1184947
1185948
1186949-- TO ARTIFACTS
1187950
1188951
1189−data Root
952+data Main
1190953 = Inside ModuleName.Raw
1191954 | Outside ModuleName.Raw I.Interface Opt.LocalGraph
1192955
1193956
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
957+toArtifacts :: Env -> Dependencies -> Map.Map ModuleName.Raw Result -> NE.List MainResult -> Either Exit.BuildProblem Artifacts
958+toArtifacts (Env _ _ pkg _ _ _) foreigns results mainResults =
959+ case gatherProblemsOrMains results mainResults of
1197960 Left (NE.List e es) ->
1198− Left (Exit.BuildBadModules root e es)
961+ Left (Exit.BuildModuleProblems e es)
1199962
1200− Right roots ->
1201− Right $ Artifacts (projectTypeToPkg projectType) foreigns roots $
1202− Map.foldrWithKey addInside (foldr addOutside [] rootResults) results
963+ Right mains ->
964+ Right $ Artifacts pkg foreigns mains $
965+ Map.foldrWithKey addInside (foldr addOutside [] mainResults) results
1203966
1204967
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) =
968+gatherProblemsOrMains :: Map.Map ModuleName.Raw Result -> NE.List MainResult -> Either (NE.List Error.Module) (NE.List Main)
969+gatherProblemsOrMains results (NE.List mainResult mainResults) =
1207970 let
1208− addResult result (es, roots) =
971+ sortMain result (es, mains) =
1209972 case result of
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)
973+ RInside n -> ( es, Inside n : mains)
974+ ROutsideOk n i o -> ( es, Outside n i o : mains)
975+ ROutsideErr e -> (e:es, mains)
976+ ROutsideBlocked -> ( es, mains)
1214977
1215978 errors = Map.foldr addErrors [] results
1216979 in
1217− case (rootResult, foldr addResult (errors, []) rootResults) of
980+ case (mainResult, foldr sortMain (errors, []) mainResults) of
1218981 (RInside n , ( [], ms)) -> Right (NE.List (Inside n) ms)
1219982 (RInside _ , (e:es, _ )) -> Left (NE.List e es)
1220983 (ROutsideOk n i o, ( [], ms)) -> Right (NE.List (Outside n i o) ms)
@@ -1227,14 +990,14 @@ gatherProblemsOrMains results (NE.List rootResult rootResults) =
1227990addInside :: ModuleName.Raw -> Result -> [Module] -> [Module]
1228991addInside name result modules =
1229992 case result of
1230− RNew _ iface objs _ -> Fresh name iface objs : modules
1231− RSame _ iface objs _ -> Fresh name iface objs : modules
1232− RCached main _ mvar -> Cached name main mvar : modules
1233− RNotFound _ -> error (badInside name)
1234− RProblem _ -> error (badInside name)
1235− RBlocked -> error (badInside name)
1236− RForeign _ -> modules
1237− RKernel -> modules
993+ RNew _ iface objs -> Fresh name iface objs : modules
994+ RSame _ iface objs -> Fresh name iface objs : modules
995+ RCached main mvar -> Cached name main mvar : modules
996+ RNotFound _ -> error (badInside name)
997+ RProblem _ -> error (badInside name)
998+ RBlocked -> error (badInside name)
999+ RForeign _ -> modules
1000+ RKernel -> modules
12381001
12391002
12401003badInside :: ModuleName.Raw -> [Char]
@@ -1242,9 +1005,9 @@ badInside name =
12421005 "Error from `" ++ Name.toChars name ++ "` should have been reported already."
12431006
12441007
1245−addOutside :: RootResult -> [Module] -> [Module]
1246−addOutside root modules =
1247− case root of
1008+addOutside :: MainResult -> [Module] -> [Module]
1009+addOutside main modules =
1010+ case main of
12481011 RInside _ -> modules
12491012 ROutsideOk name iface objs -> Fresh name iface objs : modules
12501013 ROutsideErr _ -> modules
builder/src/Deps/Bump.hsdeleted−37
@@ -1,37 +0,0 @@
1−module Deps.Bump
2− ( getPossibilities
3− )
4− where
5−
6−
7−import qualified Data.List as List
8−
9−import qualified Deps.Registry as Registry
10−import qualified Elm.Magnitude as M
11−import qualified Elm.Version as V
12−
13−
14−
15−-- GET POSSIBILITIES
16−
17−
18−getPossibilities :: Registry.KnownVersions -> [(V.Version, V.Version, M.Magnitude)]
19−getPossibilities (Registry.KnownVersions latest previous) =
20− let
21− allVersions = reverse (latest:previous)
22− minorPoints = map last (List.groupBy sameMajor allVersions)
23− patchPoints = map last (List.groupBy sameMinor allVersions)
24− in
25− (latest, V.bumpMajor latest, M.MAJOR)
26− : map (\v -> (v, V.bumpMinor v, M.MINOR)) minorPoints
27− ++ map (\v -> (v, V.bumpPatch v, M.PATCH)) patchPoints
28−
29−
30−sameMajor :: V.Version -> V.Version -> Bool
31−sameMajor (V.Version major1 _ _) (V.Version major2 _ _) =
32− major1 == major2
33−
34−
35−sameMinor :: V.Version -> V.Version -> Bool
36−sameMinor (V.Version major1 minor1 _) (V.Version major2 minor2 _) =
37− major1 == major2 && minor1 == minor2
builder/src/Deps/Diff.hs+5−7
@@ -18,7 +18,7 @@ import qualified Data.List as List
1818import qualified Data.Map as Map
1919import qualified Data.Name as Name
2020import qualified Data.Set as Set
21−import qualified System.Directory as Dir
21+import qualified Data.Utf8 as Utf8
2222import System.FilePath ((</>))
2323
2424import qualified Deps.Website as Website
@@ -204,7 +204,7 @@ isSameName :: Name.Name -> Name.Name -> Bool
204204isSameName oldFullName newFullName =
205205 let
206206 dedot name =
207− reverse (Name.splitDots name)
207+ reverse (Utf8.split 0x2E {-.-} (Name.toUtf8 name))
208208 in
209209 case ( dedot oldFullName, dedot newFullName ) of
210210 (oldName:[], newName:_) ->
@@ -357,8 +357,7 @@ changeMagnitude (Changes added changed removed) =
357357
358358getDocs :: Stuff.PackageCache -> Http.Manager -> Pkg.Name -> V.Version -> IO (Either Exit.DocsProblem Docs.Documentation)
359359getDocs cache manager name version =
360− do let home = Stuff.package cache name version
361− let path = home </> "docs.json"
360+ do let path = Stuff.package cache name version </> "docs.json"
362361 exists <- File.exists path
363362 if exists
364363 then
@@ -375,9 +374,8 @@ getDocs cache manager name version =
375374 Http.get manager url [] Exit.DP_Http $ \body ->
376375 case D.fromByteString Docs.decoder body of
377376 Right docs ->
378− do Dir.createDirectoryIfMissing True home
379− File.writeUtf8 path body
377+ do File.writeUtf8 path body
380378 return $ Right docs
381379
382380 Left _ ->
383− return $ Left $ Exit.DP_Data url body
381+ return $ Left Exit.DP_Data
builder/src/Deps/Registry.hs+68−35
@@ -16,8 +16,11 @@ module Deps.Registry
1616import Prelude hiding (read)
1717import Control.Monad (liftM2)
1818import Data.Binary (Binary, get, put)
19+import Data.Function (on)
1920import qualified Data.List as List
2021import qualified Data.Map.Strict as Map
22+import qualified Data.Name as Name
23+import qualified Data.Utf8 as Utf8
2124
2225import qualified Deps.Website as Website
2326import qualified Elm.Package as Pkg
@@ -25,8 +28,8 @@ import qualified Elm.Version as V
2528import qualified File
2629import qualified Http
2730import qualified Json.Decode as D
28−import qualified Parse.Primitives as P
2931import qualified Reporting.Exit as Exit
32+import qualified Reporting.Suggest as Suggest
3033import qualified Stuff
3134
3235
@@ -54,7 +57,11 @@ data KnownVersions =
5457
5558read :: Stuff.PackageCache -> IO (Maybe Registry)
5659read cache =
57− File.readBinary (Stuff.registry cache)
60+ do let path = Stuff.registry cache
61+ exists <- File.exists path
62+ if exists
63+ then File.readBinary path
64+ else return Nothing
5865
5966
6067
@@ -79,19 +86,26 @@ addEntry (KnownVersions _ vs) count =
7986
8087allPkgsDecoder :: D.Decoder () (Map.Map Pkg.Name KnownVersions)
8188allPkgsDecoder =
82− let
83− keyDecoder =
84− Pkg.keyDecoder bail
89+ do pairs <- D.pairs (D.list (D.mapError (\_ -> ()) V.decoder))
90+ checkKeys pairs Map.empty
91+ where
92+ checkKeys pairs pkgs =
93+ case pairs of
94+ [] ->
95+ return pkgs
8596
86− versionsDecoder =
87− D.list (D.mapError (\_ -> ()) V.decoder)
97+ (key, versions) : rest ->
98+ case Pkg.fromString key of
99+ Right pkg ->
100+ case List.sortBy (flip compare) versions of
101+ [] ->
102+ D.failure ()
88103
89− toKnownVersions versions =
90− case List.sortBy (flip compare) versions of
91− v:vs -> return (KnownVersions v vs)
92− [] -> D.failure ()
93− in
94− D.dict keyDecoder (toKnownVersions =<< versionsDecoder)
104+ v:vs ->
105+ checkKeys rest (Map.insert pkg (KnownVersions v vs) pkgs)
106+
107+ Left _ ->
108+ D.failure ()
95109
96110
97111
@@ -130,26 +144,22 @@ addNew (name, version) versions =
130144 Map.alter (Just . add) name versions
131145
132146
133−
134−-- NEW PACKAGE DECODER
135−
136−
137147newPkgDecoder :: D.Decoder () (Pkg.Name, V.Version)
138148newPkgDecoder =
139− D.customString newPkgParser bail
140−
149+ do str <- D.string
150+ case Utf8.split 0x40 {-@-} str of
151+ [key, value] ->
152+ case Pkg.fromString key of
153+ Right pkg ->
154+ case V.fromString value of
155+ Just vsn -> return (pkg, vsn)
156+ Nothing -> D.failure ()
141157
142−newPkgParser :: P.Parser () (Pkg.Name, V.Version)
143−newPkgParser =
144− do pkg <- P.specialize (\_ _ _ -> ()) Pkg.parser
145− P.word1 0x40 {-@-} bail
146− vsn <- P.specialize (\_ _ _ -> ()) V.parser
147− return (pkg, vsn)
158+ Left _ ->
159+ D.failure ()
148160
149−
150−bail :: row -> col -> ()
151−bail _ _ =
152− ()
161+ _ ->
162+ D.failure ()
153163
154164
155165
@@ -180,7 +190,33 @@ getVersions' :: Pkg.Name -> Registry -> Either [Pkg.Name] KnownVersions
180190getVersions' name (Registry _ versions) =
181191 case Map.lookup name versions of
182192 Just kvs -> Right kvs
183− Nothing -> Left $ Pkg.nearbyNames name (Map.keys versions)
193+ Nothing -> Left $ nearbyNames name (Map.keys versions)
194+
195+
196+nearbyNames :: Pkg.Name -> [Pkg.Name] -> [Pkg.Name]
197+nearbyNames (Pkg.Name author1 project1) possibleNames =
198+ let
199+ authorDist = authorDistance (Name.toChars author1)
200+ projectDist = projectDistance (Name.toChars project1)
201+
202+ addDistance name@(Pkg.Name author2 project2) =
203+ ( authorDist author2 + projectDist project2, name )
204+ in
205+ map snd $ take 4 $
206+ List.sortBy (compare `on` fst) $
207+ map addDistance possibleNames
208+
209+
210+authorDistance :: String -> Name.Name -> Int
211+authorDistance bad possibility =
212+ abs (Suggest.distance bad (Name.toChars possibility))
213+
214+
215+projectDistance :: String -> Name.Name -> Int
216+projectDistance bad possibility =
217+ if possibility == "elm" || possibility == "elm-explorations"
218+ then 0
219+ else abs (Suggest.distance bad (Name.toChars possibility))
184220
185221
186222
@@ -189,14 +225,11 @@ getVersions' name (Registry _ versions) =
189225
190226post :: Http.Manager -> String -> D.Decoder x a -> (a -> IO b) -> IO (Either Exit.RegistryProblem b)
191227post manager path decoder callback =
192− let
193− url = Website.route path []
194− in
195− Http.post manager url [] Exit.RP_Http $
228+ Http.post manager (Website.route path []) [] Exit.RP_Http $
196229 \body ->
197230 case D.fromByteString decoder body of
198231 Right a -> Right <$> callback a
199− Left _ -> return $ Left $ Exit.RP_Data url body
232+ Left _ -> return $ Left Exit.RP_Data
200233
201234
202235
builder/src/Deps/Solver.hs+29−31
@@ -94,7 +94,6 @@ 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 $
9897 case try constraints of
9998 Solver solver ->
10099 solver (State cache connection registry Map.empty)
@@ -131,7 +130,6 @@ data AppSolution =
131130
132131addToApp :: Stuff.PackageCache -> Connection -> Registry.Registry -> Pkg.Name -> Outline.AppOutline -> IO (Result AppSolution)
133132addToApp cache connection registry pkg outline@(Outline.AppOutline _ _ direct indirect testDirect testIndirect) =
134− Stuff.withRegistryLock cache $
135133 let
136134 allIndirects = Map.union indirect testIndirect
137135 allDirects = Map.union direct testDirect
@@ -313,11 +311,10 @@ getConstraints pkg vsn =
313311 back state
314312
315313 Online manager ->
316− do let url = Website.metadata pkg vsn "elm.json"
317− result <- Http.get manager url [] id (return . Right)
314+ do result <- Http.get manager (Website.metadata pkg vsn "elm.json") [] id (return . Right)
318315 case result of
319316 Left httpProblem ->
320− err (Exit.SolverBadHttp pkg vsn httpProblem)
317+ err (Exit.SolverBadHttp httpProblem)
321318
322319 Right body ->
323320 case D.fromByteString constraintsDecoder body of
@@ -327,9 +324,11 @@ getConstraints pkg vsn =
327324 ok (toNewState cs) cs back
328325
329326 Left _ ->
330− err (Exit.SolverBadHttpData pkg vsn url)
327+ err (Exit.SolverBadHttpData pkg vsn)
331328
332329
330+-- TODO write constraintsDecoder to be a bit faster
331+--
333332constraintsDecoder :: D.Decoder () Constraints
334333constraintsDecoder =
335334 do outline <- D.mapError (const ()) Outline.decoder
@@ -351,31 +350,30 @@ data Env =
351350
352351initEnv :: IO (Either Exit.RegistryProblem Env)
353352initEnv =
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
353+ do mvar <- newEmptyMVar
354+ _ <- forkIO $ putMVar mvar =<< Http.getManager
355+ cache <- Stuff.getPackageCache
356+ maybeRegistry <- Registry.read cache
357+ manager <- readMVar mvar
358+
359+ case maybeRegistry of
360+ Nothing ->
361+ do eitherRegistry <- Registry.fetch manager cache
362+ case eitherRegistry of
363+ Right latestRegistry ->
364+ return $ Right $ Env cache manager (Online manager) latestRegistry
365+
366+ Left problem ->
367+ return $ Left $ problem
368+
369+ Just cachedRegistry ->
370+ do eitherRegistry <- Registry.update manager cache cachedRegistry
371+ case eitherRegistry of
372+ Right latestRegistry ->
373+ return $ Right $ Env cache manager (Online manager) latestRegistry
374+
375+ Left _ ->
376+ return $ Right $ Env cache manager Offline cachedRegistry
379377
380378
381379
builder/src/Elm/Bump.hsnew file+137
@@ -0,0 +1,137 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+module Elm.Bump
3+ ( bump
4+ , toPossibleBumps
5+ )
6+ where
7+
8+
9+import Control.Monad.Trans (liftIO)
10+import qualified Data.List as List
11+
12+import qualified Deps.Cache as Cache
13+import qualified Deps.Diff as Diff
14+import qualified Elm.Project.Json as Project
15+import qualified Elm.Project.Summary as Summary
16+import qualified Elm.Version as V
17+import Reporting.Doc ((<>), (<+>))
18+import qualified Reporting.Doc as D
19+import qualified Reporting.Exit as Exit
20+import qualified Reporting.Exit.Bump as E
21+import qualified Reporting.Exit.Help as Help
22+import qualified Reporting.Progress.Terminal as Terminal
23+import qualified Reporting.Task as Task
24+
25+
26+
27+-- BUMP
28+
29+
30+bump :: Summary.Summary -> Task.Task ()
31+bump summary@(Summary.Summary root project _ _ _) =
32+ case project of
33+ Project.App _ ->
34+ Task.throw (Exit.Bump E.Application)
35+
36+ Project.Pkg info@(Project.PkgInfo name _ _ version _ _ _ _) ->
37+ do registry <- Cache.mandatoryUpdate
38+ case Cache.getVersions name registry of
39+ Left _suggestions ->
40+ checkNewPackage root info
41+
42+ Right publishedVersions ->
43+ let
44+ bumpableVersions =
45+ map (\(old, _, _) -> old) (toPossibleBumps publishedVersions)
46+ in
47+ if elem version bumpableVersions then
48+ suggestVersion summary info
49+ else
50+ Task.throw $ Exit.Bump $ E.Unbumpable version $
51+ map head (List.group (List.sort bumpableVersions))
52+
53+
54+
55+-- VALID BUMPS
56+
57+
58+toPossibleBumps :: [V.Version] -> [(V.Version, V.Version, Diff.Magnitude)]
59+toPossibleBumps publishedVersions =
60+ case publishedVersions of
61+ [] ->
62+ []
63+
64+ _ ->
65+ let
66+ patchPoints =
67+ V.filterLatest V.majorAndMinor publishedVersions
68+
69+ minorPoints =
70+ V.filterLatest V._major publishedVersions
71+
72+ majorPoint =
73+ maximum publishedVersions
74+ in
75+ (majorPoint, V.bumpMajor majorPoint, Diff.MAJOR)
76+ : map (\v -> (v, V.bumpMinor v, Diff.MINOR)) minorPoints
77+ ++ map (\v -> (v, V.bumpPatch v, Diff.PATCH)) patchPoints
78+
79+
80+
81+-- CHECK NEW PACKAGE
82+
83+
84+checkNewPackage :: FilePath -> Project.PkgInfo -> Task.Task ()
85+checkNewPackage root info@(Project.PkgInfo _ _ _ version _ _ _ _) =
86+ do liftIO $ putStrLn Terminal.newPackageOverview
87+ if version == V.one
88+ then
89+ liftIO $ putStrLn "The version number in elm.json is correct so you are all set!"
90+ else
91+ changeVersion root info V.one $
92+ "It looks like the version in elm.json has been changed though!\n\
93+ \Would you like me to change it back to "
94+ <> D.fromUtf8 (V.toString V.one) <> "? [Y/n] "
95+
96+
97+
98+-- SUGGEST VERSION
99+
100+
101+suggestVersion :: Summary.Summary -> Project.PkgInfo -> Task.Task ()
102+suggestVersion (Summary.Summary root _ _ _ _) info@(Project.PkgInfo name _ _ version _ _ _ _) =
103+ do oldDocs <- Cache.getDocs name version
104+ newDocs <- Task.silently (error "TODO Project.generateDocs summary")
105+ let changes = Diff.diff oldDocs newDocs
106+ let newVersion = Diff.bump changes version
107+ changeVersion root info newVersion $
108+ let
109+ old = D.fromUtf8 $ V.toString version
110+ new = D.fromUtf8 $ V.toString newVersion
111+ mag = D.fromChars $ Diff.magnitudeToString (Diff.toMagnitude changes)
112+ in
113+ "Based on your new API, this should be a" <+> D.green mag <+> "change (" <> old <> " => " <> new <> ")\n"
114+ <> "Bail out of this command and run 'elm diff' for a full explanation.\n"
115+ <> "\n"
116+ <> "Should I perform the update (" <> old <> " => " <> new <> ") in elm.json? [Y/n] "
117+
118+
119+
120+-- CHANGE VERSION
121+
122+
123+changeVersion :: FilePath -> Project.PkgInfo -> V.Version -> D.Doc -> Task.Task ()
124+changeVersion root info targetVersion explanation =
125+ do approved <- Task.getApproval explanation
126+ if not approved
127+ then
128+ liftIO $ putStrLn "Okay, I did not change anything!"
129+
130+ else
131+ do liftIO $ Project.write root $ Project.Pkg $
132+ info { Project._pkg_version = targetVersion }
133+
134+ liftIO $ Help.toStdout $
135+ "Version changed to "
136+ <> D.green (D.fromUtf8 (V.toString targetVersion))
137+ <> "!\n"
builder/src/Elm/Details.hs+96−193
@@ -2,7 +2,6 @@
22{-# LANGUAGE BangPatterns, OverloadedStrings #-}
33module Elm.Details
44 ( Details(..)
5− , BuildID
65 , ValidOutline(..)
76 , Local(..)
87 , Foreign(..)
@@ -16,32 +15,25 @@ module Elm.Details
1615
1716import Control.Concurrent (forkIO)
1817import Control.Concurrent.MVar (MVar, newEmptyMVar, newMVar, putMVar, readMVar, takeMVar)
19−import Control.Monad (liftM, liftM2, liftM3)
18+import Control.Monad (liftM, liftM2, liftM4)
2019import Data.Binary (Binary, get, put, getWord8, putWord8)
21−import qualified Data.Either as Either
2220import qualified Data.Map as Map
2321import qualified Data.Map.Utils as Map
2422import qualified Data.Map.Merge.Strict as Map
25−import qualified Data.Maybe as Maybe
2623import qualified Data.Name as Name
27−import qualified Data.NonEmptyList as NE
2824import qualified Data.OneOrMore as OneOrMore
2925import qualified Data.Set as Set
3026import qualified Data.Utf8 as Utf8
31−import Data.Word (Word64)
3227import qualified System.Directory as Dir
3328import System.FilePath ((</>), (<.>))
3429
35−import qualified AST.Canonical as Can
3630import qualified AST.Source as Src
3731import qualified AST.Optimized as Opt
38−import qualified BackgroundWriter as BW
3932import qualified Compile
4033import qualified Deps.Registry as Registry
4134import qualified Deps.Solver as Solver
4235import qualified Deps.Website as Website
4336import qualified Elm.Constraint as Con
44−import qualified Elm.Docs as Docs
4537import qualified Elm.Interface as I
4638import qualified Elm.Kernel as Kernel
4739import qualified Elm.ModuleName as ModuleName
@@ -51,7 +43,6 @@ import qualified Elm.Version as V
5143import qualified File
5244import qualified Http
5345import qualified Json.Decode as D
54−import qualified Json.Encode as E
5546import qualified Parse.Module as Parse
5647import qualified Reporting
5748import qualified Reporting.Annotation as A
@@ -68,42 +59,23 @@ data Details =
6859 Details
6960 { _outlineTime :: File.Time
7061 , _outline :: ValidOutline
71− , _buildID :: BuildID
7262 , _locals :: Map.Map ModuleName.Raw Local
7363 , _foreigns :: Map.Map ModuleName.Raw Foreign
7464 , _extras :: Extras
7565 }
7666
7767
78−type BuildID = Word64
68+data ValidOutline
69+ = ValidApp Outline.AppOutline
70+ | ValidPkg Outline.PkgOutline (Map.Map Pkg.Name V.Version)
7971
8072
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−--
9973data Local =
10074 Local
10175 { _path :: FilePath
10276 , _time :: File.Time
10377 , _deps :: [ModuleName.Raw]
10478 , _main :: Bool
105− , _lastChange :: BuildID
106− , _lastCompile :: BuildID
10779 }
10880
10981
@@ -125,14 +97,14 @@ type Interfaces =
12597
12698
12799loadObjects :: FilePath -> Details -> IO (MVar (Maybe Opt.GlobalGraph))
128−loadObjects root (Details _ _ _ _ _ extras) =
100+loadObjects root (Details _ _ _ _ extras) =
129101 case extras of
130102 ArtifactsFresh _ o -> newMVar (Just o)
131103 ArtifactsCached -> fork (File.readBinary (Stuff.objects root))
132104
133105
134106loadInterfaces :: FilePath -> Details -> IO (MVar (Maybe Interfaces))
135−loadInterfaces root (Details _ _ _ _ _ extras) =
107+loadInterfaces root (Details _ _ _ _ extras) =
136108 case extras of
137109 ArtifactsFresh i _ -> newMVar (Just i)
138110 ArtifactsCached -> fork (File.readBinary (Stuff.interfaces root))
@@ -142,11 +114,11 @@ loadInterfaces root (Details _ _ _ _ _ extras) =
142114-- VERIFY INSTALL -- used by Install
143115
144116
145−verifyInstall :: BW.Scope -> FilePath -> Solver.Env -> Outline.Outline -> IO (Either Exit.Details ())
146−verifyInstall scope root (Solver.Env cache manager connection registry) outline =
117+verifyInstall :: FilePath -> Solver.Env -> Outline.Outline -> IO (Either Exit.Details ())
118+verifyInstall root (Solver.Env cache manager connection registry) outline =
147119 do time <- File.getTime (root </> "elm.json")
148120 let key = Reporting.ignorer
149− let env = Env key scope root cache manager connection registry
121+ let env = Env key root cache manager connection registry
150122 case outline of
151123 Outline.Pkg pkg -> Task.run (verifyPkg env time pkg >> return ())
152124 Outline.App app -> Task.run (verifyApp env time app >> return ())
@@ -156,28 +128,28 @@ verifyInstall scope root (Solver.Env cache manager connection registry) outline
156128-- LOAD -- used by Make, Repl, Reactor
157129
158130
159−load :: Reporting.Style -> BW.Scope -> FilePath -> IO (Either Exit.Details Details)
160−load style scope root =
131+load :: Reporting.Style -> FilePath -> IO (Either Exit.Details Details)
132+load style root =
161133 do newTime <- File.getTime (root </> "elm.json")
162134 maybeDetails <- File.readBinary (Stuff.details root)
163135 case maybeDetails of
164136 Nothing ->
165− generate style scope root newTime
137+ generate style root newTime
166138
167− Just details@(Details oldTime _ buildID _ _ _) ->
139+ Just details@(Details oldTime _ _ _ _) ->
168140 if oldTime == newTime
169− then return (Right details { _buildID = buildID + 1 })
170− else generate style scope root newTime
141+ then return (Right details)
142+ else generate style root newTime
171143
172144
173145
174146-- GENERATE
175147
176148
177−generate :: Reporting.Style -> BW.Scope -> FilePath -> File.Time -> IO (Either Exit.Details Details)
178−generate style scope root time =
149+generate :: Reporting.Style -> FilePath -> File.Time -> IO (Either Exit.Details Details)
150+generate style root time =
179151 Reporting.trackDetails style $ \key ->
180− do result <- initEnv key scope root
152+ do result <- initEnv key root
181153 case result of
182154 Left exit ->
183155 return (Left exit)
@@ -195,7 +167,6 @@ generate style scope root time =
195167data Env =
196168 Env
197169 { _key :: Reporting.DKey
198− , _scope :: BW.Scope
199170 , _root :: FilePath
200171 , _cache :: Stuff.PackageCache
201172 , _manager :: Http.Manager
@@ -204,8 +175,8 @@ data Env =
204175 }
205176
206177
207−initEnv :: Reporting.DKey -> BW.Scope -> FilePath -> IO (Either Exit.Details (Env, Outline.Outline))
208−initEnv key scope root =
178+initEnv :: Reporting.DKey -> FilePath -> IO (Either Exit.Details (Env, Outline.Outline))
179+initEnv key root =
209180 do mvar <- fork Solver.initEnv
210181 eitherOutline <- Outline.read root
211182 case eitherOutline of
@@ -219,7 +190,7 @@ initEnv key scope root =
219190 return $ Left $ Exit.DetailsCannotGetRegistry problem
220191
221192 Right (Solver.Env cache manager connection registry) ->
222− return $ Right (Env key scope root cache manager connection registry, outline)
193+ return $ Right (Env key root cache manager connection registry, outline)
223194
224195
225196
@@ -230,25 +201,24 @@ type Task a = Task.Task Exit.Details a
230201
231202
232203verifyPkg :: Env -> File.Time -> Outline.PkgOutline -> Task Details
233−verifyPkg env time (Outline.PkgOutline pkg _ _ _ exposed direct testDirect elm) =
204+verifyPkg env time outline@(Outline.PkgOutline _ _ _ _ _ direct testDirect elm) =
234205 if Con.goodElm elm
235206 then
236207 do solution <- verifyConstraints env =<< union noDups direct testDirect
237− let exposedList = Outline.flattenExposed exposed
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
208+ let vsns = Map.map (\(Solver.Details v _) -> v) solution
209+ verifyDependencies env time (ValidPkg outline vsns) solution direct
240210 else
241211 Task.throw $ Exit.DetailsBadElmInPkg elm
242212
243213
244214verifyApp :: Env -> File.Time -> Outline.AppOutline -> Task Details
245−verifyApp env time outline@(Outline.AppOutline elmVersion srcDirs direct _ _ _) =
215+verifyApp env time outline@(Outline.AppOutline elmVersion _ direct _ _ _) =
246216 if elmVersion == V.compiler
247217 then
248218 do stated <- checkAppDeps outline
249219 actual <- verifyConstraints env (Map.map Con.exactly stated)
250220 if Map.size stated == Map.size actual
251− then verifyDependencies env time (ValidApp srcDirs) actual direct
221+ then verifyDependencies env time (ValidApp outline) actual direct
252222 else Task.throw $ Exit.DetailsHandEditedDependencies
253223 else
254224 Task.throw $ Exit.DetailsBadElmInAppOutline elmVersion
@@ -266,7 +236,7 @@ checkAppDeps (Outline.AppOutline _ _ direct indirect testDirect testIndirect) =
266236
267237
268238verifyConstraints :: Env -> Map.Map Pkg.Name Con.Constraint -> Task (Map.Map Pkg.Name Solver.Details)
269−verifyConstraints (Env _ _ _ cache _ connection registry) constraints =
239+verifyConstraints (Env _ _ cache _ connection registry) constraints =
270240 do result <- Task.io $ Solver.verify cache connection registry constraints
271241 case result of
272242 Solver.Ok details -> return details
@@ -312,30 +282,27 @@ fork work =
312282
313283
314284verifyDependencies :: Env -> File.Time -> ValidOutline -> Map.Map Pkg.Name Solver.Details -> Map.Map Pkg.Name a -> Task Details
315−verifyDependencies env@(Env key scope root cache _ _ _) time outline solution directDeps =
285+verifyDependencies env@(Env key root _ _ _ _) time outline solution directDeps =
316286 Task.eio id $
317287 do Reporting.report key (Reporting.DStart (Map.size solution))
318288 mvar <- newEmptyMVar
319− mvars <- Stuff.withRegistryLock cache $
320− Map.traverseWithKey (\k v -> fork (verifyDep env mvar solution k v)) solution
289+ mvars <- Map.traverseWithKey (\k v -> fork (verifyDep env mvar solution k v)) solution
321290 putMVar mvar mvars
322291 deps <- traverse readMVar mvars
323292 case sequence deps of
324− Left _ ->
325− do home <- Stuff.getElmHome
326− return $ Left $ Exit.DetailsBadDeps home $
327− Maybe.catMaybes $ Either.lefts $ Map.elems deps
293+ Left problem ->
294+ error "TODO verifyDependencies" problem
328295
329296 Right artifacts ->
330297 let
331298 objs = Map.foldr addObjects Opt.empty artifacts
332299 ifaces = Map.foldrWithKey (addInterfaces directDeps) Map.empty artifacts
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)
300+ foreigns = Map.map (OneOrMore.destruct Foreign) $ Map.foldrWithKey gatherForeigns Map.empty artifacts
301+ details = Details time outline Map.empty foreigns (ArtifactsFresh ifaces objs)
335302 in
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
303+ do File.writeBinary (Stuff.objects root) objs
304+ File.writeBinary (Stuff.interfaces root) ifaces
305+ File.writeBinary (Stuff.details root) details
339306 return (Right details)
340307
341308
@@ -375,36 +342,44 @@ data Artifacts =
375342
376343
377344type Dep =
378− Either (Maybe Exit.DetailsBadDep) Artifacts
345+ Either Problem Artifacts
346+
347+
348+data Problem
349+ = BadDownload Exit.PackageProblem
350+ | BadBuild
351+ | BadDependency
379352
380353
381354verifyDep :: Env -> MVar (Map.Map Pkg.Name (MVar Dep)) -> Map.Map Pkg.Name Solver.Details -> Pkg.Name -> Solver.Details -> IO Dep
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")
355+verifyDep (Env key _ cache manager _ _) depsMVar solution pkg details@(Solver.Details vsn directDeps) =
356+ let
357+ fingerprint = Map.intersectionWith (\(Solver.Details v _) _ -> v) solution directDeps
358+ in
359+ do exists <- Dir.doesDirectoryExist (Stuff.package cache pkg vsn </> "src")
385360 if exists
386361 then
387362 do Reporting.report key Reporting.DCached
388363 maybeCache <- File.readBinary (Stuff.package cache pkg vsn </> "artifacts.dat")
389364 case maybeCache of
390365 Nothing ->
391− build key cache depsMVar pkg details fingerprint Set.empty
366+ build key cache depsMVar pkg details (Set.singleton fingerprint)
392367
393368 Just (ArtifactCache fingerprints artifacts) ->
394369 if Set.member fingerprint fingerprints
395370 then Reporting.report key Reporting.DBuilt >> return (Right artifacts)
396− else build key cache depsMVar pkg details fingerprint fingerprints
371+ else build key cache depsMVar pkg details (Set.insert fingerprint fingerprints)
397372 else
398373 do Reporting.report key Reporting.DRequested
399374 result <- downloadPackage cache manager pkg vsn
400375 case result of
401− Left problem ->
376+ Left p ->
402377 do Reporting.report key (Reporting.DFailed pkg vsn)
403− return $ Left $ Just $ Exit.BD_BadDownload pkg vsn problem
378+ return (Left (BadDownload p))
404379
405380 Right () ->
406381 do Reporting.report key (Reporting.DReceived pkg vsn)
407− build key cache depsMVar pkg details fingerprint Set.empty
382+ build key cache depsMVar pkg details (Set.singleton fingerprint)
408383
409384
410385
@@ -426,17 +401,17 @@ type Fingerprint =
426401-- BUILD
427402
428403
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 =
404+build :: Reporting.DKey -> Stuff.PackageCache -> MVar (Map.Map Pkg.Name (MVar Dep)) -> Pkg.Name -> Solver.Details -> Set.Set Fingerprint -> IO Dep
405+build key cache depsMVar pkg (Solver.Details vsn _) fingerprints =
431406 do eitherOutline <- Outline.read (Stuff.package cache pkg vsn)
432407 case eitherOutline of
433408 Left _ ->
434409 do Reporting.report key Reporting.DBroken
435− return $ Left $ Just $ Exit.BD_BadBuild pkg vsn f
410+ return (Left BadBuild)
436411
437412 Right (Outline.App _) ->
438413 do Reporting.report key Reporting.DBroken
439− return $ Left $ Just $ Exit.BD_BadBuild pkg vsn f
414+ return (Left BadBuild)
440415
441416 Right (Outline.Pkg (Outline.PkgOutline _ _ _ _ exposed deps _ _)) ->
442417 do allDeps <- readMVar depsMVar
@@ -444,22 +419,21 @@ build key cache depsMVar pkg (Solver.Details vsn _) f fs =
444419 case sequence directDeps of
445420 Left _ ->
446421 do Reporting.report key Reporting.DBroken
447− return $ Left $ Nothing
422+ return (Left BadDependency)
448423
449424 Right directArtifacts ->
450425 do let src = Stuff.package cache pkg vsn </> "src"
451426 let foreignDeps = gatherForeignInterfaces directArtifacts
452427 let exposedDict = Map.fromKeys (\_ -> ()) (Outline.flattenExposed exposed)
453− docsStatus <- getDocsStatus cache pkg vsn
454428 mvar <- newEmptyMVar
455− mvars <- Map.traverseWithKey (const . fork . crawlModule foreignDeps mvar pkg src docsStatus) exposedDict
429+ mvars <- Map.traverseWithKey (const . fork . crawlModule foreignDeps mvar pkg src) exposedDict
456430 putMVar mvar mvars
457431 mapM_ readMVar mvars
458432 maybeStatuses <- traverse readMVar =<< readMVar mvar
459433 case sequence maybeStatuses of
460434 Nothing ->
461435 do Reporting.report key Reporting.DBroken
462− return $ Left $ Just $ Exit.BD_BadBuild pkg vsn f
436+ return (Left BadBuild)
463437
464438 Just statuses ->
465439 do rmvar <- newEmptyMVar
@@ -469,7 +443,7 @@ build key cache depsMVar pkg (Solver.Details vsn _) f fs =
469443 case sequence maybeResults of
470444 Nothing ->
471445 do Reporting.report key Reporting.DBroken
472− return $ Left $ Just $ Exit.BD_BadBuild pkg vsn f
446+ return (Left BadBuild)
473447
474448 Just results ->
475449 let
@@ -477,10 +451,8 @@ build key cache depsMVar pkg (Solver.Details vsn _) f fs =
477451 ifaces = gatherInterfaces exposedDict results
478452 objects = gatherObjects results
479453 artifacts = Artifacts ifaces objects
480− fingerprints = Set.insert f fs
481454 in
482− do writeDocs cache pkg vsn docsStatus results
483− File.writeBinary path (ArtifactCache fingerprints artifacts)
455+ do File.writeBinary path (ArtifactCache fingerprints artifacts)
484456 Reporting.report key Reporting.DBuilt
485457 return (Right artifacts)
486458
@@ -497,7 +469,7 @@ gatherObjects results =
497469addLocalGraph :: ModuleName.Raw -> Result -> Opt.GlobalGraph -> Opt.GlobalGraph
498470addLocalGraph name status graph =
499471 case status of
500− RLocal _ objs _ -> Opt.addLocalGraph objs graph
472+ RLocal _ objs -> Opt.addLocalGraph objs graph
501473 RForeign _ -> graph
502474 RKernelLocal cs -> Opt.addKernel (Name.getKernel name) cs graph
503475 RKernelForeign -> graph
@@ -516,10 +488,10 @@ gatherInterfaces exposed artifacts =
516488toLocalInterface :: (I.Interface -> a) -> Result -> Maybe a
517489toLocalInterface func result =
518490 case result of
519− RLocal iface _ _ -> Just (func iface)
520− RForeign _ -> Nothing
521− RKernelLocal _ -> Nothing
522− RKernelForeign -> Nothing
491+ RLocal iface _ -> Just (func iface)
492+ RForeign _ -> Nothing
493+ RKernelLocal _ -> Nothing
494+ RKernelForeign -> Nothing
523495
524496
525497
@@ -562,14 +534,14 @@ type StatusDict =
562534
563535
564536data Status
565− = SLocal DocsStatus (Map.Map ModuleName.Raw ()) Src.Module
537+ = SLocal (Map.Map ModuleName.Raw ()) Src.Module
566538 | SForeign I.Interface
567539 | SKernelLocal [Kernel.Chunk]
568540 | SKernelForeign
569541
570542
571−crawlModule :: Map.Map ModuleName.Raw ForeignInterface -> MVar StatusDict -> Pkg.Name -> FilePath -> DocsStatus -> ModuleName.Raw -> IO (Maybe Status)
572−crawlModule foreignDeps mvar pkg src docsStatus name =
543+crawlModule :: Map.Map ModuleName.Raw ForeignInterface -> MVar StatusDict -> Pkg.Name -> FilePath -> ModuleName.Raw -> IO (Maybe Status)
544+crawlModule foreignDeps mvar pkg src name =
573545 do let path = src </> ModuleName.toFilePath name <.> "elm"
574546 exists <- File.exists path
575547 case Map.lookup name foreignDeps of
@@ -583,7 +555,7 @@ crawlModule foreignDeps mvar pkg src docsStatus name =
583555
584556 Nothing ->
585557 if exists then
586− crawlFile foreignDeps mvar pkg src docsStatus name path
558+ crawlFile foreignDeps mvar pkg src name path
587559
588560 else if Pkg.isKernel pkg && Name.isKernel name then
589561 crawlKernel foreignDeps mvar pkg src name
@@ -592,13 +564,13 @@ crawlModule foreignDeps mvar pkg src docsStatus name =
592564 return Nothing
593565
594566
595−crawlFile :: Map.Map ModuleName.Raw ForeignInterface -> MVar StatusDict -> Pkg.Name -> FilePath -> DocsStatus -> ModuleName.Raw -> FilePath -> IO (Maybe Status)
596−crawlFile foreignDeps mvar pkg src docsStatus expectedName path =
567+crawlFile :: Map.Map ModuleName.Raw ForeignInterface -> MVar StatusDict -> Pkg.Name -> FilePath -> ModuleName.Raw -> FilePath -> IO (Maybe Status)
568+crawlFile foreignDeps mvar pkg src expectedName path =
597569 do bytes <- File.readUtf8 path
598− case Parse.fromByteString (Parse.Package pkg) bytes of
570+ case Parse.fromByteString pkg bytes of
599571 Right modul@(Src.Module (Just (A.At _ actualName)) _ _ imports _ _ _ _ _) | expectedName == actualName ->
600572 do deps <- crawlImports foreignDeps mvar pkg src imports
601− return (Just (SLocal docsStatus deps modul))
573+ return (Just (SLocal deps modul))
602574
603575 _ ->
604576 return Nothing
@@ -609,7 +581,7 @@ crawlImports foreignDeps mvar pkg src imports =
609581 do statusDict <- takeMVar mvar
610582 let deps = Map.fromList (map (\i -> (Src.getImportName i, ())) imports)
611583 let news = Map.difference deps statusDict
612− mvars <- Map.traverseWithKey (const . fork . crawlModule foreignDeps mvar pkg src DocsNotNeeded) news
584+ mvars <- Map.traverseWithKey (const . fork . crawlModule foreignDeps mvar pkg src) news
613585 putMVar mvar (Map.union mvars statusDict)
614586 mapM_ readMVar mvars
615587 return deps
@@ -645,7 +617,7 @@ getDepHome fi =
645617
646618
647619data Result
648− = RLocal !I.Interface !Opt.LocalGraph (Maybe Docs.Module)
620+ = RLocal !I.Interface !Opt.LocalGraph
649621 | RForeign I.Interface
650622 | RKernelLocal [Kernel.Chunk]
651623 | RKernelForeign
@@ -654,7 +626,7 @@ data Result
654626compile :: Pkg.Name -> MVar (Map.Map ModuleName.Raw (MVar (Maybe Result))) -> Status -> IO (Maybe Result)
655627compile pkg mvar status =
656628 case status of
657− SLocal docsStatus deps modul ->
629+ SLocal deps modul ->
658630 do resultsDict <- readMVar mvar
659631 maybeResults <- traverse readMVar (Map.intersection resultsDict deps)
660632 case sequence maybeResults of
@@ -667,11 +639,7 @@ compile pkg mvar status =
667639 return Nothing
668640
669641 Right (Compile.Artifacts canonical annotations objects) ->
670− let
671− ifaces = I.fromModule pkg canonical annotations
672− docs = makeDocs docsStatus canonical
673− in
674− return (Just (RLocal ifaces objects docs))
642+ return (Just (RLocal (I.fromModule pkg canonical annotations) objects))
675643
676644 SForeign iface ->
677645 return (Just (RForeign iface))
@@ -686,59 +654,10 @@ compile pkg mvar status =
686654getInterface :: Result -> Maybe I.Interface
687655getInterface result =
688656 case result of
689− RLocal iface _ _ -> Just iface
690− RForeign iface -> Just iface
691− RKernelLocal _ -> Nothing
692− RKernelForeign -> Nothing
693−
694−
695−
696−-- MAKE DOCS
697−
698−
699−data DocsStatus
700− = DocsNeeded
701− | DocsNotNeeded
702−
703−
704−getDocsStatus :: Stuff.PackageCache -> Pkg.Name -> V.Version -> IO DocsStatus
705−getDocsStatus cache pkg vsn =
706− do exists <- File.exists (Stuff.package cache pkg vsn </> "docs.json")
707− if exists
708− then return DocsNotNeeded
709− else return DocsNeeded
710−
711−
712−makeDocs :: DocsStatus -> Can.Module -> Maybe Docs.Module
713−makeDocs status modul =
714− case status of
715− DocsNeeded ->
716− case Docs.fromModule modul of
717− Right docs -> Just docs
718− Left _ -> Nothing
719−
720− DocsNotNeeded ->
721− Nothing
722−
723−
724−writeDocs :: Stuff.PackageCache -> Pkg.Name -> V.Version -> DocsStatus -> Map.Map ModuleName.Raw Result -> IO ()
725−writeDocs cache pkg vsn status results =
726− case status of
727− DocsNeeded ->
728− E.writeUgly (Stuff.package cache pkg vsn </> "docs.json") $
729− Docs.encode $ Map.mapMaybe toDocs results
730−
731− DocsNotNeeded ->
732− return ()
733−
734−
735−toDocs :: Result -> Maybe Docs.Module
736−toDocs result =
737− case result of
738− RLocal _ _ docs -> docs
739− RForeign _ -> Nothing
740− RKernelLocal _ -> Nothing
741− RKernelForeign -> Nothing
657+ RLocal iface _ -> Just iface
658+ RForeign iface -> Just iface
659+ RKernelLocal _ -> Nothing
660+ RKernelForeign -> Nothing
742661
743662
744663
@@ -747,27 +666,24 @@ toDocs result =
747666
748667downloadPackage :: Stuff.PackageCache -> Http.Manager -> Pkg.Name -> V.Version -> IO (Either Exit.PackageProblem ())
749668downloadPackage cache manager pkg vsn =
750− let
751− url = Website.metadata pkg vsn "endpoint.json"
752− in
753669 do eitherByteString <-
754− Http.get manager url [] id (return . Right)
670+ Http.get manager (Website.metadata pkg vsn "endpoint.json") [] id (return . Right)
755671
756672 case eitherByteString of
757673 Left err ->
758− return $ Left $ Exit.PP_BadEndpointRequest err
674+ return (Left (Exit.PP_BadEndpointRequest err))
759675
760676 Right byteString ->
761677 case D.fromByteString endpointDecoder byteString of
762678 Left _ ->
763− return $ Left $ Exit.PP_BadEndpointContent url
679+ return (Left Exit.PP_BadEndpointContent)
764680
765681 Right (endpoint, expectedHash) ->
766− Http.getArchive manager endpoint Exit.PP_BadArchiveRequest (Exit.PP_BadArchiveContent endpoint) $
682+ Http.getArchive manager endpoint Exit.PP_BadArchiveRequest Exit.PP_BadArchiveContent $
767683 \(sha, archive) ->
768684 if expectedHash == Http.shaToChars sha
769685 then Right <$> File.writePackage (Stuff.package cache pkg vsn) archive
770− else return $ Left $ Exit.PP_BadArchiveHash endpoint expectedHash (Http.shaToChars sha)
686+ else return $ Left $ Exit.PP_BadArchiveHash expectedHash (Http.shaToChars sha)
771687
772688
773689endpointDecoder :: D.Decoder e (String, String)
@@ -782,40 +698,27 @@ endpointDecoder =
782698
783699
784700instance Binary Details where
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)
701+ get = do { a <- get; b <- get; c <- get; d <- get; return (Details a b c d ArtifactsCached) }
702+ put (Details a b c d _) = put a >> put b >> put c >> put d
793703
794704
795705instance Binary ValidOutline where
796706 put outline =
797707 case outline of
798− ValidApp a -> putWord8 0 >> put a
799− ValidPkg a b c -> putWord8 1 >> put a >> put b >> put c
708+ ValidApp a -> putWord8 0 >> put a
709+ ValidPkg a b -> putWord8 1 >> put a >> put b
800710
801711 get =
802712 do n <- getWord8
803713 case n of
804714 0 -> liftM ValidApp get
805− 1 -> liftM3 ValidPkg get get get
806− _ -> fail "binary encoding of ValidOutline was corrupted"
715+ 1 -> liftM2 ValidPkg get get
716+ _ -> error "binary encoding of ValidOutline was corrupted"
807717
808718
809719instance Binary Local where
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)
720+ get = liftM4 Local get get get get
721+ put (Local a b c d) = put a >> put b >> put c >> put d
819722
820723
821724instance Binary Foreign where
builder/src/Elm/Diff.hsnew file+284
@@ -0,0 +1,284 @@
1+{-# OPTIONS_GHC -Wall #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+module Elm.Diff
4+ ( Args(..)
5+ , diff
6+ )
7+ where
8+
9+
10+import Control.Monad.Except (liftIO)
11+import qualified Data.List as List
12+import qualified Data.Map as Map
13+import qualified Data.Maybe as Maybe
14+import qualified Data.Name as Name
15+
16+import qualified Deps.Cache as Cache
17+import Deps.Diff (PackageChanges(..), ModuleChanges(..), Changes(..), Magnitude(..))
18+import qualified Deps.Diff as Diff
19+import qualified Elm.Compiler.Type as Type
20+import qualified Elm.Docs as Docs
21+import qualified Elm.ModuleName as ModuleName
22+import qualified Elm.Package as Pkg
23+import qualified Elm.Project as Project
24+import qualified Elm.Project.Json as Project
25+import qualified Elm.Project.Summary as Summary
26+import qualified Elm.Version as V
27+import Reporting.Doc ((<>), (<+>))
28+import qualified Reporting.Doc as D
29+import qualified Reporting.Exit as Exit
30+import qualified Reporting.Exit.Diff as E
31+import qualified Reporting.Exit.Help as Help
32+import qualified Reporting.Render.Type.Localizer as L
33+import qualified Reporting.Task as Task
34+
35+
36+
37+-- DIFF
38+
39+
40+data Args
41+ = CodeVsLatest
42+ | CodeVsExactly V.Version
43+ | LocalInquiry V.Version V.Version
44+ | GlobalInquiry Pkg.Name V.Version V.Version
45+
46+
47+diff :: Args -> Task.Task ()
48+diff args =
49+ case args of
50+ GlobalInquiry name v1 v2 ->
51+ do registry <- Cache.mandatoryUpdate
52+ case Cache.getVersions name registry of
53+ Left suggestions ->
54+ throw $ E.UnknownPackage name suggestions
55+
56+ Right vsns ->
57+ do oldDocs <- getDocs name vsns (min v1 v2)
58+ newDocs <- getDocs name vsns (max v1 v2)
59+ writeDiff oldDocs newDocs
60+
61+ LocalInquiry v1 v2 ->
62+ do (_, name, vsns) <- getPackageInfo
63+ oldDocs <- getDocs name vsns (min v1 v2)
64+ newDocs <- getDocs name vsns (max v1 v2)
65+ writeDiff oldDocs newDocs
66+
67+ CodeVsLatest ->
68+ do (summary, name, vsns) <- getPackageInfo
69+ oldDocs <- getDocs name vsns (maximum vsns)
70+ newDocs <- Task.silently (error "TODO Project.generateDocs summary" summary)
71+ writeDiff oldDocs newDocs
72+
73+ CodeVsExactly version ->
74+ do (summary, name, vsns) <- getPackageInfo
75+ oldDocs <- getDocs name vsns version
76+ newDocs <- Task.silently (error "TODO Project.generateDocs summary" summary)
77+ writeDiff oldDocs newDocs
78+
79+
80+throw :: E.Exit -> Task.Task a
81+throw exit =
82+ Task.throw $ Exit.Diff exit
83+
84+
85+
86+-- DIFF HELPERS
87+
88+
89+getDocs :: Pkg.Name -> [V.Version] -> V.Version -> Task.Task Docs.Documentation
90+getDocs name allVersions version =
91+ if elem version allVersions then
92+ Cache.getDocs name version
93+ else
94+ throw $ E.UnknownVersion name version allVersions
95+
96+
97+getPackageInfo :: Task.Task (Summary.Summary, Pkg.Name, [V.Version])
98+getPackageInfo =
99+ do summary <- Project.getRoot
100+ case Summary._project summary of
101+ Project.App _ ->
102+ throw $ E.Application
103+
104+ Project.Pkg (Project.PkgInfo name _ _ _ _ _ _ _) ->
105+ do registry <- Cache.mandatoryUpdate
106+ case Cache.getVersions name registry of
107+ Right vsns ->
108+ return ( summary, name, vsns )
109+
110+ Left _ ->
111+ throw E.Unpublished
112+
113+
114+
115+-- WRITE DOC
116+
117+
118+writeDiff :: Docs.Documentation -> Docs.Documentation -> Task.Task ()
119+writeDiff oldDocs newDocs =
120+ let
121+ changes = Diff.diff oldDocs newDocs
122+ localizer = L.fromNames (Map.union oldDocs newDocs)
123+ in
124+ liftIO $ Help.toStdout (toDoc localizer changes <> "\n")
125+
126+
127+
128+-- TO DOC
129+
130+
131+toDoc :: L.Localizer -> PackageChanges -> D.Doc
132+toDoc localizer changes@(PackageChanges added changed removed) =
133+ if null added && Map.null changed && null removed then
134+ "No API changes detected, so this is a" <+> D.green "PATCH" <+> "change."
135+ else
136+ let
137+ magDoc =
138+ D.fromChars (Diff.magnitudeToString (Diff.toMagnitude changes))
139+
140+ header =
141+ "This is a" <+> D.green magDoc <+> "change."
142+
143+ addedChunk =
144+ if null added then [] else
145+ [ Chunk "ADDED MODULES" MINOR $
146+ D.vcat $ map (D.fromUtf8 . ModuleName.nameToString) added
147+ ]
148+
149+ removedChunk =
150+ if null removed then [] else
151+ [ Chunk "REMOVED MODULES" MAJOR $
152+ D.vcat $ map (D.fromUtf8 . ModuleName.nameToString) removed
153+ ]
154+
155+ chunks =
156+ addedChunk ++ removedChunk ++ map (changesToChunk localizer) (Map.toList changed)
157+ in
158+ D.vcat (header : "" : map chunkToDoc chunks)
159+
160+
161+data Chunk =
162+ Chunk
163+ { _title :: String
164+ , _magnitude :: Magnitude
165+ , _details :: D.Doc
166+ }
167+
168+
169+chunkToDoc :: Chunk -> D.Doc
170+chunkToDoc (Chunk title magnitude details) =
171+ let
172+ magDoc =
173+ Diff.magnitudeToString magnitude
174+
175+ header =
176+ "----" <+> D.fromChars title <+> "-" <+> D.fromChars magDoc <+> "----"
177+ in
178+ D.vcat
179+ [ D.dullcyan header
180+ , ""
181+ , D.indent 4 details
182+ , ""
183+ , ""
184+ ]
185+
186+
187+changesToChunk :: L.Localizer -> (Name.Name, ModuleChanges) -> Chunk
188+changesToChunk localizer (name, changes@(ModuleChanges unions aliases values binops)) =
189+ let
190+ magnitude =
191+ Diff.moduleChangeMagnitude changes
192+
193+ (unionAdd, unionChange, unionRemove) =
194+ changesToDocTriple (unionToDoc localizer) unions
195+
196+ (aliasAdd, aliasChange, aliasRemove) =
197+ changesToDocTriple (aliasToDoc localizer) aliases
198+
199+ (valueAdd, valueChange, valueRemove) =
200+ changesToDocTriple (valueToDoc localizer) values
201+
202+ (binopAdd, binopChange, binopRemove) =
203+ changesToDocTriple (binopToDoc localizer) binops
204+ in
205+ Chunk (Name.toChars name) magnitude $
206+ D.vcat $ List.intersperse "" $ Maybe.catMaybes $
207+ [ changesToDoc "Added" unionAdd aliasAdd valueAdd binopAdd
208+ , changesToDoc "Removed" unionRemove aliasRemove valueRemove binopRemove
209+ , changesToDoc "Changed" unionChange aliasChange valueChange binopChange
210+ ]
211+
212+
213+changesToDocTriple :: (k -> v -> D.Doc) -> Changes k v -> ([D.Doc], [D.Doc], [D.Doc])
214+changesToDocTriple entryToDoc (Changes added changed removed) =
215+ let
216+ indented (name, value) =
217+ D.indent 4 (entryToDoc name value)
218+
219+ diffed (name, (oldValue, newValue)) =
220+ D.vcat
221+ [ " - " <> entryToDoc name oldValue
222+ , " + " <> entryToDoc name newValue
223+ , ""
224+ ]
225+ in
226+ ( map indented (Map.toList added)
227+ , map diffed (Map.toList changed)
228+ , map indented (Map.toList removed)
229+ )
230+
231+
232+changesToDoc :: String -> [D.Doc] -> [D.Doc] -> [D.Doc] -> [D.Doc] -> Maybe D.Doc
233+changesToDoc categoryName unions aliases values binops =
234+ if null unions && null aliases && null values && null binops then
235+ Nothing
236+
237+ else
238+ Just $ D.vcat $
239+ D.fromChars categoryName <> ":" : unions ++ aliases ++ binops ++ values
240+
241+
242+unionToDoc :: L.Localizer -> Name.Name -> Docs.Union -> D.Doc
243+unionToDoc localizer name (Docs.Union _ tvars ctors) =
244+ let
245+ setup =
246+ "type" <+> D.fromName name <+> D.hsep (map D.fromName tvars)
247+
248+ ctorDoc (ctor, tipes) =
249+ typeDoc localizer (Type.Type ctor tipes)
250+ in
251+ D.hang 4 (D.sep (setup : zipWith (<+>) ("=" : repeat "|") (map ctorDoc ctors)))
252+
253+
254+aliasToDoc :: L.Localizer -> Name.Name -> Docs.Alias -> D.Doc
255+aliasToDoc localizer name (Docs.Alias _ tvars tipe) =
256+ let
257+ declaration =
258+ "type" <+> "alias" <+> D.hsep (map D.fromName (name:tvars)) <+> "="
259+ in
260+ D.hang 4 (D.sep [ declaration, typeDoc localizer tipe ])
261+
262+
263+valueToDoc :: L.Localizer -> Name.Name -> Docs.Value -> D.Doc
264+valueToDoc localizer name (Docs.Value _ tipe) =
265+ D.hang 4 $ D.sep [ D.fromName name <+> ":", typeDoc localizer tipe ]
266+
267+
268+binopToDoc :: L.Localizer -> Name.Name -> Docs.Binop -> D.Doc
269+binopToDoc localizer name (Docs.Binop _ tipe associativity (Docs.Precedence n)) =
270+ "(" <> D.fromName name <> ")" <+> ":" <+> typeDoc localizer tipe <> D.black details
271+ where
272+ details =
273+ " (" <> D.fromName assoc <> "/" <> D.fromInt n <> ")"
274+
275+ assoc =
276+ case associativity of
277+ Docs.Left -> "left"
278+ Docs.Non -> "non"
279+ Docs.Right -> "right"
280+
281+
282+typeDoc :: L.Localizer -> Type.Type -> D.Doc
283+typeDoc localizer tipe =
284+ Type.toDoc localizer Type.None tipe
builder/src/Elm/Outline.hs+117−146
@@ -1,11 +1,10 @@
11{-# OPTIONS_GHC -Wall #-}
2−{-# LANGUAGE MultiWayIf, OverloadedStrings #-}
2+{-# LANGUAGE OverloadedStrings #-}
33module Elm.Outline
44 ( Outline(..)
55 , AppOutline(..)
66 , PkgOutline(..)
77 , Exposed(..)
8− , SrcDir(..)
98 , read
109 , write
1110 , encode
@@ -19,12 +18,11 @@ module Elm.Outline
1918import Prelude hiding (read)
2019import Control.Monad (filterM, liftM)
2120import Data.Binary (Binary, get, put, getWord8, putWord8)
21+import Data.Foldable (traverse_)
2222import qualified Data.Map as Map
2323import qualified Data.NonEmptyList as NE
24−import qualified Data.OneOrMore as OneOrMore
25−import Foreign.Ptr (minusPtr)
24+import qualified Data.Utf8 as Utf8
2625import qualified System.Directory as Dir
27−import qualified System.FilePath as FP
2826import System.FilePath ((</>))
2927
3028import qualified Elm.Constraint as Con
@@ -35,9 +33,6 @@ import qualified Elm.Version as V
3533import qualified File
3634import qualified Json.Decode as D
3735import qualified Json.Encode as E
38−import Json.Encode ((==>))
39−import qualified Json.String as Json
40−import qualified Parse.Primitives as P
4136import qualified Reporting.Exit as Exit
4237
4338
@@ -53,7 +48,7 @@ data Outline
5348data AppOutline =
5449 AppOutline
5550 { _app_elm_version :: V.Version
56− , _app_source_dirs :: NE.List SrcDir
51+ , _app_source_dirs :: NE.List FilePath
5752 , _app_deps_direct :: Map.Map Pkg.Name V.Version
5853 , _app_deps_indirect :: Map.Map Pkg.Name V.Version
5954 , _app_test_direct :: Map.Map Pkg.Name V.Version
@@ -64,7 +59,7 @@ data AppOutline =
6459data PkgOutline =
6560 PkgOutline
6661 { _pkg_name :: Pkg.Name
67− , _pkg_summary :: Json.String
62+ , _pkg_summary :: Utf8.String
6863 , _pkg_license :: Licenses.License
6964 , _pkg_version :: V.Version
7065 , _pkg_exposed :: Exposed
@@ -76,21 +71,16 @@ data PkgOutline =
7671
7772data Exposed
7873 = ExposedList [ModuleName.Raw]
79− | ExposedDict [(Json.String, [ModuleName.Raw])]
80−
81−
82−data SrcDir
83− = AbsoluteSrcDir FilePath
84− | RelativeSrcDir FilePath
74+ | ExposedDict [(Utf8.String, [ModuleName.Raw])]
8575
8676
8777
8878-- DEFAULTS
8979
9080
91−defaultSummary :: Json.String
81+defaultSummary :: Utf8.String
9282defaultSummary =
93− Json.fromChars "helpful summary of your project, less than 80 characters"
83+ "helpful summary of your project, less than 80 characters"
9484
9585
9686
@@ -125,8 +115,8 @@ encode outline =
125115 case outline of
126116 App (AppOutline elm srcDirs depsDirect depsTrans testDirect testTrans) ->
127117 E.object
128− [ "type" ==> E.chars "application"
129− , "source-directories" ==> E.list encodeSrcDir (NE.toList srcDirs)
118+ [ "type" ==> E.string "application"
119+ , "source-directories" ==> E.list (E.string . Utf8.fromChars) (NE.toList srcDirs)
130120 , "elm-version" ==> V.encode elm
131121 , "dependencies" ==>
132122 E.object
@@ -142,7 +132,7 @@ encode outline =
142132
143133 Pkg (PkgOutline name summary license version exposed deps tests elm) ->
144134 E.object
145− [ "type" ==> E.string (Json.fromChars "package")
135+ [ "type" ==> E.string "package"
146136 , "name" ==> Pkg.encode name
147137 , "summary" ==> E.string summary
148138 , "license" ==> Licenses.encode license
@@ -154,6 +144,11 @@ encode outline =
154144 ]
155145
156146
147+(==>) :: a -> b -> (a, b)
148+(==>) a b =
149+ (a, b)
150+
151+
157152encodeExposed :: Exposed -> E.Value
158153encodeExposed exposed =
159154 case exposed of
@@ -171,14 +166,7 @@ encodeModule name =
171166
172167encodeDeps :: (a -> E.Value) -> Map.Map Pkg.Name a -> E.Value
173168encodeDeps encodeValue deps =
174− E.dict Pkg.toJsonString encodeValue deps
175−
176−
177−encodeSrcDir :: SrcDir -> E.Value
178−encodeSrcDir srcDir =
179− case srcDir of
180− AbsoluteSrcDir dir -> E.chars dir
181− RelativeSrcDir dir -> E.chars dir
169+ E.dict Pkg.toString encodeValue deps
182170
183171
184172
@@ -194,72 +182,19 @@ read root =
194182
195183 Right outline ->
196184 case outline of
197− Pkg (PkgOutline pkg _ _ _ _ deps _ _) ->
198− return $
199− if Map.notMember Pkg.core deps && pkg /= Pkg.core
200− then Left Exit.OutlineNoPkgCore
201− else Right outline
202−
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−
210− | otherwise ->
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)
185+ Pkg _ ->
186+ return $ Right outline
224187
188+ App (AppOutline _ srcDirs _ _ _ _) ->
189+ do badDirs <- filterM (isBadSrcDir root) (NE.toList srcDirs)
190+ case badDirs of
191+ [] -> return $ Right outline
192+ d:ds -> return $ Left (Exit.OutlineHasBadSrcDirs d ds)
225193
226−isSrcDirMissing :: FilePath -> SrcDir -> IO Bool
227−isSrcDirMissing root srcDir =
228− not <$> Dir.doesDirectoryExist (toAbsolute root srcDir)
229194
230−
231−toGiven :: SrcDir -> FilePath
232−toGiven srcDir =
233− case srcDir of
234− AbsoluteSrcDir dir -> dir
235− RelativeSrcDir dir -> dir
236−
237−
238−toAbsolute :: FilePath -> SrcDir -> FilePath
239−toAbsolute root srcDir =
240− case srcDir of
241− AbsoluteSrcDir dir -> dir
242− RelativeSrcDir dir -> root </> dir
243−
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)
195+isBadSrcDir :: FilePath -> FilePath -> IO Bool
196+isBadSrcDir root dir =
197+ not <$> Dir.doesDirectoryExist (root </> dir)
263198
264199
265200
@@ -272,14 +207,16 @@ type Decoder a =
272207
273208decoder :: Decoder Outline
274209decoder =
275− let
276− application = Json.fromChars "application"
277− package = Json.fromChars "package"
278− in
279210 do tipe <- D.field "type" D.string
280− if | tipe == application -> App <$> appDecoder
281− | tipe == package -> Pkg <$> pkgDecoder
282− | otherwise -> D.failure Exit.OP_BadType
211+ case tipe of
212+ "application" ->
213+ App <$> appDecoder
214+
215+ "package" ->
216+ Pkg <$> pkgDecoder
217+
218+ other ->
219+ D.failure (Exit.OP_BadType other)
283220
284221
285222appDecoder :: Decoder AppOutline
@@ -296,7 +233,7 @@ appDecoder =
296233pkgDecoder :: Decoder PkgOutline
297234pkgDecoder =
298235 PkgOutline
299− <$> D.field "name" nameDecoder
236+ <$> D.field "name" (D.mapError Exit.OP_BadPkgName Pkg.decoder)
300237 <*> D.field "summary" summaryDecoder
301238 <*> D.field "license" (Licenses.decoder Exit.OP_BadLicense)
302239 <*> D.field "version" versionDecoder
@@ -310,21 +247,17 @@ pkgDecoder =
310247-- JSON DECODE HELPERS
311248
312249
313−nameDecoder :: Decoder Pkg.Name
314−nameDecoder =
315− D.mapError (uncurry Exit.OP_BadPkgName) Pkg.decoder
316−
317−
318−summaryDecoder :: Decoder Json.String
250+summaryDecoder :: Decoder Utf8.String
319251summaryDecoder =
320− D.customString
321− (boundParser 80 Exit.OP_BadSummaryTooLong)
322− (\_ _ -> Exit.OP_BadSummaryTooLong)
252+ do summary <- D.string
253+ if Utf8.size summary < 80
254+ then return summary
255+ else D.failure Exit.OP_BadSummaryTooLong
323256
324257
325258versionDecoder :: Decoder V.Version
326259versionDecoder =
327− D.mapError (uncurry Exit.OP_BadVersion) V.decoder
260+ D.mapError Exit.OP_BadVersion V.decoder
328261
329262
330263constraintDecoder :: Decoder Con.Constraint
@@ -334,19 +267,27 @@ constraintDecoder =
334267
335268depsDecoder :: Decoder a -> Decoder (Map.Map Pkg.Name a)
336269depsDecoder valueDecoder =
337− D.dict (Pkg.keyDecoder Exit.OP_BadDependencyName) valueDecoder
270+ Map.fromList <$> (
271+ traverse validateKey =<< D.pairs valueDecoder
272+ )
338273
339274
340−dirsDecoder :: Decoder (NE.List SrcDir)
341−dirsDecoder =
342− fmap (toSrcDir . Json.toChars) <$> D.nonEmptyList D.string Exit.OP_NoSrcDirs
275+validateKey :: (Utf8.String, a) -> Decoder (Pkg.Name, a)
276+validateKey (key, value) =
277+ case Pkg.fromString key of
278+ Right name ->
279+ return (name, value)
343280
281+ Left _ ->
282+ D.failure (Exit.OP_BadDependencyName key)
344283
345−toSrcDir :: FilePath -> SrcDir
346−toSrcDir path =
347− if FP.isRelative path
348− then RelativeSrcDir path
349− else AbsoluteSrcDir path
284+
285+dirsDecoder :: Decoder (NE.List FilePath)
286+dirsDecoder =
287+ do dirs <- D.list D.string
288+ case map Utf8.toChars dirs of
289+ d:ds -> return (NE.List d ds)
290+ [] -> D.failure Exit.OP_NoSrcDirs
350291
351292
352293
@@ -357,51 +298,81 @@ exposedDecoder :: Decoder Exposed
357298exposedDecoder =
358299 D.oneOf
359300 [ ExposedList <$> D.list moduleDecoder
360− , ExposedDict <$> D.pairs headerKeyDecoder (D.list moduleDecoder)
301+ , do pairs <- D.pairs (D.list moduleDecoder)
302+ traverse_ (checkHeader . fst) pairs
303+ return (ExposedDict pairs)
361304 ]
362305
363306
364307moduleDecoder :: Decoder ModuleName.Raw
365308moduleDecoder =
366− D.mapError (uncurry Exit.OP_BadModuleName) ModuleName.decoder
309+ D.mapError Exit.OP_BadModuleName ModuleName.decoder
310+
367311
312+checkHeader :: Utf8.String -> Decoder ()
313+checkHeader header =
314+ if Utf8.size header < 20
315+ then return ()
316+ else D.failure (Exit.OP_BadModuleHeaderTooLong header)
368317
369−headerKeyDecoder :: D.KeyDecoder Exit.OutlineProblem Json.String
370−headerKeyDecoder =
371− D.KeyDecoder
372− (boundParser 20 Exit.OP_BadModuleHeaderTooLong)
373− (\_ _ -> Exit.OP_BadModuleHeaderTooLong)
374318
375319
320+-- BINARY
321+
376322
377−-- BOUND PARSER
323+instance Binary Outline where
324+ put outline =
325+ case outline of
326+ App a -> putWord8 0 >> put a
327+ Pkg a -> putWord8 1 >> put a
378328
329+ get =
330+ do n <- getWord8
331+ case n of
332+ 0 -> liftM App get
333+ 1 -> liftM Pkg get
334+ _ -> error "binary encoding of Outline was corrupted"
379335
380−boundParser :: Int -> x -> P.Parser x Json.String
381−boundParser bound tooLong =
382− P.Parser $ \(P.State src pos end indent row col) cok _ cerr _ ->
383− let
384− len = minusPtr end pos
385− newCol = col + fromIntegral len
386− in
387− if len < bound
388− then cok (Json.fromPtr pos end) (P.State src end end indent row newCol)
389− else cerr row newCol (\_ _ -> tooLong)
390336
337+instance Binary AppOutline where
338+ put (AppOutline a b c d e f) =
339+ put a >> put b >> put c >> put d >> put e >> put f
391340
341+ get =
342+ do a <- get
343+ b <- get
344+ c <- get
345+ d <- get
346+ e <- get
347+ f <- get
348+ return (AppOutline a b c d e f)
392349
393−-- BINARY
394350
351+instance Binary PkgOutline where
352+ put (PkgOutline a b c d e f g h) =
353+ put a >> put b >> put c >> put d >> put e >> put f >> put g >> put h
395354
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
355+ get =
356+ do a <- get
357+ b <- get
358+ c <- get
359+ d <- get
360+ e <- get
361+ f <- get
362+ g <- get
363+ h <- get
364+ return (PkgOutline a b c d e f g h)
365+
366+
367+instance Binary Exposed where
368+ put exposed =
369+ case exposed of
370+ ExposedList a -> putWord8 0 >> put a
371+ ExposedDict a -> putWord8 1 >> put a
401372
402373 get =
403374 do n <- getWord8
404375 case n of
405− 0 -> liftM AbsoluteSrcDir get
406− 1 -> liftM RelativeSrcDir get
407− _ -> fail "binary encoding of SrcDir was corrupted"
376+ 0 -> liftM ExposedList get
377+ 1 -> liftM ExposedDict get
378+ _ -> error "binary encoding of ProjectDeps was corrupted"
builder/src/Elm/Publish.hsnew file+255
@@ -0,0 +1,255 @@
1+{-# OPTIONS_GHC -Wall #-}
2+module Elm.Publish (publish) where
3+
4+
5+import Control.Monad (when)
6+import Control.Monad.Except (catchError, runExceptT)
7+import Control.Monad.Trans (liftIO, lift)
8+import qualified Data.List as List
9+import qualified Data.Utf8 as Utf8
10+import qualified System.Directory as Dir
11+import qualified System.Exit as Exit
12+import System.FilePath ((</>))
13+import qualified System.IO as IO
14+import qualified System.Process as Process
15+
16+import qualified Deps.Cache as Cache
17+import qualified Deps.Diff as Diff
18+import qualified Deps.Website as Website
19+import qualified Elm.Bump as Bump
20+import qualified Elm.Docs as Docs
21+import qualified Elm.Package as Pkg
22+import qualified Elm.Project.Json as Project
23+import qualified Elm.Project.Summary as Summary
24+import qualified Elm.Version as V
25+import qualified Reporting.Exit as Exit
26+import qualified Reporting.Exit.Publish as E
27+import qualified Reporting.Progress as Progress
28+import qualified Reporting.Task as Task
29+import qualified Stuff.Paths as Path
30+
31+
32+
33+-- PUBLISH
34+
35+
36+publish :: Summary.Summary -> Task.Task ()
37+publish summary@(Summary.Summary root project _ _ _) =
38+ case project of
39+ Project.App _ ->
40+ throw E.Application
41+
42+ Project.Pkg (Project.PkgInfo name smry _ version exposed _ _ _) ->
43+ do
44+ registry <- Cache.mandatoryUpdate
45+ let maybePublishedVersions = either (const Nothing) Just (Cache.getVersions name registry)
46+
47+ Task.report (Progress.PublishStart name version maybePublishedVersions)
48+
49+ when (noExposed exposed) $ throw E.NoExposed
50+ when (badSummary smry) $ throw E.NoSummary
51+
52+ verifyReadme root
53+ verifyLicense root
54+ docs <- Task.silently (error "TODO Project.generateDocs summary" summary)
55+ verifyVersion name version docs maybePublishedVersions
56+ commitHash <- verifyTag name version
57+ verifyNoChanges commitHash version
58+ zipHash <- verifyZip name version
59+
60+ Website.register name version commitHash zipHash
61+
62+ Task.report Progress.PublishEnd
63+
64+
65+throw :: E.Exit -> Task.Task a
66+throw exit =
67+ Task.throw (Exit.Publish exit)
68+
69+
70+
71+-- VERIFY SUMMARY
72+
73+
74+badSummary :: Utf8.String -> Bool
75+badSummary summary =
76+ Utf8.isEmpty summary || Project.defaultSummary == summary
77+
78+
79+noExposed :: Project.Exposed -> Bool
80+noExposed exposed =
81+ case exposed of
82+ Project.ExposedList modules ->
83+ null modules
84+
85+ Project.ExposedDict chunks ->
86+ all (null . snd) chunks
87+
88+
89+
90+-- VERIFY README
91+
92+
93+verifyReadme :: FilePath -> Task.Task ()
94+verifyReadme root =
95+ phase Progress.CheckReadme $
96+ do let readmePath = root </> "README.md"
97+ exists <- liftIO $ Dir.doesFileExist readmePath
98+ case exists of
99+ False ->
100+ throw E.NoReadme
101+
102+ True ->
103+ do size <- liftIO $ IO.withFile readmePath IO.ReadMode IO.hFileSize
104+ if size < 300
105+ then throw E.ShortReadme
106+ else return ()
107+
108+
109+
110+-- VERIFY LICENSE
111+
112+
113+verifyLicense :: FilePath -> Task.Task ()
114+verifyLicense root =
115+ phase Progress.CheckLicense $
116+ do let licensePath = root </> "LICENSE"
117+ exists <- liftIO $ Dir.doesFileExist licensePath
118+ if exists
119+ then return ()
120+ else throw E.NoLicense
121+
122+
123+
124+-- VERIFY GITHUB TAG
125+
126+
127+verifyTag :: Pkg.Name -> V.Version -> Task.Task String
128+verifyTag name version =
129+ phase (Progress.CheckTag version) $
130+ Website.githubCommit name version `catchError` \_ ->
131+ throw (E.MissingTag version)
132+
133+
134+
135+-- VERIFY NO LOCAL CHANGES SINCE TAG
136+
137+
138+verifyNoChanges :: String -> V.Version -> Task.Task ()
139+verifyNoChanges commitHash version =
140+ phase Progress.CheckChanges $
141+ do maybeGit <- liftIO $ Dir.findExecutable "git"
142+ case maybeGit of
143+ Nothing ->
144+ throw E.NoGit
145+
146+ Just git ->
147+ do -- https://stackoverflow.com/questions/3878624/how-do-i-programmatically-determine-if-there-are-uncommited-changes
148+ exitCode <- liftIO $
149+ Process.rawSystem git [ "diff-index", "--quiet", commitHash, "--" ]
150+
151+ case exitCode of
152+ Exit.ExitSuccess ->
153+ return ()
154+
155+ Exit.ExitFailure _ ->
156+ throw (E.LocalChanges version)
157+
158+
159+
160+-- VERIFY THAT ZIP BUILDS / COMPUTE HASH
161+
162+
163+verifyZip :: Pkg.Name -> V.Version -> Task.Task Website.Sha
164+verifyZip name version =
165+ withTempDir $ \dir ->
166+ do hash <- phase Progress.CheckDownload $
167+ Website.githubDownload name version dir
168+
169+ phase Progress.CheckBuild $
170+ do runner <- Task.getSilentRunner
171+ result <- liftIO $ Dir.withCurrentDirectory dir $ runner $
172+ Task.silently $ error "TODO Project.generateDocs =<< Project.getRoot"
173+ either Task.throw (\_ -> return ()) result
174+
175+ return hash
176+
177+
178+withTempDir :: (FilePath -> Task.Task a) -> Task.Task a
179+withTempDir callback =
180+ do liftIO $ Dir.createDirectoryIfMissing True Path.prepublishDir
181+ result <- lift $ runExceptT $ callback Path.prepublishDir
182+ liftIO $ Dir.removeDirectoryRecursive Path.prepublishDir
183+ either Task.throw return result
184+
185+
186+
187+-- PHASE REPORTING
188+
189+
190+phase :: Progress.PublishPhase -> Task.Task a -> Task.Task a
191+phase publishPhase task =
192+ do Task.report $ Progress.PublishProgress publishPhase Nothing
193+
194+ result <- task `catchError` \exit ->
195+ do Task.report $ Progress.PublishProgress publishPhase (Just Progress.Bad)
196+ Task.throw exit
197+
198+ Task.report $ Progress.PublishProgress publishPhase (Just Progress.Good)
199+
200+ return result
201+
202+
203+
204+-- VERIFY VERSION
205+
206+
207+verifyVersion :: Pkg.Name -> V.Version -> Docs.Documentation -> Maybe [V.Version] -> Task.Task ()
208+verifyVersion name version docs maybePublishedVersions =
209+ let
210+ reportBumpPhase bumpPhase =
211+ Task.report $ Progress.PublishCheckBump version bumpPhase
212+ in
213+ do reportBumpPhase Progress.StatedVersion
214+ case maybePublishedVersions of
215+ Nothing ->
216+ if version == V.one then
217+ reportBumpPhase Progress.GoodStart
218+ else
219+ throw (E.NotInitialVersion version)
220+
221+ Just publishedVersions ->
222+ if elem version publishedVersions then
223+ throw $ E.AlreadyPublished version
224+ else
225+ do (old, magnitude) <- verifyBump name version docs publishedVersions
226+ reportBumpPhase (Progress.GoodBump old magnitude)
227+
228+ `catchError` \exit ->
229+ do reportBumpPhase Progress.BadBump
230+ Task.throw exit
231+
232+
233+verifyBump :: Pkg.Name -> V.Version -> Docs.Documentation -> [V.Version] -> Task.Task (V.Version, Diff.Magnitude)
234+verifyBump name statedVersion newDocs publishedVersions =
235+ let
236+ possibleBumps =
237+ Bump.toPossibleBumps publishedVersions
238+
239+ isTheBump (_ ,new, _) =
240+ statedVersion == new
241+ in
242+ case List.find isTheBump possibleBumps of
243+ Nothing ->
244+ throw $ E.InvalidBump statedVersion (last publishedVersions)
245+
246+ Just (old, new, magnitude) ->
247+ do oldDocs <- Cache.getDocs name old
248+ let changes = Diff.diff oldDocs newDocs
249+ let realNew = Diff.bump changes old
250+ if new == realNew
251+ then
252+ return (old, magnitude)
253+ else
254+ throw $ E.BadBump old new magnitude realNew $
255+ Diff.toMagnitude changes
builder/src/File.hs+5−28
@@ -1,7 +1,6 @@
11module File
22 ( Time
33 , getTime
4− , zeroTime
54 , writeBinary
65 , readBinary
76 , writeUtf8
@@ -24,7 +23,6 @@ import qualified Data.ByteString.Builder as B
2423import qualified Data.ByteString.Lazy as LBS
2524import qualified Data.Fixed as Fixed
2625import qualified Data.List as List
27−import qualified Data.Time.Clock as Time
2826import qualified Data.Time.Clock.POSIX as Time
2927import qualified Foreign.ForeignPtr as FPtr
3028import GHC.IO.Exception (IOException, IOErrorType(InvalidArgument))
@@ -46,15 +44,11 @@ newtype Time = Time Fixed.Pico
4644getTime :: FilePath -> IO Time
4745getTime path =
4846 fmap
49− (Time . Time.nominalDiffTimeToSeconds . Time.utcTimeToPOSIXSeconds)
47+ (Time . realToFrac . Time.utcTimeToPOSIXSeconds)
48+-- TODO (Time . Time.nominalDiffTimeToSeconds . Time.utcTimeToPOSIXSeconds)
5049 (Dir.getModificationTime path)
5150
5251
53−zeroTime :: Time
54−zeroTime =
55− Time 0
56−
57−
5852instance Binary.Binary Time where
5953 put (Time time) = Binary.put time
6054 get = Time <$> Binary.get
@@ -78,21 +72,8 @@ readBinary path =
7872 then
7973 do result <- Binary.decodeFileOrFail path
8074 case result of
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
75+ Right a -> return (Just a)
76+ Left e -> return Nothing
9677 else
9778 return Nothing
9879
@@ -190,11 +171,7 @@ writeEntry destination root entry =
190171 let
191172 path = drop root (Zip.eRelativePath entry)
192173 in
193− if List.isPrefixOf "src/" path
194− || path == "LICENSE"
195− || path == "README.md"
196− || path == "elm.json"
197− then
174+ if List.isPrefixOf "src/" path then
198175 if not (null path) && last path == '/'
199176 then Dir.createDirectoryIfMissing True (destination </> path)
200177 else LBS.writeFile (destination </> path) (Zip.fromEntry entry)
builder/src/Generate.hsdeleted−211
@@ -1,211 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−module Generate
3− ( debug
4− , dev
5− , prod
6− , repl
7− )
8− where
9−
10−
11−import Prelude hiding (cycle, print)
12−import Control.Concurrent (MVar, forkIO, newEmptyMVar, newMVar, putMVar, readMVar)
13−import Control.Monad (liftM2)
14−import qualified Data.ByteString.Builder as B
15−import Data.Map ((!))
16−import qualified Data.Map as Map
17−import qualified Data.Maybe as Maybe
18−import qualified Data.Name as N
19−import qualified Data.NonEmptyList as NE
20−
21−import qualified AST.Optimized as Opt
22−import qualified Build
23−import qualified Elm.Compiler.Type.Extract as Extract
24−import qualified Elm.Details as Details
25−import qualified Elm.Interface as I
26−import qualified Elm.ModuleName as ModuleName
27−import qualified Elm.Package as Pkg
28−import qualified File
29−import qualified Generate.JavaScript as JS
30−import qualified Generate.Mode as Mode
31−import qualified Nitpick.Debug as Nitpick
32−import qualified Reporting.Exit as Exit
33−import qualified Reporting.Task as Task
34−import qualified Stuff
35−
36−
37−-- NOTE: This is used by Make, Repl, and Reactor right now. But it may be
38−-- desireable to have Repl and Reactor to keep foreign objects in memory
39−-- to make things a bit faster?
40−
41−
42−
43−-- GENERATORS
44−
45−
46−type Task a =
47− Task.Task Exit.Generate a
48−
49−
50−debug :: FilePath -> Details.Details -> Build.Artifacts -> Task B.Builder
51−debug root details (Build.Artifacts pkg ifaces roots modules) =
52− do loading <- loadObjects root details modules
53− types <- loadTypes root ifaces modules
54− objects <- finalizeObjects loading
55− let mode = Mode.Dev (Just types)
56− let graph = objectsToGlobalGraph objects
57− let mains = gatherMains pkg objects roots
58− return $ JS.generate mode graph mains
59−
60−
61−dev :: FilePath -> Details.Details -> Build.Artifacts -> Task B.Builder
62−dev root details (Build.Artifacts pkg _ roots modules) =
63− do objects <- finalizeObjects =<< loadObjects root details modules
64− let mode = Mode.Dev Nothing
65− let graph = objectsToGlobalGraph objects
66− let mains = gatherMains pkg objects roots
67− return $ JS.generate mode graph mains
68−
69−
70−prod :: FilePath -> Details.Details -> Build.Artifacts -> Task B.Builder
71−prod root details (Build.Artifacts pkg _ roots modules) =
72− do objects <- finalizeObjects =<< loadObjects root details modules
73− checkForDebugUses objects
74− let graph = objectsToGlobalGraph objects
75− let mode = Mode.Prod (Mode.shortenFieldNames graph)
76− let mains = gatherMains pkg objects roots
77− return $ JS.generate mode graph mains
78−
79−
80−repl :: FilePath -> Details.Details -> Bool -> Build.ReplArtifacts -> N.Name -> Task B.Builder
81−repl root details ansi (Build.ReplArtifacts home modules localizer annotations) name =
82− do objects <- finalizeObjects =<< loadObjects root details modules
83− let graph = objectsToGlobalGraph objects
84− return $ JS.generateForRepl ansi localizer graph home name (annotations ! name)
85−
86−
87−
88−-- CHECK FOR DEBUG
89−
90−
91−checkForDebugUses :: Objects -> Task ()
92−checkForDebugUses (Objects _ locals) =
93− case Map.keys (Map.filter Nitpick.hasDebugUses locals) of
94− [] -> return ()
95− m:ms -> Task.throw (Exit.GenerateCannotOptimizeDebugValues m ms)
96−
97−
98−
99−-- GATHER MAINS
100−
101−
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)
105−
106−
107−lookupMain :: Pkg.Name -> Map.Map ModuleName.Raw Opt.LocalGraph -> Build.Root -> Maybe (ModuleName.Canonical, Opt.Main)
108−lookupMain pkg locals root =
109− let
110− toPair name (Opt.LocalGraph maybeMain _ _) =
111− (,) (ModuleName.Canonical pkg name) <$> maybeMain
112− in
113− case root of
114− Build.Inside name -> toPair name =<< Map.lookup name locals
115− Build.Outside name _ g -> toPair name g
116−
117−
118−
119−-- LOADING OBJECTS
120−
121−
122−data LoadingObjects =
123− LoadingObjects
124− { _foreign_mvar :: MVar (Maybe Opt.GlobalGraph)
125− , _local_mvars :: Map.Map ModuleName.Raw (MVar (Maybe Opt.LocalGraph))
126− }
127−
128−
129−loadObjects :: FilePath -> Details.Details -> [Build.Module] -> Task LoadingObjects
130−loadObjects root details modules =
131− Task.io $
132− do mvar <- Details.loadObjects root details
133− mvars <- traverse (loadObject root) modules
134− return $ LoadingObjects mvar (Map.fromList mvars)
135−
136−
137−loadObject :: FilePath -> Build.Module -> IO (ModuleName.Raw, MVar (Maybe Opt.LocalGraph))
138−loadObject root modul =
139− case modul of
140− Build.Fresh name _ graph ->
141− do mvar <- newMVar (Just graph)
142− return (name, mvar)
143−
144− Build.Cached name _ _ ->
145− do mvar <- newEmptyMVar
146− _ <- forkIO $ putMVar mvar =<< File.readBinary (Stuff.elmo root name)
147− return (name, mvar)
148−
149−
150−
151−-- FINALIZE OBJECTS
152−
153−
154−data Objects =
155− Objects
156− { _foreign :: Opt.GlobalGraph
157− , _locals :: Map.Map ModuleName.Raw Opt.LocalGraph
158− }
159−
160−
161−finalizeObjects :: LoadingObjects -> Task Objects
162−finalizeObjects (LoadingObjects mvar mvars) =
163− Task.eio id $
164− do result <- readMVar mvar
165− results <- traverse readMVar mvars
166− case liftM2 Objects result (sequence results) of
167− Just loaded -> return (Right loaded)
168− Nothing -> return (Left Exit.GenerateCannotLoadArtifacts)
169−
170−
171−objectsToGlobalGraph :: Objects -> Opt.GlobalGraph
172−objectsToGlobalGraph (Objects globals locals) =
173− foldr Opt.addLocalGraph globals locals
174−
175−
176−
177−-- LOAD TYPES
178−
179−
180−loadTypes :: FilePath -> Map.Map ModuleName.Canonical I.DependencyInterface -> [Build.Module] -> Task Extract.Types
181−loadTypes root ifaces modules =
182− Task.eio id $
183− do mvars <- traverse (loadTypesHelp root) modules
184− let !foreigns = Extract.mergeMany (Map.elems (Map.mapWithKey Extract.fromDependencyInterface ifaces))
185− results <- traverse readMVar mvars
186− case sequence results of
187− Just ts -> return (Right (Extract.merge foreigns (Extract.mergeMany ts)))
188− Nothing -> return (Left Exit.GenerateCannotLoadArtifacts)
189−
190−
191−loadTypesHelp :: FilePath -> Build.Module -> IO (MVar (Maybe Extract.Types))
192−loadTypesHelp root modul =
193− case modul of
194− Build.Fresh name iface _ ->
195− newMVar (Just (Extract.fromInterface name iface))
196−
197− Build.Cached name _ ciMVar ->
198− do cachedInterface <- readMVar ciMVar
199− case cachedInterface of
200− Build.Unneeded ->
201− do mvar <- newEmptyMVar
202− _ <- forkIO $
203− do maybeIface <- File.readBinary (Stuff.elmi root name)
204− putMVar mvar (Extract.fromInterface name <$> maybeIface)
205− return mvar
206−
207− Build.Loaded iface ->
208− newMVar (Just (Extract.fromInterface name iface))
209−
210− Build.Corrupted ->
211− newMVar Nothing
builder/src/Http.hs+1−14
@@ -16,7 +16,6 @@ module Http
1616 -- upload
1717 , upload
1818 , filePart
19− , jsonPart
2019 , stringPart
2120 )
2221 where
@@ -27,7 +26,6 @@ import qualified Codec.Archive.Zip as Zip
2726import Control.Exception (SomeException, handle)
2827import qualified Data.Binary as Binary
2928import qualified Data.Binary.Get as Binary
30−import qualified Data.ByteString.Builder as B
3129import qualified Data.ByteString.Char8 as BS
3230import qualified Data.Digest.Pure.SHA as SHA
3331import qualified Data.String as String
@@ -36,10 +34,8 @@ import Network.HTTP.Client
3634import Network.HTTP.Client.TLS (tlsManagerSettings)
3735import Network.HTTP.Types.Header (Header, hAccept, hAcceptEncoding, hUserAgent)
3836import Network.HTTP.Types.Method (Method, methodGet, methodPost)
39−import qualified Network.HTTP.Client as Multi (RequestBody(RequestBodyLBS))
4037import qualified Network.HTTP.Client.MultipartFormData as Multi
4138
42−import qualified Json.Encode as Encode
4339import qualified Elm.Version as V
4440
4541
@@ -230,15 +226,6 @@ filePart name filePath =
230226 Multi.partFileSource (String.fromString name) filePath
231227
232228
233−jsonPart :: String -> FilePath -> Encode.Value -> Multi.Part
234−jsonPart name filePath value =
235− let
236− body =
237− Multi.RequestBodyLBS $ B.toLazyByteString $ Encode.encodeUgly value
238− in
239− Multi.partFileRequestBody (String.fromString name) filePath body
240−
241−
242229stringPart :: String -> String -> Multi.Part
243230stringPart name string =
244− Multi.partBS (String.fromString name) (BS.pack string)
231+ Multi.partBS (String.fromString name) (BS.pack string)
builder/src/Reporting.hs+22−43
@@ -1,7 +1,6 @@
11{-# LANGUAGE BangPatterns, OverloadedStrings #-}
22module Reporting
33 ( Style
4− , silent
54 , json
65 , terminal
76 --
@@ -33,7 +32,7 @@ import qualified Data.ByteString.Builder as B
3332import qualified Data.NonEmptyList as NE
3433import qualified System.Exit as Exit
3534import qualified System.Info as Info
36−import System.IO (hFlush, hPutStr, hPutStrLn, stderr, stdout)
35+import System.IO (hFlush, hPutStr, stderr, stdout)
3736
3837import qualified Elm.ModuleName as ModuleName
3938import qualified Elm.Package as Pkg
@@ -50,16 +49,10 @@ import qualified Reporting.Exit.Help as Help
5049
5150
5251data Style
53− = Silent
54− | Json
52+ = Json
5553 | Terminal (MVar ())
5654
5755
58−silent :: Style
59−silent =
60− Silent
61−
62−
6356json :: Style
6457json =
6558 Json
@@ -78,9 +71,7 @@ attempt :: (x -> Help.Report) -> IO (Either x a) -> IO a
7871attempt toReport work =
7972 do result <- work `catch` reportExceptionsNicely
8073 case result of
81− Right a ->
82− return a
83−
74+ Right a -> return a
8475 Left x ->
8576 do Exit.toStderr (toReport x)
8677 Exit.exitFailure
@@ -90,14 +81,9 @@ attemptWithStyle :: Style -> (x -> Help.Report) -> IO (Either x a) -> IO a
9081attemptWithStyle style toReport work =
9182 do result <- work `catch` reportExceptionsNicely
9283 case result of
93− Right a ->
94− return a
95−
84+ Right a -> return a
9685 Left x ->
9786 case style of
98− Silent ->
99− do Exit.exitFailure
100−
10187 Json ->
10288 do B.hPutBuilder stderr (Encode.encodeUgly (Exit.toJson (toReport x)))
10389 Exit.exitFailure
@@ -122,6 +108,11 @@ badMark =
122108 D.red $ if isWindows then "X" else "✗"
123109
124110
111+_waitingMark :: D.Doc
112+_waitingMark =
113+ D.dullyellow $ if isWindows then "-" else "→"
114+
115+
125116isWindows :: Bool
126117isWindows =
127118 Info.os == "mingw32"
@@ -177,9 +168,6 @@ type DKey = Key DMsg
177168trackDetails :: Style -> (DKey -> IO a) -> IO a
178169trackDetails style callback =
179170 case style of
180− Silent ->
181− callback (Key (\_ -> return ()))
182−
183171 Json ->
184172 callback (Key (\_ -> return ()))
185173
@@ -264,8 +252,8 @@ putDownload :: D.Doc -> Pkg.Name -> V.Version -> IO ()
264252putDownload mark pkg vsn =
265253 Help.toStdout $ D.indent 2 $
266254 mark
267− <+> D.fromPackage pkg
268− <+> D.fromVersion vsn
255+ <+> D.fromUtf8 (Pkg.toString pkg)
256+ <+> D.fromUtf8 (V.toString vsn)
269257 <> "\n"
270258
271259
@@ -309,9 +297,6 @@ type BResult a = Either Exit.BuildProblem a
309297trackBuild :: Style -> (BKey -> IO (BResult a)) -> IO (BResult a)
310298trackBuild style callback =
311299 case style of
312− Silent ->
313− callback (Key (\_ -> return ()))
314−
315300 Json ->
316301 callback (Key (\_ -> return ()))
317302
@@ -364,10 +349,10 @@ toFinalMessage done result =
364349
365350 Left problem ->
366351 case problem of
367− Exit.BuildBadModules _ _ [] ->
352+ Exit.BuildModuleProblems _ [] ->
368353 "Detected problems in 1 module."
369354
370− Exit.BuildBadModules _ _ (_:ps) ->
355+ Exit.BuildModuleProblems _ (_:ps) ->
371356 "Detected problems in " ++ show (2 + length ps) ++ " modules."
372357
373358 Exit.BuildProjectProblem _ ->
@@ -381,9 +366,6 @@ toFinalMessage done result =
381366reportGenerate :: Style -> NE.List ModuleName.Raw -> FilePath -> IO ()
382367reportGenerate style names output =
383368 case style of
384− Silent ->
385− return ()
386−
387369 Json ->
388370 return ()
389371
@@ -446,23 +428,20 @@ reportExceptionsNicely e =
446428
447429
448430putException :: SomeException -> IO ()
449−putException e = do
450− hPutStrLn stderr ""
431+putException e =
451432 Help.toStderr $ D.stack $
452− [ D.dullyellow "-- ERROR -----------------------------------------------------------------------"
453− , D.reflow $
454− "I ran into something that bypassed the normal error reporting process!\
433+ [ D.reflow $
434+ "Oh no! I ran into something that bypassed the normal error reporting process!\
455435 \ I extracted whatever information I could from the internal error:"
456436 , D.vcat $ map (\line -> D.red ">" <> " " <> D.fromChars line) (lines (show e))
457437 , D.reflow $
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 ---------------------------------------------------------------------"
438+ "These errors are usually pretty confusing, so start by asking around on Slack\
439+ \ or Discourse to see if anyone can get you unstuck quickly."
440+ , "------------------------------------------------------------"
462441 , D.reflow $
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."
442+ "From there, if you are feeling up to it, please try to get your code down to the\
443+ \ smallest version that still triggers this message. Ideally in a single Main.elm\
444+ \ and elm.json file."
466445 , D.reflow $
467446 "From there open a NEW issue at https://github.com/elm/compiler/issues with\
468447 \ your reduced example pasted in directly. (Not a link to a repo or gist!) Do not\
builder/src/Reporting/Exit.hs+375−1616
@@ -1,27 +1,31 @@
11{-# LANGUAGE OverloadedStrings #-}
22module Reporting.Exit
3− ( Init(..), initToReport
4− , Diff(..), diffToReport
5− , Make(..), makeToReport
6− , Bump(..), bumpToReport
7− , Repl(..), replToReport
8− , Publish(..), publishToReport
9− , Install(..), installToReport
10− , Reactor(..), reactorToReport
11− , newPackageOverview
3+ ( Exit(..)
4+ --
5+ , Init(..)
6+ , initToReport
7+ --
8+ , Diff(..)
9+ , diffToReport
10+ --
11+ , Install(..)
12+ , installToReport
1213 --
1314 , Solver(..)
15+ --
1416 , Outline(..)
1517 , OutlineProblem(..)
18+ --
1619 , Details(..)
17− , DetailsBadDep(..)
18− , PackageProblem(..)
1920 , RegistryProblem(..)
21+ , PackageProblem(..)
22+ --
23+ , Make(..)
2024 , BuildProblem(..)
2125 , BuildProjectProblem(..)
22− , DocsProblem(..)
23− , Generate(..)
26+ , makeToReport
2427 --
28+ , DocsProblem(..)
2529 , toString
2630 , toStderr
2731 , toJson
@@ -29,56 +33,61 @@ module Reporting.Exit
2933 where
3034
3135
32−import qualified Data.ByteString as BS
33−import qualified Data.ByteString.UTF8 as BS_UTF8
3436import qualified Data.List as List
35−import qualified Data.Map as Map
36−import qualified Data.Name as N
3737import qualified Data.NonEmptyList as NE
38−import qualified Network.HTTP.Client as HTTP
39−import qualified Network.HTTP.Types.Header as HTTP
40−import qualified Network.HTTP.Types.Status as HTTP
41−import qualified System.FilePath as FP
42−import System.FilePath ((</>), (<.>))
38+import qualified Data.Utf8 as Utf8
4339
4440import qualified Elm.Constraint as C
4541import qualified Elm.Magnitude as M
4642import qualified Elm.ModuleName as ModuleName
4743import qualified Elm.Package as Pkg
4844import qualified Elm.Version as V
49−import qualified File
5045import qualified Http
51−import qualified Json.Decode as Decode
5246import qualified Json.Encode as Encode
53−import qualified Json.String as Json
54−import Parse.Primitives (Row, Col)
55−import qualified Reporting.Annotation as A
5647import Reporting.Doc ((<>))
5748import qualified Reporting.Doc as D
5849import qualified Reporting.Error.Import as Import
5950import qualified Reporting.Error.Json as Json
6051import qualified Reporting.Exit.Help as Help
6152import qualified Reporting.Error as Error
62−import qualified Reporting.Render.Code as Code
63−
64−
6553
66−-- RENDERERS
6754
6855
69−toString :: Help.Report -> String
70−toString report =
71− Help.toString (Help.reportToDoc report)
56+-- ALL POSSIBLE ERRORS
7257
7358
74−toStderr :: Help.Report -> IO ()
75−toStderr report =
76− Help.toStderr (Help.reportToDoc report)
59+data Exit
60+ -- bump
61+ = BumpApplication
62+ | BumpUnexpectedVersion V.Version [V.Version]
63+ | BumpMustHaveLatestRegistry RegistryProblem
64+ | BumpCannotFindDocs Pkg.Name V.Version DocsProblem
65+ -- publish
66+ | PublishMustHaveLatestRegistry RegistryProblem
67+ | PublishApplication
68+ | PublishNotInitialVersion V.Version
69+ | PublishAlreadyPublished V.Version
70+ | PublishInvalidBump V.Version V.Version
71+ | PublishBadBump V.Version V.Version M.Magnitude V.Version M.Magnitude
72+ | PublishNoSummary
73+ | PublishNoExposed
74+ | PublishNoReadme
75+ | PublishShortReadme
76+ | PublishNoLicense
77+ | PublishCannotGetTag Http.Error
78+ | PublishCannotGetZip Http.Error
79+ | PublishCannotDecodeZip
80+ | PublishCannotGetDocs DocsProblem
81+ | PublishCannotRegister Http.Error
82+ | PublishMissingTag V.Version
83+ | PublishNoGit
84+ | PublishLocalChanges V.Version
7785
7886
79−toJson :: Help.Report -> Encode.Value
80−toJson report =
81− Help.reportToJson report
87+data DocsProblem
88+ = DP_Http Http.Error
89+ | DP_Data
90+ | DP_Cache
8291
8392
8493
@@ -109,18 +118,13 @@ initToReport exit =
109118
110119 InitNoOfflineSolution pkgs ->
111120 Help.report "NO OFFLINE SOLUTION" Nothing
112− "I tried to create an elm.json with the following direct dependencies:"
113− [ D.indent 4 $ D.vcat $
114− map (D.dullyellow . D.fromChars . Pkg.toChars) pkgs
115− , D.reflow $
116− "I could not find compatible versions though, but that may be because I could not\
117− \ connect to https://package.elm-lang.org to get the latest list of packages. Are\
118− \ you able to connect to the internet? Please ask around one of the community\
119− \ forums at https://elm-lang.org/community for help!"
120− ]
121+ (error "TODO InitNoOfflineSolution" pkgs)
122+ (error "TODO InitNoOfflineSolution" pkgs)
123+ -- note about Russia IP addresses?
124+ -- ask if they are on a plane or train
121125
122126 InitSolverProblem solver ->
123− toSolverReport solver
127+ error "TODO InitSolverProblem" solver
124128
125129 InitAlreadyExists ->
126130 Help.report "EXISTING PROJECT" Nothing
@@ -131,9 +135,8 @@ initToReport exit =
131135 ]
132136 ]
133137
134− InitRegistryProblem problem ->
135− toRegistryProblemReport "PROBLEM LOADING PACKAGE LIST" problem $
136− "I need the list of published packages before I can start initializing projects"
138+ InitRegistryProblem _ ->
139+ error "TODO InitRegistryProblem"
137140
138141
139142
@@ -141,48 +144,22 @@ initToReport exit =
141144
142145
143146data Diff
144− = DiffNoOutline
145− | DiffBadOutline Outline
146− | DiffApplication
147− | DiffNoExposed
147+ = DiffApplication
148148 | DiffUnpublished
149149 | DiffUnknownPackage Pkg.Name [Pkg.Name]
150150 | DiffUnknownVersion Pkg.Name V.Version [V.Version]
151− | DiffDocsProblem V.Version DocsProblem
151+ | DiffCannotFindDocs DocsProblem
152152 | DiffMustHaveLatestRegistry RegistryProblem
153− | DiffBadDetails Details
154− | DiffBadBuild BuildProblem
155153
156154
157155diffToReport :: Diff -> Help.Report
158156diffToReport diff =
159157 case diff of
160− DiffNoOutline ->
161− Help.report "DIFF WHAT?" Nothing
162− "I cannot find an elm.json so I am not sure what you want me to diff.\
163− \ Normally you run `elm diff` from within a project!"
164− [ D.reflow $ "If you are just curious to see a diff, try running this command:"
165− , D.indent 4 $ D.green $ "elm diff elm/http 1.0.0 2.0.0"
166− ]
167−
168− DiffBadOutline outline ->
169− toOutlineReport outline
170−
171158 DiffApplication ->
172− Help.report "CANNOT DIFF APPLICATIONS" (Just "elm.json")
173− "Your elm.json says this project is an application, but `elm diff` only works\
174− \ with packages. That way there are previously published versions of the API to\
175− \ diff against!"
176− [ D.reflow $ "If you are just curious to see a diff, try running this command:"
177− , D.indent 4 $ D.dullyellow $ "elm diff elm/json 1.0.0 1.1.2"
178− ]
179−
180− DiffNoExposed ->
181− Help.report "NO EXPOSED MODULES" (Just "elm.json")
182− "Your elm.json has no \"exposed-modules\" which means there is no public API at\
183− \ all right now! What am I supposed to diff?"
184− [ D.reflow $
185− "Try adding some modules back to the \"exposed-modules\" field."
159+ Help.report "CANNOT DIFF APPLICATIONS" Nothing
160+ "I cannot perform diffs on applications, only packages! If you are\
161+ \ just curious to see a diff, try running this command:"
162+ [ D.indent 4 $ D.green $ "elm diff elm/html 5.1.1 6.0.0"
186163 ]
187164
188165 DiffUnpublished ->
@@ -194,16 +171,16 @@ diffToReport diff =
194171 Help.report "UNKNOWN PACKAGE" Nothing
195172 ( "I cannot find a package called:"
196173 )
197− [ D.indent 4 $ D.red $ D.fromChars $ Pkg.toChars pkg
174+ [ D.indent 4 $ D.red $ D.fromUtf8 $ Pkg.toString pkg
198175 , "Maybe you want one of these instead?"
199− , D.indent 4 $ D.dullyellow $ D.vcat $ map (D.fromChars . Pkg.toChars) suggestions
176+ , D.indent 4 $ D.dullyellow $ D.vcat $ map (D.fromUtf8 . Pkg.toString) suggestions
200177 , "But check <https://package.elm-lang.org> to see all possibilities!"
201178 ]
202179
203180 DiffUnknownVersion _pkg vsn realVersions ->
204181 Help.docReport "UNKNOWN VERSION" Nothing
205182 ( D.fillSep $
206− [ "Version", D.red (D.fromVersion vsn)
183+ [ "Version", D.red (D.fromUtf8 (V.toString vsn))
207184 , "has", "never", "been", "published,", "so", "I"
208185 , "cannot", "diff", "against", "it."
209186 ]
@@ -212,57 +189,232 @@ diffToReport diff =
212189 , D.indent 4 $ D.dullyellow $ D.vcat $
213190 let
214191 sameMajor v1 v2 = V._major v1 == V._major v2
215− mkRow vsns = D.hsep $ map D.fromVersion vsns
192+ mkRow vsns = D.hsep $ map (D.fromUtf8 . V.toString) vsns
216193 in
217194 map mkRow $ List.groupBy sameMajor (List.sort realVersions)
218195 , "Want one of those instead?"
219196 ]
220197
221− DiffDocsProblem version problem ->
222− toDocsProblemReport problem $
223− "I need the docs for " ++ V.toChars version ++ " to compute this diff"
198+ DiffCannotFindDocs problem ->
199+ error "TODO DiffCannotFindDocs" problem
224200
225201 DiffMustHaveLatestRegistry problem ->
226− toRegistryProblemReport "PROBLEM UPDATING PACKAGE LIST" problem $
227− "I need the latest list of published packages before I do this diff"
202+ error "TODO DiffMustHaveLatestRegistry" problem
228203
229− DiffBadDetails details ->
230− toDetailsReport details
231204
232− DiffBadBuild buildProblem ->
233− toBuildProblemReport buildProblem
234205
206+-- INSTALL
235207
236208
237−-- BUMP
209+data Install
210+ = InstallNoProject
211+ | InstallNoArgs FilePath
212+ | InstallNoOnlineSolution
213+ | InstallNoOfflineSolution
214+ | InstallHadSolverTrouble Solver
215+ | InstallUnknownPackageOnline [Pkg.Name]
216+ | InstallUnknownPackageOffline [Pkg.Name]
217+ | InstallHasBadDetails Details
238218
239219
240−data Bump
241− = BumpNoOutline
242− | BumpBadOutline Outline
243− | BumpApplication
244− | BumpUnexpectedVersion V.Version [V.Version]
245− | BumpMustHaveLatestRegistry RegistryProblem
246− | BumpCannotFindDocs Pkg.Name V.Version DocsProblem
247− | BumpBadDetails Details
248− | BumpNoExposed
249− | BumpBadBuild BuildProblem
220+installToReport :: Install -> Help.Report
221+installToReport exit =
222+ case exit of
223+ InstallNoProject ->
224+ Help.report "NEW PROJECT?" Nothing
225+ "Are you trying to start a new project? Try this command instead:"
226+ [ D.indent 4 $ D.green "elm init"
227+ , D.reflow "It will help you get started!"
228+ ]
250229
230+ InstallNoArgs elmHome ->
231+ Help.report "INSTALL WHAT?" Nothing
232+ "I am expecting commands like:"
233+ [ D.green $ D.indent 4 $ D.vcat $
234+ [ "elm install elm/http"
235+ , "elm install elm/json"
236+ , "elm install elm/random"
237+ ]
238+ , D.toFancyHint
239+ ["In","JavaScript","folks","run","`npm install`","to","start","projects."
240+ ,"\"Gotta","download","everything!\"","But","why","download","packages"
241+ ,"again","and","again?","Instead,","Elm","caches","packages","in"
242+ ,D.dullyellow (D.fromChars elmHome)
243+ ,"so","each","one","is","downloaded","and","built","ONCE","on","your","machine."
244+ ,"Elm","projects","check","that","cache","before","trying","the","internet."
245+ ,"This","reduces","build","times,","reduces","server","costs,","and","makes","it"
246+ ,"easier","to","work","offline.","As","a","result"
247+ ,D.dullcyan "elm install","is","only","for","adding","dependencies","to","elm.json,"
248+ ,"whereas",D.dullcyan "elm make","is","in","charge","of","gathering","dependencies"
249+ ,"and","building","everything.","So","maybe","try",D.green "elm make","instead?"
250+ ]
251+ ]
251252
252−bumpToReport :: Bump -> Help.Report
253−bumpToReport bump =
254− case bump of
255− BumpNoOutline ->
256− Help.report "BUMP WHAT?" Nothing
257− "I cannot find an elm.json so I am not sure what you want me to bump."
258− [ D.reflow $
259− "Elm packages always have an elm.json that says current the version number. If\
260− \ you run this command from a directory with an elm.json file, I will try to bump\
261− \ the version in there based on the API changes."
253+ InstallNoOnlineSolution ->
254+ Help.report "UNSOLVABLE DEPENDENCIES" (Just "elm.json") -- TODO recommend using solver in `elm reactor`
255+ "This usually happens if you try to modify dependency constraints by\
256+ \ hand. I recommend deleting any dependency you added recently (or all\
257+ \ of them if things are bad) and then adding them again with:"
258+ [ D.indent 4 $ D.green "elm install"
259+ , D.reflow $
260+ "And do not be afaid to ask for help on Slack if you get stuck!"
262261 ]
263262
264− BumpBadOutline outline ->
265− toOutlineReport outline
263+ InstallNoOfflineSolution ->
264+ error "TODO InstallNoOfflineSolution"
265+
266+ InstallHadSolverTrouble solver ->
267+ error "TODO InstallHadSolverTrouble" solver
268+
269+ InstallUnknownPackageOnline suggestions ->
270+ error "TODO InstallUnknownPackageOnline" suggestions
271+
272+ InstallUnknownPackageOffline suggestions ->
273+ error "TODO InstallUnknownPackageOffline" suggestions
274+
275+ InstallHasBadDetails _ ->
276+ error "TODO InstallHasBadDetails"
277+
278+
279+{- TODO detect if library has no 0.19.0 version. Maybe do this on website though?
280+ Help.report "OLD DEPENDENCIES" (Just "elm.json")
281+ ( "The following packages do not work with Elm " ++ V.toChars V.compiler ++ " right now:"
282+ )
283+ [ D.indent 4 $ D.vcat $ map (D.red . D.fromUtf8 . Pkg.toString) badPackages
284+ , D.reflow $
285+ "This may be because it is not upgraded yet. It may be because a\
286+ \ better solution came along, so there was no need to upgrade it.\
287+ \ Etc. Try asking around on Slack to learn more about the topic."
288+ , D.toSimpleNote
289+ "Whatever the case, please be kind to the relevant package authors! Having\
290+ \ friendly interactions with users is great motivation, and conversely, getting\
291+ \ berated by strangers on the internet sucks your soul dry. Furthermore, package\
292+ \ authors are humans with families, friends, jobs, vacations, responsibilities,\
293+ \ goals, etc. They face obstacles outside of their technical work you will never\
294+ \ know about, so please assume the best and try to be patient and supportive!"
295+ ]
296+-}
297+
298+
299+
300+-- SOLVER
301+
302+
303+data Solver
304+ = SolverBadCacheData Pkg.Name V.Version
305+ | SolverBadHttpData Pkg.Name V.Version
306+ | SolverBadHttp Http.Error
307+
308+
309+
310+-- OUTLINE
311+
312+
313+data Outline
314+ = OutlineHasBadStructure (Json.Error OutlineProblem)
315+ | OutlineHasBadSrcDirs FilePath [FilePath]
316+
317+
318+data OutlineProblem
319+ = OP_BadType Utf8.String
320+ | OP_BadPkgName Pkg.BadName
321+ | OP_BadVersion Utf8.String
322+ | OP_BadConstraint C.Error
323+ | OP_BadModuleName Utf8.String
324+ | OP_BadModuleHeaderTooLong Utf8.String
325+ | OP_BadDependencyName Utf8.String
326+ | OP_BadLicense Utf8.String [Utf8.String]
327+ | OP_BadSummaryTooLong
328+ | OP_NoSrcDirs
329+
330+
331+
332+-- DETAILS
333+
334+
335+data Details
336+ = DetailsCorrupt
337+ | DetailsNoSolution
338+ | DetailsNoOfflineSolution
339+ | DetailsSolverProblem Solver
340+ | DetailsBadElmInPkg C.Constraint
341+ | DetailsBadElmInAppOutline V.Version
342+ | DetailsHandEditedDependencies
343+ | DetailsBadOutline Outline
344+ | DetailsCannotGetRegistry RegistryProblem
345+ | DetailsCannotBuildPackage Pkg.Name V.Version PackageProblem
346+
347+
348+data RegistryProblem
349+ = RP_Http Http.Error
350+ | RP_Data
351+
352+
353+data PackageProblem
354+ = PP_BadEndpointRequest Http.Error
355+ | PP_BadEndpointContent
356+ | PP_BadArchiveRequest Http.Error
357+ | PP_BadArchiveContent
358+ | PP_BadArchiveHash String String
359+
360+
361+
362+-- MAKE
363+
364+
365+data Make
366+ = MakeNeedsOutline
367+ | MakeCannotOptimizeAndDebug
368+ | MakeBlockedByDetailsProblem Details
369+ | MakeAppNeedsFileNames
370+ | MakePkgNeedsExposing
371+ | MakeMultipleFilesIntoHtml
372+ | MakeNonMainFilesIntoJavaScript ModuleName.Raw [ModuleName.Raw]
373+ | MakeCannotOptimizeDebugValues ModuleName.Raw [ModuleName.Raw]
374+ | MakeCannotBuild BuildProblem
375+ | MakeCannotLoadArtifacts
376+
377+
378+data BuildProblem
379+ = BuildModuleProblems Error.Module [Error.Module]
380+ | BuildProjectProblem BuildProjectProblem
381+
382+
383+data BuildProjectProblem
384+ = BP_PathUnknown FilePath
385+ | BP_WithBadExtension FilePath
386+ | BP_WithAmbiguousSrcDir FilePath FilePath
387+ | BP_MainPathDuplicate FilePath FilePath
388+ | BP_MainNameDuplicate ModuleName.Raw FilePath FilePath
389+ | BP_CannotLoadDependencies
390+ | BP_Cycle ModuleName.Raw [ModuleName.Raw]
391+ | BP_MissingExposed (NE.List (ModuleName.Raw, Import.Problem))
392+
393+
394+
395+-- RENDERERS
396+
397+
398+toString :: Help.Report -> String
399+toString report =
400+ Help.toString (Help.reportToDoc report)
401+
402+
403+toStderr :: Help.Report -> IO ()
404+toStderr report =
405+ Help.toStderr (Help.reportToDoc report)
406+
407+
408+toJson :: Help.Report -> Encode.Value
409+toJson report =
410+ Help.reportToJson report
411+
412+
413+_toReport :: Exit -> Help.Report
414+_toReport exit =
415+ case exit of
416+
417+ -- bump
266418
267419 BumpApplication ->
268420 Help.report "CANNOT BUMP APPLICATIONS" (Just "elm.json")
@@ -274,7 +426,7 @@ bumpToReport bump =
274426 Help.docReport "CANNOT BUMP" (Just "elm.json")
275427 ( D.fillSep
276428 ["Your","elm.json","says","I","should","bump","relative","to","version"
277− ,D.red (D.fromVersion vsn) <> ","
429+ ,D.red (D.fromUtf8 (V.toString vsn)) <> ","
278430 ,"but","I","cannot","find","that","version","on","<https://package.elm-lang.org>."
279431 ,"That","means","there","is","no","API","for","me","to","diff","against","and"
280432 ,"figure","out","if","these","are","MAJOR,","MINOR,","or","PATCH","changes."
@@ -283,116 +435,19 @@ bumpToReport bump =
283435 [ D.fillSep $
284436 ["Try","bumping","again","after","changing","the",D.dullyellow "\"version\"","in","elm.json"]
285437 ++ if length versions == 1 then ["to:"] else ["to","one","of","these:"]
286− , D.vcat $ map (D.green . D.fromVersion) versions
438+ , D.vcat $ map (D.green . D.fromUtf8 . V.toString) versions
287439 ]
288440
289441 BumpMustHaveLatestRegistry problem ->
290− toRegistryProblemReport "PROBLEM UPDATING PACKAGE LIST" problem $
291− "I need the latest list of published packages before I can bump any versions"
292−
293− BumpCannotFindDocs _ version problem ->
294− toDocsProblemReport problem $
295− "I need the docs for " ++ V.toChars version ++ " to compute the next version number"
296−
297− BumpBadDetails details ->
298− toDetailsReport details
299−
300− BumpNoExposed ->
301− Help.docReport "NO EXPOSED MODULES" (Just "elm.json")
302− ( D.fillSep $
303− [ "To", "bump", "a", "package,", "the"
304− , D.dullyellow "\"exposed-modules\"", "field", "of", "your"
305− , "elm.json", "must", "list", "at", "least", "one", "module."
306− ]
307− )
308− [ D.reflow $
309− "Try adding some modules back to the \"exposed-modules\" field."
310− ]
311−
312− BumpBadBuild problem ->
313− toBuildProblemReport problem
314−
315−
316−
317−-- OVERVIEW OF VERSIONING
318−
319−
320−newPackageOverview :: String
321−newPackageOverview =
322− unlines
323− [ "This package has never been published before. Here's how things work:"
324− , ""
325− , " - Versions all have exactly three parts: MAJOR.MINOR.PATCH"
326− , ""
327− , " - All packages start with initial version " ++ V.toChars V.one
328− , ""
329− , " - Versions are incremented based on how the API changes:"
330− , ""
331− , " PATCH = the API is the same, no risk of breaking code"
332− , " MINOR = values have been added, existing values are unchanged"
333− , " MAJOR = existing values have been changed or removed"
334− , ""
335− , " - I will bump versions for you, automatically enforcing these rules"
336− , ""
337− ]
338−
339−
340−
341−-- PUBLISH
342−
343−
344−data Publish
345− = PublishNoOutline
346− | PublishBadOutline Outline
347− | PublishBadDetails Details
348− | PublishMustHaveLatestRegistry RegistryProblem
349− | PublishApplication
350− | PublishNotInitialVersion V.Version
351− | PublishAlreadyPublished V.Version
352− | PublishInvalidBump V.Version V.Version
353− | PublishBadBump V.Version V.Version M.Magnitude V.Version M.Magnitude
354− | PublishNoSummary
355− | PublishNoExposed
356− | PublishNoReadme
357− | PublishShortReadme
358− | PublishNoLicense
359− | PublishBuildProblem BuildProblem
360− | PublishMissingTag V.Version
361− | PublishCannotGetTag V.Version Http.Error
362− | PublishCannotGetTagData V.Version String BS.ByteString
363− | PublishCannotGetZip Http.Error
364− | PublishCannotDecodeZip String
365− | PublishCannotGetDocs V.Version V.Version DocsProblem
366− | PublishCannotRegister Http.Error
367− | PublishNoGit
368− | PublishLocalChanges V.Version
369− --
370− | PublishZipBadDetails Details
371− | PublishZipApplication
372− | PublishZipNoExposed
373− | PublishZipBuildProblem BuildProblem
374−
375−
376−publishToReport :: Publish -> Help.Report
377−publishToReport publish =
378− case publish of
379− PublishNoOutline ->
380− Help.report "PUBLISH WHAT?" Nothing
381− "I cannot find an elm.json so I am not sure what you want me to publish."
382− [ D.reflow $
383− "Elm packages always have an elm.json that states the version number,\
384− \ dependencies, exposed modules, etc."
385− ]
442+ error "TODO BumpMustHaveLatestRegistry" problem
386443
387− PublishBadOutline outline ->
388− toOutlineReport outline
444+ BumpCannotFindDocs name version problem ->
445+ error "TODO BumpCannotFindDocs" name version problem
389446
390− PublishBadDetails problem ->
391− toDetailsReport problem
447+ -- publish
392448
393449 PublishMustHaveLatestRegistry problem ->
394− toRegistryProblemReport "PROBLEM UPDATING PACKAGE LIST" problem $
395− "I need the latest list of published packages to make sure this is safe to publish"
450+ error "TODO PublishMustHaveLatestRegistry" problem
396451
397452 PublishApplication ->
398453 Help.report "UNPUBLISHABLE" Nothing "I cannot publish applications, only packages!" []
@@ -401,7 +456,7 @@ publishToReport publish =
401456 Help.docReport "INVALID VERSION" Nothing
402457 ( D.fillSep
403458 ["I","cannot","publish"
404− ,D.red (D.fromVersion vsn)
459+ ,D.red (D.fromUtf8 (V.toString vsn))
405460 ,"as","the","initial","version."
406461 ]
407462 )
@@ -415,7 +470,7 @@ publishToReport publish =
415470 Help.docReport "ALREADY PUBLISHED" Nothing
416471 ( D.vcat
417472 [ D.fillSep
418− [ "Version", D.green (D.fromVersion vsn)
473+ [ "Version", D.green (D.fromUtf8 (V.toString vsn))
419474 , "has", "already", "been", "published.", "You", "cannot"
420475 , "publish", "it", "again!"
421476 ]
@@ -432,14 +487,14 @@ publishToReport publish =
432487 Help.docReport "INVALID VERSION" (Just "elm.json")
433488 ( D.fillSep $
434489 ["Your","elm.json","says","the","next","version","should","be"
435− ,D.red (D.fromVersion statedVersion) <> ","
490+ ,D.red (D.fromUtf8 (V.toString statedVersion)) <> ","
436491 ,"but","that","is","not","valid","based","on","the","previously"
437492 ,"published","versions."
438493 ]
439494 )
440495 [ D.fillSep $
441496 ["Change","the","version","back","to"
442− ,D.green (D.fromVersion latestVersion)
497+ ,D.green (D.fromUtf8 (V.toString latestVersion))
443498 ,"which","is","the","most","recently","published","version."
444499 ,"From","there,","have","Elm","bump","the","version","by","running:"
445500 ]
@@ -454,7 +509,7 @@ publishToReport publish =
454509 (
455510 D.fillSep $
456511 ["Your","elm.json","says","the","next","version","should","be"
457− ,D.red (D.fromVersion new) <> ","
512+ ,D.red (D.fromUtf8 (V.toString new)) <> ","
458513 ,"indicating","a",D.fromChars (M.toChars magnitude)
459514 ,"change","to","the","public","API."
460515 ,"This","does","not","match","the","API","diff","given","by:"
@@ -467,7 +522,7 @@ publishToReport publish =
467522 ["This","command","says","this","is","a"
468523 ,D.fromChars (M.toChars realMagnitude)
469524 ,"change,","so","the","next","version","should","be"
470− ,D.green (D.fromVersion realNew) <> "."
525+ ,D.green (D.fromUtf8 (V.toString realNew)) <> "."
471526 ,"Double","check","everything","to","make","sure","you"
472527 ,"are","publishing","what","you","want!"
473528 ]
@@ -497,17 +552,16 @@ publishToReport publish =
497552 ]
498553 )
499554 [ D.reflow $
500− "Which modules do you want users of the package to have access to? Add their\
501− \ names to the \"exposed-modules\" list."
555+ "What is the point of a package that has no modules?!"
502556 ]
503557
504558 PublishNoReadme ->
505− toBadReadmeReport "NO README" $
559+ badReadmeReport "NO README" $
506560 "Every published package must have a helpful README.md\
507561 \ file, but I do not see one in your project."
508562
509563 PublishShortReadme ->
510− toBadReadmeReport "SHORT README" $
564+ badReadmeReport "SHORT README" $
511565 "This README.md is too short. Having more details will help\
512566 \ people assess your package quickly and fairly."
513567
@@ -524,8 +578,20 @@ publishToReport publish =
524578 \ named LICENSE. Add that file and you will be all set!"
525579 ]
526580
527− PublishBuildProblem buildProblem ->
528− toBuildProblemReport buildProblem
581+ PublishCannotGetTag httpError ->
582+ error "TODO PublishCannotGetTag" httpError
583+
584+ PublishCannotGetZip httpError ->
585+ error "TODO PublishCannotGetZip" httpError
586+
587+ PublishCannotDecodeZip ->
588+ error "TODO PublishCannotDecodeZip"
589+
590+ PublishCannotGetDocs docsProblem ->
591+ error "TODO PublishCannotGetDocs" docsProblem
592+
593+ PublishCannotRegister httpError ->
594+ error "TODO PublishCannotRegister" httpError
529595
530596 PublishMissingTag version ->
531597 let vsn = V.toChars version in
@@ -546,70 +612,6 @@ publishToReport publish =
546612 , "The -m flag is for a helpful message. Try to make it more informative!"
547613 ]
548614
549− PublishCannotGetTag version httpError ->
550− case httpError of
551− Http.BadHttp _ (HTTP.StatusCodeException response _)
552− | HTTP.statusCode (HTTP.responseStatus response) == 404 ->
553− let vsn = V.toChars version in
554− Help.report "NO TAG ON GITHUB" Nothing
555− ("You have version " ++ vsn ++ " tagged locally, but not on GitHub.")
556− [ D.reflow
557− "Run the following command to make this tag available on GitHub:"
558− , D.indent 4 $ D.dullyellow $ D.fromChars $
559− "git push origin " ++ vsn
560− , D.reflow
561− "This will make it possible to find your code online based on the version number."
562− ]
563−
564− _ ->
565− toHttpErrorReport "PROBLEM VERIFYING TAG" httpError
566− "I need to check that the version tag is registered on GitHub"
567−
568− PublishCannotGetTagData version url body ->
569− Help.report "PROBLEM VERIFYING TAG" Nothing
570− ("I need to check that version " ++ V.toChars version ++ " is tagged on GitHub, so I fetched:")
571− [ D.indent 4 $ D.dullyellow $ D.fromChars url
572− , D.reflow $
573− "I got the data back, but it was not what I was expecting. The response\
574− \ body contains " ++ show (BS.length body) ++ " bytes. Here is the "
575− ++ if BS.length body <= 76 then "whole thing:" else "beginning:"
576− , D.indent 4 $ D.dullyellow $ D.fromChars $
577− if BS.length body <= 76
578− then BS_UTF8.toString body
579− else take 73 (BS_UTF8.toString body) ++ "..."
580− , D.reflow $
581− "Does this error keep showing up? Maybe there is something weird with your\
582− \ internet connection. We have gotten reports that schools, businesses,\
583− \ airports, etc. sometimes intercept requests and add things to the body\
584− \ or change its contents entirely. Could that be the problem?"
585− ]
586−
587− PublishCannotGetZip httpError ->
588− toHttpErrorReport "PROBLEM DOWNLOADING CODE" httpError $
589− "I need to check that folks can download and build the source code when they\
590− \ install this package"
591−
592− PublishCannotDecodeZip url ->
593− Help.report "PROBLEM DOWNLOADING CODE" Nothing
594− "I need to check that folks can download and build the source code when they\
595− \ install this package, so I downloaded the code from:"
596− [ D.indent 4 $ D.dullyellow $ D.fromChars url
597− , D.reflow $
598− "I was unable to unzip the archive though. Maybe there is something weird with\
599− \ your internet connection. We have gotten reports that schools, businesses,\
600− \ airports, etc. sometimes intercept requests and add things to the body or\
601− \ change its contents entirely. Could that be the problem?"
602− ]
603−
604− PublishCannotGetDocs old new docsProblem ->
605− toDocsProblemReport docsProblem $
606− "I need the docs for " ++ V.toChars old ++ " to verify that "
607− ++ V.toChars new ++ " really does come next"
608−
609− PublishCannotRegister httpError ->
610− toHttpErrorReport "PROBLEM PUBLISHING PACKAGE" httpError $
611− "I need to send information about your package to the package website"
612−
613615 PublishNoGit ->
614616 Help.report "NO GIT" Nothing
615617 "I searched your PATH environment variable for `git` and could not\
@@ -639,21 +641,9 @@ publishToReport publish =
639641 ++ vsn ++ "` and publish your code from there."
640642 ]
641643
642− PublishZipBadDetails _ ->
643− badZipReport
644−
645− PublishZipApplication ->
646− badZipReport
647−
648− PublishZipNoExposed ->
649− badZipReport
650644
651− PublishZipBuildProblem _ ->
652− badZipReport
653−
654−
655−toBadReadmeReport :: String -> String -> Help.Report
656−toBadReadmeReport title summary =
645+badReadmeReport :: String -> String -> Help.Report
646+badReadmeReport title summary =
657647 Help.report title (Just "README.md") summary
658648 [ D.reflow $
659649 "When people look at your README, they are wondering:"
@@ -666,653 +656,32 @@ toBadReadmeReport title summary =
666656 \ most common usage scenario. Show people what they can expect if\
667657 \ they learn more!"
668658 , D.toSimpleNote $
669− "By publishing your package, you are inviting people to invest time in\
670− \ understanding your work. Spending an hour on your README to communicate your\
671− \ knowledge more clearly can save the community days or weeks of time in\
672− \ aggregate, and saving time in aggregate is the whole point of publishing\
673− \ packages! People really appreciate it, and it makes the whole ecosystem feel\
674− \ nicer!"
675− ]
676−
677−
678−badZipReport :: Help.Report
679−badZipReport =
680− Help.report "PROBLEM VERIFYING PACKAGE" Nothing
681− "Before publishing packages, I download the code from GitHub and try to build it\
682− \ from scratch. That way I can be more confident that it will work for other\
683− \ people too. But I am not able to build it!"
684− [ D.reflow $
685− "I was just able to build your local copy though. Is there some way the version\
686− \ on GitHub could be different?"
659+ "By publishing your package, you are inviting people to invest time\
660+ \ in understanding your work. Spending an hour to communicate your\
661+ \ knowledge more clearly can save the community days or weeks of time\
662+ \ in aggregate, and saving time in aggregate is the whole point of\
663+ \ publishing packages! People really appreciate it, and it makes the\
664+ \ whole ecosystem feel nicer!"
687665 ]
688666
689667
690668
691−-- DOCS
692−
693−
694−data DocsProblem
695− = DP_Http Http.Error
696− | DP_Data String BS.ByteString
697− | DP_Cache
698−
699−
700−toDocsProblemReport :: DocsProblem -> String -> Help.Report
701−toDocsProblemReport problem context =
702− case problem of
703− DP_Http httpError ->
704− toHttpErrorReport "PROBLEM LOADING DOCS" httpError context
705−
706− DP_Data url body ->
707− Help.report "PROBLEM LOADING DOCS" Nothing (context ++ ", so I fetched:")
708− [ D.indent 4 $ D.dullyellow $ D.fromChars url
709− , D.reflow $
710− "I got the data back, but it was not what I was expecting. The response\
711− \ body contains " ++ show (BS.length body) ++ " bytes. Here is the "
712− ++ if BS.length body <= 76 then "whole thing:" else "beginning:"
713− , D.indent 4 $ D.dullyellow $ D.fromChars $
714− if BS.length body <= 76
715− then BS_UTF8.toString body
716− else take 73 (BS_UTF8.toString body) ++ "..."
717− , D.reflow $
718− "Does this error keep showing up? Maybe there is something weird with your\
719− \ internet connection. We have gotten reports that schools, businesses,\
720− \ airports, etc. sometimes intercept requests and add things to the body\
721− \ or change its contents entirely. Could that be the problem?"
722− ]
723−
724− DP_Cache ->
725− Help.report "PROBLEM LOADING DOCS" Nothing (context ++ ", but the local copy seems to be corrupted.")
726− [ D.reflow $
727− "I deleted the cached version, so the next run should download a fresh copy of\
728− \ the docs. Hopefully that will get you unstuck, but it will not resolve the root\
729− \ problem if, for example, a 3rd party editor plugin is modifing cached files\
730− \ for some reason."
731− ]
732−
733−
734−
735−-- INSTALL
736−
737−
738−data Install
739− = InstallNoOutline
740− | InstallBadOutline Outline
741− | InstallBadRegistry RegistryProblem
742− | InstallNoArgs FilePath
743− | InstallNoOnlineAppSolution Pkg.Name
744− | InstallNoOfflineAppSolution Pkg.Name
745− | InstallNoOnlinePkgSolution Pkg.Name
746− | InstallNoOfflinePkgSolution Pkg.Name
747− | InstallHadSolverTrouble Solver
748− | InstallUnknownPackageOnline Pkg.Name [Pkg.Name]
749− | InstallUnknownPackageOffline Pkg.Name [Pkg.Name]
750− | InstallBadDetails Details
751−
752−
753−installToReport :: Install -> Help.Report
754−installToReport exit =
755− case exit of
756− InstallNoOutline ->
757− Help.report "NEW PROJECT?" Nothing
758− "Are you trying to start a new project? Try this command instead:"
759− [ D.indent 4 $ D.green "elm init"
760− , D.reflow "It will help you get started!"
761− ]
762−
763− InstallBadOutline outline ->
764− toOutlineReport outline
765−
766− InstallBadRegistry problem ->
767− toRegistryProblemReport "PROBLEM LOADING PACKAGE LIST" problem $
768− "I need the list of published packages to figure out how to install things"
769−
770− InstallNoArgs elmHome ->
771− Help.report "INSTALL WHAT?" Nothing
772− "I am expecting commands like:"
773− [ D.green $ D.indent 4 $ D.vcat $
774− [ "elm install elm/http"
775− , "elm install elm/json"
776− , "elm install elm/random"
777− ]
778− , D.toFancyHint
779− ["In","JavaScript","folks","run","`npm install`","to","start","projects."
780− ,"\"Gotta","download","everything!\"","But","why","download","packages"
781− ,"again","and","again?","Instead,","Elm","caches","packages","in"
782− ,D.dullyellow (D.fromChars elmHome)
783− ,"so","each","one","is","downloaded","and","built","ONCE","on","your","machine."
784− ,"Elm","projects","check","that","cache","before","trying","the","internet."
785− ,"This","reduces","build","times,","reduces","server","costs,","and","makes","it"
786− ,"easier","to","work","offline.","As","a","result"
787− ,D.dullcyan "elm install","is","only","for","adding","dependencies","to","elm.json,"
788− ,"whereas",D.dullcyan "elm make","is","in","charge","of","gathering","dependencies"
789− ,"and","building","everything.","So","maybe","try",D.green "elm make","instead?"
790− ]
791− ]
792−
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."
827− , D.reflow $
828− "Try again later when you have internet!"
829− ]
830−
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− ]
862−
863− InstallHadSolverTrouble solver ->
864− toSolverReport solver
865−
866− InstallUnknownPackageOnline pkg suggestions ->
867− Help.docReport "UNKNOWN PACKAGE" Nothing
868− (
869− D.fillSep
870− ["I","cannot","find","a","package","named",D.red (D.fromPackage pkg) <> "."]
871− )
872− [ D.reflow $
873− "I looked through https://package.elm-lang.org for packages with similar names\
874− \ and found these:"
875− , D.indent 4 $ D.dullyellow $ D.vcat $ map D.fromPackage suggestions
876− , D.reflow $ "Maybe you want one of these instead?"
877− ]
878−
879− InstallUnknownPackageOffline pkg suggestions ->
880− Help.docReport "UNKNOWN PACKAGE" Nothing
881− (
882− D.fillSep
883− ["I","cannot","find","a","package","named",D.red (D.fromPackage pkg) <> "."]
884− )
885− [ D.reflow $
886− "I could not connect to https://package.elm-lang.org though, so new packages may\
887− \ have been published since I last updated my local cache of package names."
888− , D.reflow $
889− "Looking through the locally cached names, the closest ones are:"
890− , D.indent 4 $ D.dullyellow $ D.vcat $ map D.fromPackage suggestions
891− , D.reflow $ "Maybe you want one of these instead?"
892− ]
893−
894− InstallBadDetails details ->
895− toDetailsReport details
896−
897−
898−
899−-- SOLVER
900−
901−
902−data Solver
903− = SolverBadCacheData Pkg.Name V.Version
904− | SolverBadHttpData Pkg.Name V.Version String
905− | SolverBadHttp Pkg.Name V.Version Http.Error
906−
907−
908−toSolverReport :: Solver -> Help.Report
909−toSolverReport problem =
910− case problem of
911− SolverBadCacheData pkg vsn ->
912− Help.report "PROBLEM SOLVING PACKAGE CONSTRAINTS" Nothing
913− (
914− "I need the elm.json of " ++ Pkg.toChars pkg ++ " " ++ V.toChars vsn ++ " to\
915− \ help me search for a set of compatible packages. I had it cached locally, but\
916− \ it looks like the file was corrupted!"
917− )
918− [ D.reflow $
919− "I deleted the cached version, so the next run should download a fresh copy.\
920− \ Hopefully that will get you unstuck, but it will not resolve the root\
921− \ problem if a 3rd party tool is modifing cached files for some reason."
922− ]
923−
924− SolverBadHttpData pkg vsn url ->
925− Help.report "PROBLEM SOLVING PACKAGE CONSTRAINTS" Nothing
926− (
927− "I need the elm.json of " ++ Pkg.toChars pkg ++ " " ++ V.toChars vsn ++ " to\
928− \ help me search for a set of compatible packages, but I ran into corrupted\
929− \ information from:"
930− )
931− [ D.indent 4 $ D.dullyellow $ D.fromChars url
932− , D.reflow $
933− "Is something weird with your internet connection. We have gotten reports that\
934− \ schools, businesses, airports, etc. sometimes intercept requests and add things\
935− \ to the body or change its contents entirely. Could that be the problem?"
936− ]
937−
938− SolverBadHttp pkg vsn httpError ->
939− toHttpErrorReport "PROBLEM SOLVING PACKAGE CONSTRAINTS" httpError $
940− "I need the elm.json of " ++ Pkg.toChars pkg ++ " " ++ V.toChars vsn
941− ++ " to help me search for a set of compatible packages"
942−
943−
944−
945−-- OUTLINE
946−
947−
948−data Outline
949− = OutlineHasBadStructure (Decode.Error OutlineProblem)
950− | OutlineHasMissingSrcDirs FilePath [FilePath]
951− | OutlineHasDuplicateSrcDirs FilePath FilePath FilePath
952− | OutlineNoPkgCore
953− | OutlineNoAppCore
954− | OutlineNoAppJson
955−
956−
957−data OutlineProblem
958− = OP_BadType
959− | OP_BadPkgName Row Col
960− | OP_BadVersion Row Col
961− | OP_BadConstraint C.Error
962− | OP_BadModuleName Row Col
963− | OP_BadModuleHeaderTooLong
964− | OP_BadDependencyName Row Col
965− | OP_BadLicense Json.String [Json.String]
966− | OP_BadSummaryTooLong
967− | OP_NoSrcDirs
968−
969−
970−toOutlineReport :: Outline -> Help.Report
971−toOutlineReport problem =
972− case problem of
973− OutlineHasBadStructure decodeError ->
974− Json.toReport "elm.json" (Json.FailureToReport toOutlineProblemReport) decodeError $
975− Json.ExplicitReason "I ran into a problem with your elm.json file."
976−
977− OutlineHasMissingSrcDirs dir dirs ->
978− case dirs of
979− [] ->
980− Help.report "MISSING SOURCE DIRECTORY" (Just "elm.json")
981− "I need a valid elm.json file, but the \"source-directories\" field lists the following directory:"
982− [ D.indent 4 $ D.red $ D.fromChars dir
983− , D.reflow $
984− "I cannot find it though. Is it missing? Is there a typo?"
985− ]
986−
987− _:_ ->
988− Help.report "MISSING SOURCE DIRECTORIES" (Just "elm.json")
989− "I need a valid elm.json file, but the \"source-directories\" field lists the following directories:"
990− [ D.indent 4 $ D.vcat $
991− map (D.red . D.fromChars) (dir:dirs)
992− , D.reflow $
993− "I cannot find them though. Are they missing? Are there typos?"
994− ]
995−
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−
1017− OutlineNoPkgCore ->
1018− Help.report "MISSING DEPENDENCY" (Just "elm.json")
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."
1025− ]
1026−
1027− OutlineNoAppCore ->
1028− Help.report "MISSING DEPENDENCY" (Just "elm.json")
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."
1035− ]
1036−
1037− OutlineNoAppJson ->
1038− Help.report "MISSING DEPENDENCY" (Just "elm.json")
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."
1045− ]
1046−
1047−
1048−toOutlineProblemReport :: FilePath -> Code.Source -> Json.Context -> A.Region -> OutlineProblem -> Help.Report
1049−toOutlineProblemReport path source _ region problem =
1050− let
1051− toHighlight row col =
1052− Just $ A.Region (A.Position row col) (A.Position row col)
1053−
1054− toSnippet title highlight pair =
1055− Help.jsonReport title (Just path) $
1056− Code.toSnippet source region highlight pair
1057− in
1058− case problem of
1059− OP_BadType ->
1060− toSnippet "UNEXPECTED TYPE" Nothing
1061− ( D.reflow $
1062− "I got stuck while reading your elm.json file. I cannot handle a \"type\" like this:"
1063− , D.fillSep
1064− ["Try","changing","the","\"type\"","to"
1065− ,D.green "\"application\"","or",D.green "\"package\"","instead."
1066− ]
1067− )
1068−
1069− OP_BadPkgName row col ->
1070− toSnippet "INVALID PACKAGE NAME" (toHighlight row col)
1071− ( D.reflow $
1072− "I got stuck while reading your elm.json file. I ran into trouble with the package name:"
1073− , D.stack
1074− [ D.fillSep
1075− ["Package","names","are","always","written","as"
1076− ,D.green "\"author/project\""
1077− ,"so","I","am","expecting","to","see","something","like:"
1078− ]
1079− , D.dullyellow $ D.indent 4 $ D.vcat $
1080− [ "\"mdgriffith/elm-ui\""
1081− , "\"w0rm/elm-physics\""
1082− , "\"Microsoft/elm-json-tree-view\""
1083− , "\"FordLabs/elm-star-rating\""
1084− , "\"1602/json-schema\""
1085− ]
1086− , D.reflow
1087− "The author name should match your GitHub name exactly, and the project name\
1088− \ needs to follow these rules:"
1089− , D.indent 4 $ D.vcat $
1090− [ "+--------------------------------------+-----------+-----------+"
1091− , "| RULE | BAD | GOOD |"
1092− , "+--------------------------------------+-----------+-----------+"
1093− , "| only lower case, digits, and hyphens | elm-HTTP | elm-http |"
1094− , "| no leading digits | 3D | elm-3d |"
1095− , "| no non-ASCII characters | elm-bjørn | elm-bear |"
1096− , "| no underscores | elm_ui | elm-ui |"
1097− , "| no double hyphens | elm--hash | elm-hash |"
1098− , "| no starting or ending hyphen | -elm-tar- | elm-tar |"
1099− , "+--------------------------------------+-----------+-----------+"
1100− ]
1101− , D.toSimpleNote $
1102− "These rules only apply to the project name, so you should never need\
1103− \ to change your GitHub name!"
1104− ]
1105− )
1106−
1107− OP_BadVersion row col ->
1108− toSnippet "PROBLEM WITH VERSION" (toHighlight row col)
1109− ( D.reflow $
1110− "I got stuck while reading your elm.json file. I was expecting a version number here:"
1111− , D.fillSep
1112− ["I","need","something","like",D.green "\"1.0.0\"","or",D.green "\"2.0.4\""
1113− ,"that","explicitly","states","all","three","numbers!"
1114− ]
1115− )
1116−
1117− OP_BadConstraint constraintError ->
1118− case constraintError of
1119− C.BadFormat row col ->
1120− toSnippet "PROBLEM WITH CONSTRAINT" (toHighlight row col)
1121− ( D.reflow $
1122− "I got stuck while reading your elm.json file. I do not understand this version constraint:"
1123− , D.stack
1124− [ D.fillSep
1125− ["I","need","something","like",D.green "\"1.0.0 <= v < 2.0.0\""
1126− ,"that","explicitly","lists","the","lower","and","upper","bounds."
1127− ]
1128− , D.toSimpleNote $
1129− "The spaces in there are required! Taking them out will confuse me. Adding\
1130− \ extra spaces confuses me too. I recommend starting with a valid example\
1131− \ and just changing the version numbers."
1132− ]
1133− )
1134−
1135− C.InvalidRange before after ->
1136− if before == after then
1137− toSnippet "PROBLEM WITH CONSTRAINT" Nothing
1138− ( D.reflow $
1139− "I got stuck while reading your elm.json file. I ran into an invalid version constraint:"
1140− , D.fillSep
1141− ["Elm","checks","that","all","package","APIs","follow","semantic","versioning,"
1142− ,"so","it","is","best","to","use","wide","constraints.","I","recommend"
1143− ,D.green $ "\"" <> D.fromVersion before <> " <= v < " <> D.fromVersion (V.bumpMajor after) <> "\""
1144− ,"since","it","is","guaranteed","that","breaking","API","changes","cannot"
1145− ,"happen","in","any","of","the","versions","in","that","range."
1146− ]
1147− )
1148−
1149− else
1150− toSnippet "PROBLEM WITH CONSTRAINT" Nothing
1151− ( D.reflow $
1152− "I got stuck while reading your elm.json file. I ran into an invalid version constraint:"
1153− , D.fillSep
1154− ["Maybe","you","want","something","like"
1155− ,D.green $ "\"" <> D.fromVersion before <> " <= v < " <> D.fromVersion (V.bumpMajor before) <> "\""
1156− ,"instead?","Elm","checks","that","all","package","APIs","follow","semantic"
1157− ,"versioning,","so","it","is","guaranteed","that","breaking","API","changes"
1158− ,"cannot","happen","in","any","of","the","versions","in","that","range."
1159− ]
1160− )
1161−
1162− OP_BadModuleName row col ->
1163− toSnippet "PROBLEM WITH MODULE NAME" (toHighlight row col)
1164− ( D.reflow $
1165− "I got stuck while reading your elm.json file. I was expecting a module name here:"
1166− , D.fillSep
1167− ["I","need","something","like",D.green "\"Html.Events\""
1168− ,"or",D.green "\"Browser.Navigation\""
1169− ,"where","each","segment","starts","with","a","capital"
1170− ,"letter","and","the","segments","are","separated","by","dots."
1171− ]
1172− )
1173−
1174− OP_BadModuleHeaderTooLong ->
1175− toSnippet "HEADER TOO LONG" Nothing
1176− ( D.reflow $
1177− "I got stuck while reading your elm.json file. This section header is too long:"
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."
1188− ]
1189− )
1190−
1191− OP_BadDependencyName row col ->
1192− toSnippet "PROBLEM WITH DEPENDENCY NAME" (toHighlight row col)
1193− ( D.reflow $
1194− "I got stuck while reading your elm.json file. There is something wrong with this dependency name:"
1195− , D.stack
1196− [ D.fillSep
1197− ["Package","names","always","include","the","name","of","the","author,"
1198− ,"so","I","am","expecting","to","see","dependencies","like"
1199− ,D.dullyellow "\"mdgriffith/elm-ui\"","and"
1200− ,D.dullyellow "\"Microsoft/elm-json-tree-view\"" <> "."
1201− ]
1202− , D.fillSep $
1203− ["I","generally","recommend","finding","the","package","you","want","on"
1204− ,"the","package","website,","and","installing","it","with","the"
1205− ,D.green "elm install","command!"
1206− ]
1207− ]
1208− )
1209−
1210− OP_BadLicense _ suggestions ->
1211− toSnippet "UNKNOWN LICENSE" Nothing
1212− ( D.reflow $
1213− "I got stuck while reading your elm.json file. I do not know about this type of license:"
1214− ,
1215− D.stack
1216− [ D.fillSep
1217− ["Elm","packages","generally","use"
1218− ,D.green "\"BSD-3-Clause\"","or",D.green "\"MIT\"" <> ","
1219− ,"but","I","accept","any","OSI","approved","SPDX","license."
1220− ,"Here","some","that","seem","close","to","what","you","wrote:"
1221− ]
1222− , D.indent 4 $ D.dullyellow $ D.vcat $ map (D.fromChars . Json.toChars) suggestions
1223− , D.reflow $
1224− "Check out https://spdx.org/licenses/ for the full list of options."
1225− ]
1226− )
1227−
1228− OP_BadSummaryTooLong ->
1229− toSnippet "SUMMARY TOO LONG" Nothing
1230− ( D.reflow $
1231− "I got stuck while reading your elm.json file. Your \"summary\" is too long:"
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."
1242− ]
1243− )
1244−
1245− OP_NoSrcDirs ->
1246− toSnippet "NO SOURCE DIRECTORIES" Nothing
1247− ( D.reflow $
1248− "I got stuck while reading your elm.json file. You do not have any \"source-directories\" listed here:"
1249− , D.fillSep
1250− ["I","need","something","like",D.green "[\"src\"]"
1251− ,"so","I","know","where","to","look","for","your","modules!"
1252− ]
1253− )
1254−
1255−
1256−
1257−-- DETAILS
1258−
1259−
1260−data Details
1261− = DetailsNoSolution
1262− | DetailsNoOfflineSolution
1263− | DetailsSolverProblem Solver
1264− | DetailsBadElmInPkg C.Constraint
1265− | DetailsBadElmInAppOutline V.Version
1266− | DetailsHandEditedDependencies
1267− | DetailsBadOutline Outline
1268− | DetailsCannotGetRegistry RegistryProblem
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)
669+-- DETAILS TO REPORT
1275670
1276671
1277−toDetailsReport :: Details -> Help.Report
1278−toDetailsReport details =
672+detailsToReport :: Details -> Help.Report
673+detailsToReport details =
1279674 case details of
1280− DetailsNoSolution ->
1281− Help.report "INCOMPATIBLE DEPENDENCIES" (Just "elm.json")
1282− "The dependencies in your elm.json are not compatible."
1283− [ D.fillSep
1284− ["Did","you","change","them","by","hand?","Try","to","change","it","back!"
1285− ,"It","is","much","more","reliable","to","add","dependencies","with",D.green "elm install" <> "."
1286− ]
1287− , D.reflow $
1288− "Please ask for help on the community forums if you try those paths and are still\
1289− \ having problems!"
1290− ]
1291−
1292− DetailsNoOfflineSolution ->
1293− Help.report "TROUBLE VERIFYING DEPENDENCIES" (Just "elm.json")
1294− "I could not connect to https://package.elm-lang.org to get the latest list of\
1295− \ packages, and I was unable to verify your dependencies with the information I\
1296− \ have cached locally."
1297− [ D.reflow $
1298− "Are you able to connect to the internet? These dependencies may work once you\
1299− \ get access to the registry!"
1300− , D.toFancyNote
1301− ["If","you","changed","your","dependencies","by","hand,","try","to","change","them","back!"
1302− ,"It","is","much","more","reliable","to","add","dependencies","with",D.green "elm install" <> "."
1303− ]
1304− ]
1305−
1306− DetailsSolverProblem solver ->
1307− toSolverReport solver
675+ DetailsCorrupt ->
676+ error "TODO DetailsCorrupt"
1308677
1309678 DetailsBadElmInPkg constraint ->
1310679 Help.report "ELM VERSION MISMATCH" (Just "elm.json")
1311680 "Your elm.json says this package needs a version of Elm in this range:"
1312− [ D.indent 4 $ D.dullyellow $ D.fromChars $ C.toChars constraint
681+ [ D.indent 4 $ D.dullyellow $ D.fromUtf8 $ C.toString constraint
1313682 , D.fillSep
1314683 [ "But", "you", "are", "using", "Elm"
1315− , D.red (D.fromVersion V.compiler)
684+ , D.red (D.fromUtf8 (V.toString V.compiler))
1316685 , "right", "now."
1317686 ]
1318687 ]
@@ -1322,286 +691,40 @@ toDetailsReport details =
1322691 "Your elm.json says this application needs a different version of Elm."
1323692 [ D.fillSep
1324693 [ "It", "requires"
1325− , D.green (D.fromVersion version) <> ","
694+ , D.green (D.fromUtf8 (V.toString version)) <> ","
1326695 , "but", "you", "are", "using"
1327− , D.red (D.fromVersion V.compiler)
696+ , D.red (D.fromUtf8 (V.toString V.compiler))
1328697 , "right", "now."
1329698 ]
1330699 ]
1331700
1332701 DetailsHandEditedDependencies ->
1333− Help.report "ERROR IN DEPENDENCIES" (Just "elm.json")
1334− "It looks like the dependencies elm.json in were edited by hand (or by a 3rd\
1335− \ party tool) leaving them in an invalid state."
1336− [ D.fillSep
1337− ["Try","to","change","them","back","to","what","they","were","before!"
1338− ,"It","is","much","more","reliable","to","add","dependencies","with",D.green "elm install" <> "."
1339− ]
1340− , D.reflow $
1341− "Please ask for help on the community forums if you try those paths and are still\
1342− \ having problems!"
1343− ]
702+ error "TODO DetailsHandEditedDependencies"
1344703
1345− DetailsBadOutline outline ->
1346− toOutlineReport outline
704+ DetailsBadOutline problem ->
705+ error "TODO DetailsBadOutline" problem
1347706
1348707 DetailsCannotGetRegistry problem ->
1349− toRegistryProblemReport "PROBLEM LOADING PACKAGE LIST" problem $
1350− "I need the list of published packages to verify your dependencies"
1351−
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
1398−
708+ error "TODO DetailsCannotGetRegistry" problem
1399709
710+ DetailsCannotBuildPackage name version problem ->
711+ error "TODO DetailsCannotBuildPackage" name version problem
1400712
1401−-- PACKAGE PROBLEM
1402−
1403−
1404−data PackageProblem
1405− = PP_BadEndpointRequest Http.Error
1406− | PP_BadEndpointContent String
1407− | PP_BadArchiveRequest Http.Error
1408− | PP_BadArchiveContent String
1409− | PP_BadArchiveHash String String String
1410−
1411−
1412−toPackageProblemReport :: Pkg.Name -> V.Version -> PackageProblem -> Help.Report
1413−toPackageProblemReport pkg vsn problem =
1414− let
1415− thePackage =
1416− Pkg.toChars pkg ++ " " ++ V.toChars vsn
1417− in
1418− case problem of
1419− PP_BadEndpointRequest httpError ->
1420− toHttpErrorReport "PROBLEM DOWNLOADING PACKAGE" httpError $
1421− "I need to find the latest download link for " ++ thePackage
1422−
1423− PP_BadEndpointContent url ->
1424− Help.report "PROBLEM DOWNLOADING PACKAGE" Nothing
1425− (
1426− "I need to find the latest download link for " ++ thePackage ++ ", but I ran into corrupted information from:"
1427− )
1428− [ D.indent 4 $ D.dullyellow $ D.fromChars url
1429− , D.reflow $
1430− "Is something weird with your internet connection. We have gotten reports that\
1431− \ schools, businesses, airports, etc. sometimes intercept requests and add things\
1432− \ to the body or change its contents entirely. Could that be the problem?"
1433− ]
1434−
1435− PP_BadArchiveRequest httpError ->
1436− toHttpErrorReport "PROBLEM DOWNLOADING PACKAGE" httpError $
1437− "I was trying to download the source code for " ++ thePackage
1438−
1439− PP_BadArchiveContent url ->
1440− Help.report "PROBLEM DOWNLOADING PACKAGE" Nothing
1441− (
1442− "I downloaded the source code for " ++ thePackage ++ " from:"
1443− )
1444− [ D.indent 4 $ D.dullyellow $ D.fromChars url
1445− , D.reflow $
1446− "But I was unable to unzip the data. Maybe there is something weird with\
1447− \ your internet connection. We have gotten reports that schools, businesses,\
1448− \ airports, etc. sometimes intercept requests and add things to the body or\
1449− \ change its contents entirely. Could that be the problem?"
1450− ]
1451−
1452− PP_BadArchiveHash url expectedHash actualHash ->
1453− Help.report "CORRUPT PACKAGE DATA" Nothing
1454− (
1455− "I downloaded the source code for " ++ thePackage ++ " from:"
1456− )
1457− [ D.indent 4 $ D.dullyellow $ D.fromChars url
1458− , D.reflow "But it looks like the hash of the archive has changed since publication:"
1459− , D.vcat $ map D.fromChars $
1460− [ " Expected: " ++ expectedHash
1461− , " Actual: " ++ actualHash
1462− ]
1463− , D.reflow $
1464− "This usually means that the package author moved the version\
1465− \ tag, so report it to them and see if that is the issue. Folks\
1466− \ on Elm slack can probably help as well."
1467− ]
1468−
1469−
1470−
1471−-- REGISTRY PROBLEM
1472−
1473−
1474−data RegistryProblem
1475− = RP_Http Http.Error
1476− | RP_Data String BS.ByteString
1477−
1478−
1479−toRegistryProblemReport :: String -> RegistryProblem -> String -> Help.Report
1480−toRegistryProblemReport title problem context =
1481− case problem of
1482− RP_Http err ->
1483− toHttpErrorReport title err context
1484−
1485− RP_Data url body ->
1486− Help.report title Nothing (context ++ ", so I fetched:")
1487− [ D.indent 4 $ D.dullyellow $ D.fromChars url
1488− , D.reflow $
1489− "I got the data back, but it was not what I was expecting. The response\
1490− \ body contains " ++ show (BS.length body) ++ " bytes. Here is the "
1491− ++ if BS.length body <= 76 then "whole thing:" else "beginning:"
1492− , D.indent 4 $ D.dullyellow $ D.fromChars $
1493− if BS.length body <= 76
1494− then BS_UTF8.toString body
1495− else take 73 (BS_UTF8.toString body) ++ "..."
1496− , D.reflow $
1497− "Does this error keep showing up? Maybe there is something weird with your\
1498− \ internet connection. We have gotten reports that schools, businesses,\
1499− \ airports, etc. sometimes intercept requests and add things to the body\
1500− \ or change its contents entirely. Could that be the problem?"
1501− ]
1502−
1503−
1504−toHttpErrorReport :: String -> Http.Error -> String -> Help.Report
1505−toHttpErrorReport title err context =
1506− let
1507− toHttpReport intro url details =
1508− Help.report title Nothing intro $
1509− D.indent 4 (D.dullyellow (D.fromChars url)) : details
1510− in
1511− case err of
1512− Http.BadUrl url reason ->
1513− toHttpReport (context ++ ", so I wanted to fetch:") url
1514− [ D.reflow $ "But my HTTP library is saying this is not a valid URL. It is saying:"
1515− , D.indent 4 $ D.fromChars reason
1516− , D.reflow $
1517− "This may indicate that there is some problem in the compiler, so please open an\
1518− \ issue at https://github.com/elm/compiler/issues listing your operating system, Elm\
1519− \ version, the command you ran, the terminal output, and any additional information\
1520− \ that might help others reproduce the error."
1521− ]
1522−
1523− Http.BadHttp url httpExceptionContent ->
1524− case httpExceptionContent of
1525− HTTP.StatusCodeException response body ->
1526− let
1527− (HTTP.Status code message) = HTTP.responseStatus response
1528− in
1529− toHttpReport (context ++ ", so I tried to fetch:") url
1530− [ D.fillSep $
1531− ["But","it","came","back","as",D.red (D.fromInt code)]
1532− ++ map D.fromChars (words (BS_UTF8.toString message))
1533− , D.indent 4 $ D.reflow $ BS_UTF8.toString body
1534− , D.reflow $
1535− "This may mean some online endpoint changed in an unexpected way, so if does not\
1536− \ seem like something on your side is causing this (e.g. firewall) please report\
1537− \ this to https://github.com/elm/compiler/issues with your operating system, Elm\
1538− \ version, the command you ran, the terminal output, and any additional information\
1539− \ that can help others reproduce the error!"
1540− ]
1541−
1542− HTTP.TooManyRedirects responses ->
1543− toHttpReport (context ++ ", so I tried to fetch:") url
1544− [ D.reflow $ "But I gave up after following these " ++ show (length responses) ++ " redirects:"
1545− , D.indent 4 $ D.vcat $ map toRedirectDoc responses
1546− , D.reflow $
1547− "Is it possible that your internet connection intercepts certain requests? That\
1548− \ sometimes causes problems for folks in schools, businesses, airports, hotels,\
1549− \ and certain countries. Try asking for help locally or in a community forum!"
1550− ]
1551−
1552− otherException ->
1553− toHttpReport (context ++ ", so I tried to fetch:") url
1554− [ D.reflow $ "But my HTTP library is giving me the following error message:"
1555− , D.indent 4 $ D.fromChars (show otherException)
1556− , D.reflow $
1557− "Are you somewhere with a slow internet connection? Or no internet?\
1558− \ Does the link I am trying to fetch work in your browser? Maybe the\
1559− \ site is down? Does your internet connection have a firewall that\
1560− \ blocks certain domains? It is usually something like that!"
1561− ]
1562−
1563− Http.BadMystery url someException ->
1564− toHttpReport (context ++ ", so I tried to fetch:") url
1565− [ D.reflow $ "But I ran into something weird! I was able to extract this error message:"
1566− , D.indent 4 $ D.fromChars (show someException)
1567− , D.reflow $
1568− "Is it possible that your internet connection intercepts certain requests? That\
1569− \ sometimes causes problems for folks in schools, businesses, airports, hotels,\
1570− \ and certain countries. Try asking for help locally or in a community forum!"
1571− ]
1572−
1573−
1574−toRedirectDoc :: HTTP.Response body -> D.Doc
1575−toRedirectDoc response =
1576− let
1577− (HTTP.Status code message) = HTTP.responseStatus response
1578− in
1579− case List.lookup HTTP.hLocation (HTTP.responseHeaders response) of
1580− Just loc -> D.red (D.fromInt code) <> " - " <> D.fromChars (BS_UTF8.toString loc)
1581− Nothing -> D.red (D.fromInt code) <> " - " <> D.fromChars (BS_UTF8.toString message)
713+ DetailsNoSolution ->
714+ error "TODO DetailsNoSolution"
1582715
716+ DetailsNoOfflineSolution ->
717+ error "TODO DetailsNoOfflineSolution"
1583718
719+ DetailsSolverProblem _ ->
720+ error "TODO DetailsSolverProblem"
1584721
1585−-- MAKE
1586−
1587−
1588−data Make
1589− = MakeNoOutline
1590− | MakeCannotOptimizeAndDebug
1591− | MakeBadDetails Details
1592− | MakeAppNeedsFileNames
1593− | MakePkgNeedsExposing
1594− | MakeMultipleFilesIntoHtml
1595− | MakeNoMain
1596− | MakeNonMainFilesIntoJavaScript ModuleName.Raw [ModuleName.Raw]
1597− | MakeCannotBuild BuildProblem
1598− | MakeBadGenerate Generate
1599722
1600723
1601724makeToReport :: Make -> Help.Report
1602725makeToReport make =
1603726 case make of
1604− MakeNoOutline ->
727+ MakeNeedsOutline ->
1605728 Help.report "NO elm.json FILE" Nothing
1606729 "It looks like you are starting a new Elm project. Very exciting! Try running:"
1607730 [ D.indent 4 $ D.green $ "elm init"
@@ -1622,344 +745,27 @@ makeToReport make =
1622745 \ at once though! Pick just one of those flags and it should work!"
1623746 ]
1624747
1625− MakeBadDetails detailsProblem ->
1626− toDetailsReport detailsProblem
748+ MakeBlockedByDetailsProblem detailsProblem ->
749+ detailsToReport detailsProblem
1627750
1628751 MakeAppNeedsFileNames ->
1629752 Help.report "NO INPUT" Nothing
1630− "What should I make though? I need specific files like:"
1631− [ D.vcat
1632− [ D.indent 4 $ D.green "elm make src/Main.elm"
1633− , D.indent 4 $ D.green "elm make src/This.elm src/That.elm"
1634− ]
1635− , D.reflow $
1636− "I recommend reading through https://guide.elm-lang.org for guidance on what to\
1637− \ actually put in those files!"
753+ "What should I make though? I need a specific file like this:"
754+ [ D.indent 4 $ D.green "elm make src/Main.elm"
755+ , D.reflow
756+ "However many files you give, I will create one JS file out of them."
1638757 ]
1639758
1640759 MakePkgNeedsExposing ->
1641− Help.report "NO INPUT" Nothing
1642− "What should I make though? I need specific files like:"
1643− [ D.vcat
1644− [ D.indent 4 $ D.green "elm make src/Main.elm"
1645− , D.indent 4 $ D.green "elm make src/This.elm src/That.elm"
1646− ]
1647− , D.reflow $
1648− "You can also entries to the \"exposed-modules\" list in your elm.json file, and\
1649− \ I will try to compile the relevant files."
1650− ]
760+ error "TODO MakePkgNeedsExposing"
1651761
1652762 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− ]
763+ error "TODO MakeMultipleFilesIntoHtml"
1671764
1672− MakeNoMain ->
1673− Help.report "NO MAIN" Nothing
1674− (
1675− "When producing an HTML file, I require that the given file has a `main` value.\
1676− \ That way I have something to show on screen!"
1677− )
1678− [ D.reflow $
1679− "Try adding a `main` value to your file? Or if you just want to verify that this\
1680− \ module compiles, switch to --output=/dev/null to skip the code gen phase\
1681− \ altogether."
1682− , D.toSimpleNote $
1683− "Adding a `main` value can be as brief as adding something like this:"
1684− , D.vcat
1685− [ D.fillSep [D.cyan "import","Html"]
1686− , ""
1687− , D.fillSep [D.green "main","="]
1688− , D.indent 2 $ D.fillSep [D.cyan "Html" <> ".text",D.dullyellow "\"Hello!\""]
1689− ]
1690− , D.reflow $
1691− "From there I can create an HTML file that says \"Hello!\" on screen. I recommend\
1692− \ looking through https://guide.elm-lang.org for more guidance on how to fill in\
1693− \ the `main` value."
1694− ]
1695−
1696− MakeNonMainFilesIntoJavaScript m ms ->
1697− case ms of
1698− [] ->
1699− Help.report "NO MAIN" Nothing
1700− (
1701− "When producing a JS file, I require that the given file has a `main` value. That\
1702− \ way Elm." ++ ModuleName.toChars m ++ ".init() is definitely defined in the\
1703− \ resulting file!"
1704− )
1705− [ D.reflow $
1706− "Try adding a `main` value to your file? Or if you just want to verify that this\
1707− \ module compiles, switch to --output=/dev/null to skip the code gen phase\
1708− \ altogether."
1709− , D.toSimpleNote $
1710− "Adding a `main` value can be as brief as adding something like this:"
1711− , D.vcat
1712− [ D.fillSep [D.cyan "import","Html"]
1713− , ""
1714− , D.fillSep [D.green "main","="]
1715− , D.indent 2 $ D.fillSep [D.cyan "Html" <> ".text",D.dullyellow "\"Hello!\""]
1716− ]
1717− , D.reflow $
1718− "Or use https://package.elm-lang.org/packages/elm/core/latest/Platform#worker to\
1719− \ make a `main` with no user interface."
1720− ]
1721−
1722− _:_ ->
1723− Help.report "NO MAIN" Nothing
1724− (
1725− "When producing a JS file, I require that given files all have `main` values.\
1726− \ That way functions like Elm." ++ ModuleName.toChars m ++ ".init() are\
1727− \ definitely defined in the resulting file. I am missing `main` values in:"
1728− )
1729− [ D.indent 4 $ D.red $ D.vcat $ map D.fromName (m:ms)
1730− , D.reflow $
1731− "Try adding a `main` value to them? Or if you just want to verify that these\
1732− \ modules compile, switch to --output=/dev/null to skip the code gen phase\
1733− \ altogether."
1734− , D.toSimpleNote $
1735− "Adding a `main` value can be as brief as adding something like this:"
1736− , D.vcat
1737− [ D.fillSep [D.cyan "import","Html"]
1738− , ""
1739− , D.fillSep [D.green "main","="]
1740− , D.indent 2 $ D.fillSep [D.cyan "Html" <> ".text",D.dullyellow "\"Hello!\""]
1741− ]
1742− , D.reflow $
1743− "Or use https://package.elm-lang.org/packages/elm/core/latest/Platform#worker to\
1744− \ make a `main` with no user interface."
1745− ]
1746−
1747− MakeCannotBuild buildProblem ->
1748− toBuildProblemReport buildProblem
1749−
1750− MakeBadGenerate generateProblem ->
1751− toGenerateReport generateProblem
1752−
1753−
1754−
1755−-- BUILD PROBLEM
1756−
1757−
1758−data BuildProblem
1759− = BuildBadModules FilePath Error.Module [Error.Module]
1760− | BuildProjectProblem BuildProjectProblem
1761−
1762−
1763−data BuildProjectProblem
1764− = BP_PathUnknown FilePath
1765− | BP_WithBadExtension FilePath
1766− | BP_WithAmbiguousSrcDir FilePath FilePath FilePath
1767− | BP_MainPathDuplicate FilePath FilePath
1768− | BP_RootNameDuplicate ModuleName.Raw FilePath FilePath
1769− | BP_RootNameInvalid FilePath FilePath [String]
1770− | BP_CannotLoadDependencies
1771− | BP_Cycle ModuleName.Raw [ModuleName.Raw]
1772− | BP_MissingExposed (NE.List (ModuleName.Raw, Import.Problem))
1773−
1774−
1775−toBuildProblemReport :: BuildProblem -> Help.Report
1776−toBuildProblemReport problem =
1777− case problem of
1778− BuildBadModules root e es ->
1779− Help.compilerReport root e es
1780−
1781− BuildProjectProblem projectProblem ->
1782− toProjectProblemReport projectProblem
1783−
1784−
1785−toProjectProblemReport :: BuildProjectProblem -> Help.Report
1786−toProjectProblemReport projectProblem =
1787− case projectProblem of
1788− BP_PathUnknown path ->
1789− Help.report "FILE NOT FOUND" Nothing
1790− "I cannot find this file:"
1791− [ D.indent 4 $ D.red $ D.fromChars path
1792− , D.reflow $ "Is there a typo?"
1793− , D.toSimpleNote $
1794− "If you are just getting started, try working through the examples in the\
1795− \ official guide https://guide.elm-lang.org to get an idea of the kinds of things\
1796− \ that typically go in a src/Main.elm file."
1797− ]
1798−
1799− BP_WithBadExtension path ->
1800− Help.report "UNEXPECTED FILE EXTENSION" Nothing
1801− "I can only compile Elm files (with a .elm extension) but you want me to compile:"
1802− [ D.indent 4 $ D.red $ D.fromChars path
1803− , D.reflow $ "Is there a typo? Can the file extension be changed?"
1804− ]
1805−
1806− BP_WithAmbiguousSrcDir path srcDir1 srcDir2 ->
1807− Help.report "CONFUSING FILE" Nothing
1808− "I am getting confused when I try to compile this file:"
1809− [ D.indent 4 $ D.red $ D.fromChars path
1810− , D.reflow $
1811− "I always check if files appear in any of the \"source-directories\" listed in\
1812− \ your elm.json to see if there might be some cached information about them. That\
1813− \ can help me compile faster! But in this case, it looks like this file may be in\
1814− \ either of these directories:"
1815− , D.indent 4 $ D.red $ D.vcat $ map D.fromChars [srcDir1,srcDir2]
1816− , D.reflow $
1817− "Try to make it so no source directory contains another source directory!"
1818− ]
1819−
1820− BP_MainPathDuplicate path1 path2 ->
1821− Help.report "CONFUSING FILES" Nothing
1822− "You are telling me to compile these two files:"
1823− [ D.indent 4 $ D.red $ D.vcat $ map D.fromChars [ path1, path2 ]
1824− , D.reflow $
1825− if path1 == path2 then
1826− "Why are you telling me twice? Is something weird going on with a script?\
1827− \ I figured I would let you know about it just in case something is wrong.\
1828− \ Only list it once and you should be all set!"
1829− else
1830− "But seem to be the same file though... It makes me think something tricky is\
1831− \ going on with symlinks in your project, so I figured I would let you know\
1832− \ about it just in case. Remove one of these files from your command to get\
1833− \ unstuck!"
1834− ]
1835−
1836− BP_RootNameDuplicate name outsidePath otherPath ->
1837− Help.report "MODULE NAME CLASH" Nothing
1838− "These two files are causing a module name clash:"
1839− [ D.indent 4 $ D.red $ D.vcat $ map D.fromChars [ outsidePath, otherPath ]
1840− , D.reflow $
1841− "They both say `module " ++ ModuleName.toChars name ++ " exposing (..)` up\
1842− \ at the top, but they cannot have the same name!"
1843− , D.reflow $
1844− "Try changing to a different module name in one of them!"
1845− ]
1846−
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− ]
765+ MakeNonMainFilesIntoJavaScript _ _ ->
766+ error "TODO MakeNonMainFilesIntoJavaScript"
1864767
1865− BP_CannotLoadDependencies ->
1866− corruptCacheReport
1867−
1868− BP_Cycle name names ->
1869− Help.report "IMPORT CYCLE" Nothing
1870− "Your module imports form a cycle:"
1871− [ D.cycle 4 name names
1872− , D.reflow $
1873− "Learn more about why this is disallowed and how to break cycles here:"
1874− ++ D.makeLink "import-cycles"
1875− ]
1876−
1877− BP_MissingExposed (NE.List (name, problem) _) ->
1878− case problem of
1879− Import.NotFound ->
1880− Help.report "MISSING MODULE" (Just "elm.json")
1881− "The \"exposed-modules\" of your elm.json lists the following module:"
1882− [ D.indent 4 $ D.red $ D.fromName name
1883− , D.reflow $
1884− "But I cannot find it in your src/ directory. Is there a typo? Was it renamed?"
1885− ]
1886−
1887− Import.Ambiguous _ _ pkg _ ->
1888− Help.report "AMBIGUOUS MODULE NAME" (Just "elm.json")
1889− "The \"exposed-modules\" of your elm.json lists the following module:"
1890− [ D.indent 4 $ D.red $ D.fromName name
1891− , D.reflow $
1892− "But a module from " ++ Pkg.toChars pkg ++ " already uses that name. Try\
1893− \ choosing a different name for your local file."
1894− ]
1895−
1896− Import.AmbiguousLocal path1 path2 paths ->
1897− Help.report "AMBIGUOUS MODULE NAME" (Just "elm.json")
1898− "The \"exposed-modules\" of your elm.json lists the following module:"
1899− [ D.indent 4 $ D.red $ D.fromName name
1900− , D.reflow $
1901− "But I found multiple files with that name:"
1902− , D.dullyellow $ D.indent 4 $ D.vcat $
1903− map D.fromChars (path1:path2:paths)
1904− , D.reflow $
1905− "Change the module names to be distinct!"
1906− ]
1907−
1908− Import.AmbiguousForeign _ _ _ ->
1909− Help.report "MISSING MODULE" (Just "elm.json")
1910− "The \"exposed-modules\" of your elm.json lists the following module:"
1911− [ D.indent 4 $ D.red $ D.fromName name
1912− , D.reflow $
1913− "But I cannot find it in your src/ directory. Is there a typo? Was it renamed?"
1914− , D.toSimpleNote $
1915− "It is not possible to \"re-export\" modules from other packages. You can only\
1916− \ expose modules that you define in your own code."
1917− ]
1918−
1919−
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−
1947−
1948−-- GENERATE
1949−
1950−
1951−data Generate
1952− = GenerateCannotLoadArtifacts
1953− | GenerateCannotOptimizeDebugValues ModuleName.Raw [ModuleName.Raw]
1954−
1955−
1956−toGenerateReport :: Generate -> Help.Report
1957−toGenerateReport problem =
1958− case problem of
1959− GenerateCannotLoadArtifacts ->
1960− corruptCacheReport
1961−
1962− GenerateCannotOptimizeDebugValues m ms ->
768+ MakeCannotOptimizeDebugValues m ms ->
1963769 Help.report "DEBUG REMNANTS" Nothing
1964770 "There are uses of the `Debug` module in the following modules:"
1965771 [ D.indent 4 $ D.red $ D.vcat $ map (D.fromChars . ModuleName.toChars) (m:ms)
@@ -1968,7 +774,7 @@ toGenerateReport problem =
1968774 "The issue is that --optimize strips out info needed by `Debug` functions.\
1969775 \ Here are two examples:"
1970776 , D.indent 4 $ D.reflow $
1971− "(1) It shortens record field names. This makes the generated JavaScript\
777+ "(1) It shortens record field names. This makes the generated JavaScript is\
1972778 \ smaller, but `Debug.toString` cannot know the real field names anymore."
1973779 , D.indent 4 $ D.reflow $
1974780 "(2) Values like `type Height = Height Float` are unboxed. This reduces\
@@ -1981,89 +787,42 @@ toGenerateReport problem =
1981787 \ exists!"
1982788 ]
1983789
790+ MakeCannotBuild buildProblem ->
791+ case buildProblem of
792+ BuildProjectProblem bp ->
793+ case bp of
794+ BP_PathUnknown _ ->
795+ error "TODO BP_PathUnknown"
1984796
797+ BP_WithBadExtension _ ->
798+ error "TODO BP_WithBadExtension"
1985799
1986−-- CORRUPT CACHE
1987−
1988−
1989−corruptCacheReport :: Help.Report
1990−corruptCacheReport =
1991− Help.report "CORRUPT CACHE" Nothing
1992− "It looks like some of the information cached in elm-stuff/ has been corrupted."
1993− [ D.reflow $
1994− "Try deleting your elm-stuff/ directory to get unstuck."
1995− , D.toSimpleNote $
1996− "This almost certainly means that a 3rd party tool (or editor plugin) is\
1997− \ causing problems your the elm-stuff/ directory. Try disabling 3rd party tools\
1998− \ one by one until you figure out which it is!"
1999− ]
2000−
2001−
2002−
2003−-- REACTOR
2004−
2005−
2006−data Reactor
2007− = ReactorNoOutline
2008− | ReactorBadDetails Details
2009− | ReactorBadBuild BuildProblem
2010− | ReactorBadGenerate Generate
2011−
2012−
2013−reactorToReport :: Reactor -> Help.Report
2014−reactorToReport problem =
2015− case problem of
2016− ReactorNoOutline ->
2017− Help.report "NEW PROJECT?" Nothing
2018− "Are you trying to start a new project? Try this command in the terminal:"
2019− [ D.indent 4 $ D.green "elm init"
2020− , D.reflow "It will help you get started!"
2021− ]
2022−
2023− ReactorBadDetails details ->
2024− toDetailsReport details
2025−
2026− ReactorBadBuild buildProblem ->
2027− toBuildProblemReport buildProblem
2028−
2029− ReactorBadGenerate generate ->
2030− toGenerateReport generate
2031−
2032−
2033−
2034−-- REPL
2035−
2036−
2037−data Repl
2038− = ReplBadDetails Details
2039− | ReplBadInput BS.ByteString Error.Error
2040− | ReplBadLocalDeps FilePath Error.Module [Error.Module]
2041− | ReplProjectProblem BuildProjectProblem
2042− | ReplBadGenerate Generate
2043− | ReplBadCache
2044− | ReplBlocked
2045−
800+ BP_WithAmbiguousSrcDir _ _ ->
801+ error "TODO BP_WithAmbiguousSrcDir"
2046802
2047−replToReport :: Repl -> Help.Report
2048−replToReport problem =
2049− case problem of
2050− ReplBadDetails details ->
2051− toDetailsReport details
803+ BP_MainPathDuplicate _ _ ->
804+ error "TODO BP_MainPathDuplicate"
2052805
2053− ReplBadInput source err ->
2054− Help.compilerReport "/" (Error.Module N.replModule "REPL" File.zeroTime source err) []
806+ BP_MainNameDuplicate _ _ _ ->
807+ error "TODO BP_MainNameDuplicate"
2055808
2056− ReplBadLocalDeps root e es ->
2057− Help.compilerReport root e es
809+ BP_CannotLoadDependencies ->
810+ error "TODO BP_CannotLoadDependencies"
2058811
2059− ReplProjectProblem projectProblem ->
2060− toProjectProblemReport projectProblem
812+ BP_Cycle name names ->
813+ Help.report "IMPORT CYCLE" Nothing
814+ "Your module imports form a cycle:"
815+ [ D.cycle 4 name names
816+ , D.reflow $
817+ "Learn more about why this is disallowed and how to break cycles here:"
818+ ++ D.makeLink "import-cycles"
819+ ]
2061820
2062− ReplBadGenerate generate ->
2063− toGenerateReport generate
821+ BP_MissingExposed _ ->
822+ error "TODO BP_MissingExposed"
2064823
2065− ReplBadCache ->
2066− corruptCacheReport
824+ BuildModuleProblems p ps ->
825+ Help.compilerReport p ps
2067826
2068− ReplBlocked ->
2069− corruptCacheReport
827+ MakeCannotLoadArtifacts ->
828+ error "TODO MakeCannotLoadArtifacts"
builder/src/Reporting/Exit/Assets.hsnew file+227
@@ -0,0 +1,227 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+module Reporting.Exit.Assets
3+ ( Exit(..)
4+ , ElmJsonProblem(..)
5+ , toReport
6+ , BadElmJsonContent(..)
7+ , badContentToDocs
8+ )
9+ where
10+
11+
12+import qualified Data.Text as Text
13+
14+import qualified Elm.Package as Pkg
15+import Reporting.Doc ((<>))
16+import qualified Reporting.Doc as D
17+import qualified Reporting.Exit.Help as Help
18+
19+
20+
21+-- EXITS
22+
23+
24+data Exit
25+ = BadElmJson ElmJsonProblem
26+ | CorruptElmJson Pkg.Name Pkg.Version
27+ | CorruptDocumentation Pkg.Name Pkg.Version
28+ | CorruptBinary FilePath FilePath
29+
30+
31+
32+-- ELM JSON PROBLEM
33+
34+
35+data ElmJsonProblem
36+ = BadJson D.Doc
37+ | BadSrcDir FilePath
38+ | NoPkgCore
39+ | NoAppCore
40+ | NoAppJson
41+
42+
43+
44+-- TO REPORT
45+
46+
47+toReport :: Exit -> Help.Report
48+toReport exit =
49+ case exit of
50+ CorruptElmJson pkg vsn ->
51+ corruptJsonToReport "elm.json" pkg vsn
52+
53+ CorruptDocumentation pkg vsn ->
54+ corruptJsonToReport "docs.json" pkg vsn
55+
56+ CorruptBinary elmHome path ->
57+ Help.report "CORRUPT BINARY" (Just path)
58+ ("The binary data at " ++ path ++ " is corrupt.")
59+ [ D.reflow "Elm caches build artifacts in the following directories:"
60+ , D.dullyellow $ D.indent 4 $ D.vcat $
61+ [ D.fromString elmHome
62+ , "elm-stuff/"
63+ ]
64+ , D.reflow
65+ "Maybe you recently installed a command line tool or editor plugin that messes\
66+ \ with them? They definitely should not be doing that, but you never know! So\
67+ \ maybe try deleting them? Everything will be rebuilt from scratch. This may\
68+ \ help reveal the corrupting influence."
69+ ]
70+
71+ BadElmJson problem ->
72+ elmJsonProblemToReport problem
73+
74+
75+
76+-- CORRUPT JSON
77+
78+
79+corruptJsonToReport :: FilePath -> Pkg.Name -> Pkg.Version -> Help.Report
80+corruptJsonToReport path pkg vsn =
81+ Help.report "CORRUPT JSON" Nothing
82+ ( "The " ++ path ++ " for " ++ Pkg.toString pkg
83+ ++ " " ++ Pkg.versionToString vsn ++ " got corrupted somehow."
84+ )
85+ [ D.reflow $
86+ "I removed it from my file cache, so if it was some transient\
87+ \ error it should be fixed if you try the same thing again.\
88+ \ Please report this if it seems like an Elm problem though!"
89+ ]
90+
91+
92+
93+-- BAD ELM JSON
94+
95+
96+elmJsonProblemToReport :: ElmJsonProblem -> Help.Report
97+elmJsonProblemToReport problem =
98+ case problem of
99+ BadJson doc ->
100+ Help.jsonReport "BAD JSON" (Just "elm.json") doc
101+
102+ BadSrcDir dir ->
103+ Help.report "BAD JSON" (Just "elm.json")
104+ "The \"source-directories\" in your elm.json lists the following directory:"
105+ [ D.indent 4 (D.dullyellow (D.fromString dir))
106+ , D.reflow "I cannot find that directory though! Is it missing? Is there a typo?"
107+ ]
108+
109+ NoPkgCore ->
110+ Help.report "MISSING DEPENDENCY" (Just "elm.json")
111+ "A package must have \"elm/core\" as a dependency. Try running:"
112+ [ D.indent 4 $ D.green $ "elm install elm/core"
113+ , D.reflow "I need it for the default imports that make `List` and `Maybe` available."
114+ ]
115+
116+ NoAppCore ->
117+ Help.report "MISSING DEPENDENCY" (Just "elm.json")
118+ "An application must have \"elm/core\" as a dependency. Try running:"
119+ [ D.indent 4 $ D.green $ "elm install elm/core"
120+ , D.reflow "It has some supporting code that is needed by every Elm application!"
121+ ]
122+
123+ NoAppJson ->
124+ Help.report "MISSING DEPENDENCY" (Just "elm.json")
125+ "An application must have \"elm/json\" as a dependency. Try running:"
126+ [ D.indent 4 $ D.green $ "elm install elm/json"
127+ , D.reflow "It helps me handle flags and ports."
128+ ]
129+
130+
131+
132+-- PROBLEM TO DOCS
133+
134+
135+data BadElmJsonContent
136+ = BadType Text.Text
137+ | BadPkgName String
138+ | BadVersion Text.Text
139+ | BadConstraint String
140+ | BadModuleName Text.Text
141+ | BadModuleHeaderTooLong Text.Text
142+ | BadDependencyName Text.Text
143+ | BadLicense Text.Text [Text.Text]
144+ | BadDirectoryNotString
145+ | BadSummaryTooLong
146+
147+
148+badContentToDocs :: BadElmJsonContent -> [D.Doc]
149+badContentToDocs badContent =
150+ case badContent of
151+ BadType _ ->
152+ ["The","only","valid","types","of","elm.json","are"
153+ ,D.green "\"application\"","and",D.green "\"package\"" <> "."
154+ ]
155+
156+ BadPkgName problem ->
157+ map D.fromString (words problem)
158+
159+ BadVersion txt ->
160+ ["You","provided",D.red (D.fromString (show txt))
161+ ,"which","is","not","a","valid","version.","I","need","something","like"
162+ ,D.green "\"1.0.0\"","or",D.green "\"2.0.4\"" <> "."
163+ ]
164+
165+ BadConstraint problem ->
166+ map D.fromString (words ("It is not a valid constraint. " ++ problem))
167+
168+ BadModuleName name ->
169+ ["You","provided",D.fromString (show name),"which","is","not","a","valid","module","name."
170+ ,"I","need","something","like",D.green "\"Html.Events\"","or",D.green "\"Browser.Navigation\"" <> "."
171+ ]
172+
173+ BadModuleHeaderTooLong header ->
174+ ["The",D.fromString (show header),"header","is","too","long."
175+ ,"I","need","it","to","be",D.green "under",D.green "20",D.green "characters"
176+ ,"to","ensure","that","formatting","is","nice","on","the","package","website."
177+ ]
178+
179+ BadDependencyName name ->
180+ ["The",D.fromString (show name),"entry","is","not","a","valid","package","name."
181+ ,"I","recommend","deleting","it,","finding","the","package","you","want","on"
182+ ,"the","package","website,","and","installing","it","with","the"
183+ ,D.green "`elm install`","command","instead."
184+ ]
185+
186+ BadLicense _given suggestions ->
187+ case suggestions of
188+ [] ->
189+ ["I","need","an","OSI","approved","SPDX","license,","like"
190+ ,D.green "\"BSD-3-Clause\"","or",D.green "\"MIT\".","See"
191+ ,"<https://spdx.org/licenses/>","for","a","full","list","of","options."
192+ ]
193+
194+ code:codes ->
195+ ["I","need","an","OSI","approved","SPDX","license."]
196+ ++ ["Maybe you wanted"] ++ oneOf code codes ++ ["instead?"]
197+ ++ ["See","<https://spdx.org/licenses/>","for","a","full","list","of","options."]
198+
199+ BadDirectoryNotString ->
200+ ["I","need","a",D.green "STRING","that","points","to","a","directory","of","Elm","code."
201+ ]
202+
203+ BadSummaryTooLong ->
204+ ["Your","summary","is","too","long.","I","need","it","to"
205+ ,"be",D.green "under",D.green "80",D.green "characters."
206+ ]
207+
208+
209+oneOf :: Text.Text -> [Text.Text] -> [D.Doc]
210+oneOf code codes =
211+ let
212+ toDoc spdx =
213+ D.green (D.fromString (show spdx))
214+ in
215+ case codes of
216+ [] ->
217+ [toDoc code]
218+
219+ [code2] ->
220+ [toDoc code,"or",toDoc code2]
221+
222+ _:_ ->
223+ let
224+ these = code : init codes
225+ final = last codes
226+ in
227+ map (\spdx -> toDoc spdx <> ",") these ++ ["or",toDoc final]
builder/src/Reporting/Exit/Crawl.hsnew file+345
@@ -0,0 +1,345 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+module Reporting.Exit.Crawl
3+ ( Exit(..)
4+ , Problem(..)
5+ , Origin(..)
6+ , SrcDirs(..)
7+ , toReport
8+ )
9+ where
10+
11+
12+import qualified Data.Char as Char
13+import qualified Data.Map as Map
14+import qualified Data.Time.Clock as Time
15+
16+import qualified Elm.Compiler as Compiler
17+import qualified Elm.ModuleName as ModuleName
18+import qualified Elm.Package as Pkg
19+import qualified Elm.Version as V
20+import Reporting.Doc ((<+>), (<>))
21+import qualified Reporting.Doc as D
22+import qualified Reporting.Exit.Compile as Compile
23+import qualified Reporting.Exit.Help as Help
24+
25+
26+
27+-- EXIT
28+
29+
30+data Exit
31+ = RootFileNotFound FilePath
32+ | RootModuleNameDuplicate ModuleName.Raw [FilePath]
33+ | RootNameless FilePath
34+ | DependencyProblems Problem [Problem]
35+ | BadKernelHeader FilePath
36+
37+
38+data Problem
39+ = ModuleNotFound Origin ModuleName.Raw SrcDirs
40+ | ModuleAmbiguous Origin ModuleName.Raw [FilePath] [Pkg.Canonical]
41+ | BadHeader FilePath Time.UTCTime String Compiler.Error
42+ | ModuleNameReservedForKernel Origin ModuleName.Raw
43+ | ModuleNameMissing FilePath ModuleName.Raw
44+ | ModuleNameMismatch
45+ FilePath
46+ ModuleName.Raw -- expected
47+ ModuleName.Raw -- actual
48+ | PortsInPackage FilePath ModuleName.Raw
49+ | EffectsUnexpected FilePath ModuleName.Raw
50+
51+
52+data Origin
53+ = ElmJson
54+ | File FilePath
55+ | Module FilePath ModuleName.Raw
56+
57+
58+data SrcDirs
59+ = App [FilePath]
60+ | Pkg
61+
62+
63+
64+-- TO REPORT
65+
66+
67+toReport :: Exit -> Help.Report
68+toReport exit =
69+ case exit of
70+ RootFileNotFound path ->
71+ Help.report "FILE NOT FOUND" Nothing
72+ "You want me to compile this file:"
73+ [ D.indent 4 $ D.dullyellow $ D.fromChars path
74+ , "I cannot find it though! Is there a typo?"
75+ ]
76+
77+ RootModuleNameDuplicate name paths ->
78+ Help.report "DUPLICATE NAMES" Nothing
79+ "I am trying to compile multiple modules with the same name:"
80+ [ D.indent 4 $ D.dullyellow $ D.vcat $
81+ map D.fromChars paths
82+ , D.fillSep $
83+ [ "These", "modules", if length paths == 2 then "both" else "all", "claim"
84+ , "to", "be", "named", D.dullyellow (D.fromChars (ModuleName.nameToChars name)) <> "."
85+ , "Change", "them", "to", "have", "unique", "names", "and", "you"
86+ , "should", "be", "all", "set!"
87+ ]
88+ ]
89+
90+ RootNameless path ->
91+ namelessToDoc path "Main"
92+
93+ DependencyProblems problem otherProblems ->
94+ case otherProblems of
95+ [] ->
96+ problemToReport problem
97+
98+ _ ->
99+ problemToReport problem
100+ -- error "TODO handle multiple dependency errors"
101+
102+ BadKernelHeader filePath ->
103+ Help.report "BAD KERNEL HEADER" Nothing
104+ "I ran into a bad header in this file:"
105+ [ D.indent 4 $ D.dullyellow $ D.fromChars filePath
106+ , D.reflow $
107+ "NOTE: Kernel code is only available to core Elm libraries to ensure\
108+ \ the portability and security of the Elm ecosystem. This restriction\
109+ \ also makes it possible to improve code gen (i.e. performance) without\
110+ \ disrupting the ecosystem."
111+ ]
112+
113+
114+
115+-- PROBLEM TO REPORT
116+
117+
118+problemToReport :: Problem -> Help.Report
119+problemToReport problem =
120+ case problem of
121+ ModuleNotFound origin name srcDirs ->
122+ notFoundToDoc origin name srcDirs
123+
124+ ModuleAmbiguous origin child paths pkgs ->
125+ ambiguousToDoc origin child paths pkgs
126+
127+ BadHeader path time source compilerError ->
128+ let
129+ compilerExit =
130+ Compile.Exit "???" path time source [compilerError]
131+ in
132+ Help.compilerReport compilerExit []
133+
134+ ModuleNameMissing path name ->
135+ namelessToDoc path name
136+
137+ ModuleNameMismatch path expected actual ->
138+ Help.report "MODULE NAME MISMATCH" (Just path)
139+ ( "The file at " ++ path ++ " has a typo in the module name. It says:"
140+ )
141+ [ D.indent 4 $ D.dullyellow $ "module" <+> D.red (D.fromChars (ModuleName.nameToChars actual)) <+> "exposing (..)"
142+ , "Looks like a typo or copy/paste error. Instead it needs to say:"
143+ , D.indent 4 $ D.dullyellow $ "module" <+> D.green (D.fromChars (ModuleName.nameToChars expected)) <+> "exposing (..)"
144+ , "Make the change and you should be all set!"
145+ ]
146+
147+ ModuleNameReservedForKernel origin name ->
148+ kernelNameToDoc origin name
149+
150+ PortsInPackage path name ->
151+ badTagToDoc path name "port" "port-modules" $
152+ "Packages cannot have any `port` modules."
153+
154+ EffectsUnexpected path name ->
155+ badTagToDoc path name "effect" "effect-modules" $
156+ "Creating `effect` modules is relatively experimental. There are a\
157+ \ couple in @elm repos right now, but we have decided to be very\
158+ \ cautious in expanding its usage."
159+
160+
161+badTagToDoc :: FilePath -> ModuleName.Raw -> String -> String -> String -> Help.Report
162+badTagToDoc path name tag hintName summary =
163+ Help.report
164+ ("UNEXPECTED " ++ map Char.toUpper tag ++ " MODULE")
165+ (Just path)
166+ summary
167+ [ D.fillSep $
168+ [ "Get", "rid", "of", "all", "the"
169+ , D.red (D.fromChars tag)
170+ , "stuff", "in"
171+ , D.dullyellow (D.fromChars (ModuleName.nameToChars name))
172+ , "to", "proceed."
173+ ]
174+ , D.toSimpleNote $
175+ "You can learn the reasoning behind this design choice at "
176+ ++ D.makeLink hintName
177+ ]
178+
179+
180+
181+-- NAMELESS
182+
183+
184+namelessToDoc :: FilePath -> ModuleName.Raw -> Help.Report
185+namelessToDoc path name =
186+ Help.report "UNNAMED MODULE" (Just path)
187+ ( "The `" ++ ModuleName.nameToChars name
188+ ++ "` module must start with a line like this:"
189+ )
190+ [ D.indent 4 $ D.dullyellow $ D.fromChars $
191+ "module " ++ ModuleName.nameToChars name ++ " exposing (..)"
192+ , D.reflow $
193+ "Try adding that as the first line of your file!"
194+ , D.toSimpleNote $
195+ "It is best to replace (..) with an explicit list of types and\
196+ \ functions you want to expose. If you know a value is only used\
197+ \ WITHIN this module, it is extra easy to refactor. This kind of\
198+ \ information is great, especially as your project grows!"
199+ ]
200+
201+
202+
203+-- NOT FOUND
204+
205+
206+notFoundToDoc :: Origin -> ModuleName.Raw -> SrcDirs -> Help.Report
207+notFoundToDoc origin child srcDirs =
208+ case origin of
209+ ElmJson ->
210+ Help.report "MODULE NOT FOUND" (Just "elm.json")
211+ "Your elm.json says your project has the following module:"
212+ [ D.indent 4 $ D.red $ D.fromChars $ ModuleName.nameToChars child
213+ , D.reflow $
214+ "When creating packages, all modules must live in the src/ directory."
215+ ]
216+
217+ File path ->
218+ Help.report "UNKNOWN IMPORT" (Just path)
219+ ("I cannot find a `" ++ ModuleName.nameToChars child ++ "` module to import.")
220+ (notFoundDetails child srcDirs)
221+
222+ Module path parent ->
223+ Help.report "UNKNOWN IMPORT" (Just path)
224+ ("The " ++ ModuleName.nameToChars parent ++ " module has a bad import:")
225+ (notFoundDetails child srcDirs)
226+
227+
228+notFoundDetails :: ModuleName.Raw -> SrcDirs -> [D.Doc]
229+notFoundDetails child srcDirs =
230+ let
231+ simulatedCode =
232+ D.indent 4 $ D.red $ D.fromChars $ "import " ++ ModuleName.nameToChars child
233+ in
234+ case Map.lookup child Pkg.suggestions of
235+ Just pkg ->
236+ [ simulatedCode
237+ , D.reflow $
238+ "Do you want the one from the " ++ Pkg.toChars pkg
239+ ++ " package? If so, run this command to add that dependency to your elm.json file:"
240+ , D.indent 4 $ D.green $ D.fromChars $ "elm install " ++ Pkg.toChars pkg
241+ , case srcDirs of
242+ Pkg ->
243+ D.reflow $
244+ "If you want a local file, make sure the `"
245+ ++ ModuleName.nameToChars child
246+ ++ "` module is in your src/ directory."
247+
248+ App _ ->
249+ D.reflow $
250+ "If you want a local file, make sure the `"
251+ ++ ModuleName.nameToChars child
252+ ++ "` module is in one of the \"source-directories\" listed in your elm.json file."
253+ ]
254+
255+ Nothing ->
256+ [ simulatedCode
257+ , "I cannot find that module! Is there a typo in the module name?"
258+ , D.reflow $
259+ case srcDirs of
260+ Pkg ->
261+ "When creating a package, all modules must live in the src/ directory."
262+
263+ App [] ->
264+ "The \"source-directories\" field of your elm.json is empty, so I only\
265+ \ searched in packages. Maybe you need to add a \"src\" directory there?"
266+
267+ App [dir] ->
268+ "The \"source-directories\" field of your elm.json tells me to only look in the "
269+ ++ dir ++ " directory, but it is not there. Maybe it is in a package that is not installed yet?"
270+
271+ App (dir:_:_) ->
272+ "The \"source-directories\" field of your elm.json tells me to look in directories like "
273+ ++ dir ++ ", but it is not in any of them. Maybe it is in a package that is not installed yet?"
274+ ]
275+
276+
277+ambiguousToDoc :: Origin -> ModuleName.Raw -> [FilePath] -> [Pkg.Canonical] -> Help.Report
278+ambiguousToDoc origin child paths pkgs =
279+ let
280+ pkgToString (Pkg.Canonical pkg vsn) =
281+ "exposed by " ++ Pkg.toChars pkg ++ " " ++ V.toChars vsn
282+
283+ makeReport maybePath summary yellowString =
284+ Help.report "AMBIGUOUS IMPORT" maybePath summary
285+ [ D.indent 4 $ D.dullyellow $ D.fromChars yellowString
286+ , D.reflow $
287+ "I found multiple module with that name though:"
288+ , D.indent 4 $ D.dullyellow $ D.vcat $
289+ map D.fromChars $ paths ++ map pkgToString pkgs
290+ , D.reflow $
291+ if null paths then
292+ "It looks like the name clash is in your dependencies, which is\
293+ \ out of your control. Elm does not support this scenario right\
294+ \ now, but it may be worthwhile. Please open an issue describing\
295+ \ your scenario so we can gather more usage information!"
296+ else
297+ "Which is the right one? Try renaming your modules to have unique names."
298+ ]
299+ in
300+ case origin of
301+ ElmJson ->
302+ makeReport
303+ Nothing
304+ "Your elm.json wants the following module:"
305+ (ModuleName.nameToChars child)
306+
307+ File path ->
308+ makeReport
309+ (Just path)
310+ ("The file at " ++ path ++ " has an ambiguous import:")
311+ ("import " ++ ModuleName.nameToChars child)
312+
313+ Module path parent ->
314+ makeReport
315+ (Just path)
316+ ("The " ++ ModuleName.nameToChars parent ++ " module has an ambiguous import:")
317+ ("import " ++ ModuleName.nameToChars child)
318+
319+
320+kernelNameToDoc :: Origin -> ModuleName.Raw -> Help.Report
321+kernelNameToDoc origin kernelName =
322+ let
323+ (maybePath, statement) =
324+ case origin of
325+ ElmJson ->
326+ ( Nothing
327+ , "Your elm.json says your project has the following module:"
328+ )
329+
330+ File path ->
331+ ( Just path
332+ , "This file is trying to import the following module:"
333+ )
334+
335+ Module path parent ->
336+ ( Just path
337+ , "Your " ++ ModuleName.nameToChars parent ++ " module is trying to import:"
338+ )
339+ in
340+ Help.report "BAD MODULE NAME" maybePath statement
341+ [ D.indent 4 $ D.dullyellow $ D.fromChars $ ModuleName.nameToChars kernelName
342+ , D.reflow $
343+ "But names like that are reserved for internal use.\
344+ \ Switch to a name outside of the Elm/Kernel/ namespace."
345+ ]
builder/src/Reporting/Exit/Deps.hsnew file+123
@@ -0,0 +1,123 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+module Reporting.Exit.Deps
3+ ( Exit(..)
4+ , toReport
5+ )
6+ where
7+
8+
9+import qualified Elm.Constraint as Con
10+import qualified Elm.Package as Pkg
11+import qualified Elm.Version as V
12+import Reporting.Doc ((<>))
13+import qualified Reporting.Doc as D
14+import qualified Reporting.Exit.Help as Help
15+
16+
17+
18+-- EXITS
19+
20+
21+data Exit
22+ = CorruptVersionCache FilePath Pkg.Name
23+ | PackageNotFound Pkg.Name [Pkg.Name]
24+ -- verify
25+ | PkgBadElm Con.Constraint
26+ | AppBadElm V.Version
27+ | AppMissingTrans [(Pkg.Name, V.Version)]
28+ | BadDeps
29+ | BuildFailure FilePath Pkg.Name V.Version
30+
31+
32+
33+-- TO DOC
34+
35+
36+toReport :: Exit -> Help.Report
37+toReport exit =
38+ case exit of
39+ CorruptVersionCache elmHome pkg ->
40+ Help.report "CORRUPT CACHE" Nothing
41+ ( "I ran into an unknown package while exploring dependencies:"
42+ )
43+ [ D.indent 4 $ D.dullyellow $ D.fromUtf8 $ Pkg.toString pkg
44+ , D.reflow $
45+ "This suggests that your " ++ elmHome ++ " directory has been corrupted.\
46+ \ Maybe some program is messing with it? It is just cached files,\
47+ \ so you can delete it and see if that fixes the issue."
48+ ]
49+
50+ PackageNotFound package suggestions ->
51+ Help.docReport "PACKAGE NOT FOUND" Nothing
52+ ( D.fillSep
53+ ["I","cannot","find","a"
54+ ,D.red (D.fromUtf8 (Pkg.toString package))
55+ ,"package","on","the","package","website."
56+ ]
57+ )
58+ [ "Maybe you want one of these instead?"
59+ , D.indent 4 $ D.dullyellow $ D.vcat $ map (D.fromUtf8 . Pkg.toString) suggestions
60+ , "But check <https://package.elm-lang.org> to see all possibilities!"
61+ ]
62+
63+ PkgBadElm constraint ->
64+ Help.report "ELM VERSION MISMATCH" (Just "elm.json")
65+ "Your elm.json says this package needs a version of Elm in this range:"
66+ [ D.indent 4 $ D.dullyellow $ D.fromUtf8 $ Con.toString constraint
67+ , D.fillSep
68+ [ "But", "you", "are", "using", "Elm"
69+ , D.red (D.fromUtf8 (V.toString V.compiler))
70+ , "right", "now."
71+ ]
72+ ]
73+
74+ AppBadElm version ->
75+ Help.report "ELM VERSION MISMATCH" (Just "elm.json")
76+ "Your elm.json says this application needs a different version of Elm."
77+ [ D.fillSep
78+ [ "It", "requires"
79+ , D.green (D.fromUtf8 (V.toString version)) <> ","
80+ , "but", "you", "are", "using"
81+ , D.red (D.fromUtf8 (V.toString V.compiler))
82+ , "right", "now."
83+ ]
84+ ]
85+
86+ AppMissingTrans missingDeps ->
87+ let
88+ toEntry (pkg, vsn) =
89+ "\"" ++ Pkg.toChars pkg ++ "\": \"" ++ V.toChars vsn ++ "\""
90+ in
91+ Help.report "MISSING DEPENDENCIES" (Just "elm.json")
92+ "Your elm.json is missing some \"indirect\" dependencies:"
93+ [ D.indent 4 $ D.dullyellow $ D.vcat $ map (D.fromChars . toEntry) missingDeps
94+ , D.fillSep
95+ ["This","usually","means","you","are","editing","elm.json","by","hand."
96+ ,"It","is","much","more","reliable","to","use","the"
97+ ,D.green "elm install","command","instead."
98+ ]
99+ ]
100+
101+ BadDeps ->
102+ Help.report "INVALID PACKAGE DEPENDENCIES" (Just "elm.json")
103+ "The dependencies in your elm.json are not compatible."
104+ [ D.fillSep
105+ ["Did","you","change","them","by","hand?","Try","to","change","it","back!"
106+ ,"It","is","much","better","to","add","dependencies","with",D.green "elm install"
107+ ,"or","the","dependency","management","tool","in",D.green "elm reactor" <> "."
108+ ]
109+ , D.reflow $
110+ "Please ask for help on the Elm slack <http://elmlang.herokuapp.com/> if\
111+ \ you try those paths and still cannot figure it out!"
112+ ]
113+
114+ BuildFailure elmHome pkg vsn ->
115+ Help.report "CORRUPT DEPENDENCY" Nothing
116+ "I ran into a problem while building the following package:"
117+ [ D.indent 4 $ D.red $ D.fromChars $ Pkg.toChars pkg ++ " " ++ V.toChars vsn
118+ , D.fillSep
119+ ["This","probably","means","the","downloaded","files","got","corrupted","somehow."
120+ ,"Try","deleting",D.dullyellow (D.fromChars elmHome),"(a","directory","for"
121+ ,"caching","build","artifacts)","and","see","if","that","resolves","the","issue."
122+ ]
123+ ]
builder/src/Reporting/Exit/Help.hs+10−9
@@ -14,6 +14,7 @@ module Reporting.Exit.Help
1414 where
1515
1616
17+import qualified Data.Utf8 as Utf8
1718import GHC.IO.Handle (hIsTerminalDevice)
1819import System.IO (Handle, hPutStr, stderr, stdout)
1920
@@ -29,7 +30,7 @@ import qualified Reporting.Error as Error
2930
3031
3132data Report
32− = CompilerReport FilePath Error.Module [Error.Module]
33+ = CompilerReport Error.Module [Error.Module]
3334 | Report
3435 { _title :: String
3536 , _path :: Maybe FilePath
@@ -52,7 +53,7 @@ jsonReport =
5253 Report
5354
5455
55−compilerReport :: FilePath -> Error.Module -> [Error.Module] -> Report
56+compilerReport :: Error.Module -> [Error.Module] -> Report
5657compilerReport =
5758 CompilerReport
5859
@@ -64,8 +65,8 @@ compilerReport =
6465reportToDoc :: Report -> D.Doc
6566reportToDoc report_ =
6667 case report_ of
67− CompilerReport root e es ->
68− Error.toDoc root e es
68+ CompilerReport e es ->
69+ Error.toDoc e es
6970
7071 Report title maybePath message ->
7172 let
@@ -94,17 +95,17 @@ reportToDoc report_ =
9495reportToJson :: Report -> E.Value
9596reportToJson report_ =
9697 case report_ of
97− CompilerReport _ e es ->
98+ CompilerReport e es ->
9899 E.object
99− [ "type" ==> E.chars "compile-errors"
100+ [ "type" ==> E.string "compile-errors"
100101 , "errors" ==> E.list Error.toJson (e:es)
101102 ]
102103
103104 Report title maybePath message ->
104105 E.object
105− [ "type" ==> E.chars "error"
106− , "path" ==> maybe E.null E.chars maybePath
107− , "title" ==> E.chars title
106+ [ "type" ==> E.string "error"
107+ , "path" ==> maybe E.null (E.string . Utf8.fromChars) maybePath
108+ , "title" ==> E.string (Utf8.fromChars title)
108109 , "message" ==> D.encode message
109110 ]
110111
builder/src/Reporting/Exit/Http.hsnew file+104
@@ -0,0 +1,104 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+module Reporting.Exit.Http
3+ ( Exit(..)
4+ , toReport
5+ , BadJson(..)
6+ , badJsonToDocs
7+ )
8+ where
9+
10+
11+import qualified Data.Text as Text
12+
13+import Reporting.Doc ((<>))
14+import qualified Reporting.Doc as D
15+import qualified Reporting.Exit.Help as Help
16+
17+
18+
19+-- EXITS
20+
21+
22+data Exit
23+ = Unknown String
24+ | BadJson String D.Doc
25+ | BadZipData
26+ | BadZipSha String String
27+
28+
29+
30+-- TO REPORT
31+
32+
33+toReport :: String -> Exit -> Help.Report
34+toReport url exit =
35+ let
36+ urlDoc =
37+ D.indent 4 $ D.dullyellow $ "<" <> D.fromString url <> ">"
38+ in
39+ case exit of
40+ Unknown message ->
41+ Help.report "HTTP PROBLEM" Nothing "The following HTTP request failed:"
42+ [ urlDoc
43+ , D.stack
44+ [ "Here is the error message I was able to extract:"
45+ , D.indent 4 $ D.reflow message
46+ ]
47+ ]
48+
49+ BadJson path doc ->
50+ Help.jsonReport "UNEXPECTED JSON" (Just path) doc
51+
52+ BadZipData ->
53+ Help.report "CORRUPT ZIP" Nothing "I could not unzip the file downloaded from:"
54+ [ urlDoc
55+ , D.reflow $
56+ "If it is a transient issue, it should be fixed if you try this\
57+ \ again. If it seems like an Elm problem, please report it though!"
58+ ]
59+
60+ BadZipSha expectedHash actualHash ->
61+ Help.report "CORRUPT ZIP" Nothing "I got an unexpected zip file from:"
62+ [ urlDoc
63+ , D.reflow "I check the hash the zip, and it seems off:"
64+ , D.vcat $ map D.fromString $
65+ [ " Expected: " ++ expectedHash
66+ , " Actual: " ++ actualHash
67+ ]
68+ , D.reflow $
69+ "This usually means that the package author moved the version\
70+ \ tag, so report it to them and see if that is the issue. Folks\
71+ \ on Elm slack can probably help as well."
72+ ]
73+
74+
75+
76+-- BAD JSON
77+
78+
79+data BadJson
80+ = BadNewPkg Text.Text
81+ | BadAllPkg Text.Text String
82+ | BadAllVsn Text.Text
83+
84+
85+badJsonToDocs :: BadJson -> [D.Doc]
86+badJsonToDocs badJson =
87+ case badJson of
88+ BadNewPkg txt ->
89+ ["I","ran","into",D.red (D.fromString (show txt)) <> ","
90+ ,"but","I","need","entries","like"
91+ ,D.green "\"elm/core@6.0.0\"" <> "."
92+ ]
93+
94+ BadAllPkg txt suggestion ->
95+ ["The",D.red (D.fromString (show txt)),"value","is","not","a","valid","package","name."
96+ ]
97+ ++ map D.fromString (words suggestion)
98+
99+ BadAllVsn txt ->
100+ ["You","provided",D.red (D.fromString (show txt))
101+ ,"which","is","not","a","valid","version.","I","need","something","like"
102+ ,D.green "\"1.0.0\"","or",D.green "\"2.0.4\"" <> "."
103+ ]
104+
builder/src/Reporting/Task.hs−17
@@ -3,10 +3,8 @@ module Reporting.Task
33 ( Task
44 , run
55 , throw
6− , mapError
76 --
87 , io
9− , mio
108 , eio
119 )
1210 where
@@ -33,12 +31,6 @@ throw x =
3331 Task $ \_ err -> err x
3432
3533
36−mapError :: (x -> y) -> Task x a -> Task y a
37−mapError func (Task task) =
38− Task $ \ok err ->
39− task ok (err . func)
40−
41−
4234
4335-- IO
4436
@@ -49,15 +41,6 @@ io work =
4941 Task $ \ok _ -> work >>= ok
5042
5143
52−mio :: x -> IO (Maybe a) -> Task x a
53−mio x work =
54− Task $ \ok err ->
55− do result <- work
56− case result of
57− Just a -> ok a
58− Nothing -> err x
59−
60−
6144eio :: (x -> y) -> IO (Either x a) -> Task y a
6245eio func work =
6346 Task $ \ok err ->
builder/src/Stuff.hs+9−8
@@ -8,8 +8,8 @@ module Stuff
88 , elmo
99 , temp
1010 , findRoot
11− , withRootLock
12− , withRegistryLock
11+ , withProjectLock
12+ , withCacheLock
1313 , PackageCache
1414 , getPackageCache
1515 , registry
@@ -120,16 +120,17 @@ findRootHelp dirs =
120120-- LOCKS
121121
122122
123−withRootLock :: FilePath -> IO a -> IO a
124−withRootLock root work =
123+withProjectLock :: FilePath -> IO a -> IO a
124+withProjectLock root work =
125125 do let dir = stuff root
126126 Dir.createDirectoryIfMissing True dir
127− Lock.withFileLock (dir </> "lock") Lock.Exclusive (\_ -> work)
127+ Lock.withFileLock (dir </> "project.lock") Lock.Exclusive (\_ -> work)
128128
129129
130−withRegistryLock :: PackageCache -> IO a -> IO a
131−withRegistryLock (PackageCache dir) work =
132− Lock.withFileLock (dir </> "lock") Lock.Exclusive (\_ -> work)
130+withCacheLock :: PackageCache -> IO a -> IO a
131+withCacheLock (PackageCache dir) work =
132+ Lock.withFileLock (dir </> "cache.lock") Lock.Exclusive (\_ -> work)
133+
133134
134135
135136
cabal.configdeleted−2
@@ -1,2 +0,0 @@
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− _ -> fail "binary encoding of CtorOpts was corrupted"
345+ _ -> error "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− _ -> fail "binary encoding of AliasType was corrupted"
396+ _ -> error "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 -- PERF profile switching Global to Name
138+ , _l_nodes :: Map.Map Global Node -- TODO 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− _ -> fail "problem getting Opt.Expr binary"
311+ _ -> error "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− _ -> fail "problem getting Opt.Def binary"
325+ _ -> error "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− _ -> fail "problem getting Opt.Path binary"
348+ _ -> error "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− _ -> fail "problem getting Opt.Decider binary"
364+ _ -> error "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− _ -> fail "problem getting Opt.Choice binary"
378+ _ -> error "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− _ -> fail "problem getting Opt.Main binary"
403+ _ -> error "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− _ -> fail "problem getting Opt.Node binary"
435+ _ -> error "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− _ -> fail "problem getting Opt.EffectsType binary"
451+ _ -> error "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 [Exposed]
198+ | Explicit [A.Located Exposed]
199199
200200
201201data Exposed
202− = Lower (A.Located Name)
203− | Upper (A.Located Name) Privacy
204− | Operator A.Region Name
202+ = Lower Name
203+ | Upper Name Privacy
204+ | Operator Name
205205
206206
207207data Privacy
208− = Public A.Region
208+ = Public
209209 | Private
compiler/src/AST/Utils/Binop.hs+6−5
@@ -41,11 +41,12 @@ instance Binary Precedence where
4141instance Binary Associativity where
4242 get =
4343 do n <- getWord8
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"
44+ return $
45+ case n of
46+ 0 -> Left
47+ 1 -> Non
48+ 2 -> Right
49+ _ -> error "Error reading valid associativity from serialized string"
4950
5051 put assoc =
5152 putWord8 $
compiler/src/AST/Utils/Shader.hs+4−51
@@ -4,27 +4,22 @@ module AST.Utils.Shader
44 ( Source
55 , Types(..)
66 , Type(..)
7− , fromChars
8− , toJsStringBuilder
97 )
108 where
119
1210
13−import Control.Monad (liftM)
14−import Data.Binary (Binary, get, put)
15−import qualified Data.ByteString as BS
16−import qualified Data.ByteString.Builder as B
17−import qualified Data.ByteString.UTF8 as BS_UTF8
1811import qualified Data.Map as Map
1912import qualified Data.Name as Name
13+import qualified Data.Utf8 as Utf8
2014
2115
2216
2317-- SOURCE
2418
2519
26−newtype Source =
27− Source BS.ByteString
20+type Source = Utf8.VeryLong SOURCE
21+
22+data SOURCE
2823
2924
3025
@@ -47,45 +42,3 @@ data Type
4742 | V4
4843 | M4
4944 | Texture
50−
51−
52−
53−-- TO BUILDER
54−
55−
56−toJsStringBuilder :: Source -> B.Builder
57−toJsStringBuilder (Source src) =
58− B.byteString src
59−
60−
61−
62−-- FROM CHARS
63−
64−
65−fromChars :: [Char] -> Source
66−fromChars chars =
67− Source (BS_UTF8.fromString (escape chars))
68−
69−
70−escape :: [Char] -> [Char]
71−escape chars =
72− case chars of
73− [] ->
74− []
75−
76− c:cs
77− | c == '\r' -> escape cs
78− | c == '\n' -> '\\' : 'n' : escape cs
79− | c == '\"' -> '\\' : '"' : escape cs
80− | c == '\'' -> '\\' : '\'' : escape cs
81− | c == '\\' -> '\\' : '\\' : escape cs
82− | otherwise -> c : escape cs
83−
84−
85−
86−-- BINARY
87−
88−
89−instance Binary Source where
90− get = liftM Source get
91− put (Source a) = put a
compiler/src/AST/Utils/Type.hs+1
@@ -1,4 +1,5 @@
11{-# OPTIONS_GHC -Wall #-}
2+{-# LANGUAGE OverloadedStrings #-}
23module AST.Utils.Type
34 ( delambda
45 , dealias
compiler/src/Canonicalize/Environment.hs+20−50
@@ -4,8 +4,6 @@ module Canonicalize.Environment
44 ( Env(..)
55 , Exposed
66 , Qualified
7− , Info(..)
8− , mergeInfo
97 , Var(..)
108 , Type(..)
119 , Ctor(..)
@@ -22,8 +20,8 @@ module Canonicalize.Environment
2220
2321import qualified Data.Map.Merge.Strict as Map
2422import qualified Data.Map.Strict as Map
23+import qualified Data.Map.Strict.Internal as I
2524import qualified Data.Name as Name
26−import qualified Data.OneOrMore as OneOrMore
2725
2826import qualified AST.Utils.Binop as Binop
2927import qualified AST.Canonical as Can
@@ -60,34 +58,11 @@ data Env =
6058
6159
6260type Exposed a =
63− Map.Map Name.Name (Info a)
61+ Map.Map Name.Name (Map.Map ModuleName.Canonical a)
6462
6563
6664type Qualified 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))
65+ Map.Map Name.Name (Map.Map Name.Name (Map.Map ModuleName.Canonical a))
9166
9267
9368
@@ -97,8 +72,7 @@ mergeInfo info1 info2 =
9772data Var
9873 = Local A.Region
9974 | TopLevel A.Region
100− | Foreign ModuleName.Canonical Can.Annotation
101− | Foreigns ModuleName.Canonical (OneOrMore.OneOrMore ModuleName.Canonical)
75+ | Foreign (Map.Map ModuleName.Canonical Can.Annotation)
10276
10377
10478
@@ -165,10 +139,7 @@ addLocalLeft _ region =
165139addLocalBoth :: Name.Name -> A.Region -> Var -> Result i w Var
166140addLocalBoth name region var =
167141 case var of
168− Foreign _ _ ->
169− Result.ok (Local region)
170−
171− Foreigns _ _ ->
142+ Foreign _ ->
172143 Result.ok (Local region)
173144
174145 Local parentRegion ->
@@ -179,18 +150,17 @@ addLocalBoth name region var =
179150
180151
181152
182−
183153-- FIND TYPE
184154
185155
186156findType :: A.Region -> Env -> Name.Name -> Result i w Type
187157findType region (Env _ _ ts _ _ _ qts _) name =
188158 case Map.lookup name ts of
189− Just (Specific _ tipe) ->
159+ Just (I.Bin 1 _ tipe _ _) ->
190160 Result.ok tipe
191161
192− Just (Ambiguous h hs) ->
193− Result.throw (Error.AmbiguousType region Nothing name h hs)
162+ Just homes ->
163+ Result.throw (Error.AmbiguousType region Nothing name (Map.keys homes))
194164
195165 Nothing ->
196166 Result.throw (Error.NotFoundType region Nothing name (toPossibleNames ts qts))
@@ -201,11 +171,11 @@ findTypeQual region (Env _ _ ts _ _ _ qts _) prefix name =
201171 case Map.lookup prefix qts of
202172 Just qualified ->
203173 case Map.lookup name qualified of
204− Just (Specific _ tipe) ->
174+ Just (I.Bin 1 _ tipe _ _) ->
205175 Result.ok tipe
206176
207− Just (Ambiguous h hs) ->
208− Result.throw (Error.AmbiguousType region (Just prefix) name h hs)
177+ Just homes ->
178+ Result.throw (Error.AmbiguousType region (Just prefix) name (Map.keys homes))
209179
210180 Nothing ->
211181 Result.throw (Error.NotFoundType region (Just prefix) name (toPossibleNames ts qts))
@@ -221,11 +191,11 @@ findTypeQual region (Env _ _ ts _ _ _ qts _) prefix name =
221191findCtor :: A.Region -> Env -> Name.Name -> Result i w Ctor
222192findCtor region (Env _ _ _ cs _ _ _ qcs) name =
223193 case Map.lookup name cs of
224− Just (Specific _ ctor) ->
194+ Just (I.Bin 1 _ ctor _ _) ->
225195 Result.ok ctor
226196
227− Just (Ambiguous h hs) ->
228− Result.throw (Error.AmbiguousVariant region Nothing name h hs)
197+ Just homes ->
198+ Result.throw (Error.AmbiguousVariant region Nothing name (Map.keys homes))
229199
230200 Nothing ->
231201 Result.throw (Error.NotFoundVariant region Nothing name (toPossibleNames cs qcs))
@@ -236,11 +206,11 @@ findCtorQual region (Env _ _ _ cs _ _ _ qcs) prefix name =
236206 case Map.lookup prefix qcs of
237207 Just qualified ->
238208 case Map.lookup name qualified of
239− Just (Specific _ pattern) ->
209+ Just (I.Bin 1 _ pattern _ _) ->
240210 Result.ok pattern
241211
242− Just (Ambiguous h hs) ->
243− Result.throw (Error.AmbiguousVariant region (Just prefix) name h hs)
212+ Just homes ->
213+ Result.throw (Error.AmbiguousVariant region (Just prefix) name (Map.keys homes))
244214
245215 Nothing ->
246216 Result.throw (Error.NotFoundVariant region (Just prefix) name (toPossibleNames cs qcs))
@@ -256,11 +226,11 @@ findCtorQual region (Env _ _ _ cs _ _ _ qcs) prefix name =
256226findBinop :: A.Region -> Env -> Name.Name -> Result i w Binop
257227findBinop region (Env _ _ _ _ binops _ _ _) name =
258228 case Map.lookup name binops of
259− Just (Specific _ binop) ->
229+ Just (I.Bin 1 _ binop _ _) ->
260230 Result.ok binop
261231
262− Just (Ambiguous h hs) ->
263− Result.throw (Error.AmbiguousBinop region name h hs)
232+ Just homes ->
233+ Result.throw (Error.AmbiguousBinop region name (Map.keys homes))
264234
265235 Nothing ->
266236 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 (\new old -> OneOrMore.more old new) name (OneOrMore.one (Info region value)) dict
108+ Map.insertWith OneOrMore.more name (OneOrMore.one (Info region value)) dict
109109
110110
111111union :: Dict a -> Dict a -> Dict a
compiler/src/Canonicalize/Environment/Foreign.hs+37−49
@@ -35,14 +35,7 @@ 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 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
38+ Result.ok (Env.Env home (Map.map Env.Foreign vs) ts cs bs qvs qts qcs)
4639
4740
4841
@@ -68,7 +61,7 @@ emptyState =
6861
6962emptyTypes :: Env.Exposed Env.Type
7063emptyTypes =
71− Map.singleton "List" (Env.Specific ModuleName.list (Env.Union 1 ModuleName.list))
64+ Map.singleton "List" (Map.singleton ModuleName.list (Env.Union 1 ModuleName.list))
7265
7366
7467
@@ -109,8 +102,8 @@ addImport ifaces (State vs ts cs bs qvs qts qcs) (Src.Import (A.At _ name) maybe
109102 (Map.mapMaybeWithKey (unionToType home) unions)
110103 (Map.mapMaybeWithKey (aliasToType home) aliases)
111104
112− !vars = Map.map (Env.Specific home) defs
113− !types = Map.map (Env.Specific home . fst) rawTypeInfo
105+ !vars = Map.map (Map.singleton home) defs
106+ !types = Map.map (Map.singleton home . fst) rawTypeInfo
114107 !ctors = Map.foldr (addExposed . snd) Map.empty rawTypeInfo
115108
116109 !qvs2 = addQualified prefix vars qvs
@@ -136,7 +129,7 @@ addImport ifaces (State vs ts cs bs qvs qts qcs) (Src.Import (A.At _ name) maybe
136129
137130addExposed :: Env.Exposed a -> Env.Exposed a -> Env.Exposed a
138131addExposed =
139− Map.unionWith Env.mergeInfo
132+ Map.unionWith Map.union
140133
141134
142135addQualified :: Name.Name -> Env.Exposed a -> Env.Qualified a -> Env.Qualified a
@@ -157,7 +150,7 @@ unionToTypeHelp :: ModuleName.Canonical -> Name.Name -> Can.Union -> (Env.Type,
157150unionToTypeHelp home name union@(Can.Union vars ctors _ _) =
158151 let
159152 addCtor dict (Can.Ctor ctor index _ args) =
160− Map.insert ctor (Env.Specific home (Env.Ctor home name union index args)) dict
153+ Map.insert ctor (Map.singleton home (Env.Ctor home name union index args)) dict
161154 in
162155 ( Env.Union (length vars) home
163156 , List.foldl' addCtor Map.empty ctors
@@ -188,7 +181,7 @@ aliasToTypeHelp home name (Can.Alias vars tipe) =
188181 (Can.TAlias home name avars (Can.Filled tipe))
189182 (Can.fieldsToList fields)
190183 in
191− Map.singleton name (Env.Specific home (Env.RecordCtor home vars alias))
184+ Map.singleton name (Map.singleton home (Env.RecordCtor home vars alias))
192185
193186 _ ->
194187 Map.empty
@@ -199,9 +192,9 @@ aliasToTypeHelp home name (Can.Alias vars tipe) =
199192-- BINOP
200193
201194
202−binopToBinop :: ModuleName.Canonical -> Name.Name -> I.Binop -> Env.Info Env.Binop
195+binopToBinop :: ModuleName.Canonical -> Name.Name -> I.Binop -> Map.Map ModuleName.Canonical Env.Binop
203196binopToBinop home op (I.Binop name annotation associativity precedence) =
204− Env.Specific home (Env.Binop op home name annotation associativity precedence)
197+ Map.singleton home (Env.Binop op home name annotation associativity precedence)
205198
206199
207200
@@ -214,19 +207,19 @@ addExposedValue
214207 -> Map.Map Name.Name (Env.Type, Env.Exposed Env.Ctor)
215208 -> Map.Map Name.Name I.Binop
216209 -> State
217− -> Src.Exposed
210+ -> A.Located Src.Exposed
218211 -> Result i w State
219−addExposedValue home vars types binops (State vs ts cs bs qvs qts qcs) exposed =
212+addExposedValue home vars types binops (State vs ts cs bs qvs qts qcs) (A.At region exposed) =
220213 case exposed of
221− Src.Lower (A.At region name) ->
214+ Src.Lower name ->
222215 case Map.lookup name vars of
223216 Just info ->
224− Result.ok (State (Map.insertWith Env.mergeInfo name info vs) ts cs bs qvs qts qcs)
217+ Result.ok (State (Map.insert name info vs) ts cs bs qvs qts qcs)
225218
226219 Nothing ->
227220 Result.throw (Error.ImportExposingNotFound region home name (Map.keys vars))
228221
229− Src.Upper (A.At region name) privacy ->
222+ Src.Upper name privacy ->
230223 case privacy of
231224 Src.Private ->
232225 case Map.lookup name types of
@@ -234,43 +227,43 @@ addExposedValue home vars types binops (State vs ts cs bs qvs qts qcs) exposed =
234227 case tipe of
235228 Env.Union _ _ ->
236229 let
237− !ts2 = Map.insert name (Env.Specific home tipe) ts
230+ !ts2 = Map.insert name (Map.singleton home tipe) ts
238231 in
239232 Result.ok (State vs ts2 cs bs qvs qts qcs)
240233
241234 Env.Alias _ _ _ _ ->
242235 let
243− !ts2 = Map.insert name (Env.Specific home tipe) ts
236+ !ts2 = Map.insert name (Map.singleton home tipe) ts
244237 !cs2 = addExposed cs ctors
245238 in
246239 Result.ok (State vs ts2 cs2 bs qvs qts qcs)
247240
248241 Nothing ->
249− case checkForCtorMistake name types of
250− tipe:_ ->
242+ case Map.lookup name (toCtors types) of
243+ Just tipe ->
251244 Result.throw $ Error.ImportCtorByName region name tipe
252245
253− [] ->
246+ Nothing ->
254247 Result.throw $ Error.ImportExposingNotFound region home name (Map.keys types)
255248
256− Src.Public dotDotRegion ->
249+ Src.Public ->
257250 case Map.lookup name types of
258251 Just (tipe, ctors) ->
259252 case tipe of
260253 Env.Union _ _ ->
261254 let
262− !ts2 = Map.insert name (Env.Specific home tipe) ts
255+ !ts2 = Map.insert name (Map.singleton home tipe) ts
263256 !cs2 = addExposed cs ctors
264257 in
265258 Result.ok (State vs ts2 cs2 bs qvs qts qcs)
266259
267260 Env.Alias _ _ _ _ ->
268− Result.throw (Error.ImportOpenAlias dotDotRegion name)
261+ Result.throw (Error.ImportOpenAlias region name)
269262
270263 Nothing ->
271264 Result.throw (Error.ImportExposingNotFound region home name (Map.keys types))
272265
273− Src.Operator region op ->
266+ Src.Operator op ->
274267 case Map.lookup op binops of
275268 Just binop ->
276269 let
@@ -282,23 +275,18 @@ addExposedValue home vars types binops (State vs ts cs bs qvs qts qcs) exposed =
282275 Result.throw (Error.ImportExposingNotFound region home op (Map.keys binops))
283276
284277
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
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
288282 where
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
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
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 = Env.Specific home (Env.Union arity home)
113+ let one = Map.singleton 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 = Env.Specific home (Env.Alias (length args) home args ctype)
136+ let one = Map.singleton 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 (Env.Info Env.Ctor)
284+type CtorDups = Dups.Dict (Map.Map ModuleName.Canonical 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 (Env.Specific home (toRecordCtor home name vars fields))
300+ Dups.one name region (Map.singleton 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 $ Env.Specific home $
354+ Dups.one name region $ Map.singleton home $
355355 Env.Ctor home typeName union index args
compiler/src/Canonicalize/Expression.hs+7−6
@@ -14,6 +14,7 @@ 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
1718import qualified Data.Name as Name
1819
1920import qualified AST.Canonical as Can
@@ -695,15 +696,15 @@ findVar region (Env.Env localHome vs _ _ _ qvs _ _) name =
695696 Env.TopLevel _ ->
696697 logVar name (Can.VarTopLevel localHome name)
697698
698− Env.Foreign home annotation ->
699+ Env.Foreign (I.Bin 1 home annotation _ _) ->
699700 Result.ok $
700701 if home == ModuleName.debug then
701702 Can.VarDebug localHome name annotation
702703 else
703704 Can.VarForeign home name annotation
704705
705− Env.Foreigns h hs ->
706− Result.throw (Error.AmbiguousVar region Nothing name h hs)
706+ Env.Foreign homes ->
707+ Result.throw (Error.AmbiguousVar region Nothing name (Map.keys homes))
707708
708709 Nothing ->
709710 Result.throw (Error.NotFoundVar region Nothing name (toPossibleNames vs qvs))
@@ -714,15 +715,15 @@ findVarQual region (Env.Env localHome vs _ _ _ qvs _ _) prefix name =
714715 case Map.lookup prefix qvs of
715716 Just qualified ->
716717 case Map.lookup name qualified of
717− Just (Env.Specific home annotation) ->
718+ Just (I.Bin 1 home annotation _ _) ->
718719 Result.ok $
719720 if home == ModuleName.debug then
720721 Can.VarDebug localHome name annotation
721722 else
722723 Can.VarForeign home name annotation
723724
724− Just (Env.Ambiguous h hs) ->
725− Result.throw (Error.AmbiguousVar region (Just prefix) name h hs)
725+ Just homes ->
726+ Result.throw (Error.AmbiguousVar region (Just prefix) name (Map.keys homes))
726727
727728 Nothing ->
728729 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− -> Src.Exposed
239+ -> A.Located Src.Exposed
240240 -> Result i w (Dups.Dict (A.Located Can.Export))
241−checkExposed values unions aliases binops effects exposed =
241+checkExposed values unions aliases binops effects (A.At region exposed) =
242242 case exposed of
243− Src.Lower (A.At region name) ->
243+ Src.Lower 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 exposed =
252252 Result.throw $ Error.ExportNotFound region Error.BadVar name $
253253 ports ++ Map.keys values
254254
255− Src.Operator region name ->
255+ Src.Operator 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 (A.At region name) (Src.Public dotDotRegion) ->
262+ Src.Upper name Src.Public ->
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 dotDotRegion name
266+ Result.throw $ Error.ExportOpenAlias region name
267267 else
268268 Result.throw $ Error.ExportNotFound region Error.BadType name $
269269 Map.keys unions ++ Map.keys aliases
270270
271− Src.Upper (A.At region name) Src.Private ->
271+ Src.Upper 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+2−3
@@ -8,7 +8,6 @@ module Canonicalize.Pattern
88 where
99
1010
11−import qualified Data.List as List
1211import qualified Data.Map.Strict as Map
1312import qualified Data.Name as Name
1413
@@ -174,8 +173,8 @@ logVar name region value =
174173logFields :: [A.Located Name.Name] -> a -> Result DupsDict w a
175174logFields fields value =
176175 let
177− addField dict (A.At region name) =
176+ addField (A.At region name) dict =
178177 Dups.insert name region region dict
179178 in
180179 Result.Result $ \bindings warnings _ ok ->
181− ok (List.foldl' addField bindings fields) warnings value
180+ ok (foldr addField bindings fields) warnings value
compiler/src/Data/Name.hs+60−60
@@ -19,6 +19,7 @@ module Data.Name
1919 , isAppendableType
2020 , isCompappendType
2121 , fromVarIndex
22+ , fromReplCount
2223 , fromWords
2324 , fromManyNames
2425 , fromTypeVariable
@@ -31,7 +32,7 @@ module Data.Name
3132 , shader, debug, debugger, bitwise, basics
3233 , utils, negate, true, false, value
3334 , node, program, _main, _Main, dollar, identity
34− , replModule, replValueToPrint
35+ , replModule
3536 )
3637 where
3738
@@ -44,14 +45,19 @@ import qualified Data.Coerce as Coerce
4445import qualified Data.List as List
4546import qualified Data.String as Chars
4647import qualified Data.Utf8 as Utf8
48+import Foreign.Ptr (plusPtr, minusPtr)
4749import GHC.Exts
48− ( Int(I#), Ptr
50+ ( Int(I#), Ptr(Ptr)
51+ , RealWorld
4952 , MutableByteArray#
5053 , isTrue#
5154 , newByteArray#
5255 , sizeofByteArray#
56+ , writeWord8OffAddr#
57+ , copyByteArrayToAddr#
5358 , unsafeFreezeByteArray#
5459 )
60+import GHC.IO
5561import GHC.ST (ST(ST), runST)
5662import GHC.Prim
5763import GHC.Word (Word8(W8#))
@@ -202,11 +208,11 @@ fromVarIndex :: Int -> Name
202208fromVarIndex n =
203209 runST
204210 (
205− do let !size = 2 + getIndexSize n
211+ do let !size = getIndexSize n
206212 mba <- newByteArray size
207213 writeWord8 mba 0 0x5F {- _ -}
208214 writeWord8 mba 1 0x76 {- v -}
209− writeDigitsAtEnd mba size n
215+ writeDigits mba (size - 1) n
210216 freeze mba
211217 )
212218
@@ -214,20 +220,19 @@ fromVarIndex n =
214220{-# INLINE getIndexSize #-}
215221getIndexSize :: Int -> Int
216222getIndexSize n
217− | n < 10 = 1
218− | n < 100 = 2
219− | True = ceiling (logBase 10 (fromIntegral n + 1) :: Float)
223+ | n < 10 = 3
224+ | n < 100 = 4
225+ | True = 2 + ceiling (logBase 10 (fromIntegral n + 1) :: Float)
220226
221227
222228
223−writeDigitsAtEnd :: MBA s -> Int -> Int -> ST s ()
224−writeDigitsAtEnd !mba !oldOffset !n =
229+writeDigits :: MBA s -> Int -> Int -> ST s ()
230+writeDigits !mba !offset !n =
225231 do let (q,r) = quotRem n 10
226− let !newOffset = oldOffset - 1
227− writeWord8 mba newOffset (0x30 + fromIntegral r)
232+ writeWord8 mba offset (0x30 + fromIntegral r)
228233 if q <= 0
229234 then return ()
230− else writeDigitsAtEnd mba newOffset q
235+ else writeDigits mba (offset-1) q
231236
232237
233238
@@ -250,7 +255,7 @@ fromTypeVariable name@(Utf8.Utf8 ba#) index =
250255 mba <- newByteArray size
251256 copyToMBA name mba
252257 writeWord8 mba (I# len#) 0x5F {- _ -}
253− writeDigitsAtEnd mba size index
258+ writeDigits mba (size - 1) index
254259 freeze mba
255260 )
256261 else
@@ -259,7 +264,7 @@ fromTypeVariable name@(Utf8.Utf8 ba#) index =
259264 do let !size = I# len# + getIndexSize index
260265 mba <- newByteArray size
261266 copyToMBA name mba
262− writeDigitsAtEnd mba size index
267+ writeDigits mba (size - 1) index
263268 freeze mba
264269 )
265270
@@ -278,61 +283,61 @@ fromTypeVariableScheme scheme =
278283 freeze mba
279284 else
280285 do let (extra, letter) = quotRem scheme 26
281− let !size = 1 + getIndexSize extra
286+ let !size = getIndexSize extra
282287 mba <- newByteArray size
283288 writeWord8 mba 0 (0x61 + fromIntegral letter)
284− writeDigitsAtEnd mba size extra
289+ writeDigits mba (size - 1) extra
285290 freeze mba
286291 )
287292
288293
289294
295+-- FROM REPL COUNT
296+
297+
298+fromReplCount :: Int -> Name
299+fromReplCount n =
300+ Utf8.fromChars ("repl_value_" ++ show n)
301+
302+
303+
290304-- 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)
300305
301306
302307fromManyNames :: [Name] -> Name
303308fromManyNames names =
304− case names of
305− [] ->
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− )
309+ let
310+ !(I# size#) = sum (map (\(Utf8.Utf8 ba#) -> I# (sizeofByteArray# ba# +# 1#)) names)
311+ in
312+ runST
313+ (
314+ ST $ \s ->
315+ case newByteArray# size# s of
316+ (# s, mba# #) ->
317+ case writeNames mba# 0# names s of
318+ s ->
319+ case unsafeFreezeByteArray# mba# s of
320+ (# s, ba# #) -> (# s, Utf8.Utf8 ba# #)
321+ )
330322
331323
332−{-# NOINLINE blank #-}
333−blank :: Name
334−blank =
335− fromWords [0x5F,0x4D,0x24] {-_M$-}
324+writeNames :: MutableByteArray# s -> Int# -> [Name] -> State# s -> State# s
325+writeNames mba# !offset# names s =
326+ case names of
327+ [] ->
328+ s
329+
330+ (Utf8.Utf8 ba#) : names ->
331+ case writeWord8Array# mba# offset# 0x24## {- $ -} s of
332+ s ->
333+ let
334+ !offset1# = offset# +# 1#
335+ !len# = sizeofByteArray# ba#
336+ !newOffset# = offset1# +# len#
337+ in
338+ case copyByteArray# ba# 0# mba# offset1# len# s of
339+ s ->
340+ writeNames mba# newOffset# names s
336341
337342
338343
@@ -603,8 +608,3 @@ identity = fromChars "identity"
603608{-# NOINLINE replModule #-}
604609replModule :: Name
605610replModule = fromChars "Elm_Repl"
606−
607−
608−{-# NOINLINE replValueToPrint #-}
609−replValueToPrint :: Name
610−replValueToPrint = fromChars "repl_input_value_"
compiler/src/Data/NonEmptyList.hs+2−6
@@ -52,12 +52,8 @@ instance Foldable List where
5252-- SORT BY
5353
5454
55−sortBy :: (Ord b) => (a -> b) -> List a -> List a
56−sortBy toRank (List x xs) =
57− let
58− comparison a b =
59− compare (toRank a) (toRank b)
60− in
55+sortBy :: (a -> a -> Ordering) -> List a -> List a
56+sortBy comparison (List x xs) =
6157 case List.sortBy comparison xs of
6258 [] ->
6359 List x []
compiler/src/Data/Utf8.hs+4−6
@@ -63,7 +63,7 @@ import GHC.Exts
6363import GHC.IO
6464import GHC.ST (ST(ST), runST)
6565import GHC.Prim
66−import GHC.Word (Word8(W8#))
66+import GHC.Word (Word8(W8#), Word16(W16#))
6767
6868import qualified Parse.Primitives as P
6969
@@ -261,9 +261,7 @@ instance Eq (Utf8 t) where
261261
262262
263263-- COMPARE
264−--
265−-- TODO: is it fine to sort by length and only compare bytes on length ties?
266−--
264+
267265
268266instance Ord (Utf8 t) where
269267 compare (Utf8 ba1#) (Utf8 ba2#) =
@@ -457,7 +455,7 @@ toEscapedBuilderHelp before after !name@(Utf8 ba#) k =
457455 !bLen = minusPtr bEnd bOffset
458456 in
459457 if len <= bLen then
460− do -- PERF test if writing word-by-word is faster
458+ do -- TODO test if writing word-by-word is faster
461459 copyToPtr name offset bOffset len
462460 escape before after bOffset name offset len 0
463461 let !newBufferRange = B.BufferRange (plusPtr bOffset len) bEnd
@@ -567,7 +565,7 @@ data MBA s =
567565 MBA# (MutableByteArray# s)
568566
569567
570−newByteArray :: Int -> ST s (MBA s) -- PERF see if newPinnedByteArray for len > 256 is positive
568+newByteArray :: Int -> ST s (MBA s) -- TODO see if newPinnedByteArray for len > 256 is positive
571569newByteArray (I# len#) =
572570 ST $ \s ->
573571 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 [ Src.Upper (A.At A.zero name) (Src.Public A.zero) ]
52+ Src.Explicit [ A.At A.zero (Src.Upper name Src.Public) ]
5353
5454
5555typeClosed :: Name.Name -> Src.Exposing
5656typeClosed name =
57− Src.Explicit [ Src.Upper (A.At A.zero name) Src.Private ]
57+ Src.Explicit [ A.At A.zero (Src.Upper name Src.Private) ]
5858
5959
6060operator :: Name.Name -> Src.Exposing
6161operator op =
62− Src.Explicit [ Src.Operator A.zero op ]
62+ Src.Explicit [ A.At A.zero (Src.Operator 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− -- PERF profile Opt.Global representation
90+ -- TODO profile Opt.Global representation
9191 -- current representation needs less allocation
9292 -- but maybe the lookup is much worse
9393
compiler/src/Elm/Constraint.hs+77−55
@@ -5,6 +5,9 @@ module Elm.Constraint
55 , exactly
66 , anything
77 , toChars
8+ , toString
9+ , Error(..)
10+ , fromString
811 , satisfies
912 , check
1013 , intersect
@@ -13,8 +16,6 @@ module Elm.Constraint
1316 , untilNextMajor
1417 , untilNextMinor
1518 , expand
16− --
17− , Error(..)
1819 , decoder
1920 , encode
2021 )
@@ -23,12 +24,11 @@ module Elm.Constraint
2324
2425import Control.Monad (liftM4)
2526import Data.Binary (Binary, get, put, getWord8, putWord8)
27+import qualified Data.Utf8 as Utf8
2628
2729import qualified Elm.Version as V
2830import qualified Json.Decode as D
2931import qualified Json.Encode as E
30−import qualified Parse.Primitives as P
31−import Parse.Primitives (Row, Col)
3232
3333
3434
@@ -61,21 +61,78 @@ anything =
6161
6262
6363
64−-- TO CHARS
64+-- TO STRING
6565
6666
67−toChars :: Constraint -> [Char]
67+toChars :: Constraint -> String
6868toChars constraint =
69+ Utf8.toChars (toString constraint)
70+
71+
72+toString :: Constraint -> Utf8.String
73+toString constraint =
6974 case constraint of
7075 Range lower lowerOp upperOp upper ->
71− V.toChars lower ++ opToChars lowerOp ++ "v" ++ opToChars upperOp ++ V.toChars upper
76+ Utf8.join 0x20 {- -}
77+ [ V.toString lower
78+ , toStringHelp lowerOp
79+ , "v"
80+ , toStringHelp upperOp
81+ , V.toString upper
82+ ]
7283
7384
74−opToChars :: Op -> [Char]
75−opToChars op =
85+toStringHelp :: Op -> Utf8.String
86+toStringHelp op =
7687 case op of
77− Less -> " < "
78− LessOrEqual -> " <= "
88+ Less -> "<"
89+ LessOrEqual -> "<="
90+
91+
92+
93+-- FROM STRING
94+
95+
96+data Error
97+ = BadLower Utf8.String
98+ | BadUpper Utf8.String
99+ | BadFormat
100+ | InvalidOp
101+ | InvalidRange V.Version V.Version
102+
103+
104+fromString :: Utf8.String -> Either Error Constraint
105+fromString string =
106+ case Utf8.split 0x20 {- -} string of
107+ [lower, lowerOp, "v", upperOp, upper] ->
108+ do lo <- versionFromString lower BadLower
109+ lop <- opFromString lowerOp
110+ hop <- opFromString upperOp
111+ hi <- versionFromString upper BadUpper
112+ if lo < hi
113+ then Right (Range lo lop hop hi)
114+ else Left (InvalidRange lo hi)
115+
116+ _ ->
117+ Left BadFormat
118+
119+
120+versionFromString :: Utf8.String -> (Utf8.String -> Error) -> Either Error V.Version
121+versionFromString string toError =
122+ case V.fromString string of
123+ Just vsn ->
124+ Right vsn
125+
126+ Nothing ->
127+ Left (toError string)
128+
129+
130+opFromString :: Utf8.String -> Either Error Op
131+opFromString text =
132+ case text of
133+ "<=" -> Right LessOrEqual
134+ "<" -> Right Less
135+ _ -> Left InvalidOp
79136
80137
81138
@@ -188,12 +245,18 @@ expand constraint@(Range lower lowerOp upperOp upper) version
188245
189246encode :: Constraint -> E.Value
190247encode constraint =
191− E.chars (toChars constraint)
248+ E.string (toString constraint)
192249
193250
194251decoder :: D.Decoder Error Constraint
195252decoder =
196− D.customString parser BadFormat
253+ do str <- D.string
254+ case fromString str of
255+ Right constraint ->
256+ return constraint
257+
258+ Left err ->
259+ D.failure err
197260
198261
199262
@@ -216,45 +279,4 @@ instance Binary Op where
216279 case n of
217280 0 -> return Less
218281 1 -> return LessOrEqual
219− _ -> fail "binary encoding of Op was corrupted"
220−
221−
222−
223−-- PARSER
224−
225−
226−data Error
227− = BadFormat Row Col
228− | InvalidRange V.Version V.Version
229−
230−
231−parser :: P.Parser Error Constraint
232−parser =
233− do lower <- parseVersion
234− P.word1 0x20 {- -} BadFormat
235− loOp <- parseOp
236− P.word1 0x20 {- -} BadFormat
237− P.word1 0x76 {-v-} BadFormat
238− P.word1 0x20 {- -} BadFormat
239− hiOp <- parseOp
240− P.word1 0x20 {- -} BadFormat
241− higher <- parseVersion
242− P.Parser $ \state@(P.State _ _ _ _ row col) _ eok _ eerr ->
243− if lower < higher
244− then eok (Range lower loOp hiOp higher) state
245− else eerr row col (\_ _ -> InvalidRange lower higher)
246−
247−
248−parseVersion :: P.Parser Error V.Version
249−parseVersion =
250− P.specialize (\(r,c) _ _ -> BadFormat r c) V.parser
251−
252−
253−parseOp :: P.Parser Error Op
254−parseOp =
255− do P.word1 0x3C {-<-} BadFormat
256− P.oneOfWithFallback
257− [ do P.word1 0x3D {-=-} BadFormat
258− return LessOrEqual
259− ]
260− Less
282+ _ -> error "binary encoding of Op was corrupted"
compiler/src/Elm/Docs.hs+158−218
@@ -1,7 +1,8 @@
11{-# OPTIONS_GHC -Wall #-}
2−{-# LANGUAGE BangPatterns, MultiWayIf, OverloadedStrings, UnboxedTuples #-}
2+{-# LANGUAGE OverloadedStrings #-}
33module Elm.Docs
44 ( Documentation
5+ , toDict
56 , Module(..)
67 , fromModule
78 , Union(..)
@@ -17,35 +18,33 @@ module Elm.Docs
1718 where
1819
1920
20−import qualified Data.Coerce as Coerce
21+import qualified Data.ByteString as B
2122import qualified Data.List as List
2223import Data.Map ((!))
2324import qualified Data.Map as Map
24−import qualified Data.Map.Merge.Strict as Map
2525import qualified Data.Name as Name
26−import qualified Data.NonEmptyList as NE
27−import qualified Data.OneOrMore as OneOrMore
28−import Data.Word (Word8)
29−import Foreign.Ptr (Ptr, plusPtr)
26+import qualified Data.Text as Text
27+import qualified Data.Text.Encoding as Text
3028
3129import qualified AST.Canonical as Can
32−import qualified AST.Source as Src
3330import qualified AST.Utils.Binop as Binop
31+import qualified Data.OneOrMore as OneOrMore
3432import qualified Elm.Compiler.Type as Type
3533import qualified Elm.Compiler.Type.Extract as Extract
3634import qualified Elm.ModuleName as ModuleName
3735import qualified Json.Decode as D
3836import qualified Json.Encode as E
3937import Json.Encode ((==>))
40−import qualified Json.String as Json
41−import Parse.Primitives (Row, Col, word1)
42−import qualified Parse.Primitives as P
43−import qualified Parse.Space as Space
44−import qualified Parse.Symbol as Symbol
45−import qualified Parse.Variable as Var
4638import qualified Reporting.Annotation as A
39+import qualified Reporting.Error as Error
4740import qualified Reporting.Error.Docs as E
41+import qualified Reporting.Region as R
4842import qualified Reporting.Result as Result
43+import Parse.Primitives (Parser)
44+import qualified Parse.Primitives as P
45+import qualified Parse.Primitives.Symbol as Symbol
46+import qualified Parse.Primitives.Variable as Var
47+import qualified Parse.Primitives.Whitespace as W
4948
5049
5150
@@ -56,6 +55,21 @@ type Documentation =
5655 Map.Map Name.Name Module
5756
5857
58+toDict :: [Module] -> Documentation
59+toDict modules =
60+ Map.fromList (map toPair modules)
61+
62+
63+
64+toPair :: Module -> (Name.Name, Module)
65+toPair modul@(Module name _ _ _ _ _) =
66+ (name, modul)
67+
68+
69+
70+-- MODULES
71+
72+
5973data Module =
6074 Module
6175 { _name :: Name.Name
@@ -66,7 +80,9 @@ data Module =
6680 , _binops :: Map.Map Name.Name Binop
6781 }
6882
69−type Comment = Json.String
83+
84+type Comment = Text.Text
85+
7086
7187data Alias = Alias Comment [Name.Name] Type.Type
7288data Union = Union Comment [Name.Name] [(Name.Name, [Type.Type])]
@@ -75,19 +91,14 @@ data Binop = Binop Comment Type.Type Binop.Associativity Binop.Precedence
7591
7692
7793
78−-- JSON
79−
80−
81−encode :: Documentation -> E.Value
82−encode docs =
83− E.list encodeModule (Map.elems docs)
94+-- JSON ENCODE / DECODE
8495
8596
86−encodeModule :: Module -> E.Value
87−encodeModule (Module name comment unions aliases values binops) =
97+encode :: Module -> E.Value
98+encode (Module name comment unions aliases values binops) =
8899 E.object $
89100 [ "name" ==> ModuleName.encode name
90− , "comment" ==> E.string comment
101+ , "comment" ==> E.text comment
91102 , "unions" ==> E.list encodeUnion (Map.toList unions)
92103 , "aliases" ==> E.list encodeAlias (Map.toList aliases)
93104 , "values" ==> E.list encodeValue (Map.toList values)
@@ -96,31 +107,16 @@ encodeModule (Module name comment unions aliases values binops) =
96107
97108
98109data Error
99− = BadAssociativity
100− | BadModuleName
110+ = BadAssociativity Text.Text
111+ | BadName
101112 | BadType
102113
103114
104−decoder :: D.Decoder Error Documentation
115+decoder :: D.Decoder Error Module
105116decoder =
106− toDict <$> D.list moduleDecoder
107−
108−
109−toDict :: [Module] -> Documentation
110−toDict modules =
111− Map.fromList (map toDictHelp modules)
112−
113−
114−toDictHelp :: Module -> (Name.Name, Module)
115−toDictHelp modul@(Module name _ _ _ _ _) =
116− (name, modul)
117−
118−
119−moduleDecoder :: D.Decoder Error Module
120−moduleDecoder =
121117 Module
122− <$> D.field "name" moduleNameDecoder
123− <*> D.field "comment" D.string
118+ <$> D.field "name" nameDecoder
119+ <*> D.field "comment" D.text
124120 <*> D.field "unions" (dictDecoder union)
125121 <*> D.field "aliases" (dictDecoder alias)
126122 <*> D.field "values" (dictDecoder value)
@@ -135,18 +131,13 @@ dictDecoder entryDecoder =
135131named :: D.Decoder Error a -> D.Decoder Error (Name.Name, a)
136132named entryDecoder =
137133 (,)
138− <$> D.field "name" nameDecoder
134+ <$> D.field "name" D.name
139135 <*> entryDecoder
140136
141137
142−nameDecoder :: D.Decoder e Name.Name
138+nameDecoder :: D.Decoder Error Name.Name
143139nameDecoder =
144− fmap Coerce.coerce D.string
145−
146−
147−moduleNameDecoder :: D.Decoder Error ModuleName.Raw
148−moduleNameDecoder =
149− D.mapError (const BadModuleName) ModuleName.decoder
140+ D.mapError (const BadName) ModuleName.decoder
150141
151142
152143typeDecoder :: D.Decoder Error Type.Type
@@ -162,7 +153,7 @@ encodeUnion :: (Name.Name, Union) -> E.Value
162153encodeUnion (name, Union comment args cases) =
163154 E.object
164155 [ "name" ==> E.name name
165− , "comment" ==> E.string comment
156+ , "comment" ==> E.text comment
166157 , "args" ==> E.list E.name args
167158 , "cases" ==> E.list encodeCase cases
168159 ]
@@ -171,8 +162,8 @@ encodeUnion (name, Union comment args cases) =
171162union :: D.Decoder Error Union
172163union =
173164 Union
174− <$> D.field "comment" D.string
175− <*> D.field "args" (D.list nameDecoder)
165+ <$> D.field "comment" D.text
166+ <*> D.field "args" (D.list D.name)
176167 <*> D.field "cases" (D.list caseDecoder)
177168
178169
@@ -183,7 +174,7 @@ encodeCase ( tag, args ) =
183174
184175caseDecoder :: D.Decoder Error ( Name.Name, [Type.Type] )
185176caseDecoder =
186− D.pair nameDecoder (D.list typeDecoder)
177+ D.pair D.name (D.list typeDecoder)
187178
188179
189180
@@ -194,7 +185,7 @@ encodeAlias :: (Name.Name, Alias) -> E.Value
194185encodeAlias ( name, Alias comment args tipe) =
195186 E.object
196187 [ "name" ==> E.name name
197− , "comment" ==> E.string comment
188+ , "comment" ==> E.text comment
198189 , "args" ==> E.list E.name args
199190 , "type" ==> Type.encode tipe
200191 ]
@@ -203,8 +194,8 @@ encodeAlias ( name, Alias comment args tipe) =
203194alias :: D.Decoder Error Alias
204195alias =
205196 Alias
206− <$> D.field "comment" D.string
207− <*> D.field "args" (D.list nameDecoder)
197+ <$> D.field "comment" D.text
198+ <*> D.field "args" (D.list D.name)
208199 <*> D.field "type" typeDecoder
209200
210201
@@ -216,7 +207,7 @@ encodeValue :: (Name.Name, Value) -> E.Value
216207encodeValue (name, Value comment tipe) =
217208 E.object
218209 [ "name" ==> E.name name
219− , "comment" ==> E.string comment
210+ , "comment" ==> E.text comment
220211 , "type" ==> Type.encode tipe
221212 ]
222213
@@ -224,7 +215,7 @@ encodeValue (name, Value comment tipe) =
224215value :: D.Decoder Error Value
225216value =
226217 Value
227− <$> D.field "comment" D.string
218+ <$> D.field "comment" D.text
228219 <*> D.field "type" typeDecoder
229220
230221
@@ -236,7 +227,7 @@ encodeBinop :: (Name.Name, Binop) -> E.Value
236227encodeBinop (name, Binop comment tipe assoc prec) =
237228 E.object
238229 [ "name" ==> E.name name
239− , "comment" ==> E.string comment
230+ , "comment" ==> E.text comment
240231 , "type" ==> Type.encode tipe
241232 , "associativity" ==> encodeAssoc assoc
242233 , "precedence" ==> encodePrec prec
@@ -246,7 +237,7 @@ encodeBinop (name, Binop comment tipe assoc prec) =
246237binop :: D.Decoder Error Binop
247238binop =
248239 Binop
249− <$> D.field "comment" D.string
240+ <$> D.field "comment" D.text
250241 <*> D.field "type" typeDecoder
251242 <*> D.field "associativity" assocDecoder
252243 <*> D.field "precedence" precDecoder
@@ -259,23 +250,19 @@ binop =
259250encodeAssoc :: Binop.Associativity -> E.Value
260251encodeAssoc assoc =
261252 case assoc of
262− Binop.Left -> E.chars "left"
263− Binop.Non -> E.chars "non"
264− Binop.Right -> E.chars "right"
253+ Binop.Left -> E.text "left"
254+ Binop.Non -> E.text "non"
255+ Binop.Right -> E.text "right"
265256
266257
267258assocDecoder :: D.Decoder Error Binop.Associativity
268259assocDecoder =
269− let
270− left = Json.fromChars "left"
271− non = Json.fromChars "non"
272− right = Json.fromChars "right"
273− in
274− do str <- D.string
275− if | str == left -> return Binop.Left
276− | str == non -> return Binop.Non
277− | str == right -> return Binop.Right
278− | otherwise -> D.failure BadAssociativity
260+ do txt <- D.text
261+ case txt of
262+ "left" -> D.succeed Binop.Left
263+ "non" -> D.succeed Binop.Non
264+ "right" -> D.succeed Binop.Right
265+ _ -> D.fail (BadAssociativity txt)
279266
280267
281268
@@ -296,190 +283,142 @@ precDecoder =
296283-- FROM MODULE
297284
298285
299−fromModule :: Can.Module -> Either E.Error Module
300−fromModule modul@(Can.Module _ exports docs _ _ _ _ _) =
286+fromModule :: Can.Module -> Result.Result i w Error.Error Module
287+fromModule (Can.Module name docs exports decls unions aliases binops effects) =
301288 case exports of
302289 Can.ExportEverything region ->
303− Left (E.ImplicitExposing region)
290+ Result.throw $ Error.Docs $ E.ImplicitExposing region
304291
305292 Can.Export exportDict ->
306293 case docs of
307− Src.NoDocs region ->
308− Left (E.NoDocs region)
294+ Can.NoDocs region ->
295+ Result.throw $ Error.Docs $ E.NoDocs region
309296
310− Src.YesDocs overview comments ->
311− do names <- parseOverview overview
312− checkNames exportDict names
313− checkDefs exportDict overview (Map.fromList comments) modul
297+ Can.YesDocs region overview comments ->
298+ do names <- parseOverview region overview
299+ Result.mapError Error.Docs $
300+ do checkNames exportDict names
301+ let types = gatherTypes decls Map.empty
302+ let info = Info comments types unions aliases binops effects
303+ inserters <- Map.traverseWithKey (checkExport info) exportDict
304+ return $ foldr ($) (emptyModule name overview) inserters
305+
306+
307+emptyModule :: ModuleName.Canonical -> B.ByteString -> Module
308+emptyModule (ModuleName.Canonical _ name) overview =
309+ Module name (Text.decodeUtf8 overview) Map.empty Map.empty Map.empty Map.empty
314310
315311
316312
317313-- PARSE OVERVIEW
318314
319315
320−parseOverview :: Src.Comment -> Either E.Error [A.Located Name.Name]
321−parseOverview (Src.Comment snippet) =
322− case P.fromSnippet (chompOverview []) E.BadEnd snippet of
316+parseOverview :: R.Region -> B.ByteString -> Result.Result i w Error.Error [A.Located Name.Name]
317+parseOverview (R.Region (R.Position row col) _) overview =
318+ case P.runAt row (col + 3) (chompOverview []) overview of
323319 Left err ->
324− Left (E.SyntaxProblem err)
320+ Result.throw (Error.Syntax err)
325321
326322 Right names ->
327− Right names
328−
329−
330−type Parser a =
331− P.Parser E.SyntaxProblem a
323+ Result.ok names
332324
333325
334326chompOverview :: [A.Located Name.Name] -> Parser [A.Located Name.Name]
335327chompOverview names =
336− do isDocs <- chompUntilDocs
328+ do isDocs <- W.chompUntilDocs
337329 if isDocs
338− then
339− do Space.chomp E.Space
340− chompOverview =<< chompDocs names
341− else
342− return names
330+ then chompOverviewHelp names
331+ else return names
332+
333+
334+chompOverviewHelp :: [A.Located Name.Name] -> Parser [A.Located Name.Name]
335+chompOverviewHelp names =
336+ do pos <- P.getPosition
337+ (W.SPos spos) <- W.whitespace
338+ if pos == spos
339+ then chompOverview names
340+ else chompOverview =<< chompDocs names
343341
344342
345343chompDocs :: [A.Located Name.Name] -> Parser [A.Located Name.Name]
346344chompDocs names =
347− do name <-
348− P.addLocation $
349− P.oneOf E.Name
350− [ Var.lower E.Name
351− , Var.upper E.Name
352− , chompOperator
353− ]
354−
355− Space.chomp E.Space
356−
357− P.oneOfWithFallback
358− [ do pos <- P.getPosition
359− Space.checkIndent pos E.Comma
360− word1 0x2C {-,-} E.Comma
361− Space.chomp E.Space
345+ do name <- P.addLocation (P.oneOf [ Var.lower, Var.upper, chompBinop ])
346+ spos <- W.whitespace
347+ P.oneOf
348+ [ do P.checkSpace spos
349+ Symbol.comma
350+ P.spaces
362351 chompDocs (name:names)
352+ , return (name:names)
363353 ]
364− (name:names)
365−
366−
367−chompOperator :: Parser Name.Name
368−chompOperator =
369− do word1 0x28 {-(-} E.Op
370− op <- Symbol.operator E.Op E.OpBad
371− word1 0x29 {-)-} E.Op
372− return op
373−
374−
375−-- TODO add rule that @docs must be after newline in 0.20
376−--
377−chompUntilDocs :: Parser Bool
378−chompUntilDocs =
379− P.Parser $ \(P.State src pos end indent row col) cok _ _ _ ->
380− let
381− (# isDocs, newPos, newRow, newCol #) = untilDocs pos end row col
382− !newState = P.State src newPos end indent newRow newCol
383− in
384− cok isDocs newState
385−
386−
387−untilDocs :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> (# Bool, Ptr Word8, Row, Col #)
388−untilDocs pos end row col =
389− if pos >= end then
390− (# False, pos, row, col #)
391− else
392− let !word = P.unsafeIndex pos in
393− if word == 0x0A {-\n-} then
394− untilDocs (plusPtr pos 1) end (row + 1) 1
395− else
396− let !pos5 = plusPtr pos 5 in
397− if pos5 <= end
398− && P.unsafeIndex ( pos ) == 0x40 {-@-}
399− && P.unsafeIndex (plusPtr pos 1) == 0x64 {-d-}
400− && P.unsafeIndex (plusPtr pos 2) == 0x6F {-o-}
401− && P.unsafeIndex (plusPtr pos 3) == 0x63 {-c-}
402− && P.unsafeIndex (plusPtr pos 4) == 0x73 {-s-}
403− && Var.getInnerWidth pos5 end == 0
404− then
405− (# True, pos5, row, col + 5 #)
406− else
407− let !newPos = plusPtr pos (P.getCharWidth word) in
408− untilDocs newPos end row (col + 1)
354+
355+
356+chompBinop :: Parser Name.Name
357+chompBinop =
358+ do Symbol.leftParen
359+ name <- Symbol.binop
360+ Symbol.rightParen
361+ return name
409362
410363
411364
412365-- CHECK NAMES
413366
414367
415−checkNames :: Map.Map Name.Name (A.Located Can.Export) -> [A.Located Name.Name] -> Either E.Error ()
416−checkNames exports names =
417− let
418− docs = List.foldl' addName Map.empty names
419− loneDoc = Map.traverseMissing onlyInDocs
420− loneExport = Map.traverseMissing onlyInExports
421− checkBoth = Map.zipWithAMatched (\n _ r -> isUnique n r)
422− in
423− case Result.run (Map.mergeA loneExport loneDoc checkBoth exports docs) of
424− (_, Right _) -> Right ()
425− (_, Left es) -> Left (E.NameProblems (OneOrMore.destruct NE.List es))
368+type Result i w a =
369+ Result.Result i w E.Error a
370+
371+
372+type Dups =
373+ Map.Map Name.Name (OneOrMore.OneOrMore R.Region)
426374
427375
428−type DocNameRegions =
429− Map.Map Name.Name (OneOrMore.OneOrMore A.Region)
376+checkNames :: Map.Map Name.Name (A.Located Can.Export) -> [A.Located Name.Name] -> Result i w ()
377+checkNames exports names =
378+ do docs <- Map.traverseWithKey isUnique (List.foldl' addName Map.empty names)
379+ let overlap = Map.size (Map.intersection docs exports)
380+ if Map.size exports == overlap && overlap == Map.size docs
381+ then Result.ok ()
382+ else
383+ do _ <- Map.traverseWithKey onlyInDocs (Map.difference docs exports)
384+ _ <- Map.traverseWithKey onlyInExports (Map.difference exports docs)
385+ Result.ok ()
430386
431387
432−addName :: DocNameRegions -> A.Located Name.Name -> DocNameRegions
388+addName :: Dups -> A.Located Name.Name -> Dups
433389addName dict (A.At region name) =
434390 Map.insertWith OneOrMore.more name (OneOrMore.one region) dict
435391
436392
437−isUnique :: Name.Name -> OneOrMore.OneOrMore A.Region -> Result.Result i w E.NameProblem A.Region
393+isUnique :: Name.Name -> OneOrMore.OneOrMore R.Region -> Result i w R.Region
438394isUnique name regions =
439395 case regions of
440396 OneOrMore.One region ->
441397 Result.ok region
442398
443− OneOrMore.More left right ->
444− let (r1, r2) = OneOrMore.getFirstTwo left right in
445− Result.throw (E.NameDuplicate name r1 r2)
399+ OneOrMore.More _ _ ->
400+ let (r1:r2:_) = OneOrMore.toList regions in
401+ Result.throw (E.Duplicate name r1 r2)
446402
447403
448−onlyInDocs :: Name.Name -> OneOrMore.OneOrMore A.Region -> Result.Result i w E.NameProblem a
449−onlyInDocs name regions =
450− do region <- isUnique name regions
451− Result.throw $ E.NameOnlyInDocs name region
404+onlyInDocs :: Name.Name -> R.Region -> Result i w a
405+onlyInDocs name region =
406+ Result.throw $ E.OnlyInDocs name region
452407
453408
454−onlyInExports :: Name.Name -> A.Located Can.Export -> Result.Result i w E.NameProblem a
409+onlyInExports :: Name.Name -> A.Located Can.Export -> Result i w a
455410onlyInExports name (A.At region _) =
456− Result.throw $ E.NameOnlyInExports name region
457−
458−
459−
460−-- CHECK DEFS
461−
411+ Result.throw $ E.OnlyInExports name region
462412
463−checkDefs :: Map.Map Name.Name (A.Located Can.Export) -> Src.Comment -> Map.Map Name.Name Src.Comment -> Can.Module -> Either E.Error Module
464−checkDefs exportDict overview comments (Can.Module name _ _ decls unions aliases infixes effects) =
465− let
466− types = gatherTypes decls Map.empty
467− info = Info comments types unions aliases infixes effects
468− in
469− case Result.run (Map.traverseWithKey (checkExport info) exportDict) of
470− (_, Left problems ) -> Left $ E.DefProblems (OneOrMore.destruct NE.List problems)
471− (_, Right inserters) -> Right $ foldr ($) (emptyModule name overview) inserters
472413
473414
474−emptyModule :: ModuleName.Canonical -> Src.Comment -> Module
475−emptyModule (ModuleName.Canonical _ name) (Src.Comment overview) =
476− Module name (Json.fromComment overview) Map.empty Map.empty Map.empty Map.empty
415+-- CHECK EXPORTS
477416
478417
479418data Info =
480419 Info
481− { _iComments :: Map.Map Name.Name Src.Comment
482− , _iValues :: Map.Map Name.Name (Either A.Region Can.Type)
420+ { _iComments :: Map.Map Name.Name Comment
421+ , _iValues :: Types
483422 , _iUnions :: Map.Map Name.Name Can.Union
484423 , _iAliases :: Map.Map Name.Name Can.Alias
485424 , _iBinops :: Map.Map Name.Name Can.Binop
@@ -487,7 +426,7 @@ data Info =
487426 }
488427
489428
490−checkExport :: Info -> Name.Name -> A.Located Can.Export -> Result.Result i w E.DefProblem (Module -> Module)
429+checkExport :: Info -> Name.Name -> A.Located Can.Export -> Result i w (Module -> Module)
491430checkExport info name (A.At region export) =
492431 case export of
493432 Can.ExportValue ->
@@ -528,23 +467,23 @@ checkExport info name (A.At region export) =
528467 m { _values = Map.insert name (Value comment tipe) (_values m) }
529468
530469
531−getComment :: A.Region -> Name.Name -> Info -> Result.Result i w E.DefProblem Comment
470+getComment :: R.Region -> Name.Name -> Info -> Result i w Comment
532471getComment region name info =
533472 case Map.lookup name (_iComments info) of
534473 Nothing ->
535474 Result.throw (E.NoComment name region)
536475
537− Just (Src.Comment snippet) ->
538− Result.ok (Json.fromComment snippet)
476+ Just comment ->
477+ Result.ok comment
539478
540479
541−getType :: Name.Name -> Info -> Result.Result i w E.DefProblem Type.Type
480+getType :: Name.Name -> Info -> Result i w Type.Type
542481getType name info =
543482 case _iValues info ! name of
544− Left region ->
545− Result.throw (E.NoAnnotation name region)
483+ A.At defRegion Nothing ->
484+ Result.throw (E.NoAnnotation name defRegion)
546485
547− Right tipe ->
486+ A.At _ (Just tipe) ->
548487 Result.ok (Extract.fromType tipe)
549488
550489
@@ -558,7 +497,7 @@ dector (Can.Ctor name _ _ args) =
558497
559498
560499type Types =
561− Map.Map Name.Name (Either A.Region Can.Type)
500+ Map.Map Name.Name (A.Located (Maybe Can.Type))
562501
563502
564503gatherTypes :: Can.Decls -> Types -> Types
@@ -567,8 +506,8 @@ gatherTypes decls types =
567506 Can.Declare def subDecls ->
568507 gatherTypes subDecls (addDef types def)
569508
570− Can.DeclareRec def defs subDecls ->
571− gatherTypes subDecls (List.foldl' addDef (addDef types def) defs)
509+ Can.DeclareRec defs subDecls ->
510+ gatherTypes subDecls (List.foldl' addDef types defs)
572511
573512 Can.SaveTheEnvironment ->
574513 types
@@ -578,10 +517,11 @@ addDef :: Types -> Can.Def -> Types
578517addDef types def =
579518 case def of
580519 Can.Def (A.At region name) _ _ ->
581− Map.insert name (Left region) types
520+ Map.insert name (A.At region Nothing) types
582521
583− Can.TypedDef (A.At _ name) _ typedArgs _ resultType ->
522+ Can.TypedDef (A.At region name) _ typedArgs _ resultType ->
584523 let
585− tipe = foldr Can.TLambda resultType (map snd typedArgs)
524+ tipe =
525+ foldr Can.TLambda resultType (map snd typedArgs)
586526 in
587− Map.insert name (Right tipe) types
527+ Map.insert name (A.At region (Just tipe)) types
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− _ -> fail "binary encoding of Union was corrupted"
218+ _ -> error "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− _ -> fail "binary encoding of Alias was corrupted"
232+ _ -> error "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− _ -> fail "binary encoding of DependencyInterface was corrupted"
254+ _ -> error "binary encoding of DependencyInterface was corrupted"
compiler/src/Elm/Kernel.hs+46−48
@@ -11,14 +11,14 @@ module Elm.Kernel
1111
1212import Control.Monad (liftM, liftM2)
1313import Data.Binary (Binary, get, put, getWord8, putWord8)
14−import qualified Data.ByteString.Internal as B
14+import qualified Data.ByteString as BS
15+import Data.Coerce (coerce)
1516import qualified Data.List as List
1617import qualified Data.Map as Map
1718import qualified Data.Name as Name
18−import Data.Word (Word8)
19−import Foreign.Ptr (Ptr, plusPtr, minusPtr)
20−import Foreign.ForeignPtr (ForeignPtr)
21−import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
19+import qualified Data.Utf8 as Utf8
20+import Data.Word (Word8, Word16)
21+import Foreign.Ptr (Ptr, plusPtr)
2222
2323import qualified AST.Source as Src
2424import qualified Elm.ModuleName as ModuleName
@@ -36,7 +36,7 @@ import qualified Reporting.Annotation as A
3636
3737
3838data Chunk
39− = JS B.ByteString
39+ = JS (Utf8.VeryLong UNCHECKED)
4040 | ElmVar ModuleName.Canonical Name.Name
4141 | JsVar Name.Name Name.Name
4242 | ElmField Name.Name
@@ -46,6 +46,9 @@ data Chunk
4646 | Prod
4747
4848
49+data UNCHECKED
50+
51+
4952
5053-- COUNT FIELDS
5154
@@ -80,13 +83,13 @@ type Foreigns =
8083 Map.Map ModuleName.Raw Pkg.Name
8184
8285
83−fromByteString :: Pkg.Name -> Foreigns -> B.ByteString -> Maybe Content
86+fromByteString :: Pkg.Name -> Foreigns -> BS.ByteString -> Maybe Content
8487fromByteString pkg foreigns bytes =
85− case P.fromByteString (parser pkg foreigns) toError bytes of
86− Right content ->
88+ case P.fromByteString (parser pkg foreigns) bytes of
89+ P.Ok content _ ->
8790 Just content
8891
89− Left () ->
92+ P.Err () ->
9093 Nothing
9194
9295
@@ -117,21 +120,21 @@ ignoreError _ _ _ =
117120
118121parseChunks :: VarTable -> Enums -> Fields -> Parser () [Chunk]
119122parseChunks vtable enums fields =
120− P.Parser $ \(P.State src pos end indent row col) cok _ cerr _ ->
123+ P.Parser $ \(P.State pos end indent row col) cok _ cerr _ ->
121124 let
122125 (# chunks, newPos, newRow, newCol #) =
123− chompChunks vtable enums fields src pos end row col pos []
126+ chompChunks vtable enums fields pos end row col pos []
124127 in
125128 if newPos == end then
126− cok chunks (P.State src newPos end indent newRow newCol)
129+ cok chunks (P.State newPos end indent newRow newCol)
127130 else
128131 cerr row col toError
129132
130133
131−chompChunks :: VarTable -> Enums -> Fields -> ForeignPtr Word8 -> Ptr Word8 -> Ptr Word8 -> Row -> Col -> Ptr Word8 -> [Chunk] -> (# [Chunk], Ptr Word8, Row, Col #)
132−chompChunks vs es fs src pos end row col lastPos revChunks =
134+chompChunks :: VarTable -> Enums -> Fields -> Ptr Word8 -> Ptr Word8 -> Word16 -> Word16 -> Ptr Word8 -> [Chunk] -> (# [Chunk], Ptr Word8, Word16, Word16 #)
135+chompChunks vs es fs pos end row col lastPos revChunks =
133136 if pos >= end then
134− let !js = toByteString src lastPos end in
137+ let !js = Utf8.fromPtr lastPos end in
135138 (# reverse (JS js : revChunks), pos, row, col #)
136139
137140 else
@@ -142,34 +145,24 @@ chompChunks vs es fs src pos end row col lastPos revChunks =
142145 !pos3 = plusPtr pos 3
143146 in
144147 if pos3 <= end && unsafeIndex pos1 == 0x5F {-_-} then
145− let !js = toByteString src lastPos pos in
146− chompTag vs es fs src pos3 end row (col + 3) (JS js : revChunks)
148+ let !js = Utf8.fromPtr lastPos pos in
149+ chompTag vs es fs pos3 end row (col + 3) (JS js : revChunks)
147150 else
148− chompChunks vs es fs src pos1 end row (col + 1) lastPos revChunks
151+ chompChunks vs es fs pos1 end row (col + 1) lastPos revChunks
149152
150153 else if word == 0x0A {-\n-} then
151− chompChunks vs es fs src (plusPtr pos 1) end (row + 1) 1 lastPos revChunks
154+ chompChunks vs es fs (plusPtr pos 1) end (row + 1) 1 lastPos revChunks
152155
153156 else
154157 let
155− !newPos = plusPtr pos (getCharWidth word)
158+ !newPos = plusPtr pos (getCharWidth pos end word)
156159 in
157− chompChunks vs es fs src newPos end row (col + 1) lastPos revChunks
158−
159−
160−toByteString :: ForeignPtr Word8 -> Ptr Word8 -> Ptr Word8 -> B.ByteString
161−toByteString src pos end =
162− let
163− !off = minusPtr pos (unsafeForeignPtrToPtr src)
164− !len = minusPtr end pos
165− in
166− B.PS src off len
167−
160+ chompChunks vs es fs newPos end row (col + 1) lastPos revChunks
168161
169162
170163-- relies on external checks in chompChunks
171−chompTag :: VarTable -> Enums -> Fields -> ForeignPtr Word8 -> Ptr Word8 -> Ptr Word8 -> Row -> Col -> [Chunk] -> (# [Chunk], Ptr Word8, Row, Col #)
172−chompTag vs es fs src pos end row col revChunks =
164+chompTag :: VarTable -> Enums -> Fields -> Ptr Word8 -> Ptr Word8 -> Word16 -> Word16 -> [Chunk] -> (# [Chunk], Ptr Word8, Word16, Word16 #)
165+chompTag vs es fs pos end row col revChunks =
173166 let
174167 (# newPos, newCol #) = Var.chompInnerChars pos end col
175168 !tagPos = plusPtr pos (-1)
@@ -179,7 +172,7 @@ chompTag vs es fs src pos end row col revChunks =
179172 let
180173 !name = Name.fromPtr pos newPos
181174 in
182− chompChunks vs es fs src newPos end row newCol newPos $
175+ chompChunks vs es fs newPos end row newCol newPos $
183176 ElmField name : revChunks
184177 else
185178 let
@@ -190,7 +183,7 @@ chompTag vs es fs src pos end row col revChunks =
190183 (enum, newEnums) =
191184 lookupEnum (word - 0x30) name es
192185 in
193− chompChunks vs newEnums fs src newPos end row newCol newPos $
186+ chompChunks vs newEnums fs newPos end row newCol newPos $
194187 JsEnum enum : revChunks
195188
196189 else if 0x61 {-a-} <= word && word <= 0x7A {-z-} then
@@ -198,19 +191,19 @@ chompTag vs es fs src pos end row col revChunks =
198191 (field, newFields) =
199192 lookupField name fs
200193 in
201− chompChunks vs es newFields src newPos end row newCol newPos $
194+ chompChunks vs es newFields newPos end row newCol newPos $
202195 JsField field : revChunks
203196
204197 else if name == "DEBUG" then
205− chompChunks vs es fs src newPos end row newCol newPos (Debug : revChunks)
198+ chompChunks vs es fs newPos end row newCol newPos (Debug : revChunks)
206199
207200 else if name == "PROD" then
208− chompChunks vs es fs src newPos end row newCol newPos (Prod : revChunks)
201+ chompChunks vs es fs newPos end row newCol newPos (Prod : revChunks)
209202
210203 else
211204 case Map.lookup name vs of
212205 Just chunk ->
213− chompChunks vs es fs src newPos end row newCol newPos (chunk : revChunks)
206+ chompChunks vs es fs newPos end row newCol newPos (chunk : revChunks)
214207
215208 Nothing ->
216209 (# revChunks, pos, row, col #)
@@ -319,19 +312,19 @@ toNames exposing =
319312 map toName exposedList
320313
321314
322−toName :: Src.Exposed -> Name.Name
323−toName exposed =
315+toName :: A.Located Src.Exposed -> Name.Name
316+toName (A.At _ exposed) =
324317 case exposed of
325− Src.Lower (A.At _ name) ->
318+ Src.Lower name ->
326319 name
327320
328− Src.Upper (A.At _ name) Src.Private ->
321+ Src.Upper name Src.Private ->
329322 name
330323
331− Src.Upper _ (Src.Public _) ->
324+ Src.Upper _ Src.Public ->
332325 error "cannot have Maybe(..) syntax in kernel code header"
333326
334− Src.Operator _ _ ->
327+ Src.Operator _ ->
335328 error "cannot use binops in kernel code"
336329
337330
@@ -342,7 +335,7 @@ toName exposed =
342335instance Binary Chunk where
343336 put chunk =
344337 case chunk of
345− JS a -> putWord8 0 >> put a
338+ JS a -> putWord8 0 >> put (coerce a :: Utf8.String)
346339 ElmVar a b -> putWord8 1 >> put a >> put b
347340 JsVar a b -> putWord8 2 >> put a >> put b
348341 ElmField a -> putWord8 3 >> put a
@@ -354,7 +347,7 @@ instance Binary Chunk where
354347 get =
355348 do word <- getWord8
356349 case word of
357− 0 -> liftM JS get
350+ 0 -> liftM toJS get
358351 1 -> liftM2 ElmVar get get
359352 2 -> liftM2 JsVar get get
360353 3 -> liftM ElmField get
@@ -363,3 +356,8 @@ instance Binary Chunk where
363356 6 -> return Debug
364357 7 -> return Prod
365358 _ -> error "problem deserializing Elm.Kernel.Chunk"
359+
360+
361+toJS :: Utf8.String -> Chunk
362+toJS str =
363+ JS (coerce str)
compiler/src/Elm/Licenses.hs+25−25
@@ -83,61 +83,63 @@ check givenCode =
8383osiApprovedSpdxLicenses :: Map.Map Json.String [Char]
8484osiApprovedSpdxLicenses =
8585 Map.fromList
86− [ "0BSD" ==> "BSD Zero Clause License"
87− , "AAL" ==> "Attribution Assurance License"
88− , "AFL-1.1" ==> "Academic Free License v1.1"
86+ [ "AFL-1.1" ==> "Academic Free License v1.1"
8987 , "AFL-1.2" ==> "Academic Free License v1.2"
9088 , "AFL-2.0" ==> "Academic Free License v2.0"
9189 , "AFL-2.1" ==> "Academic Free License v2.1"
9290 , "AFL-3.0" ==> "Academic Free License v3.0"
93− , "AGPL-3.0" ==> "GNU Affero General Public License v3.0"
91+ , "APL-1.0" ==> "Adaptive Public License 1.0"
9492 , "Apache-1.1" ==> "Apache License 1.1"
9593 , "Apache-2.0" ==> "Apache License 2.0"
96− , "APL-1.0" ==> "Adaptive Public License 1.0"
9794 , "APSL-1.0" ==> "Apple Public Source License 1.0"
9895 , "APSL-1.1" ==> "Apple Public Source License 1.1"
9996 , "APSL-1.2" ==> "Apple Public Source License 1.2"
10097 , "APSL-2.0" ==> "Apple Public Source License 2.0"
10198 , "Artistic-1.0" ==> "Artistic License 1.0"
102− , "Artistic-1.0-cl8" ==> "Artistic License 1.0 w/clause 8"
10399 , "Artistic-1.0-Perl" ==> "Artistic License 1.0 (Perl)"
100+ , "Artistic-1.0-cl8" ==> "Artistic License 1.0 w/clause 8"
104101 , "Artistic-2.0" ==> "Artistic License 2.0"
102+ , "AAL" ==> "Attribution Assurance License"
103+ , "BSL-1.0" ==> "Boost Software License 1.0"
105104 , "BSD-2-Clause" ==> "BSD 2-clause \"Simplified\" License"
106105 , "BSD-3-Clause" ==> "BSD 3-clause \"New\" or \"Revised\" 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"
106+ , "0BSD" ==> "BSD Zero Clause License"
110107 , "CECILL-2.1" ==> "CeCILL Free Software License Agreement v2.1"
111108 , "CNRI-Python" ==> "CNRI Python License"
109+ , "CDDL-1.0" ==> "Common Development and Distribution License 1.0"
112110 , "CPAL-1.0" ==> "Common Public Attribution License 1.0"
113111 , "CPL-1.0" ==> "Common Public License 1.0"
112+ , "CATOSL-1.1" ==> "Computer Associates Trusted Open Source License 1.1"
114113 , "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"
121120 , "EUDatagrid" ==> "EU DataGrid Software License"
122121 , "EUPL-1.1" ==> "European Union Public License 1.1"
123122 , "Fair" ==> "Fair License"
124123 , "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"
127130 , "HPND" ==> "Historic Permission Notice and Disclaimer"
131+ , "IPL-1.0" ==> "IBM Public License v1.0"
128132 , "Intel" ==> "Intel Open Source License"
129133 , "IPA" ==> "IPA Font License"
130− , "IPL-1.0" ==> "IBM Public License v1.0"
131134 , "ISC" ==> "ISC License"
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"
135+ , "LPPL-1.3c" ==> "LaTeX Project Public License v1.3c"
135136 , "LiLiQ-P-1.1" ==> "Licence Libre du Québec – Permissive version 1.1"
136− , "LiLiQ-R-1.1" ==> "Licence Libre du Québec – Réciprocité version 1.1"
137137 , "LiLiQ-Rplus-1.1" ==> "Licence Libre du Québec – Réciprocité forte version 1.1"
138− , "LPL-1.0" ==> "Lucent Public License Version 1.0"
138+ , "LiLiQ-R-1.1" ==> "Licence Libre du Québec – Réciprocité version 1.1"
139139 , "LPL-1.02" ==> "Lucent Public License v1.02"
140− , "LPPL-1.3c" ==> "LaTeX Project Public License v1.3c"
140+ , "LPL-1.0" ==> "Lucent Public License Version 1.0"
141+ , "MS-PL" ==> "Microsoft Public License"
142+ , "MS-RL" ==> "Microsoft Reciprocal License"
141143 , "MirOS" ==> "MirOS Licence"
142144 , "MIT" ==> "MIT License"
143145 , "Motosoto" ==> "Motosoto License"
@@ -145,40 +147,38 @@ osiApprovedSpdxLicenses =
145147 , "MPL-1.1" ==> "Mozilla Public License 1.1"
146148 , "MPL-2.0" ==> "Mozilla Public License 2.0"
147149 , "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"
154153 , "NGPL" ==> "Nethack General Public License"
155154 , "Nokia" ==> "Nokia Open Source License"
156155 , "NPOSL-3.0" ==> "Non-Profit Open Software License 3.0"
157156 , "NTP" ==> "NTP License"
158157 , "OCLC-2.0" ==> "OCLC Research Public License 2.0"
159− , "OFL-1.1" ==> "SIL Open Font License 1.1"
160158 , "OGTSL" ==> "Open Group Test Suite License"
161− , "OSET-PL-2.1" ==> "OSET Public License version 2.1"
162159 , "OSL-1.0" ==> "Open Software License 1.0"
163160 , "OSL-2.0" ==> "Open Software License 2.0"
164161 , "OSL-2.1" ==> "Open Software License 2.1"
165162 , "OSL-3.0" ==> "Open Software License 3.0"
163+ , "OSET-PL-2.1" ==> "OSET Public License version 2.1"
166164 , "PHP-3.0" ==> "PHP License v3.0"
167165 , "PostgreSQL" ==> "PostgreSQL License"
168166 , "Python-2.0" ==> "Python License 2.0"
169167 , "QPL-1.0" ==> "Q Public License 1.0"
168+ , "RPSL-1.0" ==> "RealNetworks Public Source License v1.0"
170169 , "RPL-1.1" ==> "Reciprocal Public License 1.1"
171170 , "RPL-1.5" ==> "Reciprocal Public License 1.5"
172− , "RPSL-1.0" ==> "RealNetworks Public Source License v1.0"
173171 , "RSCPL" ==> "Ricoh Source Code Public License"
172+ , "OFL-1.1" ==> "SIL Open Font License 1.1"
174173 , "SimPL-2.0" ==> "Simple Public License 2.0"
175− , "SISSL" ==> "Sun Industry Standards Source License v1.1"
176174 , "Sleepycat" ==> "Sleepycat License"
175+ , "SISSL" ==> "Sun Industry Standards Source License v1.1"
177176 , "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"
179180 , "VSL-1.0" ==> "Vovida Software License v1.0"
180181 , "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+39−65
@@ -1,19 +1,18 @@
1−{-# LANGUAGE BangPatterns, OverloadedStrings, UnboxedTuples #-}
1+{-# LANGUAGE OverloadedStrings #-}
22module Elm.ModuleName
33 ( Raw
44 , toChars
5+ , toString
56 , toFilePath
67 , toHyphenPath
7− --
8+ , fromHyphenPath
89 , encode
910 , decoder
10− , parser
11− --
1211 , Canonical(..)
1312 , basics, char, string
1413 , maybe, result, list, array, dict, tuple
1514 , platform, cmd, sub
16− , debug
15+ , debug, bitwise
1716 , virtualDom
1817 , jsonDecode, jsonEncode
1918 , webgl, texture, vector2, vector3, vector4, matrix4
@@ -23,19 +22,15 @@ module Elm.ModuleName
2322
2423import Control.Monad (liftM2)
2524import Data.Binary (Binary(..))
25+import qualified Data.Char as Char
2626import qualified Data.Name as Name
2727import qualified Data.Utf8 as Utf8
28−import Data.Word (Word8)
29−import Foreign.Ptr (Ptr, plusPtr, minusPtr)
3028import Prelude hiding (maybe)
3129import qualified System.FilePath as FP
3230
3331import qualified Elm.Package as Pkg
34−import qualified Json.Decode as D
35−import qualified Json.Encode as E
36−import qualified Parse.Variable as Var
37−import qualified Parse.Primitives as P
38−import Parse.Primitives (Row, Col)
32+import qualified Json.Decode as Decode
33+import qualified Json.Encode as Encode
3934
4035
4136
@@ -50,6 +45,11 @@ toChars =
5045 Name.toChars
5146
5247
48+toString :: Raw -> Utf8.String
49+toString =
50+ Name.toUtf8
51+
52+
5353toFilePath :: Raw -> FilePath
5454toFilePath name =
5555 map (\c -> if c == '.' then FP.pathSeparator else c) (Name.toChars name)
@@ -60,68 +60,38 @@ toHyphenPath name =
6060 map (\c -> if c == '.' then '-' else c) (Name.toChars name)
6161
6262
63+fromHyphenPath :: Utf8.String -> Maybe Raw
64+fromHyphenPath str =
65+ let
66+ chunks =
67+ Utf8.split 0x2D {- - -} str
68+ in
69+ if all isGoodChunk chunks
70+ then Just (Name.fromUtf8 (Utf8.join 0x2E {- . -} chunks))
71+ else Nothing
72+
73+
6374
6475-- JSON
6576
6677
67−encode :: Raw -> E.Value
78+encode :: Raw -> Encode.Value
6879encode =
69− E.name
80+ Encode.name
7081
7182
72−decoder :: D.Decoder (Row, Col) Raw
83+decoder :: Decode.Decoder Utf8.String Raw
7384decoder =
74− D.customString parser (,)
75−
76−
77−
78−-- PARSER
85+ do str <- Decode.string
86+ if all isGoodChunk (Utf8.split 0x2E {- . -} str)
87+ then return (Name.fromUtf8 str)
88+ else Decode.failure str
7989
8090
81−parser :: P.Parser (Row, Col) Raw
82−parser =
83− P.Parser $ \(P.State src pos end indent row col) cok _ cerr eerr ->
84− let
85− (# isGood, newPos, newCol #) = chompStart pos end col
86− in
87− if isGood && minusPtr newPos pos < 256 then
88− let !newState = P.State src newPos end indent row newCol in
89− cok (Utf8.fromPtr pos newPos) newState
90−
91− else if col == newCol then
92− eerr row newCol (,)
93−
94− else
95− cerr row newCol (,)
96−
97−
98−chompStart :: Ptr Word8 -> Ptr Word8 -> Col -> (# Bool, Ptr Word8, Col #)
99−chompStart pos end col =
100− let
101− !width = Var.getUpperWidth pos end
102− in
103− if width == 0 then
104− (# False, pos, col #)
105− else
106− chompInner (plusPtr pos width) end (col + 1)
107−
108−
109−chompInner :: Ptr Word8 -> Ptr Word8 -> Col -> (# Bool, Ptr Word8, Col #)
110−chompInner pos end col =
111− if pos >= end then
112− (# True, pos, col #)
113− else
114− let
115− !word = P.unsafeIndex pos
116− !width = Var.getInnerWidthHelp pos end word
117− in
118− if width == 0 then
119− if word == 0x2E {-.-} then
120− chompStart (plusPtr pos 1) end (col + 1)
121− else
122− (# True, pos, col #)
123− else
124− chompInner (plusPtr pos width) end (col + 1)
91+isGoodChunk :: Utf8.String -> Bool
92+isGoodChunk chunk =
93+ Utf8.startsWithChar Char.isUpper chunk
94+ && Utf8.all (\c -> Char.isAlphaNum c || c == '_') chunk
12595
12696
12797
@@ -135,7 +105,6 @@ data Canonical =
135105 }
136106
137107
138−
139108-- INSTANCES
140109
141110
@@ -226,6 +195,11 @@ debug :: Canonical
226195debug = Canonical Pkg.core Name.debug
227196
228197
198+{-# NOINLINE bitwise #-}
199+bitwise :: Canonical
200+bitwise = Canonical Pkg.core Name.bitwise
201+
202+
229203
230204-- HTML
231205
compiler/src/Elm/Package.hs+15−5
@@ -31,6 +31,7 @@ module Elm.Package
3131import Control.Monad (liftM2)
3232import Data.Binary (Binary, get, put)
3333import qualified Data.Coerce as Coerce
34+import Data.Function (on)
3435import qualified Data.List as List
3536import qualified Data.Map as Map
3637import qualified Data.Name as Name
@@ -58,7 +59,6 @@ data Name =
5859 { _author :: !Author
5960 , _project :: !Project
6061 }
61− deriving (Ord)
6262
6363
6464type Author = Utf8.Utf8 AUTHOR
@@ -236,10 +236,12 @@ nearbyNames (Name author1 project1) possibleNames =
236236 authorDist = authorDistance (Utf8.toChars author1)
237237 projectDist = projectDistance (Utf8.toChars project1)
238238
239− nameDistance (Name author2 project2) =
240− authorDist author2 + projectDist project2
239+ addDistance name@(Name author2 project2) =
240+ ( authorDist author2 + projectDist project2, name )
241241 in
242− take 4 $ List.sortOn nameDistance possibleNames
242+ map snd $ take 4 $
243+ List.sortBy (compare `on` fst) $
244+ map addDistance possibleNames
243245
244246
245247authorDistance :: [Char] -> Author -> Int
@@ -268,11 +270,19 @@ instance Eq Canonical where
268270 version1 == version2 && package1 == package2
269271
270272
273+instance Ord Name where
274+ compare (Name author1 project1) (Name author2 project2) =
275+ case compare project1 project2 of
276+ LT -> LT
277+ EQ -> compare author1 author2
278+ GT -> GT
279+
280+
271281
272282-- BINARY
273283
274284
275−instance Binary Name where -- PERF try storing as a Word16
285+instance Binary Name where -- TODO try storing as a Word16
276286 get = liftM2 Name Utf8.getUnder256 Utf8.getUnder256
277287 put (Name a b) = Utf8.putUnder256 a >> Utf8.putUnder256 b
278288
compiler/src/Elm/String.hs+1
@@ -108,6 +108,7 @@ 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
111112writeCode :: MBA RealWorld -> Int -> Int -> ST RealWorld ()
112113writeCode mba offset code =
113114 do writeWord8 mba offset 0x5C {- \ -}
compiler/src/Generate/Html.hs+10−11
@@ -29,23 +29,22 @@ sandwich moduleName javascript =
2929
3030<body>
3131
32−<pre id="elm"></pre>
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>
3339
3440<script>
35−try {
3641|] <> javascript <> [r|
3742
43+try {
3844 var app = Elm.|] <> name <> [r|.init({ node: document.getElementById("elm") });
39−}
40−catch (e)
41−{
45+} catch (e) {
4246 // display initialization errors (e.g. bad flags, infinite recursion)
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;
47+ document.getElementById("elm").innerText = e;
4948 throw e;
5049}
5150</script>
compiler/src/Generate/JavaScript.hs+19−51
@@ -2,7 +2,6 @@
22module Generate.JavaScript
33 ( generate
44 , generateForRepl
5− , generateForReplEndpoint
65 )
76 where
87
@@ -86,9 +85,7 @@ generateForRepl ansi localizer (Opt.GlobalGraph graph _) home name (Can.Forall _
8685 debugState = addGlobal mode graph emptyState (Opt.Global ModuleName.debug "toString")
8786 evalState = addGlobal mode graph debugState (Opt.Global home name)
8887 in
89− "process.on('uncaughtException', function(err) { process.stderr.write(err.toString() + '\\n'); process.exit(1); });"
90− <> Functions.functions
91− <> stateToBuilder evalState
88+ stateToBuilder evalState
9289 <> print ansi localizer home name tipe
9390
9491
@@ -100,47 +97,14 @@ print ansi localizer home name tipe =
10097 tipeDoc = RT.canToDoc localizer RT.None tipe
10198 bool = if ansi then "true" else "false"
10299 in
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"
100+ "var _value = " <> toString <> "(" <> bool <> ", " <> value <> ");\n\
101+ \var _type = " <> B.stringUtf8 (show (D.toString tipeDoc)) <> ";\n\
102+ \function _print(t) { console.log(_value + (" <> bool <> " ? '\x1b[90m' + t + '\x1b[0m' : t)); }\n\
103+ \if (_value.length + 3 + _type.length >= 80 || _type.indexOf('\\n') >= 0) {\n\
104+ \ _print('\\n : ' + _type.split('\\n').join('\\n '));\n\
105+ \} else {\n\
106+ \ _print(' : ' + _type);\n\
107+ \}\n"
144108
145109
146110
@@ -292,7 +256,7 @@ generateCycle mode (Opt.Global home _) names values functions =
292256 "Some top-level definitions from `" <> Name.toBuilder (ModuleName._module home) <> "` are causing infinite recursion:\\n"
293257 <> drawCycle names
294258 <> "\\n\\nThese errors are very tricky, so read "
295− <> B.stringUtf8 (D.makeNakedLink "bad-recursion")
259+ <> B.stringUtf8 (D.makeNakedLink "halting-problem")
296260 <> " to learn how to fix it!"
297261 ]
298262
@@ -350,7 +314,7 @@ addChunk :: Mode.Mode -> K.Chunk -> B.Builder -> B.Builder
350314addChunk mode chunk builder =
351315 case chunk of
352316 K.JS javascript ->
353− B.byteString javascript <> builder
317+ Utf8.toBuilder javascript <> builder
354318
355319 K.ElmVar home name ->
356320 JsName.toBuilder (JsName.fromGlobal home name) <> builder
@@ -534,7 +498,7 @@ generateExports mode (Trie maybeMain subs) =
534498 <> List.foldl' (addSubTrie mode) "}" otherSubTries
535499
536500
537−addSubTrie :: Mode.Mode -> B.Builder -> (Name.Name, Trie) -> B.Builder
501+addSubTrie :: Mode.Mode -> B.Builder -> (Utf8.String, Trie) -> B.Builder
538502addSubTrie mode end (name, trie) =
539503 ",'" <> Utf8.toBuilder name <> "':" <> generateExports mode trie <> end
540504
@@ -546,7 +510,7 @@ addSubTrie mode end (name, trie) =
546510data Trie =
547511 Trie
548512 { _main :: Maybe (ModuleName.Canonical, Opt.Main)
549− , _subs :: Map.Map Name.Name Trie
513+ , _subs :: Map.Map Utf8.String Trie
550514 }
551515
552516
@@ -557,10 +521,14 @@ emptyTrie =
557521
558522addToTrie :: ModuleName.Canonical -> Opt.Main -> Trie -> Trie
559523addToTrie home@(ModuleName.Canonical _ moduleName) main trie =
560− merge trie $ segmentsToTrie home (Name.splitDots moduleName) main
524+ let
525+ segments =
526+ Utf8.split 0x2E {-.-} (Name.toUtf8 moduleName)
527+ in
528+ merge trie $ segmentsToTrie home segments main
561529
562530
563−segmentsToTrie :: ModuleName.Canonical -> [Name.Name] -> Opt.Main -> Trie
531+segmentsToTrie :: ModuleName.Canonical -> [Utf8.String] -> Opt.Main -> Trie
564532segmentsToTrie home segments main =
565533 case segments of
566534 [] ->
compiler/src/Generate/JavaScript/Builder.hs−13
@@ -28,19 +28,6 @@ import qualified Json.Encode as Json
2828-- EXPRESSIONS
2929
3030
31−-- NOTE: I tried making this create a B.Builder directly.
32−--
33−-- The hope was that it'd allocate less and speed things up, but it seemed
34−-- to be neutral for perf.
35−--
36−-- The downside is that Generate.JavaScript.Expression inspects the
37−-- structure of Expr and Stmt on some occassions to try to strip out
38−-- unnecessary closures. I think these closures are already avoided
39−-- by other logic in code gen these days, but I am not 100% certain.
40−--
41−-- For this to be worth it, I think it would be necessary to avoid
42−-- returning tuples when generating expressions.
43−--
4431data Expr
4532 = String Builder
4633 | Float Builder
compiler/src/Generate/JavaScript/Expression.hs+3−5
@@ -22,7 +22,6 @@ import qualified Data.Utf8 as Utf8
2222
2323import qualified AST.Canonical as Can
2424import qualified AST.Optimized as Opt
25−import qualified AST.Utils.Shader as Shader
2625import qualified Data.Index as Index
2726import qualified Elm.Compiler.Type as Type
2827import qualified Elm.Compiler.Type.Extract as Extract
@@ -33,7 +32,6 @@ import qualified Generate.JavaScript.Builder as JS
3332import qualified Generate.JavaScript.Name as JsName
3433import qualified Generate.Mode as Mode
3534import qualified Json.Encode as Encode
36−import Json.Encode ((==>))
3735import qualified Optimize.DecisionTree as DT
3836import qualified Reporting.Annotation as A
3937
@@ -191,7 +189,7 @@ generate mode expression =
191189 JS.Object (map toTranlation (Set.toList fields))
192190 in
193191 JsExpr $ JS.Object $
194− [ ( JsName.fromLocal "src", JS.String (Shader.toJsStringBuilder src) )
192+ [ ( JsName.fromLocal "src", JS.String (Utf8.toBuilder src) )
195193 , ( JsName.fromLocal "attributes", toTranslationObject attributes )
196194 , ( JsName.fromLocal "uniforms", toTranslationObject uniforms )
197195 ]
@@ -1065,6 +1063,6 @@ toDebugMetadata mode msgType =
10651063
10661064 Mode.Dev (Just interfaces) ->
10671065 JS.Json $ Encode.object $
1068− [ "versions" ==> Encode.object [ "elm" ==> V.encode V.compiler ]
1069− , "types" ==> Type.encodeMetadata (Extract.fromMsg interfaces msgType)
1066+ [ ("versions", Encode.object [ ("elm", V.encode V.compiler) ])
1067+ , ("types", Type.encodeMetadata (Extract.fromMsg interfaces msgType))
10701068 ]
compiler/src/Generate/JavaScript/Name.hs+12−22
@@ -62,13 +62,19 @@ fromLocal name =
6262
6363
6464fromGlobal :: ModuleName.Canonical -> Name.Name -> Name
65−fromGlobal home name =
66− Name $ homeToBuilder home <> usd <> Name.toBuilder name
65+fromGlobal (ModuleName.Canonical (Pkg.Name author project) home) name =
66+ Name $ Name.toEscapedBuilder 0x2D {- - -} 0x5F {- _ -} author
67+ <> "$" <> Name.toEscapedBuilder 0x2D {- - -} 0x5F {- _ -} project
68+ <> "$" <> Name.toEscapedBuilder 0x2E {- . -} 0x24 {- $ -} home
69+ <> "$" <> Name.toBuilder name
6770
6871
6972fromCycle :: ModuleName.Canonical -> Name.Name -> Name
70−fromCycle home name =
71− Name $ homeToBuilder home <> "$cyclic$" <> Name.toBuilder name
73+fromCycle (ModuleName.Canonical (Pkg.Name author project) home) name =
74+ Name $ Name.toEscapedBuilder 0x2D {- - -} 0x5F {- _ -} author
75+ <> "$" <> Name.toEscapedBuilder 0x2D {- - -} 0x5F {- _ -} project
76+ <> "$" <> Name.toEscapedBuilder 0x2E {- . -} 0x24 {- $ -} home
77+ <> "$cyclic$" <> Name.toBuilder name
7278
7379
7480fromKernel :: Name.Name -> Name.Name -> Name
@@ -76,17 +82,6 @@ fromKernel home name =
7682 Name ("_" <> Name.toBuilder home <> "_" <> Name.toBuilder name)
7783
7884
79−{-# INLINE homeToBuilder #-}
80−homeToBuilder :: ModuleName.Canonical -> B.Builder
81−homeToBuilder (ModuleName.Canonical (Pkg.Name author project) home) =
82− usd <>
83− Utf8.toEscapedBuilder 0x2D {- - -} 0x5F {- _ -} author
84− <> usd <>
85− Utf8.toEscapedBuilder 0x2D {- - -} 0x5F {- _ -} project
86− <> usd <>
87− Utf8.toEscapedBuilder 0x2E {- . -} 0x24 {- $ -} home
88−
89−
9085
9186-- TEMPORARY NAMES
9287
@@ -103,7 +98,7 @@ makeA n =
10398
10499makeLabel :: Name.Name -> Int -> Name
105100makeLabel name index =
106− Name (Name.toBuilder name <> usd <> B.intDec index)
101+ Name (Name.toBuilder name <> "$" <> B.intDec index)
107102
108103
109104makeTemp :: Name.Name -> Name
@@ -113,12 +108,7 @@ makeTemp name =
113108
114109dollar :: Name
115110dollar =
116− Name usd
117−
118−
119−usd :: B.Builder
120−usd =
121− Name.toBuilder Name.dollar
111+ Name (Name.toBuilder Name.dollar)
122112
123113
124114
compiler/src/Generate/Mode.hs+1
@@ -49,6 +49,7 @@ 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
5253 Map.insertWith (++) frequency [field] buckets
5354
5455
compiler/src/Json/Decode.hs+73−78
@@ -24,7 +24,6 @@ module Json.Decode
2424 , Problem(..)
2525 , DecodeExpectation(..)
2626 , ParseError(..)
27− , StringProblem(..)
2827 )
2928 where
3029
@@ -32,7 +31,7 @@ module Json.Decode
3231import qualified Data.ByteString.Internal as B
3332import qualified Data.Map as Map
3433import qualified Data.NonEmptyList as NE
35−import Data.Word (Word8)
34+import Data.Word (Word8, Word16)
3635import Foreign.Ptr (Ptr, plusPtr, minusPtr)
3736import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
3837
@@ -40,7 +39,6 @@ import qualified Json.String as Json
4039import qualified Parse.Keyword as K
4140import qualified Parse.Primitives as P
4241import Parse.Primitives (Row, Col)
43−import qualified Reporting.Annotation as A
4442
4543
4644
@@ -51,10 +49,10 @@ fromByteString :: Decoder x a -> B.ByteString -> Either (Error x) a
5149fromByteString (Decoder decode) src =
5250 case P.fromByteString pFile BadEnd src of
5351 Right ast ->
54− decode ast Right (Left . DecodeProblem src)
52+ decode ast Right (Left . DecodeProblem)
5553
5654 Left problem ->
57− Left (ParseProblem src problem)
55+ Left (ParseProblem problem)
5856
5957
6058
@@ -77,8 +75,8 @@ newtype Decoder x a =
7775
7876
7977data Error x
80− = DecodeProblem B.ByteString (Problem x)
81− | ParseProblem B.ByteString ParseError
78+ = DecodeProblem (Problem x)
79+ | ParseProblem ParseError
8280
8381
8482
@@ -89,8 +87,8 @@ data Problem x
8987 = Field B.ByteString (Problem x)
9088 | Index Int (Problem x)
9189 | OneOf (Problem x) [Problem x]
92− | Failure A.Region x
93− | Expecting A.Region DecodeExpectation
90+ | Failure x
91+ | Expecting DecodeExpectation
9492
9593
9694data DecodeExpectation
@@ -157,26 +155,26 @@ instance Monad (Decoder x) where
157155
158156string :: Decoder x Json.String
159157string =
160− Decoder $ \(A.At region ast) ok err ->
158+ Decoder $ \ast ok err ->
161159 case ast of
162160 String snippet ->
163161 ok (Json.fromSnippet snippet)
164162
165163 _ ->
166− err (Expecting region TString)
164+ err (Expecting TString)
167165
168166
169167customString :: P.Parser x a -> (Row -> Col -> x) -> Decoder x a
170168customString parser toBadEnd =
171− Decoder $ \(A.At region ast) ok err ->
169+ Decoder $ \ast ok err ->
172170 case ast of
173171 String snippet ->
174172 case P.fromSnippet parser toBadEnd snippet of
175173 Right a -> ok a
176− Left x -> err (Failure region x)
174+ Left x -> err (Failure x)
177175
178176 _ ->
179− err (Expecting region TString)
177+ err (Expecting TString)
180178
181179
182180
@@ -185,7 +183,7 @@ customString parser toBadEnd =
185183
186184bool :: Decoder x Bool
187185bool =
188− Decoder $ \(A.At region ast) ok err ->
186+ Decoder $ \ast ok err ->
189187 case ast of
190188 TRUE ->
191189 ok True
@@ -194,7 +192,7 @@ bool =
194192 ok False
195193
196194 _ ->
197− err (Expecting region TBool)
195+ err (Expecting TBool)
198196
199197
200198
@@ -203,13 +201,13 @@ bool =
203201
204202int :: Decoder x Int
205203int =
206− Decoder $ \(A.At region ast) ok err ->
204+ Decoder $ \ast ok err ->
207205 case ast of
208206 Int n ->
209207 ok n
210208
211209 _ ->
212− err (Expecting region TInt)
210+ err (Expecting TInt)
213211
214212
215213
@@ -218,13 +216,13 @@ int =
218216
219217list :: Decoder x a -> Decoder x [a]
220218list decoder =
221− Decoder $ \(A.At region ast) ok err ->
219+ Decoder $ \ast ok err ->
222220 case ast of
223221 Array asts ->
224222 listHelp decoder ok err 0 asts []
225223
226224 _ ->
227− err (Expecting region TArray)
225+ err (Expecting TArray)
228226
229227
230228listHelp :: Decoder x a -> ([a] -> b) -> (Problem x -> b) -> Int -> [AST] -> [a] -> b
@@ -259,7 +257,7 @@ nonEmptyList decoder x =
259257
260258pair :: Decoder x a -> Decoder x b -> Decoder x (a,b)
261259pair (Decoder decodeA) (Decoder decodeB) =
262− Decoder $ \(A.At region ast) ok err ->
260+ Decoder $ \ast ok err ->
263261 case ast of
264262 Array vs ->
265263 case vs of
@@ -276,10 +274,10 @@ pair (Decoder decodeA) (Decoder decodeB) =
276274 decodeA astA ok0 err0
277275
278276 _ ->
279− err (Expecting region (TArrayPair (length vs)))
277+ err (Expecting (TArrayPair (length vs)))
280278
281279 _ ->
282− err (Expecting region TArray)
280+ err (Expecting TArray)
283281
284282
285283
@@ -297,13 +295,13 @@ dict keyDecoder valueDecoder =
297295
298296pairs :: KeyDecoder x k -> Decoder x a -> Decoder x [(k, a)]
299297pairs keyDecoder valueDecoder =
300− Decoder $ \(A.At region ast) ok err ->
298+ Decoder $ \ast ok err ->
301299 case ast of
302300 Object kvs ->
303301 pairsHelp keyDecoder valueDecoder ok err kvs []
304302
305303 _ ->
306− err (Expecting region TObject)
304+ err (Expecting TObject)
307305
308306
309307pairsHelp :: KeyDecoder x k -> Decoder x a -> ([(k, a)] -> b) -> (Problem x -> b) -> [(P.Snippet, AST)] -> [(k, a)] -> b
@@ -315,7 +313,7 @@ pairsHelp keyDecoder@(KeyDecoder keyParser toBadEnd) valueDecoder@(Decoder decod
315313 (snippet, ast) : kvs ->
316314 case P.fromSnippet keyParser toBadEnd snippet of
317315 Left x ->
318− err (Failure (snippetToRegion snippet) x)
316+ err (Failure x)
319317
320318 Right key ->
321319 let
@@ -327,18 +325,13 @@ pairsHelp keyDecoder@(KeyDecoder keyParser toBadEnd) valueDecoder@(Decoder decod
327325 decodeA ast ok' err'
328326
329327
330−snippetToRegion :: P.Snippet -> A.Region
331−snippetToRegion (P.Snippet _ _ len row col) =
332− A.Region (A.Position row col) (A.Position row (col + fromIntegral len))
333−
334−
335328
336329-- FIELDS
337330
338331
339332field :: B.ByteString -> Decoder x a -> Decoder x a
340333field key (Decoder decodeA) =
341− Decoder $ \(A.At region ast) ok err ->
334+ Decoder $ \ast ok err ->
342335 case ast of
343336 Object kvs ->
344337 case findField key kvs of
@@ -350,10 +343,10 @@ field key (Decoder decodeA) =
350343 decodeA value ok err'
351344
352345 Nothing ->
353− err (Expecting region (TObjectWith key))
346+ err (Expecting (TObjectWith key))
354347
355348 _ ->
356− err (Expecting region TObject)
349+ err (Expecting TObject)
357350
358351
359352findField :: B.ByteString -> [(P.Snippet, AST)] -> Maybe AST
@@ -417,8 +410,8 @@ oneOfError problems prob ps =
417410
418411failure :: x -> Decoder x a
419412failure x =
420− Decoder $ \(A.At region _) _ err ->
421− err (Failure region x)
413+ Decoder $ \_ _ err ->
414+ err (Failure x)
422415
423416
424417
@@ -437,22 +430,18 @@ mapError func (Decoder decodeA) =
437430mapErrorHelp :: (x -> y) -> Problem x -> Problem y
438431mapErrorHelp func problem =
439432 case problem of
440− Field k p -> Field k (mapErrorHelp func p)
441− Index i p -> Index i (mapErrorHelp func p)
442− OneOf p ps -> OneOf (mapErrorHelp func p) (map (mapErrorHelp func) ps)
443− Failure r x -> Failure r (func x)
444− Expecting r e -> Expecting r e
433+ Field k p -> Field k (mapErrorHelp func p)
434+ Index i p -> Index i (mapErrorHelp func p)
435+ OneOf p ps -> OneOf (mapErrorHelp func p) (map (mapErrorHelp func) ps)
436+ Failure x -> Failure (func x)
437+ Expecting e -> Expecting e
445438
446439
447440
448441-- AST
449442
450443
451−type AST =
452− A.Located AST_
453−
454−
455−data AST_
444+data AST
456445 = Array [AST]
457446 | Object [(P.Snippet, AST)]
458447 | String P.Snippet
@@ -471,14 +460,21 @@ type Parser a =
471460
472461
473462data ParseError
474− = Start Row Col
475− | ObjectField Row Col
476− | ObjectColon Row Col
463+ = ObjectStart Row Col
464+ | ObjectMore Row Col
477465 | ObjectEnd Row Col
466+ | ArrayStart Row Col
467+ | ArrayMore Row Col
478468 | ArrayEnd Row Col
469+ | StringStart Row Col
479470 | StringProblem StringProblem Row Col
471+ | IntStart Row Col
480472 | NoLeadingZeros Row Col
481473 | NoFloats Row Col
474+ | Bool Row Col
475+ | Null Row Col
476+ | Value Row Col
477+ | Colon Row Col
482478 | BadEnd Row Col
483479
484480-- PIndex Int ParseError Row Col
@@ -506,15 +502,14 @@ pFile =
506502
507503pValue :: Parser AST
508504pValue =
509− P.addLocation $
510− P.oneOf Start
511− [ String <$> pString Start
505+ P.oneOf Value
506+ [ String <$> pString
512507 , pObject
513508 , pArray
514509 , pInt
515− , K.k4 0x74 0x72 0x75 0x65 Start >> return TRUE
516− , K.k5 0x66 0x61 0x6C 0x73 0x65 Start >> return FALSE
517− , K.k4 0x6E 0x75 0x6C 0x6C Start >> return NULL
510+ , K.k4 0x74 0x72 0x75 0x65 Bool >> return TRUE
511+ , K.k5 0x66 0x61 0x6C 0x73 0x65 Bool >> return FALSE
512+ , K.k4 0x6E 0x75 0x6C 0x6C Null >> return NULL
518513 ]
519514
520515
@@ -522,11 +517,11 @@ pValue =
522517-- OBJECT
523518
524519
525−pObject :: Parser AST_
520+pObject :: Parser AST
526521pObject =
527− do P.word1 0x7B {- { -} Start
522+ do P.word1 0x7B {- { -} ObjectStart
528523 spaces
529− P.oneOf ObjectField
524+ P.oneOf ObjectMore
530525 [ do entry <- pField
531526 spaces
532527 pObjectHelp [entry]
@@ -535,11 +530,11 @@ pObject =
535530 ]
536531
537532
538−pObjectHelp :: [(P.Snippet, AST)] -> Parser AST_
533+pObjectHelp :: [(P.Snippet, AST)] -> Parser AST
539534pObjectHelp revEntries =
540− P.oneOf ObjectEnd
535+ P.oneOf ObjectMore
541536 [
542− do P.word1 0x2C {-,-} ObjectEnd
537+ do P.word1 0x2C {-,-} ObjectMore
543538 spaces
544539 entry <- pField
545540 spaces
@@ -552,9 +547,9 @@ pObjectHelp revEntries =
552547
553548pField :: Parser (P.Snippet, AST)
554549pField =
555− do key <- pString ObjectField
550+ do key <- pString
556551 spaces
557− P.word1 0x3A {-:-} ObjectColon
552+ P.word1 0x3A {-:-} Colon
558553 spaces
559554 value <- pValue
560555 return (key, value)
@@ -564,11 +559,11 @@ pField =
564559-- ARRAY
565560
566561
567−pArray :: Parser AST_
562+pArray :: Parser AST
568563pArray =
569− do P.word1 0x5B {-[-} Start
564+ do P.word1 0x5B {-[-} ArrayStart
570565 spaces
571− P.oneOf Start
566+ P.oneOf ArrayMore
572567 [ do entry <- pValue
573568 spaces
574569 pArrayHelp 1 [entry]
@@ -577,11 +572,11 @@ pArray =
577572 ]
578573
579574
580−pArrayHelp :: Int -> [AST] -> Parser AST_
575+pArrayHelp :: Int -> [AST] -> Parser AST
581576pArrayHelp !len revEntries =
582− P.oneOf ArrayEnd
577+ P.oneOf ArrayMore
583578 [
584− do P.word1 0x2C {-,-} ArrayEnd
579+ do P.word1 0x2C {-,-} ArrayMore
585580 spaces
586581 entry <- pValue
587582 spaces
@@ -596,8 +591,8 @@ pArrayHelp !len revEntries =
596591-- STRING
597592
598593
599−pString :: (Row -> Col -> ParseError) -> Parser P.Snippet
600−pString start =
594+pString :: Parser P.Snippet
595+pString =
601596 P.Parser $ \(P.State src pos end indent row col) cok _ cerr eerr ->
602597 if pos < end && P.unsafeIndex pos == 0x22 {-"-} then
603598
@@ -622,7 +617,7 @@ pString start =
622617 cerr newRow newCol (StringProblem problem)
623618
624619 else
625− eerr row col start
620+ eerr row col StringStart
626621
627622
628623data StringStatus
@@ -630,7 +625,7 @@ data StringStatus
630625 | BadString StringProblem
631626
632627
633−pStringHelp :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> (# StringStatus, Ptr Word8, Row, Col #)
628+pStringHelp :: Ptr Word8 -> Ptr Word8 -> Word16 -> Word16 -> (# StringStatus, Ptr Word8, Word16, Word16 #)
634629pStringHelp pos end row col =
635630 if pos >= end then
636631 (# BadString BadStringEnd, pos, row, col #)
@@ -676,7 +671,7 @@ pStringHelp pos end row col =
676671 if word < 0x20 then
677672 (# BadString BadStringControlChar, pos, row, col #)
678673 else
679− let !newPos = plusPtr pos (P.getCharWidth word) in
674+ let !newPos = plusPtr pos (P.getCharWidth pos end word) in
680675 pStringHelp newPos end row (col + 1)
681676
682677
@@ -708,7 +703,7 @@ spaces =
708703 cok () newState
709704
710705
711−eatSpaces :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> (# Ptr Word8, Row, Col #)
706+eatSpaces :: Ptr Word8 -> Ptr Word8 -> Word16 -> Word16 -> (# Ptr Word8, Word16, Word16 #)
712707eatSpaces pos end row col =
713708 if pos >= end then
714709 (# pos, row, col #)
@@ -727,16 +722,16 @@ eatSpaces pos end row col =
727722-- INTS
728723
729724
730−pInt :: Parser AST_
725+pInt :: Parser AST
731726pInt =
732727 P.Parser $ \(P.State src pos end indent row col) cok _ cerr eerr ->
733728 if pos >= end then
734− eerr row col Start
729+ eerr row col IntStart
735730
736731 else
737732 let !word = P.unsafeIndex pos in
738733 if not (isDecimalDigit word) then
739− eerr row col Start
734+ eerr row col IntStart
740735
741736 else if word == 0x30 {-0-} then
742737
compiler/src/Json/Encode.hs+5−23
@@ -70,6 +70,11 @@ name nm =
7070 String (B.char7 '"' <> Name.toBuilder nm <> B.char7 '"')
7171
7272
73+chars :: [Char] -> Value
74+chars chrs =
75+ String (B.char7 '"' <> error "TODO escape this properly. Who is using this?" chrs <> B.char7 '"')
76+
77+
7378bool :: Bool -> Value
7479bool =
7580 Boolean
@@ -101,29 +106,6 @@ list encodeEntry entries =
101106
102107
103108
104−-- CHARS
105−
106−
107−chars :: [Char] -> Value -- PERF can this be done better? Look for examples.
108−chars chrs =
109− String (B.char7 '"' <> B.stringUtf8 (escape chrs) <> B.char7 '"')
110−
111−
112−escape :: [Char] -> [Char]
113−escape chrs =
114− case chrs of
115− [] ->
116− []
117−
118− c:cs
119− | c == '\r' -> '\\' : 'r' : escape cs
120− | c == '\n' -> '\\' : 'n' : escape cs
121− | c == '\"' -> '\\' : '"' : escape cs
122− | c == '\\' -> '\\' : '\\' : escape cs
123− | otherwise -> c : escape cs
124−
125−
126−
127109-- HELPERS
128110
129111
compiler/src/Json/String.hs+3−8
@@ -2,7 +2,6 @@
22{-# LANGUAGE BangPatterns, EmptyDataDecls #-}
33module Json.String
44 ( String
5− , isEmpty
65 --
76 , fromPtr
87 , fromName
@@ -37,7 +36,7 @@ import qualified Parse.Primitives as P
3736
3837
3938-- INVARIANT: any Json.String is appropriately escaped already
40−-- PERF: is this the right representation for Json.String? Maybe ByteString instead?
39+-- TODO: is this the right representation for Json.String? Maybe ByteString instead?
4140--
4241type String =
4342 Utf8.Utf8 JSON_STRING
@@ -46,11 +45,6 @@ type String =
4645data JSON_STRING
4746
4847
49−isEmpty :: String -> Bool
50−isEmpty =
51− Utf8.isEmpty
52−
53−
5448
5549-- FROM
5650
@@ -116,6 +110,7 @@ chompChunks pos end start revChunks =
116110 case word of
117111 0x0A {-\n-} -> chompEscape 0x6E {-n-} pos end start revChunks
118112 0x22 {-"-} -> chompEscape 0x22 {-"-} pos end start revChunks
113+ 0x27 {-'-} -> chompEscape 0x27 {-'-} pos end start revChunks
119114 0x5C {-\-} -> chompEscape 0x5C {-\-} pos end start revChunks
120115 0x0D {-\r-} ->
121116 let
@@ -125,7 +120,7 @@ chompChunks pos end start revChunks =
125120
126121 _ ->
127122 let
128− !width = P.getCharWidth word
123+ !width = P.getCharWidth pos end word
129124 !newPos = plusPtr pos width
130125 in
131126 chompChunks newPos end start revChunks
compiler/src/Nitpick/PatternMatches.hs+3−3
@@ -22,11 +22,11 @@ import qualified Data.Map as Map
2222import qualified Data.Maybe as Maybe
2323import qualified Data.Name as Name
2424import qualified Data.NonEmptyList as NE
25+import qualified Data.Utf8 as Utf8
2526
2627import qualified AST.Canonical as Can
2728import qualified Data.Index as Index
2829import qualified Elm.ModuleName as ModuleName
29−import qualified Elm.String as ES
3030import qualified Reporting.Annotation as A
3131
3232
@@ -41,8 +41,8 @@ data Pattern
4141
4242
4343data Literal
44− = Chr ES.String
45− | Str ES.String
44+ = Chr Utf8.String
45+ | Str Utf8.String
4646 | Int Int
4747 deriving (Eq)
4848
compiler/src/Optimize/DecisionTree.hs+5−5
@@ -27,11 +27,11 @@ import qualified Data.List as List
2727import qualified Data.Maybe as Maybe
2828import qualified Data.Name as Name
2929import qualified Data.Set as Set
30+import qualified Data.Utf8 as Utf8
3031
3132import qualified AST.Canonical as Can
3233import qualified Data.Index as Index
3334import qualified Elm.ModuleName as ModuleName
34−import qualified Elm.String as ES
3535import qualified Reporting.Annotation as A
3636
3737
@@ -77,8 +77,8 @@ data Test
7777 | IsNil
7878 | IsTuple
7979 | IsInt Int
80− | IsChr ES.String
81− | IsStr ES.String
80+ | IsChr Utf8.String
81+ | IsStr Utf8.String
8282 | IsBool Bool
8383 deriving (Eq, Ord)
8484
@@ -618,7 +618,7 @@ instance Binary Test where
618618 5 -> liftM IsStr get
619619 6 -> liftM IsInt get
620620 7 -> liftM IsBool get
621− _ -> fail "problem getting DecisionTree.Test binary"
621+ _ -> error "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− _ -> fail "problem getting DecisionTree.Path binary"
637+ _ -> error "problem getting DecisionTree.Path binary"
compiler/src/Optimize/Module.hs+3−3
@@ -213,10 +213,10 @@ findMain defs =
213213 def:rest ->
214214 case def of
215215 Can.Def (A.At region name) _ _ ->
216− if name == Name._main then Just region else findMain rest
216+ if name == Name.main then Just region else findMain rest
217217
218218 Can.TypedDef (A.At region name) _ _ _ _ ->
219− if name == Name._main then Just region else findMain rest
219+ if name == Name.main then Just region else findMain rest
220220
221221
222222defToName :: Can.Def -> Name.Name
@@ -244,7 +244,7 @@ addDef home annotations def graph =
244244
245245addDefHelp :: A.Region -> Annotations -> ModuleName.Canonical -> Name.Name -> [Can.Pattern] -> Can.Expr -> Opt.LocalGraph -> Result i w Opt.LocalGraph
246246addDefHelp region annotations home name args body graph@(Opt.LocalGraph _ nodes fieldCounts) =
247− if name /= Name._main then
247+ if name /= Name.main then
248248 Result.ok (addDefNode home name args body Set.empty graph)
249249 else
250250 let
compiler/src/Optimize/Port.hs+3−3
@@ -58,7 +58,7 @@ toEncoder tipe =
5858 | name == Name.array -> encodeArray arg
5959
6060 _ ->
61− error "toEncoder: bad custom type"
61+ error "toEncoder: bad union type"
6262
6363 Can.TRecord _ (Just _) ->
6464 error "toEncoder: bad record"
@@ -68,7 +68,7 @@ toEncoder tipe =
6868 encodeField (name, Can.FieldType _ fieldType) =
6969 do encoder <- toEncoder fieldType
7070 let value = Opt.Call encoder [Opt.Access (Opt.VarLocal Name.dollar) name]
71− return $ Opt.Tuple (Opt.Str (Name.toElmString name)) value Nothing
71+ return $ Opt.Tuple (Opt.Str (Name.toUtf8 name)) value Nothing
7272 in
7373 do object <- encode "object"
7474 keyValuePairs <- traverse encodeField (Map.toList fields)
@@ -309,7 +309,7 @@ fieldAndThen decoder (key, Can.FieldType _ tipe) =
309309 return $
310310 Opt.Call andThen
311311 [ Opt.Function [key] decoder
312− , Opt.Call field [ Opt.Str (Name.toElmString key), typeDecoder ]
312+ , Opt.Call field [ Opt.Str (Name.toUtf8 key), typeDecoder ]
313313 ]
314314
315315
compiler/src/Parse/Docs.hsnew file+275
@@ -0,0 +1,275 @@
1+module Parse.Docs
2+ ( Docs(..)
3+ , parser
4+ )
5+ where
6+
7+
8+
9+-- DOCS
10+
11+
12+data Docs =
13+ Docs
14+ { _exposed :: [A.Located Name.Name]
15+ , _overview :: Utf8.String
16+ , _listed :: [A.Located Name.Name]
17+ , _comments :: Map.Map Name.Name Utf8.String
18+ }
19+
20+
21+
22+-- PARSER
23+
24+
25+parser :: Parser Docs
26+parser =
27+ error "TODO implement docs parser"
28+
29+
30+chompUntilDocs :: Parser Bool
31+chompUntilDocs =
32+ P.Parser $ \(P.State fp offset terminal indent row col ctx) cok _ _ _ ->
33+ let
34+ (# isStart, newOffset, newRow, newCol #) =
35+ eatDocs fp offset terminal row col
36+
37+ !newState =
38+ P.State fp newOffset terminal indent newRow newCol ctx
39+ in
40+ cok isStart newState
41+
42+
43+eatDocs :: ForeignPtr Word8 -> Int -> Int -> Word16 -> Word16 -> (# Bool, Int, Word16, Word16 #)
44+eatDocs fp offset terminal row col =
45+ if offset >= terminal then
46+ (# False, offset, row, col #)
47+
48+ else if isDocsStart fp offset terminal then
49+ (# True, offset + 5, row, col + 5 #)
50+
51+ else
52+ let !word = P.unsafeIndex fp offset in
53+ if word == 0x0A {- \n -} then
54+ eatDocs fp (offset + 1) terminal (row + 1) 1
55+
56+ else
57+ let !newOffset = offset + P.getCharWidth fp offset terminal word in
58+ eatDocs fp newOffset terminal row (col + 1)
59+
60+
61+isDocsStart :: ForeignPtr Word8 -> Int -> Int -> Bool
62+isDocsStart =
63+ let (B.PS dfp doff dlen) = docsStart in
64+ P.isSubstring dfp doff dlen
65+
66+
67+{-# NOINLINE docsStart #-}
68+docsStart :: B.ByteString
69+docsStart =
70+ "@docs"
71+
72+
73+chompOverview :: [A.Located Name.Name] -> Parser [A.Located Name.Name]
74+chompOverview names =
75+ do isDocs <- chompUntilDocs
76+ if isDocs
77+ then chompOverviewHelp names
78+ else return names
79+
80+
81+chompOverviewHelp :: [A.Located Name.Name] -> Parser [A.Located Name.Name]
82+chompOverviewHelp names =
83+ do pos <- getPosition
84+ (SPos spos) <- whitespace
85+ if pos == spos
86+ then chompOverview names
87+ else chompOverview =<< chompDocs names
88+
89+
90+chompDocs :: [A.Located Name.Name] -> Parser [A.Located Name.Name]
91+chompDocs names =
92+ do name <- addLocation (oneOf SE.XXX [ Var.lower, Var.upper, chompBinop ])
93+ spos <- whitespace
94+ oneOf SE.XXX
95+ [ do checkSpace spos
96+ word1 0x2C {-,-} SE.XXX
97+ spaces
98+ chompDocs (name:names)
99+ , return (name:names)
100+ ]
101+
102+
103+chompBinop :: Parser Name.Name
104+chompBinop =
105+ do word1 0x28 {-(-} SE.XXX
106+ name <- Symbol.binop
107+ word1 0x29 {-)-} SE.XXX
108+ return name
109+
110+
111+
112+
113+-- CHECK NAMES
114+
115+
116+type Result i w a =
117+ Result.Result i w E.Error a
118+
119+
120+type Dups =
121+ Map.Map Name.Name (OneOrMore.OneOrMore A.Region)
122+
123+
124+checkNames :: Map.Map Name.Name (A.Located Can.Export) -> [A.Located Name.Name] -> Result i w ()
125+checkNames exports names =
126+ do docs <- Map.traverseWithKey isUnique (List.foldl' addName Map.empty names)
127+ let overlap = Map.size (Map.intersection docs exports)
128+ if Map.size exports == overlap && overlap == Map.size docs
129+ then Result.ok ()
130+ else
131+ do _ <- Map.traverseWithKey onlyInDocs (Map.difference docs exports)
132+ _ <- Map.traverseWithKey onlyInExports (Map.difference exports docs)
133+ Result.ok ()
134+
135+
136+addName :: Dups -> A.Located Name.Name -> Dups
137+addName dict (A.At region name) =
138+ Map.insertWith OneOrMore.more name (OneOrMore.one region) dict
139+
140+
141+isUnique :: Name.Name -> OneOrMore.OneOrMore A.Region -> Result i w A.Region
142+isUnique name regions =
143+ case regions of
144+ OneOrMore.One region ->
145+ Result.ok region
146+
147+ OneOrMore.More _ _ ->
148+ let (r1:r2:_) = OneOrMore.toList regions in
149+ Result.throw (E.Duplicate name r1 r2)
150+
151+
152+onlyInDocs :: Name.Name -> A.Region -> Result i w a
153+onlyInDocs name region =
154+ Result.throw $ E.OnlyInDocs name region
155+
156+
157+onlyInExports :: Name.Name -> A.Located Can.Export -> Result i w a
158+onlyInExports name (A.At region _) =
159+ Result.throw $ E.OnlyInExports name region
160+
161+
162+
163+-- CHECK EXPORTS
164+
165+
166+data Info =
167+ Info
168+ { _iComments :: Map.Map Name.Name Comment
169+ , _iValues :: Types
170+ , _iUnions :: Map.Map Name.Name Can.Union
171+ , _iAliases :: Map.Map Name.Name Can.Alias
172+ , _iBinops :: Map.Map Name.Name Can.Binop
173+ , _iEffects :: Can.Effects
174+ }
175+
176+
177+checkExport :: Info -> Name.Name -> A.Located Can.Export -> Result i w (Module -> Module)
178+checkExport info name (A.At region export) =
179+ case export of
180+ Can.ExportValue ->
181+ do tipe <- getType name info
182+ comment <- getComment region name info
183+ Result.ok $ \m ->
184+ m { _values = Map.insert name (Value comment tipe) (_values m) }
185+
186+ Can.ExportBinop ->
187+ do let (Can.Binop_ assoc prec realName) = _iBinops info ! name
188+ tipe <- getType realName info
189+ comment <- getComment region realName info
190+ Result.ok $ \m ->
191+ m { _binops = Map.insert name (Binop comment tipe assoc prec) (_binops m) }
192+
193+ Can.ExportAlias ->
194+ do let (Can.Alias tvars tipe) = _iAliases info ! name
195+ comment <- getComment region name info
196+ Result.ok $ \m ->
197+ m { _aliases = Map.insert name (Alias comment tvars (Extract.fromType tipe)) (_aliases m) }
198+
199+ Can.ExportUnionOpen ->
200+ do let (Can.Union tvars ctors _ _) = _iUnions info ! name
201+ comment <- getComment region name info
202+ Result.ok $ \m ->
203+ m { _unions = Map.insert name (Union comment tvars (map dector ctors)) (_unions m) }
204+
205+ Can.ExportUnionClosed ->
206+ do let (Can.Union tvars _ _ _) = _iUnions info ! name
207+ comment <- getComment region name info
208+ Result.ok $ \m ->
209+ m { _unions = Map.insert name (Union comment tvars []) (_unions m) }
210+
211+ Can.ExportPort ->
212+ do tipe <- getType name info
213+ comment <- getComment region name info
214+ Result.ok $ \m ->
215+ m { _values = Map.insert name (Value comment tipe) (_values m) }
216+
217+
218+getComment :: A.Region -> Name.Name -> Info -> Result i w Comment
219+getComment region name info =
220+ case Map.lookup name (_iComments info) of
221+ Nothing ->
222+ Result.throw (E.NoComment name region)
223+
224+ Just comment ->
225+ Result.ok comment
226+
227+
228+getType :: Name.Name -> Info -> Result i w Type.Type
229+getType name info =
230+ case _iValues info ! name of
231+ A.At defRegion Nothing ->
232+ Result.throw (E.NoAnnotation name defRegion)
233+
234+ A.At _ (Just tipe) ->
235+ Result.ok (Extract.fromType tipe)
236+
237+
238+dector :: Can.Ctor -> (Name.Name, [Type.Type])
239+dector (Can.Ctor name _ _ args) =
240+ ( name, map Extract.fromType args )
241+
242+
243+
244+-- GATHER TYPES
245+
246+
247+type Types =
248+ Map.Map Name.Name (A.Located (Maybe Can.Type))
249+
250+
251+gatherTypes :: Can.Decls -> Types -> Types
252+gatherTypes decls types =
253+ case decls of
254+ Can.Declare def subDecls ->
255+ gatherTypes subDecls (addDef types def)
256+
257+ Can.DeclareRec defs subDecls ->
258+ gatherTypes subDecls (List.foldl' addDef types defs)
259+
260+ Can.SaveTheEnvironment ->
261+ types
262+
263+
264+addDef :: Types -> Can.Def -> Types
265+addDef types def =
266+ case def of
267+ Can.Def (A.At region name) _ _ ->
268+ Map.insert name (A.At region Nothing) types
269+
270+ Can.TypedDef (A.At region name) _ typedArgs _ resultType ->
271+ let
272+ tipe =
273+ foldr Can.TLambda resultType (map snd typedArgs)
274+ in
275+ Map.insert name (A.At region (Just tipe)) types
compiler/src/Parse/Expression.hs+38−46
@@ -16,7 +16,7 @@ import qualified Parse.Shader as Shader
1616import qualified Parse.Space as Space
1717import qualified Parse.Symbol as Symbol
1818import qualified Parse.Type as Type
19−import qualified Parse.String as String
19+import qualified Parse.Utf8 as Utf8
2020import qualified Parse.Variable as Var
2121import Parse.Primitives hiding (State)
2222import qualified Parse.Primitives as P
@@ -46,13 +46,13 @@ term =
4646
4747string :: A.Position -> Parser E.Expr Src.Expr
4848string start =
49− do str <- String.string E.Start E.String
49+ do str <- Utf8.string E.Start E.String
5050 addEnd start (Src.Str str)
5151
5252
5353character :: A.Position -> Parser E.Expr Src.Expr
5454character start =
55− do chr <- String.character E.Start E.Char
55+ do chr <- Utf8.character E.Start E.Char
5656 addEnd start (Src.Chr chr)
5757
5858
@@ -128,46 +128,38 @@ 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− 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− ]
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+ ]
171163
172164
173165chompTupleEnd :: A.Position -> Src.Expr -> [Src.Expr] -> Parser E.Tuple Src.Expr
@@ -545,14 +537,14 @@ chompMatchingName expectedName =
545537 let
546538 (P.Parser parserL) = Var.lower E.DefNameRepeat
547539 in
548− P.Parser $ \state@(P.State _ _ _ _ sr sc) cok eok cerr eerr ->
540+ P.Parser $ \state@(P.State _ _ _ sr sc) cok eok cerr eerr ->
549541 let
550− cokL name newState@(P.State _ _ _ _ er ec) =
542+ cokL name newState@(P.State _ _ _ er ec) =
551543 if expectedName == name
552544 then cok (A.At (A.Region (A.Position sr sc) (A.Position er ec)) name) newState
553545 else cerr sr sc (E.DefNameMatch name)
554546
555− eokL name newState@(P.State _ _ _ _ er ec) =
547+ eokL name newState@(P.State _ _ _ er ec) =
556548 if expectedName == name
557549 then eok (A.At (A.Region (A.Position sr sc) (A.Position er ec)) name) newState
558550 else eerr sr sc (E.DefNameMatch name)
compiler/src/Parse/Module.hs+107−156
@@ -2,10 +2,9 @@
22{-# LANGUAGE OverloadedStrings #-}
33module Parse.Module
44 ( fromByteString
5− , ProjectType(..)
6− , isKernel
5+ , Header(..)
6+ , Effects(..)
77 , chompImports
8− , chompImport
98 )
109 where
1110
@@ -31,34 +30,11 @@ import qualified Reporting.Error.Syntax as E
3130-- FROM BYTE STRING
3231
3332
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
38− Left err -> Left (E.ParseError err)
39−
40−
41−
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
33+fromByteString :: Pkg.Name -> BS.ByteString -> Either E.Error Src.Module
34+fromByteString pkg source =
35+ case P.fromByteString (chompModule pkg) source of
36+ P.Ok modul _ -> checkModule modul
37+ P.Err err -> Left (E.ParseError err)
6238
6339
6440
@@ -68,74 +44,69 @@ isKernel projectType =
6844data Module =
6945 Module
7046 { _header :: Maybe Header
47+ , _comment :: Maybe Src.Comment
7148 , _imports :: [Src.Import]
7249 , _infixes :: [A.Located Src.Infix]
7350 , _decls :: [Decl.Decl]
7451 }
7552
7653
77−chompModule :: ProjectType -> Parser E.Module Module
78−chompModule projectType =
79− do header <- chompHeader
80− imports <- chompImports (if isCore projectType then [] else Imports.defaults)
81− infixes <- if isKernel projectType then chompInfixes [] else return []
54+chompModule :: Pkg.Name -> Parser E.Module Module
55+chompModule pkg =
56+ do freshLine E.FreshLine
57+ header <- chompHeader
58+ comment <- chompModuleDocComment
59+ imports <- chompImports (if pkg == Pkg.core then [] else Imports.defaults)
60+ infixes <- if Pkg.isKernel pkg then chompInfixes [] else return []
8261 decls <- specialize E.Declarations $ chompDecls []
83− return (Module header imports infixes decls)
62+ endOfFile
63+ return (Module header comment imports infixes decls)
8464
8565
8666
8767-- CHECK MODULE
8868
8969
90−checkModule :: ProjectType -> Module -> Either E.Error Src.Module
91−checkModule projectType (Module maybeHeader imports infixes decls) =
70+checkModule :: Module -> Either E.Error Src.Module
71+checkModule (Module maybeHeader maybeComment imports infixes decls) =
9272 let
9373 (values, unions, aliases, ports) = categorizeDecls [] [] [] [] decls
74+
75+ docs =
76+ case maybeComment of
77+ Just c -> Just (Src.Docs c (getComments decls []))
78+ Nothing -> Nothing
9479 in
9580 case maybeHeader of
96− Just (Header name effects exports docs) ->
97− Src.Module (Just name) exports (toDocs docs decls) imports values unions aliases infixes
98− <$> checkEffects projectType ports effects
81+ Just (Header name effects exports) ->
82+ Src.Module (Just name) exports docs imports values unions aliases infixes
83+ <$> checkEffects ports effects
9984
10085 Nothing ->
10186 Right $
102− Src.Module Nothing (A.At A.one Src.Open) (Src.NoDocs A.one) imports values unions aliases infixes $
87+ Src.Module Nothing (A.At A.one Src.Open) docs imports values unions aliases infixes $
10388 case ports of
10489 [] -> Src.NoEffects
10590 _:_ -> Src.Ports ports
10691
10792
108−checkEffects :: ProjectType -> [Src.Port] -> Effects -> Either E.Error Src.Effects
109−checkEffects projectType ports effects =
93+checkEffects :: [Src.Port] -> Effects -> Either E.Error Src.Effects
94+checkEffects ports effects =
11095 case effects of
11196 NoEffects region ->
11297 case ports of
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)
98+ [] -> Right Src.NoEffects
99+ _:_ -> Left (E.UnexpectedPort region)
120100
121101 Ports region ->
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)
102+ case ports of
103+ [] -> Left (E.NoPorts region)
104+ _:_ -> Right (Src.Ports ports)
130105
131106 Manager region manager ->
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−
107+ case ports of
108+ [] -> Right (Src.Manager region manager)
109+ _:_ -> Left (E.UnexpectedPort region)
139110
140111
141112categorizeDecls :: [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] )
@@ -152,20 +123,6 @@ categorizeDecls values unions aliases ports decls =
152123 Decl.Port _ port_ -> categorizeDecls values unions aliases (port_:ports) otherDecls
153124
154125
155−
156−-- TO DOCS
157−
158−
159−toDocs :: Either A.Region Src.Comment -> [Decl.Decl] -> Src.Docs
160−toDocs comment decls =
161− case comment of
162− Right overview ->
163− Src.YesDocs overview (getComments decls [])
164−
165− Left region ->
166− Src.NoDocs region
167−
168−
169126getComments :: [Decl.Decl] -> [(Name.Name,Src.Comment)] -> [(Name.Name,Src.Comment)]
170127getComments decls comments =
171128 case decls of
@@ -197,6 +154,15 @@ freshLine toFreshLineError =
197154 Space.checkFreshLine toFreshLineError
198155
199156
157+endOfFile :: Parser E.Module ()
158+endOfFile =
159+ P.Parser $ \state@(P.State pos end _ row col) _ eok _ eerr ->
160+ if pos < end then
161+ eerr row col E.ModuleEndOfFile
162+ else
163+ eok () state
164+
165+
200166
201167-- CHOMP DECLARATIONS
202168
@@ -224,17 +190,16 @@ chompInfixes infixes =
224190-- MODULE DOC COMMENT
225191
226192
227−chompModuleDocCommentSpace :: Parser E.Module (Either A.Region Src.Comment)
228−chompModuleDocCommentSpace =
229− do (A.At region ()) <- addLocation (freshLine E.FreshLine)
230− oneOfWithFallback
231− [
232− do docComment <- Space.docComment E.ImportStart E.ModuleSpace
233− Space.chomp E.ModuleSpace
234− Space.checkFreshLine E.FreshLine
235− return (Right docComment)
236− ]
237− (Left region)
193+chompModuleDocComment :: Parser E.Module (Maybe Src.Comment)
194+chompModuleDocComment =
195+ oneOfWithFallback
196+ [
197+ do docComment <- Space.docComment E.ImportStart E.ModuleSpace
198+ Space.chomp E.ModuleSpace
199+ Space.checkFreshLine E.FreshLine
200+ return (Just docComment)
201+ ]
202+ Nothing
238203
239204
240205
@@ -242,7 +207,7 @@ chompModuleDocCommentSpace =
242207
243208
244209data Header =
245− Header (A.Located Name.Name) Effects (A.Located Src.Exposing) (Either A.Region Src.Comment)
210+ Header (A.Located Name.Name) Effects (A.Located Src.Exposing)
246211
247212
248213data Effects
@@ -253,43 +218,40 @@ data Effects
253218
254219chompHeader :: Parser E.Module (Maybe Header)
255220chompHeader =
256− do freshLine E.FreshLine
257− start <- getPosition
221+ do start <- getPosition
258222 oneOfWithFallback
259223 [
260224 -- module MyThing exposing (..)
261225 do Keyword.module_ E.ModuleProblem
262− effectEnd <- getPosition
226+ end <- getPosition
263227 Space.chompAndCheckIndent E.ModuleSpace E.ModuleProblem
264228 name <- addLocation (Var.moduleName E.ModuleName)
265229 Space.chompAndCheckIndent E.ModuleSpace E.ModuleProblem
266230 Keyword.exposing_ E.ModuleProblem
267231 Space.chompAndCheckIndent E.ModuleSpace E.ModuleProblem
268232 exports <- addLocation (specialize E.ModuleExposing exposing)
269− comment <- chompModuleDocCommentSpace
270− return $ Just $
271− Header name (NoEffects (A.Region start effectEnd)) exports comment
233+ freshLine E.FreshLine
234+ return (Just (Header name (NoEffects (A.Region start end)) exports))
272235 ,
273236 -- port module MyThing exposing (..)
274237 do Keyword.port_ E.PortModuleProblem
275238 Space.chompAndCheckIndent E.ModuleSpace E.PortModuleProblem
276239 Keyword.module_ E.PortModuleProblem
277− effectEnd <- getPosition
240+ end <- getPosition
278241 Space.chompAndCheckIndent E.ModuleSpace E.PortModuleProblem
279242 name <- addLocation (Var.moduleName E.PortModuleName)
280243 Space.chompAndCheckIndent E.ModuleSpace E.PortModuleProblem
281244 Keyword.exposing_ E.PortModuleProblem
282245 Space.chompAndCheckIndent E.ModuleSpace E.PortModuleProblem
283246 exports <- addLocation (specialize E.PortModuleExposing exposing)
284− comment <- chompModuleDocCommentSpace
285− return $ Just $
286− Header name (Ports (A.Region start effectEnd)) exports comment
247+ freshLine E.FreshLine
248+ return (Just (Header name (Ports (A.Region start end)) exports))
287249 ,
288250 -- effect module MyThing where { command = MyCmd } exposing (..)
289251 do Keyword.effect_ E.Effect
290252 Space.chompAndCheckIndent E.ModuleSpace E.Effect
291253 Keyword.module_ E.Effect
292− effectEnd <- getPosition
254+ end <- getPosition
293255 Space.chompAndCheckIndent E.ModuleSpace E.Effect
294256 name <- addLocation (Var.moduleName E.ModuleName)
295257 Space.chompAndCheckIndent E.ModuleSpace E.Effect
@@ -300,9 +262,8 @@ chompHeader =
300262 Keyword.exposing_ E.Effect
301263 Space.chompAndCheckIndent E.ModuleSpace E.Effect
302264 exports <- addLocation (specialize (const E.Effect) exposing)
303− comment <- chompModuleDocCommentSpace
304− return $ Just $
305− Header name (Manager (A.Region start effectEnd) manager) exports comment
265+ freshLine E.FreshLine
266+ return (Just (Header name (Manager (A.Region start end) manager) exports))
306267 ]
307268 -- default header
308269 Nothing
@@ -372,33 +333,28 @@ spaces_em =
372333
373334
374335chompImports :: [Src.Import] -> Parser E.Module [Src.Import]
375−chompImports is =
336+chompImports imports =
376337 oneOfWithFallback
377− [ do i <- chompImport
378− chompImports (i:is)
338+ [ do Keyword.import_ E.ImportStart
339+ Space.chompAndCheckIndent E.ModuleSpace E.ImportIndentName
340+ name@(A.At (A.Region _ end) _) <- addLocation (Var.moduleName E.ImportName)
341+ Space.chomp E.ModuleSpace
342+ oneOf E.ImportEnd
343+ [ do Space.checkFreshLine E.ImportEnd
344+ chompImports $
345+ Src.Import name Nothing (Src.Explicit []) : imports
346+ , do Space.checkIndent end E.ImportEnd
347+ oneOf E.ImportAs
348+ [ chompAs name imports
349+ , chompExposing name Nothing imports
350+ ]
351+ ]
379352 ]
380− (reverse is)
381−
382−
383−chompImport :: Parser E.Module Src.Import
384−chompImport =
385− do Keyword.import_ E.ImportStart
386− Space.chompAndCheckIndent E.ModuleSpace E.ImportIndentName
387− name@(A.At (A.Region _ end) _) <- addLocation (Var.moduleName E.ImportName)
388− Space.chomp E.ModuleSpace
389− oneOf E.ImportEnd
390− [ do Space.checkFreshLine E.ImportEnd
391− return $ Src.Import name Nothing (Src.Explicit [])
392− , do Space.checkIndent end E.ImportEnd
393− oneOf E.ImportAs
394− [ chompAs name
395− , chompExposing name Nothing
396− ]
397− ]
353+ (reverse imports)
398354
399355
400−chompAs :: A.Located Name.Name -> Parser E.Module Src.Import
401−chompAs name =
356+chompAs :: A.Located Name.Name -> [Src.Import] -> Parser E.Module [Src.Import]
357+chompAs name imports =
402358 do Keyword.as_ E.ImportAs
403359 Space.chompAndCheckIndent E.ModuleSpace E.ImportIndentAlias
404360 alias <- Var.upper E.ImportAlias
@@ -406,19 +362,21 @@ chompAs name =
406362 Space.chomp E.ModuleSpace
407363 oneOf E.ImportEnd
408364 [ do Space.checkFreshLine E.ImportEnd
409− return $ Src.Import name (Just alias) (Src.Explicit [])
365+ chompImports $
366+ Src.Import name (Just alias) (Src.Explicit []) : imports
410367 , do Space.checkIndent end E.ImportEnd
411− chompExposing name (Just alias)
368+ chompExposing name (Just alias) imports
412369 ]
413370
414371
415−chompExposing :: A.Located Name.Name -> Maybe Name.Name -> Parser E.Module Src.Import
416−chompExposing name maybeAlias =
372+chompExposing :: A.Located Name.Name -> Maybe Name.Name -> [Src.Import] -> Parser E.Module [Src.Import]
373+chompExposing name maybeAlias imports =
417374 do Keyword.exposing_ E.ImportExposing
418375 Space.chompAndCheckIndent E.ModuleSpace E.ImportIndentExposingList
419376 exposed <- specialize E.ImportExposingList exposing
420377 freshLine E.ImportEnd
421− return $ Src.Import name maybeAlias exposed
378+ chompImports $
379+ Src.Import name maybeAlias exposed : imports
422380
423381
424382
@@ -434,18 +392,18 @@ exposing =
434392 Space.chompAndCheckIndent E.ExposingSpace E.ExposingIndentEnd
435393 word1 0x29 {-)-} E.ExposingEnd
436394 return Src.Open
437− , do exposed <- chompExposed
395+ , do exposed <- addLocation chompExposed
438396 Space.chompAndCheckIndent E.ExposingSpace E.ExposingIndentEnd
439397 exposingHelp [exposed]
440398 ]
441399
442400
443−exposingHelp :: [Src.Exposed] -> Parser E.Exposing Src.Exposing
401+exposingHelp :: [A.Located Src.Exposed] -> Parser E.Exposing Src.Exposing
444402exposingHelp revExposed =
445403 oneOf E.ExposingEnd
446404 [ do word1 0x2C {-,-} E.ExposingEnd
447405 Space.chompAndCheckIndent E.ExposingSpace E.ExposingIndentValue
448− exposed <- chompExposed
406+ exposed <- addLocation chompExposed
449407 Space.chompAndCheckIndent E.ExposingSpace E.ExposingIndentEnd
450408 exposingHelp (exposed:revExposed)
451409 , do word1 0x29 {-)-} E.ExposingEnd
@@ -455,21 +413,16 @@ exposingHelp revExposed =
455413
456414chompExposed :: Parser E.Exposing Src.Exposed
457415chompExposed =
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− ]
416+ oneOf E.ExposingValue
417+ [ Src.Lower <$> Var.lower E.ExposingValue
418+ , do word1 0x28 {-(-} E.ExposingValue
419+ op <- Symbol.operator E.ExposingOperator E.ExposingOperatorReserved
420+ word1 0x29 {-)-} E.ExposingOperatorRightParen
421+ return (Src.Operator op)
422+ , do name <- Var.upper E.ExposingValue
423+ Space.chompAndCheckIndent E.ExposingSpace E.ExposingIndentEnd
424+ Src.Upper name <$> privacy
425+ ]
473426
474427
475428privacy :: Parser E.Exposing Src.Privacy
@@ -477,11 +430,9 @@ privacy =
477430 oneOfWithFallback
478431 [ do word1 0x28 {-(-} E.ExposingTypePrivacy
479432 Space.chompAndCheckIndent E.ExposingSpace E.ExposingTypePrivacy
480− start <- getPosition
481433 word2 0x2E 0x2E {-..-} E.ExposingTypePrivacy
482− end <- getPosition
483434 Space.chompAndCheckIndent E.ExposingSpace E.ExposingTypePrivacy
484435 word1 0x29 {-)-} E.ExposingTypePrivacy
485− return $ Src.Public (A.Region start end)
436+ return Src.Public
486437 ]
487438 Src.Private
compiler/src/Parse/Number.hs+8−8
@@ -11,11 +11,11 @@ module Parse.Number
1111 where
1212
1313
14+import qualified Data.Utf8 as Utf8
1415import Data.Word (Word8)
1516import Foreign.Ptr (Ptr, plusPtr, minusPtr)
1617
1718import qualified AST.Utils.Binop as Binop
18−import qualified Elm.Float as EF
1919import Parse.Primitives (Parser, Row, Col)
2020import qualified Parse.Variable as Var
2121import qualified Parse.Primitives as P
@@ -43,12 +43,12 @@ isDecimalDigit word =
4343
4444data Number
4545 = Int Int
46− | Float EF.Float
46+ | Float (Utf8.Under256 Float)
4747
4848
4949number :: (Row -> Col -> x) -> (E.Number -> Row -> Col -> x) -> Parser x Number
5050number toExpectation toError =
51− P.Parser $ \(P.State src pos end indent row col) cok _ cerr eerr ->
51+ P.Parser $ \(P.State pos end indent row col) cok _ cerr eerr ->
5252 if pos >= end then
5353 eerr row col toExpectation
5454
@@ -76,16 +76,16 @@ number toExpectation toError =
7676 let
7777 !newCol = col + fromIntegral (minusPtr newPos pos)
7878 !integer = Int n
79− !newState = P.State src newPos end indent row newCol
79+ !newState = P.State newPos end indent row newCol
8080 in
8181 cok integer newState
8282
8383 OkFloat newPos ->
8484 let
8585 !newCol = col + fromIntegral (minusPtr newPos pos)
86− !copy = EF.fromPtr pos newPos
86+ !copy = Utf8.fromPtr pos newPos
8787 !float = Float copy
88− !newState = P.State src newPos end indent row newCol
88+ !newState = P.State newPos end indent row newCol
8989 in
9090 cok float newState
9191
@@ -290,7 +290,7 @@ stepHex pos end word acc
290290
291291precedence :: (Row -> Col -> x) -> Parser x Binop.Precedence
292292precedence toExpectation =
293− P.Parser $ \(P.State src pos end indent row col) cok _ _ eerr ->
293+ P.Parser $ \(P.State pos end indent row col) cok _ _ eerr ->
294294 if pos >= end then
295295 eerr row col toExpectation
296296
@@ -299,7 +299,7 @@ precedence toExpectation =
299299 if isDecimalDigit word then
300300 cok
301301 (Binop.Precedence (fromIntegral (word - 0x30 {-0-})))
302− (P.State src (plusPtr pos 1) end indent row (col + 1))
302+ (P.State (plusPtr pos 1) end indent row (col + 1))
303303
304304 else
305305 eerr row col toExpectation
compiler/src/Parse/Pattern.hs+7−7
@@ -16,7 +16,7 @@ import qualified AST.Source as Src
1616import qualified Parse.Keyword as Keyword
1717import qualified Parse.Number as Number
1818import qualified Parse.Space as Space
19−import qualified Parse.String as String
19+import qualified Parse.Utf8 as Utf8
2020import qualified Parse.Variable as Var
2121import qualified Parse.Primitives as P
2222import Parse.Primitives (Parser, addLocation, addEnd, getPosition, inContext, oneOf, oneOfWithFallback, word1, word2)
@@ -67,16 +67,16 @@ termHelp start =
6767 return (A.at start end (Src.PInt int))
6868
6969 Number.Float float ->
70− P.Parser $ \(P.State _ _ _ _ row col) _ _ cerr _ ->
70+ P.Parser $ \(P.State _ _ _ row col) _ _ cerr _ ->
7171 let
7272 width = fromIntegral (Utf8.size float)
7373 in
7474 cerr row (col - width) (E.PFloat width)
7575 ,
76− do str <- String.string E.PStart E.PString
76+ do str <- Utf8.string E.PStart E.PString
7777 addEnd start (Src.PStr str)
7878 ,
79− do chr <- String.character E.PStart E.PChar
79+ do chr <- Utf8.character E.PStart E.PChar
8080 addEnd start (Src.PChr chr)
8181 ]
8282
@@ -87,7 +87,7 @@ termHelp start =
8787
8888wildcard :: Parser E.Pattern ()
8989wildcard =
90− P.Parser $ \(P.State src pos end indent row col) cok _ cerr eerr ->
90+ P.Parser $ \(P.State pos end indent row col) cok _ cerr eerr ->
9191 if pos == end || P.unsafeIndex pos /= 0x5F {- _ -} then
9292 eerr row col E.PStart
9393 else
@@ -99,7 +99,7 @@ wildcard =
9999 let (# badPos, badCol #) = Var.chompInnerChars newPos end newCol in
100100 cerr row col (E.PWildcardNotVar (Name.fromPtr pos badPos) (fromIntegral (badCol - col)))
101101 else
102− let !newState = P.State src newPos end indent row newCol in
102+ let !newState = P.State newPos end indent row newCol in
103103 cok () newState
104104
105105
@@ -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 (reverse vars))
132+ addEnd start (Src.PRecord vars)
133133 ]
134134
135135
compiler/src/Parse/Primitives.hs+4−4
@@ -46,7 +46,7 @@ newtype Parser x a =
4646 )
4747
4848
49−data State = -- PERF try taking some out to avoid allocation
49+data State = -- TODO 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 -- PERF is this function okay? Worried about allocation/laziness with fallback values.
148+oneOfWithFallback :: [Parser x a] -> a -> Parser x a -- TODO 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
@@ -394,8 +394,8 @@ isWord pos end word =
394394 pos < end && unsafeIndex pos == word
395395
396396
397−getCharWidth :: Word8 -> Int
398−getCharWidth word
397+getCharWidth :: Ptr Word8 -> Ptr Word8 -> Word8 -> Int
398+getCharWidth _pos _end word -- TODO remove unused variables. Shorter stack?
399399 | word < 0x80 = 1
400400 | word < 0xc0 = error "Need UTF-8 encoded input. Ran into unrecognized bits."
401401 | word < 0xe0 = 2
compiler/src/Parse/Repl.hsnew file+117
@@ -0,0 +1,117 @@
1+{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+module Parse.Repl
4+ ( Entry(..)
5+ , parseEntry
6+ )
7+ where
8+
9+
10+import qualified Data.ByteString.UTF8 as BS_UTF8
11+import Data.Name (Name)
12+
13+import qualified AST.Source as Src
14+import qualified Parse.Primitives as P
15+import Parse.Utils
16+
17+
18+
19+-- ENTRY
20+
21+
22+data Entry
23+ = Import Name (Maybe Name) Src.Exposing String
24+ | Type Name String
25+ | Def (Maybe Name) String
26+ | Other String
27+ | Annotation
28+ | Port
29+
30+
31+
32+-- PARSE
33+
34+
35+parseEntry :: String -> Entry
36+parseEntry source =
37+ case P.fromByteString parser (BS_UTF8.fromString source) of
38+ P.Ok entry _ ->
39+ entry
40+
41+ P.Err _ _ _ _ ->
42+ Other source
43+
44+
45+parser :: Parser Entry
46+parser =
47+ error "TODO parse the REPL stuff"
48+
49+{-
50+ oneOf
51+ [
52+ do Keyword.import_
53+ spaces
54+ name <- Var.moduleName
55+ alias <- tryAlias
56+ exposing <-
57+ oneOf
58+ [ do spaces
59+ Keyword.exposing_
60+ spaces
61+ Module.exposing
62+ , return (Src.Explicit [])
63+ ]
64+ return (Import name alias exposing source)
65+ ,
66+ do Keyword.port_
67+ return Port
68+ ,
69+ do Keyword.type_
70+ spaces
71+ oneOf
72+ [ do Keyword.alias_
73+ spaces
74+ , return ()
75+ ]
76+ name <- Var.upper
77+ return (Type name source)
78+ ,
79+ do root <- Pattern.term
80+ spaces
81+ case A.toValue root of
82+ Src.PVar name ->
83+ oneOf
84+ [ do word1 0x3A {-:-} E.XXX
85+ return Annotation
86+ , do chompArgs
87+ return (Def (Just name) source)
88+ ]
89+
90+ _ ->
91+ do word1 0x3D {-=-} E.XXX
92+ return (Def Nothing source)
93+ ]
94+
95+
96+chompArgs :: Parser ()
97+chompArgs =
98+ oneOf
99+ [ do Pattern.term
100+ spaces
101+ chompArgs
102+ , do word1 0x3D {-=-} E.XXX
103+ return ()
104+ ]
105+
106+
107+tryAlias :: Parser (Maybe Name)
108+tryAlias =
109+ oneOf
110+ [ try $
111+ do spaces
112+ Keyword.as_
113+ spaces
114+ Just <$> Var.upper
115+ , return Nothing
116+ ]
117+-}
compiler/src/Parse/Shader.hs+14−16
@@ -6,13 +6,12 @@ module Parse.Shader
66 where
77
88
9−import qualified Data.ByteString.Internal as B
10−import qualified Data.ByteString.UTF8 as BS_UTF8
9+import qualified Data.List as List
1110import qualified Data.Map as Map
1211import qualified Data.Name as Name
12+import qualified Data.Utf8 as Utf8
1313import Data.Word (Word8)
14−import Foreign.Ptr (Ptr, plusPtr, minusPtr)
15−import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
14+import Foreign.Ptr (Ptr, plusPtr)
1615import qualified Language.GLSL.Parser as GLP
1716import qualified Language.GLSL.Syntax as GLS
1817import qualified Text.Parsec as Parsec
@@ -33,16 +32,16 @@ import qualified Reporting.Error.Syntax as E
3332shader :: A.Position -> Parser E.Expr Src.Expr
3433shader start@(A.Position row col) =
3534 do block <- parseBlock
36− shdr <- parseGlsl row col block
35+ shdr <- parseGlsl row col src
3736 end <- P.getPosition
38− return (A.at start end (Src.Shader (Shader.fromChars block) shdr))
37+ return (A.at start end (Src.Shader (Shader.fromChars src) shdr))
3938
4039
4140
4241-- BLOCK
4342
4443
45−parseBlock :: Parser E.Expr [Char]
44+parseBlock :: Parser E.Expr P.Snippet
4645parseBlock =
4746 P.Parser $ \(P.State src pos end indent row col) cok _ cerr eerr ->
4847 let
@@ -63,12 +62,11 @@ parseBlock =
6362 case status of
6463 Good ->
6564 let
66− !off = minusPtr pos6 (unsafeForeignPtrToPtr src)
67− !len = minusPtr newPos pos6
68− !block = BS_UTF8.toString (B.PS src off len)
65+ !block = Utf8.fromPtr pos6 newPos
66+ !source = Utf8.toChars block
6967 !newState = P.State src (plusPtr newPos 2) end indent newRow (newCol + 2)
7068 in
71− cok block newState
69+ cok source newState
7270
7371 Unending ->
7472 cerr row col E.EndlessShader
@@ -96,7 +94,7 @@ eatShader pos end row col =
9694 eatShader (plusPtr pos 1) end (row + 1) 1
9795
9896 else
99− let !newPos = plusPtr pos (P.getCharWidth word) in
97+ let !newPos = plusPtr pos (P.getCharWidth pos end word) in
10098 eatShader newPos end row (col + 1)
10199
102100
@@ -104,7 +102,7 @@ eatShader pos end row col =
104102-- GLSL
105103
106104
107−parseGlsl :: Row -> Col -> [Char] -> Parser E.Expr Shader.Types
105+parseGlsl :: Row -> Col -> String -> Parser E.Expr Shader.Types
108106parseGlsl startRow startCol src =
109107 case GLP.parse src of
110108 Right (GLS.TranslationUnit decls) ->
@@ -129,7 +127,7 @@ parseGlsl startRow startCol src =
129127 else failure (startRow + row - 1) col msg
130128
131129
132−failure :: Row -> Col -> [Char] -> Parser E.Expr a
130+failure :: Row -> Col -> String -> Parser E.Expr a
133131failure row col msg =
134132 P.Parser $ \(P.State _ _ _ _ _ _) _ _ cerr _ ->
135133 cerr row col (E.ShaderProblem msg)
@@ -144,7 +142,7 @@ emptyTypes =
144142 Shader.Types Map.empty Map.empty Map.empty
145143
146144
147−addInput :: (GLS.StorageQualifier, Shader.Type, [Char]) -> Shader.Types -> Shader.Types
145+addInput :: (GLS.StorageQualifier, Shader.Type, String) -> Shader.Types -> Shader.Types
148146addInput (qual, tipe, name) glDecls =
149147 case qual of
150148 GLS.Attribute -> glDecls { Shader._attribute = Map.insert (Name.fromChars name) tipe (Shader._attribute glDecls) }
@@ -153,7 +151,7 @@ addInput (qual, tipe, name) glDecls =
153151 _ -> error "Should never happen due to `extractInputs` function"
154152
155153
156−extractInputs :: GLS.ExternalDeclaration -> [(GLS.StorageQualifier, Shader.Type, [Char])]
154+extractInputs :: GLS.ExternalDeclaration -> [(GLS.StorageQualifier, Shader.Type, String)]
157155extractInputs decl =
158156 case decl of
159157 GLS.Declaration
compiler/src/Parse/Space.hs+4−4
@@ -157,7 +157,7 @@ eatSpaces pos end row col =
157157-- LINE COMMENTS
158158
159159
160−eatLineComment :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> (# Status, Ptr Word8, Row, Col #)
160+eatLineComment :: Ptr Word8 -> Ptr Word8 -> Word16 -> Word16 -> (# Status, Ptr Word8, Word16, Word16 #)
161161eatLineComment pos end row col =
162162 if pos >= end then
163163 (# Good, pos, row, col #)
@@ -167,7 +167,7 @@ eatLineComment pos end row col =
167167 if word == 0x0A {- \n -} then
168168 eatSpaces (plusPtr pos 1) end (row + 1) 1
169169 else
170− let !newPos = plusPtr pos (P.getCharWidth word) in
170+ let !newPos = plusPtr pos (P.getCharWidth pos end word) in
171171 eatLineComment newPos end row (col + 1)
172172
173173
@@ -208,7 +208,7 @@ data MultiStatus
208208 | MultiEndless
209209
210210
211−eatMultiCommentHelp :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> Word16 -> (# MultiStatus, Ptr Word8, Row, Col #)
211+eatMultiCommentHelp :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> Word16 -> (# MultiStatus, Ptr Word8, Word16, Word16 #)
212212eatMultiCommentHelp pos end row col openComments =
213213 if pos >= end then
214214 (# MultiEndless, pos, row, col #)
@@ -231,7 +231,7 @@ eatMultiCommentHelp pos end row col openComments =
231231 eatMultiCommentHelp (plusPtr pos 2) end row (col + 2) (openComments + 1)
232232
233233 else
234− let !newPos = plusPtr pos (P.getCharWidth word) in
234+ let !newPos = plusPtr pos (P.getCharWidth pos end word) in
235235 eatMultiCommentHelp newPos end row (col + 1) openComments
236236
237237
compiler/src/Parse/String.hs+5−5
@@ -87,7 +87,7 @@ chompChar pos end row col numChars mostRecent =
8787
8888 else
8989 let
90− !width = P.getCharWidth word
90+ !width = P.getCharWidth pos end word
9191 !newPos = plusPtr pos width
9292 in
9393 chompChar newPos end row (col + 1) (numChars + 1) (ES.Slice pos width)
@@ -165,7 +165,7 @@ addEscape chunk start end revChunks =
165165-- SINGLE STRINGS
166166
167167
168−singleString :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> Ptr Word8 -> [ES.Chunk] -> StringResult
168+singleString :: Ptr Word8 -> Ptr Word8 -> Word16 -> Word16 -> Ptr Word8 -> [ES.Chunk] -> StringResult
169169singleString pos end row col initialPos revChunks =
170170 if pos >= end then
171171 Err row col E.StringEndless_Single
@@ -203,7 +203,7 @@ singleString pos end row col initialPos revChunks =
203203 Err row (col + 1) E.StringEndless_Single
204204
205205 else
206− let !newPos = plusPtr pos (P.getCharWidth word) in
206+ let !newPos = plusPtr pos (P.getCharWidth pos end word) in
207207 singleString newPos end row (col + 1) initialPos revChunks
208208
209209
@@ -211,7 +211,7 @@ singleString pos end row col initialPos revChunks =
211211-- MULTI STRINGS
212212
213213
214−multiString :: Ptr Word8 -> Ptr Word8 -> Row -> Col -> Ptr Word8 -> Row -> Col -> [ES.Chunk] -> StringResult
214+multiString :: Ptr Word8 -> Ptr Word8 -> Word16 -> Word16 -> Ptr Word8 -> Word16 -> Word16 -> [ES.Chunk] -> StringResult
215215multiString pos end row col initialPos sr sc revChunks =
216216 if pos >= end then
217217 Err sr sc E.StringEndless_Multi
@@ -254,7 +254,7 @@ multiString pos end row col initialPos sr sc revChunks =
254254 Err sr sc E.StringEndless_Multi
255255
256256 else
257− let !newPos = plusPtr pos (P.getCharWidth word) in
257+ let !newPos = plusPtr pos (P.getCharWidth pos end word) in
258258 multiString newPos end row (col + 1) initialPos sr sc revChunks
259259
260260
compiler/src/Parse/Symbol.hs+1−1
@@ -40,7 +40,7 @@ operator toExpectation toError =
4040
4141 else
4242 case Name.fromPtr pos newPos of
43− "." -> eerr row col (toError BadDot)
43+ "." -> cerr row col (toError BadDot)
4444 "|" -> cerr row col (toError BadPipe)
4545 "->" -> cerr row col (toError BadArrow)
4646 "=" -> cerr row col (toError BadEquals)
compiler/src/Parse/Variable.hs+14−15
@@ -1,5 +1,5 @@
11{-# OPTIONS_GHC -Wall #-}
2−{-# LANGUAGE BangPatterns, MagicHash, OverloadedStrings, UnboxedTuples #-}
2+{-# LANGUAGE BangPatterns, MagicHash, UnboxedTuples, OverloadedStrings #-}
33module Parse.Variable
44 ( lower
55 , upper
@@ -8,7 +8,6 @@ module Parse.Variable
88 , foreignUpper
99 , foreignAlpha
1010 , chompInnerChars
11− , getUpperWidth
1211 , getInnerWidth
1312 , getInnerWidthHelp
1413 , reservedWords
@@ -35,13 +34,13 @@ import qualified Parse.Primitives as P
3534
3635upper :: (Row -> Col -> x) -> Parser x Name.Name
3736upper toError =
38− P.Parser $ \(P.State src pos end indent row col) cok _ _ eerr ->
37+ P.Parser $ \(P.State pos end indent row col) cok _ _ eerr ->
3938 let (# newPos, newCol #) = chompUpper pos end col in
4039 if pos == newPos then
4140 eerr row col toError
4241 else
4342 let !name = Name.fromPtr pos newPos in
44− cok name (P.State src newPos end indent row newCol)
43+ cok name (P.State newPos end indent row newCol)
4544
4645
4746
@@ -50,7 +49,7 @@ upper toError =
5049
5150lower :: (Row -> Col -> x) -> Parser x Name.Name
5251lower toError =
53− P.Parser $ \(P.State src pos end indent row col) cok _ _ eerr ->
52+ P.Parser $ \(P.State pos end indent row col) cok _ _ eerr ->
5453 let (# newPos, newCol #) = chompLower pos end col in
5554 if pos == newPos then
5655 eerr row col toError
@@ -61,13 +60,13 @@ lower toError =
6160 else
6261 let
6362 !newState =
64− P.State src newPos end indent row newCol
63+ P.State newPos end indent row newCol
6564 in
6665 cok name newState
6766
6867
6968{-# NOINLINE reservedWords #-}
70−reservedWords :: Set.Set Name.Name -- PERF try using a trie instead
69+reservedWords :: Set.Set Name.Name -- TODO try using a trie instead
7170reservedWords =
7271 Set.fromList
7372 [ "if", "then", "else"
@@ -87,7 +86,7 @@ reservedWords =
8786
8887moduleName :: (Row -> Col -> x) -> Parser x Name.Name
8988moduleName toError =
90− P.Parser $ \(P.State src pos end indent row col) cok _ cerr eerr ->
89+ P.Parser $ \(P.State pos end indent row col) cok _ cerr eerr ->
9190 let
9291 (# pos1, col1 #) = chompUpper pos end col
9392 in
@@ -101,7 +100,7 @@ moduleName toError =
101100 Good ->
102101 let
103102 !name = Name.fromPtr pos newPos
104− !newState = P.State src newPos end indent row newCol
103+ !newState = P.State newPos end indent row newCol
105104 in
106105 cok name newState
107106
@@ -141,22 +140,22 @@ data Upper
141140
142141foreignUpper :: (Row -> Col -> x) -> Parser x Upper
143142foreignUpper toError =
144− P.Parser $ \(P.State src pos end indent row col) cok _ _ eerr ->
143+ P.Parser $ \(P.State pos end indent row col) cok _ _ eerr ->
145144 let (# upperStart, upperEnd, newCol #) = foreignUpperHelp pos end col in
146145 if upperStart == upperEnd then
147146 eerr row newCol toError
148147 else
149148 let
150− !newState = P.State src upperEnd end indent row newCol
149+ !newState = P.State upperEnd end indent row newCol
151150 !name = Name.fromPtr upperStart upperEnd
152− !upperName =
151+ !foreign =
153152 if upperStart == pos then
154153 Unqualified name
155154 else
156155 let !home = Name.fromPtr pos (plusPtr upperStart (-1)) in
157156 Qualified home name
158157 in
159− cok upperName newState
158+ cok foreign newState
160159
161160
162161foreignUpperHelp :: Ptr Word8 -> Ptr Word8 -> Col -> (# Ptr Word8, Ptr Word8, Col #)
@@ -180,13 +179,13 @@ foreignUpperHelp pos end col =
180179
181180foreignAlpha :: (Row -> Col -> x) -> Parser x Src.Expr_
182181foreignAlpha toError =
183− P.Parser $ \(P.State src pos end indent row col) cok _ _ eerr ->
182+ P.Parser $ \(P.State pos end indent row col) cok _ _ eerr ->
184183 let (# alphaStart, alphaEnd, newCol, varType #) = foreignAlphaHelp pos end col in
185184 if alphaStart == alphaEnd then
186185 eerr row newCol toError
187186 else
188187 let
189− !newState = P.State src alphaEnd end indent row newCol
188+ !newState = P.State alphaEnd end indent row newCol
190189 !name = Name.fromPtr alphaStart alphaEnd
191190 in
192191 if alphaStart == pos then
compiler/src/Reporting/Annotation.hs+1−1
@@ -26,7 +26,7 @@ import Data.Word (Word16)
2626
2727
2828data Located a =
29− At Region a -- PERF see if unpacking region is helpful
29+ At Region a -- TODO see if unpacking region is helpful
3030
3131
3232instance Functor Located where
compiler/src/Reporting/Doc.hs+47−79
@@ -7,38 +7,16 @@ module Reporting.Doc
77 , P.hcat, P.hsep, P.indent, P.sep, P.vcat
88 , P.red, P.cyan, P.magenta, P.green, P.blue, P.black, P.yellow
99 , P.dullred, P.dullcyan, P.dullyellow
10− --
11− , fromChars
12− , fromName
13− , fromVersion
14− , fromPackage
15− , fromInt
16− --
17− , toAnsi
18− , toString
19− , toLine
20− --
10+
11+ , fromChars, fromName, fromInt, fromUtf8
12+ , toAnsi, toString, toLine
2113 , encode
22− --
23− , stack
24− , reflow
25− , commaSep
26− --
27− , toSimpleNote
28− , toFancyNote
29− , toSimpleHint
30− , toFancyHint
31− --
32− , link
33− , fancyLink
34− , reflowLink
35− , makeLink
36− , makeNakedLink
37− --
38− , args
39− , moreArgs
40− , ordinal
41− , intToOrdinal
14+
15+ , stack, reflow, commaSep
16+ , toSimpleNote, toSimpleHint, toFancyHint
17+ , link, fancyLink, reflowLink, makeLink, makeNakedLink
18+ , args, moreArgs
19+ , ordinal, intToOrdinal
4220 , cycle
4321 )
4422 where
@@ -48,17 +26,14 @@ import Prelude hiding (cycle)
4826import qualified Data.List as List
4927import Data.Monoid ((<>))
5028import qualified Data.Name as Name
29+import qualified Data.Utf8 as Utf8
5130import qualified System.Console.ANSI.Types as Ansi
5231import qualified System.Info as Info
5332import System.IO (Handle)
5433import qualified Text.PrettyPrint.ANSI.Leijen as P
5534
5635import qualified Data.Index as Index
57−import qualified Elm.Package as Pkg
58−import qualified Elm.Version as V
59−import Json.Encode ((==>))
6036import qualified Json.Encode as E
61−import qualified Json.String as Json
6237
6338
6439
@@ -75,21 +50,16 @@ fromName name =
7550 P.text (Name.toChars name)
7651
7752
78−fromVersion :: V.Version -> P.Doc
79−fromVersion vsn =
80− P.text (V.toChars vsn)
81−
82−
83−fromPackage :: Pkg.Name -> P.Doc
84−fromPackage pkg =
85− P.text (Pkg.toChars pkg)
86−
87−
8853fromInt :: Int -> P.Doc
8954fromInt n =
9055 P.text (show n)
9156
9257
58+fromUtf8 :: Utf8.String -> P.Doc
59+fromUtf8 utf8 =
60+ P.text (Utf8.toChars utf8)
61+
62+
9363
9464-- TO STRING
9565
@@ -141,21 +111,12 @@ commaSep conjunction addStyle names =
141111
142112
143113
144−-- NOTES
114+-- HINTS
145115
146116
147117toSimpleNote :: String -> P.Doc
148118toSimpleNote message =
149− toFancyNote (map P.text (words message))
150−
151−
152−toFancyNote :: [P.Doc] -> P.Doc
153−toFancyNote chunks =
154− P.fillSep (P.underline "Note" <> ":" : chunks)
155−
156−
157−
158−-- HINTS
119+ P.fillSep ((P.underline "Note" <> ":") : map P.text (words message))
159120
160121
161122toSimpleHint :: String -> P.Doc
@@ -172,32 +133,32 @@ toFancyHint chunks =
172133-- LINKS
173134
174135
175−link :: String -> String -> String -> String -> P.Doc
136+link :: P.Doc -> String -> String -> String -> P.Doc
176137link word before fileName after =
177138 P.fillSep $
178− (P.underline (P.text word) <> ":")
139+ (P.underline word <> ":")
179140 : map P.text (words before)
180141 ++ P.text (makeLink fileName)
181142 : map P.text (words after)
182143
183144
184−fancyLink :: String -> [P.Doc] -> String -> [P.Doc] -> P.Doc
145+fancyLink :: P.Doc -> [P.Doc] -> String -> [P.Doc] -> P.Doc
185146fancyLink word before fileName after =
186147 P.fillSep $
187− (P.underline (P.text word) <> ":") : before ++ P.text (makeLink fileName) : after
148+ (P.underline word <> ":") : before ++ P.text (makeLink fileName) : after
188149
189150
190−makeLink :: [Char] -> [Char]
151+makeLink :: String -> String
191152makeLink fileName =
192− "<https://elm-lang.org/" <> V.toChars V.compiler <> "/" <> fileName <> ">"
153+ "<https://elm-lang.org/" <> error "TODO V.toString V.compiler" <> "/" <> fileName <> ">"
193154
194155
195−makeNakedLink :: [Char] -> [Char]
156+makeNakedLink :: String -> String
196157makeNakedLink fileName =
197− "https://elm-lang.org/" <> V.toChars V.compiler <> "/" <> fileName
158+ "https://elm-lang.org/" <> error "TODO V.toString V.compiler" <> "/" <> fileName
198159
199160
200−reflowLink :: [Char] -> [Char] -> [Char] -> P.Doc
161+reflowLink :: String -> String -> String -> P.Doc
201162reflowLink before fileName after =
202163 P.fillSep $
203164 map P.text (words before)
@@ -306,8 +267,10 @@ data Color
306267 | WHITE
307268
308269
309−toJsonHelp :: Style -> [String] -> P.SimpleDoc -> [E.Value]
270+toJsonHelp :: Style -> [a] -> P.SimpleDoc -> [E.Value]
310271toJsonHelp style revChunks simpleDoc =
272+ error "TODO generate json on errors" style revChunks simpleDoc sgrToStyle encodeColor
273+{-
311274 case simpleDoc of
312275 P.SFail ->
313276 error $
@@ -318,18 +281,23 @@ toJsonHelp style revChunks simpleDoc =
318281 [ encodeChunks style revChunks ]
319282
320283 P.SChar char rest ->
321− toJsonHelp style ([char] : revChunks) rest
284+ toJsonHelp style (TB.singleton char : revChunks) rest
322285
323286 P.SText _ string rest ->
324− toJsonHelp style (string : revChunks) rest
287+ toJsonHelp style (TB.fromString string : revChunks) rest
325288
326289 P.SLine indent rest ->
327− toJsonHelp style (replicate indent ' ' : "\n" : revChunks) rest
290+ toJsonHelp style (spaces indent : "\n" : revChunks) rest
328291
329292 P.SSGR sgrs rest ->
330293 encodeChunks style revChunks : toJsonHelp (sgrToStyle sgrs style) [] rest
331294
332295
296+spaces :: Int -> TB.Builder
297+spaces n =
298+ TB.fromText (Text.replicate n " ")
299+-}
300+
333301sgrToStyle :: [Ansi.SGR] -> Style -> Style
334302sgrToStyle sgrs style@(Style bold underline color) =
335303 case sgrs of
@@ -390,28 +358,28 @@ toColor layer intensity color =
390358 Ansi.White -> pick White WHITE
391359 Ansi.Black -> pick Black BLACK
392360
393−
394−encodeChunks :: Style -> [String] -> E.Value
361+{-
362+encodeChunks :: Style -> [TB.Builder] -> E.Value
395363encodeChunks (Style bold underline color) revChunks =
396364 let
397− chars = concat (reverse revChunks)
365+ !str = Utf8.concat (reverse revChunks)
398366 in
399367 case color of
400368 Nothing | not bold && not underline ->
401− E.chars chars
369+ E.string str
402370
403371 _ ->
404372 E.object
405− [ "bold" ==> E.bool bold
406− , "underline" ==> E.bool underline
407− , "color" ==> maybe E.null encodeColor color
408− , "string" ==> E.chars chars
373+ [ ("bold", E.bool bold)
374+ , ("underline", E.bool underline)
375+ , ("color", maybe E.null encodeColor color)
376+ , ("string", E.string str)
409377 ]
410−
378+-}
411379
412380encodeColor :: Color -> E.Value
413381encodeColor color =
414− E.string $ Json.fromChars $
382+ E.string $
415383 case color of
416384 Red -> "red"
417385 RED -> "RED"
compiler/src/Reporting/Error.hs+26−32
@@ -10,9 +10,10 @@ module Reporting.Error
1010
1111
1212import qualified Data.ByteString as B
13+import qualified Data.Name as Name
1314import qualified Data.NonEmptyList as NE
1415import qualified Data.OneOrMore as OneOrMore
15−import qualified System.FilePath as FP
16+import qualified Data.Utf8 as Utf8
1617
1718import qualified Elm.ModuleName as ModuleName
1819import qualified File
@@ -21,7 +22,6 @@ import Json.Encode ((==>))
2122import qualified Reporting.Annotation as A
2223import qualified Reporting.Doc as D
2324import qualified Reporting.Error.Canonicalize as Canonicalize
24−import qualified Reporting.Error.Docs as Docs
2525import qualified Reporting.Error.Import as Import
2626import qualified Reporting.Error.Main as Main
2727import qualified Reporting.Error.Pattern as Pattern
@@ -39,8 +39,8 @@ import qualified Reporting.Report as Report
3939data Module =
4040 Module
4141 { _name :: ModuleName.Raw
42− , _absolutePath :: FilePath
43− , _modificationTime :: File.Time
42+ , _path :: FilePath
43+ , _time :: File.Time
4444 , _source :: B.ByteString
4545 , _error :: Error
4646 }
@@ -57,7 +57,6 @@ data Error
5757 | BadTypes L.Localizer (NE.List Type.Error)
5858 | BadMains L.Localizer (OneOrMore.OneOrMore Main.Error)
5959 | BadPatterns (NE.List Pattern.Error)
60− | BadDocs Docs.Error
6160
6261
6362
@@ -85,34 +84,32 @@ toReports source err =
8584 BadPatterns errs ->
8685 fmap (Pattern.toReport source) errs
8786
88− BadDocs docsErr ->
89− Docs.toReports source docsErr
90−
9187
9288
9389-- TO DOC
9490
9591
96−toDoc :: FilePath -> Module -> [Module] -> D.Doc
97−toDoc root err errs =
92+toDoc :: Module -> [Module] -> D.Doc
93+toDoc err errs =
9894 let
99− (NE.List m ms) = NE.sortBy _modificationTime (NE.List err errs)
95+ timeCompare m1 m2 = compare (_time m1) (_time m2)
96+ (NE.List m ms) = NE.sortBy timeCompare (NE.List err errs)
10097 in
101− D.vcat (toDocHelp root m ms)
98+ D.vcat (toDocHelp m ms)
10299
103100
104−toDocHelp :: FilePath -> Module -> [Module] -> [D.Doc]
105−toDocHelp root module1 modules =
101+toDocHelp :: Module -> [Module] -> [D.Doc]
102+toDocHelp module1 modules =
106103 case modules of
107104 [] ->
108− [moduleToDoc root module1
105+ [moduleToDoc module1
109106 ,""
110107 ]
111108
112109 module2 : otherModules ->
113− moduleToDoc root module1
110+ moduleToDoc module1
114111 : toSeparator module1 module2
115− : toDocHelp root module2 otherModules
112+ : toDocHelp module2 otherModules
116113
117114
118115toSeparator :: Module -> Module -> D.Doc
@@ -134,22 +131,19 @@ toSeparator beforeModule afterModule =
134131-- MODULE TO DOC
135132
136133
137−moduleToDoc :: FilePath -> Module -> D.Doc
138−moduleToDoc root (Module _ absolutePath _ source err) =
134+moduleToDoc :: Module -> D.Doc
135+moduleToDoc (Module _ path _ source err) =
139136 let
140137 reports =
141138 toReports (Code.toSource source) err
142−
143− relativePath =
144− FP.makeRelative root absolutePath
145139 in
146− D.vcat $ map (reportToDoc relativePath) (NE.toList reports)
140+ D.vcat $ map (reportToDoc path) (NE.toList reports)
147141
148142
149143reportToDoc :: FilePath -> Report.Report -> D.Doc
150−reportToDoc relativePath (Report.Report title _ _ message) =
144+reportToDoc path (Report.Report title _ _ message) =
151145 D.vcat
152− [ toMessageBar title relativePath
146+ [ toMessageBar title path
153147 , ""
154148 , message
155149 , ""
@@ -179,8 +173,8 @@ toJson (Module name path _ source err) =
179173 toReports (Code.toSource source) err
180174 in
181175 E.object
182− [ "path" ==> E.chars path
183− , "name" ==> E.name name
176+ [ "path" ==> E.string (Utf8.fromChars path)
177+ , "name" ==> E.string (Name.toUtf8 name)
184178 , "problems" ==> E.array (map reportToJson (NE.toList reports))
185179 ]
186180
@@ -188,7 +182,7 @@ toJson (Module name path _ source err) =
188182reportToJson :: Report.Report -> E.Value
189183reportToJson (Report.Report title region _sgstns message) =
190184 E.object
191− [ "title" ==> E.chars title
185+ [ "title" ==> E.string (Utf8.fromChars title)
192186 , "region" ==> encodeRegion region
193187 , "message" ==> D.encode message
194188 ]
@@ -199,12 +193,12 @@ encodeRegion (A.Region (A.Position sr sc) (A.Position er ec)) =
199193 E.object
200194 [ "start" ==>
201195 E.object
202− [ "line" ==> E.int (fromIntegral sr)
203− , "column" ==> E.int (fromIntegral sc)
196+ [ ("line", E.int (fromIntegral sr))
197+ , ("column", E.int (fromIntegral sc))
204198 ]
205199 , "end" ==>
206200 E.object
207− [ "line" ==> E.int (fromIntegral er)
208− , "column" ==> E.int (fromIntegral ec)
201+ [ ("line", E.int (fromIntegral er))
202+ , ("column", E.int (fromIntegral ec))
209203 ]
210204 ]
compiler/src/Reporting/Error/Canonicalize.hs+40−41
@@ -14,10 +14,8 @@ module Reporting.Error.Canonicalize
1414
1515
1616import qualified Data.Char as Char
17−import qualified Data.List as List
1817import qualified Data.Map as Map
1918import qualified Data.Name as Name
20−import qualified Data.OneOrMore as OneOrMore
2119import qualified Data.Set as Set
2220
2321import qualified AST.Canonical as Can
@@ -39,10 +37,10 @@ import qualified Reporting.Suggest as Suggest
3937
4038data Error
4139 = AnnotationTooShort A.Region Name.Name Index.ZeroBased Int
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)
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]
4644 | BadArity A.Region BadArityContext Name.Name Int Int
4745 | Binop A.Region Name.Name Name.Name
4846 | DuplicateDecl Name.Name A.Region A.Region
@@ -166,17 +164,17 @@ toReport source err =
166164 <> " be deleted? Maybe some parentheses are missing?"
167165 )
168166
169− AmbiguousVar region maybePrefix name h hs ->
170− ambiguousName source region maybePrefix name h hs "variable"
167+ AmbiguousVar region maybePrefix name possibleHomes ->
168+ ambiguousName source region maybePrefix name possibleHomes "variable"
171169
172− AmbiguousType region maybePrefix name h hs ->
173− ambiguousName source region maybePrefix name h hs "type"
170+ AmbiguousType region maybePrefix name possibleHomes ->
171+ ambiguousName source region maybePrefix name possibleHomes "type"
174172
175− AmbiguousVariant region maybePrefix name h hs ->
176− ambiguousName source region maybePrefix name h hs "variant"
173+ AmbiguousVariant region maybePrefix name possibleHomes ->
174+ ambiguousName source region maybePrefix name possibleHomes "variant"
177175
178− AmbiguousBinop region name h hs ->
179− ambiguousName source region Nothing name h hs "operator"
176+ AmbiguousBinop region name possibleHomes ->
177+ ambiguousName source region Nothing name possibleHomes "operator"
180178
181179 BadArity region badArityContext name expected actual ->
182180 let
@@ -244,11 +242,11 @@ toReport source err =
244242
245243 DuplicateAliasArg typeName name r1 r2 ->
246244 nameClash source r1 r2 $
247− "The `" <> Name.toChars typeName <> "` type alias has multiple `" <> Name.toChars name <> "` type variables."
245+ "The `" <> Name.toChars typeName <> "` type alias has multilpe `" <> Name.toChars name <> "` type variables."
248246
249247 DuplicateUnionArg typeName name r1 r2 ->
250248 nameClash source r1 r2 $
251− "The `" <> Name.toChars typeName <> "` type has multiple `" <> Name.toChars name <> "` type variables."
249+ "The `" <> Name.toChars typeName <> "` type has multilpe `" <> Name.toChars name <> "` type variables."
252250
253251 DuplicatePattern context name r1 r2 ->
254252 nameClash source r1 r2 $
@@ -276,7 +274,7 @@ toReport source err =
276274 "You have declared that `" ++ Name.toChars name ++ "` is an effect type:"
277275 ,
278276 D.reflow $
279− "But I cannot find a custom type named `" ++ Name.toChars name ++ "` in this file!"
277+ "But I cannot find a union type named `" ++ Name.toChars name ++ "` in this file!"
280278 )
281279
282280 EffectFunctionNotFound region name ->
@@ -344,7 +342,7 @@ toReport source err =
344342 Code.toSnippet source region Nothing
345343 (
346344 D.reflow $
347− "The (..) syntax is for exposing variants of a custom type. It cannot be used with a type alias like `"
345+ "The (..) syntax is for exposing union type constructors. It cannot be used with a type alias like `"
348346 ++ Name.toChars name ++ "` though."
349347 ,
350348 D.reflow $
@@ -357,12 +355,12 @@ toReport source err =
357355 (
358356 D.reflow $
359357 "You are trying to import the `" <> Name.toChars ctor
360− <> "` variant by name:"
358+ <> "` type constructor by name:"
361359 ,
362360 D.fillSep
363361 ["Try","importing",D.green (D.fromName tipe <> "(..)"),"instead."
364362 ,"The","dots","mean","“expose","the",D.fromName tipe,"type","and"
365− ,"all","its","variants","so","it","gives","you","access","to"
363+ ,"all","its","constructors”","so","it","gives","you","access","to"
366364 , D.fromName ctor <> "."
367365 ]
368366 )
@@ -388,8 +386,13 @@ toReport source err =
388386 D.reflow $
389387 "The `" <> Name.toChars name <> "` type alias cannot be followed by (..) like this:"
390388 ,
391− D.reflow $
392− "Remove the (..) and it should work."
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+ ]
393396 )
394397
395398 ImportExposingNotFound region (ModuleName.Canonical _ home) value possibleNames ->
@@ -519,7 +522,7 @@ toReport source err =
519522 <> "` as a function, but it is not available in pattern matching like this:"
520523 ,
521524 D.reflow $
522− "I recommend matching the record as a variable and unpacking it later."
525+ "I recommend matching matching the record as a variable and unpacking it later."
523526 )
524527
525528 PortPayloadInvalid region portName _badType invalidPayload ->
@@ -679,7 +682,7 @@ toReport source err =
679682 "The `" <> Name.toChars name <> "` value is defined directly in terms of itself, causing an infinite loop."
680683 ,
681684 D.stack
682− [ makeTheory "Are you trying to mutate a variable?" $
685+ [ makeTheory "Are you are trying to mutate a variable?" $
683686 "Elm does not have mutation, so when I see " ++ Name.toChars name
684687 ++ " defined in terms of " ++ Name.toChars name
685688 ++ ", I treat it as a recursive definition. Try giving the new value a new name!"
@@ -725,7 +728,7 @@ toReport source err =
725728 "The `" <> Name.toChars name <> "` value is defined directly in terms of itself, causing an infinite loop."
726729 ,
727730 D.stack
728− [ makeTheory "Are you trying to mutate a variable?" $
731+ [ makeTheory "Are you are trying to mutate a variable?" $
729732 "Elm does not have mutation, so when I see " ++ Name.toChars name
730733 ++ " defined in terms of " ++ Name.toChars name
731734 ++ ", I treat it as a recursive definition. Try giving the new value a new name!"
@@ -976,32 +979,28 @@ nameClash source r1 r2 messageThatEndsWithPunctuation =
976979-- AMBIGUOUS NAME
977980
978981
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
982+ambiguousName :: Code.Source -> A.Region -> Maybe Name.Name -> Name.Name -> [ModuleName.Canonical] -> String -> Report.Report
983+ambiguousName source region maybePrefix name possibleHomes thing =
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 <> "." <> D.fromName name)
990+ D.dullyellow (D.fromName home)
991+
992+ bothOrAll =
993+ if length possibleHomes == 2 then "both" else "all"
991994 in
992995 (
993− D.reflow $ "This usage of `" ++ Name.toChars name ++ "` is ambiguous:"
996+ D.reflow $ "This usage of `" ++ Name.toChars name ++ "` is ambiguous."
994997 ,
995998 D.stack
996999 [ D.reflow $
997− "This name is exposed by " ++ show (length possibleHomes) ++ " of your imports, so I am not\
998− \ sure which one to use:"
1000+ "Check your imports. The following modules " ++ bothOrAll
1001+ ++ " expose a `" ++ Name.toChars name ++ "` " ++ thing ++ ":"
9991002 , D.indent 4 $ D.vcat $ map homeToYellowDoc possibleHomes
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."
1003+ , D.reflowLink "Read" "imports" "to learn how to clarify which one you want."
10051004 ]
10061005 )
10071006
@@ -1009,9 +1008,9 @@ ambiguousName source region maybePrefix name h hs thing =
10091008 let
10101009 homeToYellowDoc (ModuleName.Canonical _ home) =
10111010 if prefix == home then
1012− D.cyan "import" <+> D.fromName home
1011+ D.blue "import" <+> D.dullyellow (D.fromName home)
10131012 else
1014− D.cyan "import" <+> D.fromName home <+> D.cyan "as" <+> D.fromName prefix
1013+ D.blue "import" <+> D.dullyellow (D.fromName home) <+> D.blue "as" <+> D.dullyellow (D.fromName prefix)
10151014
10161015 eitherOrAny =
10171016 if length possibleHomes == 2 then "either" else "any"
compiler/src/Reporting/Error/Docs.hs+18−127
@@ -2,24 +2,17 @@
22{-# LANGUAGE OverloadedStrings #-}
33module Reporting.Error.Docs
44 ( Error(..)
5− , SyntaxProblem(..)
6− , NameProblem(..)
7− , DefProblem(..)
8− , toReports
5+ , toReport
96 )
107 where
118
129
1310import qualified Data.Name as Name
14−import qualified Data.NonEmptyList as NE
1511
16−import Parse.Primitives (Row, Col)
17−import Parse.Symbol (BadOperator(..))
1812import qualified Reporting.Annotation as A
1913import Reporting.Doc ((<>))
2014import qualified Reporting.Doc as D
2115import qualified Reporting.Render.Code as Code
22−import qualified Reporting.Error.Syntax as E
2316import qualified Reporting.Report as Report
2417
2518
@@ -27,56 +20,36 @@ import qualified Reporting.Report as Report
2720data Error
2821 = NoDocs A.Region
2922 | ImplicitExposing A.Region
30− | SyntaxProblem SyntaxProblem
31− | NameProblems (NE.List NameProblem)
32− | DefProblems (NE.List DefProblem)
33−
34−
35−data SyntaxProblem
36− = Op Row Col
37− | OpBad BadOperator Row Col
38− | Name Row Col
39− | Space E.Space Row Col
40− | Comma Row Col
41− | BadEnd Row Col
42−
43−
44−data NameProblem
45− = NameDuplicate Name.Name A.Region A.Region
46− | NameOnlyInDocs Name.Name A.Region
47− | NameOnlyInExports Name.Name A.Region
48−
49−
50−data DefProblem
51− = NoComment Name.Name A.Region
23+ | Duplicate Name.Name A.Region A.Region
24+ | OnlyInDocs Name.Name A.Region
25+ | OnlyInExports Name.Name A.Region
26+ | NoComment Name.Name A.Region
5227 | NoAnnotation Name.Name A.Region
5328
5429
5530
56−-- TO REPORTS
31+-- TO REPORT
5732
5833
59−toReports :: Code.Source -> Error -> NE.List Report.Report
60−toReports source err =
34+toReport :: Code.Source -> Error -> Report.Report
35+toReport source err =
6136 case err of
6237 NoDocs region ->
63− NE.singleton $
6438 Report.Report "NO DOCS" region [] $
65− Code.toSnippet source region Nothing
66− (
39+ D.stack
40+ [
6741 D.reflow $
6842 "You must have a documentation comment between the module\
6943 \ declaration and the imports."
7044 ,
7145 D.reflow
72− "Learn more at <https://package.elm-lang.org/help/documentation-format>"
73− )
46+ "Learn more at <http://package.elm-lang.org/help/documentation-format>"
47+ ]
7448
7549 ImplicitExposing region ->
76− NE.singleton $
7750 Report.Report "IMPLICIT EXPOSING" region [] $
78− Code.toSnippet source region Nothing
79− (
51+ D.stack
52+ [
8053 D.reflow $
8154 "I need you to be explicit about what this module exposes:"
8255 ,
@@ -86,83 +59,9 @@ toReports source err =
8659 \ to be explicit about this is a way of adding another quality check before\
8760 \ code gets published. So as you write out the public API, ask yourself if\
8861 \ it will be easy to understand as people read the documentation!"
89− )
90−
91− SyntaxProblem problem ->
92− NE.singleton $
93− toSyntaxProblemReport source problem
94−
95− NameProblems problems ->
96− fmap (toNameProblemReport source) problems
97−
98− DefProblems problems ->
99− fmap (toDefProblemReport source) problems
100−
101−
102−
103−-- SYNTAX PROBLEM
104−
62+ ]
10563
106−toSyntaxProblemReport :: Code.Source -> SyntaxProblem -> Report.Report
107−toSyntaxProblemReport source problem =
108− let
109− toSyntaxReport row col details =
110− let
111− region = toRegion row col
112− in
113− Report.Report "PROBLEM IN DOCS" region [] $
114− Code.toSnippet source region Nothing
115− ( D.reflow "I was partway through parsing your module documentation, but I got stuck here:"
116− , D.stack $
117− [ D.reflow details
118− , D.toSimpleHint $
119− "Read through <https://package.elm-lang.org/help/documentation-format> for\
120− \ tips on how to write module documentation!"
121− ]
122− )
123− in
124− case problem of
125− Op row col ->
126− toSyntaxReport row col $
127− "I am trying to parse an operator like (+) or (*) but something is going wrong."
128−
129− OpBad _ row col ->
130− toSyntaxReport row col $
131− "I am trying to parse an operator like (+) or (*) but it looks like you are using\
132− \ a reserved symbol in this case."
133−
134− Name row col ->
135− toSyntaxReport row col $
136− "I was expecting to see the name of another exposed value from this module."
137−
138− Space space row col ->
139− E.toSpaceReport source space row col
140−
141− Comma row col ->
142− toSyntaxReport row col $
143− "I was expecting to see a comma next."
144−
145− BadEnd row col ->
146− toSyntaxReport row col $
147− "I am not really sure what I am getting stuck on though."
148−
149−
150−toRegion :: Row -> Col -> A.Region
151−toRegion row col =
152− let
153− pos = A.Position row col
154− in
155− A.Region pos pos
156−
157−
158−
159−-- NAME PROBLEM
160−
161−
162−toNameProblemReport :: Code.Source -> NameProblem -> Report.Report
163−toNameProblemReport source problem =
164− case problem of
165− NameDuplicate name r1 r2 ->
64+ Duplicate name r1 r2 ->
16665 Report.Report "DUPLICATE DOCS" r2 [] $
16766 Code.toPair source r1 r2
16867 (
@@ -182,7 +81,7 @@ toNameProblemReport source problem =
18281 "Remove one of them!"
18382 )
18483
185− NameOnlyInDocs name region ->
84+ OnlyInDocs name region ->
18685 Report.Report "DOCS MISTAKE" region [] $
18786 Code.toSnippet source region Nothing
18887 (
@@ -195,7 +94,7 @@ toNameProblemReport source problem =
19594 <> Name.toChars name <> "` and forgot to delete it here?"
19695 )
19796
198− NameOnlyInExports name region ->
97+ OnlyInExports name region ->
19998 Report.Report "DOCS MISTAKE" region [] $
20099 Code.toSnippet source region Nothing
201100 (
@@ -211,14 +110,6 @@ toNameProblemReport source problem =
211110 ]
212111 )
213112
214−
215−
216−-- DEF PROBLEM
217−
218−
219−toDefProblemReport :: Code.Source -> DefProblem -> Report.Report
220−toDefProblemReport source problem =
221− case problem of
222113 NoComment name region ->
223114 Report.Report "NO DOCS" region [] $
224115 Code.toSnippet source region Nothing
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\" listed in your elm.json,\
59+ "I checked the \"dependencies\" and \"source-directories\" listend 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+269−281
@@ -1,344 +1,332 @@
11{-# OPTIONS_GHC -Wall #-}
22{-# LANGUAGE OverloadedStrings #-}
33module Reporting.Error.Json
4− ( toReport
5− , FailureToReport(..)
6− , Context(..)
7− , Reason(..)
4+ ( Error(..)
5+ , Problem(..)
6+ , DecodeExpectation(..)
7+ , ParseError(..)
8+ , toReport
89 )
910 where
1011
1112
12−import qualified Data.ByteString as BS
13−import qualified Data.ByteString.UTF8 as BS_UTF8
14−import qualified Data.NonEmptyList as NE
13+import qualified Data.Utf8 as Utf8
14+import Data.Word (Word16)
1515
16−import Json.Decode (Error(..), Problem(..), DecodeExpectation(..), ParseError(..), StringProblem(..))
17−import qualified Reporting.Annotation as A
18−import qualified Reporting.Doc as D
19−import qualified Reporting.Exit.Help as Help
20−import qualified Reporting.Render.Code as Code
16+import qualified Reporting.Report as Report
2117
2218
2319
24−-- TO REPORT
20+-- ERROR
2521
2622
27−toReport :: FilePath -> FailureToReport x -> Error x -> Reason -> Help.Report
28−toReport path ftr err reason =
29− case err of
30− DecodeProblem bytes problem ->
31− problemToReport path ftr (Code.toSource bytes) CRoot problem reason
23+data Error e
24+ = DecodeProblem (Problem e)
25+ | ParseProblem ParseError
3226
33− ParseProblem bytes parseError ->
34− parseErrorToReport path (Code.toSource bytes) parseError reason
3527
3628
37−newtype Reason =
38− ExplicitReason String
29+-- DECODE PROBLEMS
3930
4031
41−because :: Reason -> String -> String
42−because (ExplicitReason iNeedThings) problem =
43− iNeedThings ++ " " ++ problem
32+data Problem e
33+ = Field Utf8.String (Problem e)
34+ | Index Int (Problem e)
35+ | OneOf (Problem e) [Problem e]
36+ | Failure e
37+ | Expecting DecodeExpectation
4438
4539
40+data DecodeExpectation
41+ = TObject
42+ | TArray
43+ | TString
44+ | TBool
45+ | TInt
46+ | TObjectWith Utf8.String
47+ | TArrayPair Int
4648
47−-- PARSE ERROR TO REPORT
4849
4950
50−parseErrorToReport :: FilePath -> Code.Source -> ParseError -> Reason -> Help.Report
51−parseErrorToReport path source parseError reason =
52− let
53− toSnippet title row col (problem, details) =
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
59− Help.jsonReport title (Just path) $
60− Code.toSnippet source surroundings (Just region)
61− ( D.reflow (because reason problem)
62− , details
63− )
64− in
65− case parseError of
66− Start row col ->
67− toSnippet "EXPECTING A VALUE" row col
68− (
69− "I was expecting to see a JSON value next:"
70− ,
71− D.stack
72− [ D.fillSep
73− ["Try","something","like",D.dullyellow "\"this\"","or"
74− ,D.dullyellow "42","to","move","on","to","better","hints!"
75− ]
76− , D.toSimpleNote $
77− "The JSON specification does not allow trailing commas, so you can sometimes\
78− \ get this error in arrays that have an extra comma at the end. In that case,\
79− \ remove that last comma or add another array entry after it!"
80− ]
81− )
51+-- PARSE ERROR
8252
83− ObjectField row col ->
84− toSnippet "EXTRA COMMA" row col
85− (
86− "I was partway through parsing a JSON object when I got stuck here:"
87− ,
88− D.stack
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."
98− , objectNote
99− ]
100− )
10153
102− ObjectColon row col ->
103− toSnippet "EXPECTING COLON" row col
104− (
105− "I was partway through parsing a JSON object when I got stuck here:"
106− ,
107− D.stack
108− [ D.reflow $ "I was expecting to see a colon next."
109− , objectNote
110− ]
111− )
54+data ParseError
55+ = PIndex Int ParseError Row Col
56+ | PField Utf8.String ParseError Row Col
57+ | ObjectStart Row Col
58+ | ObjectMore Row Col
59+ | ObjectEnd Row Col
60+ | ArrayStart Row Col
61+ | ArrayMore Row Col
62+ | ArrayEnd Row Col
63+ | StringStart Row Col
64+ | StringEnd Row Col
65+ | IntStart Row Col
66+ | NoLeadingZeros Row Col
67+ | NoFloats Row Col
68+ | Bool Row Col
69+ | Null Row Col
70+ | Value Row Col
71+ | Colon Row Col
72+ | EndOfFile Row Col
11273
113− ObjectEnd row col ->
114− toSnippet "UNFINISHED OBJECT" row col
115− (
116− "I was partway through parsing a JSON object when I got stuck here:"
117− ,
118− D.stack
74+
75+type Row = Word16
76+type Col = Word16
77+
78+
79+
80+-- TO REPORT
81+
82+
83+toReport :: Error e -> Report.Report
84+toReport err =
85+ error "TODO Reporting.Error.Json.toReport" err
86+
87+
88+{-
89+
90+-- ERROR
91+
92+
93+data Error e
94+ = BadJson Syntax.Error
95+ | BadContent (Json.Error e)
96+
97+
98+
99+-- TO DOC
100+
101+
102+toDoc :: String -> Code.Source -> (e -> [D.Doc]) -> Error e -> D.Doc
103+toDoc rootName source userErrorToDocs err =
104+ case err of
105+ BadJson syntaxError ->
106+ case Syntax.toReport source syntaxError of
107+ Report.Report _ _ _ doc ->
108+ doc
109+
110+ BadContent jsonError ->
111+ case flatten jsonError of
112+ [] ->
113+ D.reflow
114+ "I am not sure what is wrong with this JSON. Please create an <http://sscce.org>\
115+ \ and share it at <https://github.com/elm/compiler/issues> so I can\
116+ \ provide a helpful hint here!"
117+
118+ [flatError] ->
119+ flatErrorToDoc rootName [] userErrorToDocs flatError
120+
121+ flatErrors ->
122+ let
123+ toNumberedDoc index flatErr =
124+ D.dullcyan ("(" <> D.fromInt index <> ")") <+> flatErrorToDoc rootName [] userErrorToDocs flatErr
125+ in
126+ D.stack $
119127 [ D.reflow $
120− "I was expecting to see a comma or a closing curly brace next."
121− , D.reflow $
122− "Is a comma missing on the previous line? Is an array missing a closing square\
123− \ bracket? It is often something tricky like that!"
124− , objectNote
128+ "I have " ++ show (length flatErrors) ++ " theories on what is going wrong:"
125129 ]
126− )
130+ ++ zipWith toNumberedDoc [1..] flatErrors
131+
132+
133+
134+-- FLAT ERROR TO DOC
127135
128− ArrayEnd row col ->
129− toSnippet "UNFINISHED ARRAY" row col
130− (
131− "I was partway through parsing a JSON array when I got stuck here:"
132− ,
136+
137+flatErrorToDoc :: String -> [D.Doc] -> (e -> [D.Doc]) -> FlatError e -> D.Doc
138+flatErrorToDoc rootName starter userErrorToDocs (FlatError accesses json theory theories) =
139+ case theories of
140+ [] ->
141+ let
142+ explanation =
143+ case theory of
144+ Failure userError ->
145+ userErrorToDocs userError
146+
147+ Expecting tipe ->
148+ ["I","was","expecting"] ++ anExpectedThing tipe
149+ in
150+ case accesses of
151+ [] ->
152+ D.fillSep (starter ++ explanation)
153+
154+ _ ->
133155 D.stack
134− [ D.reflow $ "I was expecting to see a comma or a closing square bracket next."
135− , D.reflow $
136− "Is a comma missing on the previous line? It is often something like that!"
156+ [ D.fillSep $ starter ++ ["The"] ++ actualThing json ++ ["at",accessToDoc rootName accesses,"is","causing","issues."]
157+ , D.fillSep explanation
137158 ]
138− )
139−
140− StringProblem stringProblem row col ->
141− case stringProblem of
142− BadStringEnd ->
143− toSnippet "ENDLESS STRING" row col
144− (
145− "I got to the end of the line without seeing the closing double quote:"
146− ,
147− D.fillSep $
148− ["Strings","look","like",D.green "\"this\"","with","double"
149− ,"quotes","on","each","end.","Is","the","closing","double"
150− ,"quote","missing","in","your","code?"
151− ]
152− )
153−
154− BadStringControlChar ->
155− toSnippet "UNEXPECTED CONTROL CHARACTER" row col
156− (
157− "I ran into a control character unexpectedly:"
158− ,
159− D.reflow $
160− "These are characters that represent tabs, backspaces, newlines, and\
161− \ a bunch of other invisible characters. They all come before 20 in the\
162− \ ASCII range, and they are disallowed by the JSON specificaiton. Maybe\
163− \ a copy/paste added one of these invisible characters to your JSON?"
164− )
165−
166− BadStringEscapeChar ->
167− toSnippet "UNKNOWN ESCAPE" row col
168− (
169− "Backslashes always start escaped characters, but I do not recognize this one:"
170− ,
171− D.stack
172− [ D.reflow $
173− "Valid escape characters include:"
174− , D.dullyellow $ D.indent 4 $ D.vcat $
175− ["\\\"","\\\\","\\/","\\b","\\f","\\n","\\r","\\t","\\u003D"]
176− , D.reflow $
177− "Do you want one of those instead? Maybe you need \\\\ to escape a backslash?"
178− ]
179− )
180−
181− BadStringEscapeHex ->
182− toSnippet "BAD HEX ESCAPE" row col
183− (
184− "This is not a valid hex escape:"
185− ,
186− D.fillSep $
187− ["Valid","hex","escapes","in","JSON","are","between"
188− ,D.green "\\u0000","and",D.green "\\uFFFF"
189− ,"and","always","have","exactly","four","digits."
190− ]
191− )
192−
193− NoLeadingZeros row col ->
194− toSnippet "BAD NUMBER" row col
195− (
196− "Numbers cannot start with zeros like this:"
197− ,
198− D.reflow $ "Try deleting the leading zeros?"
199− )
200−
201− NoFloats row col ->
202− toSnippet "UNEXPECTED NUMBER" row col
203− (
204− "I got stuck while trying to parse this number:"
205− ,
206− D.reflow $
207− "I do not accept floating point numbers like 3.1415 right now. That kind\
208− \ of JSON value is not needed for any of the uses that Elm has for now."
209− )
210−
211− BadEnd row col ->
212− toSnippet "JSON PROBLEM" row col
213− (
214− "I was partway through parsing some JSON when I got stuck here:"
215− ,
216− D.reflow $
217− "I am not really sure what is wrong. This sometimes means there is extra\
218− \ stuff after a valid JSON value?"
219− )
220−
221−
222−objectNote :: D.Doc
223−objectNote =
224− D.stack
225− [ D.toSimpleNote $ "Here is an example of a valid JSON object for reference:"
226− , D.vcat
227− [ D.indent 4 $ "{"
228− , D.indent 6 $ D.dullyellow "\"name\"" <> ": " <> D.dullyellow "\"Tom\"" <> ","
229− , D.indent 6 $ D.dullyellow "\"age\"" <> ": " <> D.dullyellow "42"
230− , D.indent 4 $ "}"
159+
160+ _:_ ->
161+ let
162+ introduction =
163+ case accesses of
164+ [] ->
165+ ["I","am","having","trouble","with","the"]
166+ ++ actualThing json
167+ ++ ["here","because:"]
168+
169+ _ ->
170+ ["I","am","having","trouble","with","the"]
171+ ++ actualThing json
172+ ++ ["at",accessToDoc rootName accesses,"because:"]
173+ in
174+ D.stack
175+ [ D.fillSep (starter ++ introduction)
176+ , D.stack (toBullet [] userErrorToDocs theory : map (toBullet ["OR"] userErrorToDocs) theories)
177+ , D.reflow "I accept any of these things."
231178 ]
232− , D.reflow $
233− "Notice that (1) the field names are in double quotes and (2) there is no\
234− \ trailing comma after the last entry. Both are strict requirements in JSON!"
235− ]
236179
237180
181+accessToDoc :: String -> [String] -> D.Doc
182+accessToDoc rootName accesses =
183+ D.dullyellow (D.fromString (rootName ++ concat accesses))
238184
239−-- PROBLEM TO REPORT
240185
186+actualThing :: E.Value -> [D.Doc]
187+actualThing json =
188+ case json of
189+ E.Array _ -> [D.red "array"]
190+ E.Object _ -> [D.red "object"]
191+ E.String _ -> [D.red "string"]
192+ E.Boolean b -> [D.red (if b then "true" else "false"),"value"]
193+ E.Integer n -> ["number",D.red (D.fromInt n)]
194+ E.Number _ -> [D.red "number"]
195+ E.Null -> [D.red "null","value"]
241196
242−data Context
243− = CRoot
244− | CField BS.ByteString Context
245− | CIndex Int Context
246197
198+anExpectedThing :: Json.Type -> [D.Doc]
199+anExpectedThing tipe =
200+ case tipe of
201+ Json.TObject -> ["an", D.green "OBJECT" <> "."]
202+ Json.TArray -> ["an", D.green "ARRAY" <> "."]
203+ Json.TString -> ["a", D.green "STRING" <> "."]
204+ Json.TBool -> ["a", D.green "BOOLEAN" <> "."]
205+ Json.TInt -> ["an", D.green "INT" <> "."]
206+ Json.TObjectWith field -> ["an",D.green "OBJECT","with","a",D.green ("\"" <> D.fromString (Text.unpack field) <> "\""),"field."]
207+ Json.TArrayPair len ->
208+ ["an",D.green "ARRAY","with",D.green "TWO","entries."
209+ ,"This","array","has",D.fromInt len, if len == 1 then "element." else "elements."
210+ ]
247211
248−problemToReport :: FilePath -> FailureToReport x -> Code.Source -> Context -> Problem x -> Reason -> Help.Report
249−problemToReport path ftr source context problem reason =
250− case problem of
251− Field field prob ->
252− problemToReport path ftr source (CField field context) prob reason
253212
254− Index index prob ->
255− problemToReport path ftr source (CIndex index context) prob reason
213+toBullet :: [D.Doc] -> (e -> [D.Doc]) -> Theory e -> D.Doc
214+toBullet intro userErrorToDocs theory =
215+ D.indent 4 $ D.fillSep $ (++) intro $
216+ case theory of
217+ Failure userError ->
218+ userErrorToDocs userError
256219
257− OneOf p ps ->
258− -- NOTE: only displays the deepest problem. This works well for the kind
259− -- of JSON used by Elm, but probably would not work well in general.
260− let
261− (NE.List prob _) = NE.sortBy (negate . getMaxDepth) (NE.List p ps)
262− in
263− problemToReport path ftr source context prob reason
220+ Expecting tipe ->
221+ ["I","was","expecting"] ++ anExpectedThing tipe
222+
223+
224+
225+-- TO FLAT ERRORS
264226
265− Failure region x ->
266− _failureToReport ftr path source context region x
267227
268− Expecting region expectation ->
269− expectationToReport path source context region expectation reason
228+data FlatError e =
229+ FlatError [String] E.Value (Theory e) [Theory e]
270230
271231
272−getMaxDepth :: Problem x -> Int
273−getMaxDepth problem =
274− case problem of
275− Field _ prob -> 1 + getMaxDepth prob
276− Index _ prob -> 1 + getMaxDepth prob
277− OneOf p ps -> maximum (getMaxDepth p : map getMaxDepth ps)
278− Failure _ _ -> 0
279− Expecting _ _ -> 0
232+data Theory e
233+ = Failure e
234+ | Expecting Json.Type
280235
281236
282−newtype FailureToReport x =
283− FailureToReport { _failureToReport :: FilePath -> Code.Source -> Context -> A.Region -> x -> Help.Report }
237+flatten :: Json.Error e -> [FlatError e]
238+flatten jsonError =
239+ let
240+ depth (FlatError accesses _ _ _) =
241+ length accesses
242+ in
243+ List.sortOn depth $ flattenTree (toErrorTree jsonError)
284244
285245
286−expectationToReport :: FilePath -> Code.Source -> Context -> A.Region -> DecodeExpectation -> Reason -> Help.Report
287−expectationToReport path source context (A.Region start end) expectation reason =
246+flattenTree :: ErrorTree e -> [FlatError e]
247+flattenTree (ErrorTree theories subTrees) =
288248 let
289− (A.Position sr _) = start
290− (A.Position er _) = end
249+ addAccess access (FlatError accesses json t ts) =
250+ FlatError (access:accesses) json t ts
291251
292− region =
293− if sr == er then region else A.Region start start
252+ toFlats (name, tree) =
253+ map (addAccess name) (flattenTree tree)
254+
255+ subErrors =
256+ concatMap toFlats (Map.toList subTrees)
257+ in
258+ case theories of
259+ [] ->
260+ subErrors
294261
295− introduction =
296− case context of
297− CRoot ->
298− "I ran into some trouble here:"
262+ (json, theory) : rest ->
263+ FlatError [] json theory (map snd rest) : subErrors
299264
300− CField field _ ->
301− "I ran into trouble with the value of the \"" ++ BS_UTF8.toString field ++ "\" field:"
302265
303− CIndex index (CField field _) ->
304− "When looking at the \"" ++ BS_UTF8.toString field ++ "\" field, I ran into trouble with the "
305− ++ D.intToOrdinal index ++ " entry:"
306266
307− CIndex index _ ->
308− "I ran into trouble with the " ++ D.intToOrdinal index ++ " index of this array:"
267+-- TO ERROR TREE
309268
310− toSnippet title aThing =
311− Help.jsonReport title (Just path) $
312− Code.toSnippet source region Nothing
313− ( D.reflow (because reason introduction)
314− , D.fillSep $ ["I","was","expecting","to","run","into"] ++ aThing
315− )
269+
270+data ErrorTree e =
271+ ErrorTree
272+ { _theories :: [(E.Value, Theory e)]
273+ , _subErrors :: Map.Map String (ErrorTree e)
274+ }
275+
276+
277+toErrorTree :: Json.Error e -> ErrorTree e
278+toErrorTree jsonError =
279+ add jsonError empty
280+
281+
282+empty :: ErrorTree e
283+empty =
284+ ErrorTree [] Map.empty
285+
286+
287+add :: Json.Error e -> ErrorTree e -> ErrorTree e
288+add jsonError tree@(ErrorTree theories subErrors) =
289+ case jsonError of
290+ Json.Field field subErr ->
291+ ErrorTree theories (addName (fieldToName field) subErr subErrors)
292+
293+ Json.Index index subErr ->
294+ ErrorTree theories (addName (indexToName index) subErr subErrors)
295+
296+ Json.OneOf errors ->
297+ foldr add tree errors
298+
299+ Json.Expecting json tipe ->
300+ ErrorTree ((json, Expecting tipe) : theories) subErrors
301+
302+ Json.Failure json err ->
303+ ErrorTree ((json, Failure err) : theories) subErrors
304+
305+
306+addName :: String -> Json.Error e -> Map.Map String (ErrorTree e) -> Map.Map String (ErrorTree e)
307+addName name err subErrors =
308+ let
309+ subAdd maybeCrush =
310+ Just (add err (maybe empty id maybeCrush))
316311 in
317− case expectation of
318− TObject ->
319− toSnippet "EXPECTING OBJECT" ["an", D.green "OBJECT" <> "."]
312+ Map.alter subAdd name subErrors
320313
321− TArray ->
322− toSnippet "EXPECTING ARRAY" ["an", D.green "ARRAY" <> "."]
323314
324− TString ->
325− toSnippet "EXPECTING STRING" ["a", D.green "STRING" <> "."]
315+fieldToName :: Text.Text -> String
316+fieldToName field =
317+ case Text.unpack field of
318+ [] ->
319+ "['']"
326320
327− TBool ->
328− toSnippet "EXPECTING BOOL" ["a", D.green "BOOLEAN" <> "."]
321+ string@(char : rest) ->
322+ if Char.isAlpha char && all Char.isAlphaNum rest then
323+ '.' : string
324+ else
325+ "['" ++ string ++ "']"
329326
330− TInt ->
331− toSnippet "EXPECTING INT" ["an", D.green "INT" <> "."]
332327
333− TObjectWith field ->
334− toSnippet "MISSING FIELD"
335− ["an",D.green "OBJECT","with","a"
336− ,D.green ("\"" <> D.fromChars (BS_UTF8.toString field) <> "\"")
337− ,"field."
338− ]
328+indexToName :: Int -> String
329+indexToName index =
330+ "[" ++ show index ++ "]"
339331
340− TArrayPair len ->
341− toSnippet "EXPECTING PAIR"
342− ["an",D.green "ARRAY","with",D.green "TWO","entries."
343− ,"This","array","has",D.fromInt len, if len == 1 then "element." else "elements."
344− ]
332+-}
compiler/src/Reporting/Error/Pattern.hs+4−5
@@ -8,7 +8,6 @@ module Reporting.Error.Pattern
88
99import qualified Data.List as List
1010
11−import qualified Elm.String as ES
1211import qualified Nitpick.PatternMatches as P
1312import Reporting.Doc ((<>))
1413import qualified Reporting.Doc as D
@@ -41,7 +40,7 @@ toReport source err =
4140 Report.Report "UNSAFE PATTERN" region [] $
4241 Code.toSnippet source region Nothing
4342 (
44− "This pattern does not cover all possibilities:"
43+ "This pattern does not cover all possiblities:"
4544 ,
4645 D.stack
4746 [ "Other possibilities include:"
@@ -64,7 +63,7 @@ toReport source err =
6463 , unhandledPatternsToDocBlock unhandled
6564 , D.reflow $
6665 "I would have to crash if I saw one of those! You can use\
67− \ `let` to deconstruct values only if there is ONE possibility.\
66+ \ `let` to deconstruct values only if there is ONE possiblity.\
6867 \ Switch to a `case` expression to account for all possibilities."
6968 , D.toSimpleHint $
7069 "Are you calling a function that definitely returns values\
@@ -118,10 +117,10 @@ patternToDoc context pattern =
118117 NonList (P.Literal literal) ->
119118 case literal of
120119 P.Chr chr ->
121− "'" <> D.fromChars (ES.toChars chr) <> "'"
120+ "'" <> D.fromUtf8 chr <> "'"
122121
123122 P.Str str ->
124− "\"" <> D.fromChars (ES.toChars str) <> "\""
123+ "\"" <> D.fromUtf8 str <> "\""
125124
126125 P.Int int ->
127126 D.fromInt int
compiler/src/Reporting/Error/Syntax.hs+460−1036
@@ -2,7 +2,6 @@
22{-# LANGUAGE OverloadedStrings #-}
33module Reporting.Error.Syntax
44 ( Error(..)
5− , toReport
65 --
76 , Module(..)
87 , Exposing(..)
@@ -40,7 +39,7 @@ module Reporting.Error.Syntax
4039 , Number(..)
4140 --
4241 , Space(..)
43− , toSpaceReport
42+ , toReport
4443 )
4544 where
4645
@@ -69,9 +68,6 @@ data Error
6968 | ModuleNameMismatch ModuleName.Raw (A.Located ModuleName.Raw)
7069 | UnexpectedPort A.Region
7170 | NoPorts A.Region
72− | NoPortsInPackage (A.Located Name.Name)
73− | NoPortModulesInPackage A.Region
74− | NoEffectsOutsideKernel A.Region
7571 | ParseError Module
7672
7773
@@ -81,7 +77,7 @@ data Error
8177
8278data Module
8379 = ModuleSpace Space Row Col
84− | ModuleBadEnd Row Col
80+ | ModuleEndOfFile Row Col
8581 --
8682 | ModuleProblem Row Col
8783 | ModuleName Row Col
@@ -520,7 +516,7 @@ toReport source err =
520516 ,
521517 D.stack
522518 [ D.reflow $
523− "I need it to match the file path, so I was expecting to see `"
519+ "I need it to match the file path, so I was expecting it to see `"
524520 ++ ModuleName.toChars expectedName
525521 ++ "` here. Make the following change, and you should be all set!"
526522 , D.indent 4 $
@@ -564,94 +560,75 @@ toReport source err =
564560 ]
565561 )
566562
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−
619563 ParseError modul ->
620564 toParseErrorReport source modul
621565
622566
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−
645567toParseErrorReport :: Code.Source -> Module -> Report.Report
646568toParseErrorReport source modul =
647569 case modul of
648570 ModuleSpace space row col ->
649571 toSpaceReport source space row col
650572
651− ModuleBadEnd row col ->
652− if col == 1
653− then toDeclStartReport source row col
654− else toWeirdEndReport source row col
573+ ModuleEndOfFile row col ->
574+ case Code.whatIsNext source row col of
575+ Code.Keyword keyword ->
576+ let
577+ region = toKeywordRegion row col keyword
578+ in
579+ Report.Report "RESERVED WORD" region [] $
580+ Code.toSnippet source region Nothing
581+ (
582+ D.reflow $
583+ "I got stuck on this reserved word:"
584+ ,
585+ D.reflow $
586+ "The name `" ++ keyword ++ "` is reserved, so try using a different name?"
587+ )
588+
589+ Code.Operator op ->
590+ let
591+ region = toKeywordRegion row col op
592+ in
593+ Report.Report "UNEXPECTED SYMBOL" region [] $
594+ Code.toSnippet source region Nothing
595+ (
596+ D.reflow $
597+ "I ran into an unexpected symbol:"
598+ ,
599+ D.reflow $
600+ "I was not expecting to see a " ++ op ++ " here. Try deleting it? Maybe\
601+ \ I can give a better hint from there?"
602+ )
603+
604+ Code.Close term bracket ->
605+ let
606+ region = toRegion row col
607+ in
608+ Report.Report ("UNEXPECTED " ++ map Char.toUpper term) region [] $
609+ Code.toSnippet source region Nothing
610+ (
611+ D.reflow $
612+ "I ran into an unexpected " ++ term ++ ":"
613+ ,
614+ D.reflow $
615+ "This " ++ bracket : " does not match up with an earlier open " ++ term ++ ". Try deleting it?"
616+ )
617+
618+ Code.Other ->
619+ let
620+ region = toRegion row col
621+ in
622+ Report.Report "SYNTAX PROBLEM" region [] $
623+ Code.toSnippet source region Nothing
624+ (
625+ D.reflow $
626+ "I got stuck here:"
627+ ,
628+ D.reflow $
629+ "Whatever I am running into is confusing me a lot! Normally I can give fairly\
630+ \ specific hints, but something is really tripping me up this time."
631+ )
655632
656633 ModuleProblem row col ->
657634 let
@@ -797,15 +774,15 @@ toParseErrorReport source modul =
797774 [ D.reflow $
798775 "I am not sure what is going on, but I recommend starting an Elm\
799776 \ file with the following lines:"
800− , D.indent 4 $ D.vcat $
777+ , D.vcat
801778 [ D.fillSep [D.cyan "import","Html"]
802779 , ""
803− , "main ="
804− , " Html.text " <> D.dullyellow "\"Hello!\""
780+ , D.fillSep [D.green "main","="]
781+ , D.indent 2 $ D.fillSep [D.cyan "Html" <> ".text",D.dullyellow "\"Hello!\""]
805782 ]
806783 , D.reflow $
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!"
784+ "You should be able to copy those lines directly into your file. Check out\
785+ \ some of the examples on https://elm-lang.org for more help getting started!"
809786 , D.toSimpleNote $
810787 "This can also happen when something is indented too much!"
811788 ]
@@ -830,12 +807,11 @@ toParseErrorReport source modul =
830807 , D.indent 4 $ D.vcat $
831808 [ D.fillSep [D.cyan "import","Dict"]
832809 , D.fillSep [D.cyan "import","Maybe"]
833− , D.fillSep [D.cyan "import","Html.Attributes",D.cyan "as","A"]
834− , D.fillSep [D.cyan "import","Json.Decode",D.cyan "exposing","(..)"]
810+ , D.fillSep [D.cyan "import","Html.Attributes"]
811+ , D.fillSep [D.cyan "import","Json.Decode"]
835812 ]
836813 , D.reflow $
837814 "Notice that the module names all start with capital letters. That is required!"
838− , D.reflowLink "Read" "imports" "to learn more."
839815 ]
840816 )
841817
@@ -846,7 +822,7 @@ toParseErrorReport source modul =
846822 let
847823 region = toRegion row col
848824 in
849− Report.Report "EXPECTING IMPORT ALIAS" region [] $
825+ Report.Report "EXECTING IMPORT ALIAS" region [] $
850826 Code.toSnippet source region Nothing
851827 (
852828 D.reflow $
@@ -862,7 +838,6 @@ toParseErrorReport source modul =
862838 ]
863839 , D.reflow $
864840 "Notice that the alias always starts with a capital letter. That is required!"
865− , D.reflowLink "Read" "imports" "to learn more."
866841 ]
867842 )
868843
@@ -925,192 +900,6 @@ toParseErrorReport source modul =
925900
926901
927902
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−
1114903-- IMPORTS
1115904
1116905
@@ -1136,7 +925,6 @@ toImportReport source row col =
1136925 ]
1137926 , D.reflow $
1138927 "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."
1140928 ]
1141929 )
1142930
@@ -1443,7 +1231,106 @@ toDeclarationsReport :: Code.Source -> Decl -> Report.Report
14431231toDeclarationsReport source decl =
14441232 case decl of
14451233 DeclStart row col ->
1446− toDeclStartReport source row col
1234+ case Code.whatIsNext source row col of
1235+ Code.Close term bracket ->
1236+ let
1237+ region = toRegion row col
1238+ in
1239+ Report.Report ("STRAY " ++ map Char.toUpper term) region [] $
1240+ Code.toSnippet source region Nothing
1241+ (
1242+ D.reflow $
1243+ "I was not expecting to see a " ++ term ++ " here:"
1244+ , D.reflow $
1245+ "This " ++ bracket : " does not match up with an earlier open " ++ term ++ ". Try deleting it?"
1246+ )
1247+
1248+ Code.Keyword keyword ->
1249+ let
1250+ region = toKeywordRegion row col keyword
1251+ in
1252+ Report.Report "RESERVED WORD" region [] $
1253+ Code.toSnippet source region Nothing
1254+ (
1255+ D.reflow $
1256+ "I was not expecting to run into the `" ++ keyword ++ "` keyword here:"
1257+ ,
1258+ case keyword of
1259+ "import" ->
1260+ D.reflow $
1261+ "It is reserved for declaring imports at the top of your module. If you want\
1262+ \ another import, try moving it up top with the other imports. If you want to\
1263+ \ define a value or function, try changing the name to something else!"
1264+
1265+ "case" ->
1266+ D.stack
1267+ [ D.reflow $
1268+ "It is reserved for writing `case` expressions. Try using a different name?"
1269+ , D.toSimpleNote $
1270+ "If you are trying to write a `case` expression, it needs to be part of a\
1271+ \ definition. So you could write something like this instead:"
1272+ , D.vcat $
1273+ [ D.indent 0 $ D.fillSep [D.green "getWidth","maybeWidth","="]
1274+ , D.indent 2 $ D.fillSep [D.cyan "case","maybeWidth",D.cyan "of"]
1275+ , D.indent 4 $ D.fillSep [D.blue "Just","width","->"]
1276+ , D.indent 6 $ D.fillSep ["width","+",D.dullyellow "200"]
1277+ , ""
1278+ , D.indent 4 $ D.fillSep [D.blue "Nothing","->"]
1279+ , D.indent 6 $ D.fillSep [D.dullyellow "400"]
1280+ ]
1281+ , D.reflow $
1282+ "This defines a `getWidth` function that we can use elsewhere in our program."
1283+ ]
1284+
1285+ "if" ->
1286+ D.stack
1287+ [ D.reflow $
1288+ "It is reserved for writing `if` expressions. Try using a different name?"
1289+ , D.toSimpleNote $
1290+ "If you are trying to write an `if` expression, it needs to be part of a\
1291+ \ definition. So you could write something like this instead:"
1292+ , D.vcat $
1293+ [ D.indent 0 $ D.fillSep [D.green "reviewPowerLevel","powerLevel","="]
1294+ , D.indent 2 $ D.fillSep $
1295+ [D.cyan "if","powerLevel",">",D.dullyellow "9000"
1296+ ,D.cyan "then",D.dullyellow "\"OVER 9000!!!\""
1297+ ,D.cyan "else",D.dullyellow "\"not bad\""
1298+ ]
1299+ ]
1300+ , D.reflow $
1301+ "This defines a `reviewPowerLevel` function that we can use elsewhere in our program."
1302+ ]
1303+
1304+ _ ->
1305+ D.reflow $
1306+ "It is a reserved word. Try changing the name to something else?"
1307+ )
1308+
1309+ _ ->
1310+ let
1311+ region = toRegion row col
1312+ in
1313+ Report.Report "SYNTAX PROBLEM" region [] $
1314+ Code.toSnippet source region Nothing
1315+ (
1316+ D.reflow $
1317+ "I was expecting to see a new declaration here:"
1318+ ,
1319+ D.stack
1320+ [ D.reflow $
1321+ "I am not sure what is going wrong exactly, but here are a couple valid\
1322+ \ declarations for reference:"
1323+ , D.vcat
1324+ [ D.fillSep [D.green "add",":","Int","->","Int","->","Int"]
1325+ , D.fillSep [D.green "add","x","y","="]
1326+ , D.fillSep [" ","x","+","y"]
1327+ ]
1328+ , D.fillSep [D.cyan "type",D.green "User","=","Anonymous","|","LoggedIn String"]
1329+ , D.reflow $
1330+ "Note that all declarations start with lower-case letters in Elm. Capitalization\
1331+ \ makes a difference, so be consious of that if you are working from examples!"
1332+ ]
1333+ )
14471334
14481335 DeclSpace space row col ->
14491336 toSpaceReport source space row col
@@ -1473,165 +1360,6 @@ toDeclarationsReport source decl =
14731360 )
14741361
14751362
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−
16351363
16361364-- PORT
16371365
@@ -1758,7 +1486,7 @@ toPortReport source port_ startRow startCol =
17581486 [ D.reflow $
17591487 "I was expecting to see a type next. Here are examples of outgoing and\
17601488 \ incoming ports for reference:"
1761− , D.indent 4 $ D.vcat $
1489+ , D.vcat
17621490 [ D.fillSep [D.cyan "port","send",":","String -> Cmd msg"]
17631491 , D.fillSep [D.cyan "port","receive",":","(String -> msg) -> Sub msg"]
17641492 ]
@@ -1777,7 +1505,7 @@ portNote =
17771505 D.stack
17781506 [ D.toSimpleNote $
17791507 "Here are some example `port` declarations for reference:"
1780− , D.indent 4 $ D.vcat $
1508+ , D.vcat
17811509 [ D.fillSep [D.cyan "port","send",":","String -> Cmd msg"]
17821510 , D.fillSep [D.cyan "port","receive",":","(String -> msg) -> Sub msg"]
17831511 ]
@@ -1907,7 +1635,7 @@ toTypeAliasReport source typeAlias startRow startCol =
19071635 ,
19081636 D.stack
19091637 [ D.reflow $
1910− "I was expecting to see a type variable or an equals sign next."
1638+ "I was expecting to see a type variable or an an equals sign next."
19111639 , typeAliasNote
19121640 ]
19131641 )
@@ -1928,7 +1656,7 @@ toTypeAliasReport source typeAlias startRow startCol =
19281656 ,
19291657 D.stack
19301658 [ D.reflow $
1931− "I was expecting to see a type variable or an equals sign next."
1659+ "I was expecting to see a type variable or an an equals sign next."
19321660 , typeAliasNote
19331661 ]
19341662 )
@@ -1960,8 +1688,8 @@ typeAliasNote =
19601688 [ D.toSimpleNote $
19611689 "Here is an example of a valid `type alias` for reference:"
19621690 , D.vcat $
1963− [ D.indent 4 $ D.fillSep [D.cyan "type",D.cyan "alias","Person","="]
1964− , D.indent 6 $ D.vcat $
1691+ [ D.indent 0 $ D.fillSep [D.cyan "type",D.cyan "alias",D.green "Person","="]
1692+ , D.indent 2 $ D.vcat $
19651693 ["{ name : String"
19661694 ,", age : Int"
19671695 ,", height : Float"
@@ -2035,7 +1763,7 @@ toCustomTypeReport source customType startRow startCol =
20351763 ,
20361764 D.stack
20371765 [ D.reflow $
2038− "I was expecting to see a type variable or an equals sign next."
1766+ "I was expecting to see a type variable or an an equals sign next."
20391767 , customTypeNote
20401768 ]
20411769 )
@@ -2095,7 +1823,7 @@ toCustomTypeReport source customType startRow startCol =
20951823 ,
20961824 D.stack
20971825 [ D.reflow $
2098− "I was expecting to see a type variable or an equals sign next."
1826+ "I was expecting to see a type variable or an an equals sign next."
20991827 , customTypeNote
21001828 ]
21011829 )
@@ -2161,10 +1889,10 @@ customTypeNote =
21611889 [ D.toSimpleNote $
21621890 "Here is an example of a valid `type` declaration for reference:"
21631891 , D.vcat $
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"]
1892+ [ D.indent 0 $ D.fillSep [D.cyan "type",D.green "Status"]
1893+ , D.indent 2 $ D.fillSep ["=","Failure"]
1894+ , D.indent 2 $ D.fillSep ["|","Waiting"]
1895+ , D.indent 2 $ D.fillSep ["|","Success","String"]
21681896 ]
21691897 , D.reflow $
21701898 "This defines a new `Status` type with three variants. This could be useful if\
@@ -2193,57 +1921,13 @@ toDeclDefReport source name declDef startRow startCol =
21931921 region = toKeywordRegion row col keyword
21941922 in
21951923 Report.Report "RESERVED WORD" region [] $
2196− Code.toSnippet source surroundings (Just region)
2197− (
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− ]
2204− ,
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 [] $
22281924 Code.toSnippet source surroundings (Just region)
22291925 (
22301926 D.reflow $
2231− "I was not expecting to see an arrow here:"
1927+ "It looks like you are trying to use `" ++ keyword ++ "` as an argument:"
22321928 ,
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− ]
1929+ D.reflow $
1930+ "This is a reserved word! Try using some other name?"
22471931 )
22481932
22491933 Code.Operator op ->
@@ -2261,10 +1945,10 @@ toDeclDefReport source name declDef startRow startCol =
22611945 [ D.reflow $
22621946 "I am not sure what is going wrong exactly, so here is a valid\
22631947 \ definition (with an optional type annotation) for reference:"
2264− , D.indent 4 $ D.vcat $
2265− [ "greet : String -> String"
2266− , "greet name ="
2267− , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
1948+ , D.vcat
1949+ [ D.fillSep [D.green "add",":","Int","->","Int","->","Int"]
1950+ , D.fillSep [D.green "add","x","y","="]
1951+ , D.fillSep [" ","x","+","y"]
22681952 ]
22691953 , D.reflow $
22701954 "Try to use that format with your `" ++ Name.toChars name ++ "` definition!"
@@ -2286,10 +1970,10 @@ toDeclDefReport source name declDef startRow startCol =
22861970 [ D.reflow $
22871971 "I am not sure what is going wrong exactly, so here is a valid\
22881972 \ definition (with an optional type annotation) for reference:"
2289− , D.indent 4 $ D.vcat $
2290− [ "greet : String -> String"
2291− , "greet name ="
2292− , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
1973+ , D.vcat
1974+ [ D.fillSep [D.green "add",":","Int","->","Int","->","Int"]
1975+ , D.fillSep [D.green "add","x","y","="]
1976+ , D.fillSep [" ","x","+","y"]
22931977 ]
22941978 , D.reflow $
22951979 "Try to use that format!"
@@ -2404,10 +2088,10 @@ declDefNote =
24042088 D.stack
24052089 [ D.reflow $
24062090 "Here is a valid definition (with a type annotation) for reference:"
2407− , D.indent 4 $ D.vcat $
2408− [ "greet : String -> String"
2409− , "greet name ="
2410− , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
2091+ , D.vcat
2092+ [ D.fillSep [D.green "add",":","Int","->","Int","->","Int"]
2093+ , D.fillSep [D.green "add","x","y","="]
2094+ , D.fillSep [" ","x","+","y"]
24112095 ]
24122096 , D.reflow $
24132097 "The top line (called a \"type annotation\") is optional. You can leave it off\
@@ -2519,40 +2203,25 @@ toExprReport source context expr startRow startCol =
25192203 )
25202204
25212205 OperatorRight op row col ->
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
2206+ let region = toRegion row col in
25272207 Report.Report "MISSING EXPRESSION" region [] $
2528− Code.toSnippet source surroundings (Just region)
2208+ Code.toSnippet source region Nothing
25292209 (
25302210 D.reflow $
2531− "I just saw a " ++ Name.toChars op ++ " "
2532− ++ (if isMath then "sign" else "operator")
2533− ++ ", so I am getting stuck here:"
2211+ "I was expecting to see an expression after this " ++ Name.toChars op ++ " operator:"
25342212 ,
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."
2213+ D.stack
2214+ [ D.fillSep $
2215+ ["You","can","just","put","anything","for","now,","like"
2216+ ,D.dullyellow "42","or",D.dullyellow"\"hello\"" <> "."
2217+ ,"Once","there","is","something","there,","I","can","probably"
2218+ ,"give","a","more","specific","hint!"
2219+ ]
2220+ , D.toSimpleNote $
2221+ "This can also happen if run into reserved words like `let` or `as` unexpectedly.\
2222+ \ Or if I run into operators in unexpected spots. Point is, there are a\
2223+ \ couple ways I can get confused and give sort of weird advice!"
2224+ ]
25562225 )
25572226
25582227 OperatorReserved operator row col ->
@@ -2573,6 +2242,7 @@ toExprReport source context expr startRow startCol =
25732242 InNode NElse r c _ -> (r, c, "an `if` expression")
25742243 InNode NCase r c _ -> (r, c, "a `case` expression")
25752244 InNode NBranch r c _ -> (r, c, "a `case` expression")
2245+ -- TODO check if this is actually the best way to get error messages here
25762246
25772247 surroundings = A.Region (A.Position contextRow contextCol) (A.Position row col)
25782248 region = toRegion row col
@@ -2591,7 +2261,7 @@ toExprReport source context expr startRow startCol =
25912261 ,"give","a","more","specific","hint!"
25922262 ]
25932263 , D.toSimpleNote $
2594− "This can also happen if I run into reserved words like `let` or `as` unexpectedly.\
2264+ "This can also happen if run into reserved words like `let` or `as` unexpectedly.\
25952265 \ Or if I run into operators in unexpected spots. Point is, there are a\
25962266 \ couple ways I can get confused and give sort of weird advice!"
25972267 ]
@@ -2737,19 +2407,7 @@ toStringReport source string row col =
27372407 ,"quotes","on","each","end.","Is","the","closing","double"
27382408 ,"quote","missing","in","your","code?"
27392409 ]
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− ]
2410+ , D.link "Note" "Read" "TODO" "if you want a string that spans multiple lines."
27532411 ]
27542412 )
27552413
@@ -2765,18 +2423,7 @@ toStringReport source string row col =
27652423 ,
27662424 D.stack
27672425 [ D.reflow "Add a \"\"\" somewhere after this to end the string."
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− ]
2426+ , D.link "Hint" "Read" "TODO" "for more information on strings and multi-line strings."
27802427 ]
27812428 )
27822429
@@ -3009,41 +2656,33 @@ toOperatorReport source context operator row col =
30092656 in
30102657 Report.Report "UNEXPECTED ARROW" region [] $
30112658 Code.toSnippet source region Nothing $
3012− if isWithin NCase context then
3013− (
3014− D.reflow $
3015− "I am parsing a `case` expression right now, but this arrow is confusing me:"
3016− ,
3017− D.stack
3018− [ D.reflow "Maybe the `of` keyword is missing on a previous line?"
3019− , noteForCaseError
3020− ]
3021− )
3022−
3023− else if isWithin NBranch context then
2659+ if isWithin NBranch context then
30242660 (
30252661 D.reflow $
3026− "I am parsing a `case` expression right now, but this arrow is confusing me:"
2662+ "I was not expecting to see an arrow here:"
30272663 ,
30282664 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
2665+ [
2666+ D.reflow $
2667+ "I think I am parsing a `case` expression right now, so it makes sense to\
2668+ \ see arrows around here. This one is confusing me though!"
2669+ ,
2670+ D.toSimpleHint $
2671+ "I may be getting confused by the indentation. Every pattern in a `case` must be\
2672+ \ exactly aligned (with exactly the same amount of indentation) so maybe this arrow\
2673+ \ appears after the next `case` pattern (correctly!) but the pattern itself is\
2674+ \ indented too far?"
30322675 ]
30332676 )
30342677
30352678 else
30362679 (
30372680 D.reflow $
3038− "I was partway through parsing an expression when I got stuck on this arrow:"
2681+ "I was not expecting an arrow here:"
30392682 ,
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− ]
2683+ D.reflow $
2684+ "Arrows should only appear in `case` expressions and anonymous functions. Maybe\
2685+ \ you want > or >= instead?"
30472686 )
30482687
30492688 BadEquals ->
@@ -3170,7 +2809,7 @@ toLetReport source context let_ startRow startCol =
31702809 , D.toSimpleNote $
31712810 "This can also happen if you are trying to define another value within the `let` but\
31722811 \ it is not indented enough. Make sure each definition has exactly the same amount of\
3173− \ spaces before it. They should line up exactly!"
2812+ \ spaces before it. The should line up exactly!"
31742813 ]
31752814 )
31762815
@@ -3240,8 +2879,8 @@ toUnfinishLetReport source row col startRow startCol message =
32402879 [ message
32412880 , D.toSimpleNote $
32422881 "Here is an example with a valid `let` expression for reference:"
3243− , D.indent 4 $ D.vcat $
3244− [ D.indent 0 $ D.fillSep ["viewPerson","person","="]
2882+ , D.vcat $
2883+ [ D.indent 0 $ D.fillSep [D.green "viewPerson","person","="]
32452884 , D.indent 2 $ D.fillSep [D.cyan "let"]
32462885 , D.indent 4 $ D.fillSep ["fullName","="]
32472886 , D.indent 6 $ D.fillSep ["person.firstName","++",D.dullyellow "\" \"","++","person.lastName"]
@@ -3316,57 +2955,13 @@ toLetDefReport source name def startRow startCol =
33162955 region = toKeywordRegion row col keyword
33172956 in
33182957 Report.Report "RESERVED WORD" region [] $
3319− Code.toSnippet source surroundings (Just region)
3320− (
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− ]
3327− ,
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 [] $
33512958 Code.toSnippet source surroundings (Just region)
33522959 (
33532960 D.reflow $
3354− "I was not expecting to see an arrow here:"
2961+ "It looks like you are trying to use `" ++ keyword ++ "` as an argument:"
33552962 ,
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− ]
2963+ D.reflow $
2964+ "This is a reserved word! Try using some other name?"
33702965 )
33712966
33722967 Code.Operator op ->
@@ -3384,10 +2979,10 @@ toLetDefReport source name def startRow startCol =
33842979 [ D.reflow $
33852980 "I am not sure what is going wrong exactly, so here is a valid\
33862981 \ definition (with an optional type annotation) for reference:"
3387− , D.indent 4 $ D.vcat $
3388− [ "greet : String -> String"
3389− , "greet name ="
3390− , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
2982+ , D.vcat
2983+ [ D.indent 4 $ D.fillSep [D.green "add",":","Int","->","Int","->","Int"]
2984+ , D.indent 4 $ D.fillSep [D.green "add","x","y","="]
2985+ , D.indent 6 $ D.fillSep ["x","+","y"]
33912986 ]
33922987 , D.reflow $
33932988 "Try to use that format with your `" ++ Name.toChars name ++ "` definition!"
@@ -3409,10 +3004,10 @@ toLetDefReport source name def startRow startCol =
34093004 [ D.reflow $
34103005 "I am not sure what is going wrong exactly, so here is a valid\
34113006 \ definition (with an optional type annotation) for reference:"
3412− , D.indent 4 $ D.vcat $
3413− [ "greet : String -> String"
3414− , "greet name ="
3415− , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
3007+ , D.vcat
3008+ [ D.indent 4 $ D.fillSep [D.green "add",":","Int","->","Int","->","Int"]
3009+ , D.indent 4 $ D.fillSep [D.green "add","x","y","="]
3010+ , D.indent 4 $ D.fillSep ["x","+","y"]
34163011 ]
34173012 , D.reflow $
34183013 "Try to use that format!"
@@ -3502,10 +3097,10 @@ defNote =
35023097 D.stack
35033098 [ D.reflow $
35043099 "Here is a valid definition (with a type annotation) for reference:"
3505− , D.indent 4 $ D.vcat $
3506− [ "greet : String -> String"
3507− , "greet name ="
3508− , " " <> D.dullyellow "\"Hello \"" <> " ++ name ++ " <> D.dullyellow "\"!\""
3100+ , D.vcat
3101+ [ D.indent 4 $ D.fillSep [D.green "add",":","Int","->","Int","->","Int"]
3102+ , D.indent 4 $ D.fillSep [D.green "add","x","y","="]
3103+ , D.indent 6 $ D.fillSep ["x","+","y"]
35093104 ]
35103105 , D.reflow $
35113106 "The top line (called a \"type annotation\") is optional. You can leave it off\
@@ -3668,10 +3263,9 @@ toCaseReport source context case_ startRow startCol =
36683263 D.reflow $
36693264 "I am partway through parsing a `case` expression, but I got stuck here:"
36703265 ,
3671− D.stack
3672− [ D.reflow "I was expecting to see an arrow next."
3673− , noteForCaseIndentError
3674− ]
3266+ addNoteForCaseIndentError $
3267+ D.reflow $
3268+ "I was expecting to see an arrow next."
36753269 )
36763270
36773271 CaseExpr expr row col ->
@@ -3719,39 +3313,34 @@ toUnfinishCaseReport source row col startRow startCol message =
37193313 in
37203314 Report.Report "UNFINISHED CASE" region [] $
37213315 Code.toSnippet source surroundings (Just region)
3722− (
3723− D.reflow $
3724− "I was partway through parsing a `case` expression, but I got stuck here:"
3725− ,
3726− D.stack
3727− [ message
3728− , noteForCaseError
3729− ]
3730− )
3731−
3732−
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− ]
3316+ (
3317+ D.reflow $
3318+ "I was partway through parsing a `case` expression, but I got stuck here:"
3319+ ,
3320+ D.stack
3321+ [ message
3322+ , D.toSimpleNote $
3323+ "Here is an example of a valid `case` expression for reference."
3324+ , D.vcat $
3325+ [ D.indent 4 $ D.fillSep [D.cyan "case","maybeWidth",D.cyan "of"]
3326+ , D.indent 6 $ D.fillSep [D.blue "Just","width","->"]
3327+ , D.indent 8 $ D.fillSep ["width","+",D.dullyellow "200"]
3328+ , ""
3329+ , D.indent 6 $ D.fillSep [D.blue "Nothing","->"]
3330+ , D.indent 8 $ D.fillSep [D.dullyellow "400"]
3331+ ]
3332+ , D.reflow $
3333+ "Notice the indentation. Each pattern is aligned, and each branch is indented\
3334+ \ a bit more than the corresponding pattern. That is important!"
3335+ ]
3336+ )
37503337
37513338
3752−noteForCaseIndentError :: D.Doc
3753−noteForCaseIndentError =
3754− D.stack
3339+addNoteForCaseIndentError :: D.Doc -> D.Doc
3340+addNoteForCaseIndentError message =
3341+ D.stack $
3342+ message
3343+ :
37553344 [ D.toSimpleNote $
37563345 "Sometimes I get confused by indentation, so try to make your `case` look\
37573346 \ something like this:"
@@ -3764,9 +3353,8 @@ noteForCaseIndentError =
37643353 , D.indent 8 $ D.fillSep [D.dullyellow "400"]
37653354 ]
37663355 , D.reflow $
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!"
3356+ "Notice the indentation! Each pattern is aligned, and each branch is indented\
3357+ \ a bit more than the corresponding pattern. That is important!"
37703358 ]
37713359
37723360
@@ -3918,43 +3506,23 @@ toIfReport source context if_ startRow startCol =
39183506 )
39193507
39203508 IfIndentElse row col ->
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− )
3509+ let
3510+ surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
3511+ region = toRegion row col
3512+ in
3513+ Report.Report "UNFINISHED IF" region [] $
3514+ Code.toSnippet source surroundings (Just region)
3515+ (
3516+ D.reflow $
3517+ "I was expecting to see an `else` branch after this:"
3518+ ,
3519+ D.stack
3520+ [ D.reflow $
3521+ "I know what to do when the condition is `True`, but not when it is `False`."
3522+ , D.fillSep
3523+ ["Add","an",D.cyan "else","branch","to","handle","that","scenario!"]
3524+ ]
3525+ )
39583526
39593527
39603528
@@ -3987,22 +3555,15 @@ toRecordReport source context record startRow startCol =
39873555 surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
39883556 region = toRegion row col
39893557 in
3990− Report.Report "PROBLEM IN RECORD" region [] $
3558+ Report.Report "UNFINISHED RECORD" region [] $
39913559 Code.toSnippet source surroundings (Just region)
39923560 (
39933561 D.reflow $
39943562 "I just started parsing a record, but I got stuck here:"
39953563 ,
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
3564+ D.fillSep
3565+ ["Records","look","like",D.dullyellow "{ x = 3, y = 4 },"
3566+ ,"so","I","was","expecting","to","see","a","field","name","next."
40063567 ]
40073568 )
40083569
@@ -4011,7 +3572,7 @@ toRecordReport source context record startRow startCol =
40113572 surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
40123573 region = toRegion row col
40133574 in
4014− Report.Report "PROBLEM IN RECORD" region [] $
3575+ Report.Report "UNFINISHED RECORD" region [] $
40153576 Code.toSnippet source surroundings (Just region)
40163577 (
40173578 D.reflow $
@@ -4046,67 +3607,22 @@ toRecordReport source context record startRow startCol =
40463607 \ that is a reserved word. Try using a different name!"
40473608 )
40483609
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−
40883610 _ ->
40893611 let
40903612 surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
40913613 region = toRegion row col
40923614 in
4093− Report.Report "PROBLEM IN RECORD" region [] $
3615+ Report.Report "UNFINISHED RECORD" region [] $
40943616 Code.toSnippet source surroundings (Just region)
40953617 (
40963618 D.reflow $
4097− "I am partway through parsing a record, but I got stuck here:"
3619+ "I am partway through parsing a record, but I got stuck after that last comma:"
40983620 ,
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− ]
3621+ addNoteForRecordError $
3622+ D.reflow $
3623+ "Trailing commas are not allowed in records, so I was expecting to see another\
3624+ \ record field defined next. If you are done defining the record, the fix may\
3625+ \ be to delete that last comma?"
41103626 )
41113627
41123628 RecordEquals row col ->
@@ -4114,19 +3630,17 @@ toRecordReport source context record startRow startCol =
41143630 surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
41153631 region = toRegion row col
41163632 in
4117− Report.Report "PROBLEM IN RECORD" region [] $
3633+ Report.Report "UNFINISHED RECORD" region [] $
41183634 Code.toSnippet source surroundings (Just region)
41193635 (
41203636 D.reflow $
41213637 "I am partway through parsing a record, but I got stuck here:"
41223638 ,
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− ]
3639+ addNoteForRecordError $
3640+ D.fillSep $
3641+ ["I","just","saw","a","field","name,","so","I","was","expecting","to","see"
3642+ ,"an","equals","sign","next.","So","try","putting","an",D.green "=","sign","here?"
3643+ ]
41303644 )
41313645
41323646 RecordExpr expr row col ->
@@ -4146,54 +3660,29 @@ toRecordReport source context record startRow startCol =
41463660 D.reflow $
41473661 "I just saw the opening curly brace of a record, but then I got stuck here:"
41483662 ,
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− ]
3663+ addNoteForRecordIndentError $
3664+ D.fillSep $
3665+ ["I","am","expecting","a","record","like",D.dullyellow "{ x = 3, y = 4 }","here."
3666+ ,"Try","defining","some","fields","of","your","own?"
3667+ ]
41563668 )
41573669
41583670 RecordIndentEnd row col ->
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− )
3671+ let
3672+ surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
3673+ region = toRegion row col
3674+ in
3675+ Report.Report "UNFINISHED RECORD" region [] $
3676+ Code.toSnippet source surroundings (Just region)
3677+ (
3678+ D.reflow $
3679+ "I was expecting to see a closing curly brace next:"
3680+ ,
3681+ addNoteForRecordIndentError $
3682+ D.fillSep $
3683+ ["Try","putting","an",D.green "}","and","see","if","that","helps?"
3684+ ]
3685+ )
41973686
41983687 RecordIndentField row col ->
41993688 let
@@ -4206,13 +3695,11 @@ toRecordReport source context record startRow startCol =
42063695 D.reflow $
42073696 "I am partway through parsing a record, but I got stuck after that last comma:"
42083697 ,
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− ]
3698+ addNoteForRecordError $
3699+ D.reflow $
3700+ "Trailing commas are not allowed in records, so the fix may be to\
3701+ \ delete that last comma? Or maybe you were in the middle of defining\
3702+ \ an additional field?"
42163703 )
42173704
42183705 RecordIndentEquals row col ->
@@ -4227,12 +3714,10 @@ toRecordReport source context record startRow startCol =
42273714 "I am partway through parsing a record. I just saw a record\
42283715 \ field, so I was expecting to see an equals sign next:"
42293716 ,
4230− D.stack
4231− [ D.fillSep $
4232− ["Try","putting","an",D.green "=","followed","by","an","expression?"
4233− ]
4234− , noteForRecordIndentError
4235− ]
3717+ addNoteForRecordIndentError $
3718+ D.fillSep $
3719+ ["Try","putting","an",D.green "=","followed","by","an","expression?"
3720+ ]
42363721 )
42373722
42383723 RecordIndentExpr row col ->
@@ -4246,48 +3731,52 @@ toRecordReport source context record startRow startCol =
42463731 D.reflow $
42473732 "I am partway through parsing a record, and I was expecting to run into an expression next:"
42483733 ,
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− ]
3734+ addNoteForRecordIndentError $
3735+ D.fillSep $
3736+ ["Try","putting","something","like"
3737+ ,D.dullyellow "42","or",D.dullyellow"\"hello\"","for","now?"
3738+ ]
42563739 )
42573740
42583741
4259−noteForRecordError :: D.Doc
4260−noteForRecordError =
3742+addNoteForRecordError :: D.Doc -> D.Doc
3743+addNoteForRecordError normalRecommendation =
42613744 D.stack $
3745+ normalRecommendation
3746+ :
42623747 [ D.toSimpleNote
42633748 "If you are trying to define a record across multiple lines, I recommend using this format:"
42643749 , D.indent 4 $ D.vcat $
4265− [ "{ name = " <> D.dullyellow "\"Alice\""
4266− , ", age = " <> D.dullyellow "42"
4267− , ", height = " <> D.dullyellow "1.75"
3750+ [ "{ name = \"Alice\""
3751+ , ", age = 42"
3752+ , ", height = 1.75"
42683753 , "}"
42693754 ]
42703755 , D.reflow $
4271− "Notice that each line starts with some indentation. Usually two or four spaces.\
4272− \ This is the stylistic convention in the Elm ecosystem."
3756+ "Notice that each line starts with some indentation. Usually two or four spaces. I\
3757+ \ know this style can be jarring for people coming from C-like syntax, but folks generally\
3758+ \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
42733759 ]
42743760
42753761
4276−noteForRecordIndentError :: D.Doc
4277−noteForRecordIndentError =
4278− D.stack
3762+addNoteForRecordIndentError :: D.Doc -> D.Doc
3763+addNoteForRecordIndentError normalRecommendation =
3764+ D.stack $
3765+ normalRecommendation
3766+ :
42793767 [ D.toSimpleNote
42803768 "I may be confused by indentation. For example, if you are trying to define\
42813769 \ a record across multiple lines, I recommend using this format:"
42823770 , D.indent 4 $ D.vcat $
4283− [ "{ name = " <> D.dullyellow "\"Alice\""
4284− , ", age = " <> D.dullyellow "42"
4285− , ", height = " <> D.dullyellow "1.75"
3771+ [ "{ name = \"Alice\""
3772+ , ", age = 42"
3773+ , ", height = 1.75"
42863774 , "}"
42873775 ]
42883776 , D.reflow $
4289− "Notice that each line starts with some indentation. Usually two or four spaces.\
4290− \ This is the stylistic convention in the Elm ecosystem!"
3777+ "Notice that each line starts with some indentation. Usually two or four spaces. I\
3778+ \ know this style can be jarring for people coming from C-like syntax, but folks generally\
3779+ \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
42913780 ]
42923781
42933782
@@ -4476,14 +3965,15 @@ toListReport source context list startRow startCol =
44763965 , D.toSimpleNote
44773966 "I recommend using the following format for lists that span multiple lines:"
44783967 , D.indent 4 $ D.vcat $
4479− [ "[ " <> D.dullyellow "\"Alice\""
4480− , ", " <> D.dullyellow "\"Bob\""
4481− , ", " <> D.dullyellow "\"Chuck\""
3968+ [ "[ \"Alice\""
3969+ , ", \"Bob\""
3970+ , ", \"Chuck\""
44823971 , "]"
44833972 ]
44843973 , D.reflow $
4485− "Notice that each line starts with some indentation. Usually two or four spaces.\
4486− \ This is the stylistic convention in the Elm ecosystem."
3974+ "Notice that nothing comes directly after a newline. Each line starts with some spaces.\
3975+ \ This style can be jarring for people coming from C-like syntax, but folks generally\
3976+ \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
44873977 ]
44883978 )
44893979
@@ -4536,14 +4026,15 @@ toListReport source context list startRow startCol =
45364026 "I may be confused by indentation. For example, if you are trying to define\
45374027 \ a list across multiple lines, I recommend using this format:"
45384028 , D.indent 4 $ D.vcat $
4539− [ "[ " <> D.dullyellow "\"Alice\""
4540− , ", " <> D.dullyellow "\"Bob\""
4541− , ", " <> D.dullyellow "\"Chuck\""
4029+ [ "[ \"Alice\""
4030+ , ", \"Bob\""
4031+ , ", \"Chuck\""
45424032 , "]"
45434033 ]
45444034 , D.reflow $
4545− "Notice that each line starts with some indentation. Usually two or four spaces.\
4546− \ This is the stylistic convention in the Elm ecosystem."
4035+ "Notice that nothing comes directly after a newline. Each line starts with some spaces.\
4036+ \ This style can be jarring for people coming from C-like syntax, but folks generally\
4037+ \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
45474038 ]
45484039 )
45494040
@@ -4567,14 +4058,15 @@ toListReport source context list startRow startCol =
45674058 "I may be confused by indentation. For example, if you are trying to define\
45684059 \ a list across multiple lines, I recommend using this format:"
45694060 , D.indent 4 $ D.vcat $
4570− [ "[ " <> D.dullyellow "\"Alice\""
4571− , ", " <> D.dullyellow "\"Bob\""
4572− , ", " <> D.dullyellow "\"Chuck\""
4061+ [ "[ \"Alice\""
4062+ , ", \"Bob\""
4063+ , ", \"Chuck\""
45734064 , "]"
45744065 ]
45754066 , D.reflow $
4576− "Notice that each line starts with some indentation. Usually two or four spaces.\
4577− \ This is the stylistic convention in the Elm ecosystem."
4067+ "Notice that nothing comes directly after a newline. Each line starts with some spaces.\
4068+ \ This style can be jarring for people coming from C-like syntax, but folks generally\
4069+ \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
45784070 ]
45794071 )
45804072
@@ -4595,14 +4087,15 @@ toListReport source context list startRow startCol =
45954087 , D.toSimpleNote
45964088 "I recommend using the following format for lists that span multiple lines:"
45974089 , D.indent 4 $ D.vcat $
4598− [ "[ " <> D.dullyellow "\"Alice\""
4599− , ", " <> D.dullyellow "\"Bob\""
4600− , ", " <> D.dullyellow "\"Chuck\""
4090+ [ "[ \"Alice\""
4091+ , ", \"Bob\""
4092+ , ", \"Chuck\""
46014093 , "]"
46024094 ]
46034095 , D.reflow $
4604− "Notice that each line starts with some indentation. Usually two or four spaces.\
4605− \ This is the stylistic convention in the Elm ecosystem."
4096+ "Notice that nothing comes directly after a newline. Each line starts with some spaces.\
4097+ \ This style can be jarring for people coming from C-like syntax, but folks generally\
4098+ \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
46064099 ]
46074100 )
46084101
@@ -4851,7 +4344,7 @@ toPatternReport source context pattern startRow startCol =
48514344 ,"((" <> D.dullyellow "x" <> "," <> D.dullyellow "y" <> ") " <> D.cyan "as" <> D.dullyellow " point" <> ")"
48524345 ,"so","you","can","refer","to","individual","parts","of","the","tuple","with"
48534346 ,D.dullyellow "x","and",D.dullyellow "y","or","you","refer","to","the","whole"
4854− ,"thing","with",D.dullyellow "point" <> "."
4347+ ,"thing","with",D.dullyellow "point."
48554348 ]
48564349 , D.reflow $
48574350 "So I was expecting to see a variable name after the `as` keyword here. Sometimes\
@@ -5043,7 +4536,7 @@ toPTupleReport source context tuple startRow startCol =
50434536 "I just saw an open parenthesis, but I got stuck here:"
50444537 ,
50454538 D.fillSep
5046− ["I","was","expecting","to","see","a","pattern","next."
4539+ ["I","was","expecting","so","see","a","pattern","next."
50474540 ,"Maybe","it","will","end","up","being","something"
50484541 ,"like",D.dullyellow "(x,y)","or",D.dullyellow "(name, _)" <> "?"
50494542 ]
@@ -5152,7 +4645,7 @@ toPTupleReport source context tuple startRow startCol =
51524645 "I just saw an open parenthesis, but then I got stuck here:"
51534646 ,
51544647 D.fillSep
5155− ["I","was","expecting","to","see","a","pattern","next."
4648+ ["I","was","expecting","so","see","a","pattern","next."
51564649 ,"Maybe","it","will","end","up","being","something"
51574650 ,"like",D.dullyellow "(x,y)","or",D.dullyellow "(name, _)" <> "?"
51584651 ]
@@ -5171,7 +4664,7 @@ toPTupleReport source context tuple startRow startCol =
51714664 ,
51724665 D.stack
51734666 [ D.fillSep
5174− ["I","was","expecting","to","see","a","pattern","next."
4667+ ["I","was","expecting","so","see","a","pattern","next."
51754668 ,"I","am","expecting","the","final","result","to","be","something"
51764669 ,"like",D.dullyellow "(x,y)","or",D.dullyellow "(name, _)" <> "."
51774670 ]
@@ -5475,64 +4968,22 @@ toTRecordReport source context record startRow startCol =
54754968 \ that is a reserved word. Try using a different name!"
54764969 )
54774970
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−
55174971 _ ->
55184972 let
55194973 surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
55204974 region = toRegion row col
55214975 in
5522− Report.Report "PROBLEM IN RECORD TYPE" region [] $
4976+ Report.Report "UNFINISHED RECORD TYPE" region [] $
55234977 Code.toSnippet source surroundings (Just region)
55244978 (
55254979 D.reflow $
5526− "I am partway through parsing a record type, but I got stuck here:"
4980+ "I am partway through parsing a record type, but I got stuck after that last comma:"
55274981 ,
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− ]
4982+ addNoteForRecordTypeError $
4983+ D.reflow $
4984+ "Trailing commas are not allowed in records, so I was expecting to see another\
4985+ \ record field defined next. If you are done defining the record, the fix may\
4986+ \ be to delete that last comma?"
55364987 )
55374988
55384989 TRecordColon row col ->
@@ -5546,13 +4997,11 @@ toTRecordReport source context record startRow startCol =
55464997 D.reflow $
55474998 "I am partway through parsing a record type, but I got stuck here:"
55484999 ,
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− ]
5000+ addNoteForRecordTypeError $
5001+ D.fillSep $
5002+ ["I","just","saw","a","field","name,","so","I","was","expecting","to","see"
5003+ ,"a","colon","next.","So","try","putting","an",D.green ":","sign","here?"
5004+ ]
55565005 )
55575006
55585007 TRecordType tipe row col ->
@@ -5572,54 +5021,29 @@ toTRecordReport source context record startRow startCol =
55725021 D.reflow $
55735022 "I just saw the opening curly brace of a record type, but then I got stuck here:"
55745023 ,
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− ]
5024+ addNoteForRecordTypeIndentError $
5025+ D.fillSep $
5026+ ["I","am","expecting","a","record","like",D.dullyellow "{ name : String, age : Int }","here."
5027+ ,"Try","defining","some","fields","of","your","own?"
5028+ ]
55825029 )
55835030
55845031 TRecordIndentEnd row col ->
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− )
5032+ let
5033+ surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
5034+ region = toRegion row col
5035+ in
5036+ Report.Report "UNFINISHED RECORD TYPE" region [] $
5037+ Code.toSnippet source surroundings (Just region)
5038+ (
5039+ D.reflow $
5040+ "I was expecting to see a closing curly brace next:"
5041+ ,
5042+ addNoteForRecordTypeIndentError $
5043+ D.fillSep $
5044+ ["Try","putting","an",D.green "}","and","see","if","that","helps?"
5045+ ]
5046+ )
56235047
56245048 TRecordIndentField row col ->
56255049 let
@@ -5632,13 +5056,11 @@ toTRecordReport source context record startRow startCol =
56325056 D.reflow $
56335057 "I am partway through parsing a record type, but I got stuck after that last comma:"
56345058 ,
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− ]
5059+ addNoteForRecordTypeIndentError $
5060+ D.reflow $
5061+ "Trailing commas are not allowed in record types, so the fix may be to\
5062+ \ delete that last comma? Or maybe you were in the middle of defining\
5063+ \ an additional field?"
56425064 )
56435065
56445066 TRecordIndentColon row col ->
@@ -5653,12 +5075,10 @@ toTRecordReport source context record startRow startCol =
56535075 "I am partway through parsing a record type. I just saw a record\
56545076 \ field, so I was expecting to see a colon next:"
56555077 ,
5656− D.stack
5657− [ D.fillSep $
5658− ["Try","putting","an",D.green ":","followed","by","a","type?"
5659− ]
5660− , noteForRecordTypeIndentError
5661− ]
5078+ addNoteForRecordTypeIndentError $
5079+ D.fillSep $
5080+ ["Try","putting","an",D.green ":","followed","by","a","type?"
5081+ ]
56625082 )
56635083
56645084 TRecordIndentType row col ->
@@ -5672,19 +5092,19 @@ toTRecordReport source context record startRow startCol =
56725092 D.reflow $
56735093 "I am partway through parsing a record type, and I was expecting to run into a type next:"
56745094 ,
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− ]
5095+ addNoteForRecordTypeIndentError $
5096+ D.fillSep $
5097+ ["Try","putting","something","like"
5098+ ,D.dullyellow "Int","or",D.dullyellow "String","for","now?"
5099+ ]
56825100 )
56835101
56845102
5685−noteForRecordTypeError :: D.Doc
5686−noteForRecordTypeError =
5103+addNoteForRecordTypeError :: D.Doc -> D.Doc
5104+addNoteForRecordTypeError normalRecommendation =
56875105 D.stack $
5106+ normalRecommendation
5107+ :
56885108 [ D.toSimpleNote
56895109 "If you are trying to define a record type across multiple lines, I recommend using this format:"
56905110 , D.indent 4 $ D.vcat $
@@ -5694,14 +5114,17 @@ noteForRecordTypeError =
56945114 , "}"
56955115 ]
56965116 , D.reflow $
5697− "Notice that each line starts with some indentation. Usually two or four spaces.\
5698− \ This is the stylistic convention in the Elm ecosystem."
5117+ "Notice that each line starts with some indentation. Usually two or four spaces. I\
5118+ \ know this style can be jarring for people coming from C-like syntax, but folks generally\
5119+ \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
56995120 ]
57005121
57015122
5702−noteForRecordTypeIndentError :: D.Doc
5703−noteForRecordTypeIndentError =
5123+addNoteForRecordTypeIndentError :: D.Doc -> D.Doc
5124+addNoteForRecordTypeIndentError normalRecommendation =
57045125 D.stack $
5126+ normalRecommendation
5127+ :
57055128 [ D.toSimpleNote
57065129 "I may be confused by indentation. For example, if you are trying to define\
57075130 \ a record type across multiple lines, I recommend using this format:"
@@ -5712,8 +5135,9 @@ noteForRecordTypeIndentError =
57125135 , "}"
57135136 ]
57145137 , D.reflow $
5715− "Notice that each line starts with some indentation. Usually two or four spaces.\
5716− \ This is the stylistic convention in the Elm ecosystem."
5138+ "Notice that each line starts with some indentation. Usually two or four spaces. I\
5139+ \ know this style can be jarring for people coming from C-like syntax, but folks generally\
5140+ \ report that they are used to it (and often prefer it!) after a week or two of using Elm."
57175141 ]
57185142
57195143
@@ -5765,7 +5189,7 @@ toTTupleReport source context tuple startRow startCol =
57655189 Code.toSnippet source surroundings (Just region)
57665190 (
57675191 D.reflow $
5768− "I was expecting to see a closing parenthesis next, but I got stuck here:"
5192+ "I was expecting to see a closing parentheses next, but I got stuck here:"
57695193 ,
57705194 D.stack
57715195 [ D.fillSep ["Try","adding","a",D.dullyellow ")","to","see","if","that","helps?"]
compiler/src/Reporting/Error/Type.hs+23−44
@@ -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− "custom-types"
234+ "union-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.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."
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>"
261261 ]
262262 )
263263
@@ -431,14 +431,13 @@ problemToHint problem =
431431 ]
432432 ]
433433
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."
434+ T.AnythingToList ->
435+ [ D.toSimpleHint "Did you forget to add [] around it?"
440436 ]
441437
438+ T.MissingArgs _ -> []
439+ T.ReturnMismatch -> []
440+
442441 T.BadFlexSuper direction super _ tipe ->
443442 case tipe of
444443 T.Lambda _ _ _ -> badFlexSuper direction super tipe
@@ -559,31 +558,11 @@ badFlexSuper :: T.Direction -> T.Super -> T.Type -> [D.Doc]
559558badFlexSuper direction super tipe =
560559 case super of
561560 T.Comparable ->
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− ]
561+ [ D.toSimpleHint "Only ints, floats, chars, strings, lists, and tuples are comparable."
562+ ]
584563
585564 T.Appendable ->
586− [ D.toSimpleHint "I only know how to append strings and lists."
565+ [ D.toSimpleHint "Only strings and lists are appendable."
587566 ]
588567
589568 T.CompAppend ->
@@ -710,11 +689,11 @@ toExprReport source localizer exprRegion category tipe expected =
710689 , "The " <> ith <> " element of this list does not match all the previous elements:"
711690 , "The " <> ith <> " element is"
712691 , "But all the previous elements in the list are:"
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."
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>"
718697 ]
719698 )
720699
@@ -761,7 +740,7 @@ toExprReport source localizer exprRegion category tipe expected =
761740 , [ D.link "Hint"
762741 "All branches in an `if` must produce the same type of values. This way, no\
763742 \ matter which branch we take, the result is always a consistent shape. Read"
764− "custom-types"
743+ "union-types"
765744 "to learn how to “mix” types."
766745 ]
767746 )
@@ -776,7 +755,7 @@ toExprReport source localizer exprRegion category tipe expected =
776755 , [ D.link "Hint"
777756 "All branches in a `case` must produce the same type of values. This way, no\
778757 \ matter which branch we take, the result is always a consistent shape. Read"
779− "custom-types"
758+ "union-types"
780759 "to learn how to “mix” types."
781760 ]
782761 )
@@ -1093,7 +1072,7 @@ opRightToDocs localizer category op tipe expected =
10931072 ( D.reflow $ "I cannot send this through the (<|) pipe:"
10941073 , typeComparison localizer tipe expected
10951074 "The argument is:"
1096− "But (<|) is piping it to a function that expects:"
1075+ "But (<|) is piping it a function that expects:"
10971076 []
10981077 )
10991078
@@ -1104,7 +1083,7 @@ opRightToDocs localizer category op tipe expected =
11041083 ( D.reflow $ "This function cannot handle the argument sent through the (|>) pipe:"
11051084 , typeComparison localizer argType expectedArgType
11061085 "The argument is:"
1107− "But (|>) is piping it to a function that expects:"
1086+ "But (|>) is piping it a function that expects:"
11081087 []
11091088 )
11101089
compiler/src/Reporting/Render/Code.hs+26−67
@@ -7,8 +7,6 @@ module Reporting.Render.Code
77 , toPair
88 , Next(..)
99 , whatIsNext
10− , nextLineStartsWithKeyword
11− , nextLineStartsWithCloseCurly
1210 )
1311 where
1412
@@ -122,7 +120,7 @@ makeUnderline width realEndLine (A.Region (A.Position start c1) (A.Position end
122120 spaces = replicate (fromIntegral c1 + width + 1) ' '
123121 zigzag = replicate (max 1 (fromIntegral (c2 - c1))) '^'
124122 in
125− Just (D.fromChars spaces <> D.red (D.fromChars zigzag))
123+ Just (D.fromChars spaces <> D.dullred (D.fromChars zigzag))
126124
127125
128126drawLines :: Bool -> Int -> A.Region -> [(Word16, String)] -> Doc -> Doc
@@ -148,7 +146,7 @@ addLineNumber addZigZag width start end n line =
148146
149147 spacer =
150148 if addZigZag && start <= n && n <= end then
151− D.red ">"
149+ D.dullred ">"
152150 else
153151 " "
154152 in
@@ -183,8 +181,8 @@ renderPair source@(Source sourceLines) region1 region2 =
183181 OneLine $
184182 D.vcat
185183 [ D.fromChars lineNumber <> "| " <> D.fromChars line
186− , D.fromChars spaces1 <> D.red (D.fromChars zigzag1) <>
187− D.fromChars spaces2 <> D.red (D.fromChars zigzag2)
184+ , D.fromChars spaces1 <> D.dullred (D.fromChars zigzag1) <>
185+ D.fromChars spaces2 <> D.dullred (D.fromChars zigzag2)
188186 ]
189187
190188 else
@@ -201,46 +199,35 @@ data Next
201199 = Keyword [Char]
202200 | Operator [Char]
203201 | Close [Char] Char
204− | Upper Char [Char]
205− | Lower Char [Char]
206− | Other (Maybe Char)
202+ | Other
207203
208204
209205whatIsNext :: Source -> Row -> Col -> Next
210206whatIsNext (Source sourceLines) row col =
211207 case List.lookup row sourceLines of
212208 Nothing ->
213− Other Nothing
209+ Other
214210
215211 Just line ->
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 == '_'
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
244231
245232
246233isSymbol :: Char -> Bool
@@ -257,32 +244,4 @@ startsWithKeyword restOfLine keyword =
257244 True
258245
259246 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
247+ not (Char.isAlphaNum c || c == '_')
compiler/src/Reporting/Render/Type/Localizer.hs+25−5
@@ -7,6 +7,8 @@ module Reporting.Render.Type.Localizer
77 , empty
88 , fromNames
99 , fromModule
10+ , replEmpty
11+ , replAdd
1012 )
1113 where
1214
@@ -16,6 +18,7 @@ import qualified Data.Name as Name
1618import qualified Data.Set as Set
1719
1820import qualified AST.Source as Src
21+import qualified Elm.Compiler.Imports as Imports
1922import qualified Elm.ModuleName as ModuleName
2023import Reporting.Doc ((<>))
2124import qualified Reporting.Doc as D
@@ -112,9 +115,26 @@ toExposing exposing =
112115 Only (foldr addType Set.empty exposedList)
113116
114117
115−addType :: Src.Exposed -> Set.Set Name.Name -> Set.Set Name.Name
116−addType exposed types =
118+addType :: A.Located Src.Exposed -> Set.Set Name.Name -> Set.Set Name.Name
119+addType (A.At _ exposed) types =
117120 case exposed of
118− Src.Lower _ -> types
119− Src.Upper (A.At _ name) _ -> Set.insert name types
120− Src.Operator _ _ -> types
121+ Src.Lower _ -> types
122+ Src.Upper name _ -> Set.insert name types
123+ Src.Operator _ -> types
124+
125+
126+
127+-- REPL STUFF
128+
129+
130+replEmpty :: Localizer
131+replEmpty =
132+ Localizer $
133+ Map.insert Name.replModule (Import Nothing All) $
134+ Map.fromList $ map toPair Imports.defaults
135+
136+
137+replAdd :: Name.Name -> Maybe Name.Name -> Src.Exposing -> Localizer -> Localizer
138+replAdd name alias exposing (Localizer localizer) =
139+ Localizer $ Map.insert name (Import alias (toExposing exposing)) localizer
140+
compiler/src/Reporting/Result.hs−10
@@ -117,13 +117,3 @@ instance Monad (Result i w e) where
117117 Result kb -> kb i1 w1 bad good
118118 in
119119 ka i w bad good1
120−
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+123−14
@@ -175,7 +175,9 @@ data Problem
175175 | StringToFloat
176176 | AnythingToBool
177177 | AnythingFromMaybe
178− | ArityMismatch Int Int
178+ | AnythingToList
179+ | MissingArgs Int
180+ | ReturnMismatch
179181 | BadFlexSuper Direction Super Name.Name Type
180182 | BadRigidVar Name.Name Type
181183 | BadRigidSuper Super Name.Name Type
@@ -253,11 +255,7 @@ toDiff localizer ctx tipe1 tipe2 =
253255 <*> toDiff localizer RT.Func b y
254256 <*> sequenceA (zipWith (toDiff localizer RT.Func) cs zs)
255257 else
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)))
258+ diffLambda localizer ctx a b cs x y zs
261259
262260 (Tuple a b Nothing, Tuple x y Nothing) ->
263261 RT.tuple
@@ -300,7 +298,7 @@ toDiff localizer ctx tipe1 tipe2 =
300298 different
301299 (toDoc localizer ctx t1)
302300 (RT.apply ctx (D.dullyellow (L.toDoc localizer home name)) [toDoc localizer RT.App t2])
303− Bag.empty
301+ (Bag.one AnythingToList)
304302
305303 (Alias home1 name1 args1 t1, t2) ->
306304 case diffAliasedRecord localizer t1 t2 of
@@ -449,13 +447,6 @@ isSuper super tipe =
449447 Appendable -> isString h n || isList h n
450448 CompAppend -> isString h n || isList h n && isSuper Comparable (head args)
451449
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−
459450 _ ->
460451 False
461452
@@ -486,6 +477,124 @@ diffAliasedRecord localizer t1 t2 =
486477
487478
488479
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+
489598-- RECORD DIFFS
490599
491600
compiler/src/Type/Solve.hs−7
@@ -427,13 +427,6 @@ 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−--
437430typeToVar :: Int -> Pools -> Map.Map Name.Name Variable -> Type -> IO Variable
438431typeToVar rank pools aliasDict tipe =
439432 let go = typeToVar rank pools aliasDict in
compiler/src/Type/Unify.hs+10−12
@@ -103,13 +103,6 @@ instance Monad Unify where
103103 in
104104 ka vars ok1 err
105105
106− (>>) (Unify ka) (Unify kb) =
107− Unify $ \vars ok err ->
108− let
109− ok1 vars1 _ = kb vars1 ok err
110− in
111− ka vars ok1 err
112−
113106
114107register :: IO Variable -> Unify Variable
115108register mkVar =
@@ -219,6 +212,8 @@ unifyFlex context content otherContent =
219212 Error ->
220213 merge context Error
221214
215+ -- TODO see if wildcarding makes a noticable perf difference
216+
222217 FlexVar maybeName ->
223218 merge context $
224219 case maybeName of
@@ -391,13 +386,13 @@ unifyFlexSuperStructure context super flatType =
391386
392387 Comparable ->
393388 do comparableOccursCheck context
394− unifyComparableRecursive variable
395389 merge context (Structure flatType)
390+ unifyComparableRecursive variable
396391
397392 CompAppend ->
398393 do comparableOccursCheck context
399− unifyComparableRecursive variable
400394 merge context (Structure flatType)
395+ unifyComparableRecursive variable
401396
402397 Tuple1 a b maybeC ->
403398 case super of
@@ -409,12 +404,15 @@ unifyFlexSuperStructure context super flatType =
409404
410405 Comparable ->
411406 do comparableOccursCheck context
407+ merge context (Structure flatType)
412408 unifyComparableRecursive a
413409 unifyComparableRecursive b
414410 case maybeC of
415− Nothing -> return ()
416− Just c -> unifyComparableRecursive c
417− merge context (Structure flatType)
411+ Nothing ->
412+ return ()
413+
414+ Just c ->
415+ unifyComparableRecursive c
418416
419417 CompAppend ->
420418 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.1",
11+ "elm-version": "0.19.0",
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.1"` for most people!
51+The exact version of Elm this builds with. Should be `"0.19.0"` 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, and BSD-3-Clause is a good default. 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, but you can see the full list of options [here](https://spdx.org/licenses/).
5353
5454<br>
5555
docs/upgrade-instructions/0.19.1.mddeleted−60
@@ -1,60 +0,0 @@
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 (..)`
elm.cabal+12−31
@@ -38,14 +38,11 @@ Executable elm
3838 if flag(dev)
3939 ghc-options: -O0 -Wall -Werror
4040 else
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/
41+ ghc-options: -O2 -rtsopts
4442
4543 Hs-Source-Dirs:
4644 compiler/src
4745 builder/src
48− terminal/impl
4946 terminal/src
5047
5148 other-extensions:
@@ -55,38 +52,24 @@ Executable elm
5552 Main.hs
5653
5754 other-modules:
58− Bump
59− Develop
60− Diff
61− Init
62− Install
55+ Develop.StaticFiles
56+ Develop.StaticFiles.Build
6357 Make
64− Publish
65− Repl
6658
6759 -- terminal args
68− Terminal
69− Terminal.Chomp
70− Terminal.Error
71− Terminal.Helpers
72− Terminal.Internal
73−
74− -- from terminal/
75− Develop.Generate.Help
76− Develop.Generate.Index
77− Develop.StaticFiles
78− Develop.StaticFiles.Build
60+ Terminal.Args
61+ Terminal.Args.Chomp
62+ Terminal.Args.Error
63+ Terminal.Args.Helpers
64+ Terminal.Args.Internal
7965
8066 -- from builder/
8167 Build
82− BackgroundWriter
83− Deps.Bump
84− Deps.Diff
8568 Deps.Registry
69+ Deps.Diff
8670 Deps.Solver
8771 Deps.Website
8872 File
89− Generate
9073 Http
9174 Reporting
9275 Reporting.Exit
@@ -103,14 +86,12 @@ Executable elm
10386 Elm.Compiler.Type.Extract
10487 Elm.Constraint
10588 Elm.Docs
106− Elm.Float
10789 Elm.Interface
10890 Elm.Kernel
10991 Elm.Licenses
11092 Elm.Magnitude
11193 Elm.ModuleName
11294 Elm.Package
113− Elm.String
11495 Elm.Version
11596
11697 -- data structures
@@ -125,7 +106,6 @@ Executable elm
125106 -- json
126107 Json.Decode
127108 Json.Encode
128− Json.String
129109
130110 -- from compiler/
131111 AST.Canonical
@@ -165,11 +145,12 @@ Executable elm
165145 Parse.Module
166146 Parse.Number
167147 Parse.Pattern
148+ Parse.Repl
168149 Parse.Shader
169150 Parse.Space
170− Parse.String
171151 Parse.Symbol
172152 Parse.Type
153+ Parse.Utf8
173154 Parse.Variable
174155 Parse.Primitives
175156 Reporting.Annotation
@@ -231,7 +212,7 @@ Executable elm
231212 snap-core,
232213 snap-server,
233214 template-haskell,
234− time >= 1.9.1,
215+ time,
235216 unordered-containers,
236217 utf8-string,
237218 vector,
hints/bad-recursion.mddeleted−133
@@ -1,133 +0,0 @@
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.mddeleted−98
@@ -1,98 +0,0 @@
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.mddeleted−85
@@ -1,85 +0,0 @@
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.mddeleted−50
@@ -1,50 +0,0 @@
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.mddeleted−184
@@ -1,184 +0,0 @@
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.mddeleted−126
@@ -1,126 +0,0 @@
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.mddeleted−42
@@ -1,42 +0,0 @@
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.mddeleted−55
@@ -1,55 +0,0 @@
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.mddeleted−139
@@ -1,139 +0,0 @@
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.mddeleted−59
@@ -1,59 +0,0 @@
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.mddeleted−32
@@ -1,32 +0,0 @@
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.mddeleted−162
@@ -1,162 +0,0 @@
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.mddeleted−73
@@ -1,73 +0,0 @@
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.mddeleted−70
@@ -1,70 +0,0 @@
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.mddeleted−19
@@ -1,19 +0,0 @@
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.mddeleted−60
@@ -1,60 +0,0 @@
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.mddeleted−32
@@ -1,32 +0,0 @@
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/Dockerfiledeleted−39
@@ -1,39 +0,0 @@
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.mddeleted−93
@@ -1,93 +0,0 @@
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+3−5
@@ -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</title>
3+ <title>Elm Platform</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 requires Mac OS X 10.6 or later.';
13+ my.result.message = 'This version of Elm Platform requires Mac OS X 10.6 or later.';
1414 my.result.type = 'Fatal';
1515 return false;
1616 }
@@ -18,15 +18,13 @@ function pm_volume_check() {
1818}
1919
2020</script>
21− <!--
2221 <background file="background.png" alignment="bottomleft" scaling="none" mime-type="image/png"/>
23− -->
2422 <welcome mime-type="text/rtf" file="welcome.rtf" />
2523 <conclusion mime-type="text/rtf" file="conclusion.rtf" />
2624 <choices-outline>
2725 <line choice="choice2"/>
2826 </choices-outline>
29− <choice id="choice2" title="Elm">
27+ <choice id="choice2" title="Elm Platform ">
3028 <pkg-ref id="org.elm-lang.binaries.pkg"/>
3129 </choice>
3230 <pkg-ref id="org.elm-lang.binaries.pkg" installKBytes="19444" version="1" auth="Root">binaries.pkg</pkg-ref>
installers/mac/README.mddeleted−93
@@ -1,93 +0,0 @@
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.pngnew file

Binary file not shown.

installers/mac/Resources/en.lproj/conclusion.rtf+6−13
@@ -1,16 +1,9 @@
1−{\rtf1\ansi\ansicpg1252\cocoartf2509
2−\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fmodern\fcharset0 CourierNewPSMT;}
1+{\rtf1\ansi\ansicpg1252\cocoartf1187\cocoasubrtf400
2+{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
33{\colortbl;\red255\green255\blue255;}
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
4+\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
5+\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
76
8−\f0\fs28 \cf0 Try opening the terminal and running commands like:\
7+\f0\fs26 \cf0 A bunch of useful programs were just placed in /usr/local/bin/\
98\
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!}
9+Check out {\field{\*\fldinst HYPERLINK "http://elm-lang.org/Get-Started.elm"}{\fldrslt this tutorial}} to learn how to use them!}
installers/mac/Resources/en.lproj/welcome.rtf+4−9
@@ -1,12 +1,7 @@
1−{\rtf1\ansi\ansicpg1252\cocoartf2509
2−\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fmodern\fcharset0 CourierNewPSMT;}
1+{\rtf1\ansi\ansicpg1252\cocoartf1187\cocoasubrtf400
2+{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
33{\colortbl;\red255\green255\blue255;}
4−{\*\expandedcolortbl;;}
54\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
6−\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0
5+\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
76
8−\f0\fs28 \cf0 Thank you for trying out Elm!\
9−\
10−This installer makes
11−\f1 elm
12−\f0 available in your terminal.}
7+\f0\fs28 \cf0 This package will install Elm on your machine.}
installers/mac/helper-scripts/elm-startup.sh+1−1
@@ -1,3 +1,3 @@
11#!/bin/sh
22
3−open 'http://guide.elm-lang.org'
3+open 'http://elm-lang.org'
installers/mac/make-installer.sh+3−30
@@ -29,8 +29,7 @@ cp $(pwd)/preinstall $pkg_scripts
2929cp $(pwd)/postinstall $pkg_scripts
3030
3131pkgbuild \
32− --sign "Developer ID Installer: <NAME>" \
33− --identifier org.elm-lang.binary \
32+ --identifier org.elm-lang.binaries.pkg \
3433 --install-location $usr_binaries \
3534 --scripts $pkg_scripts \
3635 --filter 'Scripts.*' \
@@ -40,42 +39,16 @@ pkgbuild \
4039
4140#### BUNDLE ASSETS ####
4241
43−rm -f installer-for-mac.pkg
42+rm -f Elm.pkg
4443
4544productbuild \
46− --sign "Developer ID Installer: <NAME>" \
47− --identifier org.elm-lang.installer \
4845 --distribution Distribution.xml \
4946 --package-path . \
5047 --resources Resources \
51− installer-for-mac.pkg
48+ Elm.pkg
5249
5350
5451#### CLEAN UP ####
5552
5653rm binaries.pkg
5754rm -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+141−29
@@ -1,59 +1,171 @@
1−# Publishing
1+# Publishing a new release
22
3−Here's how to update the `npm` installer.
3+A new version of Elm came out. Huzzah! Here's how to update the `npm` installer.
44
5+## 1. Create tarballs of binaries
56
6−## 1. GitHub Release
7+You can find a list of what binaries we'll need to tar up in `index.js`.
78
8−Create a [GitHub Release](https://github.com/elm/compiler/releases) with the following files:
9+For example:
910
10−1. `binary-for-mac-64-bit.gz`
11−2. `binary-for-windows-64-bit.gz`
12−3. `binary-for-linux-64-bit.gz`
11+```javascript
12+var root =
13+ "https://github.com/elm/compiler/releases/download/" +
14+ binVersion +
15+ "/binaries-for-";
1316
14−Create each of these by running the `elm` executable for each platform through `gzip elm`.
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:
1529
30+1. `binaries-for-mac.tar.gz`
31+2. `binaries-for-windows.tar.gz`
32+3. `binaries-for-linux.tar.gz`
1633
17−## 2. Try a beta release
34+Each of these tarballs should have **only the Elm binary** inside them - no
35+directories!
1836
19−In `package.json`, bump the version to `"0.19.2-beta"`.
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:
2039
21−```bash
22−npm publish --tag beta
40+```shell
41+$ tar cvzf binaries-for-linux.tar.gz elm
2342```
2443
25−To test that it works, run these commands:
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:
2680
27−```bash
28−npm dist-tags ls elm
29−npm install elm@beta --ignore-scripts
81+```shell
82+$ git tag 0.19.0
83+$ git push origin 0.19.0
3084```
3185
32−The `latest` tag should not be changed, and there should be an additional `beta` tag.
86+Now this tag should exist on GitHub, allowing us to upload binaries to it.
3387
34−Try this on Windows, Linux, and Mac.
88+## 5. Upload binaries
3589
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.
3694
37−## 3. Publish final release
95+Upload the tarballs you created in step 1.
3896
39−Remove the `-beta` suffix from the version in `package.json`. Then run:
97+## 6. Publish beta release
4098
41−```bash
42−npm publish
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
43106```
44107
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+```
45114
46−## 4. Tag the `latest-0.19.1` version
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.
47119
48−Many compiler releases have needed multiple `npm` publications. Maybe something does not work on Windows or some dependency becomes insecure. Normal `npm` problems.
120+## 7. Verify beta installer
49121
50−The convention for each Elm release is to create a tag the latest one.
122+Make an empty directory and run `npm init` inside it.
51123
52−```bash
53−npm dist-tag add elm@0.19.1-3 latest-0.19.1
124+Then run this:
125+
126+```shell
127+$ npm install elm@beta --ignore-scripts
54128```
55129
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.
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`
57163
58−You can read more about dist-tags [here](https://docs.npmjs.com/cli/dist-tag).
164+You're done! Now whenever anyone does `npm install -g elm` they'll get the
165+version you just uploaded.
59166
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+23−30
@@ -1,45 +1,38 @@
1−# Elm Installer
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+===============
23
3−[Elm](https://elm-lang.org) is a functional programming language that compiles to JavaScript.
4+Install the [Elm Platform](https://github.com/elm-lang/elm-platform) via [`npm`](https://www.npmjs.com).
45
5−Head over to [The Official Guide](https://guide.elm-lang.org/) to start learning Elm!
6+## Installing
67
8+Run this to get the binaries:
79
8−<br/>
9−
10−## What is this package for?
11−
12−**Normal installs** ❌
13−
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.
10+```
11+$ npm install -g elm
12+```
2813
14+## Installing behind a proxy server
2915
30−<br/>
16+If you are behind a proxy server, set the environment variable "HTTPS_PROXY".
3117
32−## Install Locally
18+```
19+$ export HTTPS_PROXY=$YourProxyServer$
20+$ npm install -g elm
21+```
3322
34−The following command should download the latest Elm 0.19.1 binary:
23+Or on Windows:
3524
3625```
37−npm install elm@latest-0.19.1
26+$ set HTTPS_PROXY=$YourProxyServer$
27+$ npm install -g elm
3828```
3929
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.
30+## Troubleshooting
4131
42−Use `npm install elm@latest-0.19.0` or `npm install elm@latest-0.18.0` for earlier versions.
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.
4335
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.
36+## Getting Started
4537
38+Once everything has installed successfully, head over to the [Get Started](http://elm-lang.org/Get-Started.elm) page!
installers/npm/bin/elm+16−42
@@ -1,54 +1,28 @@
11#!/usr/bin/env node
22
33var child_process = require('child_process');
4−var path = require('path');
4+var download = require('../download.js');
55var fs = require('fs');
66
77
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.
8+// Some npm users enable --ignore-scripts (a good security measure)
119//
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.
10+// They do not run the post-install hook, so install.js does not run.
1611//
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.
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.
2615
2716
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−}
4517
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]);
4621
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−}
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+});
installers/npm/download.js+67−68
@@ -1,7 +1,7 @@
11var fs = require('fs');
22var package = require('./package.json');
3−var path = require('path');
4−var request = require('request');
3+var URL = require('url').URL;
4+var https = require('https');
55var zlib = require('zlib');
66
77
@@ -12,72 +12,87 @@ 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(callback)
15+module.exports = function(destinationPath, callback)
1616{
17− // figure out URL of binary
1817 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];
1920
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];
26−
27− verifyPlatform(version, platform);
28−
29− var url = 'https://github.com/elm/compiler/releases/download/' + version + '/binary-for-' + platform + '.gz';
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+};
3027
31− reportDownload(version, url);
3228
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' : '');
3529
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− }
30+// DOWNLOAD
4131
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− });
4632
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);
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+ );
5765}
5866
5967
6068
61−// VERIFY PLATFORM
69+// HANDLE REDIRECTS
6270
6371
64−function verifyPlatform(version, platform)
72+function requestWithRedirects(url, maxRedirects, failure, success)
6573{
66− if (platform) return;
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+ });
6792
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);
93+ req.on('error', failure);
94+
95+ req.end();
8196}
8297
8398
@@ -96,19 +111,3 @@ function exitFailure(url, message)
96111 );
97112 process.exit(1);
98113}
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+7−1
@@ -1,4 +1,10 @@
11
22var download = require('./download.js');
3+var package = require('./package.json');
4+var path = require('path');
35
4−download(function() {});
6+
7+// get slashes right for Windows
8+var targetPath = path.resolve(__dirname, Object.values(package.bin)[0]);
9+
10+download(targetPath, function() {});
installers/npm/package.json+7−6
@@ -1,6 +1,6 @@
11{
22 "name": "elm",
3− "version": "0.19.1-5",
3+ "version": "0.19.0-no-deps",
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": "Evan Czaplicki",
15− "email": "evan@elm-lang.org",
16− "url": "https://github.com/evancz"
14+ "name": "Richard Feldman",
15+ "email": "richard.t.feldman@gmail.com",
16+ "url": "https://github.com/rtfeldman"
1717 },
1818 "engines": {
1919 "node": ">=7.0.0"
@@ -35,8 +35,9 @@
3535 "install",
3636 "installer"
3737 ],
38− "bin": { "elm": "bin/elm" },
38+ "bin": {
39+ "elm": "bin/elm"
40+ },
3941 "dependencies": {
40− "request": "^2.88.0"
4142 }
4243}
installers/npm/troubleshooting.mddeleted−76
@@ -1,76 +0,0 @@
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" "https://guide.elm-lang.org"
78+ ExecShell "open" "http://elm-lang.org/get-started"
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+3−18
@@ -1,24 +1,9 @@
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
1+# Building Windows installer
172
183You will need the [NSIS installer](http://nsis.sourceforge.net/Download) to be installed.
194
205Once everything is installed, run something like this command:
216
22− make_installer.cmd 0.19.0
7+ make_installer.cmd 0.19
238
24−It will build an installer called `Elm-0.19.0-setup.exe`.
9+It will build an installer called `Elm-0.19-setup.exe`.
installers/win/file.iconew file

Binary file not shown.

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

Binary file not shown.

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

Binary file not shown.

reactor/assets/waiting.gifnew file

Binary file not shown.

reactor/elm.json+2−2
@@ -3,7 +3,7 @@
33 "source-directories": [
44 "src"
55 ],
6− "elm-version": "0.19.1",
6+ "elm-version": "0.19.0",
77 "dependencies": {
88 "direct": {
99 "elm/browser": "1.0.1",
@@ -28,4 +28,4 @@
2828 "direct": {},
2929 "indirect": {}
3030 }
31−}
31+}
reactor/src/Index.elm+15−20
@@ -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 "outline" (D.nullable Project.decoder))
67+ (D.field "project" (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 viewVersion info.depsDirect
222+ List.map (viewDependency exactDeps) info.depsDirect
223223
224224 Project.Package info ->
225− List.map (viewConstraint exactDeps) info.deps
225+ List.map (viewDependency 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 viewVersion info.testDepsDirect
240+ List.map (viewDependency exactDeps) info.testDepsDirect
241241
242242 Project.Package info ->
243− List.map (viewConstraint exactDeps) info.testDeps
243+ List.map (viewDependency exactDeps) info.testDeps
244244 in
245245 Skeleton.box
246246 { title = "Test Dependencies"
@@ -249,22 +249,9 @@ viewTestDeps exactDeps project =
249249 }
250250
251251
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, _) =
252+viewDependency : ExactDeps -> (Package.Name, vsn) -> List (Html msg)
253+viewDependency exactDeps (pkg, _) =
264254 case Dict.get (Package.toString pkg) exactDeps of
265− Just vsn ->
266− viewVersion (pkg, vsn)
267−
268255 Nothing ->
269256 [ div [ style "float" "left" ]
270257 [ Icon.package
@@ -273,6 +260,14 @@ viewConstraint exactDeps (pkg, _) =
273260 , div [ style "float" "right" ] [ text "???" ]
274261 ]
275262
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+
276271
277272toPackageUrl : Package.Name -> Version.Version -> String
278273toPackageUrl 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.mddeleted−29
@@ -1,29 +0,0 @@
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/Bump.hs+8−158
@@ -1,31 +1,10 @@
1−{-# LANGUAGE OverloadedStrings #-}
2−module Bump
3− ( run
4− )
5− where
1+module Bump (run) where
62
73
8−import qualified Data.List as List
9−import qualified Data.NonEmptyList as NE
10−
11−import qualified BackgroundWriter as BW
12−import qualified Build
13−import qualified Deps.Bump as Bump
14−import qualified Deps.Diff as Diff
15−import qualified Deps.Registry as Registry
16−import qualified Elm.Details as Details
17−import qualified Elm.Docs as Docs
18−import qualified Elm.Magnitude as M
19−import qualified Elm.Outline as Outline
20−import qualified Elm.Version as V
21−import qualified Http
22−import Reporting.Doc ((<>), (<+>))
23−import qualified Reporting
24−import qualified Reporting.Doc as D
25−import qualified Reporting.Exit as Exit
26−import qualified Reporting.Exit.Help as Help
4+import qualified Elm.Bump as Bump
5+import qualified Elm.Project as Project
276import qualified Reporting.Task as Task
28−import qualified Stuff
7+import qualified Reporting.Progress.Terminal as Terminal
298
309
3110
@@ -34,136 +13,7 @@ import qualified Stuff
3413
3514run :: () -> () -> IO ()
3615run () () =
37− Reporting.attempt Exit.bumpToReport $
38− Task.run (bump =<< getEnv)
39−
40−
41−
42−-- ENV
43−
44−
45−data Env =
46− Env
47− { _root :: FilePath
48− , _cache :: Stuff.PackageCache
49− , _manager :: Http.Manager
50− , _registry :: Registry.Registry
51− , _outline :: Outline.PkgOutline
52− }
53−
54−
55−getEnv :: Task.Task Exit.Bump Env
56−getEnv =
57− do maybeRoot <- Task.io $ Stuff.findRoot
58− case maybeRoot of
59− Nothing ->
60− Task.throw Exit.BumpNoOutline
61−
62− Just root ->
63− do cache <- Task.io $ Stuff.getPackageCache
64− manager <- Task.io $ Http.getManager
65− registry <- Task.eio Exit.BumpMustHaveLatestRegistry $ Registry.latest manager cache
66− outline <- Task.eio Exit.BumpBadOutline $ Outline.read root
67− case outline of
68− Outline.App _ ->
69− Task.throw Exit.BumpApplication
70−
71− Outline.Pkg pkgOutline ->
72− return $ Env root cache manager registry pkgOutline
73−
74−
75−
76−-- BUMP
77−
78−
79−bump :: Env -> Task.Task Exit.Bump ()
80−bump env@(Env root _ _ registry outline@(Outline.PkgOutline pkg _ _ vsn _ _ _ _)) =
81− case Registry.getVersions pkg registry of
82− Just knownVersions ->
83− let
84− bumpableVersions =
85− map (\(old, _, _) -> old) (Bump.getPossibilities knownVersions)
86− in
87− if elem vsn bumpableVersions
88− then suggestVersion env
89− else
90− Task.throw $ Exit.BumpUnexpectedVersion vsn $
91− map head (List.group (List.sort bumpableVersions))
92−
93− Nothing ->
94− Task.io $ checkNewPackage root outline
95−
96−
97−
98−-- CHECK NEW PACKAGE
99−
100−
101−checkNewPackage :: FilePath -> Outline.PkgOutline -> IO ()
102−checkNewPackage root outline@(Outline.PkgOutline _ _ _ version _ _ _ _) =
103− do putStrLn Exit.newPackageOverview
104− if version == V.one
105− then
106− putStrLn "The version number in elm.json is correct so you are all set!"
107− else
108− changeVersion root outline V.one $
109− "It looks like the version in elm.json has been changed though!\n\
110− \Would you like me to change it back to "
111− <> D.fromVersion V.one <> "? [Y/n] "
112−
113−
114−
115−-- SUGGEST VERSION
116−
117−
118−suggestVersion :: Env -> Task.Task Exit.Bump ()
119−suggestVersion (Env root cache manager _ outline@(Outline.PkgOutline pkg _ _ vsn _ _ _ _)) =
120− do oldDocs <- Task.eio (Exit.BumpCannotFindDocs pkg vsn) (Diff.getDocs cache manager pkg vsn)
121− newDocs <- generateDocs root outline
122− let changes = Diff.diff oldDocs newDocs
123− let newVersion = Diff.bump changes vsn
124− Task.io $ changeVersion root outline newVersion $
125− let
126− old = D.fromVersion vsn
127− new = D.fromVersion newVersion
128− mag = D.fromChars $ M.toChars (Diff.toMagnitude changes)
129− in
130− "Based on your new API, this should be a" <+> D.green mag <+> "change (" <> old <> " => " <> new <> ")\n"
131− <> "Bail out of this command and run 'elm diff' for a full explanation.\n"
132− <> "\n"
133− <> "Should I perform the update (" <> old <> " => " <> new <> ") in elm.json? [Y/n] "
134−
135−
136−generateDocs :: FilePath -> Outline.PkgOutline -> Task.Task Exit.Bump Docs.Documentation
137−generateDocs root (Outline.PkgOutline _ _ _ _ exposed _ _ _) =
138− do details <-
139− Task.eio Exit.BumpBadDetails $ BW.withScope $ \scope ->
140− Details.load Reporting.silent scope root
141−
142− case Outline.flattenExposed exposed of
143− [] ->
144− Task.throw $ Exit.BumpNoExposed
145−
146− e:es ->
147− Task.eio Exit.BumpBadBuild $
148− Build.fromExposed Reporting.silent root details Build.KeepDocs (NE.List e es)
149−
150−
151−
152−-- CHANGE VERSION
153−
154−
155−changeVersion :: FilePath -> Outline.PkgOutline -> V.Version -> D.Doc -> IO ()
156−changeVersion root outline targetVersion question =
157− do approved <- Reporting.ask question
158− if not approved
159− then
160− putStrLn "Okay, I did not change anything!"
161−
162− else
163− do Outline.write root $ Outline.Pkg $
164− outline { Outline._pkg_version = targetVersion }
165−
166− Help.toStdout $
167− "Version changed to "
168− <> D.green (D.fromVersion targetVersion)
169− <> "!\n"
16+ do reporter <- Terminal.create
17+ Task.run reporter $
18+ do summary <- Project.getRoot
19+ Bump.bump summary
terminal/src/Develop.hs+77−70
@@ -7,31 +7,27 @@ module Develop
77
88
99import Control.Applicative ((<|>))
10−import Control.Monad (guard)
10+import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
11+import Control.Monad (guard, void)
1112import Control.Monad.Trans (MonadIO(liftIO))
1213import qualified Data.ByteString.Builder as B
1314import qualified Data.ByteString as BS
1415import qualified Data.HashMap.Strict as HashMap
1516import Data.Monoid ((<>))
16−import qualified Data.NonEmptyList as NE
1717import qualified System.Directory as Dir
1818import System.FilePath as FP
19−import Snap.Core hiding (path)
19+import Snap.Core
2020import Snap.Http.Server
2121import Snap.Util.FileServe
2222
23−import qualified BackgroundWriter as BW
24−import qualified Build
25−import qualified Elm.Details as Details
26−import qualified Develop.Generate.Help as Help
23+import qualified Elm.Project as Project
24+import qualified Develop.Generate.Help as Generate
2725import qualified Develop.Generate.Index as Index
2826import qualified Develop.StaticFiles as StaticFiles
29−import qualified Generate.Html as Html
30−import qualified Generate
31−import qualified Reporting
27+import qualified Generate.Output as Output
3228import qualified Reporting.Exit as Exit
29+import qualified Reporting.Progress as Progress
3330import qualified Reporting.Task as Task
34−import qualified Stuff
3531
3632
3733
@@ -46,19 +42,31 @@ data Flags =
4642
4743run :: () -> Flags -> IO ()
4844run () (Flags maybePort) =
49− do let port = maybe 8000 id maybePort
50− putStrLn $ "Go to http://localhost:" ++ show port ++ " to see your project dashboard."
51− httpServe (config port) $
52− serveFiles
53− <|> serveDirectoryWith directoryConfig "."
54− <|> serveAssets
55− <|> error404
45+ let
46+ port =
47+ maybe 8000 id maybePort
48+ in
49+ do putStrLn $ "Go to <http://localhost:" ++ show port ++ "> to see your project dashboard."
50+
51+ httpServe (config port) $
52+ serveFiles
53+ <|> serveDirectoryWith directoryConfig "."
54+ <|> serveAssets
55+ <|> error404
5656
5757
5858config :: Int -> Config Snap a
5959config port =
60− setVerbose False $ setPort port $
61− setAccessLog ConfigNoLog $ setErrorLog ConfigNoLog $ defaultConfig
60+ defaultConfig
61+ # setVerbose False
62+ # setPort port
63+ # setAccessLog ConfigNoLog
64+ # setErrorLog ConfigNoLog
65+
66+
67+(#) :: a -> (a -> b) -> b
68+(#) value func =
69+ func value
6270
6371
6472
@@ -67,12 +75,18 @@ config port =
6775
6876directoryConfig :: MonadSnap m => DirectoryConfig m
6977directoryConfig =
70− fancyDirectoryConfig
71− { indexFiles = []
72− , indexGenerator = \pwd ->
73− do modifyResponse $ setContentType "text/html;charset=utf-8"
74− writeBuilder =<< liftIO (Index.generate pwd)
75− }
78+ let
79+ customGenerator pwd =
80+ do modifyResponse $ setContentType "text/html; charset=utf-8"
81+ html <- liftIO $
82+ do root <- Dir.getCurrentDirectory
83+ Index.get root pwd
84+ writeBuilder html
85+ in
86+ fancyDirectoryConfig
87+ { indexFiles = []
88+ , indexGenerator = customGenerator
89+ }
7690
7791
7892
@@ -82,8 +96,8 @@ directoryConfig =
8296error404 :: Snap ()
8397error404 =
8498 do modifyResponse $ setResponseStatus 404 "Not Found"
85− modifyResponse $ setContentType "text/html;charset=utf-8"
86− writeBuilder $ Help.makePageHtml "NotFound" Nothing
99+ modifyResponse $ setContentType "text/html; charset=utf-8"
100+ writeBuilder $ Generate.makePageHtml "NotFound" Nothing
87101
88102
89103
@@ -92,9 +106,9 @@ error404 =
92106
93107serveFiles :: Snap ()
94108serveFiles =
95− do path <- getSafePath
96− guard =<< liftIO (Dir.doesFileExist path)
97− serveElm path <|> serveFilePretty path
109+ do file <- getSafePath
110+ guard =<< liftIO (Dir.doesFileExist file)
111+ serveElm file <|> serveFilePretty file
98112
99113
100114
@@ -102,33 +116,34 @@ serveFiles =
102116
103117
104118serveFilePretty :: FilePath -> Snap ()
105−serveFilePretty path =
119+serveFilePretty file =
106120 let
107121 possibleExtensions =
108− getSubExts (takeExtensions path)
122+ getSubExts (takeExtensions file)
109123 in
110124 case mconcat (map lookupMimeType possibleExtensions) of
111125 Nothing ->
112− serveCode path
126+ serveCode file
113127
114128 Just mimeType ->
115− serveFileAs mimeType path
129+ serveFileAs mimeType file
116130
117131
118132getSubExts :: String -> [String]
119133getSubExts fullExtension =
120134 if null fullExtension then
121135 []
136+
122137 else
123138 fullExtension : getSubExts (takeExtensions (drop 1 fullExtension))
124139
125140
126141serveCode :: String -> Snap ()
127−serveCode path =
128− do code <- liftIO (BS.readFile path)
142+serveCode file =
143+ do code <- liftIO (BS.readFile file)
129144 modifyResponse (setContentType "text/html")
130145 writeBuilder $
131− Help.makeCodeHtml ('~' : '/' : path) (B.byteString code)
146+ Generate.makeCodeHtml ('~' : '/' : file) (B.byteString code)
132147
133148
134149
@@ -136,33 +151,31 @@ serveCode path =
136151
137152
138153serveElm :: FilePath -> Snap ()
139−serveElm path =
140− do guard (takeExtension path == ".elm")
154+serveElm file =
155+ do guard (takeExtension file == ".elm")
141156 modifyResponse (setContentType "text/html")
142− result <- liftIO $ compile path
143− case result of
144− Right builder ->
145− writeBuilder builder
157+ writeBuilder =<< liftIO (compileToHtmlBuilder file)
146158
147− Left exit ->
148− writeBuilder $ Help.makePageHtml "Errors" $ Just $
149− Exit.toJson $ Exit.reactorToReport exit
150159
160+compileToHtmlBuilder :: FilePath -> IO B.Builder
161+compileToHtmlBuilder file =
162+ do mvar1 <- newEmptyMVar
163+ mvar2 <- newEmptyMVar
151164
152−compile :: FilePath -> IO (Either Exit.Reactor B.Builder)
153−compile path =
154− do maybeRoot <- Stuff.findRoot
155− case maybeRoot of
156− Nothing ->
157− return $ Left $ Exit.ReactorNoOutline
165+ let reporter = Progress.Reporter (\_ -> return ()) (\_ -> return True) (putMVar mvar1)
166+ let output = Just (Output.HtmlBuilder mvar2)
167+
168+ void $ Task.try reporter $
169+ do summary <- Project.getRoot
170+ Project.compile Output.Dev Output.Client output summary [file]
158171
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
172+ result <- takeMVar mvar1
173+ case result of
174+ Just exit ->
175+ return $ Generate.makePageHtml "Errors" (Just (Exit.toJson exit))
176+
177+ Nothing ->
178+ takeMVar mvar2
166179
167180
168181
@@ -171,8 +184,8 @@ compile path =
171184
172185serveAssets :: Snap ()
173186serveAssets =
174− do path <- getSafePath
175− case StaticFiles.lookup path of
187+ do file <- getSafePath
188+ case StaticFiles.lookup file of
176189 Nothing ->
177190 pass
178191
@@ -218,16 +231,13 @@ mimeTypeDict =
218231 , ".m3u" ==> "audio/x-mpegurl"
219232 , ".mov" ==> "video/quicktime"
220233 , ".mp3" ==> "audio/mpeg"
221− , ".mp4" ==> "video/mp4"
222234 , ".mpeg" ==> "video/mpeg"
223235 , ".mpg" ==> "video/mpeg"
224236 , ".ogg" ==> "application/ogg"
225− , ".otf" ==> "font/otf"
226237 , ".pac" ==> "application/x-ns-proxy-autoconfig"
227238 , ".pdf" ==> "application/pdf"
228239 , ".png" ==> "image/png"
229240 , ".qt" ==> "video/quicktime"
230− , ".sfnt" ==> "font/sfnt"
231241 , ".sig" ==> "application/pgp-signature"
232242 , ".spl" ==> "application/futuresplash"
233243 , ".svg" ==> "image/svg+xml"
@@ -238,19 +248,16 @@ mimeTypeDict =
238248 , ".tbz" ==> "application/x-bzip-compressed-tar"
239249 , ".text" ==> "text/plain"
240250 , ".tgz" ==> "application/x-tgz"
241− , ".ttf" ==> "font/ttf"
251+ , ".ttf" ==> "application/x-font-truetype"
242252 , ".txt" ==> "text/plain"
243253 , ".wav" ==> "audio/x-wav"
244254 , ".wax" ==> "audio/x-ms-wax"
245− , ".webm" ==> "video/webm"
246− , ".webp" ==> "image/webp"
247255 , ".wma" ==> "audio/x-ms-wma"
248256 , ".wmv" ==> "video/x-ms-wmv"
249− , ".woff" ==> "font/woff"
250− , ".woff2" ==> "font/woff2"
251257 , ".xbm" ==> "image/x-xbitmap"
252258 , ".xml" ==> "text/xml"
253259 , ".xpm" ==> "image/x-xpixmap"
254260 , ".xwd" ==> "image/x-xwindowdump"
255261 , ".zip" ==> "application/zip"
256262 ]
263+
terminal/src/Develop/Generate/Index.hs+74−149
@@ -1,37 +1,36 @@
11{-# OPTIONS_GHC -Wall #-}
22{-# LANGUAGE OverloadedStrings #-}
33module Develop.Generate.Index
4− ( generate
4+ ( get
55 )
66 where
77
88
99import Control.Monad (filterM)
1010import qualified Data.ByteString.Builder as B
11−import qualified Data.List as List
1211import qualified Data.Map as Map
12+import qualified Data.Text as Text
13+import qualified Data.Text.IO as Text
1314import qualified System.Directory as Dir
1415import System.FilePath ((</>), splitDirectories, takeExtension)
1516
16−import qualified BackgroundWriter as BW
1717import qualified Develop.Generate.Help as Help
18−import qualified Elm.Details as Details
19−import qualified Elm.Outline as Outline
2018import qualified Elm.Package as Pkg
21−import qualified Elm.Version as V
19+import qualified Elm.Project.Json as Project
20+import qualified Elm.Project.Summary as Summary
2221import qualified Json.Encode as E
23−import Json.Encode ((==>))
24−import qualified Reporting
25−import qualified Stuff
22+import qualified Reporting.Progress as Progress
23+import qualified Reporting.Task as Task
24+import qualified Stuff.Verify as Verify
2625
2726
2827
29−-- GENERATE
28+-- GET
3029
3130
32−generate :: FilePath -> IO B.Builder
33−generate pwd =
34− do flags <- getFlags pwd
31+get :: FilePath -> FilePath -> IO B.Builder
32+get root pwd =
33+ do flags <- getFlags root pwd
3534 return $ Help.makePageHtml "Index" (Just (encode flags))
3635
3736
@@ -44,33 +43,60 @@ data Flags =
4443 { _root :: FilePath
4544 , _pwd :: [String]
4645 , _dirs :: [FilePath]
47− , _files :: [File]
48− , _readme :: Maybe String
49− , _outline :: Maybe Outline.Outline
50− , _exactDeps :: Map.Map Pkg.Name V.Version
46+ , _files :: [(FilePath, Bool)]
47+ , _readme :: Maybe Text.Text
48+ , _project :: Maybe Project.Project
49+ , _exactDeps :: Map.Map Pkg.Name Pkg.Version
5150 }
5251
5352
54−data File =
55− File
56− { _path :: FilePath
57− , _runnable :: Bool
58− }
53+
54+-- JSON
55+
56+
57+encode :: Flags -> E.Value
58+encode (Flags root pwd dirs files readme project exactDeps) =
59+ E.object
60+ [ ( "root", encodeFilePath root )
61+ , ( "pwd", E.list encodeFilePath pwd )
62+ , ( "dirs", E.list encodeFilePath dirs )
63+ , ( "files", E.list encodeFile files )
64+ , ( "readme", maybe E.null E.text readme )
65+ , ( "project", maybe E.null Project.encode project )
66+ , ( "exactDeps", E.dict Pkg.toText Pkg.encodeVersion exactDeps)
67+ ]
68+
69+
70+encodeFilePath :: FilePath -> E.Value
71+encodeFilePath filePath =
72+ E.text (Text.pack filePath)
73+
74+
75+encodeFile :: (FilePath, Bool) -> E.Value
76+encodeFile (file, hasMain) =
77+ E.object
78+ [ ("name", encodeFilePath file)
79+ , ("runnable", E.bool hasMain)
80+ ]
5981
6082
6183
6284-- GET FLAGS
6385
6486
65−getFlags :: FilePath -> IO Flags
66−getFlags pwd =
67− do contents <- Dir.getDirectoryContents pwd
68− root <- Dir.getCurrentDirectory
69− dirs <- getDirs pwd contents
70− files <- getFiles pwd contents
87+getFlags :: FilePath -> FilePath -> IO Flags
88+getFlags root pwd =
89+ do (dirs, files) <- getDirsAndFiles pwd
7190 readme <- getReadme pwd
72− outline <- getOutline
73− exactDeps <- getExactDeps outline
91+ exists <- Dir.doesFileExist (root </> "elm.json")
92+
93+ maybeSummary <-
94+ if exists then
95+ Task.try Progress.silentReporter $
96+ Verify.verify root =<< Project.read (root </> "elm.json")
97+ else
98+ return Nothing
99+
74100 return $
75101 Flags
76102 { _root = root
@@ -78,136 +104,35 @@ getFlags pwd =
78104 , _dirs = dirs
79105 , _files = files
80106 , _readme = readme
81− , _outline = outline
82− , _exactDeps = exactDeps
107+ , _project = fmap Summary._project maybeSummary
108+ , _exactDeps = maybe Map.empty (Map.map fst . Summary._depsGraph) maybeSummary
83109 }
84110
85111
86−
87−-- README
88−
89−
90−getReadme :: FilePath -> IO (Maybe String)
112+getReadme :: FilePath -> IO (Maybe Text.Text)
91113getReadme dir =
92114 do let readmePath = dir </> "README.md"
93115 exists <- Dir.doesFileExist readmePath
94116 if exists
95− then Just <$> readFile readmePath
117+ then Just <$> Text.readFile readmePath
96118 else return Nothing
97119
98120
99−
100−-- GET DIRECTORIES
101−
102−
103−getDirs :: FilePath -> [FilePath] -> IO [FilePath]
104−getDirs pwd contents =
105− filterM (Dir.doesDirectoryExist . (pwd </>)) contents
106−
107−
108−
109−-- GET FILES
110−
111−
112−getFiles :: FilePath -> [FilePath] -> IO [File]
113−getFiles pwd contents =
114− do paths <- filterM (Dir.doesFileExist . (pwd </>)) contents
115− mapM (toFile pwd) paths
121+getDirsAndFiles :: FilePath -> IO ([FilePath], [(FilePath, Bool)])
122+getDirsAndFiles pwd =
123+ do contents <- Dir.getDirectoryContents pwd
124+ dirs <- filterM (Dir.doesDirectoryExist . (pwd </>)) contents
125+ filePaths <- filterM (Dir.doesFileExist . (pwd </>)) contents
126+ files <- mapM (inspectFile pwd) filePaths
127+ return (dirs, files)
116128
117129
118−toFile :: FilePath -> FilePath -> IO File
119−toFile pwd path =
130+inspectFile :: FilePath -> FilePath -> IO (FilePath, Bool)
131+inspectFile pwd path =
120132 if takeExtension path == ".elm" then
121− do source <- readFile (pwd </> path)
122− let hasMain = List.isInfixOf "\nmain " source
123− return (File path hasMain)
124− else
125− return (File path False)
126−
133+ do source <- Text.readFile (pwd </> path)
134+ let hasMain = Text.isInfixOf "\nmain " source
135+ return (path, hasMain)
127136
128−
129−-- GET OUTLINE
130−
131−
132−getOutline :: IO (Maybe Outline.Outline)
133−getOutline =
134− do maybeRoot <- Stuff.findRoot
135− case maybeRoot of
136− Nothing ->
137− return Nothing
138−
139− Just root ->
140− do result <- Outline.read root
141− case result of
142− Left _ -> return Nothing
143− Right outline -> return (Just outline)
144−
145−
146−
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−
187−-- ENCODE
188−
189−
190−encode :: Flags -> E.Value
191−encode (Flags root pwd dirs files readme outline exactDeps) =
192− E.object
193− [ "root" ==> encodeFilePath root
194− , "pwd" ==> E.list encodeFilePath pwd
195− , "dirs" ==> E.list encodeFilePath dirs
196− , "files" ==> E.list encodeFile files
197− , "readme" ==> maybe E.null E.chars readme
198− , "outline" ==> maybe E.null Outline.encode outline
199− , "exactDeps" ==> E.dict Pkg.toJsonString V.encode exactDeps
200− ]
201−
202−
203−encodeFilePath :: FilePath -> E.Value
204−encodeFilePath filePath =
205− E.chars filePath
206−
207−
208−encodeFile :: File -> E.Value
209−encodeFile (File path hasMain) =
210− E.object
211− [ "name" ==> encodeFilePath path
212− , "runnable" ==> E.bool hasMain
213− ]
137+ else
138+ return (path, False)
terminal/src/Develop/StaticFiles.hs+7−1
@@ -36,6 +36,7 @@ dict :: HM.HashMap FilePath (BS.ByteString, MimeType)
3636dict =
3737 HM.fromList
3838 [ faviconPath ==> (favicon , "image/x-icon")
39+ , waitingPath ==> (waiting , "image/gif")
3940 , elmPath ==> (elm , "application/javascript")
4041 , cssPath ==> (css , "text/css")
4142 , codeFontPath ==> (codeFont, "font/ttf")
@@ -88,7 +89,7 @@ sansFontPath =
8889
8990elm :: BS.ByteString
9091elm =
91− $(bsToExp =<< runIO Build.buildReactorFrontEnd)
92+ $(bsToExp =<< runIO Build.compile)
9293
9394
9495
@@ -121,3 +122,8 @@ sansFont =
121122favicon :: BS.ByteString
122123favicon =
123124 $(bsToExp =<< runIO (Build.readAsset "favicon.ico"))
125+
126+
127+waiting :: BS.ByteString
128+waiting =
129+ $(bsToExp =<< runIO (Build.readAsset "waiting.gif"))
terminal/src/Develop/StaticFiles/Build.hs+29−46
@@ -1,25 +1,19 @@
11{-# LANGUAGE OverloadedStrings #-}
22module Develop.StaticFiles.Build
33 ( readAsset
4− , buildReactorFrontEnd
4+ , compile
55 )
66 where
77
88
99import qualified Data.ByteString as BS
10−import qualified Data.ByteString.Builder as B
11−import qualified Data.ByteString.Lazy as LBS
12−import qualified Data.NonEmptyList as NE
1310import qualified System.Directory as Dir
1411import System.FilePath ((</>))
1512
16−import qualified BackgroundWriter as BW
17−import qualified Build
18−import qualified Elm.Details as Details
19−import qualified Generate
20−import qualified Reporting
21−import qualified Reporting.Exit as Exit
13+import qualified Elm.Project as Project
14+import qualified Generate.Output as Output
2215import qualified Reporting.Task as Task
16+import qualified Reporting.Progress.Terminal as Terminal
2317
2418
2519
@@ -32,42 +26,31 @@ readAsset path =
3226
3327
3428
35−-- BUILD REACTOR ELM
29+-- COMPILE
3630
3731
38−buildReactorFrontEnd :: IO BS.ByteString
39−buildReactorFrontEnd =
40− BW.withScope $ \scope ->
32+compile :: IO BS.ByteString
33+compile =
4134 Dir.withCurrentDirectory "reactor" $
42− do root <- Dir.getCurrentDirectory
43− runTaskUnsafe $
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
46− javascript <- Task.mapError Exit.ReactorBadGenerate $ Generate.prod root details artifacts
47− return (LBS.toStrict (B.toLazyByteString javascript))
48−
49−
50−paths :: NE.List FilePath
51−paths =
52− NE.List
53− ("src" </> "NotFound.elm")
54− [ "src" </> "Errors.elm"
55− , "src" </> "Index.elm"
56− ]
57−
58−
59−runTaskUnsafe :: Task.Task Exit.Reactor a -> IO a
60−runTaskUnsafe task =
61− do result <- Task.run task
62− case result of
63− Right a ->
64− return a
65−
66− Left exit ->
67− do Exit.toStderr (Exit.reactorToReport exit)
68− error
69− "\n--------------------------------------------------------\
70− \\nError in Develop.StaticFiles.Build.buildReactorFrontEnd\
71− \\nCompile with `elm make` directly to figure it out faster\
72− \\n--------------------------------------------------------\
73− \\n"
35+ do reporter <- Terminal.create
36+ Task.run reporter $
37+ do summary <- Project.getRoot
38+ let jsOutput = Just (Output.JavaScript Nothing tempFileName)
39+ Project.compile Output.Prod Output.Client jsOutput summary rootPaths
40+
41+ result <- BS.readFile tempFileName
42+ seq (BS.length result) (Dir.removeFile tempFileName)
43+ return result
44+
45+
46+tempFileName :: FilePath
47+tempFileName =
48+ "elm.js"
49+
50+
51+rootPaths :: [FilePath]
52+rootPaths =
53+ [ "src" </> "Errors.elm"
54+ , "src" </> "Index.elm"
55+ , "src" </> "NotFound.elm"
56+ ]
terminal/src/Diff.hs+6−348
@@ -1,359 +1,17 @@
11{-# OPTIONS_GHC -Wall #-}
2−{-# LANGUAGE OverloadedStrings #-}
3−module Diff
4− ( Args(..)
5− , run
6− )
7− where
2+module Diff (run) where
83
94
10−import qualified Data.List as List
11−import qualified Data.Map as Map
12−import qualified Data.Maybe as Maybe
13−import qualified Data.Name as Name
14−import qualified Data.NonEmptyList as NE
15−
16−import qualified BackgroundWriter as BW
17−import qualified Build
18−import Deps.Diff (PackageChanges(..), ModuleChanges(..), Changes(..))
19−import qualified Deps.Diff as DD
20−import qualified Deps.Registry as Registry
21−import qualified Elm.Compiler.Type as Type
22−import qualified Elm.Details as Details
23−import qualified Elm.Docs as Docs
24−import qualified Elm.Magnitude as M
25−import qualified Elm.Outline as Outline
26−import qualified Elm.Package as Pkg
27−import qualified Elm.Version as V
28−import qualified Http
29−import qualified Reporting
30−import Reporting.Doc ((<>), (<+>))
31−import qualified Reporting.Doc as D
32−import qualified Reporting.Exit as Exit
33−import qualified Reporting.Exit.Help as Help
34−import qualified Reporting.Render.Type.Localizer as L
5+import qualified Elm.Diff as Diff
356import qualified Reporting.Task as Task
36−import qualified Stuff
7+import qualified Reporting.Progress.Terminal as Terminal
378
389
3910
4011-- RUN
4112
4213
43−data Args
44− = CodeVsLatest
45− | CodeVsExactly V.Version
46− | LocalInquiry V.Version V.Version
47− | GlobalInquiry Pkg.Name V.Version V.Version
48−
49−
50−run :: Args -> () -> IO ()
14+run :: Diff.Args -> () -> IO ()
5115run args () =
52− Reporting.attempt Exit.diffToReport $
53− Task.run $
54− do env <- getEnv
55− diff env args
56−
57−
58−
59−-- ENVIRONMENT
60−
61−
62−data Env =
63− Env
64− { _maybeRoot :: Maybe FilePath
65− , _cache :: Stuff.PackageCache
66− , _manager :: Http.Manager
67− , _registry :: Registry.Registry
68− }
69−
70−
71−getEnv :: Task Env
72−getEnv =
73− do maybeRoot <- Task.io $ Stuff.findRoot
74− cache <- Task.io $ Stuff.getPackageCache
75− manager <- Task.io $ Http.getManager
76− registry <- Task.eio Exit.DiffMustHaveLatestRegistry $ Registry.latest manager cache
77− return (Env maybeRoot cache manager registry)
78−
79−
80−
81−-- DIFF
82−
83−
84−type Task a =
85− Task.Task Exit.Diff a
86−
87−
88−diff :: Env -> Args -> Task ()
89−diff env@(Env _ _ _ registry) args =
90− case args of
91− GlobalInquiry name v1 v2 ->
92− case Registry.getVersions' name registry of
93− Right vsns ->
94− do oldDocs <- getDocs env name vsns (min v1 v2)
95− newDocs <- getDocs env name vsns (max v1 v2)
96− writeDiff oldDocs newDocs
97−
98− Left suggestions ->
99− Task.throw $ Exit.DiffUnknownPackage name suggestions
100−
101− LocalInquiry v1 v2 ->
102− do (name, vsns) <- readOutline env
103− oldDocs <- getDocs env name vsns (min v1 v2)
104− newDocs <- getDocs env name vsns (max v1 v2)
105− writeDiff oldDocs newDocs
106−
107− CodeVsLatest ->
108− do (name, vsns) <- readOutline env
109− oldDocs <- getLatestDocs env name vsns
110− newDocs <- generateDocs env
111− writeDiff oldDocs newDocs
112−
113− CodeVsExactly version ->
114− do (name, vsns) <- readOutline env
115− oldDocs <- getDocs env name vsns version
116− newDocs <- generateDocs env
117− writeDiff oldDocs newDocs
118−
119−
120−
121−-- GET DOCS
122−
123−
124−getDocs :: Env -> Pkg.Name -> Registry.KnownVersions -> V.Version -> Task Docs.Documentation
125−getDocs (Env _ cache manager _) name (Registry.KnownVersions latest previous) version =
126− if latest == version || elem version previous
127− then Task.eio (Exit.DiffDocsProblem version) $ DD.getDocs cache manager name version
128− else Task.throw $ Exit.DiffUnknownVersion name version (latest:previous)
129−
130−
131−getLatestDocs :: Env -> Pkg.Name -> Registry.KnownVersions -> Task Docs.Documentation
132−getLatestDocs (Env _ cache manager _) name (Registry.KnownVersions latest _) =
133− Task.eio (Exit.DiffDocsProblem latest) $ DD.getDocs cache manager name latest
134−
135−
136−
137−-- READ OUTLINE
138−
139−
140−readOutline :: Env -> Task (Pkg.Name, Registry.KnownVersions)
141−readOutline (Env maybeRoot _ _ registry) =
142− case maybeRoot of
143− Nothing ->
144− Task.throw $ Exit.DiffNoOutline
145−
146− Just root ->
147− do result <- Task.io $ Outline.read root
148− case result of
149− Left err ->
150− Task.throw $ Exit.DiffBadOutline err
151−
152− Right outline ->
153− case outline of
154− Outline.App _ ->
155− Task.throw $ Exit.DiffApplication
156−
157− Outline.Pkg (Outline.PkgOutline pkg _ _ _ _ _ _ _) ->
158− case Registry.getVersions pkg registry of
159− Just vsns -> return (pkg, vsns)
160− Nothing -> Task.throw Exit.DiffUnpublished
161−
162−
163−
164−-- GENERATE DOCS
165−
166−
167−generateDocs :: Env -> Task Docs.Documentation
168−generateDocs (Env maybeRoot _ _ _) =
169− case maybeRoot of
170− Nothing ->
171− Task.throw $ Exit.DiffNoOutline
172−
173− Just root ->
174− do details <-
175− Task.eio Exit.DiffBadDetails $ BW.withScope $ \scope ->
176− Details.load Reporting.silent scope root
177−
178− case Details._outline details of
179− Details.ValidApp _ ->
180− Task.throw $ Exit.DiffApplication
181−
182− Details.ValidPkg _ exposed _ ->
183− case exposed of
184− [] ->
185− Task.throw $ Exit.DiffNoExposed
186−
187− e:es ->
188− Task.eio Exit.DiffBadBuild $
189− Build.fromExposed Reporting.silent root details Build.KeepDocs (NE.List e es)
190−
191−
192−
193−-- WRITE DIFF
194−
195−
196−writeDiff :: Docs.Documentation -> Docs.Documentation -> Task ()
197−writeDiff oldDocs newDocs =
198− let
199− changes = DD.diff oldDocs newDocs
200− localizer = L.fromNames (Map.union oldDocs newDocs)
201− in
202− Task.io $ Help.toStdout $ toDoc localizer changes <> "\n"
203−
204−
205−
206−-- TO DOC
207−
208−
209−toDoc :: L.Localizer -> PackageChanges -> D.Doc
210−toDoc localizer changes@(PackageChanges added changed removed) =
211− if null added && Map.null changed && null removed then
212− "No API changes detected, so this is a" <+> D.green "PATCH" <+> "change."
213− else
214− let
215− magDoc =
216− D.fromChars (M.toChars (DD.toMagnitude changes))
217−
218− header =
219− "This is a" <+> D.green magDoc <+> "change."
220−
221− addedChunk =
222− if null added then [] else
223− [ Chunk "ADDED MODULES" M.MINOR $
224− D.vcat $ map D.fromName added
225− ]
226−
227− removedChunk =
228− if null removed then [] else
229− [ Chunk "REMOVED MODULES" M.MAJOR $
230− D.vcat $ map D.fromName removed
231− ]
232−
233− chunks =
234− addedChunk ++ removedChunk ++ map (changesToChunk localizer) (Map.toList changed)
235− in
236− D.vcat (header : "" : map chunkToDoc chunks)
237−
238−
239−data Chunk =
240− Chunk
241− { _title :: String
242− , _magnitude :: M.Magnitude
243− , _details :: D.Doc
244− }
245−
246−
247−chunkToDoc :: Chunk -> D.Doc
248−chunkToDoc (Chunk title magnitude details) =
249− let
250− header =
251− "----" <+> D.fromChars title <+> "-" <+> D.fromChars (M.toChars magnitude) <+> "----"
252− in
253− D.vcat
254− [ D.dullcyan header
255− , ""
256− , D.indent 4 details
257− , ""
258− , ""
259− ]
260−
261−
262−changesToChunk :: L.Localizer -> (Name.Name, ModuleChanges) -> Chunk
263−changesToChunk localizer (name, changes@(ModuleChanges unions aliases values binops)) =
264− let
265− magnitude =
266− DD.moduleChangeMagnitude changes
267−
268− (unionAdd, unionChange, unionRemove) =
269− changesToDocTriple (unionToDoc localizer) unions
270−
271− (aliasAdd, aliasChange, aliasRemove) =
272− changesToDocTriple (aliasToDoc localizer) aliases
273−
274− (valueAdd, valueChange, valueRemove) =
275− changesToDocTriple (valueToDoc localizer) values
276−
277− (binopAdd, binopChange, binopRemove) =
278− changesToDocTriple (binopToDoc localizer) binops
279− in
280− Chunk (Name.toChars name) magnitude $
281− D.vcat $ List.intersperse "" $ Maybe.catMaybes $
282− [ changesToDoc "Added" unionAdd aliasAdd valueAdd binopAdd
283− , changesToDoc "Removed" unionRemove aliasRemove valueRemove binopRemove
284− , changesToDoc "Changed" unionChange aliasChange valueChange binopChange
285− ]
286−
287−
288−changesToDocTriple :: (k -> v -> D.Doc) -> Changes k v -> ([D.Doc], [D.Doc], [D.Doc])
289−changesToDocTriple entryToDoc (Changes added changed removed) =
290− let
291− indented (name, value) =
292− D.indent 4 (entryToDoc name value)
293−
294− diffed (name, (oldValue, newValue)) =
295− D.vcat
296− [ " - " <> entryToDoc name oldValue
297− , " + " <> entryToDoc name newValue
298− , ""
299− ]
300− in
301− ( map indented (Map.toList added)
302− , map diffed (Map.toList changed)
303− , map indented (Map.toList removed)
304− )
305−
306−
307−changesToDoc :: String -> [D.Doc] -> [D.Doc] -> [D.Doc] -> [D.Doc] -> Maybe D.Doc
308−changesToDoc categoryName unions aliases values binops =
309− if null unions && null aliases && null values && null binops then
310− Nothing
311−
312− else
313− Just $ D.vcat $
314− D.fromChars categoryName <> ":" : unions ++ aliases ++ binops ++ values
315−
316−
317−unionToDoc :: L.Localizer -> Name.Name -> Docs.Union -> D.Doc
318−unionToDoc localizer name (Docs.Union _ tvars ctors) =
319− let
320− setup =
321− "type" <+> D.fromName name <+> D.hsep (map D.fromName tvars)
322−
323− ctorDoc (ctor, tipes) =
324− typeDoc localizer (Type.Type ctor tipes)
325− in
326− D.hang 4 (D.sep (setup : zipWith (<+>) ("=" : repeat "|") (map ctorDoc ctors)))
327−
328−
329−aliasToDoc :: L.Localizer -> Name.Name -> Docs.Alias -> D.Doc
330−aliasToDoc localizer name (Docs.Alias _ tvars tipe) =
331− let
332− declaration =
333− "type" <+> "alias" <+> D.hsep (map D.fromName (name:tvars)) <+> "="
334− in
335− D.hang 4 (D.sep [ declaration, typeDoc localizer tipe ])
336−
337−
338−valueToDoc :: L.Localizer -> Name.Name -> Docs.Value -> D.Doc
339−valueToDoc localizer name (Docs.Value _ tipe) =
340− D.hang 4 $ D.sep [ D.fromName name <+> ":", typeDoc localizer tipe ]
341−
342−
343−binopToDoc :: L.Localizer -> Name.Name -> Docs.Binop -> D.Doc
344−binopToDoc localizer name (Docs.Binop _ tipe associativity (Docs.Precedence n)) =
345− "(" <> D.fromName name <> ")" <+> ":" <+> typeDoc localizer tipe <> D.black details
346− where
347− details =
348− " (" <> D.fromName assoc <> "/" <> D.fromInt n <> ")"
349−
350− assoc =
351− case associativity of
352− Docs.Left -> "left"
353− Docs.Non -> "non"
354− Docs.Right -> "right"
355−
356−
357−typeDoc :: L.Localizer -> Type.Type -> D.Doc
358−typeDoc localizer tipe =
359− Type.toDoc localizer Type.None tipe
16+ do reporter <- Terminal.create
17+ Task.run reporter $ Diff.diff args
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 (Outline.RelativeSrcDir "src") []) directs indirects Map.empty Map.empty
93+ Outline.AppOutline V.compiler (NE.List "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+31−16
@@ -10,7 +10,6 @@ import Data.Map ((!))
1010import qualified Data.Map as Map
1111import qualified Data.Map.Merge.Strict as Map
1212
13−import qualified BackgroundWriter as BW
1413import qualified Deps.Solver as Solver
1514import qualified Deps.Registry as Registry
1615import qualified Elm.Constraint as C
@@ -41,7 +40,7 @@ run args () =
4140 do maybeRoot <- Stuff.findRoot
4241 case maybeRoot of
4342 Nothing ->
44− return (Left Exit.InstallNoOutline)
43+ return (Left Exit.InstallNoProject)
4544
4645 Just root ->
4746 case args of
@@ -51,8 +50,8 @@ run args () =
5150
5251 Install pkg ->
5352 Task.run $
54− do env <- Task.eio Exit.InstallBadRegistry $ Solver.initEnv
55− oldOutline <- Task.eio Exit.InstallBadOutline $ Outline.read root
53+ do env <- getEnv
54+ oldOutline <- getOutline root
5655 case oldOutline of
5756 Outline.App outline ->
5857 do changes <- makeAppPlan env pkg outline
@@ -64,6 +63,23 @@ run args () =
6463
6564
6665
66+getEnv :: Task Solver.Env
67+getEnv =
68+ do eitherEnv <- Task.io Solver.initEnv
69+ case eitherEnv of
70+ Right env -> return env
71+ Left problem -> Task.throw (error "TODO getEnv" problem)
72+
73+
74+getOutline :: FilePath -> Task Outline.Outline
75+getOutline root =
76+ do eitherOutline <- Task.io (Outline.read root)
77+ case eitherOutline of
78+ Right outline -> return outline
79+ Left exit -> Task.throw (error "TODO getOutline" exit)
80+
81+
82+
6783-- ATTEMPT CHANGES
6884
6985
@@ -124,13 +140,12 @@ attemptChanges root env oldOutline toChars changes =
124140
125141attemptChangesHelp :: FilePath -> Solver.Env -> Outline.Outline -> Outline.Outline -> D.Doc -> Task ()
126142attemptChangesHelp root env oldOutline newOutline question =
127− Task.eio Exit.InstallBadDetails $
128− BW.withScope $ \scope ->
143+ Task.eio Exit.InstallHasBadDetails $
129144 do approved <- Reporting.ask question
130145 if approved
131146 then
132147 do Outline.write root newOutline
133− result <- Details.verifyInstall scope root env newOutline
148+ result <- Details.verifyInstall root env newOutline
134149 case result of
135150 Left exit ->
136151 do Outline.write root oldOutline
@@ -188,8 +203,8 @@ makeAppPlan (Solver.Env cache _ connection registry) pkg outline@(Outline.AppOut
188203 case Registry.getVersions' pkg registry of
189204 Left suggestions ->
190205 case connection of
191− Solver.Online _ -> Task.throw (Exit.InstallUnknownPackageOnline pkg suggestions)
192− Solver.Offline -> Task.throw (Exit.InstallUnknownPackageOffline pkg suggestions)
206+ Solver.Online _ -> Task.throw (Exit.InstallUnknownPackageOnline suggestions)
207+ Solver.Offline -> Task.throw (Exit.InstallUnknownPackageOffline suggestions)
193208
194209 Right _ ->
195210 do result <- Task.io $ Solver.addToApp cache connection registry pkg outline
@@ -198,10 +213,10 @@ makeAppPlan (Solver.Env cache _ connection registry) pkg outline@(Outline.AppOut
198213 return (Changes (detectChanges old new) (Outline.App app))
199214
200215 Solver.NoSolution ->
201− Task.throw (Exit.InstallNoOnlineAppSolution pkg)
216+ Task.throw Exit.InstallNoOnlineSolution
202217
203218 Solver.NoOfflineSolution ->
204− Task.throw (Exit.InstallNoOfflineAppSolution pkg)
219+ Task.throw Exit.InstallNoOfflineSolution
205220
206221 Solver.Err exit ->
207222 Task.throw (Exit.InstallHadSolverTrouble exit)
@@ -230,8 +245,8 @@ makePkgPlan (Solver.Env cache _ connection registry) pkg outline@(Outline.PkgOut
230245 case Registry.getVersions' pkg registry of
231246 Left suggestions ->
232247 case connection of
233− Solver.Online _ -> Task.throw (Exit.InstallUnknownPackageOnline pkg suggestions)
234− Solver.Offline -> Task.throw (Exit.InstallUnknownPackageOffline pkg suggestions)
248+ Solver.Online _ -> Task.throw (Exit.InstallUnknownPackageOnline suggestions)
249+ Solver.Offline -> Task.throw (Exit.InstallUnknownPackageOffline suggestions)
235250
236251 Right (Registry.KnownVersions _ _) ->
237252 do let old = Map.union deps test
@@ -254,10 +269,10 @@ makePkgPlan (Solver.Env cache _ connection registry) pkg outline@(Outline.PkgOut
254269 }
255270
256271 Solver.NoSolution ->
257− Task.throw (Exit.InstallNoOnlinePkgSolution pkg)
272+ Task.throw Exit.InstallNoOnlineSolution
258273
259274 Solver.NoOfflineSolution ->
260− Task.throw (Exit.InstallNoOfflinePkgSolution pkg)
275+ Task.throw Exit.InstallNoOfflineSolution
261276
262277 Solver.Err exit ->
263278 Task.throw (Exit.InstallHadSolverTrouble exit)
@@ -385,7 +400,7 @@ viewRemove toChars (Widths nameWidth leftWidth _) name old =
385400
386401viewName :: Int -> Pkg.Name -> D.Doc
387402viewName width name =
388− D.fill (width + 3) (D.fromPackage name)
403+ D.fill (width + 3) (D.fromUtf8 (Pkg.toString name))
389404
390405
391406pad :: Int -> String -> D.Doc
terminal/src/Main.hs+36−32

This diff is too big to show here.

terminal/src/Make.hs+268−113

This diff is too big to show here.

terminal/src/Publish.hs+8−529

This diff is too big to show here.

terminal/src/Repl.hs+197−522

This diff is too big to show here.

terminal/impl/Terminal.hs → terminal/src/Terminal/Args.hsrenamed+27−33

This diff is too big to show here.

terminal/impl/Terminal/Chomp.hs → terminal/src/Terminal/Args/Chomp.hsrenamed+5−4

This diff is too big to show here.

terminal/impl/Terminal/Error.hs → terminal/src/Terminal/Args/Error.hsrenamed+18−28

This diff is too big to show here.

terminal/impl/Terminal/Helpers.hs → terminal/src/Terminal/Args/Helpers.hsrenamed+19−41

This diff is too big to show here.

terminal/impl/Terminal/Internal.hs → terminal/src/Terminal/Args/Internal.hsrenamed+8−8

This diff is too big to show here.

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

The content is the same.

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

The content is the same.

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

The content is the same.

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

The content is the same.

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

The content is the same.

worker/elm.cabal+3−25

This diff is too big to show here.

worker/elm.jsondeleted−26

This diff is too big to show here.

worker/nginx.confdeleted−22

This diff is too big to show here.

worker/outlines/compile/elm.jsondeleted−32

This diff is too big to show here.

worker/outlines/repl/elm.jsondeleted−19

This diff is too big to show here.

worker/src/Artifacts.hsdeleted−155

This diff is too big to show here.

worker/src/Cors.hsdeleted−48

This diff is too big to show here.

worker/src/Endpoint/Compile.hsdeleted−323

This diff is too big to show here.

worker/src/Endpoint/Quotes.hsdeleted−114

This diff is too big to show here.

worker/src/Endpoint/Repl.hsdeleted−244

This diff is too big to show here.

worker/src/Errors.elmdeleted−217

This diff is too big to show here.

worker/src/Main.hs+241−36

This diff is too big to show here.