summaryrefslogtreecommitdiff
path: root/Main.hs
blob: 0cdba7a9f880df5b25b83b424323b9b111a9c988 (plain) (blame)
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
module Main where

import Data.List (isPrefixOf)
import Control.Category ((>>>))
import Control.Monad (forM_, when)
import Control.Monad.Identity (Identity)
import Data.Aeson (ToJSON (..), Value (..), encode)
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.Text.IO as TextIO
import Data.Typeable
import GHC.IO.Exception (ExitCode (ExitFailure, ExitSuccess))
import Language.Fiddle.Ast
import Language.Fiddle.Compiler
import Language.Fiddle.Compiler.Backend
import Language.Fiddle.Compiler.Backend.C
import Language.Fiddle.Compiler.ConsistencyCheck
import Language.Fiddle.Compiler.Expansion
import Language.Fiddle.Compiler.ImportResolution
import Language.Fiddle.Compiler.Qualification
import Language.Fiddle.Compiler.Stage0
import Language.Fiddle.GenericTree
import Language.Fiddle.Types (Commented (unCommented), SourceSpan)
import Options.Applicative
import Options.Applicative.Types (ParserHelp (..))
import qualified System.Environment as System
import System.Exit (exitWith)
import System.IO (hPutStrLn, stderr)

newtype IntermediateAst = IntermediateAst (GenericSyntaxTree Identity (Maybe Value))
  deriving (Typeable)

-- | The total compilation pipeline.
compilationPipeline ::
  ( FilePath ->
    IO
      ( [Diagnostic],
        [Artifact],
        Maybe
          ( FiddleUnit Parsed Identity (Commented SourceSpan)
          )
      )
  ) ->
  ( FiddleUnit Parsed Identity (Commented SourceSpan) ->
    IO
      ( [Diagnostic],
        [Artifact],
        Maybe
          (FiddleUnit Checked Identity (Commented SourceSpan))
      )
  ) ->
  CompilationPhase Parsed Checked
compilationPipeline parse compile =
  (dumpPhase "parsed" >>> importResolutionPhase parse compile)
    >>> (dumpPhase "imports-resolved" >>> expansionPhase)
    >>> (dumpPhase "expanded" >>> qualificationPhase)
    >>> (dumpPhase "qualified" >>> consistencyCheckPhase)
    >>> dumpPhase "checked"

-- | Compilation phase that just emits an ast artifact.
dumpPhase ::
  forall stage.
  ( Typeable stage,
    Typeable (StageAnnotation stage),
    ToGenericSyntaxTree (FiddleUnit stage),
    StageAnnotation stage ~ Commented SourceSpan
  ) =>
  String ->
  CompilationPhase stage stage
dumpPhase stageName =
  CompilationPhase
    ( switch
        ( long ("dump-" ++ stageName)
            <> help
              ( "Dump the "
                  ++ stageName
                  ++ " intermediate ast as parseable JSON."
              )
        )
    )
    (\_ _ -> return ([], Just ()))
    ( \enable () ast -> do
        when enable $
          emitArtifact $
            Artifact $
              IntermediateAst (toGenericSyntaxTree (fmap (Just . toJSON) ast))
        return ast
    )

-- | Global flags for the compiler.
data GlobalFlags = GlobalFlags
  { flagsInputFile :: String,
    flagsDiagnosticFormat :: DiagnosticFormat,
    flagsBackend :: String
  }

-- | Parse global flags from command line arguments.
parseGlobalFlags :: Parser GlobalFlags
parseGlobalFlags =
  GlobalFlags
    <$> argument str (metavar "INPUT" <> help "Input file")
    <*> ( (\b -> if b then jsonDiagnosticFormat else coloredFormat)
            <$> switch
              ( long "diagnostics-as-json"
                  <> help "Dump diagnostics in JSON format."
              )
        )
    <*> strOption
      ( long "language"
          <> short 'L'
          <> help "The output language"
          <> metavar "LANGUAGE"
      )

-- | Parse the input file into the initial AST stages.
doParse :: String -> IO ([Diagnostic], [Artifact], Maybe (TreeType FiddleUnit Parsed))
doParse filePath = do
  text <- TextIO.readFile filePath
  return $ compile_ $ toStage0 filePath text >>= toStage1

-- | Run the compilation pipeline with the given command-line arguments and AST.
runCompilationPipeline ::
  [String] ->
  TreeType FiddleUnit Parsed ->
  IO ([Diagnostic], [Artifact], Maybe (TreeType FiddleUnit Checked))
runCompilationPipeline argv tree =
  case fromArgs argv of
    Success (_, pipelineAction, _) -> pipelineAction tree
    _ ->
      return
        ( [Diagnostic Error "Internal parsing failure (this is a bug)." (unCommented $ annot tree)],
          [],
          Nothing
        )

