git.iko.soy/rowtype-yoga/purescript-native
on 294b01d help sign in
80 lines 2.5 kB history raw
1-----------------------------------------------------------------------------
2--
3-- Module : PureScript.CodeGen.Externs
4-- Copyright : (c) Phil Freeman 2013
5-- License : MIT
6--
7-- Maintainer : Phil Freeman <paf31@cantab.net>
8-- Stability : experimental
9-- Portability :
10--
11-- |
12--
13-----------------------------------------------------------------------------
15{-# LANGUAGE GADTs, GeneralizedNewtypeDeriving #-}
17module PureScript.CodeGen.Externs (
18 externToPs
19) where
21import Data.Maybe (fromMaybe)
22import Data.List (intersperse, intercalate)
23import qualified Control.Arrow as A
24import Control.Applicative
26import PureScript.Values
27import PureScript.Types
28import PureScript.Declarations
29import PureScript.CodeGen.Common
31externToPs :: (String, Type) -> String
32externToPs (name, ty) = "extern " ++ name ++ " :: " ++ typeToPs ty
34typeLiterals :: Pattern Type String
35typeLiterals = Pattern $ A.Kleisli match
36 where
37 match Number = Just "Number"
38 match String = Just "String"
39 match Boolean = Just "Boolean"
40 match (Array ty) = Just $ "[" ++ typeToPs ty ++ "]"
41 match (Object row) = Just $ "{ " ++ rowToPs row ++ " }"
42 match (TypeVar var) = Just var
43 match (TypeConstructor ctor) = Just ctor
44 match _ = Nothing
46rowToPs :: Row -> String
47rowToPs = (\(tys, tail) -> intercalate "; " (map (uncurry nameAndTypeToPs) tys) ++ tailToPs tail) . toList
48 where
49 nameAndTypeToPs :: String -> Type -> String
50 nameAndTypeToPs name ty = name ++ " :: " ++ typeToPs ty
51 tailToPs :: Row -> String
52 tailToPs REmpty = ""
53 tailToPs (RowVar var) = " | " ++ var
54 toList :: Row -> ([(String, Type)], Row)
55 toList (RCons name ty row) = let (tys, rest) = toList row
56 in ((name, ty):tys, rest)
57 toList r = ([], r)
59typeApp :: Pattern Type (Type, Type)
60typeApp = Pattern $ A.Kleisli match
61 where
62 match (TypeApp f x) = Just (f, x)
63 match _ = Nothing
65function :: Pattern Type ([Type], Type)
66function = Pattern $ A.Kleisli match
67 where
68 match (Function args ret) = Just (args, ret)
69 match _ = Nothing
71typeToPs :: Type -> String
72typeToPs = fromMaybe (error "Incomplete pattern") . pattern matchType
73 where
74 matchType :: Pattern Type String
75 matchType = buildPrettyPrinter operators (typeLiterals <|> fmap parens matchType)
76 operators :: OperatorTable Type String
77 operators =
78 OperatorTable $ [ AssocL typeApp $ \f x -> f ++ " " ++ x
79 , Split function $ \args ret -> "(" ++ intercalate ", " (map typeToPs args) ++ ") -> " ++ typeToPs ret ]