SyntaxColoring.hs 29.2 KB
Newer Older
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
1
2
3
module Html.SyntaxColoring
  ( Program, Code (..), TypeKind (..), ConstructorKind (..)
  , IdentifierKind (..), FunctionKind (..)
4
  , genProgram, code2string, getQualIdent
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
5
6
7
8
  ) 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
Björn Peemöller 's avatar
Björn Peemöller committed
16
import Curry.Syntax hiding (isFunctionDecl)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
17

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
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
55
56
  | TypeExport
    deriving Show
57
58
59
60
61

data ConstructorKind
  = ConstrPattern
  | ConstrCall
  | ConstrDecla
62
63
  | OtherConstrKind
    deriving Show
64
65
66
67

data IdentifierKind
  = IdDecl
  | IdOccur
68
69
  | UnknownId
    deriving Show
70
71
72
73
74
75

data FunctionKind
  = InfixFunction
  | TypSig
  | FunDecl
  | FunctionCall
76
77
  | OtherFunctionKind
    deriving Show
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
78

79
--- @param src
80
81
--- @param list with parse-Results with descending quality,
---        e.g. [typingParse, fullParse, parse]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
82
83
--- @param lex-Result
--- @return program
84
genProgram :: String -> [MessageM Module] -> MessageM [(Position, Token)] -> Program
85
86
genProgram src parseResults lexed = case runMsg lexed of
  Left e -> buildMessagesIntoPlainText [e] src
Björn Peemöller 's avatar
Björn Peemöller committed
87
  Right (posNtokList, mess) ->
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
88
89
90
91
92
93
    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 code
94
--- @return qid if available
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
95
getQualIdent :: Code -> Maybe QualIdent
96
97
98
99
100
getQualIdent (ConstructorName _ qid) = Just qid
getQualIdent (Function        _ qid) = Just qid
getQualIdent (Identifier      _ qid) = Just qid
getQualIdent (TypeConstructor _ qid) = Just qid
getQualIdent  _                      = Nothing
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
101
102
103

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

104
105
106
setMessagePosition :: Message -> Message
setMessagePosition m@(Message (Just p) _) = trace'' ("pos:" ++ show p ++ ":" ++ show m) m
setMessagePosition (Message _ m) =
107
        let mes@(Message pos _) =  (Message (getPositionFromString $ show m) m) in
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
108
109
110
        trace'' ("pos:" ++ show pos ++ ":" ++ show mes) mes

getPositionFromString :: String -> Maybe Position
111
getPositionFromString msg =
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
112
113
114
115
     if l > 0 && c > 0
          then Just Position{file=f,line=l,column=c,astRef=noRef}
          else Nothing
  where
116
117
118
      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
119
120
121
122
123
124
125
126
127
128
129


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
130
flatCode code                 = code
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
131
132
133

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

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

138
139
lessMessage :: Message -> Message -> Bool
lessMessage (Message mPos1 _) (Message mPos2 _) = mPos1 < mPos2
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
140

141
nubMessages :: [Message] -> [Message]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
142
143
nubMessages = nubBy eqMessage

144
eqMessage :: Message -> Message -> Bool
145
eqMessage (Message p1 s1) (Message p2 s2) = (p1 == p2) && (show s1 == show s2)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
146

147
prepareMessages :: [Message] -> [Message]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
148
149
150
prepareMessages = qsort lessMessage . map setMessagePosition . nubMessages


151
buildMessagesIntoPlainText :: [Message] -> String -> Program
152
153
buildMessagesIntoPlainText messages src =
  buildMessagesIntoPlainText' messages (lines src) [] 1
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
154
 where
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
  buildMessagesIntoPlainText' :: [Message] -> [String] -> [String] -> Int -> Program
  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
    isLeq (Message (Just p) _) = line p <= ln
    isLeq _ = True
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
173
174

