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