Handle primitive types and pseudo ops when generating LaTeX
[ghc.git] / utils / genprimopcode / Main.hs
1 {-# OPTIONS -cpp #-}
2 ------------------------------------------------------------------
3 -- A primop-table mangling program --
4 ------------------------------------------------------------------
5
6 module Main where
7
8 #if __GLASGOW_HASKELL__ >= 504
9 import Text.ParserCombinators.Parsec
10 #else
11 import Parsec
12 #endif
13
14 import Monad
15 import Char
16 import List
17 import System ( getArgs )
18 import Maybe ( catMaybes )
19
20 main :: IO ()
21 main = getArgs >>= \args ->
22 if length args /= 1 || head args `notElem` known_args
23 then error ("usage: genprimopcode command < primops.txt > ...\n"
24 ++ " where command is one of\n"
25 ++ unlines (map (" "++) known_args)
26 )
27 else
28 do s <- getContents
29 let pres = parse pTop "" s
30 case pres of
31 Left err -> error ("parse error at " ++ (show err))
32 Right p_o_specs
33 -> myseq (sanityTop p_o_specs) (
34 case head args of
35
36 "--data-decl"
37 -> putStr (gen_data_decl p_o_specs)
38
39 "--has-side-effects"
40 -> putStr (gen_switch_from_attribs
41 "has_side_effects"
42 "primOpHasSideEffects" p_o_specs)
43
44 "--out-of-line"
45 -> putStr (gen_switch_from_attribs
46 "out_of_line"
47 "primOpOutOfLine" p_o_specs)
48
49 "--commutable"
50 -> putStr (gen_switch_from_attribs
51 "commutable"
52 "commutableOp" p_o_specs)
53
54 "--needs-wrapper"
55 -> putStr (gen_switch_from_attribs
56 "needs_wrapper"
57 "primOpNeedsWrapper" p_o_specs)
58
59 "--can-fail"
60 -> putStr (gen_switch_from_attribs
61 "can_fail"
62 "primOpCanFail" p_o_specs)
63
64 "--strictness"
65 -> putStr (gen_switch_from_attribs
66 "strictness"
67 "primOpStrictness" p_o_specs)
68
69 "--usage"
70 -> putStr (gen_switch_from_attribs
71 "usage"
72 "primOpUsg" p_o_specs)
73
74 "--primop-primop-info"
75 -> putStr (gen_primop_info p_o_specs)
76
77 "--primop-tag"
78 -> putStr (gen_primop_tag p_o_specs)
79
80 "--primop-list"
81 -> putStr (gen_primop_list p_o_specs)
82
83 "--make-haskell-wrappers"
84 -> putStr (gen_wrappers p_o_specs)
85
86 "--make-haskell-source"
87 -> putStr (gen_hs_source p_o_specs)
88
89 "--make-latex-doc"
90 -> putStr (gen_latex_doc p_o_specs)
91
92 _ -> error "Should not happen, known_args out of sync?"
93 )
94
95 known_args :: [String]
96 known_args
97 = [ "--data-decl",
98 "--has-side-effects",
99 "--out-of-line",
100 "--commutable",
101 "--needs-wrapper",
102 "--can-fail",
103 "--strictness",
104 "--usage",
105 "--primop-primop-info",
106 "--primop-tag",
107 "--primop-list",
108 "--make-haskell-wrappers",
109 "--make-haskell-source",
110 "--make-latex-doc"
111 ]
112
113 ------------------------------------------------------------------
114 -- Code generators -----------------------------------------------
115 ------------------------------------------------------------------
116
117 gen_hs_source :: Info -> String
118 gen_hs_source (Info defaults entries) =
119 "-----------------------------------------------------------------------------\n"
120 ++ "-- |\n"
121 ++ "-- Module : GHC.Arr\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\n{-\n"
133 ++ unlines (map opt defaults) ++ "-}\n"
134 ++ unlines (map ent entries) ++ "\n\n\n"
135 where opt (OptionFalse n) = n ++ " = False"
136 opt (OptionTrue n) = n ++ " = True"
137 opt (OptionString n v) = n ++ " = { " ++ v ++ "}"
138
139 hdr s@(Section {}) = sec s
140 hdr (PrimOpSpec { name = n }) = wrapOp n ++ ","
141 hdr (PseudoOpSpec { name = n }) = wrapOp n ++ ","
142 hdr (PrimTypeSpec { ty = TyApp n _ }) = wrapTy n ++ ","
143 hdr (PrimTypeSpec {}) = error "Illegal type spec"
144
145 ent (Section {}) = ""
146 ent o@(PrimOpSpec {}) = spec o
147 ent o@(PrimTypeSpec {}) = spec o
148 ent o@(PseudoOpSpec {}) = spec o
149
150 sec s = "\n-- * " ++ escape (title s) ++ "\n"
151 ++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ desc s) ++ "\n"
152
153 spec o = comm ++ decl
154 where decl = case o of
155 PrimOpSpec { name = n, ty = t } -> wrapOp n ++ " :: " ++ pty t
156 PseudoOpSpec { name = n, ty = t } -> wrapOp n ++ " :: " ++ pty t
157 PrimTypeSpec { ty = t } -> "data " ++ pty t
158 Section { } -> ""
159
160 comm = case (desc o) of
161 [] -> ""
162 d -> "\n" ++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ d)
163
164 pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
165 pty t = pbty t
166
167 pbty (TyApp tc ts) = tc ++ (concat (map (' ':) (map paty ts)))
168 pbty (TyUTup ts) = "(# " ++ (concat (intersperse "," (map pty ts))) ++ " #)"
169 pbty t = paty t
170
171 paty (TyVar tv) = tv
172 paty t = "(" ++ pty t ++ ")"
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 cs = s ++ mk (dropWhile isSpace cs)
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 gen_latex_doc :: Info -> String
193 gen_latex_doc (Info defaults entries)
194 = "\\primopdefaults{"
195 ++ mk_options defaults
196 ++ "}\n"
197 ++ (concat (map mk_entry entries))
198 where mk_entry (PrimOpSpec {cons=cons,name=name,ty=ty,cat=cat,desc=desc,opts=opts}) =
199 "\\primopdesc{"
200 ++ latex_encode cons ++ "}{"
201 ++ latex_encode name ++ "}{"
202 ++ latex_encode (zencode name) ++ "}{"
203 ++ latex_encode (show cat) ++ "}{"
204 ++ latex_encode (mk_source_ty ty) ++ "}{"
205 ++ latex_encode (mk_core_ty ty) ++ "}{"
206 ++ desc ++ "}{"
207 ++ mk_options opts
208 ++ "}\n"
209 mk_entry (Section {title=title,desc=desc}) =
210 "\\primopsection{"
211 ++ latex_encode title ++ "}{"
212 ++ desc ++ "}\n"
213 mk_entry (PrimTypeSpec {ty=ty,desc=desc,opts=opts}) =
214 "\\primtypespec{"
215 ++ latex_encode (mk_source_ty ty) ++ "}{"
216 ++ latex_encode (mk_core_ty ty) ++ "}{"
217 ++ desc ++ "}{"
218 ++ mk_options opts
219 ++ "}\n"
220 mk_entry (PseudoOpSpec {name=name,ty=ty,desc=desc,opts=opts}) =
221 "\\pseudoopspec{"
222 ++ latex_encode (zencode name) ++ "}{"
223 ++ latex_encode (mk_source_ty ty) ++ "}{"
224 ++ latex_encode (mk_core_ty ty) ++ "}{"
225 ++ desc ++ "}{"
226 ++ mk_options opts
227 ++ "}\n"
228 mk_source_ty t = pty t
229 where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
230 pty t = pbty t
231 pbty (TyApp tc ts) = tc ++ (concat (map (' ':) (map paty ts)))
232 pbty (TyUTup ts) = "(# " ++ (concat (intersperse "," (map pty ts))) ++ " #)"
233 pbty t = paty t
234 paty (TyVar tv) = tv
235 paty t = "(" ++ pty t ++ ")"
236
237 mk_core_ty t = foralls ++ (pty t)
238 where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
239 pty t = pbty t
240 pbty (TyApp tc ts) = (zencode tc) ++ (concat (map (' ':) (map paty ts)))
241 pbty (TyUTup ts) = (zencode (utuplenm (length ts))) ++ (concat ((map (' ':) (map paty ts))))
242 pbty t = paty t
243 paty (TyVar tv) = zencode tv
244 paty (TyApp tc []) = zencode tc
245 paty t = "(" ++ pty t ++ ")"
246 utuplenm 1 = "(# #)"
247 utuplenm n = "(#" ++ (replicate (n-1) ',') ++ "#)"
248 foralls = if tvars == [] then "" else "%forall " ++ (tbinds tvars)
249 tvars = tvars_of t
250 tbinds [] = ". "
251 tbinds ("o":tbs) = "(o::?) " ++ (tbinds tbs)
252 tbinds (tv:tbs) = tv ++ " " ++ (tbinds tbs)
253 tvars_of (TyF t1 t2) = tvars_of t1 `union` tvars_of t2
254 tvars_of (TyApp _ ts) = foldl union [] (map tvars_of ts)
255 tvars_of (TyUTup ts) = foldr union [] (map tvars_of ts)
256 tvars_of (TyVar tv) = [tv]
257
258 mk_options opts =
259 "\\primoptions{"
260 ++ mk_has_side_effects opts ++ "}{"
261 ++ mk_out_of_line opts ++ "}{"
262 ++ mk_commutable opts ++ "}{"
263 ++ mk_needs_wrapper opts ++ "}{"
264 ++ mk_can_fail opts ++ "}{"
265 ++ latex_encode (mk_strictness opts) ++ "}{"
266 ++ latex_encode (mk_usage opts)
267 ++ "}"
268
269 mk_has_side_effects opts = mk_bool_opt opts "has_side_effects" "Has side effects." "Has no side effects."
270 mk_out_of_line opts = mk_bool_opt opts "out_of_line" "Implemented out of line." "Implemented in line."
271 mk_commutable opts = mk_bool_opt opts "commutable" "Commutable." "Not commutable."
272 mk_needs_wrapper opts = mk_bool_opt opts "needs_wrapper" "Needs wrapper." "Needs no wrapper."
273 mk_can_fail opts = mk_bool_opt opts "can_fail" "Can fail." "Cannot fail."
274
275 mk_bool_opt opts opt_name if_true if_false =
276 case lookup_attrib opt_name opts of
277 Just (OptionTrue _) -> if_true
278 Just (OptionFalse _) -> if_false
279 Just (OptionString _ _) -> error "String value for boolean option"
280 Nothing -> ""
281
282 mk_strictness opts =
283 case lookup_attrib "strictness" opts of
284 Just (OptionString _ s) -> s -- for now
285 Just _ -> error "Boolean value for strictness"
286 Nothing -> ""
287
288 mk_usage opts =
289 case lookup_attrib "usage" opts of
290 Just (OptionString _ s) -> s -- for now
291 Just _ -> error "Boolean value for usage"
292 Nothing -> ""
293
294 zencode cs =
295 case maybe_tuple cs of
296 Just n -> n -- Tuples go to Z2T etc
297 Nothing -> concat (map encode_ch cs)
298 where
299 maybe_tuple "(# #)" = Just("Z1H")
300 maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of
301 (n, '#' : ')' : _) -> Just ('Z' : shows (n+1) "H")
302 _ -> Nothing
303 maybe_tuple "()" = Just("Z0T")
304 maybe_tuple ('(' : cs) = case count_commas (0::Int) cs of
305 (n, ')' : _) -> Just ('Z' : shows (n+1) "T")
306 _ -> Nothing
307 maybe_tuple _ = Nothing
308
309 count_commas :: Int -> String -> (Int, String)
310 count_commas n (',' : cs) = count_commas (n+1) cs
311 count_commas n cs = (n,cs)
312
313 unencodedChar :: Char -> Bool -- True for chars that don't need encoding
314 unencodedChar 'Z' = False
315 unencodedChar 'z' = False
316 unencodedChar c = isAlphaNum c
317
318 encode_ch :: Char -> String
319 encode_ch c | unencodedChar c = [c] -- Common case first
320
321 -- Constructors
322 encode_ch '(' = "ZL" -- Needed for things like (,), and (->)
323 encode_ch ')' = "ZR" -- For symmetry with (
324 encode_ch '[' = "ZM"
325 encode_ch ']' = "ZN"
326 encode_ch ':' = "ZC"
327 encode_ch 'Z' = "ZZ"
328
329 -- Variables
330 encode_ch 'z' = "zz"
331 encode_ch '&' = "za"
332 encode_ch '|' = "zb"
333 encode_ch '^' = "zc"
334 encode_ch '$' = "zd"
335 encode_ch '=' = "ze"
336 encode_ch '>' = "zg"
337 encode_ch '#' = "zh"
338 encode_ch '.' = "zi"
339 encode_ch '<' = "zl"
340 encode_ch '-' = "zm"
341 encode_ch '!' = "zn"
342 encode_ch '+' = "zp"
343 encode_ch '\'' = "zq"
344 encode_ch '\\' = "zr"
345 encode_ch '/' = "zs"
346 encode_ch '*' = "zt"
347 encode_ch '_' = "zu"
348 encode_ch '%' = "zv"
349 encode_ch c = 'z' : shows (ord c) "U"
350
351 latex_encode [] = []
352 latex_encode (c:cs) | c `elem` "#$%&_^{}" = "\\" ++ c:(latex_encode cs)
353 latex_encode ('~':cs) = "\\verb!~!" ++ (latex_encode cs)
354 latex_encode ('\\':cs) = "$\\backslash$" ++ (latex_encode cs)
355 latex_encode (c:cs) = c:(latex_encode cs)
356
357 gen_wrappers :: Info -> String
358 gen_wrappers (Info _ entries)
359 = "{-# OPTIONS -fno-implicit-prelude #-}\n"
360 -- Dependencies on Prelude must be explicit in libraries/base, but we
361 -- don't need the Prelude here so we add -fno-implicit-prelude.
362 ++ "module GHC.PrimopWrappers where\n"
363 ++ "import qualified GHC.Prim\n"
364 ++ unlines (map f (filter (not.dodgy) (filter is_primop entries)))
365 where
366 f spec = let args = map (\n -> "a" ++ show n) [1 .. arity (ty spec)]
367 src_name = wrap (name spec)
368 in "{-# NOINLINE " ++ src_name ++ " #-}\n" ++
369 src_name ++ " " ++ unwords args
370 ++ " = (GHC.Prim." ++ name spec ++ ") " ++ unwords args
371 wrap nm | isLower (head nm) = nm
372 | otherwise = "(" ++ nm ++ ")"
373
374 dodgy spec
375 = name spec `elem`
376 [-- C code generator can't handle these
377 "seq#",
378 "tagToEnum#",
379 -- not interested in parallel support
380 "par#", "parGlobal#", "parLocal#", "parAt#",
381 "parAtAbs#", "parAtRel#", "parAtForNow#"
382 ]
383
384 gen_primop_list :: Info -> String
385 gen_primop_list (Info _ entries)
386 = unlines (
387 [ " [" ++ cons first ]
388 ++
389 map (\pi -> " , " ++ cons pi) rest
390 ++
391 [ " ]" ]
392 ) where (first:rest) = filter is_primop entries
393
394 gen_primop_tag :: Info -> String
395 gen_primop_tag (Info _ entries)
396 = unlines (max_def : zipWith f primop_entries [1 :: Int ..])
397 where
398 primop_entries = filter is_primop entries
399 f i n = "tagOf_PrimOp " ++ cons i
400 ++ " = _ILIT(" ++ show n ++ ") :: FastInt"
401 max_def = "maxPrimOpTag = " ++ show (length primop_entries) ++ " :: Int"
402
403 gen_data_decl :: Info -> String
404 gen_data_decl (Info _ entries)
405 = let conss = map cons (filter is_primop entries)
406 in "data PrimOp\n = " ++ head conss ++ "\n"
407 ++ unlines (map (" | "++) (tail conss))
408
409 gen_switch_from_attribs :: String -> String -> Info -> String
410 gen_switch_from_attribs attrib_name fn_name (Info defaults entries)
411 = let defv = lookup_attrib attrib_name defaults
412 alts = catMaybes (map mkAlt (filter is_primop entries))
413
414 getAltRhs (OptionFalse _) = "False"
415 getAltRhs (OptionTrue _) = "True"
416 getAltRhs (OptionString _ s) = s
417
418 mkAlt po
419 = case lookup_attrib attrib_name (opts po) of
420 Nothing -> Nothing
421 Just xx -> Just (fn_name ++ " " ++ cons po ++ " = " ++ getAltRhs xx)
422
423 in
424 case defv of
425 Nothing -> error ("gen_switch_from: " ++ attrib_name)
426 Just xx
427 -> unlines alts
428 ++ fn_name ++ " other = " ++ getAltRhs xx ++ "\n"
429
430 ------------------------------------------------------------------
431 -- Create PrimOpInfo text from PrimOpSpecs -----------------------
432 ------------------------------------------------------------------
433
434 gen_primop_info :: Info -> String
435 gen_primop_info (Info _ entries)
436 = unlines (map mkPOItext (filter is_primop entries))
437
438 mkPOItext :: Entry -> String
439 mkPOItext i = mkPOI_LHS_text i ++ mkPOI_RHS_text i
440
441 mkPOI_LHS_text :: Entry -> String
442 mkPOI_LHS_text i
443 = "primOpInfo " ++ cons i ++ " = "
444
445 mkPOI_RHS_text :: Entry -> String
446 mkPOI_RHS_text i
447 = case cat i of
448 Compare
449 -> case ty i of
450 TyF t1 (TyF _ _)
451 -> "mkCompare " ++ sl_name i ++ ppType t1
452 _ -> error "Type error in comparison op"
453 Monadic
454 -> case ty i of
455 TyF t1 _
456 -> "mkMonadic " ++ sl_name i ++ ppType t1
457 _ -> error "Type error in monadic op"
458 Dyadic
459 -> case ty i of
460 TyF t1 (TyF _ _)
461 -> "mkDyadic " ++ sl_name i ++ ppType t1
462 _ -> error "Type error in dyadic op"
463 GenPrimOp
464 -> let (argTys, resTy) = flatTys (ty i)
465 tvs = nub (tvsIn (ty i))
466 in
467 "mkGenPrimOp " ++ sl_name i ++ " "
468 ++ listify (map ppTyVar tvs) ++ " "
469 ++ listify (map ppType argTys) ++ " "
470 ++ "(" ++ ppType resTy ++ ")"
471
472 sl_name :: Entry -> String
473 sl_name i = "FSLIT(\"" ++ name i ++ "\") "
474
475 ppTyVar :: String -> String
476 ppTyVar "a" = "alphaTyVar"
477 ppTyVar "b" = "betaTyVar"
478 ppTyVar "c" = "gammaTyVar"
479 ppTyVar "s" = "deltaTyVar"
480 ppTyVar "o" = "openAlphaTyVar"
481 ppTyVar _ = error "Unknown type var"
482
483 ppType :: Ty -> String
484 ppType (TyApp "Bool" []) = "boolTy"
485
486 ppType (TyApp "Int#" []) = "intPrimTy"
487 ppType (TyApp "Int32#" []) = "int32PrimTy"
488 ppType (TyApp "Int64#" []) = "int64PrimTy"
489 ppType (TyApp "Char#" []) = "charPrimTy"
490 ppType (TyApp "Word#" []) = "wordPrimTy"
491 ppType (TyApp "Word32#" []) = "word32PrimTy"
492 ppType (TyApp "Word64#" []) = "word64PrimTy"
493 ppType (TyApp "Addr#" []) = "addrPrimTy"
494 ppType (TyApp "Float#" []) = "floatPrimTy"
495 ppType (TyApp "Double#" []) = "doublePrimTy"
496 ppType (TyApp "ByteArr#" []) = "byteArrayPrimTy"
497 ppType (TyApp "RealWorld" []) = "realWorldTy"
498 ppType (TyApp "ThreadId#" []) = "threadIdPrimTy"
499 ppType (TyApp "ForeignObj#" []) = "foreignObjPrimTy"
500 ppType (TyApp "BCO#" []) = "bcoPrimTy"
501 ppType (TyApp "()" []) = "unitTy" -- unitTy is TysWiredIn's name for ()
502
503 ppType (TyVar "a") = "alphaTy"
504 ppType (TyVar "b") = "betaTy"
505 ppType (TyVar "c") = "gammaTy"
506 ppType (TyVar "s") = "deltaTy"
507 ppType (TyVar "o") = "openAlphaTy"
508 ppType (TyApp "State#" [x]) = "mkStatePrimTy " ++ ppType x
509 ppType (TyApp "MutVar#" [x,y]) = "mkMutVarPrimTy " ++ ppType x
510 ++ " " ++ ppType y
511 ppType (TyApp "MutArr#" [x,y]) = "mkMutableArrayPrimTy " ++ ppType x
512 ++ " " ++ ppType y
513
514 ppType (TyApp "MutByteArr#" [x]) = "mkMutableByteArrayPrimTy "
515 ++ ppType x
516
517 ppType (TyApp "Array#" [x]) = "mkArrayPrimTy " ++ ppType x
518
519
520 ppType (TyApp "Weak#" [x]) = "mkWeakPrimTy " ++ ppType x
521 ppType (TyApp "StablePtr#" [x]) = "mkStablePtrPrimTy " ++ ppType x
522 ppType (TyApp "StableName#" [x]) = "mkStableNamePrimTy " ++ ppType x
523
524 ppType (TyApp "MVar#" [x,y]) = "mkMVarPrimTy " ++ ppType x
525 ++ " " ++ ppType y
526 ppType (TyApp "TVar#" [x,y]) = "mkTVarPrimTy " ++ ppType x
527 ++ " " ++ ppType y
528 ppType (TyUTup ts) = "(mkTupleTy Unboxed " ++ show (length ts)
529 ++ " "
530 ++ listify (map ppType ts) ++ ")"
531
532 ppType (TyF s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))"
533
534 ppType other
535 = error ("ppType: can't handle: " ++ show other ++ "\n")
536
537 listify :: [String] -> String
538 listify ss = "[" ++ concat (intersperse ", " ss) ++ "]"
539
540 flatTys :: Ty -> ([Ty],Ty)
541 flatTys (TyF t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t)
542 flatTys other = ([],other)
543
544 tvsIn :: Ty -> [TyVar]
545 tvsIn (TyF t1 t2) = tvsIn t1 ++ tvsIn t2
546 tvsIn (TyApp _ tys) = concatMap tvsIn tys
547 tvsIn (TyVar tv) = [tv]
548 tvsIn (TyUTup tys) = concatMap tvsIn tys
549
550 arity :: Ty -> Int
551 arity = length . fst . flatTys
552
553 ------------------------------------------------------------------
554 -- Abstract syntax -----------------------------------------------
555 ------------------------------------------------------------------
556
557 -- info for all primops; the totality of the info in primops.txt(.pp)
558 data Info
559 = Info [Option] [Entry] -- defaults, primops
560 deriving Show
561
562 -- info for one primop
563 data Entry
564 = PrimOpSpec { cons :: String, -- PrimOp name
565 name :: String, -- name in prog text
566 ty :: Ty, -- type
567 cat :: Category, -- category
568 desc :: String, -- description
569 opts :: [Option] } -- default overrides
570 | PseudoOpSpec { name :: String, -- name in prog text
571 ty :: Ty, -- type
572 desc :: String, -- description
573 opts :: [Option] } -- default overrides
574 | PrimTypeSpec { ty :: Ty, -- name in prog text
575 desc :: String, -- description
576 opts :: [Option] } -- default overrides
577 | Section { title :: String, -- section title
578 desc :: String } -- description
579 deriving Show
580
581 is_primop :: Entry -> Bool
582 is_primop (PrimOpSpec _ _ _ _ _ _) = True
583 is_primop _ = False
584
585 -- a binding of property to value
586 data Option
587 = OptionFalse String -- name = False
588 | OptionTrue String -- name = True
589 | OptionString String String -- name = { ... unparsed stuff ... }
590 deriving Show
591
592 -- categorises primops
593 data Category
594 = Dyadic | Monadic | Compare | GenPrimOp
595 deriving Show
596
597 -- types
598 data Ty
599 = TyF Ty Ty
600 | TyApp TyCon [Ty]
601 | TyVar TyVar
602 | TyUTup [Ty] -- unboxed tuples; just a TyCon really,
603 -- but convenient like this
604 deriving (Eq,Show)
605
606 type TyVar = String
607 type TyCon = String
608
609
610 ------------------------------------------------------------------
611 -- Sanity checking -----------------------------------------------
612 ------------------------------------------------------------------
613
614 {- Do some simple sanity checks:
615 * all the default field names are unique
616 * for each PrimOpSpec, all override field names are unique
617 * for each PrimOpSpec, all overriden field names
618 have a corresponding default value
619 * that primop types correspond in certain ways to the
620 Category: eg if Comparison, the type must be of the form
621 T -> T -> Bool.
622 Dies with "error" if there's a problem, else returns ().
623 -}
624 myseq :: () -> a -> a
625 myseq () x = x
626
627 myseqAll :: [()] -> a -> a
628 myseqAll (():ys) x = myseqAll ys x
629 myseqAll [] x = x
630
631 sanityTop :: Info -> ()
632 sanityTop (Info defs entries)
633 = let opt_names = map get_attrib_name defs
634 primops = filter is_primop entries
635 in
636 if length opt_names /= length (nub opt_names)
637 then error ("non-unique default attribute names: " ++ show opt_names ++ "\n")
638 else myseqAll (map (sanityPrimOp opt_names) primops) ()
639
640 sanityPrimOp :: [String] -> Entry -> ()
641 sanityPrimOp def_names p
642 = let p_names = map get_attrib_name (opts p)
643 p_names_ok
644 = length p_names == length (nub p_names)
645 && all (`elem` def_names) p_names
646 ty_ok = sane_ty (cat p) (ty p)
647 in
648 if not p_names_ok
649 then error ("attribute names are non-unique or have no default in\n" ++
650 "info for primop " ++ cons p ++ "\n")
651 else
652 if not ty_ok
653 then error ("type of primop " ++ cons p ++ " doesn't make sense w.r.t" ++
654 " category " ++ show (cat p) ++ "\n")
655 else ()
656
657 sane_ty :: Category -> Ty -> Bool
658 sane_ty Compare (TyF t1 (TyF t2 td))
659 | t1 == t2 && td == TyApp "Bool" [] = True
660 sane_ty Monadic (TyF t1 td)
661 | t1 == td = True
662 sane_ty Dyadic (TyF t1 (TyF t2 _))
663 | t1 == t2 && t2 == t2 = True
664 sane_ty GenPrimOp _
665 = True
666 sane_ty _ _
667 = False
668
669 get_attrib_name :: Option -> String
670 get_attrib_name (OptionFalse nm) = nm
671 get_attrib_name (OptionTrue nm) = nm
672 get_attrib_name (OptionString nm _) = nm
673
674 lookup_attrib :: String -> [Option] -> Maybe Option
675 lookup_attrib _ [] = Nothing
676 lookup_attrib nm (a:as)
677 = if get_attrib_name a == nm then Just a else lookup_attrib nm as
678
679 ------------------------------------------------------------------
680 -- The parser ----------------------------------------------------
681 ------------------------------------------------------------------
682
683 keywords :: [String]
684 keywords = [ "section", "primop", "pseudoop", "primtype", "with"]
685
686 -- Due to lack of proper lexing facilities, a hack to zap any
687 -- leading comments
688 pTop :: Parser Info
689 pTop = then4 (\_ ds es _ -> Info ds es)
690 pCommentAndWhitespace pDefaults (many pEntry)
691 (lit "thats_all_folks")
692
693 pEntry :: Parser Entry
694 pEntry
695 = alts [pPrimOpSpec, pPrimTypeSpec, pPseudoOpSpec, pSection]
696
697 pSection :: Parser Entry
698 pSection = then3 (\_ n d -> Section {title = n, desc = d})
699 (lit "section") stringLiteral pDesc
700
701 pDefaults :: Parser [Option]
702 pDefaults = then2 sel22 (lit "defaults") (many pOption)
703
704 pOption :: Parser Option
705 pOption
706 = alts [
707 then3 (\nm _ _ -> OptionFalse nm) pName (lit "=") (lit "False"),
708 then3 (\nm _ _ -> OptionTrue nm) pName (lit "=") (lit "True"),
709 then3 (\nm _ zz -> OptionString nm zz)
710 pName (lit "=") pStuffBetweenBraces
711 ]
712
713 pPrimOpSpec :: Parser Entry
714 pPrimOpSpec
715 = then7 (\_ c n k t d o -> PrimOpSpec { cons = c, name = n, ty = t,
716 cat = k, desc = d, opts = o } )
717 (lit "primop") pConstructor stringLiteral
718 pCategory pType pDesc pOptions
719
720 pPrimTypeSpec :: Parser Entry
721 pPrimTypeSpec
722 = then4 (\_ t d o -> PrimTypeSpec { ty = t, desc = d, opts = o } )
723 (lit "primtype") pType pDesc pOptions
724
725 pPseudoOpSpec :: Parser Entry
726 pPseudoOpSpec
727 = then5 (\_ n t d o -> PseudoOpSpec { name = n, ty = t, desc = d,
728 opts = o } )
729 (lit "pseudoop") stringLiteral pType pDesc pOptions
730
731 pOptions :: Parser [Option]
732 pOptions = optdef [] (then2 sel22 (lit "with") (many pOption))
733
734 pCategory :: Parser Category
735 pCategory
736 = alts [
737 apply (const Dyadic) (lit "Dyadic"),
738 apply (const Monadic) (lit "Monadic"),
739 apply (const Compare) (lit "Compare"),
740 apply (const GenPrimOp) (lit "GenPrimOp")
741 ]
742
743 pDesc :: Parser String
744 pDesc = optdef "" pStuffBetweenBraces
745
746 pStuffBetweenBraces :: Parser String
747 pStuffBetweenBraces
748 = lexeme (
749 do char '{'
750 ass <- many pInsides
751 char '}'
752 return (concat ass) )
753
754 pInsides :: Parser String
755 pInsides
756 = (do char '{'
757 stuff <- many pInsides
758 char '}'
759 return ("{" ++ (concat stuff) ++ "}"))
760 <|>
761 (do c <- satisfy (/= '}')
762 return [c])
763
764 -------------------
765 -- Parsing types --
766 -------------------
767
768 pType :: Parser Ty
769 pType = then2 (\t maybe_tt -> case maybe_tt of
770 Just tt -> TyF t tt
771 Nothing -> t)
772 paT
773 (opt (then2 sel22 (lit "->") pType))
774
775 -- Atomic types
776 paT :: Parser Ty
777 paT = alts [ then2 TyApp pTycon (many ppT),
778 pUnboxedTupleTy,
779 then3 sel23 (lit "(") pType (lit ")"),
780 ppT
781 ]
782
783 -- the magic bit in the middle is: T (,T)* so to speak
784 pUnboxedTupleTy :: Parser Ty
785 pUnboxedTupleTy
786 = then3 (\ _ ts _ -> TyUTup ts)
787 (lit "(#")
788 (then2 (:) pType (many (then2 sel22 (lit ",") pType)))
789 (lit "#)")
790
791 -- Primitive types
792 ppT :: Parser Ty
793 ppT = alts [apply TyVar pTyvar,
794 apply (\tc -> TyApp tc []) pTycon
795 ]
796
797 pTyvar :: Parser String
798 pTyvar = sat (`notElem` keywords) pName
799
800 pTycon :: Parser String
801 pTycon = alts [pConstructor, lexeme (string "()")]
802
803 pName :: Parser String
804 pName = lexeme (then2 (:) lower (many isIdChar))
805
806 pConstructor :: Parser String
807 pConstructor = lexeme (then2 (:) upper (many isIdChar))
808
809 isIdChar :: Parser Char
810 isIdChar = satisfy (`elem` idChars)
811
812 idChars :: [Char]
813 idChars = ['a' .. 'z'] ++ ['A' .. 'Z'] ++ ['0' .. '9'] ++ "#_"
814
815 sat :: (a -> Bool) -> Parser a -> Parser a
816 sat pred p
817 = do x <- try p
818 if pred x
819 then return x
820 else pzero
821
822 ------------------------------------------------------------------
823 -- Helpful additions to Daan's parser stuff ----------------------
824 ------------------------------------------------------------------
825
826 alts :: [Parser a] -> Parser a
827 alts [] = pzero
828 alts [p1] = try p1
829 alts (p1:p2:ps) = (try p1) <|> alts (p2:ps)
830
831 then2 :: (a -> b -> c) -> Parser a -> Parser b -> Parser c
832 then2 f p1 p2
833 = do x1 <- p1 ; x2 <- p2 ; return (f x1 x2)
834
835 then3 :: (a -> b -> c -> d) -> Parser a -> Parser b -> Parser c -> Parser d
836 then3 f p1 p2 p3
837 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; return (f x1 x2 x3)
838
839 then4 :: (a -> b -> c -> d -> e) -> Parser a -> Parser b -> Parser c -> Parser d -> Parser e
840 then4 f p1 p2 p3 p4
841 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; return (f x1 x2 x3 x4)
842
843 then5 :: (a -> b -> c -> d -> e -> f) -> Parser a -> Parser b -> Parser c -> Parser d -> Parser e -> Parser f
844 then5 f p1 p2 p3 p4 p5
845 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5
846 return (f x1 x2 x3 x4 x5)
847
848 then6 :: (a -> b -> c -> d -> e -> f -> g) -> Parser a -> Parser b -> Parser c -> Parser d -> Parser e -> Parser f -> Parser g
849 then6 f p1 p2 p3 p4 p5 p6
850 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5 ; x6 <- p6
851 return (f x1 x2 x3 x4 x5 x6)
852
853 then7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> Parser a -> Parser b -> Parser c -> Parser d -> Parser e -> Parser f -> Parser g -> Parser h
854 then7 f p1 p2 p3 p4 p5 p6 p7
855 = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5 ; x6 <- p6 ; x7 <- p7
856 return (f x1 x2 x3 x4 x5 x6 x7)
857
858 opt :: Parser a -> Parser (Maybe a)
859 opt p
860 = (do x <- p; return (Just x)) <|> return Nothing
861
862 optdef :: a -> Parser a -> Parser a
863 optdef d p
864 = (do x <- p; return x) <|> return d
865
866 sel12 :: a -> b -> a
867 sel12 a _ = a
868
869 sel22 :: a -> b -> b
870 sel22 _ b = b
871
872 sel23 :: a -> b -> c -> b
873 sel23 _ b _ = b
874
875 apply :: (a -> b) -> Parser a -> Parser b
876 apply f p = liftM f p
877
878 -- Hacks for zapping whitespace and comments, unfortunately needed
879 -- because Daan won't let us have a lexer before the parser :-(
880 lexeme :: Parser p -> Parser p
881 lexeme p = then2 sel12 p pCommentAndWhitespace
882
883 lit :: String -> Parser ()
884 lit s = apply (const ()) (lexeme (string s))
885
886 pCommentAndWhitespace :: Parser ()
887 pCommentAndWhitespace
888 = apply (const ()) (many (alts [pLineComment,
889 apply (const ()) (satisfy isSpace)]))
890 <|>
891 return ()
892
893 pLineComment :: Parser ()
894 pLineComment
895 = try (then3 (\_ _ _ -> ()) (string "--") (many (satisfy (/= '\n'))) (char '\n'))
896
897 stringLiteral :: Parser String
898 stringLiteral = lexeme (
899 do { between (char '"')
900 (char '"' <?> "end of string")
901 (many (noneOf "\""))
902 }
903 <?> "literal string")
904
905 ------------------------------------------------------------------
906 -- end --
907 ------------------------------------------------------------------