2 ------------------------------------------------------------------
3 -- A primop-table mangling program --
4 ------------------------------------------------------------------
8 #if __GLASGOW_HASKELL__ >= 504
9 import Text.ParserCombinators.Parsec
17 import System ( getArgs )
18 import Maybe ( catMaybes )
20 main = getArgs >>= \args ->
21 if length args /= 1 || head args `notElem` known_args
22 then error ("usage: genprimopcode command < primops.txt > ...\n"
23 ++ " where command is one of\n"
24 ++ unlines (map (" "++) known_args)
28 let pres = parse pTop "" s
30 Left err -> error ("parse error at " ++ (show err))
32 -> myseq (sanityTop p_o_specs) (
36 -> putStr (gen_data_decl p_o_specs)
39 -> putStr (gen_switch_from_attribs
41 "primOpHasSideEffects" p_o_specs)
44 -> putStr (gen_switch_from_attribs
46 "primOpOutOfLine" p_o_specs)
49 -> putStr (gen_switch_from_attribs
51 "commutableOp" p_o_specs)
54 -> putStr (gen_switch_from_attribs
56 "primOpNeedsWrapper" p_o_specs)
59 -> putStr (gen_switch_from_attribs
61 "primOpCanFail" p_o_specs)
64 -> putStr (gen_switch_from_attribs
66 "primOpStrictness" p_o_specs)
69 -> putStr (gen_switch_from_attribs
71 "primOpUsg" p_o_specs)
73 "--primop-primop-info"
74 -> putStr (gen_primop_info p_o_specs)
77 -> putStr (gen_primop_tag p_o_specs)
80 -> putStr (gen_primop_list p_o_specs)
82 "--make-haskell-wrappers"
83 -> putStr (gen_wrappers p_o_specs)
86 -> putStr (gen_latex_doc p_o_specs)
99 "--primop-primop-info",
102 "--make-haskell-wrappers",
106 ------------------------------------------------------------------
107 -- Code generators -----------------------------------------------
108 ------------------------------------------------------------------
110 gen_latex_doc (Info defaults entries)
111 = "\\primopdefaults{"
112 ++ mk_options defaults
114 ++ (concat (map mk_entry entries))
115 where mk_entry (PrimOpSpec {cons=cons,name=name,ty=ty,cat=cat,desc=desc,opts=opts}) =
117 ++ latex_encode cons ++ "}{"
118 ++ latex_encode name ++ "}{"
119 ++ latex_encode (zencode name) ++ "}{"
120 ++ latex_encode (show cat) ++ "}{"
121 ++ latex_encode (mk_source_ty ty) ++ "}{"
122 ++ latex_encode (mk_core_ty ty) ++ "}{"
126 mk_entry (Section {title=title,desc=desc}) =
128 ++ latex_encode title ++ "}{"
130 mk_source_ty t = pty t
131 where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
133 pbty (TyApp tc ts) = tc ++ (concat (map (' ':) (map paty ts)))
134 pbty (TyUTup ts) = "(# " ++ (concat (intersperse "," (map pty ts))) ++ " #)"
137 paty t = "(" ++ pty t ++ ")"
139 mk_core_ty t = foralls ++ (pty t)
140 where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
142 pbty (TyApp tc ts) = (zencode tc) ++ (concat (map (' ':) (map paty ts)))
143 pbty (TyUTup ts) = (zencode (utuplenm (length ts))) ++ (concat ((map (' ':) (map paty ts))))
145 paty (TyVar tv) = zencode tv
146 paty (TyApp tc []) = zencode tc
147 paty t = "(" ++ pty t ++ ")"
149 utuplenm n = "(#" ++ (replicate (n-1) ',') ++ "#)"
150 foralls = if tvars == [] then "" else "%forall " ++ (tbinds tvars)
153 tbinds ("o":tbs) = "(o::?) " ++ (tbinds tbs)
154 tbinds (tv:tbs) = tv ++ " " ++ (tbinds tbs)
155 tvars_of (TyF t1 t2) = tvars_of t1 `union` tvars_of t2
156 tvars_of (TyApp tc ts) = foldl union [] (map tvars_of ts)
157 tvars_of (TyUTup ts) = foldr union [] (map tvars_of ts)
158 tvars_of (TyVar tv) = [tv]
162 ++ mk_has_side_effects opts ++ "}{"
163 ++ mk_out_of_line opts ++ "}{"
164 ++ mk_commutable opts ++ "}{"
165 ++ mk_needs_wrapper opts ++ "}{"
166 ++ mk_can_fail opts ++ "}{"
167 ++ latex_encode (mk_strictness opts) ++ "}{"
168 ++ latex_encode (mk_usage opts)
171 mk_has_side_effects opts = mk_bool_opt opts "has_side_effects" "Has side effects." "Has no side effects."
172 mk_out_of_line opts = mk_bool_opt opts "out_of_line" "Implemented out of line." "Implemented in line."
173 mk_commutable opts = mk_bool_opt opts "commutable" "Commutable." "Not commutable."
174 mk_needs_wrapper opts = mk_bool_opt opts "needs_wrapper" "Needs wrapper." "Needs no wrapper."
175 mk_can_fail opts = mk_bool_opt opts "can_fail" "Can fail." "Cannot fail."
177 mk_bool_opt opts opt_name if_true if_false =
178 case lookup_attrib opt_name opts of
179 Just (OptionTrue _) -> if_true
180 Just (OptionFalse _) -> if_false
184 case lookup_attrib "strictness" opts of
185 Just (OptionString _ s) -> s -- for now
189 case lookup_attrib "usage" opts of
190 Just (OptionString _ s) -> s -- for now
194 case maybe_tuple cs of
195 Just n -> n -- Tuples go to Z2T etc
196 Nothing -> concat (map encode_ch cs)
198 maybe_tuple "(# #)" = Just("Z1H")
199 maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of
200 (n, '#' : ')' : cs) -> Just ('Z' : shows (n+1) "H")
202 maybe_tuple "()" = Just("Z0T")
203 maybe_tuple ('(' : cs) = case count_commas (0::Int) cs of
204 (n, ')' : cs) -> Just ('Z' : shows (n+1) "T")
206 maybe_tuple other = Nothing
208 count_commas :: Int -> String -> (Int, String)
209 count_commas n (',' : cs) = count_commas (n+1) cs
210 count_commas n cs = (n,cs)
212 unencodedChar :: Char -> Bool -- True for chars that don't need encoding
213 unencodedChar 'Z' = False
214 unencodedChar 'z' = False
215 unencodedChar c = isAlphaNum c
217 encode_ch :: Char -> String
218 encode_ch c | unencodedChar c = [c] -- Common case first
221 encode_ch '(' = "ZL" -- Needed for things like (,), and (->)
222 encode_ch ')' = "ZR" -- For symmetry with (
242 encode_ch '\'' = "zq"
243 encode_ch '\\' = "zr"
248 encode_ch c = 'z' : shows (ord c) "U"
251 latex_encode (c:cs) | c `elem` "#$%&_^{}" = "\\" ++ c:(latex_encode cs)
252 latex_encode ('~':cs) = "\\verb!~!" ++ (latex_encode cs)
253 latex_encode ('\\':cs) = "$\\backslash$" ++ (latex_encode cs)
254 latex_encode (c:cs) = c:(latex_encode cs)
256 gen_wrappers (Info defaults entries)
257 = "{-# OPTIONS -fno-implicit-prelude #-}\n"
258 -- Dependencies on Prelude must be explicit in libraries/base, but we
259 -- don't need the Prelude here so we add -fno-implicit-prelude.
260 ++ "module GHC.PrimopWrappers where\n"
261 ++ "import qualified GHC.Prim\n"
262 ++ unlines (map f (filter (not.dodgy) (filter is_primop entries)))
264 f spec = let args = map (\n -> "a" ++ show n) [1 .. arity (ty spec)]
265 src_name = wrap (name spec)
266 in "{-# NOINLINE " ++ src_name ++ " #-}\n" ++
267 src_name ++ " " ++ unwords args
268 ++ " = (GHC.Prim." ++ name spec ++ ") " ++ unwords args
269 wrap nm | isLower (head nm) = nm
270 | otherwise = "(" ++ nm ++ ")"
274 [-- C code generator can't handle these
277 -- not interested in parallel support
278 "par#", "parGlobal#", "parLocal#", "parAt#",
279 "parAtAbs#", "parAtRel#", "parAtForNow#"
283 gen_primop_list (Info defaults entries)
285 [ " [" ++ cons first ]
287 map (\pi -> " , " ++ cons pi) rest
290 ) where (first:rest) = filter is_primop entries
292 gen_primop_tag (Info defaults entries)
293 = unlines (max_def : zipWith f primop_entries [1..])
295 primop_entries = filter is_primop entries
296 f i n = "tagOf_PrimOp " ++ cons i
297 ++ " = _ILIT(" ++ show n ++ ") :: FastInt"
298 max_def = "maxPrimOpTag = " ++ show (length primop_entries) ++ " :: Int"
300 gen_data_decl (Info defaults entries)
301 = let conss = map cons (filter is_primop entries)
302 in "data PrimOp\n = " ++ head conss ++ "\n"
303 ++ unlines (map (" | "++) (tail conss))
305 gen_switch_from_attribs :: String -> String -> Info -> String
306 gen_switch_from_attribs attrib_name fn_name (Info defaults entries)
307 = let defv = lookup_attrib attrib_name defaults
308 alts = catMaybes (map mkAlt (filter is_primop entries))
310 getAltRhs (OptionFalse _) = "False"
311 getAltRhs (OptionTrue _) = "True"
312 getAltRhs (OptionString _ s) = s
315 = case lookup_attrib attrib_name (opts po) of
317 Just xx -> Just (fn_name ++ " " ++ cons po ++ " = " ++ getAltRhs xx)
321 Nothing -> error ("gen_switch_from: " ++ attrib_name)
324 ++ fn_name ++ " other = " ++ getAltRhs xx ++ "\n"
326 ------------------------------------------------------------------
327 -- Create PrimOpInfo text from PrimOpSpecs -----------------------
328 ------------------------------------------------------------------
331 gen_primop_info (Info defaults entries)
332 = unlines (map mkPOItext (filter is_primop entries))
334 mkPOItext i = mkPOI_LHS_text i ++ mkPOI_RHS_text i
337 = "primOpInfo " ++ cons i ++ " = "
344 -> "mkCompare " ++ sl_name i ++ ppType t1
348 -> "mkMonadic " ++ sl_name i ++ ppType t1
352 -> "mkDyadic " ++ sl_name i ++ ppType t1
354 -> let (argTys, resTy) = flatTys (ty i)
355 tvs = nub (tvsIn (ty i))
357 "mkGenPrimOp " ++ sl_name i ++ " "
358 ++ listify (map ppTyVar tvs) ++ " "
359 ++ listify (map ppType argTys) ++ " "
360 ++ "(" ++ ppType resTy ++ ")"
362 sl_name i = "FSLIT(\"" ++ name i ++ "\") "
364 ppTyVar "a" = "alphaTyVar"
365 ppTyVar "b" = "betaTyVar"
366 ppTyVar "c" = "gammaTyVar"
367 ppTyVar "s" = "deltaTyVar"
368 ppTyVar "o" = "openAlphaTyVar"
371 ppType (TyApp "Bool" []) = "boolTy"
373 ppType (TyApp "Int#" []) = "intPrimTy"
374 ppType (TyApp "Int32#" []) = "int32PrimTy"
375 ppType (TyApp "Int64#" []) = "int64PrimTy"
376 ppType (TyApp "Char#" []) = "charPrimTy"
377 ppType (TyApp "Word#" []) = "wordPrimTy"
378 ppType (TyApp "Word32#" []) = "word32PrimTy"
379 ppType (TyApp "Word64#" []) = "word64PrimTy"
380 ppType (TyApp "Addr#" []) = "addrPrimTy"
381 ppType (TyApp "Float#" []) = "floatPrimTy"
382 ppType (TyApp "Double#" []) = "doublePrimTy"
383 ppType (TyApp "ByteArr#" []) = "byteArrayPrimTy"
384 ppType (TyApp "RealWorld" []) = "realWorldTy"
385 ppType (TyApp "ThreadId#" []) = "threadIdPrimTy"
386 ppType (TyApp "ForeignObj#" []) = "foreignObjPrimTy"
387 ppType (TyApp "BCO#" []) = "bcoPrimTy"
388 ppType (TyApp "()" []) = "unitTy" -- unitTy is TysWiredIn's name for ()
391 ppType (TyVar "a") = "alphaTy"
392 ppType (TyVar "b") = "betaTy"
393 ppType (TyVar "c") = "gammaTy"
394 ppType (TyVar "s") = "deltaTy"
395 ppType (TyVar "o") = "openAlphaTy"
396 ppType (TyApp "State#" [x]) = "mkStatePrimTy " ++ ppType x
397 ppType (TyApp "MutVar#" [x,y]) = "mkMutVarPrimTy " ++ ppType x
399 ppType (TyApp "MutArr#" [x,y]) = "mkMutableArrayPrimTy " ++ ppType x
402 ppType (TyApp "MutByteArr#" [x]) = "mkMutableByteArrayPrimTy "
405 ppType (TyApp "Array#" [x]) = "mkArrayPrimTy " ++ ppType x
408 ppType (TyApp "Weak#" [x]) = "mkWeakPrimTy " ++ ppType x
409 ppType (TyApp "StablePtr#" [x]) = "mkStablePtrPrimTy " ++ ppType x
410 ppType (TyApp "StableName#" [x]) = "mkStableNamePrimTy " ++ ppType x
412 ppType (TyApp "MVar#" [x,y]) = "mkMVarPrimTy " ++ ppType x
414 ppType (TyUTup ts) = "(mkTupleTy Unboxed " ++ show (length ts)
416 ++ listify (map ppType ts) ++ ")"
418 ppType (TyF s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))"
421 = error ("ppType: can't handle: " ++ show other ++ "\n")
423 listify :: [String] -> String
424 listify ss = "[" ++ concat (intersperse ", " ss) ++ "]"
426 flatTys (TyF t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t)
427 flatTys other = ([],other)
429 tvsIn (TyF t1 t2) = tvsIn t1 ++ tvsIn t2
430 tvsIn (TyApp tc tys) = concatMap tvsIn tys
431 tvsIn (TyVar tv) = [tv]
432 tvsIn (TyUTup tys) = concatMap tvsIn tys
434 arity = length . fst . flatTys
437 ------------------------------------------------------------------
438 -- Abstract syntax -----------------------------------------------
439 ------------------------------------------------------------------
441 -- info for all primops; the totality of the info in primops.txt(.pp)
443 = Info [Option] [Entry] -- defaults, primops
446 -- info for one primop
448 = PrimOpSpec { cons :: String, -- PrimOp name
449 name :: String, -- name in prog text
451 cat :: Category, -- category
452 desc :: String, -- description
453 opts :: [Option] } -- default overrides
454 | Section { title :: String, -- section title
455 desc :: String } -- description
458 is_primop (PrimOpSpec _ _ _ _ _ _) = True
461 -- a binding of property to value
463 = OptionFalse String -- name = False
464 | OptionTrue String -- name = True
465 | OptionString String String -- name = { ... unparsed stuff ... }
468 -- categorises primops
470 = Dyadic | Monadic | Compare | GenPrimOp
478 | TyUTup [Ty] -- unboxed tuples; just a TyCon really,
479 -- but convenient like this
486 ------------------------------------------------------------------
487 -- Sanity checking -----------------------------------------------
488 ------------------------------------------------------------------
490 {- Do some simple sanity checks:
491 * all the default field names are unique
492 * for each PrimOpSpec, all override field names are unique
493 * for each PrimOpSpec, all overriden field names
494 have a corresponding default value
495 * that primop types correspond in certain ways to the
496 Category: eg if Comparison, the type must be of the form
498 Dies with "error" if there's a problem, else returns ().
501 myseqAll (():ys) x = myseqAll ys x
504 sanityTop :: Info -> ()
505 sanityTop (Info defs entries)
506 = let opt_names = map get_attrib_name defs
507 primops = filter is_primop entries
509 if length opt_names /= length (nub opt_names)
510 then error ("non-unique default attribute names: " ++ show opt_names ++ "\n")
511 else myseqAll (map (sanityPrimOp opt_names) primops) ()
513 sanityPrimOp def_names p
514 = let p_names = map get_attrib_name (opts p)
516 = length p_names == length (nub p_names)
517 && all (`elem` def_names) p_names
518 ty_ok = sane_ty (cat p) (ty p)
521 then error ("attribute names are non-unique or have no default in\n" ++
522 "info for primop " ++ cons p ++ "\n")
525 then error ("type of primop " ++ cons p ++ " doesn't make sense w.r.t" ++
526 " category " ++ show (cat p) ++ "\n")
529 sane_ty Compare (TyF t1 (TyF t2 td))
530 | t1 == t2 && td == TyApp "Bool" [] = True
531 sane_ty Monadic (TyF t1 td)
533 sane_ty Dyadic (TyF t1 (TyF t2 td))
534 | t1 == t2 && t2 == t2 = True
535 sane_ty GenPrimOp any_old_thing
540 get_attrib_name (OptionFalse nm) = nm
541 get_attrib_name (OptionTrue nm) = nm
542 get_attrib_name (OptionString nm _) = nm
544 lookup_attrib nm [] = Nothing
545 lookup_attrib nm (a:as)
546 = if get_attrib_name a == nm then Just a else lookup_attrib nm as
548 ------------------------------------------------------------------
549 -- The parser ----------------------------------------------------
550 ------------------------------------------------------------------
552 -- Due to lack of proper lexing facilities, a hack to zap any
555 pTop = then4 (\_ ds es _ -> Info ds es)
556 pCommentAndWhitespace pDefaults (many pEntry)
557 (lit "thats_all_folks")
559 pEntry :: Parser Entry
561 = alts [pPrimOpSpec, pSection]
563 pSection :: Parser Entry
564 pSection = then3 (\_ n d -> Section {title = n, desc = d})
565 (lit "section") stringLiteral pDesc
567 pDefaults :: Parser [Option]
568 pDefaults = then2 sel22 (lit "defaults") (many pOption)
570 pOption :: Parser Option
573 then3 (\nm eq ff -> OptionFalse nm) pName (lit "=") (lit "False"),
574 then3 (\nm eq tt -> OptionTrue nm) pName (lit "=") (lit "True"),
575 then3 (\nm eq zz -> OptionString nm zz)
576 pName (lit "=") pStuffBetweenBraces
579 pPrimOpSpec :: Parser Entry
581 = then7 (\_ c n k t d o -> PrimOpSpec { cons = c, name = n, ty = t,
582 cat = k, desc = d, opts = o } )
583 (lit "primop") pConstructor stringLiteral
584 pCategory pType pDesc pOptions
586 pOptions :: Parser [Option]
587 pOptions = optdef [] (then2 sel22 (lit "with") (many pOption))
589 pCategory :: Parser Category
592 apply (const Dyadic) (lit "Dyadic"),
593 apply (const Monadic) (lit "Monadic"),
594 apply (const Compare) (lit "Compare"),
595 apply (const GenPrimOp) (lit "GenPrimOp")
598 pDesc :: Parser String
599 pDesc = optdef "" pStuffBetweenBraces
601 pStuffBetweenBraces :: Parser String
607 return (concat ass) )
609 pInsides :: Parser String
612 stuff <- many pInsides
614 return ("{" ++ (concat stuff) ++ "}"))
616 (do c <- satisfy (/= '}')
626 pType = then2 (\t maybe_tt -> case maybe_tt of
630 (opt (then2 sel22 (lit "->") pType))
633 paT = alts [ then2 TyApp pTycon (many ppT),
635 then3 sel23 (lit "(") pType (lit ")"),
639 -- the magic bit in the middle is: T (,T)* so to speak
641 = then3 (\ _ ts _ -> TyUTup ts)
643 (then2 (:) pType (many (then2 sel22 (lit ",") pType)))
647 ppT = alts [apply TyVar pTyvar,
648 apply (\tc -> TyApp tc []) pTycon
651 pTyvar = sat (`notElem` ["section","primop","with"]) pName
652 pTycon = alts [pConstructor, lexeme (string "()")]
653 pName = lexeme (then2 (:) lower (many isIdChar))
654 pConstructor = lexeme (then2 (:) upper (many isIdChar))
656 isIdChar = satisfy (`elem` idChars)
657 idChars = ['a' .. 'z'] ++ ['A' .. 'Z'] ++ ['0' .. '9'] ++ "#_"
665 ------------------------------------------------------------------
666 -- Helpful additions to Daan's parser stuff ----------------------
667 ------------------------------------------------------------------
670 alts (p1:p2:ps) = (try p1) <|> alts (p2:ps)
673 = do x1 <- p1 ; x2 <- p2 ; return (f x1 x2)
675 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; return (f x1 x2 x3)
677 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; return (f x1 x2 x3 x4)
678 then5 f p1 p2 p3 p4 p5
679 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5
680 return (f x1 x2 x3 x4 x5)
681 then6 f p1 p2 p3 p4 p5 p6
682 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5 ; x6 <- p6
683 return (f x1 x2 x3 x4 x5 x6)
684 then7 f p1 p2 p3 p4 p5 p6 p7
685 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5 ; x6 <- p6 ; x7 <- p7
686 return (f x1 x2 x3 x4 x5 x6 x7)
688 = (do x <- p; return (Just x)) <|> return Nothing
690 = (do x <- p; return x) <|> return d
695 apply f p = liftM f p
697 -- Hacks for zapping whitespace and comments, unfortunately needed
698 -- because Daan won't let us have a lexer before the parser :-(
699 lexeme :: Parser p -> Parser p
700 lexeme p = then2 sel12 p pCommentAndWhitespace
702 lit :: String -> Parser ()
703 lit s = apply (const ()) (lexeme (string s))
705 pCommentAndWhitespace :: Parser ()
706 pCommentAndWhitespace
707 = apply (const ()) (many (alts [pLineComment,
708 apply (const ()) (satisfy isSpace)]))
712 pLineComment :: Parser ()
714 = try (then3 (\_ _ _ -> ()) (string "--") (many (satisfy (/= '\n'))) (char '\n'))
716 stringLiteral :: Parser String
717 stringLiteral = lexeme (
718 do { between (char '"')
719 (char '"' <?> "end of string")
722 <?> "literal string")
726 ------------------------------------------------------------------
728 ------------------------------------------------------------------