SyntaxColoring.hs 31.5 KB
Newer Older
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
1
2
3
4
5
6
7
8
module Html.SyntaxColoring
  ( Program, Code (..), TypeKind (..), ConstructorKind (..)
  , IdentifierKind (..), FunctionKind (..)
  , genProgram, code2string, getQualIdent, position2code, area2codes
  ) where

import Data.Char hiding (Space)
import Data.Function (on)
9
import Data.List (intercalate, nubBy, partition)
Björn Peemöller 's avatar
Björn Peemöller committed
10
import Data.Maybe (fromMaybe, mapMaybe)
11
import Debug.Trace (trace)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
12
13
14

import Curry.Base.Ident
import Curry.Base.Position
15
import Curry.Base.Message
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
16
17
import Curry.Syntax hiding (infixOp)

18
19
import Base.Messages

Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
debug :: Bool
debug = False -- mergen von Token und Codes

trace' :: String -> a -> a
trace' s x = if debug then trace s x else x

debug' :: Bool
debug' = False -- messages

trace'' :: String -> a -> a
trace'' s x = if debug' then trace s x else x

type Program = [(Int, Int, Code)]

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
data Code
  = Keyword String
  | Space Int
  | NewLine
  | ConstructorName ConstructorKind QualIdent
  | TypeConstructor TypeKind QualIdent
  | Function FunctionKind QualIdent
  | ModuleName ModuleIdent
  | Commentary String
  | NumberCode String
  | StringCode String
  | CharCode String
  | Symbol String
  | Identifier IdentifierKind QualIdent
  | CodeWarning [Message] Code
  | NotParsed String
    deriving Show

data TypeKind
  = TypeDecla
  | TypeUse
  | TypeExport deriving Show

data ConstructorKind
  = ConstrPattern
  | ConstrCall
  | ConstrDecla
  | OtherConstrKind deriving Show

data IdentifierKind
  = IdDecl
  | IdOccur
  | UnknownId  deriving Show

data FunctionKind
  = InfixFunction
  | TypSig
  | FunDecl
  | FunctionCall
  | OtherFunctionKind deriving Show
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
74
75

--- @param plaintext
76
77
--- @param list with parse-Results with descending quality,
---        e.g. [typingParse, fullParse, parse]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
78
79
--- @param lex-Result
--- @return program
80
genProgram :: String -> [MessageM Module] -> MessageM [(Position, Token)] -> Program
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
81
genProgram plainText parseResults m = case runMsg m of
Björn Peemöller 's avatar
Björn Peemöller committed
82
83
  Left e -> buildMessagesIntoPlainText [e] plainText
  Right (posNtokList, mess) ->
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
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
    let messages = (prepareMessages (concatMap getMessages parseResults ++ mess))
        mergedMessages = (mergeMessages' (trace' ("Messages: " ++ show messages) messages) posNtokList)
        (nameList,codes) = catIdentifiers parseResults
    in tokenNcodes2codes nameList 1 1 mergedMessages codes

--- @param Program
--- @param line
--- @param col
--- @return Code at this Position
position2code :: Program -> Int -> Int -> Maybe Code
position2code []  _ _ = Nothing
position2code [_] _ _ = Nothing
position2code ((l,c,code):xs@((_,c2,_):_)) lin col
     | lin == l && col >= c && col < c2 = Just code
     | l > lin = Nothing
     | otherwise = position2code xs lin col

area2codes :: Program -> Position -> Position -> [Code]
area2codes [] _ _ = []
area2codes xxs@((l,c,code):xs) p1@Position{file=f} p2
     | p1 > p2 = area2codes xxs p2 p1
     | posEnd >= p1 && posBegin <= p2  = code : area2codes xs p1 p2
     | posBegin > p2 = []
     | otherwise = area2codes xs p1 p2
   where
      posBegin = Position f l c noRef
      posEnd   = Position f l (c + length (code2string code)) noRef
111
area2codes _ _ _ = internalError "SyntaxColoring.area2codes: no pattern match"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
112
113
114
115
116
117
118
119
120
121
122
123

--- @param code
--- @return qualIdent if available
getQualIdent :: Code -> Maybe QualIdent
getQualIdent (ConstructorName _ qualIdent) = Just qualIdent
getQualIdent (Function _ qualIdent) = Just qualIdent
getQualIdent (Identifier _ qualIdent) = Just qualIdent
getQualIdent (TypeConstructor _ qualIdent) = Just qualIdent
getQualIdent  _ = Nothing

-- DEBUGGING----------- wird bald nicht mehr gebraucht

124
125
126
setMessagePosition :: Message -> Message
setMessagePosition m@(Message (Just p) _) = trace'' ("pos:" ++ show p ++ ":" ++ show m) m
setMessagePosition (Message _ m) =
127
        let mes@(Message pos _) =  (Message (getPositionFromString $ show m) m) in
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
128
129
130
        trace'' ("pos:" ++ show pos ++ ":" ++ show mes) mes

