2 ------------------------------------------------------------------
3 -- A primop-table mangling program --
4 ------------------------------------------------------------------
14 import System ( getArgs )
15 import Maybe ( catMaybes )
18 main = getArgs >>= \args ->
19 if length args /= 1 || head args `notElem` known_args
20 then error ("usage: genprimopcode command < primops.txt > ...\n"
21 ++ " where command is one of\n"
22 ++ unlines (map (" "++) known_args)
27 Left err -> error ("parse error at " ++ (show err))
28 Right p_o_specs@(Info _ entries)
29 -> seq (sanityTop p_o_specs) (
33 -> putStr (gen_data_decl p_o_specs)
36 -> putStr (gen_switch_from_attribs
38 "primOpHasSideEffects" p_o_specs)
41 -> putStr (gen_switch_from_attribs
43 "primOpOutOfLine" p_o_specs)
46 -> putStr (gen_switch_from_attribs
48 "commutableOp" p_o_specs)
51 -> putStr (gen_switch_from_attribs
53 "primOpNeedsWrapper" p_o_specs)
56 -> putStr (gen_switch_from_attribs
58 "primOpCanFail" p_o_specs)
61 -> putStr (gen_switch_from_attribs
63 "primOpStrictness" p_o_specs)
65 "--primop-primop-info"
66 -> putStr (gen_primop_info p_o_specs)
69 -> putStr (gen_primop_tag p_o_specs)
72 -> putStr (gen_primop_list p_o_specs)
74 "--make-haskell-wrappers"
75 -> putStr (gen_wrappers p_o_specs)
77 "--make-haskell-source"
78 -> putStr (gen_hs_source p_o_specs)
80 "--make-ext-core-source"
81 -> putStr (gen_ext_core_source entries)
84 -> putStr (gen_latex_doc p_o_specs)
86 _ -> error "Should not happen, known_args out of sync?"
89 known_args :: [String]
98 "--primop-primop-info",
101 "--make-haskell-wrappers",
102 "--make-haskell-source",
103 "--make-ext-core-source",
107 ------------------------------------------------------------------
108 -- Code generators -----------------------------------------------
109 ------------------------------------------------------------------
111 gen_hs_source :: Info -> String
112 gen_hs_source (Info defaults entries) =
113 "-----------------------------------------------------------------------------\n"
115 ++ "-- Module : GHC.Prim\n"
117 ++ "-- Maintainer : cvs-ghc@haskell.org\n"
118 ++ "-- Stability : internal\n"
119 ++ "-- Portability : non-portable (GHC extensions)\n"
121 ++ "-- GHC\'s primitive types and operations.\n"
123 ++ "-----------------------------------------------------------------------------\n"
124 ++ "module GHC.Prim (\n"
125 ++ unlines (map (("\t" ++) . hdr) entries)
127 ++ unlines (map opt defaults) ++ "-}\n"
128 ++ unlines (map ent entries) ++ "\n\n\n"
129 where opt (OptionFalse n) = n ++ " = False"
130 opt (OptionTrue n) = n ++ " = True"
131 opt (OptionString n v) = n ++ " = { " ++ v ++ "}"
133 hdr s@(Section {}) = sec s
134 hdr (PrimOpSpec { name = n }) = wrapOp n ++ ","
135 hdr (PseudoOpSpec { name = n }) = wrapOp n ++ ","
136 hdr (PrimTypeSpec { ty = TyApp n _ }) = wrapTy n ++ ","
137 hdr (PrimTypeSpec {}) = error "Illegal type spec"
139 ent (Section {}) = ""
140 ent o@(PrimOpSpec {}) = spec o
141 ent o@(PrimTypeSpec {}) = spec o
142 ent o@(PseudoOpSpec {}) = spec o
144 sec s = "\n-- * " ++ escape (title s) ++ "\n"
145 ++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ desc s) ++ "\n"
147 spec o = comm ++ decl
148 where decl = case o of
149 PrimOpSpec { name = n, ty = t } -> wrapOp n ++ " :: " ++ pty t
150 PseudoOpSpec { name = n, ty = t } -> wrapOp n ++ " :: " ++ pty t
151 PrimTypeSpec { ty = t } -> "data " ++ pty t
154 comm = case (desc o) of
156 d -> "\n" ++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ d)
158 pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
161 pbty (TyApp tc ts) = tc ++ (concat (map (' ':) (map paty ts)))
162 pbty (TyUTup ts) = "(# " ++ (concat (intersperse "," (map pty ts))) ++ " #)"
166 paty t = "(" ++ pty t ++ ")"
168 wrapOp nm | isAlpha (head nm) = nm
169 | otherwise = "(" ++ nm ++ ")"
170 wrapTy nm | isAlpha (head nm) = nm
171 | otherwise = "(" ++ nm ++ ")"
172 unlatex s = case s of
173 '\\':'t':'e':'x':'t':'t':'t':'{':cs -> markup "@" "@" cs
174 '{':'\\':'t':'t':cs -> markup "@" "@" cs
175 '{':'\\':'i':'t':cs -> markup "/" "/" cs
176 c : cs -> c : unlatex cs
178 markup s t xs = s ++ mk (dropWhile isSpace xs)
180 mk ('\n':cs) = ' ' : mk cs
181 mk ('}':cs) = t ++ unlatex cs
182 mk (c:cs) = c : mk cs
183 escape = concatMap (\c -> if c `elem` special then '\\':c:[] else c:[])
184 where special = "/'`\"@<"
186 -- Generates the type environment that the stand-alone External Core tools use.
187 gen_ext_core_source :: [Entry] -> String
188 gen_ext_core_source entries =
189 "-----------------------------------------------------------------------\n"
190 ++ "-- This module is automatically generated by the GHC utility\n"
191 ++ "-- \"genprimopcode\". Do not edit!\n"
192 ++ "-----------------------------------------------------------------------\n"
193 ++ "module PrimEnv(primTcs, primVals) where\nimport Core\nimport Encoding\n\n"
194 ++ "primTcs :: [(Tcon, Kind)]\n"
196 ++ printList tcEnt entries
198 ++ "primVals :: [(Var, Ty)]\n"
200 ++ printList valEnt entries
202 where printList f = concat . intersperse ",\n" . filter (not . null) . map f
203 tcEnt (PrimTypeSpec {ty=t}) =
205 TyApp tc args -> parens tc (tcKind tc args)
206 _ -> error ("tcEnt: type in PrimTypeSpec is not a type"
207 ++ " constructor: " ++ show t)
210 -- The primops.txt.pp format doesn't have enough information in it to
211 -- print out some of the information that ext-core needs (like kinds,
212 -- and later on in this code, module names) so we special-case. An
213 -- alternative would be to refer to things indirectly and hard-wire
214 -- certain things (e.g., the kind of the Any constructor, here) into
215 -- ext-core's Prims module again.
216 tcKind "Any" _ = "Klifted"
217 tcKind tc [] | last tc == '#' = "Kunlifted"
218 tcKind tc [] | otherwise = "Klifted"
219 -- assumes that all type arguments are lifted (are they?)
220 tcKind tc (v:as) = "(Karrow Klifted " ++ tcKind tc as
222 valEnt (PseudoOpSpec {name=n, ty=t}) = valEntry n t
223 valEnt (PrimOpSpec {name=n, ty=t}) = valEntry n t
225 valEntry name ty = parens name (mkForallTy (freeTvars ty) (pty ty))
226 where pty (TyF t1 t2) = mkFunTy (pty t1) (pty t2)
227 pty (TyApp tc ts) = mkTconApp (mkTcon tc) (map pty ts)
228 pty (TyUTup ts) = mkUtupleTy (map pty ts)
229 pty (TyVar tv) = paren $ "Tvar \"" ++ tv ++ "\""
231 mkFunTy s1 s2 = "Tapp " ++ (paren ("Tapp (Tcon tcArrow)"
234 mkTconApp tc args = foldl tapp tc args
235 mkTcon tc = paren $ "Tcon " ++ paren (qualify True tc)
236 mkUtupleTy args = foldl tapp (tcUTuple (length args)) args
238 mkForallTy vs t = foldr
239 (\ v s -> "Tforall " ++
240 (paren (quot v ++ ", " ++ vKind v)) ++ " "
247 freeTvars (TyF t1 t2) = freeTvars t1 `union` freeTvars t2
248 freeTvars (TyApp _ tys) = freeTvarss tys
249 freeTvars (TyVar v) = [v]
250 freeTvars (TyUTup tys) = freeTvarss tys
251 freeTvarss = nub . concatMap freeTvars
253 tapp s nextArg = paren $ "Tapp " ++ s ++ " " ++ paren nextArg
254 tcUTuple n = paren $ "Tcon " ++ paren (qualify False $ "Z"
256 -- more hacks. might be better to do this on the ext-core side,
257 -- as per earlier comment
258 qualify _ tc | tc == "ByteArr#" = qualify True "ByteArray#"
259 qualify _ tc | tc == "MutArr#" = qualify True "MutableArray#"
260 qualify _ tc | tc == "MutByteArr#" =
261 qualify True "MutableByteArray#"
262 qualify _ tc | tc == "Bool" = "Just boolMname" ++ ", "
264 qualify _ tc | tc == "()" = "Just baseMname" ++ ", "
266 qualify enc tc = "Just primMname" ++ ", " ++ (ze enc tc)
267 ze enc tc = (if enc then "zEncodeString " else "")
268 ++ "\"" ++ tc ++ "\""
270 parens n ty = " (zEncodeString \"" ++ n ++ "\", " ++ ty ++ ")"
271 paren s = "(" ++ s ++ ")"
272 quot s = "\"" ++ s ++ "\""
274 gen_latex_doc :: Info -> String
275 gen_latex_doc (Info defaults entries)
276 = "\\primopdefaults{"
277 ++ mk_options defaults
279 ++ (concat (map mk_entry entries))
280 where mk_entry (PrimOpSpec {cons=constr,name=n,ty=t,cat=c,desc=d,opts=o}) =
282 ++ latex_encode constr ++ "}{"
283 ++ latex_encode n ++ "}{"
284 ++ latex_encode (zencode n) ++ "}{"
285 ++ latex_encode (show c) ++ "}{"
286 ++ latex_encode (mk_source_ty t) ++ "}{"
287 ++ latex_encode (mk_core_ty t) ++ "}{"
291 mk_entry (Section {title=ti,desc=d}) =
293 ++ latex_encode ti ++ "}{"
295 mk_entry (PrimTypeSpec {ty=t,desc=d,opts=o}) =
297 ++ latex_encode (mk_source_ty t) ++ "}{"
298 ++ latex_encode (mk_core_ty t) ++ "}{"
302 mk_entry (PseudoOpSpec {name=n,ty=t,desc=d,opts=o}) =
304 ++ latex_encode (zencode n) ++ "}{"
305 ++ latex_encode (mk_source_ty t) ++ "}{"
306 ++ latex_encode (mk_core_ty t) ++ "}{"
310 mk_source_ty typ = pty typ
311 where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
313 pbty (TyApp tc ts) = tc ++ (concat (map (' ':) (map paty ts)))
314 pbty (TyUTup ts) = "(# " ++ (concat (intersperse "," (map pty ts))) ++ " #)"
317 paty t = "(" ++ pty t ++ ")"
319 mk_core_ty typ = foralls ++ (pty typ)
320 where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
322 pbty (TyApp tc ts) = (zencode tc) ++ (concat (map (' ':) (map paty ts)))
323 pbty (TyUTup ts) = (zencode (utuplenm (length ts))) ++ (concat ((map (' ':) (map paty ts))))
325 paty (TyVar tv) = zencode tv
326 paty (TyApp tc []) = zencode tc
327 paty t = "(" ++ pty t ++ ")"
329 utuplenm n = "(#" ++ (replicate (n-1) ',') ++ "#)"
330 foralls = if tvars == [] then "" else "%forall " ++ (tbinds tvars)
333 tbinds ("o":tbs) = "(o::?) " ++ (tbinds tbs)
334 tbinds (tv:tbs) = tv ++ " " ++ (tbinds tbs)
335 tvars_of (TyF t1 t2) = tvars_of t1 `union` tvars_of t2
336 tvars_of (TyApp _ ts) = foldl union [] (map tvars_of ts)
337 tvars_of (TyUTup ts) = foldr union [] (map tvars_of ts)
338 tvars_of (TyVar tv) = [tv]
342 ++ mk_has_side_effects o ++ "}{"
343 ++ mk_out_of_line o ++ "}{"
344 ++ mk_commutable o ++ "}{"
345 ++ mk_needs_wrapper o ++ "}{"
346 ++ mk_can_fail o ++ "}{"
347 ++ latex_encode (mk_strictness o) ++ "}{"
350 mk_has_side_effects o = mk_bool_opt o "has_side_effects" "Has side effects." "Has no side effects."
351 mk_out_of_line o = mk_bool_opt o "out_of_line" "Implemented out of line." "Implemented in line."
352 mk_commutable o = mk_bool_opt o "commutable" "Commutable." "Not commutable."
353 mk_needs_wrapper o = mk_bool_opt o "needs_wrapper" "Needs wrapper." "Needs no wrapper."
354 mk_can_fail o = mk_bool_opt o "can_fail" "Can fail." "Cannot fail."
356 mk_bool_opt o opt_name if_true if_false =
357 case lookup_attrib opt_name o of
358 Just (OptionTrue _) -> if_true
359 Just (OptionFalse _) -> if_false
360 Just (OptionString _ _) -> error "String value for boolean option"
364 case lookup_attrib "strictness" o of
365 Just (OptionString _ s) -> s -- for now
366 Just _ -> error "Boolean value for strictness"
370 case maybe_tuple xs of
371 Just n -> n -- Tuples go to Z2T etc
372 Nothing -> concat (map encode_ch xs)
374 maybe_tuple "(# #)" = Just("Z1H")
375 maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of
376 (n, '#' : ')' : _) -> Just ('Z' : shows (n+1) "H")
378 maybe_tuple "()" = Just("Z0T")
379 maybe_tuple ('(' : cs) = case count_commas (0::Int) cs of
380 (n, ')' : _) -> Just ('Z' : shows (n+1) "T")
382 maybe_tuple _ = Nothing
384 count_commas :: Int -> String -> (Int, String)
385 count_commas n (',' : cs) = count_commas (n+1) cs
386 count_commas n cs = (n,cs)
388 unencodedChar :: Char -> Bool -- True for chars that don't need encoding
389 unencodedChar 'Z' = False
390 unencodedChar 'z' = False
391 unencodedChar c = isAlphaNum c
393 encode_ch :: Char -> String
394 encode_ch c | unencodedChar c = [c] -- Common case first
397 encode_ch '(' = "ZL" -- Needed for things like (,), and (->)
398 encode_ch ')' = "ZR" -- For symmetry with (
418 encode_ch '\'' = "zq"
419 encode_ch '\\' = "zr"
424 encode_ch c = 'z' : shows (ord c) "U"
427 latex_encode (c:cs) | c `elem` "#$%&_^{}" = "\\" ++ c:(latex_encode cs)
428 latex_encode ('~':cs) = "\\verb!~!" ++ (latex_encode cs)
429 latex_encode ('\\':cs) = "$\\backslash$" ++ (latex_encode cs)
430 latex_encode (c:cs) = c:(latex_encode cs)
432 gen_wrappers :: Info -> String
433 gen_wrappers (Info _ entries)
434 = "{-# OPTIONS -fno-implicit-prelude #-}\n"
435 -- Dependencies on Prelude must be explicit in libraries/base, but we
436 -- don't need the Prelude here so we add -fno-implicit-prelude.
437 ++ "module GHC.PrimopWrappers where\n"
438 ++ "import qualified GHC.Prim\n"
439 ++ unlines (map f (filter (not.dodgy) (filter is_primop entries)))
441 f spec = let args = map (\n -> "a" ++ show n) [1 .. arity (ty spec)]
442 src_name = wrap (name spec)
443 in "{-# NOINLINE " ++ src_name ++ " #-}\n" ++
444 src_name ++ " " ++ unwords args
445 ++ " = (GHC.Prim." ++ name spec ++ ") " ++ unwords args
446 wrap nm | isLower (head nm) = nm
447 | otherwise = "(" ++ nm ++ ")"
451 [-- C code generator can't handle these
454 -- not interested in parallel support
455 "par#", "parGlobal#", "parLocal#", "parAt#",
456 "parAtAbs#", "parAtRel#", "parAtForNow#"
459 gen_primop_list :: Info -> String
460 gen_primop_list (Info _ entries)
462 [ " [" ++ cons first ]
464 map (\p -> " , " ++ cons p) rest
467 ) where (first:rest) = filter is_primop entries
469 gen_primop_tag :: Info -> String
470 gen_primop_tag (Info _ entries)
471 = unlines (max_def_type : max_def :
472 tagOf_type : zipWith f primop_entries [1 :: Int ..])
474 primop_entries = filter is_primop entries
475 tagOf_type = "tagOf_PrimOp :: PrimOp -> FastInt"
476 f i n = "tagOf_PrimOp " ++ cons i ++ " = _ILIT(" ++ show n ++ ")"
477 max_def_type = "maxPrimOpTag :: Int"
478 max_def = "maxPrimOpTag = " ++ show (length primop_entries)
480 gen_data_decl :: Info -> String
481 gen_data_decl (Info _ entries)
482 = let conss = map cons (filter is_primop entries)
483 in "data PrimOp\n = " ++ head conss ++ "\n"
484 ++ unlines (map (" | "++) (tail conss))
486 gen_switch_from_attribs :: String -> String -> Info -> String
487 gen_switch_from_attribs attrib_name fn_name (Info defaults entries)
488 = let defv = lookup_attrib attrib_name defaults
489 alternatives = catMaybes (map mkAlt (filter is_primop entries))
491 getAltRhs (OptionFalse _) = "False"
492 getAltRhs (OptionTrue _) = "True"
493 getAltRhs (OptionString _ s) = s
496 = case lookup_attrib attrib_name (opts po) of
498 Just xx -> Just (fn_name ++ " " ++ cons po ++ " = " ++ getAltRhs xx)
502 Nothing -> error ("gen_switch_from: " ++ attrib_name)
504 -> unlines alternatives
505 ++ fn_name ++ " _ = " ++ getAltRhs xx ++ "\n"
507 ------------------------------------------------------------------
508 -- Create PrimOpInfo text from PrimOpSpecs -----------------------
509 ------------------------------------------------------------------
511 gen_primop_info :: Info -> String
512 gen_primop_info (Info _ entries)
513 = unlines (map mkPOItext (filter is_primop entries))
515 mkPOItext :: Entry -> String
516 mkPOItext i = mkPOI_LHS_text i ++ mkPOI_RHS_text i
518 mkPOI_LHS_text :: Entry -> String
520 = "primOpInfo " ++ cons i ++ " = "
522 mkPOI_RHS_text :: Entry -> String
528 -> "mkCompare " ++ sl_name i ++ ppType t1
529 _ -> error "Type error in comparison op"
533 -> "mkMonadic " ++ sl_name i ++ ppType t1
534 _ -> error "Type error in monadic op"
538 -> "mkDyadic " ++ sl_name i ++ ppType t1
539 _ -> error "Type error in dyadic op"
541 -> let (argTys, resTy) = flatTys (ty i)
542 tvs = nub (tvsIn (ty i))
544 "mkGenPrimOp " ++ sl_name i ++ " "
545 ++ listify (map ppTyVar tvs) ++ " "
546 ++ listify (map ppType argTys) ++ " "
547 ++ "(" ++ ppType resTy ++ ")"
549 sl_name :: Entry -> String
550 sl_name i = "FSLIT(\"" ++ name i ++ "\") "
552 ppTyVar :: String -> String
553 ppTyVar "a" = "alphaTyVar"
554 ppTyVar "b" = "betaTyVar"
555 ppTyVar "c" = "gammaTyVar"
556 ppTyVar "s" = "deltaTyVar"
557 ppTyVar "o" = "openAlphaTyVar"
558 ppTyVar _ = error "Unknown type var"
560 ppType :: Ty -> String
561 ppType (TyApp "Bool" []) = "boolTy"
563 ppType (TyApp "Int#" []) = "intPrimTy"
564 ppType (TyApp "Int32#" []) = "int32PrimTy"
565 ppType (TyApp "Int64#" []) = "int64PrimTy"
566 ppType (TyApp "Char#" []) = "charPrimTy"
567 ppType (TyApp "Word#" []) = "wordPrimTy"
568 ppType (TyApp "Word32#" []) = "word32PrimTy"
569 ppType (TyApp "Word64#" []) = "word64PrimTy"
570 ppType (TyApp "Addr#" []) = "addrPrimTy"
571 ppType (TyApp "Float#" []) = "floatPrimTy"
572 ppType (TyApp "Double#" []) = "doublePrimTy"
573 ppType (TyApp "ByteArr#" []) = "byteArrayPrimTy"
574 ppType (TyApp "RealWorld" []) = "realWorldTy"
575 ppType (TyApp "ThreadId#" []) = "threadIdPrimTy"
576 ppType (TyApp "ForeignObj#" []) = "foreignObjPrimTy"
577 ppType (TyApp "BCO#" []) = "bcoPrimTy"
578 ppType (TyApp "()" []) = "unitTy" -- unitTy is TysWiredIn's name for ()
580 ppType (TyVar "a") = "alphaTy"
581 ppType (TyVar "b") = "betaTy"
582 ppType (TyVar "c") = "gammaTy"
583 ppType (TyVar "s") = "deltaTy"
584 ppType (TyVar "o") = "openAlphaTy"
585 ppType (TyApp "State#" [x]) = "mkStatePrimTy " ++ ppType x
586 ppType (TyApp "MutVar#" [x,y]) = "mkMutVarPrimTy " ++ ppType x
588 ppType (TyApp "MutArr#" [x,y]) = "mkMutableArrayPrimTy " ++ ppType x
591 ppType (TyApp "MutByteArr#" [x]) = "mkMutableByteArrayPrimTy "
594 ppType (TyApp "Array#" [x]) = "mkArrayPrimTy " ++ ppType x
597 ppType (TyApp "Weak#" [x]) = "mkWeakPrimTy " ++ ppType x
598 ppType (TyApp "StablePtr#" [x]) = "mkStablePtrPrimTy " ++ ppType x
599 ppType (TyApp "StableName#" [x]) = "mkStableNamePrimTy " ++ ppType x
601 ppType (TyApp "MVar#" [x,y]) = "mkMVarPrimTy " ++ ppType x
603 ppType (TyApp "TVar#" [x,y]) = "mkTVarPrimTy " ++ ppType x
605 ppType (TyUTup ts) = "(mkTupleTy Unboxed " ++ show (length ts)
607 ++ listify (map ppType ts) ++ ")"
609 ppType (TyF s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))"
612 = error ("ppType: can't handle: " ++ show other ++ "\n")
614 listify :: [String] -> String
615 listify ss = "[" ++ concat (intersperse ", " ss) ++ "]"
617 flatTys :: Ty -> ([Ty],Ty)
618 flatTys (TyF t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t)
619 flatTys other = ([],other)
621 tvsIn :: Ty -> [TyVar]
622 tvsIn (TyF t1 t2) = tvsIn t1 ++ tvsIn t2
623 tvsIn (TyApp _ tys) = concatMap tvsIn tys
624 tvsIn (TyVar tv) = [tv]
625 tvsIn (TyUTup tys) = concatMap tvsIn tys
628 arity = length . fst . flatTys