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