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