-
Notifications
You must be signed in to change notification settings - Fork 696
/
TargetSelector.hs
2431 lines (2126 loc) · 86.7 KB
/
TargetSelector.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
{-# LANGUAGE CPP, DeriveGeneric, DeriveFunctor,
RecordWildCards, NamedFieldPuns #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.TargetSelector
-- Copyright : (c) Duncan Coutts 2012, 2015, 2016
-- License : BSD-like
--
-- Maintainer : [email protected]
--
-- Handling for user-specified target selectors.
--
-----------------------------------------------------------------------------
module Distribution.Client.TargetSelector (
-- * Target selectors
TargetSelector(..),
TargetImplicitCwd(..),
ComponentKind(..),
ComponentKindFilter,
SubComponentTarget(..),
QualLevel(..),
componentKind,
-- * Reading target selectors
readTargetSelectors,
TargetSelectorProblem(..),
reportTargetSelectorProblems,
showTargetSelector,
TargetString,
showTargetString,
parseTargetString,
-- ** non-IO
readTargetSelectorsWith,
DirActions(..),
defaultDirActions,
) where
import Prelude ()
import Distribution.Client.Compat.Prelude
import Distribution.Package
( Package(..), PackageId, PackageName, packageName )
import Distribution.Types.UnqualComponentName
( UnqualComponentName, mkUnqualComponentName, unUnqualComponentName
, packageNameToUnqualComponentName )
import Distribution.Client.Types
( PackageLocation(..), PackageSpecifier(..) )
import Distribution.Verbosity
import Distribution.PackageDescription
( PackageDescription
, Executable(..)
, TestSuite(..), TestSuiteInterface(..), testModules
, Benchmark(..), BenchmarkInterface(..), benchmarkModules
, BuildInfo(..), explicitLibModules, exeModules )
import Distribution.PackageDescription.Configuration
( flattenPackageDescription )
import Distribution.Solver.Types.SourcePackage
( SourcePackage(..) )
import Distribution.ModuleName
( ModuleName, toFilePath )
import Distribution.Simple.LocalBuildInfo
( Component(..), ComponentName(..)
, pkgComponents, componentName, componentBuildInfo )
import Distribution.Types.ForeignLib
import Distribution.Text
( Text, display, simpleParse )
import Distribution.Simple.Utils
( die', lowercase, ordNub )
import Distribution.Client.Utils
( makeRelativeCanonical )
import Data.Either
( partitionEithers )
import Data.Function
( on )
import Data.List
( stripPrefix, partition, groupBy )
import Data.Ord
( comparing )
import qualified Data.Map.Lazy as Map.Lazy
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Control.Arrow ((&&&))
import Control.Monad
import qualified Distribution.Compat.ReadP as Parse
import Distribution.Compat.ReadP
( (+++), (<++) )
import Distribution.ParseUtils
( readPToMaybe )
import System.FilePath as FilePath
( takeExtension, dropExtension
, splitDirectories, joinPath, splitPath )
import qualified System.Directory as IO
( doesFileExist, doesDirectoryExist, canonicalizePath
, getCurrentDirectory )
import System.FilePath
( (</>), (<.>), normalise, dropTrailingPathSeparator )
import Text.EditDistance
( defaultEditCosts, restrictedDamerauLevenshteinDistance )
-- ------------------------------------------------------------
-- * Target selector terms
-- ------------------------------------------------------------
-- | A target selector is expression selecting a set of components (as targets
-- for a actions like @build@, @run@, @test@ etc). A target selector
-- corresponds to the user syntax for referring to targets on the command line.
--
-- From the users point of view a target can be many things: packages, dirs,
-- component names, files etc. Internally we consider a target to be a specific
-- component (or module\/file within a component), and all the users' notions
-- of targets are just different ways of referring to these component targets.
--
-- So target selectors are expressions in the sense that they are interpreted
-- to refer to one or more components. For example a 'TargetPackage' gets
-- interpreted differently by different commands to refer to all or a subset
-- of components within the package.
--
-- The syntax has lots of optional parts:
--
-- > [ package name | package dir | package .cabal file ]
-- > [ [lib:|exe:] component name ]
-- > [ module name | source file ]
--
data TargetSelector =
-- | One (or more) packages as a whole, or all the components of a
-- particular kind within the package(s).
--
-- These are always packages that are local to the project. In the case
-- that there is more than one, they all share the same directory location.
--
TargetPackage TargetImplicitCwd [PackageId] (Maybe ComponentKindFilter)
-- | A package specified by name. This may refer to @extra-packages@ from
-- the @cabal.project@ file, or a dependency of a known project package or
-- could refer to a package from a hackage archive. It needs further
-- context to resolve to a specific package.
--
| TargetPackageNamed PackageName (Maybe ComponentKindFilter)
-- | All packages, or all components of a particular kind in all packages.
--
| TargetAllPackages (Maybe ComponentKindFilter)
-- | A specific component in a package within the project.
--
| TargetComponent PackageId ComponentName SubComponentTarget
-- | A component in a package, but where it cannot be verified that the
-- package has such a component, or because the package is itself not
-- known.
--
| TargetComponentUnknown PackageName
(Either UnqualComponentName ComponentName)
SubComponentTarget
deriving (Eq, Ord, Show, Generic)
-- | Does this 'TargetPackage' selector arise from syntax referring to a
-- package in the current directory (e.g. @tests@ or no giving no explicit
-- target at all) or does it come from syntax referring to a package name
-- or location.
--
data TargetImplicitCwd = TargetImplicitCwd | TargetExplicitNamed
deriving (Eq, Ord, Show, Generic)
data ComponentKind = LibKind | FLibKind | ExeKind | TestKind | BenchKind
deriving (Eq, Ord, Enum, Show)
type ComponentKindFilter = ComponentKind
-- | Either the component as a whole or detail about a file or module target
-- within a component.
--
data SubComponentTarget =
-- | The component as a whole
WholeComponent
-- | A specific module within a component.
| ModuleTarget ModuleName
-- | A specific file within a component.
| FileTarget FilePath
deriving (Eq, Ord, Show, Generic)
instance Binary SubComponentTarget
-- ------------------------------------------------------------
-- * Top level, do everything
-- ------------------------------------------------------------
-- | Parse a bunch of command line args as 'TargetSelector's, failing with an
-- error if any are unrecognised. The possible target selectors are based on
-- the available packages (and their locations).
--
readTargetSelectors :: [PackageSpecifier (SourcePackage (PackageLocation a))]
-> [String]
-> IO (Either [TargetSelectorProblem] [TargetSelector])
readTargetSelectors = readTargetSelectorsWith defaultDirActions
readTargetSelectorsWith :: (Applicative m, Monad m) => DirActions m
-> [PackageSpecifier (SourcePackage (PackageLocation a))]
-> [String]
-> m (Either [TargetSelectorProblem] [TargetSelector])
readTargetSelectorsWith dirActions@DirActions{..} pkgs targetStrs =
case parseTargetStrings targetStrs of
([], usertargets) -> do
usertargets' <- mapM (getTargetStringFileStatus dirActions) usertargets
knowntargets <- getKnownTargets dirActions pkgs
case resolveTargetSelectors knowntargets usertargets' of
([], btargets) -> return (Right btargets)
(problems, _) -> return (Left problems)
(strs, _) -> return (Left (map TargetSelectorUnrecognised strs))
data DirActions m = DirActions {
doesFileExist :: FilePath -> m Bool,
doesDirectoryExist :: FilePath -> m Bool,
canonicalizePath :: FilePath -> m FilePath,
getCurrentDirectory :: m FilePath
}
defaultDirActions :: DirActions IO
defaultDirActions =
DirActions {
doesFileExist = IO.doesFileExist,
doesDirectoryExist = IO.doesDirectoryExist,
-- Workaround for <https://github.com/haskell/directory/issues/63>
canonicalizePath = IO.canonicalizePath . dropTrailingPathSeparator,
getCurrentDirectory = IO.getCurrentDirectory
}
makeRelativeToCwd :: Applicative m => DirActions m -> FilePath -> m FilePath
makeRelativeToCwd DirActions{..} path =
makeRelativeCanonical <$> canonicalizePath path <*> getCurrentDirectory
-- ------------------------------------------------------------
-- * Parsing target strings
-- ------------------------------------------------------------
-- | The outline parse of a target selector. It takes one of the forms:
--
-- > str1
-- > str1:str2
-- > str1:str2:str3
-- > str1:str2:str3:str4
--
data TargetString =
TargetString1 String
| TargetString2 String String
| TargetString3 String String String
| TargetString4 String String String String
| TargetString5 String String String String String
| TargetString7 String String String String String String String
deriving (Show, Eq)
-- | Parse a bunch of 'TargetString's (purely without throwing exceptions).
--
parseTargetStrings :: [String] -> ([String], [TargetString])
parseTargetStrings =
partitionEithers
. map (\str -> maybe (Left str) Right (parseTargetString str))
parseTargetString :: String -> Maybe TargetString
parseTargetString =
readPToMaybe parseTargetApprox
where
parseTargetApprox :: Parse.ReadP r TargetString
parseTargetApprox =
(do a <- tokenQ
return (TargetString1 a))
+++ (do a <- tokenQ0
_ <- Parse.char ':'
b <- tokenQ
return (TargetString2 a b))
+++ (do a <- tokenQ0
_ <- Parse.char ':'
b <- tokenQ
_ <- Parse.char ':'
c <- tokenQ
return (TargetString3 a b c))
+++ (do a <- tokenQ0
_ <- Parse.char ':'
b <- token
_ <- Parse.char ':'
c <- tokenQ
_ <- Parse.char ':'
d <- tokenQ
return (TargetString4 a b c d))
+++ (do a <- tokenQ0
_ <- Parse.char ':'
b <- token
_ <- Parse.char ':'
c <- tokenQ
_ <- Parse.char ':'
d <- tokenQ
_ <- Parse.char ':'
e <- tokenQ
return (TargetString5 a b c d e))
+++ (do a <- tokenQ0
_ <- Parse.char ':'
b <- token
_ <- Parse.char ':'
c <- tokenQ
_ <- Parse.char ':'
d <- tokenQ
_ <- Parse.char ':'
e <- tokenQ
_ <- Parse.char ':'
f <- tokenQ
_ <- Parse.char ':'
g <- tokenQ
return (TargetString7 a b c d e f g))
token = Parse.munch1 (\x -> not (isSpace x) && x /= ':')
tokenQ = parseHaskellString <++ token
token0 = Parse.munch (\x -> not (isSpace x) && x /= ':')
tokenQ0= parseHaskellString <++ token0
parseHaskellString :: Parse.ReadP r String
parseHaskellString = Parse.readS_to_P reads
-- | Render a 'TargetString' back as the external syntax. This is mainly for
-- error messages.
--
showTargetString :: TargetString -> String
showTargetString = intercalate ":" . components
where
components (TargetString1 s1) = [s1]
components (TargetString2 s1 s2) = [s1,s2]
components (TargetString3 s1 s2 s3) = [s1,s2,s3]
components (TargetString4 s1 s2 s3 s4) = [s1,s2,s3,s4]
components (TargetString5 s1 s2 s3 s4 s5) = [s1,s2,s3,s4,s5]
components (TargetString7 s1 s2 s3 s4 s5 s6 s7) = [s1,s2,s3,s4,s5,s6,s7]
showTargetSelector :: TargetSelector -> String
showTargetSelector ts =
case [ t | ql <- [QL1 .. QLFull]
, t <- renderTargetSelector ql ts ]
of (t':_) -> showTargetString (forgetFileStatus t')
[] -> ""
showTargetSelectorKind :: TargetSelector -> String
showTargetSelectorKind bt = case bt of
TargetPackage TargetExplicitNamed _ Nothing -> "package"
TargetPackage TargetExplicitNamed _ (Just _) -> "package:filter"
TargetPackage TargetImplicitCwd _ Nothing -> "cwd-package"
TargetPackage TargetImplicitCwd _ (Just _) -> "cwd-package:filter"
TargetPackageNamed _ Nothing -> "named-package"
TargetPackageNamed _ (Just _) -> "named-package:filter"
TargetAllPackages Nothing -> "all-packages"
TargetAllPackages (Just _) -> "all-packages:filter"
TargetComponent _ _ WholeComponent -> "component"
TargetComponent _ _ ModuleTarget{} -> "module"
TargetComponent _ _ FileTarget{} -> "file"
TargetComponentUnknown _ _ WholeComponent -> "unknown-component"
TargetComponentUnknown _ _ ModuleTarget{} -> "unknown-module"
TargetComponentUnknown _ _ FileTarget{} -> "unknown-file"
-- ------------------------------------------------------------
-- * Checking if targets exist as files
-- ------------------------------------------------------------
data TargetStringFileStatus =
TargetStringFileStatus1 String FileStatus
| TargetStringFileStatus2 String FileStatus String
| TargetStringFileStatus3 String FileStatus String String
| TargetStringFileStatus4 String String String String
| TargetStringFileStatus5 String String String String String
| TargetStringFileStatus7 String String String String String String String
deriving (Eq, Ord, Show)
data FileStatus = FileStatusExistsFile FilePath -- the canonicalised filepath
| FileStatusExistsDir FilePath -- the canonicalised filepath
| FileStatusNotExists Bool -- does the parent dir exist even?
deriving (Eq, Ord, Show)
noFileStatus :: FileStatus
noFileStatus = FileStatusNotExists False
getTargetStringFileStatus :: (Applicative m, Monad m) => DirActions m
-> TargetString -> m TargetStringFileStatus
getTargetStringFileStatus DirActions{..} t =
case t of
TargetString1 s1 ->
(\f1 -> TargetStringFileStatus1 s1 f1) <$> fileStatus s1
TargetString2 s1 s2 ->
(\f1 -> TargetStringFileStatus2 s1 f1 s2) <$> fileStatus s1
TargetString3 s1 s2 s3 ->
(\f1 -> TargetStringFileStatus3 s1 f1 s2 s3) <$> fileStatus s1
TargetString4 s1 s2 s3 s4 ->
return (TargetStringFileStatus4 s1 s2 s3 s4)
TargetString5 s1 s2 s3 s4 s5 ->
return (TargetStringFileStatus5 s1 s2 s3 s4 s5)
TargetString7 s1 s2 s3 s4 s5 s6 s7 ->
return (TargetStringFileStatus7 s1 s2 s3 s4 s5 s6 s7)
where
fileStatus f = do
fexists <- doesFileExist f
dexists <- doesDirectoryExist f
case splitPath f of
_ | fexists -> FileStatusExistsFile <$> canonicalizePath f
| dexists -> FileStatusExistsDir <$> canonicalizePath f
(d:_) -> FileStatusNotExists <$> doesDirectoryExist d
_ -> pure (FileStatusNotExists False)
forgetFileStatus :: TargetStringFileStatus -> TargetString
forgetFileStatus t = case t of
TargetStringFileStatus1 s1 _ -> TargetString1 s1
TargetStringFileStatus2 s1 _ s2 -> TargetString2 s1 s2
TargetStringFileStatus3 s1 _ s2 s3 -> TargetString3 s1 s2 s3
TargetStringFileStatus4 s1 s2 s3 s4 -> TargetString4 s1 s2 s3 s4
TargetStringFileStatus5 s1 s2 s3 s4
s5 -> TargetString5 s1 s2 s3 s4 s5
TargetStringFileStatus7 s1 s2 s3 s4
s5 s6 s7 -> TargetString7 s1 s2 s3 s4 s5 s6 s7
-- ------------------------------------------------------------
-- * Resolving target strings to target selectors
-- ------------------------------------------------------------
-- | Given a bunch of user-specified targets, try to resolve what it is they
-- refer to.
--
resolveTargetSelectors :: KnownTargets
-> [TargetStringFileStatus]
-> ([TargetSelectorProblem],
[TargetSelector])
-- default local dir target if there's no given target:
resolveTargetSelectors (KnownTargets{knownPackagesAll = []}) [] =
([TargetSelectorNoTargetsInProject], [])
resolveTargetSelectors (KnownTargets{knownPackagesPrimary = []}) [] =
([TargetSelectorNoTargetsInCwd], [])
resolveTargetSelectors (KnownTargets{knownPackagesPrimary}) [] =
([], [TargetPackage TargetImplicitCwd pkgids Nothing])
where
pkgids = [ pinfoId | KnownPackage{pinfoId} <- knownPackagesPrimary ]
resolveTargetSelectors knowntargets targetStrs =
partitionEithers
. map (resolveTargetSelector knowntargets)
$ targetStrs
resolveTargetSelector :: KnownTargets
-> TargetStringFileStatus
-> Either TargetSelectorProblem TargetSelector
resolveTargetSelector knowntargets@KnownTargets{..} targetStrStatus =
case findMatch (matcher targetStrStatus) of
Unambiguous _
| projectIsEmpty -> Left TargetSelectorNoTargetsInProject
Unambiguous (TargetPackage TargetImplicitCwd [] _)
-> Left (TargetSelectorNoCurrentPackage targetStr)
Unambiguous target -> Right target
None errs
| projectIsEmpty -> Left TargetSelectorNoTargetsInProject
| otherwise -> Left (classifyMatchErrors errs)
Ambiguous exactMatch targets ->
case disambiguateTargetSelectors
matcher targetStrStatus exactMatch
targets of
Right targets' -> Left (TargetSelectorAmbiguous targetStr targets')
Left ((m, ms):_) -> Left (MatchingInternalError targetStr m ms)
Left [] -> internalError "resolveTargetSelector"
where
matcher = matchTargetSelector knowntargets
targetStr = forgetFileStatus targetStrStatus
projectIsEmpty = null knownPackagesAll
classifyMatchErrors errs
| not (null expected)
= let (things, got:_) = unzip expected in
TargetSelectorExpected targetStr things got
| not (null nosuch)
= TargetSelectorNoSuch targetStr nosuch
| otherwise
= internalError $ "classifyMatchErrors: " ++ show errs
where
expected = [ (thing, got)
| (_, MatchErrorExpected thing got)
<- map (innerErr Nothing) errs ]
-- Trim the list of alternatives by dropping duplicates and
-- retaining only at most three most similar (by edit distance) ones.
nosuch = Map.foldrWithKey genResults [] $ Map.fromListWith Set.union $
[ ((inside, thing, got), Set.fromList alts)
| (inside, MatchErrorNoSuch thing got alts)
<- map (innerErr Nothing) errs
]
genResults (inside, thing, got) alts acc = (
inside
, thing
, got
, take maxResults
$ map fst
$ takeWhile distanceLow
$ sortBy (comparing snd)
$ map addLevDist
$ Set.toList alts
) : acc
where
addLevDist = id &&& restrictedDamerauLevenshteinDistance
defaultEditCosts got
distanceLow (_, dist) = dist < length got `div` 2
maxResults = 3
innerErr _ (MatchErrorIn kind thing m)
= innerErr (Just (kind,thing)) m
innerErr c m = (c,m)
-- | The various ways that trying to resolve a 'TargetString' to a
-- 'TargetSelector' can fail.
--
data TargetSelectorProblem
= TargetSelectorExpected TargetString [String] String
-- ^ [expected thing] (actually got)
| TargetSelectorNoSuch TargetString
[(Maybe (String, String), String, String, [String])]
-- ^ [([in thing], no such thing, actually got, alternatives)]
| TargetSelectorAmbiguous TargetString
[(TargetString, TargetSelector)]
| MatchingInternalError TargetString TargetSelector
[(TargetString, [TargetSelector])]
| TargetSelectorUnrecognised String
-- ^ Syntax error when trying to parse a target string.
| TargetSelectorNoCurrentPackage TargetString
| TargetSelectorNoTargetsInCwd
| TargetSelectorNoTargetsInProject
deriving (Show, Eq)
data QualLevel = QL1 | QL2 | QL3 | QLFull
deriving (Eq, Enum, Show)
disambiguateTargetSelectors
:: (TargetStringFileStatus -> Match TargetSelector)
-> TargetStringFileStatus -> MatchClass
-> [TargetSelector]
-> Either [(TargetSelector, [(TargetString, [TargetSelector])])]
[(TargetString, TargetSelector)]
disambiguateTargetSelectors matcher matchInput exactMatch matchResults =
case partitionEithers results of
(errs@(_:_), _) -> Left errs
([], ok) -> Right ok
where
-- So, here's the strategy. We take the original match results, and make a
-- table of all their renderings at all qualification levels.
-- Note there can be multiple renderings at each qualification level.
matchResultsRenderings :: [(TargetSelector, [TargetStringFileStatus])]
matchResultsRenderings =
[ (matchResult, matchRenderings)
| matchResult <- matchResults
, let matchRenderings =
[ rendering
| ql <- [QL1 .. QLFull]
, rendering <- renderTargetSelector ql matchResult ]
]
-- Of course the point is that we're looking for renderings that are
-- unambiguous matches. So we build another memo table of all the matches
-- for all of those renderings. So by looking up in this table we can see
-- if we've got an unambiguous match.
memoisedMatches :: Map TargetStringFileStatus (Match TargetSelector)
memoisedMatches =
-- avoid recomputing the main one if it was an exact match
(if exactMatch == Exact
then Map.insert matchInput (Match Exact 0 matchResults)
else id)
$ Map.Lazy.fromList
[ (rendering, matcher rendering)
| rendering <- concatMap snd matchResultsRenderings ]
-- Finally, for each of the match results, we go through all their
-- possible renderings (in order of qualification level, though remember
-- there can be multiple renderings per level), and find the first one
-- that has an unambiguous match.
results :: [Either (TargetSelector, [(TargetString, [TargetSelector])])
(TargetString, TargetSelector)]
results =
[ case findUnambiguous originalMatch matchRenderings of
Just unambiguousRendering ->
Right ( forgetFileStatus unambiguousRendering
, originalMatch)
-- This case is an internal error, but we bubble it up and report it
Nothing ->
Left ( originalMatch
, [ (forgetFileStatus rendering, matches)
| rendering <- matchRenderings
, let (Match m _ matches) | m /= Inexact =
memoisedMatches Map.! rendering
] )
| (originalMatch, matchRenderings) <- matchResultsRenderings ]
findUnambiguous :: TargetSelector
-> [TargetStringFileStatus]
-> Maybe TargetStringFileStatus
findUnambiguous _ [] = Nothing
findUnambiguous t (r:rs) =
case memoisedMatches Map.! r of
Match Exact _ [t'] | t == t'
-> Just r
Match Exact _ _ -> findUnambiguous t rs
Match Unknown _ _ -> findUnambiguous t rs
Match Inexact _ _ -> internalError "Match Inexact"
NoMatch _ _ -> internalError "NoMatch"
internalError :: String -> a
internalError msg =
error $ "TargetSelector: internal error: " ++ msg
-- | Throw an exception with a formatted message if there are any problems.
--
reportTargetSelectorProblems :: Verbosity -> [TargetSelectorProblem] -> IO a
reportTargetSelectorProblems verbosity problems = do
case [ str | TargetSelectorUnrecognised str <- problems ] of
[] -> return ()
targets ->
die' verbosity $ unlines
[ "Unrecognised target syntax for '" ++ name ++ "'."
| name <- targets ]
case [ (t, m, ms) | MatchingInternalError t m ms <- problems ] of
[] -> return ()
((target, originalMatch, renderingsAndMatches):_) ->
die' verbosity $ "Internal error in target matching. It should always "
++ "be possible to find a syntax that's sufficiently qualified to "
++ "give an unambiguous match. However when matching '"
++ showTargetString target ++ "' we found "
++ showTargetSelector originalMatch
++ " (" ++ showTargetSelectorKind originalMatch ++ ") which does "
++ "not have an unambiguous syntax. The possible syntax and the "
++ "targets they match are as follows:\n"
++ unlines
[ "'" ++ showTargetString rendering ++ "' which matches "
++ intercalate ", "
[ showTargetSelector match ++
" (" ++ showTargetSelectorKind match ++ ")"
| match <- matches ]
| (rendering, matches) <- renderingsAndMatches ]
case [ (t, e, g) | TargetSelectorExpected t e g <- problems ] of
[] -> return ()
targets ->
die' verbosity $ unlines
[ "Unrecognised target '" ++ showTargetString target
++ "'.\n"
++ "Expected a " ++ intercalate " or " expected
++ ", rather than '" ++ got ++ "'."
| (target, expected, got) <- targets ]
case [ (t, e) | TargetSelectorNoSuch t e <- problems ] of
[] -> return ()
targets ->
die' verbosity $ unlines
[ "Unknown target '" ++ showTargetString target ++
"'.\n" ++ unlines
[ (case inside of
Just (kind, "")
-> "The " ++ kind ++ " has no "
Just (kind, thing)
-> "The " ++ kind ++ " " ++ thing ++ " has no "
Nothing -> "There is no ")
++ intercalate " or " [ mungeThing thing ++ " '" ++ got ++ "'"
| (thing, got, _alts) <- nosuch' ] ++ "."
++ if null alternatives then "" else
"\nPerhaps you meant " ++ intercalate ";\nor "
[ "the " ++ thing ++ " '" ++ intercalate "' or '" alts ++ "'?"
| (thing, alts) <- alternatives ]
| (inside, nosuch') <- groupByContainer nosuch
, let alternatives =
[ (thing, alts)
| (thing,_got,alts@(_:_)) <- nosuch' ]
]
| (target, nosuch) <- targets
, let groupByContainer =
map (\g@((inside,_,_,_):_) ->
(inside, [ (thing,got,alts)
| (_,thing,got,alts) <- g ]))
. groupBy ((==) `on` (\(x,_,_,_) -> x))
. sortBy (compare `on` (\(x,_,_,_) -> x))
]
where
mungeThing "file" = "file target"
mungeThing thing = thing
case [ (t, ts) | TargetSelectorAmbiguous t ts <- problems ] of
[] -> return ()
targets ->
die' verbosity $ unlines
[ "Ambiguous target '" ++ showTargetString target
++ "'. It could be:\n "
++ unlines [ " "++ showTargetString ut ++
" (" ++ showTargetSelectorKind bt ++ ")"
| (ut, bt) <- amb ]
| (target, amb) <- targets ]
case [ t | TargetSelectorNoCurrentPackage t <- problems ] of
[] -> return ()
target:_ ->
die' verbosity $
"The target '" ++ showTargetString target ++ "' refers to the "
++ "components in the package in the current directory, but there "
++ "is no package in the current directory (or at least not listed "
++ "as part of the project)."
--TODO: report a different error if there is a .cabal file but it's
-- not a member of the project
case [ () | TargetSelectorNoTargetsInCwd <- problems ] of
[] -> return ()
_:_ ->
die' verbosity $
"No targets given and there is no package in the current "
++ "directory. Use the target 'all' for all packages in the "
++ "project or specify packages or components by name or location. "
++ "See 'cabal build --help' for more details on target options."
case [ () | TargetSelectorNoTargetsInProject <- problems ] of
[] -> return ()
_:_ ->
die' verbosity $
"There is no <pkgname>.cabal package file or cabal.project file. "
++ "To build packages locally you need at minimum a <pkgname>.cabal "
++ "file. You can use 'cabal init' to create one.\n"
++ "\n"
++ "For non-trivial projects you will also want a cabal.project "
++ "file in the root directory of your project. This file lists the "
++ "packages in your project and all other build configuration. "
++ "See the Cabal user guide for full details."
fail "reportTargetSelectorProblems: internal error"
----------------------------------
-- Syntax type
--
-- | Syntax for the 'TargetSelector': the matcher and renderer
--
data Syntax = Syntax QualLevel Matcher Renderer
| AmbiguousAlternatives Syntax Syntax
| ShadowingAlternatives Syntax Syntax
type Matcher = TargetStringFileStatus -> Match TargetSelector
type Renderer = TargetSelector -> [TargetStringFileStatus]
foldSyntax :: (a -> a -> a) -> (a -> a -> a)
-> (QualLevel -> Matcher -> Renderer -> a)
-> (Syntax -> a)
foldSyntax ambiguous unambiguous syntax = go
where
go (Syntax ql match render) = syntax ql match render
go (AmbiguousAlternatives a b) = ambiguous (go a) (go b)
go (ShadowingAlternatives a b) = unambiguous (go a) (go b)
----------------------------------
-- Top level renderer and matcher
--
renderTargetSelector :: QualLevel -> TargetSelector
-> [TargetStringFileStatus]
renderTargetSelector ql ts =
foldSyntax
(++) (++)
(\ql' _ render -> guard (ql == ql') >> render ts)
syntax
where
syntax = syntaxForms emptyKnownTargets
-- don't need known targets for rendering
matchTargetSelector :: KnownTargets
-> TargetStringFileStatus
-> Match TargetSelector
matchTargetSelector knowntargets = \usertarget ->
nubMatchesBy (==) $
let ql = targetQualLevel usertarget in
foldSyntax
(<|>) (<//>)
(\ql' match _ -> guard (ql == ql') >> match usertarget)
syntax
where
syntax = syntaxForms knowntargets
targetQualLevel TargetStringFileStatus1{} = QL1
targetQualLevel TargetStringFileStatus2{} = QL2
targetQualLevel TargetStringFileStatus3{} = QL3
targetQualLevel TargetStringFileStatus4{} = QLFull
targetQualLevel TargetStringFileStatus5{} = QLFull
targetQualLevel TargetStringFileStatus7{} = QLFull
----------------------------------
-- Syntax forms
--
-- | All the forms of syntax for 'TargetSelector'.
--
syntaxForms :: KnownTargets -> Syntax
syntaxForms KnownTargets {
knownPackagesAll = pinfo,
knownPackagesPrimary = ppinfo,
knownComponentsAll = cinfo,
knownComponentsPrimary = pcinfo,
knownComponentsOther = ocinfo
} =
-- The various forms of syntax here are ambiguous in many cases.
-- Our policy is by default we expose that ambiguity and report
-- ambiguous matches. In certain cases we override the ambiguity
-- by having some forms shadow others.
--
-- We make modules shadow files because module name "Q" clashes
-- with file "Q" with no extension but these refer to the same
-- thing anyway so it's not a useful ambiguity. Other cases are
-- not ambiguous like "Q" vs "Q.hs" or "Data.Q" vs "Data/Q".
ambiguousAlternatives
-- convenient single-component forms
[ shadowingAlternatives
[ ambiguousAlternatives
[ syntaxForm1All
, syntaxForm1Filter ppinfo
, shadowingAlternatives
[ syntaxForm1Component pcinfo
, syntaxForm1Package pinfo
]
]
, syntaxForm1Component ocinfo
, syntaxForm1Module cinfo
, syntaxForm1File pinfo
]
-- two-component partially qualified forms
-- fully qualified form for 'all'
, syntaxForm2MetaAll
, syntaxForm2AllFilter
, syntaxForm2NamespacePackage pinfo
, syntaxForm2PackageComponent pinfo
, syntaxForm2PackageFilter pinfo
, syntaxForm2KindComponent cinfo
, shadowingAlternatives
[ syntaxForm2PackageModule pinfo
, syntaxForm2PackageFile pinfo
]
, shadowingAlternatives
[ syntaxForm2ComponentModule cinfo
, syntaxForm2ComponentFile cinfo
]
-- rarely used partially qualified forms
, syntaxForm3PackageKindComponent pinfo
, shadowingAlternatives
[ syntaxForm3PackageComponentModule pinfo
, syntaxForm3PackageComponentFile pinfo
]
, shadowingAlternatives
[ syntaxForm3KindComponentModule cinfo
, syntaxForm3KindComponentFile cinfo
]
, syntaxForm3NamespacePackageFilter pinfo
-- fully-qualified forms for all and cwd with filter
, syntaxForm3MetaAllFilter
, syntaxForm3MetaCwdFilter ppinfo
-- fully-qualified form for package and package with filter
, syntaxForm3MetaNamespacePackage pinfo
, syntaxForm4MetaNamespacePackageFilter pinfo
-- fully-qualified forms for component, module and file
, syntaxForm5MetaNamespacePackageKindComponent pinfo
, syntaxForm7MetaNamespacePackageKindComponentNamespaceModule pinfo
, syntaxForm7MetaNamespacePackageKindComponentNamespaceFile pinfo
]
where
ambiguousAlternatives = foldr1 AmbiguousAlternatives
shadowingAlternatives = foldr1 ShadowingAlternatives
-- | Syntax: "all" to select all packages in the project
--
-- > cabal build all
--
syntaxForm1All :: Syntax
syntaxForm1All =
syntaxForm1 render $ \str1 _fstatus1 -> do
guardMetaAll str1
return (TargetAllPackages Nothing)
where
render (TargetAllPackages Nothing) =
[TargetStringFileStatus1 "all" noFileStatus]
render _ = []
-- | Syntax: filter
--
-- > cabal build tests
--
syntaxForm1Filter :: [KnownPackage] -> Syntax
syntaxForm1Filter ps =
syntaxForm1 render $ \str1 _fstatus1 -> do
kfilter <- matchComponentKindFilter str1
return (TargetPackage TargetImplicitCwd pids (Just kfilter))
where
pids = [ pinfoId | KnownPackage{pinfoId} <- ps ]
render (TargetPackage TargetImplicitCwd _ (Just kfilter)) =
[TargetStringFileStatus1 (dispF kfilter) noFileStatus]
render _ = []
-- | Syntax: package (name, dir or file)
--
-- > cabal build foo
-- > cabal build ../bar ../bar/bar.cabal
--
syntaxForm1Package :: [KnownPackage] -> Syntax
syntaxForm1Package pinfo =
syntaxForm1 render $ \str1 fstatus1 -> do
guardPackage str1 fstatus1
p <- matchPackage pinfo str1 fstatus1
case p of
KnownPackage{pinfoId} ->
return (TargetPackage TargetExplicitNamed [pinfoId] Nothing)
KnownPackageName pn ->
return (TargetPackageNamed pn Nothing)
where
render (TargetPackage TargetExplicitNamed [p] Nothing) =
[TargetStringFileStatus1 (dispP p) noFileStatus]
render (TargetPackageNamed pn Nothing) =
[TargetStringFileStatus1 (dispPN pn) noFileStatus]
render _ = []
-- | Syntax: component
--
-- > cabal build foo
--
syntaxForm1Component :: [KnownComponent] -> Syntax
syntaxForm1Component cs =
syntaxForm1 render $ \str1 _fstatus1 -> do
guardComponentName str1
c <- matchComponentName cs str1
return (TargetComponent (cinfoPackageId c) (cinfoName c) WholeComponent)
where
render (TargetComponent p c WholeComponent) =
[TargetStringFileStatus1 (dispC p c) noFileStatus]
render _ = []
-- | Syntax: module
--
-- > cabal build Data.Foo
--
syntaxForm1Module :: [KnownComponent] -> Syntax
syntaxForm1Module cs =
syntaxForm1 render $ \str1 _fstatus1 -> do
guardModuleName str1
let ms = [ (m,c) | c <- cs, m <- cinfoModules c ]
(m,c) <- matchModuleNameAnd ms str1
return (TargetComponent (cinfoPackageId c) (cinfoName c) (ModuleTarget m))
where
render (TargetComponent _p _c (ModuleTarget m)) =
[TargetStringFileStatus1 (dispM m) noFileStatus]
render _ = []
-- | Syntax: file name
--
-- > cabal build Data/Foo.hs bar/Main.hsc
--
syntaxForm1File :: [KnownPackage] -> Syntax
syntaxForm1File ps =
-- Note there's a bit of an inconsistency here vs the other syntax forms
-- for files. For the single-part syntax the target has to point to a file
-- that exists (due to our use of matchPackageDirectoryPrefix), whereas for
-- all the other forms we don't require that.