getPositionFromString :: String -> Maybe Position
131
getPositionFromString msg =
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
132
133
134
135
     if l > 0 && c > 0
          then Just Position{file=f,line=l,column=c,astRef=noRef}
          else Nothing
  where
136
137
138
      f = takeWhile (/= '"') (tail (dropWhile (/= '"') msg))
      l = readInt (takeWhile (/= '.') (drop 7 (dropWhile (/= ',') msg)))
      c = readInt (takeWhile (/= ':') (tail (dropWhile (/= '.') (drop 7 (dropWhile (/= ',') msg)))))
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153


readInt :: String -> Int
readInt s =
      let onlyNum = filter isDigit s in
      if null onlyNum
         then 0
         else read onlyNum :: Int

flatCode :: Code -> Code
flatCode (CodeWarning _ code) = code
flatCode code = code

-- ----------Message---------------------------------------

154
getMessages :: MessageM a -> [Message]
Björn Peemöller 's avatar
Björn Peemöller committed
155
getMessages = either return snd . runMsg --(Result mess _) = mess
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
156
157
-- getMessages (Failure mess) = mess

158
159
lessMessage :: Message -> Message -> Bool
lessMessage (Message mPos1 _) (Message mPos2 _) = mPos1 < mPos2
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
160

161
nubMessages :: [Message] -> [Message]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
162
163
nubMessages = nubBy eqMessage

164
eqMessage :: Message -> Message -> Bool
165
eqMessage (Message p1 s1) (Message p2 s2) = (p1 == p2) && (show s1 == show s2)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
166

167
prepareMessages :: [Message] -> [Message]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
168
169
170
prepareMessages = qsort lessMessage . map setMessagePosition . nubMessages


171
buildMessagesIntoPlainText :: [Message] -> String -> Program
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
172
173
174
buildMessagesIntoPlainText messages text =
    buildMessagesIntoPlainText' messages (lines text) [] 1
 where
175
    buildMessagesIntoPlainText' :: [Message] -> [String] -> [String] -> Int -> Program
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
    buildMessagesIntoPlainText' _ [] [] _ =
          []
    buildMessagesIntoPlainText' _ [] postStrs ln =
          [(ln,1,NotParsed (unlines postStrs))]
    buildMessagesIntoPlainText' [] preStrs postStrs ln =
          [(ln,1,NotParsed (unlines (preStrs ++ postStrs)))]

    buildMessagesIntoPlainText' messages1 (str:preStrs) postStrs ln =
          let (pre,post) = partition isLeq messages1 in
          if null pre
             then buildMessagesIntoPlainText' post preStrs (postStrs ++ [str]) (ln + 1)
             else (ln,1,NotParsed (unlines postStrs)) :
                  (ln,1,CodeWarning pre (NotParsed str)) :
                  (ln,1,NewLine) :
                  buildMessagesIntoPlainText' post preStrs [] (ln + 1)
      where
192
         isLeq (Message (Just p) _) = line p <= ln
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
193
194
195
         isLeq _ = True

--- @param parse-Modules  [typingParse,fullParse,parse]
196
catIdentifiers :: [MessageM Module] -> ([(ModuleIdent,ModuleIdent)],[Code])
Björn Peemöller 's avatar
Björn Peemöller committed
197
catIdentifiers = catIds . map fst . rights_sc . map runMsg
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    where
      catIds [] = ([],[])
      catIds [m] =
          catIdentifiers' m Nothing
      catIds rs@(m:_:_) =
          catIdentifiers' (last rs) (Just m)

-- not in base befoer base4
rights_sc :: [Either a b] -> [b]
rights_sc  xs = [ x | Right x <- xs]

--- @param parse-Module
--- @param Maybe betterParse-Module
catIdentifiers' :: Module -> Maybe Module -> ([(ModuleIdent,ModuleIdent)],[Code])
212
catIdentifiers' (Module moduleIdent maybeExportSpec imports decls)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
213
                Nothing =
214
215
216
      let impCodes = concatMap importDecl2codes (qsort lessImportDecl imports)
          codes = (concatMap decl2codes (qsort lessDecl decls))
      in (concatMap renamedImports imports,
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
217
      ModuleName moduleIdent :
218
219
220
221
222
223
       maybe [] exportSpec2codes maybeExportSpec ++ impCodes ++ codes)
catIdentifiers' (Module moduleIdent maybeExportSpec1 _ _)
                (Just (Module _ maybeExportSpec2 imports decls)) =
      let impCodes = concatMap importDecl2codes (qsort lessImportDecl imports)
          codes = (concatMap decl2codes (qsort lessDecl decls))
      in (concatMap renamedImports imports,
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
224
225
226
227
228
229
      replaceFunctionCalls $
        map (addModuleIdent moduleIdent)
          ([ModuleName moduleIdent] ++
           mergeExports2codes
              (maybe [] (\(Exporting _ i) -> i)  maybeExportSpec1)
              (maybe [] (\(Exporting _ i) -> i)  maybeExportSpec2) ++
230
           impCodes ++ codes))
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
231

