@@ -10,59 +10,66 @@ import qualified Data.Set as Set
1010import Language.ECMAScript3.PrettyPrint
1111import Language.ECMAScript3.Syntax
1212
13−import Generate.JavaScript.Helpers
13+import Generate.JavaScript.Helpers as Help
1414import qualified Generate.Cases as Case
1515import qualified Generate.JavaScript.Ports as Port
16+import qualified Generate.JavaScript.Variable as Var
1617import qualified Generate.Markdown as MD
17−import SourceSyntax.Annotation
18−import SourceSyntax.Expression
19−import qualified SourceSyntax.Helpers as Help
20−import SourceSyntax.Literal
21−import SourceSyntax.Module
22−import qualified SourceSyntax.Pattern as P
23−import SourceSyntax.PrettyPrint (renderPretty)
24−import qualified SourceSyntax.Variable as V
25−import qualified Transform.SafeNames as MakeSafe
18+
19+import AST.Annotation
20+import AST.Module
21+import AST.Expression.General
22+import qualified AST.Expression.Canonical as Canonical
23+import qualified AST.Module as Module
24+import qualified AST.Helpers as Help
25+import AST.Literal
26+import qualified AST.Pattern as P
27+import qualified AST.Variable as Var
2628
2729varDecl :: String -> Expression () -> VarDecl ()
2830varDecl x expr =
2931 VarDecl () (var x) (Just expr)
3032
31−include :: String -> String -> VarDecl ()
32−include alias moduleName =
33− varDecl alias (obj (moduleName ++ ".make") <| ref "_elm")
34−
35−internalImports :: String -> Statement ()
33+internalImports :: String -> [VarDecl ()]
3634internalImports name =
37− VarDeclStmt ()
38− [ varDecl "_N" (obj "Elm.Native")
39− , include "_U" "_N.Utils"
40− , include "_L" "_N.List"
41− , include "_A" "_N.Array"
42− , include "_E" "_N.Error"
43− , varDecl "$moduleName" (string name)
35+ [ varDecl "_N" (obj ["Elm","Native"])
36+ , include "_U" "Utils"
37+ , include "_L" "List"
38+ , include "_A" "Array"
39+ , include "_E" "Error"
40+ , varDecl Help.localModuleName (string name)
4441 ]
42+ where
43+ include :: String -> String -> VarDecl ()
44+ include alias modul =
45+ varDecl alias (obj ["_N", modul, "make"] <| ref "_elm")
46+
47+_Utils :: String -> Expression ()
48+_Utils x = obj ["_U", x]
49+
50+_List :: String -> Expression ()
51+_List x = obj ["_L", x]
4552
4653literal :: Literal -> Expression ()
4754literal lit =
4855 case lit of
49− Chr c -> obj "_U.chr" <| string [c]
56+ Chr c -> _Utils "chr" <| string [c]
5057 Str s -> string s
5158 IntNum n -> IntLit () n
5259 FloatNum n -> NumLit () n
5360 Boolean b -> BoolLit () b
5461
55−expression :: Expr -> State Int (Expression ())
62+expression :: Canonical.Expr -> State Int (Expression ())
5663expression (A region expr) =
5764 case expr of
58− Var (V.Raw x) -> return $ obj x
65+ Var var -> return $ Var.canonical var
5966
6067 Literal lit -> return $ literal lit
6168
6269 Range lo hi ->
6370 do lo' <- expression lo
6471 hi' <- expression hi
65− return $ obj "_L.range" `call` [lo',hi']
72+ return $ _List "range" `call` [lo',hi']
6673
6774 Access e x ->
6875 do e' <- expression e
@@ -70,19 +77,19 @@ expression (A region expr) =
7077
7178 Remove e x ->
7279 do e' <- expression e
73− return $ obj "_U.remove" `call` [string x, e']
80+ return $ _Utils "remove" `call` [string x, e']
7481
7582 Insert e x v ->
7683 do v' <- expression v
7784 e' <- expression e
78− return $ obj "_U.insert" `call` [string x, v', e']
85+ return $ _Utils "insert" `call` [string x, v', e']
7986
8087 Modify e fs ->
8188 do e' <- expression e
8289 fs' <- forM fs $ \(f,v) -> do
8390 v' <- expression v
8491 return $ ArrayLit () [string f, v']
85− return $ obj "_U.replace" `call` [ArrayLit () fs', e']
92+ return $ _Utils "replace" `call` [ArrayLit () fs', e']
8693
8794 Record fields ->
8895 do fields' <- forM fields $ \(f,e) -> do
@@ -106,10 +113,10 @@ expression (A region expr) =
106113 where
107114 depattern (args, body) pattern =
108115 case pattern of
109− P.Var x -> return (args ++ [x], body)
116+ P.Var x -> return (args ++ [ Var.varName x ], body)
110117 _ -> do arg <- Case.newVar
111118 return ( args ++ [arg]
112− , A ann (Case (A ann (rawVar arg)) [(pattern, body)]))
119+ , A ann (Case (A ann (localVar arg)) [(pattern, body)]))
113120
114121 (patterns, innerBody) = collect [p] e
115122
@@ -142,9 +149,10 @@ expression (A region expr) =
142149 MultiIf branches ->
143150 do branches' <- forM branches $ \(b,e) -> (,) <$> expression b <*> expression e
144151 return $ case last branches of
145− (A _ (Var (V.Raw "Basics.otherwise")), _) -> safeIfs branches'
152+ (A _ (Var (Var.Canonical (Var.Module "Basics") "otherwise")), _) ->
153+ safeIfs branches'
146154 (A _ (Literal (Boolean True)), _) -> safeIfs branches'
147− _ -> ifs branches' (obj "_E.If" `call` [ ref "$moduleName", string (renderPretty region) ])
155+ _ -> ifs branches' (throw "If" region)
148156 where
149157 safeIfs branches = ifs (init branches) (snd (last branches))
150158 ifs branches finally = foldr iff finally branches
@@ -154,7 +162,7 @@ expression (A region expr) =
154162 do (tempVar,initialMatch) <- Case.toMatch cases
155163 (revisedMatch, stmt) <-
156164 case e of
157− A _ (Var (V.Raw x)) ->
165+ A _ (Var (Var.Canonical Var.Local x)) ->
158166 return (Case.matchSubst [(tempVar,x)] initialMatch, [])
159167 _ ->
160168 do e' <- expression e
@@ -164,7 +172,7 @@ expression (A region expr) =
164172
165173 ExplicitList es ->
166174 do es' <- mapM expression es
167− return $ obj "_L.fromArray" <| ArrayLit () es'
175+ return $ _List "fromArray" <| ArrayLit () es'
168176
169177 Data name es ->
170178 do es' <- mapM expression es
@@ -175,7 +183,7 @@ expression (A region expr) =
175183
176184 Markdown uid doc es ->
177185 do es' <- mapM expression es
178− return $ obj "Text.markdown" `call` (string md : string uid : es')
186+ return $ Var.value "Text" "markdown" `call` (string md : string uid : es')
179187 where
180188 pad = "<div style=\"height:0;width:0;\"> </div>"
181189 md = pad ++ MD.toHtml doc ++ pad
@@ -184,15 +192,16 @@ expression (A region expr) =
184192 return $ ObjectLit () [(PropString () "src", literal (Str src))]
185193
186194 PortIn name tipe ->
187− return $ obj "Native.Ports.portIn" `call` [ string name, Port.incoming tipe ]
195+ return $ Var.value "Native.Ports" "portIn" `call`
196+ [ string name, Port.incoming tipe ]
188197
189198 PortOut name tipe value ->
190199 do value' <- expression value
191− return $ obj "Native.Ports.portOut" `call`
200+ return $ Var.value "Native.Ports" "portOut" `call`
192201 [ string name, Port.outgoing tipe, value' ]
193202
194−definition :: Def -> State Int [Statement ()]
195−definition (Definition pattern expr@(A region _) _) = do
203+definition :: Canonical.Def -> State Int [Statement ()]
204+definition (Canonical.Definition pattern expr@(A region _) _) = do
196205 expr' <- expression expr
197206 let assign x = varDecl x expr'
198207 case pattern of
@@ -201,39 +210,39 @@ definition (Definition pattern expr@(A region _) _) = do
201210 let op = LBracket () (ref "_op") (string x) in
202211 return [ ExprStmt () $ AssignExpr () OpAssign op expr' ]
203212 | otherwise ->
204− return [ VarDeclStmt () [ assign x ] ]
213+ return [ VarDeclStmt () [ assign (Var.varName x) ] ]
205214
206215 P.Record fields ->
207− let setField f = varDecl f (dotSep ["$",f]) in
216+ let setField f = varDecl f (obj ["$",f]) in
208217 return [ VarDeclStmt () (assign "$" : map setField fields) ]
209218
210− P.Data name patterns | vars /= Nothing ->
219+ P.Data (Var.Canonical _ name) patterns | vars /= Nothing ->
211220 return [ VarDeclStmt () (setup (zipWith decl (maybe [] id vars) [0..])) ]
212221 where
213222 vars = getVars patterns
214223 getVars patterns =
215224 case patterns of
216− P.Var x : rest -> (x:) `fmap` getVars rest
225+ P.Var x : rest -> (Var.varName x :) `fmap` getVars rest
217226 [] -> Just []
218227 _ -> Nothing
219228
220− decl x n = varDecl x (dotSep ["$","_" ++ show n])
229+ decl x n = varDecl x (obj ["$","_" ++ show n])
221230 setup vars
222231 | Help.isTuple name = assign "$" : vars
223232 | otherwise = assign "_raw" : safeAssign : vars
224233
225− safeAssign = varDecl "$" (CondExpr () if' (obj "_raw") exception)
226− if' = InfixExpr () OpStrictEq (obj "_raw.ctor") (string name)
227− exception = obj "_E.Case" `call` [ref "$moduleName", string (renderPretty region)]
234+ safeAssign = varDecl "$" (CondExpr () if' (ref "_raw") exception)
235+ if' = InfixExpr () OpStrictEq (obj ["_raw","ctor"]) (string name)
236+ exception = Help.throw "Case" region
228237
229238 _ ->
230239 do defs' <- concat <$> mapM toDef vars
231240 return (VarDeclStmt () [assign "_"] : defs')
232241 where
233242 vars = P.boundVarList pattern
234− mkVar = A region . rawVar
243+ mkVar = A region . localVar
235244 toDef y = let expr = A region $ Case (mkVar "_") [(pattern, mkVar y)]
236− in definition $ Definition (P.Var y) expr Nothing
245+ in definition $ Canonical.Definition (P.Var y) expr Nothing
237246
238247match :: Region -> Case.Match -> State Int [Statement ()]
239248match region mtch =
@@ -248,15 +257,15 @@ match region mtch =
248257 _ -> False
249258
250259 access name
251− | any isLiteral clauses = obj name
252− | otherwise = dotSep (split name ++ ["ctor"])
260+ | any isLiteral clauses = obj [name]
261+ | otherwise = obj (Help.splitDots name ++ ["ctor"])
253262
254263 format isChars e
255264 | or isChars = InfixExpr () OpAdd e (string "")
256265 | otherwise = e
257266
258267 Case.Fail ->
259− return [ ExprStmt () (obj "_E.Case" `call` [ref "$moduleName", string (renderPretty region)]) ]
268+ return [ ExprStmt () (Help.throw "Case" region) ]
260269
261270 Case.Break -> return [BreakStmt () Nothing]
262271
@@ -283,98 +292,123 @@ clause region variable (Case.Clause value vars mtch) =
283292 _ -> (,) False $ case value of
284293 Right (Boolean b) -> BoolLit () b
285294 Right lit -> literal lit
286− Left name -> string $ case List.elemIndices '.' name of
287− [] -> name
288− is -> drop (last is + 1) name
295+ Left (Var.Canonical _ name) ->
296+ string name
289297
290−flattenLets :: [Def] -> Expr -> ([Def], Expr)
298+flattenLets :: [Canonical.Def] -> Canonical.Expr -> ([Canonical.Def], Canonical.Expr)
291299flattenLets defs lexpr@(A _ expr) =
292300 case expr of
293301 Let ds body -> flattenLets (defs ++ ds) body
294302 _ -> (defs, lexpr)
295303
296−generate :: MetadataModule -> String
297−generate unsafeModule =
298− show . prettyPrint $ setup (Just "Elm") (names modul ++ ["make"]) ++
299− [ assign ("Elm" : names modul ++ ["make"]) (function ["_elm"] programStmts) ]
304+generate :: CanonicalModule -> String
305+generate modul =
306+ show . prettyPrint $ setup "Elm" (names ++ ["make"]) ++
307+ [ assign ("Elm" : names ++ ["make"]) (function ["_elm"] programStmts) ]
300308 where
301− modul = MakeSafe.metadataModule unsafeModule
302− thisModule = dotSep ("_elm" : names modul ++ ["values"])
309+ names :: [String]
310+ names = Module.names modul
311+
312+ thisModule :: Expression ()
313+ thisModule = obj ("_elm" : names ++ ["values"])
314+
315+ programStmts :: [Statement ()]
303316 programStmts =
304317 concat
305− [ [ ExprStmt () $ string "use strict" ]
306− , setup (Just "_elm") (names modul ++ ["values"])
318+ [ [ ExprStmt () (string "use strict") ]
319+ , setup "_elm" (names ++ ["values"])
307320 , [ IfSingleStmt () thisModule (ret thisModule) ]
308− , [ internalImports (List.intercalate "." (names modul)) ]
309− , concatMap jsImport . Set.toList . Set.fromList . map fst $ imports modul
310− , [ assign ["_op"] (ObjectLit () []) ]
311− , concat $ evalState (mapM definition . fst . flattenLets [] $ program modul) 0
321+ , [ VarDeclStmt () localVars ]
322+ , body
312323 , [ jsExports ]
313324 , [ ret thisModule ]
314325 ]
315326
316− jsExports = assign ("_elm" : names modul ++ ["values"]) (ObjectLit () exs)
327+ localVars :: [VarDecl ()]
328+ localVars = varDecl "_op" (ObjectLit () []) :
329+ internalImports (Module.getName modul) ++
330+ explicitImports
331+ where
332+ explicitImports :: [VarDecl ()]
333+ explicitImports =
334+ map jsImport . Set.toList . Set.fromList . map fst $ Module.imports modul
335+
336+ jsImport :: String -> VarDecl ()
337+ jsImport name =
338+ varDecl (Var.moduleName name) $
339+ obj ("Elm" : Help.splitDots name ++ ["make"]) <| ref "_elm"
340+
341+ body :: [Statement ()]
342+ body = concat $ evalState defs 0
343+ where
344+ defs = mapM definition . fst . flattenLets [] $ Module.program (Module.body modul)
345+
346+ setup namespace path = map create paths
347+ where
348+ create name = assign name (InfixExpr () OpLOr (obj name) (ObjectLit () []))
349+ paths = drop 2 . init . List.inits $ namespace : path
350+
351+ jsExports = assign ("_elm" : names ++ ["values"]) (ObjectLit () exs)
317352 where
318− exs = map entry . filter (not . Help.isOp) $ "_op" : exports modul
353+ exs = map entry $ "_op" : concatMap extract (exports modul)
319354 entry x = (prop x, ref x)
355+ extract value =
356+ case value of
357+ Var.Alias _ -> []
358+ Var.Value x | Help.isOp x -> []
359+ | otherwise -> [Var.varName x]
360+ Var.ADT _ (Var.Listing ctors _) -> map Var.varName ctors
320361
321362 assign path expr =
322363 case path of
323364 [x] -> VarDeclStmt () [ varDecl x expr ]
324365 _ -> ExprStmt () $
325− AssignExpr () OpAssign (LDot () (dotSep (init path)) (last path)) expr
326−
327− jsImport modul = setup Nothing path ++ [ include ]
328− where
329− path = Help.splitDots modul
330− include = assign path $ dotSep ("Elm" : path ++ ["make"]) <| ref "_elm"
366+ AssignExpr () OpAssign (LDot () (obj (init path)) (last path)) expr
331367
332− setup namespace path = map create paths
333− where
334− create name = assign name (InfixExpr () OpLOr (dotSep name) (ObjectLit () []))
335− paths = case namespace of
336− Nothing -> tail . init $ List.inits path
337− Just nmspc -> drop 2 . init . List.inits $ nmspc : path
338−
339−binop :: Region -> String -> Expr -> Expr -> State Int (Expression ())
340−binop region op e1 e2 =
341− case op of
342− "Basics.." ->
368+binop :: Region -> Var.Canonical -> Canonical.Expr -> Canonical.Expr
369+ -> State Int (Expression ())
370+binop region func@(Var.Canonical home op) e1 e2 =
371+ case (home, op) of
372+ (Var.Module "Basics", ".") ->
343373 do es <- mapM expression (e1 : collect [] e2)
344374 return $ ["$"] ==> foldr (<|) (ref "$") es
345− "Basics.<|" ->
375+
376+ (Var.Module "Basics", "<|") ->
346377 do e2' <- expression e2
347378 es <- mapM expression (collect [] e1)
348379 return $ foldr (<|) e2' es
349− "List.++" ->
380+
381+ (Var.Module "List", "++") ->
350382 do e1' <- expression e1
351383 e2' <- expression e2
352− return $ obj "_L.append" `call` [e1', e2']
353− "::" -> expression (A region (Data "::" [e1,e2]))
354− _ ->
384+ return $ _List "append" `call` [e1', e2']
385+
386+ (Var.BuiltIn, "::") ->
387+ expression (A region (Data "::" [e1,e2]))
388+
389+ (Var.Module "Basics", _) ->
355390 do e1' <- expression e1
356391 e2' <- expression e2
357− return $ case Map.lookup op opDict of
392+ return $ case Map.lookup op basicOps of
358393 Just f -> f e1' e2'
359− Nothing -> ref "A2" `call` [ func, e1', e2' ]
394+ Nothing -> ref "A2" `call` [ Var.canonical func, e1', e2' ]
395+
396+ _ ->
397+ do e1' <- expression e1
398+ e2' <- expression e2
399+ return (ref "A2" `call` [ Var.canonical func, e1', e2' ])
400+
360401 where
361402 collect es e =
362403 case e of
363− A _ (Binop op e1 e2) | op == "Basics.." -> collect (es ++ [e1]) e2
404+ A _ (Binop (Var.Canonical (Var.Module "Basics") ".") e1 e2) ->
405+ collect (es ++ [e1]) e2
364406 _ -> es ++ [e]
365407
366− func | Help.isOp operator = BracketRef () (dotSep (init parts ++ ["_op"])) (string operator)
367− | otherwise = dotSep parts
368− where
369− parts = Help.splitDots op
370− operator = last parts
371−
372− opDict = Map.fromList (infixOps ++ specialOps)
373−
374− specialOp str func = [ (str, func), ("Basics." ++ str, func) ]
375− infixOp str op = specialOp str (InfixExpr () op)
408+ basicOps = Map.fromList (infixOps ++ specialOps)
376409
377− infixOps = concat
410+ infixOps =
411+ let infixOp str op = (str, InfixExpr () op) in
378412 [ infixOp "+" OpAdd
379413 , infixOp "-" OpSub
380414 , infixOp "*" OpMul
@@ -383,16 +417,16 @@ binop region op e1 e2 =
383417 , infixOp "||" OpLOr
384418 ]
385419
386− specialOps = concat
387− [ specialOp "^" $ \a b -> obj "Math.pow" `call` [a,b]
388− , specialOp "|>" $ flip (<|)
389− , specialOp "==" $ \a b -> obj "_U.eq" `call` [a,b]
390− , specialOp "/=" $ \a b -> PrefixExpr () PrefixLNot (obj "_U.eq" `call` [a,b])
391− , specialOp "<" $ cmp OpLT 0
392− , specialOp ">" $ cmp OpGT 0
393− , specialOp "<=" $ cmp OpLT 1
394− , specialOp ">=" $ cmp OpGT (-1)
395− , specialOp "div" $ \a b -> InfixExpr () OpBOr (InfixExpr () OpDiv a b) (IntLit () 0)
420+ specialOps =
421+ [ (,) "^" $ \a b -> obj ["Math","pow"] `call` [a,b]
422+ , (,) "|>" $ flip (<|)
423+ , (,) "==" $ \a b -> _Utils "eq" `call` [a,b]
424+ , (,) "/=" $ \a b -> PrefixExpr () PrefixLNot (_Utils "eq" `call` [a,b])
425+ , (,) "<" $ cmp OpLT 0
426+ , (,) ">" $ cmp OpGT 0
427+ , (,) "<=" $ cmp OpLT 1
428+ , (,) ">=" $ cmp OpGT (-1)
429+ , (,) "div" $ \a b -> InfixExpr () OpBOr (InfixExpr () OpDiv a b) (IntLit () 0)
396430 ]
397431
398− cmp op n a b = InfixExpr () op (obj "_U.cmp" `call` [a,b]) (IntLit () n)
432+ cmp op n a b = InfixExpr () op (_Utils "cmp" `call` [a,b]) (IntLit () n)