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