232
233
234
renamedImports :: ImportDecl -> [(ModuleIdent,ModuleIdent)]
renamedImports (ImportDecl _ oldName _ (Just newName) _) = [(oldName,newName)]
renamedImports _ = []
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
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


replaceFunctionCalls :: [Code] -> [Code]
replaceFunctionCalls codes = map (idOccur2functionCall qualIdents) codes
   where
      qualIdents = findFunctionDecls codes


findFunctionDecls :: [Code] -> [QualIdent]
findFunctionDecls  =  mapMaybe getQualIdent .
                      filter isFunctionDecl .
                      map flatCode

isFunctionDecl  :: Code -> Bool
isFunctionDecl  (Function FunDecl _)  = True
isFunctionDecl  _ = False

idOccur2functionCall :: [QualIdent] -> Code -> Code
idOccur2functionCall qualIdents ide@(Identifier IdOccur qualIdent)
   | isQualified qualIdent = Function FunctionCall qualIdent
   | elem qualIdent qualIdents = Function FunctionCall qualIdent
   | otherwise = ide
idOccur2functionCall qualIdents (CodeWarning mess code) =
       CodeWarning mess (idOccur2functionCall qualIdents code)
idOccur2functionCall _ code = code


addModuleIdent :: ModuleIdent -> Code -> Code
addModuleIdent moduleIdent c@(Function x qualIdent)
264
    | idUnique (unqualify qualIdent) == 0 =
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
        Function x (qualQualify moduleIdent qualIdent)
    | otherwise = c
addModuleIdent moduleIdent cn@(ConstructorName x qualIdent)
    | not $ isQualified qualIdent =
        ConstructorName x (qualQualify moduleIdent qualIdent)
    | otherwise = cn
addModuleIdent moduleIdent tc@(TypeConstructor TypeDecla qualIdent)
    | not $ isQualified qualIdent =
        TypeConstructor TypeDecla (qualQualify moduleIdent qualIdent)
    | otherwise = tc
addModuleIdent moduleIdent (CodeWarning mess code) =
    CodeWarning mess (addModuleIdent moduleIdent code)
addModuleIdent _ c = c

-- ----------------------------------------

281
mergeMessages' :: [Message] -> [(Position,Token)] -> [([Message],Position,Token)]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
282
283
mergeMessages' _ [] = []
mergeMessages' [] ((p,t):ps) = ([],p,t) : mergeMessages' [] ps
284
mergeMessages' mss@(m@(Message mPos x):ms) ((p,t):ps)
285
    | mPos <= Just p = trace' (show mPos ++ " <= " ++ show (Just p) ++ " Message: " ++ show x) ([m],p,t) : mergeMessages' ms ps
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
286
287
288
    | otherwise = ([],p,t) : mergeMessages' mss ps


289
tokenNcodes2codes :: [(ModuleIdent,ModuleIdent)] -> Int -> Int -> [([Message],Position,Token)] -> [Code] -> [(Int,Int,Code)]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
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
tokenNcodes2codes _ _ _ [] _ = []
tokenNcodes2codes nameList currLine currCol toks@((messages,Position{line=row,column=col},token):ts) codes
    | currLine < row =
           trace' " NewLine: "
           ((currLine,currCol,NewLine) :
           tokenNcodes2codes nameList (currLine + 1) 1 toks codes)
    | currCol < col =
           trace' (" Space " ++ show (col - currCol))
           ((currLine,currCol,Space (col - currCol)) :
           tokenNcodes2codes nameList currLine col toks codes)
    | isTokenIdentifier token && null codes =
           trace' ("empty Code-List, Token: " ++ show (row,col) ++ show token)
           (addMessage [(currLine,currCol,NotParsed tokenStr)] ++ tokenNcodes2codes nameList newLine newCol ts codes)
    | not (isTokenIdentifier token) =
           trace' (" Token ist kein Identifier: " ++ tokenStr )
           (addMessage [(currLine,currCol,token2code token)] ++ tokenNcodes2codes nameList newLine newCol ts codes)
    | tokenStr == code2string (head codes) =
           trace' (" Code wird genommen: " ++ show (head codes) )
           (addMessage [(currLine,currCol,head codes)] ++ tokenNcodes2codes nameList newLine newCol ts (tail codes))
    | tokenStr == code2qualString (renameModuleIdents nameList (head codes)) =
           let mIdent = maybe Nothing rename (getModuleIdent (head codes))
               lenMod = maybe 0 (length . moduleName) mIdent
               startPos = maybe currCol (const (currCol + lenMod + 1)) mIdent
               symbol = [(currLine,currCol + lenMod,Symbol ".")]
               prefix = maybe []
                              ( (: symbol) .
                                ( \i -> (currLine,
                                         currCol,
                                         ModuleName i)))
                              mIdent in
           trace' (" Code wird genommen: " ++ show (head codes) )
           (addMessage (prefix ++ [(currCol,startPos,head codes)]) ++ tokenNcodes2codes nameList newLine newCol ts (tail codes))
    | elem tokenStr (codeQualifiers (head codes)) =
           trace' (" Token: "++ tokenStr ++" ist Modulname von: " ++ show (head codes) )
           (addMessage [(currLine,currCol,ModuleName (mkMIdent [tokenStr]))] ++
                    tokenNcodes2codes nameList newLine newCol ts codes)
    | otherwise =
           trace' (" Token: "++
                   tokenStr ++
                   ",Code faellt weg:" ++
                   code2string (head codes) ++
                   "|" ++
                   code2qualString (head codes))
           (tokenNcodes2codes nameList currLine currCol toks (tail codes))
  where
      tokenStr = token2string token
      newLine  = (currLine + length (lines tokenStr)) - 1
      newCol   = currCol + length tokenStr

      rename mid = Just $ fromMaybe mid (lookup mid nameList)

      addMessage [] = []
      addMessage ((l,c,code):cs)
         | null messages = (l,c,code):cs
         | otherwise = trace' ("Warning bei code: " ++ show codes ++ ":" ++ show messages)
                              ((l,c,CodeWarning messages code): addMessage cs)
