@@ -25,7 +25,7 @@ module Language.PureScript.CodeGen.JS
2525 , mainCall
2626 ) where
2727
28−import Data.List ((\\), delete)
28+import Data.List ((\\), delete, intersect)
2929import qualified Data.Traversable as T (traverse)
3030
3131import Control.Applicative
@@ -53,15 +53,17 @@ moduleToJs :: forall m mode. (Applicative m, Monad m, MonadReader (Options mode)
5353moduleToJs (Module coms mn imps exps foreigns decls) = do
5454 additional <- asks optionsAdditional
5555 jsImports <- T.traverse importToJs . delete (ModuleName [ProperName C.prim]) . (\\ [mn]) $ imps
56− let foreigns' = [] -- TODO: Update this. mapMaybe (\(_, js, _) -> js) foreigns
5756 jsDecls <- mapM bindToJs decls
5857 optimized <- T.traverse (T.traverse optimize) jsDecls
5958 let isModuleEmpty = null exps
6059 comments <- not <$> asks optionsNoComments
6160 let strict = JSStringLiteral "use strict"
6261 let header = if comments && not (null coms) then JSComment coms strict else strict
63− let moduleBody = header : jsImports ++ foreigns' ++ concat optimized
64− let exps' = JSObjectLiteral $ map (runIdent &&& JSVar . identToJs) exps
62+ let moduleBody = header : jsImports ++ concat optimized
63+ let foreignExps = exps `intersect` (fst `map` foreigns)
64+ let standardExps = exps \\ foreignExps
65+ let exps' = JSObjectLiteral $ map (runIdent &&& JSVar . identToJs) standardExps
66+ ++ map (runIdent &&& foreignIdent) foreignExps
6567 return $ case additional of
6668 MakeOptions -> moduleBody ++ [JSAssignment (JSAccessor "exports" (JSVar "module")) exps']
6769 CompileOptions ns _ _ | not isModuleEmpty ->
@@ -171,6 +173,12 @@ moduleToJs (Module coms mn imps exps foreigns decls) = do
171173 unApp :: Expr Ann -> [Expr Ann] -> (Expr Ann, [Expr Ann])
172174 unApp (App _ val arg) args = unApp val (arg : args)
173175 unApp other args = (other, args)
176+ valueToJs (Var (_, _, _, Just IsForeign) qi@(Qualified (Just mn') ident)) =
177+ return $ if mn' == mn
178+ then foreignIdent ident
179+ else varToJs qi
180+ valueToJs (Var (_, _, _, Just IsForeign) ident) =
181+ error $ "Encountered an unqualified reference to a foreign ident " ++ show ident
174182 valueToJs (Var _ ident) =
175183 return $ varToJs ident
176184 valueToJs (Case (maybeSpan, _, _, _) values binders) = do
@@ -247,6 +255,9 @@ moduleToJs (Module coms mn imps exps foreigns decls) = do
247255 qualifiedToJS f (Qualified (Just mn') a) | mn /= mn' = accessor (f a) (JSVar (moduleNameToJs mn'))
248256 qualifiedToJS f (Qualified _ a) = JSVar $ identToJs (f a)
249257
258+ foreignIdent :: Ident -> JS
259+ foreignIdent ident = accessorString (runIdent ident) (JSVar "$foreign")
260+
250261 -- |
251262 -- Generate code in the simplified Javascript intermediate representation for pattern match binders
252263 -- and guards.