Do not expose LLVM-only primops in GHC.PrimopWrappers.
[ghc.git] / utils / genprimopcode / Main.hs
1 {-# OPTIONS -cpp #-}
2 ------------------------------------------------------------------
3 -- A primop-table mangling program --
4 ------------------------------------------------------------------
5
6 module Main where
7
8 import Parser
9 import Syntax
10
11 import Data.Char
12 import Data.List
13 import Data.Maybe ( catMaybes )
14 import System.Environment ( getArgs )
15
16 main :: IO ()
17 main = getArgs >>= \args ->
18 if length args /= 1 || head args `notElem` known_args
19 then error ("usage: genprimopcode command < primops.txt > ...\n"
20 ++ " where command is one of\n"
21 ++ unlines (map (" "++) known_args)
22 )
23 else
24 do s <- getContents
25 case parse s of
26 Left err -> error ("parse error at " ++ (show err))
27 Right p_o_specs@(Info _ entries)
28 -> seq (sanityTop p_o_specs) (
29 case head args of
30
31 "--data-decl"
32 -> putStr (gen_data_decl p_o_specs)
33
34 "--has-side-effects"
35 -> putStr (gen_switch_from_attribs
36 "has_side_effects"
37 "primOpHasSideEffects" p_o_specs)
38
39 "--out-of-line"
40 -> putStr (gen_switch_from_attribs
41 "out_of_line"
42 "primOpOutOfLine" p_o_specs)
43
44 "--commutable"
45 -> putStr (gen_switch_from_attribs
46 "commutable"
47 "commutableOp" p_o_specs)
48
49 "--code-size"
50 -> putStr (gen_switch_from_attribs
51 "code_size"
52 "primOpCodeSize" p_o_specs)
53
54 "--can-fail"
55 -> putStr (gen_switch_from_attribs
56 "can_fail"
57 "primOpCanFail" p_o_specs)
58
59 "--strictness"
60 -> putStr (gen_switch_from_attribs
61 "strictness"
62 "primOpStrictness" p_o_specs)
63
64 "--fixity"
65 -> putStr (gen_switch_from_attribs
66 "fixity"
67 "primOpFixity" p_o_specs)
68
69 "--primop-primop-info"
70 -> putStr (gen_primop_info p_o_specs)
71
72 "--primop-tag"
73 -> putStr (gen_primop_tag p_o_specs)
74
75 "--primop-list"
76 -> putStr (gen_primop_list p_o_specs)
77
78 "--make-haskell-wrappers"
79 -> putStr (gen_wrappers p_o_specs)
80
81 "--make-haskell-source"
82 -> putStr (gen_hs_source p_o_specs)
83
84 "--make-ext-core-source"
85 -> putStr (gen_ext_core_source entries)
86
87 "--make-latex-doc"
88 -> putStr (gen_latex_doc p_o_specs)
89
90 _ -> error "Should not happen, known_args out of sync?"
91 )
92
93 known_args :: [String]
94 known_args
95 = [ "--data-decl",
96 "--has-side-effects",
97 "--out-of-line",
98 "--commutable",
99 "--code-size",
100 "--can-fail",
101 "--strictness",
102 "--fixity",
103 "--primop-primop-info",
104 "--primop-tag",
105 "--primop-list",
106 "--make-haskell-wrappers",
107 "--make-haskell-source",
108 "--make-ext-core-source",
109 "--make-latex-doc"
110 ]
111
112 ------------------------------------------------------------------
113 -- Code generators -----------------------------------------------
114 ------------------------------------------------------------------
115
116 gen_hs_source :: Info -> String
117 gen_hs_source (Info defaults entries) =
118 "{-\n"
119 ++ "This is a generated file (generated by genprimopcode).\n"
120 ++ "It is not code to actually be used. Its only purpose is to be\n"
121 ++ "consumed by haddock.\n"
122 ++ "-}\n"
123 ++ "\n"
124 ++ "-----------------------------------------------------------------------------\n"
125 ++ "-- |\n"
126 ++ "-- Module : GHC.Prim\n"
127 ++ "-- \n"
128 ++ "-- Maintainer : ghc-devs@haskell.org\n"
129 ++ "-- Stability : internal\n"
130 ++ "-- Portability : non-portable (GHC extensions)\n"
131 ++ "--\n"
132 ++ "-- GHC\'s primitive types and operations.\n"
133 ++ "-- Use GHC.Exts from the base package instead of importing this\n"
134 ++ "-- module directly.\n"
135 ++ "--\n"
136 ++ "-----------------------------------------------------------------------------\n"
137 ++ "{-# LANGUAGE MultiParamTypeClasses #-}\n"
138 ++ "module GHC.Prim (\n"
139 ++ unlines (map (("\t" ++) . hdr) entries)
140 ++ ") where\n"
141 ++ "\n"
142 ++ "{-\n"
143 ++ unlines (map opt defaults)
144 ++ "-}\n"
145 ++ unlines (concatMap ent entries) ++ "\n\n\n"
146 where opt (OptionFalse n) = n ++ " = False"
147 opt (OptionTrue n) = n ++ " = True"
148 opt (OptionString n v) = n ++ " = { " ++ v ++ "}"
149 opt (OptionInteger n v) = n ++ " = " ++ show v
150 opt (OptionFixity mf) = "fixity" ++ " = " ++ show mf
151
152 hdr s@(Section {}) = sec s
153 hdr (PrimOpSpec { name = n }) = wrapOp n ++ ","
154 hdr (PseudoOpSpec { name = n }) = wrapOp n ++ ","
155 hdr (PrimTypeSpec { ty = TyApp n _ }) = wrapTy n ++ ","
156 hdr (PrimTypeSpec {}) = error "Illegal type spec"
157 hdr (PrimClassSpec { cls = TyApp n _ }) = wrapTy n ++ ","
158 hdr (PrimClassSpec {}) = error "Illegal class spec"
159
160 ent (Section {}) = []
161 ent o@(PrimOpSpec {}) = spec o
162 ent o@(PrimTypeSpec {}) = spec o
163 ent o@(PrimClassSpec {}) = spec o
164 ent o@(PseudoOpSpec {}) = spec o
165
166 sec s = "\n-- * " ++ escape (title s) ++ "\n"
167 ++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ desc s) ++ "\n"
168
169 spec o = comm : decls
170 where decls = case o of
171 PrimOpSpec { name = n, ty = t, opts = options } ->
172 [ pprFixity fixity n | OptionFixity (Just fixity) <- options ]
173 ++
174 [ wrapOp n ++ " :: " ++ pprTy t,
175 wrapOp n ++ " = let x = x in x" ]
176 PseudoOpSpec { name = n, ty = t } ->
177 [ wrapOp n ++ " :: " ++ pprTy t,
178 wrapOp n ++ " = let x = x in x" ]
179 PrimTypeSpec { ty = t } ->
180 [ "data " ++ pprTy t ]
181 PrimClassSpec { cls = t } ->
182 [ "class " ++ pprTy t ]
183 Section { } -> []
184
185 comm = case (desc o) of
186 [] -> ""
187 d -> "\n" ++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ d)
188
189 wrapOp nm | isAlpha (head nm) = nm
190 | otherwise = "(" ++ nm ++ ")"
191 wrapTy nm | isAlpha (head nm) = nm
192 | otherwise = "(" ++ nm ++ ")"
193 unlatex s = case s of
194 '\\':'t':'e':'x':'t':'t':'t':'{':cs -> markup "@" "@" cs
195 '{':'\\':'t':'t':cs -> markup "@" "@" cs
196 '{':'\\':'i':'t':cs -> markup "/" "/" cs
197 c : cs -> c : unlatex cs
198 [] -> []
199 markup s t xs = s ++ mk (dropWhile isSpace xs)
200 where mk "" = t
201 mk ('\n':cs) = ' ' : mk cs
202 mk ('}':cs) = t ++ unlatex cs
203 mk (c:cs) = c : mk cs
204 escape = concatMap (\c -> if c `elem` special then '\\':c:[] else c:[])
205 where special = "/'`\"@<"
206
207 pprFixity (Fixity i d) n = pprFixityDir d ++ " " ++ show i ++ " " ++ n
208
209 pprTy :: Ty -> String
210 pprTy = pty
211 where
212 pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
213 pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2
214 pty t = pbty t
215 pbty (TyApp tc ts) = tc ++ concat (map (' ' :) (map paty ts))
216 pbty (TyUTup ts) = "(# "
217 ++ concat (intersperse "," (map pty ts))
218 ++ " #)"
219 pbty t = paty t
220
221 paty (TyVar tv) = tv
222 paty t = "(" ++ pty t ++ ")"
223 --
224 -- Generates the type environment that the stand-alone External Core tools use.
225 gen_ext_core_source :: [Entry] -> String
226 gen_ext_core_source entries =
227 "-----------------------------------------------------------------------\n"
228 ++ "-- This module is automatically generated by the GHC utility\n"
229 ++ "-- \"genprimopcode\". Do not edit!\n"
230 ++ "-----------------------------------------------------------------------\n"
231 ++ "module Language.Core.PrimEnv(primTcs, primVals, intLitTypes, ratLitTypes,"
232 ++ "\n charLitTypes, stringLitTypes) where\nimport Language.Core.Core"
233 ++ "\nimport Language.Core.Encoding\n\n"
234 ++ "primTcs :: [(Tcon, Kind)]\n"
235 ++ "primTcs = [\n"
236 ++ printList tcEnt entries
237 ++ " ]\n"
238 ++ "primVals :: [(Var, Ty)]\n"
239 ++ "primVals = [\n"
240 ++ printList valEnt entries
241 ++ "]\n"
242 ++ "intLitTypes :: [Ty]\n"
243 ++ "intLitTypes = [\n"
244 ++ printList tyEnt (intLitTys entries)
245 ++ "]\n"
246 ++ "ratLitTypes :: [Ty]\n"
247 ++ "ratLitTypes = [\n"
248 ++ printList tyEnt (ratLitTys entries)
249 ++ "]\n"
250 ++ "charLitTypes :: [Ty]\n"
251 ++ "charLitTypes = [\n"
252 ++ printList tyEnt (charLitTys entries)
253 ++ "]\n"
254 ++ "stringLitTypes :: [Ty]\n"
255 ++ "stringLitTypes = [\n"
256 ++ printList tyEnt (stringLitTys entries)
257 ++ "]\n\n"
258
259 where printList f = concat . intersperse ",\n" . filter (not . null) . map f
260 tcEnt (PrimTypeSpec {ty=t}) =
261 case t of
262 TyApp tc args -> parens tc (tcKind tc args)
263 _ -> error ("tcEnt: type in PrimTypeSpec is not a type"
264 ++ " constructor: " ++ show t)
265 tcEnt _ = ""
266 -- hack alert!
267 -- The primops.txt.pp format doesn't have enough information in it to
268 -- print out some of the information that ext-core needs (like kinds,
269 -- and later on in this code, module names) so we special-case. An
270 -- alternative would be to refer to things indirectly and hard-wire
271 -- certain things (e.g., the kind of the Any constructor, here) into
272 -- ext-core's Prims module again.
273 tcKind "Any" _ = "Klifted"
274 tcKind tc [] | last tc == '#' = "Kunlifted"
275 tcKind _ [] | otherwise = "Klifted"
276 -- assumes that all type arguments are lifted (are they?)
277 tcKind tc (_v:as) = "(Karrow Klifted " ++ tcKind tc as
278 ++ ")"
279 valEnt (PseudoOpSpec {name=n, ty=t}) = valEntry n t
280 valEnt (PrimOpSpec {name=n, ty=t}) = valEntry n t
281 valEnt _ = ""
282 valEntry name' ty' = parens name' (mkForallTy (freeTvars ty') (pty ty'))
283 where pty (TyF t1 t2) = mkFunTy (pty t1) (pty t2)
284 pty (TyC t1 t2) = mkFunTy (pty t1) (pty t2)
285 pty (TyApp tc ts) = mkTconApp (mkTcon tc) (map pty ts)
286 pty (TyUTup ts) = mkUtupleTy (map pty ts)
287 pty (TyVar tv) = paren $ "Tvar \"" ++ tv ++ "\""
288
289 mkFunTy s1 s2 = "Tapp " ++ (paren ("Tapp (Tcon tcArrow)"
290 ++ " " ++ paren s1))
291 ++ " " ++ paren s2
292 mkTconApp tc args = foldl tapp tc args
293 mkTcon tc = paren $ "Tcon " ++ paren (qualify True tc)
294 mkUtupleTy args = foldl tapp (tcUTuple (length args)) args
295 mkForallTy [] t = t
296 mkForallTy vs t = foldr
297 (\ v s -> "Tforall " ++
298 (paren (quote v ++ ", " ++ vKind v)) ++ " "
299 ++ paren s) t vs
300
301 -- hack alert!
302 vKind "o" = "Kopen"
303 vKind _ = "Klifted"
304
305 freeTvars (TyF t1 t2) = freeTvars t1 `union` freeTvars t2
306 freeTvars (TyC t1 t2) = freeTvars t1 `union` freeTvars t2
307 freeTvars (TyApp _ tys) = freeTvarss tys
308 freeTvars (TyVar v) = [v]
309 freeTvars (TyUTup tys) = freeTvarss tys
310 freeTvarss = nub . concatMap freeTvars
311
312 tapp s nextArg = paren $ "Tapp " ++ s ++ " " ++ paren nextArg
313 tcUTuple n = paren $ "Tcon " ++ paren (qualify False $ "Z"
314 ++ show n ++ "H")
315
316 tyEnt (PrimTypeSpec {ty=(TyApp tc _args)}) = " " ++ paren ("Tcon " ++
317 (paren (qualify True tc)))
318 tyEnt _ = ""
319
320 -- more hacks. might be better to do this on the ext-core side,
321 -- as per earlier comment
322 qualify _ tc | tc == "Bool" = "Just boolMname" ++ ", "
323 ++ ze True tc
324 qualify _ tc | tc == "()" = "Just baseMname" ++ ", "
325 ++ ze True tc
326 qualify enc tc = "Just primMname" ++ ", " ++ (ze enc tc)
327 ze enc tc = (if enc then "zEncodeString " else "")
328 ++ "\"" ++ tc ++ "\""
329
330 intLitTys = prefixes ["Int", "Word", "Addr", "Char"]
331 ratLitTys = prefixes ["Float", "Double"]
332 charLitTys = prefixes ["Char"]
333 stringLitTys = prefixes ["Addr"]
334 prefixes ps = filter (\ t ->
335 case t of
336 (PrimTypeSpec {ty=(TyApp tc _args)}) ->
337 any (\ p -> p `isPrefixOf` tc) ps
338 _ -> False)
339
340 parens n ty' = " (zEncodeString \"" ++ n ++ "\", " ++ ty' ++ ")"
341 paren s = "(" ++ s ++ ")"
342 quote s = "\"" ++ s ++ "\""
343
344 gen_latex_doc :: Info -> String
345 gen_latex_doc (Info defaults entries)
346 = "\\primopdefaults{"
347 ++ mk_options defaults
348 ++ "}\n"
349 ++ (concat (map mk_entry entries))
350 where mk_entry (PrimOpSpec {cons=constr,name=n,ty=t,cat=c,desc=d,opts=o}) =
351 "\\primopdesc{"
352 ++ latex_encode constr ++ "}{"
353 ++ latex_encode n ++ "}{"
354 ++ latex_encode (zencode n) ++ "}{"
355 ++ latex_encode (show c) ++ "}{"
356 ++ latex_encode (mk_source_ty t) ++ "}{"
357 ++ latex_encode (mk_core_ty t) ++ "}{"
358 ++ d ++ "}{"
359 ++ mk_options o
360 ++ "}\n"
361 mk_entry (Section {title=ti,desc=d}) =
362 "\\primopsection{"
363 ++ latex_encode ti ++ "}{"
364 ++ d ++ "}\n"
365 mk_entry (PrimTypeSpec {ty=t,desc=d,opts=o}) =
366 "\\primtypespec{"
367 ++ latex_encode (mk_source_ty t) ++ "}{"
368 ++ latex_encode (mk_core_ty t) ++ "}{"
369 ++ d ++ "}{"
370 ++ mk_options o
371 ++ "}\n"
372 mk_entry (PrimClassSpec {cls=t,desc=d,opts=o}) =
373 "\\primclassspec{"
374 ++ latex_encode (mk_source_ty t) ++ "}{"
375 ++ latex_encode (mk_core_ty t) ++ "}{"
376 ++ d ++ "}{"
377 ++ mk_options o
378 ++ "}\n"
379 mk_entry (PseudoOpSpec {name=n,ty=t,desc=d,opts=o}) =
380 "\\pseudoopspec{"
381 ++ latex_encode (zencode n) ++ "}{"
382 ++ latex_encode (mk_source_ty t) ++ "}{"
383 ++ latex_encode (mk_core_ty t) ++ "}{"
384 ++ d ++ "}{"
385 ++ mk_options o
386 ++ "}\n"
387 mk_source_ty typ = pty typ
388 where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
389 pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2
390 pty t = pbty t
391 pbty (TyApp tc ts) = tc ++ (concat (map (' ':) (map paty ts)))
392 pbty (TyUTup ts) = "(# " ++ (concat (intersperse "," (map pty ts))) ++ " #)"
393 pbty t = paty t
394 paty (TyVar tv) = tv
395 paty t = "(" ++ pty t ++ ")"
396
397 mk_core_ty typ = foralls ++ (pty typ)
398 where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
399 pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2
400 pty t = pbty t
401 pbty (TyApp tc ts) = (zencode tc) ++ (concat (map (' ':) (map paty ts)))
402 pbty (TyUTup ts) = (zencode (utuplenm (length ts))) ++ (concat ((map (' ':) (map paty ts))))
403 pbty t = paty t
404 paty (TyVar tv) = zencode tv
405 paty (TyApp tc []) = zencode tc
406 paty t = "(" ++ pty t ++ ")"
407 utuplenm 1 = "(# #)"
408 utuplenm n = "(#" ++ (replicate (n-1) ',') ++ "#)"
409 foralls = if tvars == [] then "" else "%forall " ++ (tbinds tvars)
410 tvars = tvars_of typ
411 tbinds [] = ". "
412 tbinds ("o":tbs) = "(o::?) " ++ (tbinds tbs)
413 tbinds (tv:tbs) = tv ++ " " ++ (tbinds tbs)
414 tvars_of (TyF t1 t2) = tvars_of t1 `union` tvars_of t2
415 tvars_of (TyC t1 t2) = tvars_of t1 `union` tvars_of t2
416 tvars_of (TyApp _ ts) = foldl union [] (map tvars_of ts)
417 tvars_of (TyUTup ts) = foldr union [] (map tvars_of ts)
418 tvars_of (TyVar tv) = [tv]
419
420 mk_options o =
421 "\\primoptions{"
422 ++ mk_has_side_effects o ++ "}{"
423 ++ mk_out_of_line o ++ "}{"
424 ++ mk_commutable o ++ "}{"
425 ++ mk_needs_wrapper o ++ "}{"
426 ++ mk_can_fail o ++ "}{"
427 ++ mk_fixity o ++ "}{"
428 ++ latex_encode (mk_strictness o) ++ "}{"
429 ++ "}"
430
431 mk_has_side_effects o = mk_bool_opt o "has_side_effects" "Has side effects." "Has no side effects."
432 mk_out_of_line o = mk_bool_opt o "out_of_line" "Implemented out of line." "Implemented in line."
433 mk_commutable o = mk_bool_opt o "commutable" "Commutable." "Not commutable."
434 mk_needs_wrapper o = mk_bool_opt o "needs_wrapper" "Needs wrapper." "Needs no wrapper."
435 mk_can_fail o = mk_bool_opt o "can_fail" "Can fail." "Cannot fail."
436
437 mk_bool_opt o opt_name if_true if_false =
438 case lookup_attrib opt_name o of
439 Just (OptionTrue _) -> if_true
440 Just (OptionFalse _) -> if_false
441 Just (OptionString _ _) -> error "String value for boolean option"
442 Just (OptionInteger _ _) -> error "Integer value for boolean option"
443 Just (OptionFixity _) -> error "Fixity value for boolean option"
444 Nothing -> ""
445
446 mk_strictness o =
447 case lookup_attrib "strictness" o of
448 Just (OptionString _ s) -> s -- for now
449 Just _ -> error "Wrong value for strictness"
450 Nothing -> ""
451
452 mk_fixity o = case lookup_attrib "fixity" o of
453 Just (OptionFixity (Just (Fixity i d)))
454 -> pprFixityDir d ++ " " ++ show i
455 _ -> ""
456
457 zencode xs =
458 case maybe_tuple xs of
459 Just n -> n -- Tuples go to Z2T etc
460 Nothing -> concat (map encode_ch xs)
461 where
462 maybe_tuple "(# #)" = Just("Z1H")
463 maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of
464 (n, '#' : ')' : _) -> Just ('Z' : shows (n+1) "H")
465 _ -> Nothing
466 maybe_tuple "()" = Just("Z0T")
467 maybe_tuple ('(' : cs) = case count_commas (0::Int) cs of
468 (n, ')' : _) -> Just ('Z' : shows (n+1) "T")
469 _ -> Nothing
470 maybe_tuple _ = Nothing
471
472 count_commas :: Int -> String -> (Int, String)
473 count_commas n (',' : cs) = count_commas (n+1) cs
474 count_commas n cs = (n,cs)
475
476 unencodedChar :: Char -> Bool -- True for chars that don't need encoding
477 unencodedChar 'Z' = False
478 unencodedChar 'z' = False
479 unencodedChar c = isAlphaNum c
480
481 encode_ch :: Char -> String
482 encode_ch c | unencodedChar c = [c] -- Common case first
483
484 -- Constructors
485 encode_ch '(' = "ZL" -- Needed for things like (,), and (->)
486 encode_ch ')' = "ZR" -- For symmetry with (
487 encode_ch '[' = "ZM"
488 encode_ch ']' = "ZN"
489 encode_ch ':' = "ZC"
490 encode_ch 'Z' = "ZZ"
491
492 -- Variables
493 encode_ch 'z' = "zz"
494 encode_ch '&' = "za"
495 encode_ch '|' = "zb"
496 encode_ch '^' = "zc"
497 encode_ch '$' = "zd"
498 encode_ch '=' = "ze"
499 encode_ch '>' = "zg"
500 encode_ch '#' = "zh"
501 encode_ch '.' = "zi"
502 encode_ch '<' = "zl"
503 encode_ch '-' = "zm"
504 encode_ch '!' = "zn"
505 encode_ch '+' = "zp"
506 encode_ch '\'' = "zq"
507 encode_ch '\\' = "zr"
508 encode_ch '/' = "zs"
509 encode_ch '*' = "zt"
510 encode_ch '_' = "zu"
511 encode_ch '%' = "zv"
512 encode_ch c = 'z' : shows (ord c) "U"
513
514 latex_encode [] = []
515 latex_encode (c:cs) | c `elem` "#$%&_^{}" = "\\" ++ c:(latex_encode cs)
516 latex_encode ('~':cs) = "\\verb!~!" ++ (latex_encode cs)
517 latex_encode ('\\':cs) = "$\\backslash$" ++ (latex_encode cs)
518 latex_encode (c:cs) = c:(latex_encode cs)
519
520 gen_wrappers :: Info -> String
521 gen_wrappers (Info _ entries)
522 = "{-# LANGUAGE CPP, NoImplicitPrelude, UnboxedTuples #-}\n"
523 -- Dependencies on Prelude must be explicit in libraries/base, but we
524 -- don't need the Prelude here so we add NoImplicitPrelude.
525 ++ "module GHC.PrimopWrappers where\n"
526 ++ "import qualified GHC.Prim\n"
527 ++ "import GHC.Tuple ()\n"
528 ++ "import GHC.Prim (" ++ types ++ ")\n"
529 ++ unlines (concatMap f specs)
530 where
531 specs = filter (not.dodgy) $
532 filter (not.is_llvm_only) $
533 filter is_primop entries
534 tycons = foldr union [] $ map (tyconsIn . ty) specs
535 tycons' = filter (`notElem` ["()", "Bool"]) tycons
536 types = concat $ intersperse ", " tycons'
537 f spec = let args = map (\n -> "a" ++ show n) [1 .. arity (ty spec)]
538 src_name = wrap (name spec)
539 lhs = src_name ++ " " ++ unwords args
540 rhs = "(GHC.Prim." ++ name spec ++ ") " ++ unwords args
541 in ["{-# NOINLINE " ++ src_name ++ " #-}",
542 src_name ++ " :: " ++ pprTy (ty spec),
543 lhs ++ " = " ++ rhs]
544 wrap nm | isLower (head nm) = nm
545 | otherwise = "(" ++ nm ++ ")"
546
547 dodgy spec
548 = name spec `elem`
549 [-- C code generator can't handle these
550 "seq#",
551 "tagToEnum#",
552 -- not interested in parallel support
553 "par#", "parGlobal#", "parLocal#", "parAt#",
554 "parAtAbs#", "parAtRel#", "parAtForNow#"
555 ]
556
557 is_llvm_only :: Entry -> Bool
558 is_llvm_only entry =
559 case lookup_attrib "llvm_only" (opts entry) of
560 Just (OptionTrue _) -> True
561 _ -> False
562
563 gen_primop_list :: Info -> String
564 gen_primop_list (Info _ entries)
565 = unlines (
566 [ " [" ++ cons first ]
567 ++
568 map (\p -> " , " ++ cons p) rest
569 ++
570 [ " ]" ]
571 ) where (first:rest) = filter is_primop entries
572
573 gen_primop_tag :: Info -> String
574 gen_primop_tag (Info _ entries)
575 = unlines (max_def_type : max_def :
576 tagOf_type : zipWith f primop_entries [1 :: Int ..])
577 where
578 primop_entries = filter is_primop entries
579 tagOf_type = "tagOf_PrimOp :: PrimOp -> FastInt"
580 f i n = "tagOf_PrimOp " ++ cons i ++ " = _ILIT(" ++ show n ++ ")"
581 max_def_type = "maxPrimOpTag :: Int"
582 max_def = "maxPrimOpTag = " ++ show (length primop_entries)
583
584 gen_data_decl :: Info -> String
585 gen_data_decl (Info _ entries)
586 = let conss = map cons (filter is_primop entries)
587 in "data PrimOp\n = " ++ head conss ++ "\n"
588 ++ unlines (map (" | "++) (tail conss))
589
590 gen_switch_from_attribs :: String -> String -> Info -> String
591 gen_switch_from_attribs attrib_name fn_name (Info defaults entries)
592 = let defv = lookup_attrib attrib_name defaults
593 alternatives = catMaybes (map mkAlt (filter is_primop entries))
594
595 getAltRhs (OptionFalse _) = "False"
596 getAltRhs (OptionTrue _) = "True"
597 getAltRhs (OptionInteger _ i) = show i
598 getAltRhs (OptionString _ s) = s
599 getAltRhs (OptionFixity mf) = show mf
600
601 mkAlt po
602 = case lookup_attrib attrib_name (opts po) of
603 Nothing -> Nothing
604 Just xx -> Just (fn_name ++ " " ++ cons po ++ " = " ++ getAltRhs xx)
605
606 in
607 case defv of
608 Nothing -> error ("gen_switch_from: " ++ attrib_name)
609 Just xx
610 -> unlines alternatives
611 ++ fn_name ++ " _ = " ++ getAltRhs xx ++ "\n"
612
613 ------------------------------------------------------------------
614 -- Create PrimOpInfo text from PrimOpSpecs -----------------------
615 ------------------------------------------------------------------
616
617 gen_primop_info :: Info -> String
618 gen_primop_info (Info _ entries)
619 = unlines (map mkPOItext (filter is_primop entries))
620
621 mkPOItext :: Entry -> String
622 mkPOItext i = mkPOI_LHS_text i ++ mkPOI_RHS_text i
623
624 mkPOI_LHS_text :: Entry -> String
625 mkPOI_LHS_text i
626 = "primOpInfo " ++ cons i ++ " = "
627
628 mkPOI_RHS_text :: Entry -> String
629 mkPOI_RHS_text i
630 = case cat i of
631 Compare
632 -> case ty i of
633 TyF t1 (TyF _ _)
634 -> "mkCompare " ++ sl_name i ++ ppType t1
635 _ -> error "Type error in comparison op"
636 Monadic
637 -> case ty i of
638 TyF t1 _
639 -> "mkMonadic " ++ sl_name i ++ ppType t1
640 _ -> error "Type error in monadic op"
641 Dyadic
642 -> case ty i of
643 TyF t1 (TyF _ _)
644 -> "mkDyadic " ++ sl_name i ++ ppType t1
645 _ -> error "Type error in dyadic op"
646 GenPrimOp
647 -> let (argTys, resTy) = flatTys (ty i)
648 tvs = nub (tvsIn (ty i))
649 in
650 "mkGenPrimOp " ++ sl_name i ++ " "
651 ++ listify (map ppTyVar tvs) ++ " "
652 ++ listify (map ppType argTys) ++ " "
653 ++ "(" ++ ppType resTy ++ ")"
654
655 sl_name :: Entry -> String
656 sl_name i = "(fsLit \"" ++ name i ++ "\") "
657
658 ppTyVar :: String -> String
659 ppTyVar "a" = "alphaTyVar"
660 ppTyVar "b" = "betaTyVar"
661 ppTyVar "c" = "gammaTyVar"
662 ppTyVar "s" = "deltaTyVar"
663 ppTyVar "o" = "openAlphaTyVar"
664 ppTyVar _ = error "Unknown type var"
665
666 ppType :: Ty -> String
667 ppType (TyApp "Any" []) = "anyTy"
668 ppType (TyApp "Bool" []) = "boolTy"
669
670 ppType (TyApp "Int#" []) = "intPrimTy"
671 ppType (TyApp "Int32#" []) = "int32PrimTy"
672 ppType (TyApp "Int64#" []) = "int64PrimTy"
673 ppType (TyApp "Char#" []) = "charPrimTy"
674 ppType (TyApp "Word#" []) = "wordPrimTy"
675 ppType (TyApp "Word32#" []) = "word32PrimTy"
676 ppType (TyApp "Word64#" []) = "word64PrimTy"
677 ppType (TyApp "Addr#" []) = "addrPrimTy"
678 ppType (TyApp "Float#" []) = "floatPrimTy"
679 ppType (TyApp "Double#" []) = "doublePrimTy"
680 ppType (TyApp "FloatX4#" []) = "floatX4PrimTy"
681 ppType (TyApp "DoubleX2#" []) = "doubleX2PrimTy"
682 ppType (TyApp "Int32X4#" []) = "int32X4PrimTy"
683 ppType (TyApp "Int64X2#" []) = "int64X2PrimTy"
684 ppType (TyApp "ByteArray#" []) = "byteArrayPrimTy"
685 ppType (TyApp "RealWorld" []) = "realWorldTy"
686 ppType (TyApp "ThreadId#" []) = "threadIdPrimTy"
687 ppType (TyApp "ForeignObj#" []) = "foreignObjPrimTy"
688 ppType (TyApp "BCO#" []) = "bcoPrimTy"
689 ppType (TyApp "()" []) = "unitTy" -- unitTy is TysWiredIn's name for ()
690
691 ppType (TyVar "a") = "alphaTy"
692 ppType (TyVar "b") = "betaTy"
693 ppType (TyVar "c") = "gammaTy"
694 ppType (TyVar "s") = "deltaTy"
695 ppType (TyVar "o") = "openAlphaTy"
696
697 ppType (TyApp "State#" [x]) = "mkStatePrimTy " ++ ppType x
698 ppType (TyApp "MutVar#" [x,y]) = "mkMutVarPrimTy " ++ ppType x
699 ++ " " ++ ppType y
700 ppType (TyApp "MutableArray#" [x,y]) = "mkMutableArrayPrimTy " ++ ppType x
701 ++ " " ++ ppType y
702 ppType (TyApp "MutableArrayArray#" [x]) = "mkMutableArrayArrayPrimTy " ++ ppType x
703 ppType (TyApp "MutableByteArray#" [x]) = "mkMutableByteArrayPrimTy "
704 ++ ppType x
705 ppType (TyApp "Array#" [x]) = "mkArrayPrimTy " ++ ppType x
706 ppType (TyApp "ArrayArray#" []) = "mkArrayArrayPrimTy"
707
708
709 ppType (TyApp "Weak#" [x]) = "mkWeakPrimTy " ++ ppType x
710 ppType (TyApp "StablePtr#" [x]) = "mkStablePtrPrimTy " ++ ppType x
711 ppType (TyApp "StableName#" [x]) = "mkStableNamePrimTy " ++ ppType x
712
713 ppType (TyApp "MVar#" [x,y]) = "mkMVarPrimTy " ++ ppType x
714 ++ " " ++ ppType y
715 ppType (TyApp "TVar#" [x,y]) = "mkTVarPrimTy " ++ ppType x
716 ++ " " ++ ppType y
717 ppType (TyUTup ts) = "(mkTupleTy UnboxedTuple "
718 ++ listify (map ppType ts) ++ ")"
719
720 ppType (TyF s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))"
721 ppType (TyC s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))"
722
723 ppType other
724 = error ("ppType: can't handle: " ++ show other ++ "\n")
725
726 pprFixityDir :: FixityDirection -> String
727 pprFixityDir InfixN = "infix"
728 pprFixityDir InfixL = "infixl"
729 pprFixityDir InfixR = "infixr"
730
731 listify :: [String] -> String
732 listify ss = "[" ++ concat (intersperse ", " ss) ++ "]"
733
734 flatTys :: Ty -> ([Ty],Ty)
735 flatTys (TyF t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t)
736 flatTys (TyC t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t)
737 flatTys other = ([],other)
738
739 tvsIn :: Ty -> [TyVar]
740 tvsIn (TyF t1 t2) = tvsIn t1 ++ tvsIn t2
741 tvsIn (TyC t1 t2) = tvsIn t1 ++ tvsIn t2
742 tvsIn (TyApp _ tys) = concatMap tvsIn tys
743 tvsIn (TyVar tv) = [tv]
744 tvsIn (TyUTup tys) = concatMap tvsIn tys
745
746 tyconsIn :: Ty -> [TyCon]
747 tyconsIn (TyF t1 t2) = tyconsIn t1 `union` tyconsIn t2
748 tyconsIn (TyC t1 t2) = tyconsIn t1 `union` tyconsIn t2
749 tyconsIn (TyApp tc tys) = foldr union [tc] $ map tyconsIn tys
750 tyconsIn (TyVar _) = []
751 tyconsIn (TyUTup tys) = foldr union [] $ map tyconsIn tys
752
753 arity :: Ty -> Int
754 arity = length . fst . flatTys