346
tokenNcodes2codes _ _ _ _ _ = internalError "SyntaxColoring.tokenNcodes2codes: no pattern match"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
347
348
349
350
351


renameModuleIdents :: [(ModuleIdent,ModuleIdent)] -> Code -> Code
renameModuleIdents nameList c =
    case c of
352
353
        Function x qualIdent -> Function x (rename qualIdent (qidModule qualIdent))
        Identifier x qualIdent -> Identifier x (rename qualIdent (qidModule qualIdent))
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
354
355
356
        _ -> c
  where
    rename x (Nothing) = x
357
    rename x (Just m) = maybe x (\ m' -> qualifyWith m' (qidIdent x)) (lookup m nameList)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
358
359
360
361
362
363
364
365
366
367
368

{-
codeWithoutUniqueID ::  Code -> String
codeWithoutUniqueID code = maybe (code2string code) (name . unqualify) $ getQualIdent code


codeUnqualify :: Code -> Code
codeUnqualify code = maybe code (setQualIdent code . qualify . unqualify)  $ getQualIdent code
-}

codeQualifiers :: Code -> [String]
369
codeQualifiers = maybe [] midQualifiers . getModuleIdent
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
370
371

getModuleIdent :: Code -> Maybe ModuleIdent
372
373
getModuleIdent (ConstructorName _ qualIdent) = qidModule qualIdent
getModuleIdent (Function _ qualIdent) = qidModule qualIdent
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
374
getModuleIdent (ModuleName moduleIdent) = Just moduleIdent
375
376
getModuleIdent (Identifier _ qualIdent) = qidModule qualIdent
getModuleIdent (TypeConstructor _ qualIdent) = qidModule qualIdent
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
getModuleIdent _ = Nothing

{-
setQualIdent :: Code -> QualIdent -> Code
setQualIdent (Keyword str) _ = (Keyword str)
setQualIdent (Space i) _ = (Space i)
setQualIdent NewLine _ = NewLine
setQualIdent (ConstructorName kind _) qualIdent = (ConstructorName kind qualIdent)
setQualIdent (Function kind _) qualIdent = (Function kind qualIdent)
setQualIdent (ModuleName moduleIdent) _ = (ModuleName moduleIdent)
setQualIdent (Commentary str) _ = (Commentary str)
setQualIdent (NumberCode str) _ = (NumberCode str)
setQualIdent (Symbol str) _ = (Symbol str)
setQualIdent (Identifier kind _) qualIdent = (Identifier kind qualIdent)
setQualIdent (TypeConstructor kind _) qualIdent = (TypeConstructor kind qualIdent)
setQualIdent (StringCode str) _ = (StringCode str)
setQualIdent (CharCode str) _ = (CharCode str)
-}

code2string :: Code -> String
code2string (Keyword str) = str
code2string (Space i)= concat (replicate i " ")
code2string NewLine = "\n"
400
401
402
code2string (ConstructorName _ qualIdent) = idName $ unqualify qualIdent
code2string (TypeConstructor _ qualIdent) = idName $ unqualify qualIdent
code2string (Function _ qualIdent) = idName $ unqualify qualIdent
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
403
404
405
406
407
code2string (ModuleName moduleIdent) = moduleName moduleIdent
code2string (Commentary str) = str
code2string (NumberCode str) = str
code2string (StringCode str) = str
code2string (CharCode str) = str
408
code2string (Symbol str) = str
409
code2string (Identifier _ qualIdent) = idName $ unqualify qualIdent
410
code2string (CodeWarning _ c) = code2string c
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
411
412
413
414
415
416
417
418
419
420
421
code2string (NotParsed str) = str

