2 ------------------------------------------------------------------
3 -- A primop-table mangling program --
4 ------------------------------------------------------------------
12 import System ( getArgs )
13 import Maybe ( catMaybes )
15 main = getArgs >>= \args ->
16 if length args /= 1 || head args `notElem` known_args
17 then error ("usage: genprimopcode command < primops.txt > ...\n"
18 ++ " where command is one of\n"
19 ++ unlines (map (" "++) known_args)
23 let pres = parse pTop "" s
25 Left err -> error ("parse error at " ++ (show err))
27 -> myseq (sanityTop p_o_specs) (
31 -> putStr (gen_data_decl p_o_specs)
34 -> putStr (gen_switch_from_attribs
36 "primOpHasSideEffects" p_o_specs)
39 -> putStr (gen_switch_from_attribs
41 "primOpOutOfLine" p_o_specs)
44 -> putStr (gen_switch_from_attribs
46 "commutableOp" p_o_specs)
49 -> putStr (gen_switch_from_attribs
51 "primOpNeedsWrapper" p_o_specs)
54 -> putStr (gen_switch_from_attribs
56 "primOpCanFail" p_o_specs)
59 -> putStr (gen_switch_from_attribs
61 "primOpStrictness" p_o_specs)
64 -> putStr (gen_switch_from_attribs
66 "primOpUsg" p_o_specs)
68 "--primop-primop-info"
69 -> putStr (gen_primop_info p_o_specs)
72 -> putStr (gen_primop_tag p_o_specs)
75 -> putStr (gen_primop_list p_o_specs)
77 "--make-haskell-wrappers"
78 -> putStr (gen_wrappers p_o_specs)
81 -> putStr (gen_latex_doc p_o_specs)
94 "--primop-primop-info",
97 "--make-haskell-wrappers",
101 ------------------------------------------------------------------
102 -- Code generators -----------------------------------------------
103 ------------------------------------------------------------------
105 gen_latex_doc (Info defaults entries)
106 = "\\primopdefaults{"
107 ++ mk_options defaults
109 ++ (concat (map mk_entry entries))
110 where mk_entry (PrimOpSpec {cons=cons,name=name,ty=ty,cat=cat,desc=desc,opts=opts}) =
112 ++ latex_encode cons ++ "}{"
113 ++ latex_encode name ++ "}{"
114 ++ latex_encode (zencode name) ++ "}{"
115 ++ latex_encode (show cat) ++ "}{"
116 ++ latex_encode (mk_source_ty ty) ++ "}{"
117 ++ latex_encode (mk_core_ty ty) ++ "}{"
121 mk_entry (Section {title=title,desc=desc}) =
123 ++ latex_encode title ++ "}{"
125 mk_source_ty t = pty t
126 where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
128 pbty (TyApp tc ts) = tc ++ (concat (map (' ':) (map paty ts)))
129 pbty (TyUTup ts) = "(# " ++ (concat (intersperse "," (map pty ts))) ++ " #)"
132 paty t = "(" ++ pty t ++ ")"
134 mk_core_ty t = foralls ++ (pty t)
135 where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
137 pbty (TyApp tc ts) = (zencode tc) ++ (concat (map (' ':) (map paty ts)))
138 pbty (TyUTup ts) = (zencode (utuplenm (length ts))) ++ (concat ((map (' ':) (map paty ts))))
140 paty (TyVar tv) = zencode tv
141 paty (TyApp tc []) = zencode tc
142 paty t = "(" ++ pty t ++ ")"
144 utuplenm n = "(#" ++ (replicate (n-1) ',') ++ "#)"
145 foralls = if tvars == [] then "" else "%forall " ++ (tbinds tvars)
148 tbinds ("o":tbs) = "(o::?) " ++ (tbinds tbs)
149 tbinds (tv:tbs) = tv ++ " " ++ (tbinds tbs)
150 tvars_of (TyF t1 t2) = tvars_of t1 `union` tvars_of t2
151 tvars_of (TyApp tc ts) = foldl union [] (map tvars_of ts)
152 tvars_of (TyUTup ts) = foldr union [] (map tvars_of ts)
153 tvars_of (TyVar tv) = [tv]
157 ++ mk_has_side_effects opts ++ "}{"
158 ++ mk_out_of_line opts ++ "}{"
159 ++ mk_commutable opts ++ "}{"
160 ++ mk_needs_wrapper opts ++ "}{"
161 ++ mk_can_fail opts ++ "}{"
162 ++ latex_encode (mk_strictness opts) ++ "}{"
163 ++ latex_encode (mk_usage opts)
166 mk_has_side_effects opts = mk_bool_opt opts "has_side_effects" "Has side effects." "Has no side effects."
167 mk_out_of_line opts = mk_bool_opt opts "out_of_line" "Implemented out of line." "Implemented in line."
168 mk_commutable opts = mk_bool_opt opts "commutable" "Commutable." "Not commutable."
169 mk_needs_wrapper opts = mk_bool_opt opts "needs_wrapper" "Needs wrapper." "Needs no wrapper."
170 mk_can_fail opts = mk_bool_opt opts "can_fail" "Can fail." "Cannot fail."
172 mk_bool_opt opts opt_name if_true if_false =
173 case lookup_attrib opt_name opts of
174 Just (OptionTrue _) -> if_true
175 Just (OptionFalse _) -> if_false
179 case lookup_attrib "strictness" opts of
180 Just (OptionString _ s) -> s -- for now
184 case lookup_attrib "usage" opts of
185 Just (OptionString _ s) -> s -- for now
189 case maybe_tuple cs of
190 Just n -> n -- Tuples go to Z2T etc
191 Nothing -> concat (map encode_ch cs)
193 maybe_tuple "(# #)" = Just("Z1H")
194 maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of
195 (n, '#' : ')' : cs) -> Just ('Z' : shows (n+1) "H")
197 maybe_tuple "()" = Just("Z0T")
198 maybe_tuple ('(' : cs) = case count_commas (0::Int) cs of
199 (n, ')' : cs) -> Just ('Z' : shows (n+1) "T")
201 maybe_tuple other = Nothing
203 count_commas :: Int -> String -> (Int, String)
204 count_commas n (',' : cs) = count_commas (n+1) cs
205 count_commas n cs = (n,cs)
207 unencodedChar :: Char -> Bool -- True for chars that don't need encoding
208 unencodedChar 'Z' = False
209 unencodedChar 'z' = False
210 unencodedChar c = isAlphaNum c
212 encode_ch :: Char -> String
213 encode_ch c | unencodedChar c = [c] -- Common case first
216 encode_ch '(' = "ZL" -- Needed for things like (,), and (->)
217 encode_ch ')' = "ZR" -- For symmetry with (
237 encode_ch '\'' = "zq"
238 encode_ch '\\' = "zr"
243 encode_ch c = 'z' : shows (ord c) "U"
246 latex_encode (c:cs) | c `elem` "#$%&_^{}" = "\\" ++ c:(latex_encode cs)
247 latex_encode ('~':cs) = "\\verb!~!" ++ (latex_encode cs)
248 latex_encode ('\\':cs) = "$\\backslash$" ++ (latex_encode cs)
249 latex_encode (c:cs) = c:(latex_encode cs)
251 gen_wrappers (Info defaults entries)
252 = "{-# OPTIONS -fno-implicit-prelude #-}\n"
253 -- Dependencies on Prelude must be explicit in libraries/base, but we
254 -- don't need the Prelude here so we add -fno-implicit-prelude.
255 ++ "module GHC.PrimopWrappers where\n"
256 ++ "import qualified GHC.Prim\n"
257 ++ unlines (map f (filter (not.dodgy) (filter is_primop entries)))
259 f spec = let args = map (\n -> "a" ++ show n) [1 .. arity (ty spec)]
260 src_name = wrap (name spec)
261 in "{-# NOINLINE " ++ src_name ++ " #-}\n" ++
262 src_name ++ " " ++ unwords args
263 ++ " = (GHC.Prim." ++ name spec ++ ") " ++ unwords args
264 wrap nm | isLower (head nm) = nm
265 | otherwise = "(" ++ nm ++ ")"
269 [-- C code generator can't handle these
272 -- not interested in parallel support
273 "par#", "parGlobal#", "parLocal#", "parAt#",
274 "parAtAbs#", "parAtRel#", "parAtForNow#"
278 gen_primop_list (Info defaults entries)
280 [ " [" ++ cons first ]
282 map (\pi -> " , " ++ cons pi) rest
285 ) where (first:rest) = filter is_primop entries
287 gen_primop_tag (Info defaults entries)
288 = unlines (zipWith f (filter is_primop entries) [1..])
290 f i n = "tagOf_PrimOp " ++ cons i
291 ++ " = _ILIT(" ++ show n ++ ") :: FastInt"
293 gen_data_decl (Info defaults entries)
294 = let conss = map cons (filter is_primop entries)
295 in "data PrimOp\n = " ++ head conss ++ "\n"
296 ++ unlines (map (" | "++) (tail conss))
298 gen_switch_from_attribs :: String -> String -> Info -> String
299 gen_switch_from_attribs attrib_name fn_name (Info defaults entries)
300 = let defv = lookup_attrib attrib_name defaults
301 alts = catMaybes (map mkAlt (filter is_primop entries))
303 getAltRhs (OptionFalse _) = "False"
304 getAltRhs (OptionTrue _) = "True"
305 getAltRhs (OptionString _ s) = s
308 = case lookup_attrib attrib_name (opts po) of
310 Just xx -> Just (fn_name ++ " " ++ cons po ++ " = " ++ getAltRhs xx)
314 Nothing -> error ("gen_switch_from: " ++ attrib_name)
317 ++ fn_name ++ " other = " ++ getAltRhs xx ++ "\n"
319 ------------------------------------------------------------------
320 -- Create PrimOpInfo text from PrimOpSpecs -----------------------
321 ------------------------------------------------------------------
324 gen_primop_info (Info defaults entries)
325 = unlines (map mkPOItext (filter is_primop entries))
327 mkPOItext i = mkPOI_LHS_text i ++ mkPOI_RHS_text i
330 = "primOpInfo " ++ cons i ++ " = "
337 -> "mkCompare " ++ sl_name i ++ ppType t1
341 -> "mkMonadic " ++ sl_name i ++ ppType t1
345 -> "mkDyadic " ++ sl_name i ++ ppType t1
347 -> let (argTys, resTy) = flatTys (ty i)
348 tvs = nub (tvsIn (ty i))
350 "mkGenPrimOp " ++ sl_name i ++ " "
351 ++ listify (map ppTyVar tvs) ++ " "
352 ++ listify (map ppType argTys) ++ " "
353 ++ "(" ++ ppType resTy ++ ")"
355 sl_name i = "SLIT(\"" ++ name i ++ "\") "
357 ppTyVar "a" = "alphaTyVar"
358 ppTyVar "b" = "betaTyVar"
359 ppTyVar "c" = "gammaTyVar"
360 ppTyVar "s" = "deltaTyVar"
361 ppTyVar "o" = "openAlphaTyVar"
364 ppType (TyApp "Bool" []) = "boolTy"
366 ppType (TyApp "Int#" []) = "intPrimTy"
367 ppType (TyApp "Int32#" []) = "int32PrimTy"
368 ppType (TyApp "Int64#" []) = "int64PrimTy"
369 ppType (TyApp "Char#" []) = "charPrimTy"
370 ppType (TyApp "Word#" []) = "wordPrimTy"
371 ppType (TyApp "Word32#" []) = "word32PrimTy"
372 ppType (TyApp "Word64#" []) = "word64PrimTy"
373 ppType (TyApp "Addr#" []) = "addrPrimTy"
374 ppType (TyApp "Float#" []) = "floatPrimTy"
375 ppType (TyApp "Double#" []) = "doublePrimTy"
376 ppType (TyApp "ByteArr#" []) = "byteArrayPrimTy"
377 ppType (TyApp "RealWorld" []) = "realWorldTy"
378 ppType (TyApp "ThreadId#" []) = "threadIdPrimTy"
379 ppType (TyApp "ForeignObj#" []) = "foreignObjPrimTy"
380 ppType (TyApp "BCO#" []) = "bcoPrimTy"
381 ppType (TyApp "Unit" []) = "unitTy" -- dodgy
384 ppType (TyVar "a") = "alphaTy"
385 ppType (TyVar "b") = "betaTy"
386 ppType (TyVar "c") = "gammaTy"
387 ppType (TyVar "s") = "deltaTy"
388 ppType (TyVar "o") = "openAlphaTy"
389 ppType (TyApp "State#" [x]) = "mkStatePrimTy " ++ ppType x
390 ppType (TyApp "MutVar#" [x,y]) = "mkMutVarPrimTy " ++ ppType x
392 ppType (TyApp "MutArr#" [x,y]) = "mkMutableArrayPrimTy " ++ ppType x
395 ppType (TyApp "MutByteArr#" [x]) = "mkMutableByteArrayPrimTy "
398 ppType (TyApp "Array#" [x]) = "mkArrayPrimTy " ++ ppType x
401 ppType (TyApp "Weak#" [x]) = "mkWeakPrimTy " ++ ppType x
402 ppType (TyApp "StablePtr#" [x]) = "mkStablePtrPrimTy " ++ ppType x
403 ppType (TyApp "StableName#" [x]) = "mkStableNamePrimTy " ++ ppType x
405 ppType (TyApp "MVar#" [x,y]) = "mkMVarPrimTy " ++ ppType x
407 ppType (TyUTup ts) = "(mkTupleTy Unboxed " ++ show (length ts)
409 ++ listify (map ppType ts) ++ ")"
411 ppType (TyF s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))"
414 = error ("ppType: can't handle: " ++ show other ++ "\n")
416 listify :: [String] -> String
417 listify ss = "[" ++ concat (intersperse ", " ss) ++ "]"
419 flatTys (TyF t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t)
420 flatTys other = ([],other)
422 tvsIn (TyF t1 t2) = tvsIn t1 ++ tvsIn t2
423 tvsIn (TyApp tc tys) = concatMap tvsIn tys
424 tvsIn (TyVar tv) = [tv]
425 tvsIn (TyUTup tys) = concatMap tvsIn tys
427 arity = length . fst . flatTys
430 ------------------------------------------------------------------
431 -- Abstract syntax -----------------------------------------------
432 ------------------------------------------------------------------
434 -- info for all primops; the totality of the info in primops.txt(.pp)
436 = Info [Option] [Entry] -- defaults, primops
439 -- info for one primop
441 = PrimOpSpec { cons :: String, -- PrimOp name
442 name :: String, -- name in prog text
444 cat :: Category, -- category
445 desc :: String, -- description
446 opts :: [Option] } -- default overrides
447 | Section { title :: String, -- section title
448 desc :: String } -- description
451 is_primop (PrimOpSpec _ _ _ _ _ _) = True
454 -- a binding of property to value
456 = OptionFalse String -- name = False
457 | OptionTrue String -- name = True
458 | OptionString String String -- name = { ... unparsed stuff ... }
461 -- categorises primops
463 = Dyadic | Monadic | Compare | GenPrimOp
471 | TyUTup [Ty] -- unboxed tuples; just a TyCon really,
472 -- but convenient like this
479 ------------------------------------------------------------------
480 -- Sanity checking -----------------------------------------------
481 ------------------------------------------------------------------
483 {- Do some simple sanity checks:
484 * all the default field names are unique
485 * for each PrimOpSpec, all override field names are unique
486 * for each PrimOpSpec, all overriden field names
487 have a corresponding default value
488 * that primop types correspond in certain ways to the
489 Category: eg if Comparison, the type must be of the form
491 Dies with "error" if there's a problem, else returns ().
494 myseqAll (():ys) x = myseqAll ys x
497 sanityTop :: Info -> ()
498 sanityTop (Info defs entries)
499 = let opt_names = map get_attrib_name defs
500 primops = filter is_primop entries
502 if length opt_names /= length (nub opt_names)
503 then error ("non-unique default attribute names: " ++ show opt_names ++ "\n")
504 else myseqAll (map (sanityPrimOp opt_names) primops) ()
506 sanityPrimOp def_names p
507 = let p_names = map get_attrib_name (opts p)
509 = length p_names == length (nub p_names)
510 && all (`elem` def_names) p_names
511 ty_ok = sane_ty (cat p) (ty p)
514 then error ("attribute names are non-unique or have no default in\n" ++
515 "info for primop " ++ cons p ++ "\n")
518 then error ("type of primop " ++ cons p ++ " doesn't make sense w.r.t" ++
519 " category " ++ show (cat p) ++ "\n")
522 sane_ty Compare (TyF t1 (TyF t2 td))
523 | t1 == t2 && td == TyApp "Bool" [] = True
524 sane_ty Monadic (TyF t1 td)
526 sane_ty Dyadic (TyF t1 (TyF t2 td))
527 | t1 == t2 && t2 == t2 = True
528 sane_ty GenPrimOp any_old_thing
533 get_attrib_name (OptionFalse nm) = nm
534 get_attrib_name (OptionTrue nm) = nm
535 get_attrib_name (OptionString nm _) = nm
537 lookup_attrib nm [] = Nothing
538 lookup_attrib nm (a:as)
539 = if get_attrib_name a == nm then Just a else lookup_attrib nm as
541 ------------------------------------------------------------------
542 -- The parser ----------------------------------------------------
543 ------------------------------------------------------------------
545 -- Due to lack of proper lexing facilities, a hack to zap any
548 pTop = then4 (\_ ds es _ -> Info ds es)
549 pCommentAndWhitespace pDefaults (many pEntry)
550 (lit "thats_all_folks")
552 pEntry :: Parser Entry
554 = alts [pPrimOpSpec, pSection]
556 pSection :: Parser Entry
557 pSection = then3 (\_ n d -> Section {title = n, desc = d})
558 (lit "section") stringLiteral pDesc
560 pDefaults :: Parser [Option]
561 pDefaults = then2 sel22 (lit "defaults") (many pOption)
563 pOption :: Parser Option
566 then3 (\nm eq ff -> OptionFalse nm) pName (lit "=") (lit "False"),
567 then3 (\nm eq tt -> OptionTrue nm) pName (lit "=") (lit "True"),
568 then3 (\nm eq zz -> OptionString nm zz)
569 pName (lit "=") pStuffBetweenBraces
572 pPrimOpSpec :: Parser Entry
574 = then7 (\_ c n k t d o -> PrimOpSpec { cons = c, name = n, ty = t,
575 cat = k, desc = d, opts = o } )
576 (lit "primop") pConstructor stringLiteral
577 pCategory pType pDesc pOptions
579 pOptions :: Parser [Option]
580 pOptions = optdef [] (then2 sel22 (lit "with") (many pOption))
582 pCategory :: Parser Category
585 apply (const Dyadic) (lit "Dyadic"),
586 apply (const Monadic) (lit "Monadic"),
587 apply (const Compare) (lit "Compare"),
588 apply (const GenPrimOp) (lit "GenPrimOp")
591 pDesc :: Parser String
592 pDesc = optdef "" pStuffBetweenBraces
594 pStuffBetweenBraces :: Parser String
600 return (concat ass) )
602 pInsides :: Parser String
605 stuff <- many pInsides
607 return ("{" ++ (concat stuff) ++ "}"))
609 (do c <- satisfy (/= '}')
619 pType = then2 (\t maybe_tt -> case maybe_tt of
623 (opt (then2 sel22 (lit "->") pType))
626 paT = alts [ then2 TyApp pTycon (many ppT),
628 then3 sel23 (lit "(") pType (lit ")"),
632 -- the magic bit in the middle is: T (,T)* so to speak
634 = then3 (\ _ ts _ -> TyUTup ts)
636 (then2 (:) pType (many (then2 sel22 (lit ",") pType)))
640 ppT = alts [apply TyVar pTyvar,
641 apply (\tc -> TyApp tc []) pTycon
644 pTyvar = sat (`notElem` ["section","primop","with"]) pName
645 pTycon = pConstructor
646 pName = lexeme (then2 (:) lower (many isIdChar))
647 pConstructor = lexeme (then2 (:) upper (many isIdChar))
649 isIdChar = satisfy (`elem` idChars)
650 idChars = ['a' .. 'z'] ++ ['A' .. 'Z'] ++ ['0' .. '9'] ++ "#_"
658 ------------------------------------------------------------------
659 -- Helpful additions to Daan's parser stuff ----------------------
660 ------------------------------------------------------------------
663 alts (p1:p2:ps) = (try p1) <|> alts (p2:ps)
666 = do x1 <- p1 ; x2 <- p2 ; return (f x1 x2)
668 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; return (f x1 x2 x3)
670 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; return (f x1 x2 x3 x4)
671 then5 f p1 p2 p3 p4 p5
672 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5
673 return (f x1 x2 x3 x4 x5)
674 then6 f p1 p2 p3 p4 p5 p6
675 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5 ; x6 <- p6
676 return (f x1 x2 x3 x4 x5 x6)
677 then7 f p1 p2 p3 p4 p5 p6 p7
678 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5 ; x6 <- p6 ; x7 <- p7
679 return (f x1 x2 x3 x4 x5 x6 x7)
681 = (do x <- p; return (Just x)) <|> return Nothing
683 = (do x <- p; return x) <|> return d
688 apply f p = liftM f p
690 -- Hacks for zapping whitespace and comments, unfortunately needed
691 -- because Daan won't let us have a lexer before the parser :-(
692 lexeme :: Parser p -> Parser p
693 lexeme p = then2 sel12 p pCommentAndWhitespace
695 lit :: String -> Parser ()
696 lit s = apply (const ()) (lexeme (string s))
698 pCommentAndWhitespace :: Parser ()
699 pCommentAndWhitespace
700 = apply (const ()) (many (alts [pLineComment,
701 apply (const ()) (satisfy isSpace)]))
705 pLineComment :: Parser ()
707 = try (then3 (\_ _ _ -> ()) (string "--") (many (satisfy (/= '\n'))) (char '\n'))
709 stringLiteral :: Parser String
710 stringLiteral = lexeme (
711 do { between (char '"')
712 (char '"' <?> "end of string")
715 <?> "literal string")
719 ------------------------------------------------------------------
721 ------------------------------------------------------------------