--- @param parse-Modules  [typingParse,fullParse,parse]
175
catIdentifiers :: [MessageM Module] -> ([(ModuleIdent, ModuleIdent)],[Code])
Björn Peemöller 's avatar
Björn Peemöller committed
176
catIdentifiers = catIds . map fst . rights_sc . map runMsg
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
177
178
179
180
181
182
183
184
185
    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]
186
rights_sc es = [ x | Right x <- es]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
187
188
189
190

--- @param parse-Module
--- @param Maybe betterParse-Module
catIdentifiers' :: Module -> Maybe Module -> ([(ModuleIdent,ModuleIdent)],[Code])
191
catIdentifiers' (Module _ mid maybeExportSpec is decls)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
192
                Nothing =
193
      let impCodes = concatMap importDecl2codes (qsort lessImportDecl is)
194
          codes = (concatMap decl2codes (qsort lessDecl decls))
195
196
      in (concatMap renamedImports is,
      ModuleName mid :
197
       maybe [] exportSpec2codes maybeExportSpec ++ impCodes ++ codes)
198
199
catIdentifiers' (Module _ mid maybeExportSpec1 _ _)
                (Just (Module _ _ maybeExportSpec2 is decls)) =
200
      let impCodes = concatMap importDecl2codes (qsort lessImportDecl is)
201
          codes = (concatMap decl2codes (qsort lessDecl decls))
202
      in (concatMap renamedImports is,
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
203
      replaceFunctionCalls $
204
205
        map (addModuleIdent mid)
          ([ModuleName mid] ++
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
206
207
208
           mergeExports2codes
              (maybe [] (\(Exporting _ i) -> i)  maybeExportSpec1)
              (maybe [] (\(Exporting _ i) -> i)  maybeExportSpec2) ++
209
           impCodes ++ codes))
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
210

211
renamedImports :: ImportDecl -> [(ModuleIdent, ModuleIdent)]
212
renamedImports (ImportDecl _ oldName _ (Just newName) _) = [(oldName,newName)]
213
renamedImports _                                         = []
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
214
215

replaceFunctionCalls :: [Code] -> [Code]
216
217
replaceFunctionCalls codes = map (idOccur2functionCall qids) codes
   where qids = findFunctionDecls codes
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
218
219
220


findFunctionDecls :: [Code] -> [QualIdent]
221
findFunctionDecls = mapMaybe getQualIdent . filter isFunctionDecl . map flatCode
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
222

223
224
225
isFunctionDecl :: Code -> Bool
isFunctionDecl (Function FunDecl _) = True
isFunctionDecl _                    = False
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
226
227

idOccur2functionCall :: [QualIdent] -> Code -> Code
228
229
230
231
232
233
idOccur2functionCall qids ide@(Identifier IdOccur qid)
  | isQualified qid = Function FunctionCall qid
  | elem qid qids   = Function FunctionCall qid
  | otherwise       = ide
idOccur2functionCall qids (CodeWarning mess code) =
  CodeWarning mess (idOccur2functionCall qids code)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
234
235
236
237
idOccur2functionCall _ code = code


addModuleIdent :: ModuleIdent -> Code -> Code
238
239
240
241
242
243
244
245
246
247
248
addModuleIdent mid c@(Function x qid)
  | hasGlobalScope (unqualify qid) = Function x (qualQualify mid qid)
  | otherwise                      = c
addModuleIdent mid cn@(ConstructorName x qid)
  | not $ isQualified qid = ConstructorName x (qualQualify mid qid)
  | otherwise = cn
addModuleIdent mid tc@(TypeConstructor TypeDecla qid)
  | not $ isQualified qid = TypeConstructor TypeDecla (qualQualify mid qid)
  | otherwise = tc
addModuleIdent mid (CodeWarning mess code) =
    CodeWarning mess (addModuleIdent mid code)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
249
250
addModuleIdent _ c = c

251
mergeMessages' :: [Message] -> [(Position,Token)] -> [([Message],Position,Token)]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
252
253
mergeMessages' _ [] = []
mergeMessages' [] ((p,t):ps) = ([],p,t) : mergeMessages' [] ps
254
mergeMessages' mss@(m@(Message mPos x):ms) ((p,t):ps)
255
    | 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