code2qualString :: Code -> String
code2qualString (ConstructorName _ qualIdent) = qualName qualIdent
code2qualString (Function _ qualIdent) = qualName qualIdent
code2qualString (Identifier _ qualIdent) = qualName qualIdent
code2qualString (TypeConstructor _ qualIdent) = qualName qualIdent
code2qualString x = code2string x

token2code :: Token -> Code
token2code tok@(Token cat _)
422
    | elem cat [IntTok,FloatTok]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
423
         = NumberCode (token2string tok)
424
    | elem cat [KW_case,KW_data,KW_do,KW_else,KW_external,
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
425
                KW_free,KW_if,KW_import,KW_in,KW_infix,KW_infixl,KW_infixr,
426
                KW_let,KW_module,KW_newtype,KW_of,KW_then,KW_type,
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
427
428
429
430
431
                KW_where,Id_as,Id_ccall,Id_forall,Id_hiding,Id_interface,Id_primitive,
                Id_qualified]
         =  Keyword (token2string tok)
    | elem cat [LeftParen,RightParen,Semicolon,LeftBrace,RightBrace,LeftBracket,
                RightBracket,Comma,Underscore,Backquote,
432
                At,Colon,DotDot,DoubleColon,Equals,Backslash,Bar,LeftArrow,RightArrow,
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
                Tilde]
         = Symbol (token2string tok)
    | elem cat [LineComment, NestedComment]
         = Commentary (token2string tok)
    | isTokenIdentifier tok
         = Identifier UnknownId $ qualify $ mkIdent $ token2string tok
    | cat == StringTok
         = StringCode (token2string tok)
    | cat == CharTok
         = CharCode (token2string tok)
    | elem cat [EOF,VSemicolon,VRightBrace] = Space 0
    | otherwise = error "SyntaxColoring.token2code: no pattern match"

isTokenIdentifier :: Token -> Bool
isTokenIdentifier (Token cat _) =
448
  elem cat [Id, QId, Sym, QSym, SymDot, SymMinus, SymMinusDot]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
449
450
451

-- DECL Position

452
453
454
455
456
457
458
459
460
461
462
declPos :: Decl -> Position
declPos (InfixDecl        p _ _ _  ) = p
declPos (DataDecl         p _ _ _  ) = p
declPos (NewtypeDecl      p _ _ _  ) = p
declPos (TypeDecl         p _ _ _  ) = p
declPos (TypeSig          p _ _    ) = p
declPos (FunctionDecl     p _ _    ) = p
declPos (ExternalDecl     p _ _ _ _) = p
declPos (FlatExternalDecl p _      ) = p
declPos (PatternDecl      p _ _    ) = p
declPos (ExtraVariables   p _      ) = p
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
463
464
465


lessDecl :: Decl -> Decl -> Bool
466
lessDecl = (<) `on` declPos
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
467

468
469
470
lessImportDecl :: ImportDecl -> ImportDecl -> Bool
lessImportDecl = (<) `on` (\ (ImportDecl p _ _ _ _) -> p)

Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
471
qsort :: (a -> a -> Bool) -> [a] -> [a]
472
473
474
qsort _    []     = []
qsort less (x:xs) = concat [ qsort less [y | y <- xs, less y x]
                           , [x], qsort less [y | y <- xs, not $ less y x]]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
475
476
477
478
479


-- DECL TO CODE --------------------------------------------------------------------

exportSpec2codes ::  ExportSpec -> [Code]
480
exportSpec2codes (Exporting _ exports) = concatMap (export2codes []) exports
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
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

--- @param parse-Exports
--- @param betterParse-Exports
mergeExports2codes :: [Export] -> [Export]  -> [Code]
mergeExports2codes [] _ = []
mergeExports2codes (e:es) xs = concatMap (export2codes xs)  (e:es)


export2codes :: [Export] -> Export -> [Code]
export2codes exports (Export qualIdent)
    | length (filter checkDouble exports) /= 1 =
       [Identifier UnknownId qualIdent]
    | otherwise =
       let [export] = (filter checkDouble exports) in
       export2c export
  where
    checkDouble (ExportTypeWith q _) = eqQualIdent qualIdent q
    checkDouble (Export q) = eqQualIdent qualIdent q
    checkDouble _ = False

    eqQualIdent q1 q2
      | q1 == q2 = True
      | not (isQualified q1) = unqualify q1 == unqualify q2
      | otherwise = False

    export2c (Export qualIdent1) =
         [Function OtherFunctionKind qualIdent1]
    export2c _ =
         [TypeConstructor TypeExport qualIdent]

