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