-- | Parse command-line arguments into global flags and a compilation action.
fromArgs ::
  [String] ->
  ParserResult
    ( GlobalFlags,
      TreeType FiddleUnit Parsed ->
      IO ([Diagnostic], [Artifact], Maybe (TreeType FiddleUnit Checked)),
      FiddleUnit Checked Identity (Commented SourceSpan) -> IO TranspileResult
    )
fromArgs argv =
  case selectBackend argv of
    Just backend -> do
      execParserPure
        defaultPrefs
        (parserInfo backend)
        argv
    Nothing ->
      Failure $
        parserFailure
          defaultPrefs
          (parserInfo nullBackend)
          (ErrorMsg "Unknown backend")
          mempty
  where
    selectBackend :: [String] -> Maybe Backend
    selectBackend argv = selectBackendEq argv <|> selectBackendSpace argv

    selectBackendEq argv =
       case filter ("--language="`isPrefixOf`) argv of
          [backend] -> case break (=='=') backend of
             (_, '=' : s) -> selectBackendFromString s
             _ -> Nothing
          _ -> Nothing

    selectBackendSpace argv =
      case break (\s -> s == "--language" || "-L" `isPrefixOf` s) argv of
        (_, "--language" : s : _) -> selectBackendFromString s
        (_, "-L" : s : _) -> selectBackendFromString s
        (_, ('-' : 'L' : s) : _) -> selectBackendFromString s
        _ -> Nothing

    selectBackendFromString "c" = Just cBackend
    selectBackendFromString "null" = Just nullBackend
    selectBackendFromString _ = Nothing
         

    parserInfo backend =
      info
        ( (,,)
            <$> parseGlobalFlags
            <*> execCompilationPipelineWithCmdline
              (compilationPipeline doParse (runCompilationPipeline argv))
            <*> backendToParserFunction backend
              <**> helper
        )
        ( fullDesc
            <> progDesc "Compile Fiddle Files"
            <> header "fiddlec - A compiler for Fiddle files"
        )

main :: IO ()
main = do
  argv <- System.getArgs
  (globalFlags, compilationAction, backendAction) <- parseCommandLineArgs argv
  let filePath = flagsInputFile globalFlags

  maybeParsedAst <- parseInputFile filePath
  case maybeParsedAst of
    (priorDiags, _, Just ast) -> do
      ((priorDiags ++) -> diags, artifacts, ma) <- compilationAction ast
      exitCode <- processCompilationResult artifacts ma backendAction
      printDiagnostics (flagsDiagnosticFormat globalFlags) diags
      exitWith exitCode
    (diags, _, _) ->
      handleParsingFailure (flagsDiagnosticFormat globalFlags) diags

-- | Parse command-line arguments, exiting on failure.
parseCommandLineArgs ::
  [String] ->
  IO
    ( GlobalFlags,
      TreeType FiddleUnit Parsed ->
      IO ([Diagnostic], [Artifact], Maybe (TreeType FiddleUnit Checked)),
      FiddleUnit Checked Identity (Commented SourceSpan) -> IO TranspileResult
    )
parseCommandLineArgs argv = handleParseResult (fromArgs argv)

-- | Parse the input file into the initial AST.
parseInputFile :: String -> IO ([Diagnostic], [Artifact], Maybe (TreeType FiddleUnit Parsed))
parseInputFile filePath = do
  text <- TextIO.readFile filePath
  return $ compile_ $ toStage0 filePath text >>= toStage1

-- | Process the compilation result, printing the output and returning the exit code.
processCompilationResult ::
  [Artifact] -> Maybe (TreeType FiddleUnit Checked) -> 
   (TreeType FiddleUnit Checked -> IO TranspileResult)
  -> IO ExitCode
processCompilationResult artifacts ma backendFunction = do
  forM_ artifacts $ \case
    Artifact (cast -> (Just (IntermediateAst ast))) ->
      putStrLn $
        BL.unpack $
          encode $
            alterGenericSyntaxTree cleanupIdentifiers ast
    Artifact _ -> return ()

  case ma of
    Just ast -> do
      processTranspileResult =<< backendFunction ast
      return ExitSuccess
    Nothing -> do
      return (ExitFailure 1)

-- | Handle parsing failures by printing diagnostics and exiting with an error code.
handleParsingFailure :: DiagnosticFormat -> [Diagnostic] -> IO ()
handleParsingFailure fmt diags = do
  printDiagnostics fmt diags
  exitWith (ExitFailure 1)

-- | Clean up identifiers in the generic syntax tree for serialization.
cleanupIdentifiers :: GenericSyntaxTree Identity a -> Maybe (GenericSyntaxTree Identity a)
cleanupIdentifiers (SyntaxTreeObject _ _ _ tr)
  | Just (Identifier n _) <- castT tr =
      Just $ SyntaxTreeValue (String n)
  where
    castT :: (Typeable t, Typeable f, Typeable a, Typeable t') => t f a -> Maybe (t' f a)
    castT = cast
cleanupIdentifiers _ = Nothing