256
257
    | otherwise = ([],p,t) : mergeMessages' mss ps

258
tokenNcodes2codes :: [(ModuleIdent,ModuleIdent)] -> Int -> Int -> [([Message],Position,Token)] -> [Code] -> [(Int,Int,Code)]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
259
260
tokenNcodes2codes _ _ _ [] _ = []
tokenNcodes2codes nameList currLine currCol toks@((messages,Position{line=row,column=col},token):ts) codes
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
  | 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))
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
303
  where
304
      tokenStr = showToken token
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
305
306
307
308
309
310
311
312
313
314
      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)
315
tokenNcodes2codes _ _ _ _ _ = internalError "SyntaxColoring.tokenNcodes2codes: no pattern match"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
316
317
318
319
320


renameModuleIdents :: [(ModuleIdent,ModuleIdent)] -> Code -> Code
renameModuleIdents nameList c =
    case c of
321
322
        Function x qid -> Function x (rename qid (qidModule qid))
        Identifier x qid -> Identifier x (rename qid (qidModule qid))
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
323
324
325
        _ -> c
  where
    rename x (Nothing) = x
326
    rename x (Just m) = maybe x (\ m' -> qualifyWith m' (qidIdent x)) (lookup m nameList)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
327
328

codeQualifiers :: Code -> [String]
329
codeQualifiers = maybe [] midQualifiers . getModuleIdent
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
330
331

getModuleIdent :: Code -> Maybe ModuleIdent
332
333
334
335
336
337
getModuleIdent (ConstructorName _ qid) = qidModule qid
getModuleIdent (Function        _ qid) = qidModule qid
getModuleIdent (ModuleName        mid) = Just mid
getModuleIdent (Identifier      _ qid) = qidModule qid
getModuleIdent (TypeConstructor _ qid) = qidModule qid
getModuleIdent _                      = Nothing
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
338
339

code2string :: Code -> String
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
code2string (Keyword           s) = s
code2string (Space               i) = concat (replicate i " ")
code2string NewLine                 = "\n"
code2string (ConstructorName _ qid) = idName $ unqualify qid
code2string (TypeConstructor _ qid) = idName $ unqualify qid
code2string (Function        _ qid) = idName $ unqualify qid
code2string (ModuleName        mid) = moduleName mid
code2string (Commentary        s) = s
code2string (NumberCode        s) = s
code2string (StringCode        s) = s
code2string (CharCode          s) = s
code2string (Symbol            s) = s
code2string (Identifier      _ qid) = idName $ unqualify qid
code2string (CodeWarning       _ c) = code2string c
code2string (NotParsed         s) = s
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
355
356

code2qualString :: Code -> String
357
358
359
360
code2qualString (ConstructorName _ qid) = qualName qid
code2qualString (Function _ qid) = qualName qid
code2qualString (Identifier _ qid) = qualName qid
code2qualString (TypeConstructor _ qid) = qualName qid
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
361
362
363
364
code2qualString x = code2string x

token2code :: Token -> Code
token2code tok@(Token cat _)
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
  | elem cat [IntTok,FloatTok]
        = NumberCode (showToken tok)
  | elem cat [KW_case,KW_data,KW_do,KW_else,KW_external,
              KW_free,KW_if,KW_import,KW_in,KW_infix,KW_infixl,KW_infixr,
              KW_let,KW_module,KW_newtype,KW_of,KW_then,KW_type,
              KW_where,Id_as,Id_ccall,Id_forall,Id_hiding,Id_interface,Id_primitive,
              Id_qualified]
        =  Keyword (showToken tok)
  | elem cat [LeftParen,RightParen,Semicolon,LeftBrace,RightBrace,LeftBracket,
              RightBracket,Comma,Underscore,Backquote,
              At,Colon,DotDot,DoubleColon,Equals,Backslash,Bar,LeftArrow,RightArrow,
              Tilde]
        = Symbol (showToken tok)
  | elem cat [LineComment, NestedComment]
        = Commentary (showToken tok)
  | isTokenIdentifier tok
        = Identifier UnknownId $ qualify $ mkIdent $ showToken tok
  | cat == StringTok
        = StringCode (showToken tok)
  | cat == CharTok
        = CharCode (showToken tok)
  | elem cat [EOF,VSemicolon,VRightBrace] = Space 0
  | otherwise = error "SyntaxColoring.token2code: no pattern match"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
