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