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