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