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 = "module GHC.PrimopWrappers where\n"
253 ++ "import qualified GHC.Prim\n"
254 ++ unlines (map f (filter (not.dodgy) (filter is_primop entries)))
256 f spec = let args = map (\n -> "a" ++ show n) [1 .. arity (ty spec)]
257 src_name = wrap (name spec)
258 in "{-# NOINLINE " ++ src_name ++ " #-}\n" ++
259 src_name ++ " " ++ unwords args
260 ++ " = (GHC.Prim." ++ name spec ++ ") " ++ unwords args
261 wrap nm | isLower (head nm) = nm
262 | otherwise = "(" ++ nm ++ ")"
266 [-- C code generator can't handle these
269 -- not interested in parallel support
270 "par#", "parGlobal#", "parLocal#", "parAt#",
271 "parAtAbs#", "parAtRel#", "parAtForNow#"
275 gen_primop_list (Info defaults entries)
277 [ " [" ++ cons first ]
279 map (\pi -> " , " ++ cons pi) rest
282 ) where (first:rest) = filter is_primop entries
284 gen_primop_tag (Info defaults entries)
285 = unlines (zipWith f (filter is_primop entries) [1..])
287 f i n = "tagOf_PrimOp " ++ cons i
288 ++ " = _ILIT(" ++ show n ++ ") :: FastInt"
290 gen_data_decl (Info defaults entries)
291 = let conss = map cons (filter is_primop entries)
292 in "data PrimOp\n = " ++ head conss ++ "\n"
293 ++ unlines (map (" | "++) (tail conss))
295 gen_switch_from_attribs :: String -> String -> Info -> String
296 gen_switch_from_attribs attrib_name fn_name (Info defaults entries)
297 = let defv = lookup_attrib attrib_name defaults
298 alts = catMaybes (map mkAlt (filter is_primop entries))
300 getAltRhs (OptionFalse _) = "False"
301 getAltRhs (OptionTrue _) = "True"
302 getAltRhs (OptionString _ s) = s
305 = case lookup_attrib attrib_name (opts po) of
307 Just xx -> Just (fn_name ++ " " ++ cons po ++ " = " ++ getAltRhs xx)
311 Nothing -> error ("gen_switch_from: " ++ attrib_name)
314 ++ fn_name ++ " other = " ++ getAltRhs xx ++ "\n"
316 ------------------------------------------------------------------
317 -- Create PrimOpInfo text from PrimOpSpecs -----------------------
318 ------------------------------------------------------------------
321 gen_primop_info (Info defaults entries)
322 = unlines (map mkPOItext (filter is_primop entries))
324 mkPOItext i = mkPOI_LHS_text i ++ mkPOI_RHS_text i
327 = "primOpInfo " ++ cons i ++ " = "
334 -> "mkCompare " ++ sl_name i ++ ppType t1
338 -> "mkMonadic " ++ sl_name i ++ ppType t1
342 -> "mkDyadic " ++ sl_name i ++ ppType t1
344 -> let (argTys, resTy) = flatTys (ty i)
345 tvs = nub (tvsIn (ty i))
347 "mkGenPrimOp " ++ sl_name i ++ " "
348 ++ listify (map ppTyVar tvs) ++ " "
349 ++ listify (map ppType argTys) ++ " "
350 ++ "(" ++ ppType resTy ++ ")"
352 sl_name i = "SLIT(\"" ++ name i ++ "\") "
354 ppTyVar "a" = "alphaTyVar"
355 ppTyVar "b" = "betaTyVar"
356 ppTyVar "c" = "gammaTyVar"
357 ppTyVar "s" = "deltaTyVar"
358 ppTyVar "o" = "openAlphaTyVar"
361 ppType (TyApp "Bool" []) = "boolTy"
363 ppType (TyApp "Int#" []) = "intPrimTy"
364 ppType (TyApp "Int32#" []) = "int32PrimTy"
365 ppType (TyApp "Int64#" []) = "int64PrimTy"
366 ppType (TyApp "Char#" []) = "charPrimTy"
367 ppType (TyApp "Word#" []) = "wordPrimTy"
368 ppType (TyApp "Word32#" []) = "word32PrimTy"
369 ppType (TyApp "Word64#" []) = "word64PrimTy"
370 ppType (TyApp "Addr#" []) = "addrPrimTy"
371 ppType (TyApp "Float#" []) = "floatPrimTy"
372 ppType (TyApp "Double#" []) = "doublePrimTy"
373 ppType (TyApp "ByteArr#" []) = "byteArrayPrimTy"
374 ppType (TyApp "RealWorld" []) = "realWorldTy"
375 ppType (TyApp "ThreadId#" []) = "threadIdPrimTy"
376 ppType (TyApp "ForeignObj#" []) = "foreignObjPrimTy"
377 ppType (TyApp "BCO#" []) = "bcoPrimTy"
378 ppType (TyApp "Unit" []) = "unitTy" -- dodgy
381 ppType (TyVar "a") = "alphaTy"
382 ppType (TyVar "b") = "betaTy"
383 ppType (TyVar "c") = "gammaTy"
384 ppType (TyVar "s") = "deltaTy"
385 ppType (TyVar "o") = "openAlphaTy"
386 ppType (TyApp "State#" [x]) = "mkStatePrimTy " ++ ppType x
387 ppType (TyApp "MutVar#" [x,y]) = "mkMutVarPrimTy " ++ ppType x
389 ppType (TyApp "MutArr#" [x,y]) = "mkMutableArrayPrimTy " ++ ppType x
392 ppType (TyApp "MutByteArr#" [x]) = "mkMutableByteArrayPrimTy "
395 ppType (TyApp "Array#" [x]) = "mkArrayPrimTy " ++ ppType x
398 ppType (TyApp "Weak#" [x]) = "mkWeakPrimTy " ++ ppType x
399 ppType (TyApp "StablePtr#" [x]) = "mkStablePtrPrimTy " ++ ppType x
400 ppType (TyApp "StableName#" [x]) = "mkStableNamePrimTy " ++ ppType x
402 ppType (TyApp "MVar#" [x,y]) = "mkMVarPrimTy " ++ ppType x
404 ppType (TyUTup ts) = "(mkTupleTy Unboxed " ++ show (length ts)
406 ++ listify (map ppType ts) ++ ")"
408 ppType (TyF s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))"
411 = error ("ppType: can't handle: " ++ show other ++ "\n")
413 listify :: [String] -> String
414 listify ss = "[" ++ concat (intersperse ", " ss) ++ "]"
416 flatTys (TyF t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t)
417 flatTys other = ([],other)
419 tvsIn (TyF t1 t2) = tvsIn t1 ++ tvsIn t2
420 tvsIn (TyApp tc tys) = concatMap tvsIn tys
421 tvsIn (TyVar tv) = [tv]
422 tvsIn (TyUTup tys) = concatMap tvsIn tys
424 arity = length . fst . flatTys
427 ------------------------------------------------------------------
428 -- Abstract syntax -----------------------------------------------
429 ------------------------------------------------------------------
431 -- info for all primops; the totality of the info in primops.txt(.pp)
433 = Info [Option] [Entry] -- defaults, primops
436 -- info for one primop
438 = PrimOpSpec { cons :: String, -- PrimOp name
439 name :: String, -- name in prog text
441 cat :: Category, -- category
442 desc :: String, -- description
443 opts :: [Option] } -- default overrides
444 | Section { title :: String, -- section title
445 desc :: String } -- description
448 is_primop (PrimOpSpec _ _ _ _ _ _) = True
451 -- a binding of property to value
453 = OptionFalse String -- name = False
454 | OptionTrue String -- name = True
455 | OptionString String String -- name = { ... unparsed stuff ... }
458 -- categorises primops
460 = Dyadic | Monadic | Compare | GenPrimOp
468 | TyUTup [Ty] -- unboxed tuples; just a TyCon really,
469 -- but convenient like this
476 ------------------------------------------------------------------
477 -- Sanity checking -----------------------------------------------
478 ------------------------------------------------------------------
480 {- Do some simple sanity checks:
481 * all the default field names are unique
482 * for each PrimOpSpec, all override field names are unique
483 * for each PrimOpSpec, all overriden field names
484 have a corresponding default value
485 * that primop types correspond in certain ways to the
486 Category: eg if Comparison, the type must be of the form
488 Dies with "error" if there's a problem, else returns ().
491 myseqAll (():ys) x = myseqAll ys x
494 sanityTop :: Info -> ()
495 sanityTop (Info defs entries)
496 = let opt_names = map get_attrib_name defs
497 primops = filter is_primop entries
499 if length opt_names /= length (nub opt_names)
500 then error ("non-unique default attribute names: " ++ show opt_names ++ "\n")
501 else myseqAll (map (sanityPrimOp opt_names) primops) ()
503 sanityPrimOp def_names p
504 = let p_names = map get_attrib_name (opts p)
506 = length p_names == length (nub p_names)
507 && all (`elem` def_names) p_names
508 ty_ok = sane_ty (cat p) (ty p)
511 then error ("attribute names are non-unique or have no default in\n" ++
512 "info for primop " ++ cons p ++ "\n")
515 then error ("type of primop " ++ cons p ++ " doesn't make sense w.r.t" ++
516 " category " ++ show (cat p) ++ "\n")
519 sane_ty Compare (TyF t1 (TyF t2 td))
520 | t1 == t2 && td == TyApp "Bool" [] = True
521 sane_ty Monadic (TyF t1 td)
523 sane_ty Dyadic (TyF t1 (TyF t2 td))
524 | t1 == t2 && t2 == t2 = True
525 sane_ty GenPrimOp any_old_thing
530 get_attrib_name (OptionFalse nm) = nm
531 get_attrib_name (OptionTrue nm) = nm
532 get_attrib_name (OptionString nm _) = nm
534 lookup_attrib nm [] = Nothing
535 lookup_attrib nm (a:as)
536 = if get_attrib_name a == nm then Just a else lookup_attrib nm as
538 ------------------------------------------------------------------
539 -- The parser ----------------------------------------------------
540 ------------------------------------------------------------------
542 -- Due to lack of proper lexing facilities, a hack to zap any
545 pTop = then4 (\_ ds es _ -> Info ds es)
546 pCommentAndWhitespace pDefaults (many pEntry)
547 (lit "thats_all_folks")
549 pEntry :: Parser Entry
551 = alts [pPrimOpSpec, pSection]
553 pSection :: Parser Entry
554 pSection = then3 (\_ n d -> Section {title = n, desc = d})
555 (lit "section") stringLiteral pDesc
557 pDefaults :: Parser [Option]
558 pDefaults = then2 sel22 (lit "defaults") (many pOption)
560 pOption :: Parser Option
563 then3 (\nm eq ff -> OptionFalse nm) pName (lit "=") (lit "False"),
564 then3 (\nm eq tt -> OptionTrue nm) pName (lit "=") (lit "True"),
565 then3 (\nm eq zz -> OptionString nm zz)
566 pName (lit "=") pStuffBetweenBraces
569 pPrimOpSpec :: Parser Entry
571 = then7 (\_ c n k t d o -> PrimOpSpec { cons = c, name = n, ty = t,
572 cat = k, desc = d, opts = o } )
573 (lit "primop") pConstructor stringLiteral
574 pCategory pType pDesc pOptions
576 pOptions :: Parser [Option]
577 pOptions = optdef [] (then2 sel22 (lit "with") (many pOption))
579 pCategory :: Parser Category
582 apply (const Dyadic) (lit "Dyadic"),
583 apply (const Monadic) (lit "Monadic"),
584 apply (const Compare) (lit "Compare"),
585 apply (const GenPrimOp) (lit "GenPrimOp")
588 pDesc :: Parser String
589 pDesc = optdef "" pStuffBetweenBraces
591 pStuffBetweenBraces :: Parser String
597 return (concat ass) )
599 pInsides :: Parser String
602 stuff <- many pInsides
604 return ("{" ++ (concat stuff) ++ "}"))
606 (do c <- satisfy (/= '}')
616 pType = then2 (\t maybe_tt -> case maybe_tt of
620 (opt (then2 sel22 (lit "->") pType))
623 paT = alts [ then2 TyApp pTycon (many ppT),
625 then3 sel23 (lit "(") pType (lit ")"),
629 -- the magic bit in the middle is: T (,T)* so to speak
631 = then3 (\ _ ts _ -> TyUTup ts)
633 (then2 (:) pType (many (then2 sel22 (lit ",") pType)))
637 ppT = alts [apply TyVar pTyvar,
638 apply (\tc -> TyApp tc []) pTycon
641 pTyvar = sat (`notElem` ["section","primop","with"]) pName
642 pTycon = pConstructor
643 pName = lexeme (then2 (:) lower (many isIdChar))
644 pConstructor = lexeme (then2 (:) upper (many isIdChar))
646 isIdChar = satisfy (`elem` idChars)
647 idChars = ['a' .. 'z'] ++ ['A' .. 'Z'] ++ ['0' .. '9'] ++ "#_"
655 ------------------------------------------------------------------
656 -- Helpful additions to Daan's parser stuff ----------------------
657 ------------------------------------------------------------------
660 alts (p1:p2:ps) = (try p1) <|> alts (p2:ps)
663 = do x1 <- p1 ; x2 <- p2 ; return (f x1 x2)
665 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; return (f x1 x2 x3)
667 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; return (f x1 x2 x3 x4)
668 then5 f p1 p2 p3 p4 p5
669 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5
670 return (f x1 x2 x3 x4 x5)
671 then6 f p1 p2 p3 p4 p5 p6
672 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5 ; x6 <- p6
673 return (f x1 x2 x3 x4 x5 x6)
674 then7 f p1 p2 p3 p4 p5 p6 p7
675 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5 ; x6 <- p6 ; x7 <- p7
676 return (f x1 x2 x3 x4 x5 x6 x7)
678 = (do x <- p; return (Just x)) <|> return Nothing
680 = (do x <- p; return x) <|> return d
685 apply f p = liftM f p
687 -- Hacks for zapping whitespace and comments, unfortunately needed
688 -- because Daan won't let us have a lexer before the parser :-(
689 lexeme :: Parser p -> Parser p
690 lexeme p = then2 sel12 p pCommentAndWhitespace
692 lit :: String -> Parser ()
693 lit s = apply (const ()) (lexeme (string s))
695 pCommentAndWhitespace :: Parser ()
696 pCommentAndWhitespace
697 = apply (const ()) (many (alts [pLineComment,
698 apply (const ()) (satisfy isSpace)]))
702 pLineComment :: Parser ()
704 = try (then3 (\_ _ _ -> ()) (string "--") (many (satisfy (/= '\n'))) (char '\n'))
706 stringLiteral :: Parser String
707 stringLiteral = lexeme (
708 do { between (char '"')
709 (char '"' <?> "end of string")
712 <?> "literal string")
716 ------------------------------------------------------------------
718 ------------------------------------------------------------------