388
389
390

isTokenIdentifier :: Token -> Bool
isTokenIdentifier (Token cat _) =
391
  elem cat [Id, QId, Sym, QSym, SymDot, SymMinus, SymMinusDot]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
392
393
394

-- DECL Position

395
396
397
398
399
400
401
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
402
403
declPos (ForeignDecl      p _ _ _ _) = p
declPos (ExternalDecl     p _      ) = p
404
declPos (PatternDecl      p _ _    ) = p
405
declPos (FreeDecl         p _      ) = p
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
406
407

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

410
411
412
lessImportDecl :: ImportDecl -> ImportDecl -> Bool
lessImportDecl = (<) `on` (\ (ImportDecl p _ _ _ _) -> p)

Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
413
qsort :: (a -> a -> Bool) -> [a] -> [a]
414
415
416
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
417
418
419
420
421


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

exportSpec2codes ::  ExportSpec -> [Code]
422
exportSpec2codes (Exporting _ exports) = concatMap (export2codes []) exports
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
423
424
425
426
427
428
429
430

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

export2codes :: [Export] -> Export -> [Code]
431
export2codes exports (Export qid)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
432
    | length (filter checkDouble exports) /= 1 =
433
       [Identifier UnknownId qid]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
434
435
436
437
    | otherwise =
       let [export] = (filter checkDouble exports) in
       export2c export
  where
438
439
    checkDouble (ExportTypeWith q _) = eqQualIdent qid q
    checkDouble (Export q) = eqQualIdent qid q
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
440
441
442
443
444
445
446
    checkDouble _ = False

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

447
448
    export2c (Export qid1) =
         [Function OtherFunctionKind qid1]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
449
    export2c _ =
450
         [TypeConstructor TypeExport qid]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
451

452
453
454
455
456
457
export2codes _ (ExportTypeWith qid idents) =
     TypeConstructor TypeExport qid : map (Function OtherFunctionKind . qualify) idents
export2codes _ (ExportTypeAll  qid) =
     [TypeConstructor TypeExport qid]
export2codes _ (ExportModule mid) =
     [ModuleName mid]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
458

459
importDecl2codes :: ImportDecl -> [Code]
460
461
importDecl2codes (ImportDecl _ mid _ mModuleIdent importSpec) =
     [ModuleName mid] ++
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
462
     maybe [] ((:[]) . ModuleName) mModuleIdent ++
463
     maybe [] (importSpec2codes mid)  importSpec
464
465

decl2codes :: Decl -> [Code]
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
decl2codes (InfixDecl _ _ _ ops) = map (Function InfixFunction . qualify) ops
decl2codes (DataDecl _ d vs cds) =
     TypeConstructor TypeDecla (qualify d) :
     map (Identifier UnknownId . qualify) vs ++
     concatMap constrDecl2codes cds
decl2codes (NewtypeDecl _ _ _ _) = []
decl2codes (TypeDecl _ t vs ty) =
     TypeConstructor TypeDecla (qualify t) :
     map (Identifier UnknownId . qualify) vs ++
     typeExpr2codes ty
decl2codes (TypeSig _ fs ty) =
     map (Function TypSig . qualify) fs ++ typeExpr2codes ty
decl2codes (FunctionDecl  _ _ eqs) = concatMap equation2codes eqs
decl2codes (ForeignDecl _ _ _ _ _) = []
decl2codes (ExternalDecl     _ fs) = map (Function FunDecl . qualify) fs
decl2codes (PatternDecl   _ p rhs) =  pat2codes p ++ rhs2codes rhs
decl2codes (FreeDecl         _ vs) = map (Identifier IdDecl . qualify) vs
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
483
484

