/
Interface.hs
423 lines (356 loc) · 15.7 KB
/
Interface.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
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -Wno-orphans #-}
{-# OPTIONS_GHC -Wwarn=deprecations #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
{-# OPTIONS_GHC -Wno-x-partial #-}
module Language.Haskell.Liquid.GHC.Interface (
-- * Printer
pprintCBs
-- * predicates
-- , isExportedVar
-- , exportedVars
-- * Internal exports (provisional)
, extractSpecComments
, extractSpecQuotes'
, makeLogicMap
, classCons
, derivedVars
, importVars
, allImports
, qualifiedImports
, modSummaryHsFile
, makeFamInstEnv
, parseSpecFile
, clearSpec
, checkFilePragmas
, keepRawTokenStream
, ignoreInline
, lookupTyThings
, availableTyCons
, availableVars
, updLiftedSpec
) where
import Prelude hiding (error)
import Liquid.GHC.API as Ghc hiding ( text
, (<+>)
, panic
, vcat
, showPpr
, mkStableModule
, Located
)
import qualified Liquid.GHC.API as Ghc
import Control.Exception
import Control.Monad
import Control.Monad.Trans.Maybe
import Data.Data
import Data.List hiding (intersperse)
import Data.Maybe
import Data.Generics.Aliases (mkT)
import Data.Generics.Schemes (everywhere)
import qualified Data.HashSet as S
import System.IO
import Text.Megaparsec.Error
import Text.PrettyPrint.HughesPJ hiding (first, (<>))
import Language.Fixpoint.Types hiding (err, panic, Error, Result, Expr)
import qualified Language.Fixpoint.Misc as Misc
import qualified Language.Haskell.Liquid.GHC.CoreToLogic as CoreToLogic
import Language.Haskell.Liquid.GHC.Misc
import Language.Haskell.Liquid.GHC.Types (MGIModGuts(..))
import Language.Haskell.Liquid.GHC.Play
import Language.Haskell.Liquid.WiredIn (isDerivedInstance)
import qualified Language.Haskell.Liquid.Measure as Ms
import qualified Language.Haskell.Liquid.Misc as Misc
import Language.Haskell.Liquid.Parse
import Language.Haskell.Liquid.Types hiding (Spec)
-- import Language.Haskell.Liquid.Types.PrettyPrint
-- import Language.Haskell.Liquid.Types.Visitors
import Language.Haskell.Liquid.UX.QuasiQuoter
import Language.Haskell.Liquid.UX.Tidy
import qualified Debug.Trace as Debug
--------------------------------------------------------------------------------
-- | Extract Ids ---------------------------------------------------------------
--------------------------------------------------------------------------------
classCons :: Maybe [ClsInst] -> [Id]
classCons Nothing = []
classCons (Just cs) = concatMap (dataConImplicitIds . head . tyConDataCons . classTyCon . is_cls) cs
derivedVars :: Config -> MGIModGuts -> [Var]
derivedVars cfg mg = concatMap (dFunIdVars cbs . is_dfun) derInsts
where
derInsts
| checkDer = insts
| otherwise = filter isDerivedInstance insts
insts = mgClsInstances mg
checkDer = checkDerived cfg
cbs = mgi_binds mg
mgClsInstances :: MGIModGuts -> [ClsInst]
mgClsInstances = fromMaybe [] . mgi_cls_inst
dFunIdVars :: CoreProgram -> DFunId -> [Id]
dFunIdVars cbs fd = notracepp msg $ concatMap bindersOf cbs' ++ deps
where
msg = "DERIVED-VARS-OF: " ++ showpp fd
cbs' = filter f cbs
f (NonRec x _) = eqFd x
f (Rec xes) = any eqFd (fst <$> xes)
eqFd x = varName x == varName fd
deps = concatMap unfoldDep unfolds
unfolds = realUnfoldingInfo . idInfo <$> concatMap bindersOf cbs'
unfoldDep :: Unfolding -> [Id]
unfoldDep (DFunUnfolding _ _ e) = concatMap exprDep e
unfoldDep CoreUnfolding {uf_tmpl = e} = exprDep e
unfoldDep _ = []
exprDep :: CoreExpr -> [Id]
exprDep = freeVars S.empty
importVars :: CoreProgram -> [Id]
importVars = freeVars S.empty
_definedVars :: CoreProgram -> [Id]
_definedVars = concatMap defs
where
defs (NonRec x _) = [x]
defs (Rec xes) = map fst xes
--------------------------------------------------------------------------------
-- | Per-Module Pipeline -------------------------------------------------------
--------------------------------------------------------------------------------
updLiftedSpec :: Ms.BareSpec -> Maybe Ms.BareSpec -> Ms.BareSpec
updLiftedSpec s1 Nothing = s1
updLiftedSpec s1 (Just s2) = clearSpec s1 `mappend` s2
clearSpec :: Ms.BareSpec -> Ms.BareSpec
clearSpec s = s { sigs = [], asmSigs = [], aliases = [], ealiases = [], qualifiers = [], dataDecls = [] }
keepRawTokenStream :: ModSummary -> ModSummary
keepRawTokenStream modSummary = modSummary
{ ms_hspp_opts = ms_hspp_opts modSummary `gopt_set` Opt_KeepRawTokenStream }
_impThings :: [Var] -> [TyThing] -> [TyThing]
_impThings vars = filter ok
where
vs = S.fromList vars
ok (AnId x) = S.member x vs
ok _ = True
allImports :: [LImportDecl GhcRn] -> S.HashSet Symbol
allImports = \case
[]-> Debug.trace "WARNING: Missing RenamedSource" mempty
imps -> S.fromList (symbol . unLoc . ideclName . unLoc <$> imps)
qualifiedImports :: [LImportDecl GhcRn] -> QImports
qualifiedImports = \case
[] -> Debug.trace "WARNING: Missing RenamedSource" (qImports mempty)
imps -> qImports [ (qn, n) | i <- imps
, let decl = unLoc i
, let m = unLoc (ideclName decl)
, qm <- maybeToList (unLoc <$> ideclAs decl)
, let [n,qn] = symbol <$> [m, qm]
]
qImports :: [(Symbol, Symbol)] -> QImports
qImports qns = QImports
{ qiNames = Misc.group qns
, qiModules = S.fromList (snd <$> qns)
}
---------------------------------------------------------------------------------------
-- | @lookupTyThings@ grabs all the @Name@s and associated @TyThing@ known to GHC
-- for this module; we will use this to create our name-resolution environment
-- (see `Bare.Resolve`)
---------------------------------------------------------------------------------------
lookupTyThings :: HscEnv -> TcGblEnv -> IO [(Name, Maybe TyThing)]
lookupTyThings hscEnv tcGblEnv = forM names (lookupTyThing hscEnv tcGblEnv)
where
names :: [Ghc.Name]
names = liftM2 (++)
(fmap Ghc.greName . Ghc.globalRdrEnvElts . tcg_rdr_env)
(fmap is_dfun_name . tcg_insts) tcGblEnv
-- | Lookup a single 'Name' in the GHC environment, yielding back the 'Name' alongside the 'TyThing',
-- if one is found.
lookupTyThing :: HscEnv -> TcGblEnv -> Name -> IO (Name, Maybe TyThing)
lookupTyThing hscEnv tcGblEnv n = do
mty <- runMaybeT $
MaybeT (Ghc.hscTcRcLookupName hscEnv n)
`mplus`
MaybeT (
do mi <- moduleInfoTc hscEnv tcGblEnv
modInfoLookupNameIO hscEnv mi n
)
return (n, mty)
availableTyThings :: HscEnv -> TcGblEnv -> [AvailInfo] -> IO [TyThing]
availableTyThings hscEnv tcGblEnv avails =
fmap catMaybes $
mapM (fmap snd . lookupTyThing hscEnv tcGblEnv) $
availableNames avails
-- | Returns all the available (i.e. exported) 'TyCon's (type constructors) for the input 'Module'.
availableTyCons :: HscEnv -> TcGblEnv -> [AvailInfo] -> IO [Ghc.TyCon]
availableTyCons hscEnv tcGblEnv avails =
fmap (\things -> [tyCon | (ATyCon tyCon) <- things]) (availableTyThings hscEnv tcGblEnv avails)
-- | Returns all the available (i.e. exported) 'Var's for the input 'Module'.
availableVars :: HscEnv -> TcGblEnv -> [AvailInfo] -> IO [Ghc.Var]
availableVars hscEnv tcGblEnv avails =
fmap (\things -> [var | (AnId var) <- things]) (availableTyThings hscEnv tcGblEnv avails)
availableNames :: [AvailInfo] -> [Name]
availableNames =
concatMap $ \case
Avail n -> [n]
AvailTC n ns -> n : ns
_dumpTypeEnv :: TypecheckedModule -> IO ()
_dumpTypeEnv tm = do
print ("DUMP-TYPE-ENV" :: String)
print (showpp <$> tcmTyThings tm)
tcmTyThings :: TypecheckedModule -> Maybe [Name]
tcmTyThings
=
-- typeEnvElts
-- . tcg_type_env . fst
-- . md_types . snd
-- . tm_internals_
modInfoTopLevelScope
. tm_checked_module_info
modSummaryHsFile :: ModSummary -> FilePath
modSummaryHsFile modSummary =
fromMaybe
(panic Nothing $
"modSummaryHsFile: missing .hs file for " ++
showPpr (ms_mod modSummary))
(ml_hs_file $ ms_location modSummary)
checkFilePragmas :: [Located String] -> IO ()
checkFilePragmas = Misc.applyNonNull (return ()) throw . mapMaybe err
where
err pragma
| check (val pragma) = Just (ErrFilePragma $ fSrcSpan pragma :: Error)
| otherwise = Nothing
check pragma = any (`isPrefixOf` pragma) bad
bad =
[ "-i", "--idirs"
, "-g", "--ghc-option"
, "--c-files", "--cfiles"
]
--------------------------------------------------------------------------------
-- | Family instance information
--------------------------------------------------------------------------------
makeFamInstEnv :: [FamInst] -> ([Ghc.TyCon], [(Symbol, DataCon)])
makeFamInstEnv famInsts =
let fiTcs = [ tc | FamInst { fi_flavor = DataFamilyInst tc } <- famInsts ]
fiDcs = [ (symbol d, d) | tc <- fiTcs, d <- tyConDataCons tc ]
in (fiTcs, fiDcs)
--------------------------------------------------------------------------------
-- | Extract Specifications from GHC -------------------------------------------
--------------------------------------------------------------------------------
extractSpecComments :: ParsedModule -> [(Maybe RealSrcLoc, String)]
extractSpecComments = mapMaybe extractSpecComment . apiComments
-- | 'extractSpecComment' pulls out the specification part from a full comment
-- string, i.e. if the string is of the form:
-- 1. '{-@ S @-}' then it returns the substring 'S',
-- 2. '{-@ ... -}' then it throws a malformed SPECIFICATION ERROR, and
-- 3. Otherwise it is just treated as a plain comment so we return Nothing.
extractSpecComment :: Ghc.Located ApiComment -> Maybe (Maybe RealSrcLoc, String)
extractSpecComment (Ghc.L sp (ApiBlockComment txt))
| isPrefixOf "{-@" txt && isSuffixOf "@-}" txt -- valid specification
= Just (offsetPos, take (length txt - 6) $ drop 3 txt)
| isPrefixOf "{-@" txt -- invalid specification
= uError $ ErrParseAnn sp "A valid specification must have a closing '@-}'."
where
offsetPos = offsetRealSrcLoc . realSrcSpanStart <$> srcSpanToRealSrcSpan sp
offsetRealSrcLoc s =
mkRealSrcLoc (srcLocFile s) (srcLocLine s) (srcLocCol s + 3)
extractSpecComment _ = Nothing
extractSpecQuotes' :: (a -> Module) -> (a -> [Annotation]) -> a -> [BPspec]
extractSpecQuotes' thisModule getAnns a = mapMaybe extractSpecQuote anns
where
anns = map ann_value $
filter (isOurModTarget . ann_target) $
getAnns a
isOurModTarget (ModuleTarget mod1) = mod1 == thisModule a
isOurModTarget _ = False
extractSpecQuote :: AnnPayload -> Maybe BPspec
extractSpecQuote payload =
case Ghc.fromSerialized Ghc.deserializeWithData payload of
Nothing -> Nothing
Just qt -> Just $ refreshSymbols $ liquidQuoteSpec qt
refreshSymbols :: Data a => a -> a
refreshSymbols = everywhere (mkT refreshSymbol)
refreshSymbol :: Symbol -> Symbol
refreshSymbol = symbol . symbolText
--------------------------------------------------------------------------------
-- | Finding & Parsing Files ---------------------------------------------------
--------------------------------------------------------------------------------
-- | Parse a spec file by path.
--
-- On a parse error, we fail.
--
-- TODO, Andres: It would be better to fail more systematically, but currently we
-- seem to have an option between throwing an error which will be reported badly,
-- or printing the error ourselves.
--
parseSpecFile :: FilePath -> IO (ModName, Ms.BareSpec)
parseSpecFile file = do
contents <- Misc.sayReadFile file
case specSpecificationP file contents of
Left peb -> do
hPutStrLn stderr (errorBundlePretty peb)
panic Nothing "parsing spec file failed"
Right x -> pure x
--------------------------------------------------------------------------------
-- Assemble Information for Spec Extraction ------------------------------------
--------------------------------------------------------------------------------
makeLogicMap :: IO LogicMap
makeLogicMap = do
case parseSymbolToLogic "CoreToLogic.coreToLogic" CoreToLogic.coreToLogic of
Left peb -> do
hPutStrLn stderr (errorBundlePretty peb)
panic Nothing "makeLogicMap failed"
Right lm -> return (lm <> listLMap)
listLMap :: LogicMap -- TODO-REBARE: move to wiredIn
listLMap = toLogicMap [ (dummyLoc nilName , [] , hNil)
, (dummyLoc consName, [x, xs], hCons (EVar <$> [x, xs])) ]
where
x = "x"
xs = "xs"
hNil = mkEApp (dcSym Ghc.nilDataCon ) []
hCons = mkEApp (dcSym Ghc.consDataCon)
dcSym = dummyLoc . dropModuleUnique . symbol
--------------------------------------------------------------------------------
-- | Pretty Printing -----------------------------------------------------------
--------------------------------------------------------------------------------
instance PPrint TargetSpec where
pprintTidy k spec = vcat
[ "******* Target Variables ********************"
, pprintTidy k $ gsTgtVars (gsVars spec)
, "******* Type Signatures *********************"
, pprintLongList k (gsTySigs (gsSig spec))
, "******* Assumed Type Signatures *************"
, pprintLongList k (gsAsmSigs (gsSig spec))
, "******* DataCon Specifications (Measure) ****"
, pprintLongList k (gsCtors (gsData spec))
, "******* Measure Specifications **************"
, pprintLongList k (gsMeas (gsData spec)) ]
instance PPrint TargetInfo where
pprintTidy k info = vcat
[ -- "*************** Imports *********************"
-- , intersperse comma $ text <$> imports info
-- , "*************** Includes ********************"
-- , intersperse comma $ text <$> includes info
"*************** Imported Variables **********"
, pprDoc $ _giImpVars (fromTargetSrc $ giSrc info)
, "*************** Defined Variables ***********"
, pprDoc $ _giDefVars (fromTargetSrc $ giSrc info)
, "*************** Specification ***************"
, pprintTidy k $ giSpec info
, "*************** Core Bindings ***************"
, pprintCBs $ _giCbs (fromTargetSrc $ giSrc info) ]
pprintCBs :: [CoreBind] -> Doc
pprintCBs = pprDoc . tidyCBs
-- To print verbosely
-- = text . O.showSDocDebug unsafeGlobalDynFlags . O.ppr . tidyCBs
instance Show TargetInfo where
show = showpp
instance PPrint TargetVars where
pprintTidy _ AllVars = text "All Variables"
pprintTidy k (Only vs) = text "Only Variables: " <+> pprintTidy k vs
------------------------------------------------------------------------
-- Dealing with Errors ---------------------------------------------------
------------------------------------------------------------------------
instance Result SourceError where
result e = Crash ((, Nothing) <$> sourceErrors "" e) "Invalid Source"