@@ -1,21 +1,42 @@
11module Generate.JavaScript.Ports (incoming, outgoing) where
22
3+import qualified Data.List as List
34import Generate.JavaScript.Helpers
45import qualified Generate.JavaScript.Variable as V
56import AST.Type as T
67import qualified AST.Variable as Var
78import Language.ECMAScript3.Syntax
89
9−data JSType = JSNumber | JSBoolean | JSString | JSArray | JSObject [String]
10− deriving Show
10+
11+data JSType
12+ = JSNumber
13+ | JSBoolean
14+ | JSString
15+ | JSArray
16+ | JSObject [String]
17+
18+
19+typeToString :: JSType -> String
20+typeToString tipe =
21+ case tipe of
22+ JSNumber -> "a number"
23+ JSBoolean -> "a boolean (true or false)"
24+ JSString -> "a string"
25+ JSArray -> "an array"
26+ JSObject fields ->
27+ "an object with fields " ++ List.intercalate ", " fields
28+
1129
1230check :: Expression () -> JSType -> Expression () -> Expression ()
1331check x jsType continue =
1432 CondExpr () (jsFold OpLOr checks x) continue throw
1533 where
16− jsFold op checks value = foldl1 (InfixExpr () op) (map ($value) checks)
17− throw = obj ["_E","raise"] <| InfixExpr () OpAdd msg x
18− msg = string ("invalid input, expecting " ++ show jsType ++ " but got ")
34+ jsFold op checks value =
35+ foldl1 (InfixExpr () op) (map ($ value) checks)
36+
37+ throw =
38+ obj ["_U","badPort"] `call` [ string (typeToString jsType), x ]
39+
1940 checks =
2041 case jsType of
2142 JSNumber -> [typeof "number"]
@@ -24,13 +45,14 @@ check x jsType continue =
2445 JSArray -> [instanceof "Array"]
2546 JSObject fields -> [jsFold OpLAnd (typeof "object" : map member fields)]
2647
48+
2749incoming :: CanonicalType -> Expression ()
2850incoming tipe =
2951 case tipe of
3052 Aliased _ t -> incoming t
3153
3254 App (Type v) [t]
33− | Var.isSignal v -> V.value ["Native","Ports"] "incomingSignal" <| incoming t
55+ | Var.isSignal v -> obj ["_P","incomingSignal"] <| incoming t
3456
3557 _ -> ["v"] ==> inc tipe (ref "v")
3658
@@ -106,7 +128,7 @@ outgoing tipe =
106128 Aliased _ t -> outgoing t
107129
108130 App (Type v) [t]
109− | Var.isSignal v -> V.value ["Native","Ports"] "outgoingSignal" <| outgoing t
131+ | Var.isSignal v -> obj ["_P","outgoingSignal"] <| outgoing t
110132
111133 _ -> ["v"] ==> out tipe (ref "v")
112134