equation2codes :: Equation -> [Code]
485
equation2codes (Equation _ lhs rhs) = lhs2codes lhs ++ rhs2codes rhs
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
486
487

lhs2codes :: Lhs -> [Code]
488
489
490
lhs2codes (FunLhs    f ps) = Function FunDecl (qualify f) : concatMap pat2codes ps
lhs2codes (OpLhs p1 op p2) = pat2codes p1 ++ [Function FunDecl $ qualify op] ++ pat2codes p2
lhs2codes (ApLhs   lhs ps) = lhs2codes lhs ++ concatMap pat2codes ps
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
491
492

rhs2codes :: Rhs -> [Code]
493
494
rhs2codes (SimpleRhs _ e ds) = expr2codes e ++ concatMap decl2codes ds
rhs2codes (GuardedRhs ce ds) = concatMap condExpr2codes ce ++ concatMap decl2codes ds
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
495
496

condExpr2codes :: CondExpr -> [Code]
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
condExpr2codes (CondExpr _ e1 e2) = expr2codes e1 ++ expr2codes e2

pat2codes :: Pattern -> [Code]
pat2codes (LiteralPattern          _) = []
pat2codes (NegativePattern       _ _) = []
pat2codes (VariablePattern         v) = [Identifier IdDecl (qualify v)]
pat2codes (ConstructorPattern qid ps)
  = ConstructorName ConstrPattern qid : concatMap pat2codes ps
pat2codes (InfixPattern    p1 qid p2)
  = pat2codes p1 ++ [ConstructorName ConstrPattern qid] ++ pat2codes p2
pat2codes (ParenPattern            p) = pat2codes p
pat2codes (TuplePattern         _ ps) = concatMap pat2codes ps
pat2codes (ListPattern          _ ps) = concatMap pat2codes ps
pat2codes (AsPattern             v p)
  = Function OtherFunctionKind (qualify v) : pat2codes p
pat2codes (LazyPattern           _ p) = pat2codes p
pat2codes (FunctionPattern    qid ps)
  = Function OtherFunctionKind qid : concatMap pat2codes ps
pat2codes (InfixFuncPattern  p1 f p2)
  = pat2codes p1 ++ [Function InfixFunction f] ++ pat2codes p2
pat2codes (RecordPattern         _ _) =
  internalError "SyntaxColoring.pat2codes: record pattern"

expr2codes :: Expression -> [Code]
expr2codes (Literal               _) = []
expr2codes (Variable            qid) = [Identifier IdOccur qid]
expr2codes (Constructor         qid) = [ConstructorName ConstrCall qid]
expr2codes (Paren                 e) = expr2codes e
expr2codes (Typed              e ty) = expr2codes e ++ typeExpr2codes ty
expr2codes (Tuple              _ es) = concatMap expr2codes es
expr2codes (List               _ es) = concatMap expr2codes es
expr2codes (ListCompr     _ e stmts) = expr2codes e ++ concatMap statement2codes stmts
expr2codes (EnumFrom              e) = expr2codes e
expr2codes (EnumFromThen      e1 e2) = concatMap expr2codes [e1,e2]
expr2codes (EnumFromTo        e1 e2) = concatMap expr2codes [e1,e2]
expr2codes (EnumFromThenTo e1 e2 e3) = concatMap expr2codes [e1,e2,e3]
expr2codes (UnaryMinus      ident e) = Symbol (idName ident) : expr2codes e
expr2codes (Apply             e1 e2) = expr2codes e1 ++ expr2codes e2
expr2codes (InfixApply     e1 op e2) = expr2codes e1 ++ infixOp2codes op ++ expr2codes e2
expr2codes (LeftSection        e op) = expr2codes e ++ infixOp2codes op
expr2codes (RightSection       op e) = infixOp2codes op ++ expr2codes e
expr2codes (Lambda           _ ps e) = concatMap pat2codes ps ++ expr2codes e
expr2codes (Let                ds e) = concatMap decl2codes ds ++ expr2codes e
expr2codes (Do              stmts e) = concatMap statement2codes stmts ++ expr2codes e
expr2codes (IfThenElse   _ e1 e2 e3) = concatMap expr2codes [e1,e2,e3]
expr2codes (Case         _ _ e alts) = expr2codes e ++ concatMap alt2codes alts
expr2codes _ = internalError "SyntaxColoring.expr2codes: no pattern match"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
544
545

