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