0 | ||| The `Javascript` code generator.
 1 | module Compiler.ES.Javascript
 2 |
 3 | import Compiler.ES.Codegen
 4 |
 5 | import Compiler.Common
 6 |
 7 | import Libraries.Utils.Path
 8 |
 9 | import Idris.Syntax
10 |
11 | import Data.String
12 |
13 | %default covering
14 |
15 | ||| Compile a TT expression to Javascript
16 | compileToJS :
17 |   Ref Ctxt Defs ->
18 |   Ref Syn SyntaxInfo ->
19 |   ClosedTerm -> Core String
20 | compileToJS c s tm = compileToES c s Javascript tm ["browser", "javascript"]
21 |
22 | htmlHeader : String
23 | htmlHeader = """
24 |   <html>
25 |     <head>
26 |       <meta charset='utf-8'>
27 |     </head>
28 |     <body>
29 |       <script type='text/javascript'>
30 |
31 |   """
32 |
33 | htmlFooter : String
34 | htmlFooter = """
35 |
36 |       </script>
37 |     </body>
38 |   </html>
39 |   """
40 |
41 | addHeaderAndFooter : String -> String -> String
42 | addHeaderAndFooter outfile es =
43 |   case toLower <$>  extension outfile of
44 |     Just "html" => htmlHeader ++ es ++ htmlFooter
45 |     _ => es
46 |
47 | ||| Javascript implementation of the `compileExpr` interface.
48 | compileExpr :
49 |   Ref Ctxt Defs ->
50 |   Ref Syn SyntaxInfo ->
51 |   (tmpDir : String) ->
52 |   (outputDir : String) ->
53 |   ClosedTerm ->
54 |   (outfile : String) ->
55 |   Core (Maybe String)
56 | compileExpr c s tmpDir outputDir tm outfile =
57 |   do es <- compileToJS c s tm
58 |      let res = addHeaderAndFooter outfile es
59 |      let out = outputDir </> outfile
60 |      Core.writeFile out res
61 |      pure (Just out)
62 |
63 | ||| Node implementation of the `executeExpr` interface.
64 | executeExpr :
65 |   Ref Ctxt Defs ->
66 |   Ref Syn SyntaxInfo ->
67 |   (tmpDir : String) -> ClosedTerm -> Core ()
68 | executeExpr c s tmpDir tm =
69 |   throw $ InternalError "Javascript backend is only able to compile, use Node instead"
70 |
71 | ||| Codegen wrapper for Javascript implementation.
72 | export
73 | codegenJavascript : Codegen
74 | codegenJavascript = MkCG compileExpr executeExpr Nothing Nothing
75 |