-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathInternalLexer.hs
1454 lines (1328 loc) · 53.6 KB
/
InternalLexer.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : Language.Haskell.Exts.Annotated.InternalLexer
-- Copyright : (c) The GHC Team, 1997-2000
-- (c) Niklas Broberg, 2004-2009
-- License : BSD-style (see the file LICENSE.txt)
--
-- Maintainer : Niklas Broberg, [email protected]
-- Stability : stable
-- Portability : portable
--
-- Lexer for Haskell, with some extensions.
--
-----------------------------------------------------------------------------
-- ToDo: Introduce different tokens for decimal, octal and hexadecimal (?)
-- ToDo: FloatTok should have three parts (integer part, fraction, exponent) (?)
-- ToDo: Use a lexical analyser generator (lx?)
module Language.Haskell.Exts.InternalLexer (Token(..), showToken, lexer, topLexer) where
import Language.Haskell.Exts.ParseMonad
import Language.Haskell.Exts.SrcLoc hiding (loc)
import Language.Haskell.Exts.Comments
import Language.Haskell.Exts.Extension
import Language.Haskell.Exts.ExtScheme
import Prelude hiding (id, exponent)
import Data.Char
import Data.Ratio
import Data.List (intercalate, isPrefixOf)
import Control.Monad (when)
-- import Debug.Trace (trace)
data Token
= VarId String
| LabelVarId String
| QVarId (String,String)
| IDupVarId (String) -- duplicable implicit parameter
| ILinVarId (String) -- linear implicit parameter
| ConId String
| QConId (String,String)
| DVarId [String] -- to enable varid's with '-' in them
| VarSym String
| ConSym String
| QVarSym (String,String)
| QConSym (String,String)
| IntTok (Integer, String)
| FloatTok (Rational, String)
| Character (Char, String)
| StringTok (String, String)
| IntTokHash (Integer, String) -- 1#
| WordTokHash (Integer, String) -- 1##
| FloatTokHash (Rational, String) -- 1.0#
| DoubleTokHash (Rational, String) -- 1.0##
| CharacterHash (Char, String) -- c#
| StringHash (String, String) -- "Hello world!"#
-- Symbols
| LeftParen
| RightParen
| LeftHashParen
| RightHashParen
| SemiColon
| LeftCurly
| RightCurly
| VRightCurly -- a virtual close brace
| LeftSquare
| RightSquare
| ParArrayLeftSquare -- [:
| ParArrayRightSquare -- :]
| Comma
| Underscore
| BackQuote
-- Reserved operators
| Dot -- reserved for use with 'forall x . x'
| DotDot
| Colon
| QuoteColon
| DoubleColon
| Equals
| Backslash
| Bar
| LeftArrow
| RightArrow
| At
| TApp -- '@' but have to check for preceeding whitespace
| Tilde
| DoubleArrow
| Minus
| Exclamation
| Star
| LeftArrowTail -- -<
| RightArrowTail -- >-
| LeftDblArrowTail -- -<<
| RightDblArrowTail -- >>-
-- Template Haskell
| THExpQuote -- [| or [e|
| THPatQuote -- [p|
| THDecQuote -- [d|
| THTypQuote -- [t|
| THCloseQuote -- |]
| THIdEscape (String) -- dollar x
| THParenEscape -- dollar (
| THVarQuote -- 'x (but without the x)
| THTyQuote -- ''T (but without the T)
| THQuasiQuote (String,String) -- [$...|...]
-- HaRP
| RPGuardOpen -- (|
| RPGuardClose -- |)
| RPCAt -- @:
-- Hsx
| XCodeTagOpen -- <%
| XCodeTagClose -- %>
| XStdTagOpen -- <
| XStdTagClose -- >
| XCloseTagOpen -- </
| XEmptyTagClose -- />
| XChildTagOpen -- <%> (note that close doesn't exist, it's XCloseTagOpen followed by XCodeTagClose)
| XPCDATA String
| XRPatOpen -- <[
| XRPatClose -- ]>
-- Pragmas
| PragmaEnd -- #-}
| RULES
| INLINE Bool
| INLINE_CONLIKE
| SPECIALISE
| SPECIALISE_INLINE Bool
| SOURCE
| DEPRECATED
| WARNING
| SCC
| GENERATED
| CORE
| UNPACK
| NOUNPACK
| OPTIONS (Maybe String,String)
-- | CFILES String
-- | INCLUDE String
| LANGUAGE
| ANN
| MINIMAL
| NO_OVERLAP
| OVERLAP
| OVERLAPPING
| OVERLAPPABLE
| OVERLAPS
| INCOHERENT
| COMPLETE
-- Reserved Ids
| KW_As
| KW_By -- transform list comprehensions
| KW_Case
| KW_Class
| KW_Data
| KW_Default
| KW_Deriving
| KW_Do
| KW_MDo
| KW_Else
| KW_Family -- indexed type families
| KW_Forall -- universal/existential types
| KW_Group -- transform list comprehensions
| KW_Hiding
| KW_If
| KW_Import
| KW_In
| KW_Infix
| KW_InfixL
| KW_InfixR
| KW_Instance
| KW_Let
| KW_Module
| KW_NewType
| KW_Of
| KW_Proc -- arrows
| KW_Rec -- arrows
| KW_Role
| KW_Then
| KW_Type
| KW_Using -- transform list comprehensions
| KW_Where
| KW_Qualified
| KW_Pattern
| KW_Stock
| KW_Anyclass
| KW_Via
-- FFI
| KW_Foreign
| KW_Export
| KW_Safe
| KW_Unsafe
| KW_Threadsafe
| KW_Interruptible
| KW_StdCall
| KW_CCall
| KW_CPlusPlus
| KW_DotNet
| KW_Jvm
| KW_Js
| KW_JavaScript
| KW_CApi
| EOF
deriving (Eq,Show)
reserved_ops :: [(String,(Token, Maybe ExtScheme))]
reserved_ops = [
( "..", (DotDot, Nothing) ),
( ":", (Colon, Nothing) ),
( "::", (DoubleColon, Nothing) ),
( "=", (Equals, Nothing) ),
( "\\", (Backslash, Nothing) ),
( "|", (Bar, Nothing) ),
( "<-", (LeftArrow, Nothing) ),
( "->", (RightArrow, Nothing) ),
( "@", (At, Nothing) ),
( "@:", (RPCAt, Just (Any [RegularPatterns])) ),
( "~", (Tilde, Nothing) ),
( "=>", (DoubleArrow, Nothing) ),
( "*", (Star, Just (Any [KindSignatures])) ),
-- Parallel arrays
( "[:", (ParArrayLeftSquare, Just (Any [ParallelArrays])) ),
( ":]", (ParArrayRightSquare, Just (Any [ParallelArrays])) ),
-- Arrows notation
( "-<", (LeftArrowTail, Just (Any [Arrows])) ),
( ">-", (RightArrowTail, Just (Any [Arrows])) ),
( "-<<", (LeftDblArrowTail, Just (Any [Arrows])) ),
( ">>-", (RightDblArrowTail, Just (Any [Arrows])) ),
-- Unicode notation
( "\x2190", (LeftArrow, Just (Any [UnicodeSyntax])) ),
( "\x2192", (RightArrow, Just (Any [UnicodeSyntax])) ),
( "\x21d2", (DoubleArrow, Just (Any [UnicodeSyntax])) ),
( "\x2237", (DoubleColon, Just (Any [UnicodeSyntax])) ),
( "\x2919", (LeftArrowTail, Just (All [UnicodeSyntax, Arrows])) ),
( "\x291a", (RightArrowTail, Just (All [UnicodeSyntax, Arrows])) ),
( "\x291b", (LeftDblArrowTail, Just (All [UnicodeSyntax, Arrows])) ),
( "\x291c", (RightDblArrowTail, Just (All [UnicodeSyntax, Arrows])) ),
( "\x2605", (Star, Just (All [UnicodeSyntax, KindSignatures])) ),
( "\x2200", (KW_Forall, Just (All [UnicodeSyntax, ExplicitForAll])) )
]
special_varops :: [(String,(Token, Maybe ExtScheme))]
special_varops = [
-- the dot is only a special symbol together with forall, but can still be used as function composition
( ".", (Dot, Just (Any [ExplicitForAll, ExistentialQuantification])) ),
( "-", (Minus, Nothing) ),
( "!", (Exclamation, Nothing) )
]
reserved_ids :: [(String,(Token, Maybe ExtScheme))]
reserved_ids = [
( "_", (Underscore, Nothing) ),
( "by", (KW_By, Just (Any [TransformListComp])) ),
( "case", (KW_Case, Nothing) ),
( "class", (KW_Class, Nothing) ),
( "data", (KW_Data, Nothing) ),
( "default", (KW_Default, Nothing) ),
( "deriving", (KW_Deriving, Nothing) ),
( "do", (KW_Do, Nothing) ),
( "else", (KW_Else, Nothing) ),
( "family", (KW_Family, Just (Any [TypeFamilies])) ), -- indexed type families
( "forall", (KW_Forall, Just (Any [ExplicitForAll, ExistentialQuantification])) ), -- universal/existential quantification
( "group", (KW_Group, Just (Any [TransformListComp])) ),
( "if", (KW_If, Nothing) ),
( "import", (KW_Import, Nothing) ),
( "in", (KW_In, Nothing) ),
( "infix", (KW_Infix, Nothing) ),
( "infixl", (KW_InfixL, Nothing) ),
( "infixr", (KW_InfixR, Nothing) ),
( "instance", (KW_Instance, Nothing) ),
( "let", (KW_Let, Nothing) ),
( "mdo", (KW_MDo, Just (Any [RecursiveDo])) ),
( "module", (KW_Module, Nothing) ),
( "newtype", (KW_NewType, Nothing) ),
( "of", (KW_Of, Nothing) ),
( "proc", (KW_Proc, Just (Any [Arrows])) ),
( "rec", (KW_Rec, Just (Any [Arrows, RecursiveDo, DoRec])) ),
( "then", (KW_Then, Nothing) ),
( "type", (KW_Type, Nothing) ),
( "using", (KW_Using, Just (Any [TransformListComp])) ),
( "where", (KW_Where, Nothing) ),
( "role", (KW_Role, Just (Any [RoleAnnotations]))),
( "pattern", (KW_Pattern, Just (Any [PatternSynonyms]))),
( "stock", (KW_Stock, Just (Any [DerivingStrategies]))),
( "anyclass", (KW_Anyclass, Just (Any [DerivingStrategies]))),
( "via", (KW_Via, Just (Any [DerivingVia]))),
-- FFI
( "foreign", (KW_Foreign, Just (Any [ForeignFunctionInterface])) )
]
special_varids :: [(String,(Token, Maybe ExtScheme))]
special_varids = [
( "as", (KW_As, Nothing) ),
( "qualified", (KW_Qualified, Nothing) ),
( "hiding", (KW_Hiding, Nothing) ),
-- FFI
( "export", (KW_Export, Just (Any [ForeignFunctionInterface])) ),
( "safe", (KW_Safe, Just (Any [ForeignFunctionInterface, SafeImports, Safe, Trustworthy])) ),
( "unsafe", (KW_Unsafe, Just (Any [ForeignFunctionInterface])) ),
( "threadsafe", (KW_Threadsafe, Just (Any [ForeignFunctionInterface])) ),
( "interruptible", (KW_Interruptible, Just (Any [InterruptibleFFI])) ),
( "stdcall", (KW_StdCall, Just (Any [ForeignFunctionInterface])) ),
( "ccall", (KW_CCall, Just (Any [ForeignFunctionInterface])) ),
( "cplusplus", (KW_CPlusPlus, Just (Any [ForeignFunctionInterface])) ),
( "dotnet", (KW_DotNet, Just (Any [ForeignFunctionInterface])) ),
( "jvm", (KW_Jvm, Just (Any [ForeignFunctionInterface])) ),
( "js", (KW_Js, Just (Any [ForeignFunctionInterface])) ),
( "javascript", (KW_JavaScript, Just (Any [ForeignFunctionInterface])) ),
( "capi", (KW_CApi, Just (Any [CApiFFI])) )
]
pragmas :: [(String,Token)]
pragmas = [
( "rules", RULES ),
( "inline", INLINE True ),
( "noinline", INLINE False ),
( "notinline", INLINE False ),
( "specialise", SPECIALISE ),
( "specialize", SPECIALISE ),
( "source", SOURCE ),
( "deprecated", DEPRECATED ),
( "warning", WARNING ),
( "ann", ANN ),
( "scc", SCC ),
( "generated", GENERATED ),
( "core", CORE ),
( "unpack", UNPACK ),
( "nounpack", NOUNPACK ),
( "language", LANGUAGE ),
( "minimal", MINIMAL ),
( "no_overlap", NO_OVERLAP ),
( "overlap", OVERLAP ),
( "overlaps", OVERLAPS ),
( "overlapping", OVERLAPPING ),
( "overlappable", OVERLAPPABLE ),
( "incoherent", INCOHERENT ),
( "complete", COMPLETE ),
( "options", OPTIONS undefined ) -- we'll tweak it before use - promise!
-- ( "cfiles", CFILES undefined ), -- same here...
-- ( "include", INCLUDE undefined ) -- ...and here!
]
isIdent, isHSymbol, isPragmaChar :: Char -> Bool
isIdent c = isAlphaNum c || c == '\'' || c == '_'
isHSymbol c = c `elem` ":!#%&*./?@\\-" || ((isSymbol c || isPunctuation c) && not (c `elem` "(),;[]`{}_\"'"))
isPragmaChar c = isAlphaNum c || c == '_'
-- Used in the lexing of type applications
-- Why is it like this? I don't know exactly but this is how it is in
-- GHC's parser.
-- Symbol `:` is added so that `@:` is lexed as `VarSym "@:"`. See Issue #326
isOpSymbol :: Char -> Bool
isOpSymbol c = c `elem` ":!#$%&*+./<=>?@\\^|-~"
-- | Checks whether the character would be legal in some position of a qvar.
-- Means that '..' and "AAA" will pass the test.
isPossiblyQvar :: Char -> Bool
isPossiblyQvar c = isIdent (toLower c) || c == '.'
matchChar :: Char -> String -> Lex a ()
matchChar c msg = do
s <- getInput
if null s || head s /= c then fail msg else discard 1
-- The top-level lexer.
-- We need to know whether we are at the beginning of the line to decide
-- whether to insert layout tokens.
lexer :: (Loc Token -> P a) -> P a
lexer = runL topLexer
topLexer :: Lex a (Loc Token)
topLexer = do
b <- pullCtxtFlag
if b then -- trace (show cf ++ ": " ++ show VRightCurly) $
-- the lex context state flags that we must do an empty {} - UGLY
setBOL >> getSrcLocL >>= \l -> return (Loc (mkSrcSpan l l) VRightCurly)
else do
bol <- checkBOL
(bol', ws) <- lexWhiteSpace bol
-- take care of whitespace in PCDATA
ec <- getExtContext
case ec of
-- if there was no linebreak, and we are lexing PCDATA,
-- then we want to care about the whitespace.
-- We don't bother to test for XmlSyntax, since we
-- couldn't end up in ChildCtxt otherwise.
Just ChildCtxt | not bol' && ws -> getSrcLocL >>= \l -> return $ Loc (mkSrcSpan l l) $ XPCDATA " "
_ -> do startToken
sl <- getSrcLocL
t <- if bol' then lexBOL -- >>= \t -> trace ("BOL: " ++ show t) (return t)
else lexToken -- >>= \t -> trace (show t) (return t)
el <- getSrcLocL
return $ Loc (mkSrcSpan sl el) t
lexWhiteSpace :: Bool -> Lex a (Bool, Bool)
lexWhiteSpace bol = do
s <- getInput
ignL <- ignoreLinePragmasL
case s of
-- If we find a recognised pragma, we don't want to treat it as a comment.
'{':'-':'#':rest | isRecognisedPragma rest -> return (bol, False)
| isLinePragma rest && not ignL -> do
(l, fn) <- lexLinePragma
setSrcLineL l
setLineFilenameL fn
lexWhiteSpace True
'{':'-':_ -> do
loc <- getSrcLocL
discard 2
(bol1, c) <- lexNestedComment bol ""
loc2 <- getSrcLocL
pushComment $ Comment True (mkSrcSpan loc loc2) (reverse c)
(bol2, _) <- lexWhiteSpace bol1
return (bol2, True)
'-':'-':s1 | all (== '-') (takeWhile isHSymbol s1) -> do
loc <- getSrcLocL
discard 2
dashes <- lexWhile (== '-')
rest <- lexWhile (/= '\n')
s' <- getInput
loc2 <- getSrcLocL
let com = Comment False (mkSrcSpan loc loc2) $ dashes ++ rest
case s' of
[] -> pushComment com >> return (False, True)
_ -> do
pushComment com
lexNewline
lexWhiteSpace_ True
return (True, True)
'\n':_ -> do
lexNewline
lexWhiteSpace_ True
return (True, True)
'\t':_ -> do
lexTab
(bol', _) <- lexWhiteSpace bol
return (bol', True)
c:_ | isSpace c -> do
discard 1
(bol', _) <- lexWhiteSpace bol
return (bol', True)
_ -> return (bol, False)
-- | lexWhiteSpace without the return value.
lexWhiteSpace_ :: Bool -> Lex a ()
lexWhiteSpace_ bol = do _ <- lexWhiteSpace bol
return ()
isRecognisedPragma, isLinePragma :: String -> Bool
isRecognisedPragma str = let pragma = takeWhile isPragmaChar . dropWhile isSpace $ str
in case lookupKnownPragma pragma of
Nothing -> False
_ -> True
isLinePragma str = let pragma = map toLower . takeWhile isAlphaNum . dropWhile isSpace $ str
in case pragma of
"line" -> True
_ -> False
lexLinePragma :: Lex a (Int, String)
lexLinePragma = do
discard 3 -- {-#
lexWhile_ isSpace
discard 4 -- LINE
lexWhile_ isSpace
i <- lexWhile isDigit
when (null i) $ fail "Improperly formatted LINE pragma"
lexWhile_ isSpace
matchChar '"' "Improperly formatted LINE pragma"
fn <- lexWhile (/= '"')
matchChar '"' "Impossible - lexLinePragma"
lexWhile_ isSpace
mapM_ (flip matchChar "Improperly formatted LINE pragma") "#-}"
lexNewline
return (read i, fn)
lexNestedComment :: Bool -> String -> Lex a (Bool, String)
lexNestedComment bol str = do
s <- getInput
case s of
'-':'}':_ -> discard 2 >> return (bol, str)
'{':'-':_ -> do
discard 2
(bol', c) <- lexNestedComment bol ("-{" ++ str) -- rest of the subcomment
lexNestedComment bol' ("}-" ++ c ) -- rest of this comment
'\t':_ -> lexTab >> lexNestedComment bol ('\t':str)
'\n':_ -> lexNewline >> lexNestedComment True ('\n':str)
c:_ -> discard 1 >> lexNestedComment bol (c:str)
[] -> fail "Unterminated nested comment"
-- When we are lexing the first token of a line, check whether we need to
-- insert virtual semicolons or close braces due to layout.
lexBOL :: Lex a Token
lexBOL = do
pos <- getOffside
-- trace ("Off: " ++ (show pos)) $ do
case pos of
LT -> do
-- trace "layout: inserting '}'\n" $
-- Set col to 0, indicating that we're still at the
-- beginning of the line, in case we need a semi-colon too.
-- Also pop the context here, so that we don't insert
-- another close brace before the parser can pop it.
setBOL
popContextL "lexBOL"
return VRightCurly
EQ ->
-- trace "layout: inserting ';'\n" $
return SemiColon
GT -> lexToken
lexToken :: Lex a Token
lexToken = do
ec <- getExtContext
-- we don't bother to check XmlSyntax since we couldn't
-- have ended up in a non-Nothing context if it wasn't
-- enabled.
case ec of
Just HarpCtxt -> lexHarpToken
Just TagCtxt -> lexTagCtxt
Just CloseTagCtxt -> lexCloseTagCtxt
Just ChildCtxt -> lexChildCtxt
Just CodeTagCtxt -> lexCodeTagCtxt
_ -> lexStdToken
lexChildCtxt :: Lex a Token
lexChildCtxt = do
-- if we ever end up here, then XmlSyntax must be on.
s <- getInput
case s of
'<':'%':'>':_ -> do discard 3
pushExtContextL ChildCtxt
return XChildTagOpen
'<':'%':_ -> do discard 2
pushExtContextL CodeTagCtxt
return XCodeTagOpen
'<':'/':_ -> do discard 2
popExtContextL "lexChildCtxt"
pushExtContextL CloseTagCtxt
return XCloseTagOpen
'<':'[':_ -> do discard 2
pushExtContextL HarpCtxt
return XRPatOpen
'<':_ -> do discard 1
pushExtContextL TagCtxt
return XStdTagOpen
_ -> lexPCDATA
lexPCDATA :: Lex a Token
lexPCDATA = do
-- if we ever end up here, then XmlSyntax must be on.
s <- getInput
case s of
[] -> return EOF
_ -> case s of
'\n':_ -> do
x <- lexNewline >> lexPCDATA
case x of
XPCDATA p -> return $ XPCDATA $ '\n':p
EOF -> return EOF
_ -> fail $ "lexPCDATA: unexpected token: " ++ show x
'<':_ -> return $ XPCDATA ""
_ -> do let pcd = takeWhile (\c -> c `notElem` "<\n") s
l = length pcd
discard l
x <- lexPCDATA
case x of
XPCDATA pcd' -> return $ XPCDATA $ pcd ++ pcd'
EOF -> return EOF
_ -> fail $ "lexPCDATA: unexpected token: " ++ show x
lexCodeTagCtxt :: Lex a Token
lexCodeTagCtxt = do
-- if we ever end up here, then XmlSyntax must be on.
s <- getInput
case s of
'%':'>':_ -> do discard 2
popExtContextL "lexCodeTagContext"
return XCodeTagClose
_ -> lexStdToken
lexCloseTagCtxt :: Lex a Token
lexCloseTagCtxt = do
-- if we ever end up here, then XmlSyntax must be on.
s <- getInput
case s of
'%':'>':_ -> do discard 2
popExtContextL "lexCloseTagCtxt"
return XCodeTagClose
'>':_ -> do discard 1
popExtContextL "lexCloseTagCtxt"
return XStdTagClose
_ -> lexStdToken
lexTagCtxt :: Lex a Token
lexTagCtxt = do
-- if we ever end up here, then XmlSyntax must be on.
s <- getInput
case s of
'/':'>':_ -> do discard 2
popExtContextL "lexTagCtxt: Empty tag"
return XEmptyTagClose
'>':_ -> do discard 1
popExtContextL "lexTagCtxt: Standard tag"
pushExtContextL ChildCtxt
return XStdTagClose
_ -> lexStdToken
lexHarpToken :: Lex a Token
lexHarpToken = do
-- if we ever end up here, then RegularPatterns must be on.
s <- getInput
case s of
']':'>':_ -> do discard 2
popExtContextL "lexHarpToken"
return XRPatClose
_ -> lexStdToken
lexStdToken :: Lex a Token
lexStdToken = do
s <- getInput
exts <- getExtensionsL
let intHash = lexHash IntTok IntTokHash (Right WordTokHash)
case s of
[] -> return EOF
'0':c:d:_ | toLower c == 'o' && isOctDigit d -> do
discard 2
(n, str) <- lexOctal
con <- intHash
return (con (n, '0':c:str))
| toLower c == 'b' && isBinDigit d && BinaryLiterals `elem` exts -> do
discard 2
(n, str) <- lexBinary
con <- intHash
return (con (n, '0':c:str))
| toLower c == 'x' && isHexDigit d -> do
discard 2
(n, str) <- lexHexadecimal
con <- intHash
return (con (n, '0':c:str))
-- implicit parameters
'?':c:_ | isLower c && ImplicitParams `elem` exts -> do
discard 1
id <- lexWhile isIdent
return $ IDupVarId id
'%':c:_ | isLower c && ImplicitParams `elem` exts -> do
discard 1
id <- lexWhile isIdent
return $ ILinVarId id
-- end implicit parameters
-- harp
-- '(':'|':c:_ | isHSymbol c -> discard 1 >> return LeftParen
'(':'|':c:_ | RegularPatterns `elem` exts && not (isHSymbol c) ->
do discard 2
return RPGuardOpen
'|':')':_ | RegularPatterns `elem` exts ->
do discard 2
return RPGuardClose
{- This is handled by the reserved_ops above.
'@':':':_ | RegularPatterns `elem` exts ->
do discard 2
return RPCAt -}
-- template haskell
'[':'|':_ | TemplateHaskell `elem` exts -> do
discard 2
return THExpQuote
'[':c:'|':_ | c == 'e' && TemplateHaskell `elem` exts -> do
discard 3
return THExpQuote
| c == 'p' && TemplateHaskell `elem` exts -> do
discard 3
return THPatQuote
| c == 'd' && TemplateHaskell `elem` exts -> do
discard 3
return THDecQuote
| c == 't' && TemplateHaskell `elem` exts -> do
discard 3
return THTypQuote
'[':'$':c:_ | isLower c && QuasiQuotes `elem` exts ->
discard 2 >> lexQuasiQuote c
'[':c:s' | isLower c && QuasiQuotes `elem` exts && case dropWhile isIdent s' of { '|':_ -> True;_->False} ->
discard 1 >> lexQuasiQuote c
| isUpper c && QuasiQuotes `elem` exts && case dropWhile isPossiblyQvar s' of { '|':_ -> True;_->False} ->
discard 1 >> lexQuasiQuote c
'|':']':_ | TemplateHaskell `elem` exts -> do
discard 2
return THCloseQuote
'$':c:_ | isLower c && TemplateHaskell `elem` exts -> do
discard 1
id <- lexWhile isIdent
return $ THIdEscape id
| c == '(' && TemplateHaskell `elem` exts -> do
discard 2
return THParenEscape
-- end template haskell
-- hsx
'<':'%':c:_ | XmlSyntax `elem` exts ->
case c of
'>' -> do discard 3
pushExtContextL ChildCtxt
return XChildTagOpen
_ -> do discard 2
pushExtContextL CodeTagCtxt
return XCodeTagOpen
'<':c:_ | isAlpha c && XmlSyntax `elem` exts -> do
discard 1
pushExtContextL TagCtxt
return XStdTagOpen
-- end hsx
'(':'#':c:_ | unboxed exts && not (isHSymbol c) -> discard 2 >> return LeftHashParen
'#':')':_ | unboxed exts -> discard 2 >> return RightHashParen
-- pragmas
'{':'-':'#':_ -> saveExtensionsL >> discard 3 >> lexPragmaStart
'#':'-':'}':_ -> restoreExtensionsL >> discard 3 >> return PragmaEnd
-- Parallel arrays
'[':':':_ | ParallelArrays `elem` exts -> discard 2 >> return ParArrayLeftSquare
':':']':_ | ParallelArrays `elem` exts -> discard 2 >> return ParArrayRightSquare
-- Lexed seperately to deal with visible type applciation
'@':c:_ | TypeApplications `elem` exts
-- Operator starting with an '@'
&& not (isOpSymbol c) -> do
lc <- getLastChar
if isIdent lc
then discard 1 >> return At
else discard 1 >> return TApp
'#':c:_ | OverloadedLabels `elem` exts
&& isLower c || c == '_' -> do
discard 1
[ident] <- lexIdents
return $ LabelVarId ident
c:_ | isDigit c -> lexDecimalOrFloat
| isUpper c -> lexConIdOrQual ""
| isLower c || c == '_' -> do
idents <- lexIdents
case idents of
[ident] -> case lookup ident (reserved_ids ++ special_varids) of
Just (keyword, scheme) ->
-- check if an extension keyword is enabled
if isEnabled scheme exts
then flagKW keyword >> return keyword
else return $ VarId ident
Nothing -> return $ VarId ident
_ -> return $ DVarId idents
| isHSymbol c -> do
sym <- lexWhile isHSymbol
return $ case lookup sym (reserved_ops ++ special_varops) of
Just (t , scheme) ->
-- check if an extension op is enabled
if isEnabled scheme exts
then t
else case c of
':' -> ConSym sym
_ -> VarSym sym
Nothing -> case c of
':' -> ConSym sym
_ -> VarSym sym
| otherwise -> do
discard 1
case c of
-- First the special symbols
'(' -> return LeftParen
')' -> return RightParen
',' -> return Comma
';' -> return SemiColon
'[' -> return LeftSquare
']' -> return RightSquare
'`' -> return BackQuote
'{' -> do
pushContextL NoLayout
return LeftCurly
'}' -> do
popContextL "lexStdToken"
return RightCurly
'\'' -> lexCharacter
'"' -> lexString
_ -> fail ("Illegal character \'" ++ show c ++ "\'\n")
where lexIdents :: Lex a [String]
lexIdents = do
ident <- lexWhile isIdent
s <- getInput
exts <- getExtensionsL
case s of
-- This is the only way we can get more than one ident in the list
-- and it requires XmlSyntax to be on.
'-':c:_ | XmlSyntax `elem` exts && isAlpha c -> do
discard 1
idents <- lexIdents
return $ ident : idents
'#':_ | MagicHash `elem` exts -> do
hashes <- lexWhile (== '#')
return [ident ++ hashes]
_ -> return [ident]
lexQuasiQuote :: Char -> Lex a Token
lexQuasiQuote c = do
-- We've seen and dropped [$ already
ident <- lexQuoter
matchChar '|' "Malformed quasi-quote quoter"
body <- lexQQBody
return $ THQuasiQuote (ident, body)
where lexQuoter
| isLower c = lexWhile isIdent
| otherwise = do
qualThing <- lexConIdOrQual ""
case qualThing of
QVarId (s1,s2) -> return $ s1 ++ '.':s2
QVarSym (s1, s2) -> return $ s1 ++ '.':s2
_ -> fail "Malformed quasi-quote quoter"
lexQQBody :: Lex a String
lexQQBody = do
s <- getInput
case s of
'\\':']':_ -> do discard 2
str <- lexQQBody
return (']':str)
'\\':'|':_ -> do discard 2
str <- lexQQBody
return ('|':str)
'|':']':_ -> discard 2 >> return ""
'|':_ -> do discard 1
str <- lexQQBody
return ('|':str)
']':_ -> do discard 1
str <- lexQQBody
return (']':str)
'\\':_ -> do discard 1
str <- lexQQBody
return ('\\':str)
'\n':_ -> do lexNewline
str <- lexQQBody
return ('\n':str)
[] -> fail "Unexpected end of input while lexing quasi-quoter"
_ -> do str <- lexWhile (not . (`elem` "\\|\n"))
rest <- lexQQBody
return (str++rest)
unboxed :: [KnownExtension] -> Bool
unboxed exts = UnboxedSums `elem` exts || UnboxedTuples `elem` exts
-- Underscores are used in some pragmas. Options pragmas are a special case
-- with our representation: the thing after the underscore is a parameter.
-- Strip off the parameters to option pragmas by hand here, everything else
-- sits in the pragmas map.
lookupKnownPragma :: String -> Maybe Token
lookupKnownPragma s =
case map toLower s of
x | "options_" `isPrefixOf` x -> Just $ OPTIONS (Just $ drop 8 s, undefined)
| "options" == x -> Just $ OPTIONS (Nothing, undefined)
| otherwise -> lookup x pragmas
lexPragmaStart :: Lex a Token
lexPragmaStart = do
lexWhile_ isSpace
pr <- lexWhile isPragmaChar
case lookupKnownPragma pr of
Just (INLINE True) -> do
s <- getInput
case map toLower s of
' ':'c':'o':'n':'l':'i':'k':'e':_ -> do
discard 8
return INLINE_CONLIKE
_ -> return $ INLINE True
Just SPECIALISE -> do
s <- getInput
case dropWhile isSpace $ map toLower s of
'i':'n':'l':'i':'n':'e':_ -> do
lexWhile_ isSpace
discard 6
return $ SPECIALISE_INLINE True
'n':'o':'i':'n':'l':'i':'n':'e':_ -> do
lexWhile_ isSpace
discard 8
return $ SPECIALISE_INLINE False
'n':'o':'t':'i':'n':'l':'i':'n':'e':_ -> do
lexWhile_ isSpace
discard 9
return $ SPECIALISE_INLINE False
_ -> return SPECIALISE
Just (OPTIONS opt) -> -- see, I promised we'd mask out the 'undefined'
-- We do not want to store necessary whitespace in the datatype
-- but if the pragma starts with a newline then we must keep
-- it to differentiate the two cases.
let dropIfSpace (' ':xs) = xs
dropIfSpace xs = xs
in
case fst opt of
Just opt' -> do
rest <- lexRawPragma
return $ OPTIONS (Just opt', dropIfSpace rest)
Nothing -> do
s <- getInput
case s of
x:_ | isSpace x -> do
rest <- lexRawPragma
return $ OPTIONS (Nothing, dropIfSpace rest)
_ -> fail "Malformed Options pragma"
Just RULES -> do -- Rules enable ScopedTypeVariables locally.
addExtensionL ScopedTypeVariables
return RULES
{- Just (CFILES _) -> do
rest <- lexRawPragma
return $ CFILES rest
Just (INCLUDE _) -> do
rest <- lexRawPragma
return $ INCLUDE rest -}
Just p -> return p
_ -> fail "Internal error: Unrecognised recognised pragma"
-- do rawStr <- lexRawPragma
-- return $ PragmaUnknown (pr, rawStr) -- no support for unrecognized pragmas, treat as comment
-- discard 3 -- #-}
-- topLexer -- we just discard it as a comment for now and restart -}
lexRawPragma :: Lex a String
lexRawPragma = lexRawPragmaAux
where lexRawPragmaAux = do
rpr <- lexWhile (/='#')
s <- getInput
case s of
'#':'-':'}':_ -> return rpr
"" -> fail "End-of-file inside pragma"
_ -> do
discard 1
rpr' <- lexRawPragma
return $ rpr ++ '#':rpr'
lexDecimalOrFloat :: Lex a Token
lexDecimalOrFloat = do
ds <- lexWhile isDigit
rest <- getInput
exts <- getExtensionsL
case rest of
('.':d:_) | isDigit d -> do
discard 1
frac <- lexWhile isDigit
let num = parseInteger 10 (ds ++ frac)
decimals = toInteger (length frac)
(exponent, estr) <- do
rest2 <- getInput
case rest2 of
'e':_ -> lexExponent
'E':_ -> lexExponent