[project @ 2002-02-04 03:40:31 by chak]
[ghc-hetmet.git] / ghc / compiler / parser / Lex.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[Lexical analysis]{Lexical analysis}
5
6 --------------------------------------------------------
7 [Jan 98]
8 There's a known bug in here:
9
10         If an interface file ends prematurely, Lex tries to
11         do headFS of an empty FastString.
12
13 An example that provokes the error is
14
15         f _:_ _forall_ [a] <<<END OF FILE>>>
16 --------------------------------------------------------
17
18 \begin{code}
19
20 module Lex (
21
22         ifaceParseErr, srcParseErr,
23
24         -- Monad for parser
25         Token(..), lexer, ParseResult(..), PState(..),
26         checkVersion, 
27         StringBuffer,
28
29         P, thenP, thenP_, returnP, mapP, failP, failMsgP,
30         getSrcLocP, setSrcLocP, getSrcFile,
31         layoutOn, layoutOff, pushContext, popContext
32     ) where
33
34 #include "HsVersions.h"
35
36 import Char             ( isSpace, toUpper )
37 import List             ( isSuffixOf )
38
39 import PrelNames        ( mkTupNameStr )
40 import CmdLineOpts      ( opt_HiVersion, opt_NoHiCheck )
41 import ForeignCall      ( Safety(..) )
42 import NewDemand        ( StrictSig(..), Demand(..), Demands(..),
43                           DmdResult(..), mkTopDmdType, evalDmd, lazyDmd )
44 import UniqFM           ( listToUFM, lookupUFM )
45 import BasicTypes       ( Boxity(..) )
46 import SrcLoc           ( SrcLoc, incSrcLine, srcLocFile, srcLocLine,
47                           replaceSrcLine, mkSrcLoc )
48
49 import ErrUtils         ( Message )
50 import Outputable
51
52 import FastString
53 import StringBuffer
54 import GlaExts
55 import Ctype
56 import Char             ( chr, ord )
57 import PrelRead         ( readRational__ ) -- Glasgow non-std
58 \end{code}
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection{Data types}
63 %*                                                                      *
64 %************************************************************************
65
66 The token data type, fairly un-interesting except from one
67 constructor, @ITidinfo@, which is used to lazily lex id info (arity,
68 strictness, unfolding etc).
69
70 The Idea/Observation here is that the renamer needs to scan through
71 all of an interface file before it can continue. But only a fraction
72 of the information contained in the file turns out to be useful, so
73 delaying as much as possible of the scanning and parsing of an
74 interface file Makes Sense (Heap profiles of the compiler 
75 show a reduction in heap usage by at least a factor of two,
76 post-renamer). 
77
78 Hence, the interface file lexer spots when value declarations are
79 being scanned and return the @ITidinfo@ and @ITtype@ constructors
80 for the type and any other id info for that binding (unfolding, strictness
81 etc). These constructors are applied to the result of lexing these sub-chunks.
82
83 The lexing of the type and id info is all done lazily, of course, so
84 the scanning (and subsequent parsing) will be done *only* on the ids the
85 renamer finds out that it is interested in. The rest will just be junked.
86 Laziness, you know it makes sense :-)
87
88 \begin{code}
89 data Token
90   = ITas                        -- Haskell keywords
91   | ITcase
92   | ITclass
93   | ITdata
94   | ITdefault
95   | ITderiving
96   | ITdo
97   | ITelse
98   | IThiding
99   | ITif
100   | ITimport
101   | ITin
102   | ITinfix
103   | ITinfixl
104   | ITinfixr
105   | ITinstance
106   | ITlet
107   | ITmodule
108   | ITnewtype
109   | ITof
110   | ITqualified
111   | ITthen
112   | ITtype
113   | ITwhere
114   | ITscc                       -- ToDo: remove (we use {-# SCC "..." #-} now)
115
116   | ITforall                    -- GHC extension keywords
117   | ITforeign
118   | ITexport
119   | ITlabel
120   | ITdynamic
121   | ITsafe
122   | ITunsafe
123   | ITwith
124   | ITstdcallconv
125   | ITccallconv
126   | ITdotnet
127
128   | ITinterface                 -- interface keywords
129   | IT__export
130   | ITdepends
131   | IT__forall
132   | ITletrec 
133   | ITcoerce
134   | ITinlineMe
135   | ITinlineCall
136   | ITccall (Bool,Bool,Safety)  -- (is_dyn, is_casm, may_gc)
137   | ITdefaultbranch
138   | ITbottom
139   | ITinteger_lit 
140   | ITfloat_lit
141   | ITword_lit
142   | ITword64_lit
143   | ITint64_lit
144   | ITrational_lit
145   | ITaddr_lit
146   | ITlabel_lit
147   | ITlit_lit
148   | ITstring_lit
149   | ITtypeapp
150   | ITusage
151   | ITfuall
152   | ITarity 
153   | ITspecialise
154   | ITnocaf
155   | ITunfold
156   | ITstrict StrictSig
157   | ITrules
158   | ITcprinfo
159   | ITdeprecated
160   | IT__scc
161   | ITsccAllCafs
162
163   | ITspecialise_prag           -- Pragmas
164   | ITsource_prag
165   | ITinline_prag
166   | ITnoinline_prag
167   | ITrules_prag
168   | ITdeprecated_prag
169   | ITline_prag
170   | ITscc_prag
171   | ITclose_prag
172
173   | ITdotdot                    -- reserved symbols
174   | ITdcolon
175   | ITequal
176   | ITlam
177   | ITvbar
178   | ITlarrow
179   | ITrarrow
180   | ITat
181   | ITtilde
182   | ITdarrow
183   | ITminus
184   | ITbang
185   | ITdot
186
187   | ITbiglam                    -- GHC-extension symbols
188
189   | ITocurly                    -- special symbols
190   | ITccurly
191   | ITocurlybar                 -- {|, for type applications
192   | ITccurlybar                 -- |}, for type applications
193   | ITvccurly
194   | ITobrack
195   | ITcbrack
196   | IToparen
197   | ITcparen
198   | IToubxparen
199   | ITcubxparen
200   | ITsemi
201   | ITcomma
202   | ITunderscore
203   | ITbackquote
204
205   | ITvarid   FAST_STRING       -- identifiers
206   | ITconid   FAST_STRING
207   | ITvarsym  FAST_STRING
208   | ITconsym  FAST_STRING
209   | ITqvarid  (FAST_STRING,FAST_STRING)
210   | ITqconid  (FAST_STRING,FAST_STRING)
211   | ITqvarsym (FAST_STRING,FAST_STRING)
212   | ITqconsym (FAST_STRING,FAST_STRING)
213
214   | ITdupipvarid   FAST_STRING  -- GHC extension: implicit param: ?x
215   | ITsplitipvarid FAST_STRING  -- GHC extension: implicit param: %x
216
217   | ITpragma StringBuffer
218
219   | ITchar       Int
220   | ITstring     FAST_STRING
221   | ITinteger    Integer
222   | ITrational   Rational
223
224   | ITprimchar   Int
225   | ITprimstring FAST_STRING
226   | ITprimint    Integer
227   | ITprimfloat  Rational
228   | ITprimdouble Rational
229   | ITlitlit     FAST_STRING
230
231   | ITunknown String            -- Used when the lexer can't make sense of it
232   | ITeof                       -- end of file token
233   deriving Show -- debugging
234 \end{code}
235
236 -----------------------------------------------------------------------------
237 Keyword Lists
238
239 \begin{code}
240 pragmaKeywordsFM = listToUFM $
241       map (\ (x,y) -> (_PK_ x,y))
242        [( "SPECIALISE", ITspecialise_prag ),
243         ( "SPECIALIZE", ITspecialise_prag ),
244         ( "SOURCE",     ITsource_prag ),
245         ( "INLINE",     ITinline_prag ),
246         ( "NOINLINE",   ITnoinline_prag ),
247         ( "NOTINLINE",  ITnoinline_prag ),
248         ( "LINE",       ITline_prag ),
249         ( "RULES",      ITrules_prag ),
250         ( "RULEZ",      ITrules_prag ), -- american spelling :-)
251         ( "SCC",        ITscc_prag ),
252         ( "DEPRECATED", ITdeprecated_prag )
253         ]
254
255 haskellKeywordsFM = listToUFM $
256       map (\ (x,y) -> (_PK_ x,y))
257        [( "_",          ITunderscore ),
258         ( "as",         ITas ),
259         ( "case",       ITcase ),     
260         ( "class",      ITclass ),    
261         ( "data",       ITdata ),     
262         ( "default",    ITdefault ),  
263         ( "deriving",   ITderiving ), 
264         ( "do",         ITdo ),       
265         ( "else",       ITelse ),     
266         ( "hiding",     IThiding ),
267         ( "if",         ITif ),       
268         ( "import",     ITimport ),   
269         ( "in",         ITin ),       
270         ( "infix",      ITinfix ),    
271         ( "infixl",     ITinfixl ),   
272         ( "infixr",     ITinfixr ),   
273         ( "instance",   ITinstance ), 
274         ( "let",        ITlet ),      
275         ( "module",     ITmodule ),   
276         ( "newtype",    ITnewtype ),  
277         ( "of",         ITof ),       
278         ( "qualified",  ITqualified ),
279         ( "then",       ITthen ),     
280         ( "type",       ITtype ),     
281         ( "where",      ITwhere ),
282         ( "_scc_",      ITscc )         -- ToDo: remove
283      ]
284
285 isSpecial :: Token -> Bool
286 -- If we see M.x, where x is a keyword, but
287 -- is special, we treat is as just plain M.x, 
288 -- not as a keyword.
289 isSpecial ITas          = True
290 isSpecial IThiding      = True
291 isSpecial ITqualified   = True
292 isSpecial ITforall      = True
293 isSpecial ITexport      = True
294 isSpecial ITlabel       = True
295 isSpecial ITdynamic     = True
296 isSpecial ITsafe        = True
297 isSpecial ITunsafe      = True
298 isSpecial ITwith        = True
299 isSpecial ITccallconv   = True
300 isSpecial ITstdcallconv = True
301 isSpecial _             = False
302
303 -- IMPORTANT: Keep this in synch with ParseIface.y's var_fs production! (SUP)
304 ghcExtensionKeywordsFM = listToUFM $
305         map (\ (x,y) -> (_PK_ x,y))
306      [  ( "forall",     ITforall ),
307         ( "foreign",    ITforeign ),
308         ( "export",     ITexport ),
309         ( "label",      ITlabel ),
310         ( "dynamic",    ITdynamic ),
311         ( "safe",       ITunsafe ),
312         ( "unsafe",     ITunsafe ),
313         ( "with",       ITwith ),
314         ( "stdcall",    ITstdcallconv),
315         ( "ccall",      ITccallconv),
316         ( "dotnet",     ITdotnet),
317         ("_ccall_",     ITccall (False, False, PlayRisky)),
318         ("_ccall_GC_",  ITccall (False, False, PlaySafe)),
319         ("_casm_",      ITccall (False, True,  PlayRisky)),
320         ("_casm_GC_",   ITccall (False, True,  PlaySafe)),
321
322         -- interface keywords
323         ("__interface",         ITinterface),
324         ("__export",            IT__export),
325         ("__depends",           ITdepends),
326         ("__forall",            IT__forall),
327         ("__letrec",            ITletrec),
328         ("__coerce",            ITcoerce),
329         ("__inline_me",         ITinlineMe),
330         ("__inline_call",       ITinlineCall),
331         ("__depends",           ITdepends),
332         ("__DEFAULT",           ITdefaultbranch),
333         ("__bot",               ITbottom),
334         ("__integer",           ITinteger_lit),
335         ("__float",             ITfloat_lit),
336         ("__int64",             ITint64_lit),
337         ("__word",              ITword_lit),
338         ("__word64",            ITword64_lit),
339         ("__rational",          ITrational_lit),
340         ("__addr",              ITaddr_lit),
341         ("__label",             ITlabel_lit),
342         ("__litlit",            ITlit_lit),
343         ("__string",            ITstring_lit),
344         ("__a",                 ITtypeapp),
345         ("__u",                 ITusage),
346         ("__fuall",             ITfuall),
347         ("__A",                 ITarity),
348         ("__P",                 ITspecialise),
349         ("__C",                 ITnocaf),
350         ("__R",                 ITrules),
351         ("__D",                 ITdeprecated),
352         ("__U",                 ITunfold),
353         
354         ("__ccall",             ITccall (False, False, PlayRisky)),
355         ("__ccall_GC",          ITccall (False, False, PlaySafe)),
356         ("__dyn_ccall",         ITccall (True,  False, PlayRisky)),
357         ("__dyn_ccall_GC",      ITccall (True,  False, PlaySafe)),
358         ("__casm",              ITccall (False, True,  PlayRisky)),
359         ("__dyn_casm",          ITccall (True,  True,  PlayRisky)),
360         ("__casm_GC",           ITccall (False, True,  PlaySafe)),
361         ("__dyn_casm_GC",       ITccall (True,  True,  PlaySafe)),
362
363         ("/\\",                 ITbiglam)
364      ]
365
366
367 haskellKeySymsFM = listToUFM $
368         map (\ (x,y) -> (_PK_ x,y))
369       [ ("..",          ITdotdot)
370        ,("::",          ITdcolon)
371        ,("=",           ITequal)
372        ,("\\",          ITlam)
373        ,("|",           ITvbar)
374        ,("<-",          ITlarrow)
375        ,("->",          ITrarrow)
376        ,("@",           ITat)
377        ,("~",           ITtilde)
378        ,("=>",          ITdarrow)
379        ,("-",           ITminus)
380        ,("!",           ITbang)
381        ,(".",           ITdot)          -- sadly, for 'forall a . t'
382        ]
383 \end{code}
384
385 -----------------------------------------------------------------------------
386 The lexical analyser
387
388 Lexer state:
389
390         - (glaexts) lexing an interface file or -fglasgow-exts
391         - (bol)   pointer to beginning of line (for column calculations)
392         - (buf)   pointer to beginning of token
393         - (buf)   pointer to current char
394         - (atbol) flag indicating whether we're at the beginning of a line
395
396 \begin{code}
397 lexer :: (Token -> P a) -> P a
398 lexer cont buf s@(PState{
399                     loc = loc,
400                     glasgow_exts = glaexts,
401                     bol = bol,
402                     atbol = atbol,
403                     context = ctx
404                 })
405
406         -- first, start a new lexeme and lose all the whitespace
407   =  _scc_ "Lexer" 
408   tab line bol atbol (stepOverLexeme buf)
409   where
410         line = srcLocLine loc
411
412         tab y bol atbol buf = --trace ("tab: " ++ show (I# y) ++ " : " ++ show (currentChar buf)) $
413           case currentChar# buf of
414
415             '\NUL'# ->
416                    if bufferExhausted (stepOn buf)
417                         then cont ITeof buf s'
418                         else trace "lexer: misplaced NUL?" $ 
419                              tab y bol atbol (stepOn buf)
420
421             '\n'# -> let buf' = stepOn buf
422                      in tab (y +# 1#) (currentIndex# buf') 1# buf'
423
424                 -- find comments.  This got harder in Haskell 98.
425             '-'# ->  let trundle n = 
426                           let next = lookAhead# buf n in
427                           if next `eqChar#` '-'# then trundle (n +# 1#)
428                           else if is_symbol next || n <# 2#
429                                 then is_a_token
430                                 else tab y bol atbol 
431                                          (stepOnUntilChar# (stepOnBy# buf n) '\n'#)
432                     in trundle 1#
433
434                 -- comments and pragmas.  We deal with LINE pragmas here,
435                 -- and throw out any unrecognised pragmas as comments.  Any
436                 -- pragmas we know about are dealt with later (after any layout
437                 -- processing if necessary).
438             '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
439                 if lookAhead# buf 2# `eqChar#` '#'# then
440                   if lookAhead# buf 3# `eqChar#` '#'# then is_a_token else
441                   case expandWhile# is_space (setCurrentPos# buf 3#) of { buf1->
442                   case expandWhile# is_ident (stepOverLexeme buf1)   of { buf2->
443                   let lexeme = mkFastString -- ToDo: too slow
444                                   (map toUpper (lexemeToString buf2)) in
445                   case lookupUFM pragmaKeywordsFM lexeme of
446                         -- ignore RULES pragmas when -fglasgow-exts is off
447                         Just ITrules_prag | not (flag glaexts) ->
448                            skip_to_end (stepOnBy# buf 2#) s'
449                         Just ITline_prag -> 
450                            line_prag skip_to_end buf2 s'
451                         Just other -> is_a_token
452                         Nothing -> skip_to_end (stepOnBy# buf 2#) s'
453                   }}
454
455                 else skip_to_end (stepOnBy# buf 2#) s'
456                 where
457                     skip_to_end = skipNestedComment (lexer cont)
458
459                 -- special GHC extension: we grok cpp-style #line pragmas
460             '#'# | lexemeIndex buf ==# bol ->   -- the '#' must be in column 0
461                 let buf1 | lookAhead# buf 1# `eqChar#` 'l'# &&
462                            lookAhead# buf 2# `eqChar#` 'i'# &&
463                            lookAhead# buf 3# `eqChar#` 'n'# &&
464                            lookAhead# buf 4# `eqChar#` 'e'#  = stepOnBy# buf 5#
465                          | otherwise = stepOn buf
466                 in
467                 case expandWhile# is_space buf1 of { buf2 ->
468                 if is_digit (currentChar# buf2) 
469                         then line_prag next_line buf2 s'
470                         else is_a_token
471                 }
472                 where
473                 next_line buf = lexer cont (stepOnUntilChar# buf '\n'#)
474
475                 -- tabs have been expanded beforehand
476             c | is_space c -> tab y bol atbol (stepOn buf)
477               | otherwise  -> is_a_token
478
479            where s' = s{loc = replaceSrcLine loc y, 
480                         bol = bol,
481                        atbol = atbol}
482
483                  is_a_token | atbol /=# 0# = lexBOL cont buf s'
484                             | otherwise    = lexToken cont glaexts buf s'
485
486 -- {-# LINE .. #-} pragmas.  yeuch.
487 line_prag cont buf s@PState{loc=loc} =
488   case expandWhile# is_space buf                of { buf1 ->
489   case scanNumLit 0 (stepOverLexeme buf1)       of { (line,buf2) ->
490   -- subtract one: the line number refers to the *following* line.
491   let real_line = line - 1 in
492   case fromInteger real_line                    of { i@(I# l) -> 
493         -- ToDo, if no filename then we skip the newline.... d'oh
494   case expandWhile# is_space buf2               of { buf3 ->
495   case currentChar# buf3                        of
496      '\"'#{-"-} -> 
497         case untilEndOfString# (stepOn (stepOverLexeme buf3)) of { buf4 ->
498         let 
499             file = lexemeToFastString buf4 
500             new_buf = stepOn (stepOverLexeme buf4)
501         in
502         if nullFastString file
503                 then cont new_buf s{loc = replaceSrcLine loc l}
504                 else cont new_buf s{loc = mkSrcLoc file i}
505         }
506      _other -> cont (stepOverLexeme buf3) s{loc = replaceSrcLine loc l}
507   }}}}
508
509 skipNestedComment :: P a -> P a
510 skipNestedComment cont buf state = skipNestedComment' (loc state) cont buf state
511
512 skipNestedComment' :: SrcLoc -> P a -> P a
513 skipNestedComment' orig_loc cont buf = loop buf
514  where
515    loop buf = 
516      case currentChar# buf of
517         '-'# | lookAhead# buf 1# `eqChar#` '}'# -> cont (stepOnBy# buf 2#)
518
519         '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
520               skipNestedComment 
521                 (skipNestedComment' orig_loc cont) 
522                 (stepOnBy# buf 2#)
523
524         '\n'# -> \ s@PState{loc=loc} ->
525                  let buf' = stepOn buf in
526                  loop buf' s{loc = incSrcLine loc, 
527                              bol = currentIndex# buf',
528                              atbol = 1#}
529
530         -- pass the original SrcLoc to lexError so that the error is
531         -- reported at the line it was originally on, not the line at
532         -- the end of the file.
533         '\NUL'# | bufferExhausted (stepOn buf) -> 
534                 \s -> lexError "unterminated `{-'" buf s{loc=orig_loc} -- -}
535
536         _   -> loop (stepOn buf)
537
538 -- When we are lexing the first token of a line, check whether we need to
539 -- insert virtual semicolons or close braces due to layout.
540
541 lexBOL :: (Token -> P a) -> P a
542 lexBOL cont buf s@(PState{
543                     loc = loc,
544                     glasgow_exts = glaexts,
545                     bol = bol,
546                     atbol = atbol,
547                     context = ctx
548                   }) =
549         if need_close_curly then 
550                 --trace ("col = " ++ show (I# col) ++ ", layout: inserting '}'") $
551                 cont ITvccurly buf s{atbol = 1#, context = tail ctx}
552         else if need_semi_colon then
553                 --trace ("col = " ++ show (I# col) ++ ", layout: inserting ';'") $
554                 cont ITsemi buf s{atbol = 0#}
555         else
556                 lexToken cont glaexts buf s{atbol = 0#}
557   where
558         col = currentIndex# buf -# bol
559
560         need_close_curly =
561                 case ctx of
562                         [] -> False
563                         (i:_) -> case i of
564                                     NoLayout -> False
565                                     Layout n -> col <# n
566         need_semi_colon =
567                 case ctx of
568                         [] -> False
569                         (i:_) -> case i of
570                                     NoLayout -> False
571                                     Layout n -> col ==# n
572
573
574 lexToken :: (Token -> P a) -> Int# -> P a
575 lexToken cont glaexts buf =
576 -- trace "lexToken" $
577   case currentChar# buf of
578
579     -- special symbols ----------------------------------------------------
580     '('# | flag glaexts && lookAhead# buf 1# `eqChar#` '#'# 
581                 -> cont IToubxparen (setCurrentPos# buf 2#)
582          | otherwise
583                 -> cont IToparen (incLexeme buf)
584
585     ')'# -> cont ITcparen    (incLexeme buf)
586     '['# -> cont ITobrack    (incLexeme buf)
587     ']'# -> cont ITcbrack    (incLexeme buf)
588     ','# -> cont ITcomma     (incLexeme buf)
589     ';'# -> cont ITsemi      (incLexeme buf)
590     '}'# -> \ s@PState{context = ctx} ->
591             case ctx of 
592                 (_:ctx') -> cont ITccurly (incLexeme buf) s{context=ctx'}
593                 _        -> lexError "too many '}'s" buf s
594     '|'# -> case lookAhead# buf 1# of
595                  '}'#  | flag glaexts -> cont ITccurlybar 
596                                               (setCurrentPos# buf 2#)
597                  _                    -> lex_sym cont (incLexeme buf)
598
599                 
600     '#'# -> case lookAhead# buf 1# of
601                 ')'#  | flag glaexts -> cont ITcubxparen (setCurrentPos# buf 2#)
602                 '-'# -> case lookAhead# buf 2# of
603                            '}'# -> cont ITclose_prag (setCurrentPos# buf 3#)
604                            _    -> lex_sym cont (incLexeme buf)
605                 _    -> lex_sym cont (incLexeme buf)
606
607     '`'# | flag glaexts && lookAhead# buf 1# `eqChar#` '`'#
608                 -> lex_cstring cont (setCurrentPos# buf 2#)
609          | otherwise
610                 -> cont ITbackquote (incLexeme buf)
611
612     '{'# ->     -- look for "{-##" special iface pragma
613             case lookAhead# buf 1# of
614            '|'# | flag glaexts 
615                 -> cont ITocurlybar (setCurrentPos# buf 2#)
616            '-'# -> case lookAhead# buf 2# of
617                     '#'# -> case lookAhead# buf 3# of
618                                 '#'# -> 
619                                    lexPragma
620                                       cont
621                                       (\ cont lexeme buf' -> cont (ITpragma lexeme) buf')
622                                       0#
623                                       (stepOnBy# (stepOverLexeme buf) 4#)
624                                 _ -> lex_prag cont (setCurrentPos# buf 3#)
625                     _    -> cont ITocurly (incLexeme buf) 
626            _ -> (layoutOff `thenP_` cont ITocurly)  (incLexeme buf) 
627
628     -- strings/characters -------------------------------------------------
629     '\"'#{-"-} -> lex_string cont glaexts [] (incLexeme buf)
630     '\''#      -> lex_char (char_end cont) glaexts (incLexeme buf)
631
632     -- strictness and cpr pragmas and __scc treated specially.
633     '_'# | flag glaexts ->
634          case lookAhead# buf 1# of
635            '_'# -> case lookAhead# buf 2# of
636                     'S'# -> 
637                         lex_demand cont (stepOnUntil (not . isSpace) 
638                                         (stepOnBy# buf 3#)) -- past __S
639                     'M'# -> 
640                         cont ITcprinfo (stepOnBy# buf 3#)       -- past __M
641
642                     's'# -> 
643                         case prefixMatch (stepOnBy# buf 3#) "cc" of
644                                Just buf' -> lex_scc cont (stepOverLexeme buf')
645                                Nothing   -> lex_id cont glaexts buf
646                     _ -> lex_id cont glaexts buf
647            _    -> lex_id cont glaexts buf
648
649         -- Hexadecimal and octal constants
650     '0'# | (ch `eqChar#` 'x'# || ch `eqChar#` 'X'#) && is_hexdigit ch2
651                 -> readNum (after_lexnum cont glaexts) buf' is_hexdigit 16 hex
652          | (ch `eqChar#` 'o'# || ch `eqChar#` 'O'#) && is_octdigit ch2
653                 -> readNum (after_lexnum cont glaexts) buf' is_octdigit  8 oct_or_dec
654         where ch   = lookAhead# buf 1#
655               ch2  = lookAhead# buf 2#
656               buf' = setCurrentPos# buf 2#
657
658     '\NUL'# ->
659             if bufferExhausted (stepOn buf) then
660                cont ITeof buf
661             else
662                trace "lexIface: misplaced NUL?" $ 
663                cont (ITunknown "\NUL") (stepOn buf)
664
665     '?'# | flag glaexts && is_lower (lookAhead# buf 1#) ->
666             lex_ip ITdupipvarid cont (incLexeme buf)
667     '%'# | flag glaexts && is_lower (lookAhead# buf 1#) ->
668             lex_ip ITsplitipvarid cont (incLexeme buf)
669     c | is_digit  c -> lex_num cont glaexts 0 buf
670       | is_symbol c -> lex_sym cont buf
671       | is_upper  c -> lex_con cont glaexts buf
672       | is_ident  c -> lex_id  cont glaexts buf
673       | otherwise   -> lexError "illegal character" buf
674
675 -- Int# is unlifted, and therefore faster than Bool for flags.
676 {-# INLINE flag #-}
677 flag :: Int# -> Bool
678 flag 0# = False
679 flag _  = True
680
681 -------------------------------------------------------------------------------
682 -- Pragmas
683
684 lex_prag cont buf
685   = case expandWhile# is_space buf of { buf1 ->
686     case expandWhile# is_ident (stepOverLexeme buf1) of { buf2 -> 
687     let lexeme = mkFastString (map toUpper (lexemeToString buf2)) in
688     case lookupUFM pragmaKeywordsFM lexeme of
689         Just kw -> cont kw (mergeLexemes buf buf2)
690         Nothing -> panic "lex_prag"
691   }}
692
693 -------------------------------------------------------------------------------
694 -- Strings & Chars
695
696 lex_string cont glaexts s buf
697   = case currentChar# buf of
698         '"'#{-"-} -> 
699            let buf' = incLexeme buf
700                s' = mkFastStringNarrow (map chr (reverse s)) 
701            in case currentChar# buf' of
702                 '#'# | flag glaexts -> if all (<= 0xFF) s
703                     then cont (ITprimstring s') (incLexeme buf')
704                     else lexError "primitive string literal must contain only characters <= \'\\xFF\'" buf'
705                 _                   -> cont (ITstring s') buf'
706
707         -- ignore \& in a string, deal with string gaps
708         '\\'# | next_ch `eqChar#` '&'# 
709                 -> lex_string cont glaexts s buf'
710               | is_space next_ch
711                 -> lex_stringgap cont glaexts s (incLexeme buf)
712
713             where next_ch = lookAhead# buf 1#
714                   buf' = setCurrentPos# buf 2#
715
716         _ -> lex_char (lex_next_string cont s) glaexts buf
717
718 lex_stringgap cont glaexts s buf
719   = let buf' = incLexeme buf in
720     case currentChar# buf of
721         '\n'# -> \st@PState{loc = loc} -> lex_stringgap cont glaexts s buf' 
722                   st{loc = incSrcLine loc}
723         '\\'# -> lex_string cont glaexts s buf'
724         c | is_space c -> lex_stringgap cont glaexts s buf'
725         other -> charError buf'
726
727 lex_next_string cont s glaexts c buf = lex_string cont glaexts (c:s) buf
728
729 lex_char :: (Int# -> Int -> P a) -> Int# -> P a
730 lex_char cont glaexts buf
731   = case currentChar# buf of
732         '\\'# -> lex_escape (cont glaexts) (incLexeme buf)
733         c | is_any c -> cont glaexts (I# (ord# c)) (incLexeme buf)
734         other -> charError buf
735
736 char_end cont glaexts c buf
737   = case currentChar# buf of
738         '\''# -> let buf' = incLexeme buf in
739                  case currentChar# buf' of
740                         '#'# | flag glaexts 
741                                 -> cont (ITprimchar c) (incLexeme buf')
742                         _       -> cont (ITchar c) buf'
743         _     -> charError buf
744
745 lex_escape cont buf
746   = let buf' = incLexeme buf in
747     case currentChar# buf of
748         'a'#       -> cont (ord '\a') buf'
749         'b'#       -> cont (ord '\b') buf'
750         'f'#       -> cont (ord '\f') buf'
751         'n'#       -> cont (ord '\n') buf'
752         'r'#       -> cont (ord '\r') buf'
753         't'#       -> cont (ord '\t') buf'
754         'v'#       -> cont (ord '\v') buf'
755         '\\'#      -> cont (ord '\\') buf'
756         '"'#       -> cont (ord '\"') buf'
757         '\''#      -> cont (ord '\'') buf'
758         '^'#       -> let c = currentChar# buf' in
759                       if c `geChar#` '@'# && c `leChar#` '_'#
760                         then cont (I# (ord# c -# ord# '@'#)) (incLexeme buf')
761                         else charError buf'
762
763         'x'#      -> readNum (after_charnum cont) buf' is_hexdigit 16 hex
764         'o'#      -> readNum (after_charnum cont) buf' is_octdigit  8 oct_or_dec
765         x | is_digit x 
766                   -> readNum (after_charnum cont) buf is_digit    10 oct_or_dec
767
768         _          -> case [ (c,buf2) | (p,c) <- silly_escape_chars,
769                                        Just buf2 <- [prefixMatch buf p] ] of
770                             (c,buf2):_ -> cont (ord c) buf2
771                             [] -> charError buf'
772
773 after_charnum cont i buf
774   = if i >= 0 && i <= 0x10FFFF
775         then cont (fromInteger i) buf
776         else charError buf
777
778 readNum cont buf is_digit base conv = read buf 0
779   where read buf i 
780           = case currentChar# buf of { c ->
781             if is_digit c
782                 then read (incLexeme buf) (i*base + (toInteger (I# (conv c))))
783                 else cont i buf
784             }
785
786 is_hexdigit c 
787         =  is_digit c 
788         || (c `geChar#` 'a'# && c `leChar#` 'f'#)
789         || (c `geChar#` 'A'# && c `leChar#` 'F'#)
790
791 hex c | is_digit c = ord# c -# ord# '0'#
792       | otherwise  = ord# (to_lower c) -# ord# 'a'# +# 10#
793 oct_or_dec c = ord# c -# ord# '0'#
794
795 is_octdigit c = c `geChar#` '0'# && c `leChar#` '7'#
796
797 to_lower c 
798   | c `geChar#` 'A'# && c `leChar#` 'Z'#  
799         = chr# (ord# c -# (ord# 'A'# -# ord# 'a'#))
800   | otherwise = c
801
802 charError buf = lexError "error in character literal" buf
803
804 silly_escape_chars = [
805         ("NUL", '\NUL'),
806         ("SOH", '\SOH'),
807         ("STX", '\STX'),
808         ("ETX", '\ETX'),
809         ("EOT", '\EOT'),
810         ("ENQ", '\ENQ'),
811         ("ACK", '\ACK'),
812         ("BEL", '\BEL'),
813         ("BS", '\BS'),
814         ("HT", '\HT'),
815         ("LF", '\LF'),
816         ("VT", '\VT'),
817         ("FF", '\FF'),
818         ("CR", '\CR'),
819         ("SO", '\SO'),
820         ("SI", '\SI'),
821         ("DLE", '\DLE'),
822         ("DC1", '\DC1'),
823         ("DC2", '\DC2'),
824         ("DC3", '\DC3'),
825         ("DC4", '\DC4'),
826         ("NAK", '\NAK'),
827         ("SYN", '\SYN'),
828         ("ETB", '\ETB'),
829         ("CAN", '\CAN'),
830         ("EM", '\EM'),
831         ("SUB", '\SUB'),
832         ("ESC", '\ESC'),
833         ("FS", '\FS'),
834         ("GS", '\GS'),
835         ("RS", '\RS'),
836         ("US", '\US'),
837         ("SP", '\SP'),
838         ("DEL", '\DEL')
839         ]
840
841 -------------------------------------------------------------------------------
842
843 lex_demand cont buf = 
844  case read_em [] buf of { (ls,buf') -> 
845  case currentChar# buf' of
846    'b'# -> cont (ITstrict (StrictSig (mkTopDmdType ls BotRes))) (incLexeme buf')
847    'm'# -> cont (ITstrict (StrictSig (mkTopDmdType ls RetCPR))) (incLexeme buf')
848    _    -> cont (ITstrict (StrictSig (mkTopDmdType ls TopRes))) buf'
849  }
850  where
851   read_em acc buf = 
852    case currentChar# buf of
853     'T'# -> read_em (Top     : acc) (stepOn buf)
854     'L'# -> read_em (lazyDmd : acc) (stepOn buf)
855     'A'# -> read_em (Abs     : acc) (stepOn buf)
856     'V'# -> read_em (evalDmd : acc) (stepOn buf)        -- Temporary, until
857                                                         -- we've recompiled prelude etc
858     'C'# -> do_unary Call  acc (stepOnBy# buf 2#)       -- Skip 'C('
859
860     'U'# -> do_seq1 Eval         acc (stepOnBy# buf 1#)
861     'D'# -> do_seq1 Defer        acc (stepOnBy# buf 1#)
862     'S'# -> do_seq1 (Box . Eval) acc (stepOnBy# buf 1#)
863
864     _    -> (reverse acc, buf)
865
866   do_seq1 fn acc buf
867     = case currentChar# buf of
868         '('# -> do_seq2 fn acc (stepOnBy# buf 1#)
869         _    -> read_em (fn (Poly Abs) : acc) buf
870
871   do_seq2 fn acc buf
872     = case read_em [] buf of { (dmds, buf) -> 
873       case currentChar# buf of
874         ')'# -> read_em (fn (Prod dmds) : acc)
875                         (stepOn buf) 
876         '*'# -> ASSERT( length dmds == 1 )
877                 read_em (fn (Poly (head dmds)) : acc)
878                         (stepOnBy# buf 2#)      -- Skip '*)'
879       }
880         
881   do_unary fn acc buf
882     = case read_em [] buf of
883         ([dmd], rest) -> read_em (fn dmd : acc) (stepOn rest)   -- Skip ')'
884
885 ------------------
886 lex_scc cont buf =
887  case currentChar# buf of
888   'C'# -> cont ITsccAllCafs (incLexeme buf)
889   other -> cont ITscc buf
890
891 -----------------------------------------------------------------------------
892 -- Numbers
893
894 lex_num :: (Token -> P a) -> Int# -> Integer -> P a
895 lex_num cont glaexts acc buf =
896  case scanNumLit acc buf of
897      (acc',buf') ->
898        case currentChar# buf' of
899          '.'# | is_digit (lookAhead# buf' 1#) ->
900              -- this case is not optimised at all, as the
901              -- presence of floating point numbers in interface
902              -- files is not that common. (ToDo)
903             case expandWhile# is_digit (incLexeme buf') of
904               buf2 -> -- points to first non digit char
905
906                 let l = case currentChar# buf2 of
907                           'E'# -> do_exponent
908                           'e'# -> do_exponent
909                           _ -> buf2
910
911                     do_exponent 
912                         = let buf3 = incLexeme buf2 in
913                           case currentChar# buf3 of
914                                 '-'# -> expandWhile# is_digit (incLexeme buf3)
915                                 '+'# -> expandWhile# is_digit (incLexeme buf3)
916                                 x | is_digit x -> expandWhile# is_digit buf3
917                                 _ -> buf2
918
919                     v = readRational__ (lexemeToString l)
920
921                 in case currentChar# l of -- glasgow exts only
922                       '#'# | flag glaexts -> let l' = incLexeme l in
923                               case currentChar# l' of
924                                 '#'# -> cont (ITprimdouble v) (incLexeme l')
925                                 _    -> cont (ITprimfloat  v) l'
926                       _ -> cont (ITrational v) l
927
928          _ -> after_lexnum cont glaexts acc' buf'
929                 
930 after_lexnum cont glaexts i buf
931   = case currentChar# buf of
932         '#'# | flag glaexts -> cont (ITprimint i) (incLexeme buf)
933         _    -> cont (ITinteger i) buf
934
935 -----------------------------------------------------------------------------
936 -- C "literal literal"s  (i.e. things like ``NULL'', ``stdout'' etc.)
937
938 -- we lexemeToFastString on the bit between the ``''s, but include the
939 -- quotes in the full lexeme.
940
941 lex_cstring cont buf =
942  case expandUntilMatch (stepOverLexeme buf) "\'\'" of
943    Just buf' -> cont (ITlitlit (lexemeToFastString 
944                                 (setCurrentPos# buf' (negateInt# 2#))))
945                    (mergeLexemes buf buf')
946    Nothing   -> lexError "unterminated ``" buf
947
948 -----------------------------------------------------------------------------
949 -- identifiers, symbols etc.
950
951 lex_ip ip_constr cont buf =
952  case expandWhile# is_ident buf of
953    buf' -> cont (ip_constr (tailFS lexeme)) buf'
954         where lexeme = lexemeToFastString buf'
955
956 lex_id cont glaexts buf =
957  let buf1 = expandWhile# is_ident buf in
958  seq buf1 $
959
960  case (if flag glaexts 
961         then expandWhile# (eqChar# '#'#) buf1 -- slurp trailing hashes
962         else buf1)                              of { buf' ->
963
964  let lexeme  = lexemeToFastString buf' in
965
966  case _scc_ "Lex.haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
967         Just kwd_token -> --trace ("hkeywd: "++_UNPK_(lexeme)) $
968                           cont kwd_token buf';
969         Nothing        -> 
970
971  let var_token = cont (ITvarid lexeme) buf' in
972
973  if not (flag glaexts)
974    then var_token
975    else
976
977  case lookupUFM ghcExtensionKeywordsFM lexeme of {
978         Just kwd_token -> cont kwd_token buf';
979         Nothing        -> var_token
980
981  }}}
982
983 lex_sym cont buf =
984  -- trace "lex_sym" $
985  case expandWhile# is_symbol buf of
986    buf' -> case lookupUFM haskellKeySymsFM lexeme of {
987                 Just kwd_token -> --trace ("keysym: "++unpackFS lexeme) $
988                                   cont kwd_token buf' ;
989                 Nothing        -> --trace ("sym: "++unpackFS lexeme) $
990                                   cont (mk_var_token lexeme) buf'
991            }
992         where lexeme = lexemeToFastString buf'
993
994
995 -- lex_con recursively collects components of a qualified identifer.
996 -- The argument buf is the StringBuffer representing the lexeme
997 -- identified so far, where the next character is upper-case.
998
999 lex_con cont glaexts buf =
1000  -- trace ("con: "{-++unpackFS lexeme-}) $
1001  let empty_buf = stepOverLexeme buf in
1002  case expandWhile# is_ident empty_buf    of { buf1 ->
1003  case slurp_trailing_hashes buf1 glaexts of { con_buf ->
1004
1005  let all_buf = mergeLexemes buf con_buf
1006      
1007      con_lexeme = lexemeToFastString con_buf
1008      mod_lexeme = lexemeToFastString (decLexeme buf)
1009      all_lexeme = lexemeToFastString all_buf
1010
1011      just_a_conid
1012         | emptyLexeme buf = cont (ITconid con_lexeme)               all_buf
1013         | otherwise       = cont (ITqconid (mod_lexeme,con_lexeme)) all_buf
1014  in
1015
1016  case currentChar# all_buf of
1017      '.'# -> maybe_qualified cont glaexts all_lexeme 
1018                 (incLexeme all_buf) just_a_conid
1019      _    -> just_a_conid
1020   }}
1021
1022
1023 maybe_qualified cont glaexts mod buf just_a_conid =
1024  -- trace ("qid: "{-++unpackFS lexeme-}) $
1025  case currentChar# buf of
1026   '['# ->       -- Special case for []
1027     case lookAhead# buf 1# of
1028      ']'# -> cont (ITqconid  (mod,SLIT("[]"))) (setCurrentPos# buf 2#)
1029      _    -> just_a_conid
1030
1031   '('# ->  -- Special case for (,,,)
1032            -- This *is* necessary to deal with e.g. "instance C PrelBase.(,,)"
1033     case lookAhead# buf 1# of
1034      '#'# | flag glaexts -> case lookAhead# buf 2# of
1035                 ','# -> lex_ubx_tuple cont mod (setCurrentPos# buf 3#) 
1036                                 just_a_conid
1037                 _    -> just_a_conid
1038      ')'# -> cont (ITqconid (mod,SLIT("()"))) (setCurrentPos# buf 2#)
1039      ','# -> lex_tuple cont mod (setCurrentPos# buf 2#) just_a_conid
1040      _    -> just_a_conid
1041
1042   '-'# -> case lookAhead# buf 1# of
1043             '>'# -> cont (ITqconid (mod,SLIT("(->)"))) (setCurrentPos# buf 2#)
1044             _    -> lex_id3 cont glaexts mod buf just_a_conid
1045
1046   _    -> lex_id3 cont glaexts mod buf just_a_conid
1047
1048
1049 lex_id3 cont glaexts mod buf just_a_conid
1050   | is_upper (currentChar# buf) =
1051      lex_con cont glaexts buf
1052
1053   | is_symbol (currentChar# buf) =
1054      let 
1055         start_new_lexeme = stepOverLexeme buf
1056      in
1057      -- trace ("lex_id31 "{-++unpackFS lexeme-}) $
1058      case expandWhile# is_symbol start_new_lexeme of { buf' ->
1059      let
1060        lexeme  = lexemeToFastString buf'
1061         -- real lexeme is M.<sym>
1062        new_buf = mergeLexemes buf buf'
1063      in
1064      cont (mk_qvar_token mod lexeme) new_buf
1065         -- wrong, but arguably morally right: M... is now a qvarsym
1066      }
1067
1068   | otherwise   =
1069      let 
1070         start_new_lexeme = stepOverLexeme buf
1071      in
1072      -- trace ("lex_id32 "{-++unpackFS lexeme-}) $
1073      case expandWhile# is_ident start_new_lexeme of { buf1 ->
1074      if emptyLexeme buf1 
1075             then just_a_conid
1076             else
1077
1078      case slurp_trailing_hashes buf1 glaexts of { buf' ->
1079
1080      let
1081       lexeme      = lexemeToFastString buf'
1082       new_buf     = mergeLexemes buf buf'
1083       is_a_qvarid = cont (mk_qvar_token mod lexeme) new_buf
1084      in
1085      case _scc_ "Lex.haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
1086             Nothing          -> is_a_qvarid ;
1087
1088             Just kwd_token | isSpecial kwd_token   -- special ids (as, qualified, hiding) shouldn't be
1089                            -> is_a_qvarid          --  recognised as keywords here.
1090                            | otherwise
1091                            -> just_a_conid         -- avoid M.where etc.
1092      }}}
1093
1094 slurp_trailing_hashes buf glaexts
1095   | flag glaexts = expandWhile# (`eqChar#` '#'#) buf
1096   | otherwise    = buf
1097
1098
1099 mk_var_token pk_str
1100   | is_upper f          = ITconid pk_str
1101   | is_ident f          = ITvarid pk_str
1102   | f `eqChar#` ':'#    = ITconsym pk_str
1103   | otherwise           = ITvarsym pk_str
1104   where
1105       (C# f) = _HEAD_ pk_str
1106       -- tl     = _TAIL_ pk_str
1107
1108 mk_qvar_token m token =
1109 -- trace ("mk_qvar ") $ 
1110  case mk_var_token token of
1111    ITconid n  -> ITqconid  (m,n)
1112    ITvarid n  -> ITqvarid  (m,n)
1113    ITconsym n -> ITqconsym (m,n)
1114    ITvarsym n -> ITqvarsym (m,n)
1115    _          -> ITunknown (show token)
1116 \end{code}
1117
1118 ----------------------------------------------------------------------------
1119 Horrible stuff for dealing with M.(,,,)
1120
1121 \begin{code}
1122 lex_tuple cont mod buf back_off =
1123   go 2 buf
1124   where
1125    go n buf =
1126     case currentChar# buf of
1127       ','# -> go (n+1) (stepOn buf)
1128       ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Boxed n))) (stepOn buf)
1129       _    -> back_off
1130
1131 lex_ubx_tuple cont mod buf back_off =
1132   go 2 buf
1133   where
1134    go n buf =
1135     case currentChar# buf of
1136       ','# -> go (n+1) (stepOn buf)
1137       '#'# -> case lookAhead# buf 1# of
1138                 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Unboxed n)))
1139                                  (stepOnBy# buf 2#)
1140                 _    -> back_off
1141       _    -> back_off
1142 \end{code}
1143
1144 -----------------------------------------------------------------------------
1145 'lexPragma' rips along really fast, looking for a '##-}', 
1146 indicating the end of the pragma we're skipping
1147
1148 \begin{code}
1149 lexPragma cont contf inStr buf =
1150  case currentChar# buf of
1151    '#'# | inStr ==# 0# ->
1152        case lookAhead# buf 1# of { '#'# -> 
1153        case lookAhead# buf 2# of { '-'# ->
1154        case lookAhead# buf 3# of { '}'# -> 
1155            contf cont (lexemeToBuffer buf)
1156                       (stepOverLexeme (setCurrentPos# buf 4#));
1157         _    -> lexPragma cont contf inStr (incLexeme buf) };
1158         _    -> lexPragma cont contf inStr (incLexeme buf) };
1159         _    -> lexPragma cont contf inStr (incLexeme buf) }
1160
1161    '"'# ->
1162        let
1163         odd_slashes buf flg i# =
1164           case lookAhead# buf i# of
1165            '\\'# -> odd_slashes buf (not flg) (i# -# 1#)
1166            _     -> flg
1167
1168         not_inStr = if inStr ==# 0# then 1# else 0#
1169        in
1170        case lookAhead# buf (negateInt# 1#) of --backwards, actually
1171          '\\'# -> -- escaping something..
1172            if odd_slashes buf True (negateInt# 2#) 
1173                 then  -- odd number of slashes, " is escaped.
1174                       lexPragma cont contf inStr (incLexeme buf)
1175                 else  -- even number of slashes, \ is escaped.
1176                       lexPragma cont contf not_inStr (incLexeme buf)
1177          _ -> lexPragma cont contf not_inStr (incLexeme buf)
1178
1179    '\''# | inStr ==# 0# ->
1180         case lookAhead# buf 1# of { '"'# ->
1181         case lookAhead# buf 2# of { '\''# ->
1182            lexPragma cont contf inStr (setCurrentPos# buf 3#);
1183         _ -> lexPragma cont contf inStr (incLexeme buf) };
1184         _ -> lexPragma cont contf inStr (incLexeme buf) }
1185
1186     -- a sign that the input is ill-formed, since pragmas are
1187     -- assumed to always be properly closed (in .hi files).
1188    '\NUL'# -> trace "lexPragma: unexpected end-of-file" $ 
1189               cont (ITunknown "\NUL") buf
1190
1191    _ -> lexPragma cont contf inStr (incLexeme buf)
1192
1193 \end{code}
1194
1195 -----------------------------------------------------------------------------
1196
1197 \begin{code}
1198 data LayoutContext
1199   = NoLayout
1200   | Layout Int#
1201
1202 data ParseResult a
1203   = POk PState a
1204   | PFailed Message
1205
1206 data PState = PState { 
1207         loc           :: SrcLoc,
1208         glasgow_exts  :: Int#,
1209         bol           :: Int#,
1210         atbol         :: Int#,
1211         context       :: [LayoutContext]
1212      }
1213
1214 type P a = StringBuffer         -- Input string
1215         -> PState
1216         -> ParseResult a
1217
1218 returnP   :: a -> P a
1219 returnP a buf s = POk s a
1220
1221 thenP      :: P a -> (a -> P b) -> P b
1222 m `thenP` k = \ buf s ->
1223         case m buf s of
1224                 POk s1 a -> k a buf s1
1225                 PFailed err  -> PFailed err
1226
1227 thenP_     :: P a -> P b -> P b
1228 m `thenP_` k = m `thenP` \_ -> k
1229
1230 mapP :: (a -> P b) -> [a] -> P [b]
1231 mapP f [] = returnP []
1232 mapP f (a:as) = 
1233      f a `thenP` \b ->
1234      mapP f as `thenP` \bs ->
1235      returnP (b:bs)
1236
1237 failP :: String -> P a
1238 failP msg buf s = PFailed (text msg)
1239
1240 failMsgP :: Message -> P a
1241 failMsgP msg buf s = PFailed msg
1242
1243 lexError :: String -> P a
1244 lexError str buf s@PState{ loc = loc } 
1245   = failMsgP (hcat [ppr loc, text ": ", text str]) buf s
1246
1247 getSrcLocP :: P SrcLoc
1248 getSrcLocP buf s@(PState{ loc = loc }) = POk s loc
1249
1250 -- use a temporary SrcLoc for the duration of the argument
1251 setSrcLocP :: SrcLoc -> P a -> P a
1252 setSrcLocP new_loc p buf s = 
1253   case p buf s{ loc=new_loc } of
1254       POk _ a   -> POk s a
1255       PFailed e -> PFailed e
1256   
1257 getSrcFile :: P FAST_STRING
1258 getSrcFile buf s@(PState{ loc = loc }) = POk s (srcLocFile loc)
1259
1260 pushContext :: LayoutContext -> P ()
1261 pushContext ctxt buf s@(PState{ context = ctx }) = POk s{context = ctxt:ctx} ()
1262
1263 {-
1264
1265 This special case in layoutOn is to handle layout contexts with are
1266 indented the same or less than the current context.  This is illegal
1267 according to the Haskell spec, so we have to arrange to close the
1268 current context.  eg.
1269
1270 class Foo a where
1271 class Bar a
1272
1273 after the first 'where', the sequence of events is:
1274
1275         - layout system inserts a ';' (column 0)
1276         - parser begins a new context at column 0
1277         - parser shifts ';' (legal empty declaration)
1278         - parser sees 'class': parse error (we're still in the inner context)
1279
1280 trouble is, by the time we know we need a new context, the lexer has
1281 already generated the ';'.  Hacky solution is as follows: since we
1282 know the column of the next token (it's the column number of the new
1283 context), we set the ACTUAL column number of the new context to this
1284 numer plus one.  Hence the next time the lexer is called, a '}' will
1285 be generated to close the new context straight away.  Furthermore, we
1286 have to set the atbol flag so that the ';' that the parser shifted as
1287 part of the new context is re-generated.
1288
1289 when the new context is *less* indented than the current one:
1290
1291 f = f where g = g where
1292 h = h
1293
1294         - current context: column 12.
1295         - on seeing 'h' (column 0), the layout system inserts '}'
1296         - parser starts a new context, column 0
1297         - parser sees '}', uses it to close new context
1298         - we still need to insert another '}' followed by a ';',
1299           hence the atbol trick.
1300
1301 There's also a special hack in here to deal with
1302
1303         do
1304            ....
1305            e $ do
1306            blah
1307
1308 i.e. the inner context is at the same indentation level as the outer
1309 context.  This is strictly illegal according to Haskell 98, but
1310 there's a lot of existing code using this style and it doesn't make
1311 any sense to disallow it, since empty 'do' lists don't make sense.
1312 -}
1313
1314 layoutOn :: Bool -> P ()
1315 layoutOn strict buf s@(PState{ bol = bol, context = ctx }) =
1316     let offset = lexemeIndex buf -# bol in
1317     case ctx of
1318         Layout prev_off : _ 
1319            | if strict then prev_off >=# offset else prev_off ># offset ->
1320                 --trace ("layout on, column: " ++  show (I# offset)) $
1321                 POk s{ context = Layout (offset +# 1#) : ctx, atbol = 1# } ()
1322         other -> 
1323                 --trace ("layout on, column: " ++  show (I# offset)) $
1324                 POk s{ context = Layout offset : ctx } ()
1325
1326 layoutOff :: P ()
1327 layoutOff buf s@(PState{ context = ctx }) =
1328     POk s{ context = NoLayout:ctx } ()
1329
1330 popContext :: P ()
1331 popContext = \ buf s@(PState{ context = ctx, loc = loc }) ->
1332   case ctx of
1333         (_:tl) -> POk s{ context = tl } ()
1334         []     -> PFailed (srcParseErr buf loc)
1335
1336 {- 
1337  Note that if the name of the file we're processing ends
1338  with `hi-boot', we accept it on faith as having the right
1339  version. This is done so that .hi-boot files that comes
1340  with hsc don't have to be updated before every release,
1341  *and* it allows us to share .hi-boot files with versions
1342  of hsc that don't have .hi version checking (e.g., ghc-2.10's)
1343
1344  If the version number is 0, the checking is also turned off.
1345  (needed to deal with GHC.hi only!)
1346
1347  Once we can assume we're compiling with a version of ghc that
1348  supports interface file checking, we can drop the special
1349  pleading
1350 -}
1351 checkVersion :: Maybe Integer -> P ()
1352 checkVersion mb@(Just v) buf s@(PState{loc = loc})
1353  | (v==0) || (v == fromInt opt_HiVersion) || opt_NoHiCheck = POk s ()
1354  | otherwise = PFailed (ifaceVersionErr mb loc ([]::[Token]){-Todo-})
1355 checkVersion mb@Nothing  buf s@(PState{loc = loc})
1356  | "hi-boot" `isSuffixOf` (_UNPK_ (srcLocFile loc)) = POk s ()
1357  | otherwise = PFailed (ifaceVersionErr mb loc ([]::[Token]){-Todo-})
1358
1359 -----------------------------------------------------------------
1360
1361 ifaceParseErr :: StringBuffer -> SrcLoc -> Message
1362 ifaceParseErr s l
1363   = hsep [ppr l, ptext SLIT("Interface file parse error; on input `"),
1364           text (lexemeToString s), char '\'']
1365
1366 ifaceVersionErr hi_vers l toks
1367   = hsep [ppr l, ptext SLIT("Interface file version error;"),
1368           ptext SLIT("Expected"), int opt_HiVersion, 
1369           ptext SLIT("found "), pp_version]
1370     where
1371      pp_version =
1372       case hi_vers of
1373         Nothing -> ptext SLIT("pre ghc-3.02 version")
1374         Just v  -> ptext SLIT("version") <+> integer v
1375
1376 -----------------------------------------------------------------------------
1377
1378 srcParseErr :: StringBuffer -> SrcLoc -> Message
1379 srcParseErr s l
1380   = hcat [ppr l, 
1381           if null token 
1382              then ptext SLIT(": parse error (possibly incorrect indentation)")
1383              else hcat [ptext SLIT(": parse error on input "),
1384                         char '`', text token, char '\'']
1385     ]
1386   where 
1387         token = lexemeToString s
1388
1389 \end{code}