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