summaryrefslogtreecommitdiff
path: root/source/Felix/Workspace.hs
blob: b9034c5d7cbcd5d2c9ae0f8633782291a9d16a2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
{-# LANGUAGE NoImplicitPrelude #-}

-- | Stable source-mount policy and authority-free workspace preparation.
module Felix.Workspace
    ( WorkspaceEnvironment
    , prepareDefaultWorkspaceEnvironment
    , workspaceSourceMounts
    , workspaceHtmlMountPrefixes
    , workspaceRendererSearchRoots
    , prepareWorkspaceRoot
    , prepareSourceGraph
    , prepareDefaultSourceGraph
    , AuthorityFreeParseError(..)
    , renderAuthorityFreeParseError
    , parseWorkspace
    , parse
    , tokenize
    , scan
    , simpleStream
    , TokStream
    , ParseException(..)
    , builtins
    ) where

import Base
import Felix.Parse (ParseException(..), ParseWorkspaceError(..))
import Felix.Parse qualified as Parse
import Felix.Prelude qualified as Prelude
import Felix.Source
import Felix.Source.Graph (ResolvedSourceGraph)
import Felix.Source.Graph qualified as SourceGraph
import Felix.Report.Location
import Felix.Syntax.Abstract qualified as Raw
import Felix.Syntax.Adapt (ScannedLexicalItem, scanChunk)
import Felix.Syntax.Lexicon (builtins)
import Felix.Syntax.Token

import Control.Exception qualified as Exception
import Data.Bifunctor (first)
import System.Directory (getCurrentDirectory)
import System.Environment (lookupEnv)
import System.FilePath.Posix ((</>), isAbsolute)
import Text.Megaparsec (errorBundlePretty)

data WorkspaceEnvironment = WorkspaceEnvironment
    !SourceMounts
    ![(SourceMountId, [Text])]
    ![FilePath]

workspaceSourceMounts :: WorkspaceEnvironment -> SourceMounts
workspaceSourceMounts (WorkspaceEnvironment mounts _prefixes _rendererRoots) =
    mounts

workspaceHtmlMountPrefixes
    :: WorkspaceEnvironment
    -> [(SourceMountId, [Text])]
workspaceHtmlMountPrefixes
        (WorkspaceEnvironment _mounts prefixes _rendererRoots) =
    prefixes

workspaceRendererSearchRoots :: WorkspaceEnvironment -> [FilePath]
workspaceRendererSearchRoots
        (WorkspaceEnvironment _mounts _prefixes rendererRoots) =
    rendererRoots

prepareDefaultWorkspaceEnvironment
    :: IO (Either ParseWorkspaceError WorkspaceEnvironment)
prepareDefaultWorkspaceEnvironment = do
    currentDir <- getCurrentDirectory
    configuredLibrary <- lookupEnv "NAPROCHE_LIB"
    let libraryDir = fromMaybe (currentDir </> "library") configuredLibrary
        debugDir = currentDir </> "debug"
        rendererRoots = [currentDir, libraryDir, debugDir]
        prefixes =
            [ (sourceMountId "project", [])
            , (sourceMountId "library", ["library"])
            , (sourceMountId "debug", ["debug"])
            ]
    fmap (first SourceWorkspaceError)
        (fmap
            (\mounts ->
                WorkspaceEnvironment mounts prefixes rendererRoots)
            <$> prepareSourceMounts
                [ (sourceMountId "project", currentDir)
                , (sourceMountId "library", libraryDir)
                , (sourceMountId "debug", debugDir)
                ])

prepareWorkspaceRoot
    :: WorkspaceEnvironment
    -> FilePath
    -> IO (Either ParseWorkspaceError RootRequest)
prepareWorkspaceRoot _environment file =
    first SourceWorkspaceError <$> classifyRootRequest file

prepareSourceGraph
    :: WorkspaceEnvironment
    -> RootRequest
    -> IO (Either ParseWorkspaceError ResolvedSourceGraph)
prepareSourceGraph environment request =
    first SourceWorkspaceError
        <$> SourceGraph.buildResolvedSourceGraph
            (workspaceSourceMounts environment)
            request

prepareDefaultSourceGraph
    :: FilePath
    -> IO (Either ParseWorkspaceError ResolvedSourceGraph)
prepareDefaultSourceGraph file = do
    preparedEnvironment <- prepareDefaultWorkspaceEnvironment
    case preparedEnvironment of
        Left failure -> pure (Left failure)
        Right environment -> do
            preparedRoot <- prepareWorkspaceRoot environment file
            case preparedRoot of
                Left failure -> pure (Left failure)
                Right request -> prepareSourceGraph environment request

classifyRootRequest :: FilePath -> IO (Either SourceError RootRequest)
classifyRootRequest file
    | isAbsolute file = existingRoot file
    | otherwise = pure (searchedRoot file)

data AuthorityFreeParseError
    = AuthorityFreePreludeLoadFailed !Prelude.PreludeLoadError
    | AuthorityFreePreludeParseFailed !Prelude.PreludeParseError
    | AuthorityFreeWorkspaceFailed !ParseWorkspaceError
    deriving (Show)

instance Exception.Exception AuthorityFreeParseError

renderAuthorityFreeParseError :: AuthorityFreeParseError -> Text
renderAuthorityFreeParseError = \case
    AuthorityFreePreludeLoadFailed failure ->
        "packaged final prelude loading failed: "
            <> Prelude.renderPreludeLoadError failure
    AuthorityFreePreludeParseFailed failure ->
        "packaged final prelude parsing failed: "
            <> Prelude.renderPreludeParseError failure
    AuthorityFreeWorkspaceFailed failure ->
        Parse.renderParseWorkspaceError failure

parseWorkspace
    :: FilePath
    -> IO (Either AuthorityFreeParseError [Raw.Block])
parseWorkspace file =
    fmap Parse.importedBeforeImporterBlocks
        <$> parseDefaultWorkspaceWithPrelude file

parse :: FilePath -> IO [Raw.Block]
parse file = parseWorkspace file >>= either Exception.throwIO pure

parseDefaultWorkspaceWithPrelude
    :: FilePath
    -> IO (Either AuthorityFreeParseError Parse.ParsedSourceWorkspace)
parseDefaultWorkspaceWithPrelude file =
    Prelude.loadReservedPreludeSourceInput >>= \case
        Left failure ->
            pure (Left (AuthorityFreePreludeLoadFailed failure))
        Right source ->
            Prelude.parseReservedPreludeSource source >>= \case
                Left failure ->
                    pure (Left (AuthorityFreePreludeParseFailed failure))
                Right prelude -> do
                    preparedEnvironment <- prepareDefaultWorkspaceEnvironment
                    case preparedEnvironment of
                        Left failure ->
                            pure (Left (AuthorityFreeWorkspaceFailed failure))
                        Right environment -> do
                            preparedRoot <- prepareWorkspaceRoot environment file
                            case preparedRoot of
                                Left failure ->
                                    pure
                                        (Left
                                            (AuthorityFreeWorkspaceFailed
                                                failure))
                                Right request -> do
                                    let syntax =
                                            Parse.identifiedParsedModuleSyntaxInterface
                                                (Prelude.reservedParsedPreludeModule
                                                    prelude)
                                    first AuthorityFreeWorkspaceFailed
                                        <$> Parse.parseSourceWorkspaceWithSyntaxInputsAndGraphValidation
                                            (workspaceSourceMounts environment)
                                            request
                                            (const [syntax])
                                            (Prelude.rejectOrdinaryPreludeSourceGraph
                                                source)

lexFile :: FilePath -> IO (Text, [[Located Token]])
lexFile file = do
    environment <- prepareDefaultWorkspaceEnvironment
        >>= either throwWorkspaceError pure
    request <- prepareWorkspaceRoot environment file
        >>= either throwWorkspaceError pure
    loaded <- resolveAndLoadRoot (workspaceSourceMounts environment) request
        >>= either Exception.throwIO pure
    let source = loadedSource loaded
        raw = loadedText loaded
        locationPath = resolvedSourceLocationPath source
        canonicalPath =
            canonicalPathFilePath (resolvedSourceCanonicalPath source)
    registration <- registerFilePathWithDisplay canonicalPath locationPath
    fileId <- either
        (Exception.throwIO . SourceLocationRegistrationFailed source)
        pure
        registration
    case runLexer fileId locationPath raw of
        Left tokenError ->
            Exception.throwIO (TokenError (errorBundlePretty tokenError))
        Right (_imports, chunks) ->
            pure (raw, chunks)

tokenize :: FilePath -> IO TokStream
tokenize file = do
    (raw, chunks) <- lexFile file
    pure (TokStream raw chunks)

scan :: FilePath -> IO [ScannedLexicalItem]
scan input = do
    tokenStream <- tokenize input
    concatMap (fmap unLocated)
        <$> traverse
            (either
                (Exception.throwIO . LexicalScanFailure)
                pure
                . scanChunk)
            (unTokStream tokenStream)

simpleStream :: TokStream -> [[Token]]
simpleStream TokStream{unTokStream = chunks} =
    [unLocated <$> chunk | chunk <- chunks]

throwWorkspaceError :: ParseWorkspaceError -> IO value
throwWorkspaceError = \case
    SourceWorkspaceError err -> Exception.throwIO err
    err@SourceLexiconCollision{} -> Exception.throwIO err
    err@SourceSyntaxPragmaError{} -> Exception.throwIO err
    err@SourceSyntaxDeclarationError{} -> Exception.throwIO err
    err@SourceSyntaxMaterializationError{} -> Exception.throwIO err
    err@SourceParsedModuleKeyError{} -> Exception.throwIO err
    SourceParseError _source err -> Exception.throwIO err