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