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