export2codes _ (ExportTypeWith qualIdent idents) =
     TypeConstructor TypeExport qualIdent : map (Function OtherFunctionKind . qualify) idents
export2codes _ (ExportTypeAll  qualIdent) =
     [TypeConstructor TypeExport qualIdent]
export2codes _ (ExportModule moduleIdent) =
     [ModuleName moduleIdent]

518
519
importDecl2codes :: ImportDecl -> [Code]
importDecl2codes (ImportDecl _ moduleIdent _ mModuleIdent importSpec) =
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
520
521
522
     [ModuleName moduleIdent] ++
     maybe [] ((:[]) . ModuleName) mModuleIdent ++
     maybe [] (importSpec2codes moduleIdent)  importSpec
523
524

decl2codes :: Decl -> [Code]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
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
decl2codes (InfixDecl _ _ _ idents) =
     map (Function InfixFunction . qualify) idents
decl2codes (DataDecl _ ident idents constrDecls) =
     TypeConstructor TypeDecla (qualify ident) :
     map (Identifier UnknownId . qualify) idents ++
     concatMap constrDecl2codes constrDecls
decl2codes (NewtypeDecl _ _ _ _) =
     []
decl2codes (TypeDecl _ ident idents typeExpr) =
     TypeConstructor TypeDecla (qualify ident) :
     map (Identifier UnknownId . qualify) idents ++
     typeExpr2codes typeExpr
decl2codes (TypeSig _ idents typeExpr) =
     map (Function TypSig . qualify) idents ++ typeExpr2codes typeExpr
decl2codes (FunctionDecl _ _ equations) =
     concatMap equation2codes equations
decl2codes (ExternalDecl _ _ _ _ _) =
     []
decl2codes (FlatExternalDecl _ idents) =
     map (Function FunDecl . qualify) idents
decl2codes (PatternDecl _ constrTerm rhs) =
     constrTerm2codes constrTerm ++ rhs2codes rhs
decl2codes (ExtraVariables _ idents) =
     map (Identifier IdDecl . qualify) idents

equation2codes :: Equation -> [Code]
equation2codes (Equation _ lhs rhs) =
     lhs2codes lhs ++ rhs2codes rhs

lhs2codes :: Lhs -> [Code]
lhs2codes (FunLhs ident constrTerms) =
    Function FunDecl (qualify ident) : concatMap constrTerm2codes constrTerms
lhs2codes (OpLhs constrTerm1 ident constrTerm2) =
    constrTerm2codes constrTerm1 ++ [Function FunDecl $ qualify ident] ++ constrTerm2codes constrTerm2
lhs2codes (ApLhs lhs constrTerms) =
    lhs2codes lhs ++ concatMap constrTerm2codes constrTerms

rhs2codes :: Rhs -> [Code]
rhs2codes (SimpleRhs _ expression decls) =
    expression2codes expression ++ concatMap decl2codes decls
rhs2codes (GuardedRhs condExprs decls) =
    concatMap condExpr2codes condExprs ++ concatMap decl2codes decls

condExpr2codes :: CondExpr -> [Code]
condExpr2codes (CondExpr _ expression1 expression2) =
   expression2codes expression1 ++ expression2codes expression2

constrTerm2codes :: ConstrTerm -> [Code]
constrTerm2codes (LiteralPattern _) = []
constrTerm2codes (NegativePattern _ _) = []
constrTerm2codes (VariablePattern ident) = [Identifier IdDecl (qualify ident)]
constrTerm2codes (ConstructorPattern qualIdent constrTerms) =
    ConstructorName ConstrPattern qualIdent : concatMap constrTerm2codes constrTerms
constrTerm2codes (InfixPattern constrTerm1 qualIdent constrTerm2) =
    constrTerm2codes constrTerm1 ++ [ConstructorName ConstrPattern qualIdent] ++ constrTerm2codes constrTerm2
constrTerm2codes (ParenPattern constrTerm) = constrTerm2codes constrTerm
constrTerm2codes (TuplePattern _ constrTerms) = concatMap constrTerm2codes constrTerms
constrTerm2codes (ListPattern _ constrTerms) = concatMap constrTerm2codes constrTerms
constrTerm2codes (AsPattern ident constrTerm) =
    Function OtherFunctionKind (qualify ident) : constrTerm2codes constrTerm
constrTerm2codes (LazyPattern _ constrTerm) = constrTerm2codes constrTerm
constrTerm2codes (FunctionPattern qualIdent constrTerms) =
    Function OtherFunctionKind qualIdent : concatMap constrTerm2codes constrTerms
constrTerm2codes (InfixFuncPattern constrTerm1 qualIdent constrTerm2) =
    constrTerm2codes constrTerm1 ++ [Function InfixFunction qualIdent] ++ constrTerm2codes constrTerm2
constrTerm2codes (RecordPattern _ _) =
591
  internalError "SyntaxColoring.constrTerm2codes: record pattern"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
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

