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