infixOp2codes :: InfixOp -> [Code]
546
547
infixOp2codes (InfixOp     qid) = [Function InfixFunction qid]
infixOp2codes (InfixConstr qid) = [ConstructorName OtherConstrKind qid]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
548
549

statement2codes :: Statement -> [Code]
550
551
552
statement2codes (StmtExpr   _ e) = expr2codes e
statement2codes (StmtDecl    ds) = concatMap decl2codes ds
statement2codes (StmtBind _ p e) = pat2codes p ++ expr2codes e
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
553
554

alt2codes :: Alt -> [Code]
555
alt2codes (Alt _ p rhs) = pat2codes p ++ rhs2codes rhs
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
556
557

constrDecl2codes :: ConstrDecl -> [Code]
558
559
560
561
constrDecl2codes (ConstrDecl _ _ c tys)
  = ConstructorName ConstrDecla (qualify c) : concatMap typeExpr2codes tys
constrDecl2codes (ConOpDecl _ _ ty1 op ty2)
  = typeExpr2codes ty1 ++ [ConstructorName ConstrDecla $ qualify op] ++ typeExpr2codes ty2
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
562
563

importSpec2codes :: ModuleIdent -> ImportSpec -> [Code]
564
565
importSpec2codes mid (Importing _ is) = concatMap (import2codes mid) is
importSpec2codes mid (Hiding _ is) = concatMap (import2codes mid) is
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
566
567

import2codes :: ModuleIdent -> Import -> [Code]
568
569
570
571
572
573
574
import2codes mid (Import ident) =
     [Function OtherFunctionKind $ qualifyWith mid ident]
import2codes mid (ImportTypeWith ident idents) =
     ConstructorName OtherConstrKind (qualifyWith mid ident) :
     map (Function OtherFunctionKind . qualifyWith mid) idents
import2codes mid (ImportTypeAll  ident) =
     [ConstructorName OtherConstrKind $ qualifyWith mid ident]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
575
576

typeExpr2codes :: TypeExpr -> [Code]
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
typeExpr2codes (ConstructorType qid tys)
  = TypeConstructor TypeUse qid : concatMap typeExpr2codes tys
typeExpr2codes (VariableType          v) = [Identifier IdOccur (qualify v)]
typeExpr2codes (TupleType           tys) = concatMap typeExpr2codes tys
typeExpr2codes (ListType             ty) = typeExpr2codes ty
typeExpr2codes (ArrowType       ty1 ty2) = concatMap typeExpr2codes [ty1, ty2]
typeExpr2codes (RecordType          _ _) = internalError "SyntaxColoring.typeExpr2codes: Record pattern"