expression2codes :: Expression -> [Code]
expression2codes (Literal _) = []
expression2codes (Variable qualIdent) =
    [Identifier IdOccur qualIdent]
expression2codes (Constructor qualIdent) =
    [ConstructorName ConstrCall qualIdent]
expression2codes (Paren expression) =
    expression2codes expression
expression2codes (Typed expression typeExpr) =
    expression2codes expression ++ typeExpr2codes typeExpr
expression2codes (Tuple _ expressions) =
    concatMap expression2codes expressions
expression2codes (List _ expressions) =
    concatMap expression2codes expressions
expression2codes (ListCompr _ expression statements) =
    expression2codes expression ++ concatMap statement2codes statements
expression2codes (EnumFrom expression) =
    expression2codes expression
expression2codes (EnumFromThen expression1 expression2) =
    expression2codes expression1 ++ expression2codes expression2
expression2codes (EnumFromTo expression1 expression2) =
    expression2codes expression1 ++ expression2codes expression2
expression2codes (EnumFromThenTo expression1 expression2 expression3) =
    expression2codes expression1 ++
    expression2codes expression2 ++
    expression2codes expression3
expression2codes (UnaryMinus ident expression) =
620
    Symbol (idName ident) : expression2codes expression
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
expression2codes (Apply expression1 expression2) =
    expression2codes expression1 ++ expression2codes expression2
expression2codes (InfixApply expression1 infixOp expression2) =
    expression2codes expression1 ++ infixOp2codes infixOp ++ expression2codes expression2
expression2codes (LeftSection expression infixOp) =
    expression2codes expression ++ infixOp2codes infixOp
expression2codes (RightSection infixOp expression) =
    infixOp2codes infixOp ++ expression2codes expression
expression2codes (Lambda _ constrTerms expression) =
    concatMap constrTerm2codes constrTerms ++ expression2codes expression
expression2codes (Let decls expression) =
    concatMap decl2codes decls ++ expression2codes expression
expression2codes (Do statements expression) =
    concatMap statement2codes statements ++ expression2codes expression
expression2codes (IfThenElse _ expression1 expression2 expression3) =
    expression2codes expression1 ++ expression2codes expression2 ++ expression2codes expression3
637
expression2codes (Case _ _ expression alts) =
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
638
    expression2codes expression ++ concatMap alt2codes alts
639
expression2codes _ = internalError "SyntaxColoring.expression2codes: no pattern match"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
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

infixOp2codes :: InfixOp -> [Code]
infixOp2codes (InfixOp qualIdent) = [Function InfixFunction qualIdent]
infixOp2codes (InfixConstr qualIdent) = [ConstructorName OtherConstrKind qualIdent]


statement2codes :: Statement -> [Code]
statement2codes (StmtExpr _ expression) =
    expression2codes expression
statement2codes (StmtDecl decls) =
    concatMap decl2codes decls
statement2codes (StmtBind _ constrTerm expression) =
     constrTerm2codes constrTerm ++ expression2codes expression


alt2codes :: Alt -> [Code]
alt2codes (Alt _ constrTerm rhs) =
    constrTerm2codes constrTerm ++ rhs2codes rhs

constrDecl2codes :: ConstrDecl -> [Code]
constrDecl2codes (ConstrDecl _ _ ident typeExprs) =
    ConstructorName ConstrDecla (qualify ident) : concatMap typeExpr2codes typeExprs
constrDecl2codes (ConOpDecl _ _ typeExpr1 ident typeExpr2) =
    typeExpr2codes typeExpr1 ++ [ConstructorName ConstrDecla $ qualify ident] ++ typeExpr2codes typeExpr2


importSpec2codes :: ModuleIdent -> ImportSpec -> [Code]
importSpec2codes moduleIdent (Importing _ imports) = concatMap (import2codes moduleIdent) imports
importSpec2codes moduleIdent (Hiding _ imports) = concatMap (import2codes moduleIdent) imports

import2codes :: ModuleIdent -> Import -> [Code]
import2codes moduleIdent (Import ident) =
     [Function OtherFunctionKind $ qualifyWith moduleIdent ident]
import2codes moduleIdent (ImportTypeWith ident idents) =
     ConstructorName OtherConstrKind (qualifyWith moduleIdent ident) :
     map (Function OtherFunctionKind . qualifyWith moduleIdent) idents
import2codes moduleIdent (ImportTypeAll  ident) =
     [ConstructorName OtherConstrKind $ qualifyWith moduleIdent ident]

typeExpr2codes :: TypeExpr -> [Code]
typeExpr2codes (ConstructorType qualIdent typeExprs) =
    TypeConstructor TypeUse qualIdent : concatMap typeExpr2codes typeExprs
typeExpr2codes (VariableType ident) =
    [Identifier IdOccur (qualify ident)]
typeExpr2codes (TupleType typeExprs) =
    concatMap typeExpr2codes typeExprs
