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