showToken :: Token -> [Char]
showToken (Token Id           a) = showAttr a
showToken (Token QId          a) = showAttr a
showToken (Token Sym          a) = showAttr a
showToken (Token QSym         a) = showAttr a
showToken (Token IntTok       a) = showAttr a
showToken (Token FloatTok     a) = showAttr a
showToken (Token CharTok      a) = showAttr a
showToken (Token StringTok    a) = showAttr a
showToken (Token LeftParen    _) = "("
showToken (Token RightParen   _) = ")"
showToken (Token Semicolon    _) = ";"
showToken (Token LeftBrace    _) = "{"
showToken (Token RightBrace   _) = "}"
showToken (Token LeftBracket  _) = "["
showToken (Token RightBracket _) = "]"
showToken (Token Comma        _) = ","
showToken (Token Underscore   _) = "_"
showToken (Token Backquote    _) = "`"
showToken (Token VSemicolon   _) = ""
showToken (Token LeftBraceSemicolon _) = "{;"
showToken (Token VRightBrace  _) = ""
showToken (Token At           _) = "@"
showToken (Token Colon        _) = ":"
showToken (Token DotDot       _) = ".."
showToken (Token DoubleColon  _) = "::"
showToken (Token Equals       _) = "="
showToken (Token Backslash    _) = "\\"
showToken (Token Bar          _) = "|"
showToken (Token LeftArrow    _) = "<-"
showToken (Token RightArrow   _) = "->"
showToken (Token Tilde        _) = "~"
showToken (Token Bind         _) = ":="
showToken (Token Select       _) = ":>"
showToken (Token SymDot       _) = "."
showToken (Token SymMinus     _) = "-"
showToken (Token SymMinusDot  _) = "-."
showToken (Token KW_case      _) = "case"
showToken (Token KW_data      _) = "data"
showToken (Token KW_do        _) = "do"
showToken (Token KW_else      _) = "else"
showToken (Token KW_external  _) = "external"
showToken (Token KW_fcase     _) = "fcase"
showToken (Token KW_foreign   _) = "foreign"
showToken (Token KW_free      _) = "free"
showToken (Token KW_if        _) = "if"
showToken (Token KW_import    _) = "import"
showToken (Token KW_in        _) = "in"
showToken (Token KW_infix     _) = "infix"
showToken (Token KW_infixl    _) = "infixl"
showToken (Token KW_infixr    _) = "infixr"
showToken (Token KW_let       _) = "let"
showToken (Token KW_module    _) = "module"
showToken (Token KW_newtype   _) = "newtype"
showToken (Token KW_of        _) = "of"
showToken (Token KW_then      _) = "then"
showToken (Token KW_type      _) = "type"
showToken (Token KW_where     _) = "where"
showToken (Token Id_as        _) = "as"
showToken (Token Id_ccall     _) = "ccall"
showToken (Token Id_forall    _) = "forall"
showToken (Token Id_hiding    _) = "hiding"
showToken (Token Id_interface _) = "interface"
showToken (Token Id_primitive _) = "primitive"
showToken (Token Id_qualified _) = "qualified"
showToken (Token EOF          _) = ""
651
652
653
showToken (Token PragmaLanguage _) = "{-# LANGUAGE"
showToken (Token PragmaOptions  a) = "{-# OPTIONS" ++ showAttr a
showToken (Token PragmaEnd      _) = "#-}"
654
655
656
657
658
659
showToken (Token LineComment   (StringAttributes sv _)) = sv
showToken (Token LineComment   a                      ) = showAttr a
showToken (Token NestedComment (StringAttributes sv _)) = sv
showToken (Token NestedComment                       a) = showAttr a

showAttr :: Attributes -> [Char]
660
661
662
663
664
665
666
667
668
669
670
showAttr NoAttributes             = ""
showAttr (CharAttributes    cv _) = showCharacter cv
showAttr (IntAttributes     iv _) = show iv
showAttr (FloatAttributes   fv _) = show fv
showAttr (StringAttributes  sv _) = showSt sv
showAttr (IdentAttributes  mid i) = intercalate "." $ mid ++ [i]
showAttr (OptionsAttributes mt s) = showTool mt ++ ' ' : s

showTool :: Maybe String -> String
showTool Nothing  = ""
showTool (Just t) = '_' : t
671
672
673
674
675
676

showCharacter :: Char -> [Char]
showCharacter c
  | c == '\\'                              = "'\\\\'"
  | c `elem` ('\127' : ['\001' .. '\031']) = show c
  | otherwise                              = ['\'', c, '\'']
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
677
678
679

showSt :: [Char] -> [Char]
showSt = addQuotes . concatMap toGoodChar
680
  where addQuotes x = "\"" ++ x ++ "\""
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
681
682
683

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

{-
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
-}

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

-- --- @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
-- area2codes _ _ _ = internalError "SyntaxColoring.area2codes: no pattern match"