typeExpr2codes (ListType typeExpr) =
    typeExpr2codes typeExpr
typeExpr2codes (ArrowType typeExpr1 typeExpr2) =
    typeExpr2codes typeExpr1 ++ typeExpr2codes typeExpr2
690
typeExpr2codes (RecordType _ _) = internalError "SyntaxColoring.typeExpr2codes: Record pattern"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714

-- TOKEN TO STRING ------------------------------------------------------------
token2string :: Token -> [Char]
token2string (Token Id a) = attributes2string a
token2string (Token QId a) = attributes2string a
token2string (Token Sym a) = attributes2string a
token2string (Token QSym a) = attributes2string a
token2string (Token IntTok a) = attributes2string a
token2string (Token FloatTok a) = attributes2string a
token2string (Token CharTok a) = attributes2string a
token2string (Token StringTok a) = attributes2string a
token2string (Token LeftParen _) = "("
token2string (Token RightParen _) = ")"
token2string (Token Semicolon _) = ";"
token2string (Token LeftBrace _) = "{"
token2string (Token RightBrace _) = "}"
token2string (Token LeftBracket _) = "["
token2string (Token RightBracket _) = "]"
token2string (Token Comma _) = ","
token2string (Token Underscore _) = "_"
token2string (Token Backquote _) = "`"
token2string (Token VSemicolon _) = ""
token2string (Token VRightBrace _) = ""
token2string (Token At _) = "@"
715
token2string (Token Colon _) = ":"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
716
717
718
719
720
721
722
723
token2string (Token DotDot _) = ".."
token2string (Token DoubleColon _) = "::"
token2string (Token Equals _) = "="
token2string (Token Backslash _) = "\\"
token2string (Token Bar _) = "|"
token2string (Token LeftArrow _) = "<-"
token2string (Token RightArrow _) = "->"
token2string (Token Tilde _) = "~"
724
725
726
token2string (Token SymDot _) = "."
token2string (Token SymMinus _) = "-"
token2string (Token SymMinusDot _) = "-."
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
727
728
729
730
731
token2string (Token KW_case _) = "case"
token2string (Token KW_data _) = "data"
token2string (Token KW_do _) = "do"
token2string (Token KW_else _) = "else"
token2string (Token KW_external _) = "external"
732
token2string (Token KW_fcase _) = "fcase"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
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
token2string (Token KW_free _) = "free"
token2string (Token KW_if _) = "if"
token2string (Token KW_import _) = "import"
token2string (Token KW_in _) = "in"
token2string (Token KW_infix _) = "infix"
token2string (Token KW_infixl _) = "infixl"
token2string (Token KW_infixr _) = "infixr"
token2string (Token KW_let _) = "let"
token2string (Token KW_module _) = "module"
token2string (Token KW_newtype _) = "newtype"
token2string (Token KW_of _) = "of"
token2string (Token KW_then _) = "then"
token2string (Token KW_type _) = "type"
token2string (Token KW_where _) = "where"
token2string (Token Id_as _) = "as"
token2string (Token Id_ccall _) = "ccall"
token2string (Token Id_forall _) = "forall"
token2string (Token Id_hiding _) = "hiding"
token2string (Token Id_interface _) = "interface"
token2string (Token Id_primitive _) = "primitive"
token2string (Token Id_qualified _) = "qualified"
token2string (Token EOF _) = ""
token2string (Token LineComment (StringAttributes sv _)) = sv
token2string (Token LineComment a) = attributes2string a
token2string (Token NestedComment (StringAttributes sv _)) = sv
token2string (Token NestedComment a) = attributes2string a
token2string (Token LeftBraceSemicolon _) = "{;"
760
761
token2string (Token Bind _) = ":="
token2string (Token Select _) = ":>"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
762
763

attributes2string :: Attributes -> [Char]
764
765
766
767
attributes2string NoAttributes            = ""
attributes2string (CharAttributes   cv _) = showCh cv
attributes2string (IntAttributes    iv _) = show iv
attributes2string (FloatAttributes  fv _) = show fv
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
768
attributes2string (StringAttributes sv _) = showSt sv
769
attributes2string (IdentAttributes mid i) = intercalate "." $ mid ++ [i]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791

showCh :: Char -> [Char]
showCh c
   | c == '\\' = "'\\\\'"
   | elem c ('\127' : ['\001' .. '\031']) = show c
   | otherwise = toString c
  where
    toString c' = '\'' : c' : "'"

showSt :: [Char] -> [Char]
showSt = addQuotes . concatMap toGoodChar
   where
      addQuotes x = "\"" ++ x ++ "\""

toGoodChar :: Char -> [Char]
toGoodChar c
   | c == '\\' = "\\\\"
   | elem c ('\127' : ['\001' .. '\031']) = justShow c
   | c == '"' = "\\\""
   | otherwise = c : ""
 where
     justShow = init . tail . show