-
Notifications
You must be signed in to change notification settings - Fork 681
/
Rule.hs
451 lines (401 loc) · 14.6 KB
/
Rule.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
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RankNTypes #-}
-- |
-- Module: Distribution.Simple.SetupHooks.Rule
--
-- Internal module that defines fine-grained rules for setup hooks.
-- Users should import 'Distribution.Simple.SetupHooks' instead.
module Distribution.Simple.SetupHooks.Rule
( -- * Rules
-- ** Rule
Rule (..)
, RuleId (..)
, simpleRule
-- * Action
, Action (..)
, ActionId (..)
, simpleAction
-- ** Collections of rules
, Rules (..)
, Dependency (..)
, RuleOutput (..)
, rules
, noRules
-- ** Rule inputs/outputs
, Location
-- ** Monitoring
, MonitoredValue
, MonitorFileOrDir (..)
, MonitorKindFile (..)
, MonitorKindDir (..)
-- *** Monadic API for generation of 'ActionId'
, RulesM
, ActionsM (..)
, RulesT (..)
, computeRules
)
where
import Distribution.Compat.Prelude
import Distribution.Utils.ShortText
( ShortText
)
import Distribution.Verbosity
( Verbosity
)
import Control.Monad.Fix
( MonadFix
)
import Control.Monad.Trans
( MonadIO
, MonadTrans (..)
)
import qualified Control.Monad.Trans.Reader as Reader
import qualified Control.Monad.Trans.State as State
#if MIN_VERSION_transformers(0,5,6)
import qualified Control.Monad.Trans.Writer.CPS as Writer
#else
import qualified Control.Monad.Trans.Writer.Strict as Writer
#endif
import qualified Data.ByteString.Lazy as LBS
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as Map
( empty
)
--------------------------------------------------------------------------------
{- Note [Fine-grained hooks]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To best understand how the framework of fine-grained build rules
fits into Cabal and the greater Haskell ecosystem, it is helpful to think
that we want build tools (such as cabal-install or HLS) to be able to call
individual build rules on-demand, so that e.g. when a user modifies a .xyz file
the associated preprocessor is re-run.
To do this, we need to perform two different kinds of invocations:
Query: query the package for the rules that it provides, with their
dependency information. This allows one to determine when each
rule should be rerun.
(For example, if one rule preprocesses *.xyz into *.hs, we need to
re-run the rule whenever *.xyz is modified.)
Run: run the relevant action, once one has determined that the rule
has gone stale.
To do this, any Cabal package with Hooks build-type provides a SetupHooks
module which supports these queries; for example it can be compiled into
a separate executable which can be invoked in the manner described above.
The function that implements this API in Cabal is
Distribution.Simple.UserHooks.hooksMain.
-}
-- | A unique identifier for an t'Action'.
data ActionId = ActionId
{ actionUnitId :: !ShortText
, actionId :: !ShortText
}
deriving (Show, Eq, Ord, Generic)
instance Binary ActionId
instance Structured ActionId
-- | A unique identifier for a t'Rule'.
data RuleId = RuleId
{ ruleUnitId :: !ShortText
, ruleId :: !ShortText
}
deriving (Show, Eq, Ord, Generic)
instance Binary RuleId
instance Structured RuleId
-- | A monitored value.
--
-- Use this to declare a dependency on a certain projection of the
-- environment passed in to a computation.
--
-- A computation is considered out-of-date when the environment passed to
-- it changes and this value also changes.
--
-- A value of 'Nothing' means: always consider the computation to be out-of-date
-- when the environment changes.
type MonitoredValue = Maybe LBS.ByteString
-- | A monitored file or directory.
--
-- Use this to declare a dependency of the computation of rules. For example,
-- returning @[MonitorDir DirContents "abc"]@ will ensure that rules are
-- re-computed whenever the contents of directory @abc@ changes.
data MonitorFileOrDir
= MonitorFile
{ monitorKindFile :: !MonitorKindFile
, monitorPath :: !FilePath
}
| MonitorDir
{ monitorKindDir :: !MonitorKindDir
, monitorDirLocation :: !FilePath
}
deriving (Generic, Eq, Show)
instance Binary MonitorFileOrDir
instance Structured MonitorFileOrDir
data MonitorKindFile
= FileExists
| FileModTime
| FileHashed
| FileNotExists
deriving (Generic, Eq, Show)
instance Binary MonitorKindFile
instance Structured MonitorKindFile
data MonitorKindDir
= DirExists
| DirContents
| DirNotExists
deriving (Generic, Eq, Show)
instance Binary MonitorKindDir
instance Structured MonitorKindDir
-- | A rule consists of:
--
-- - an action to run, indirectly referenced by the 'ActionId' of
-- the 'Action'
-- - a description of the action:
--
-- - what inputs the action depends on,
-- - what outputs will result from the execution of the action.
--
-- The location of each dependency and of each output will get passed to the
-- action when executing the rule.
--
-- Use 'simpleRule' to construct a rule, overriding specific fields, rather
-- than directly using the 'Rule' constructor.
--
-- __Requirements:__ the t'Action' whose t'ActionId' is stored in the 'actionId'
-- field of a 'Rule' must satisfy the following:
--
-- - the t'Action' expects exactly as many elements in its first argument
-- as there are values stored in the 'dependencies' field of the 'Rule's;
-- - the t'Action' expects exactly as many elements in its second argument
-- as there are values stored in the 'results' field of the rule;
-- the execution of the action must produce results in these specified
-- locations.
data Rule
= -- | Please use the 'simpleRule' smart constructor instead of
-- this constructor, in order to avoid relying on internal implementation
-- details.
Rule
{ dependencies :: ![Dependency]
-- ^ Dependencies of this rule.
--
-- When the build system executes the action associated to this rule,
-- it will pass the locations of these dependencies as the first argument
-- to the action.
, results :: !(NE.NonEmpty Location)
-- ^ Results of this rule; see t'Result'.
--
-- When the build system executes the action associated to this rule,
-- it will pass these locations as the second argument to the action.
, ruleActionId :: !ActionId
-- ^ To run this rule, which t'Action' should we execute?
--
-- The t'Action' will receive exactly as many elements in its first
-- argument as there are 'dependencies' to this t'Rule', and exactly
-- as many elements in its second argument as there are 'results'
-- of this rule.
, monitoredValue :: !MonitoredValue
-- ^ A monitored value. The rule should be re-run whenever this value
-- changes.
--
-- Use this to declare a dependency on a certain projection of the
-- environment passed to the rule.
--
-- A value of 'Nothing' means: always re-run the rule when the
-- environment passed to the computation of rules changes.
}
deriving (Generic, Show)
-- | A simple rule, with no additional monitoring.
--
-- Prefer using this smart constructor instead of v'Rule' whenever possible.
simpleRule :: ActionId -> [Dependency] -> NE.NonEmpty Location -> Rule
simpleRule actId dep res =
Rule
{ dependencies = dep
, results = res
, monitoredValue = Nothing
, ruleActionId = actId
}
instance Binary Rule
instance Structured Rule
-- | A (fully resolved) location of a dependency or result of a rule,
-- consisting of a base directory and of a file path relative to that base
-- directory path.
--
-- In practice, this will be something like @( dir, toFilePath modName )@,
-- where:
--
-- - for a file dependency, @dir@ is one of the Cabal search directories,
-- - for an output, @dir@ is a directory such as @autogenComponentModulesDir@
-- or @componentBuildDir@.
type Location = (FilePath, FilePath)
-- The reason for splitting it up this way is that some pre-processors don't
-- simply generate one output @.hs@ file from one input file, but have
-- dependencies on other generated files (notably @c2hs@, where building one
-- @.hs@ file may require reading other @.chi@ files, and then compiling the
-- @.hs@ file may require reading a generated @.h@ file).
-- In these cases, the generated files need to embed relative path names to each
-- other (eg the generated @.hs@ file mentions the @.h@ file in the FFI imports).
-- This path must be relative to the base directory where the generated files
-- are located; it cannot be relative to the top level of the build tree because
-- the compilers do not look for @.h@ files relative to there, ie we do not use
-- @-I .@, instead we use @-I dist/build@ (or whatever dist dir has been set
-- by the user).
-- | A dependency of a rule.
data Dependency
= -- | A dependency on an output of another rule.
RuleDependency !RuleOutput
| -- | A direct dependency on a file at a particular location on disk.
--
-- This should not be used for files that are generated by other rules;
-- use 'RuleDependency' instead.
FileDependency !Location
deriving stock (Show, Eq, Ord, Generic)
instance Binary Dependency
instance Structured Dependency
-- | A reference to an output of another rule.
data RuleOutput = RuleOutput
{ outputOfRule :: !RuleId
-- ^ which rule's outputs are we referring to?
, outputIndex :: !Int
-- ^ which particular output of that rule?
}
deriving stock (Show, Eq, Ord, Generic)
instance Binary RuleOutput
instance Structured RuleOutput
-- | An action to run to execute a 'Rule', for example an invocation
-- of an external executable such as @happy@ or @alex@.
--
-- Use 'simpleAction' to construct an action, overriding specific fields,
-- rather than directly using the 'Action' constructor.
--
-- Arguments:
--
-- 1. The locations of the __dependencies__ of this action,
-- as declared by the rule that this action is executing.
-- There will be as many values passed in this list as there are
-- 'dependencies' values declared in the 'Rule' that calls the action.
--
-- 2. The locations in which the __results__ of this action should be put.
-- There will be as many values passed in this list as there are
-- 'results' values declared in the 'Rule' that calls the action.
newtype Action
= -- | Please use the 'simpleAction' smart constructor instead of
-- this constructor, in order to avoid relying on internal implementation
-- details.
Action
{ action
:: [Location]
-- \^ Locations of the __dependencies__ of this action,
-- as declared by the rule that this action is executing.
-> NE.NonEmpty Location
-- \^ Locations in which the __results__ of this action
-- should be put.
-> IO ()
}
-- | A simple action, with no additional monitoring.
--
-- Prefer using this smart constructor over v'Action' whenever possible.
simpleAction :: ([Location] -> NE.NonEmpty Location -> IO ()) -> Action
simpleAction f = Action{action = f}
-- | A collection of t'Rule's and t'Action's for executing them.
--
-- Use the 'rules' smart constructor instead of directly using the v'Rules'
-- constructor.
--
-- Actions are registered using 'registerAction', and rules are registered
-- using 'registerRule'. One can declare additional monitored files or
-- directories using 'addRuleMonitors'; a change in these will trigger the
-- recomputation of all rules.
--
-- The @env@ type parameter represents an extra argument, which usually
-- consists of information known to Cabal such as 'LocalBuildInfo' and
-- 'ComponentLocalBuildInfo'.
--
-- Even though t'Rule's and t'Action's are registered separately, the nature
-- of the arguments passed to an t'Action' corresponds with the description
-- of the 'Rule', e.g. the action will receive as many 'Location's in its first
-- argument as the rule declared 'dependencies'.
--
-- See t'Rule' for more information.
newtype Rules env
= -- | Return a collection of t'Action's and their t'ActionId's, and then,
-- in the inner computation, a collection of t'Rule's, each of which
-- specifies its dependencies, results, and the t'ActionId' of the t'Action'
-- to run in order to execute the rule, together with a list of
-- monitored files or directories (when any of these change, the rules
-- are out-of-date and must be recomputed).
--
-- You can think of this type signature as:
--
-- > env -> ( Map ActionId Action, IO ( Map RuleId Rule, [ MonitorFileOrDir ] ) )
Rules {runRules :: env -> RulesM ()}
-- | __Warning__: this 'Semigroup' instance is not commutative.
instance Semigroup (Rules env) where
(Rules rs1) <> (Rules rs2) =
Rules $ \inputs -> do
x1 <- rs1 inputs
x2 <- rs2 inputs
return $ do
y1 <- x1
y2 <- x2
return $ y1 <> y2
instance Monoid (Rules env) where
mempty = Rules $ const noRules
-- | An empty collection of rules.
noRules :: RulesM ()
noRules = pure $ pure ()
-- | Construct a collection of rules.
--
-- Prefer using this smart constructor over v'Rules' whenever possible.
rules :: (env -> RulesM ()) -> Rules env
rules f = Rules{runRules = f}
-- | Internal function: run the monadic 'Rules' computations in order
-- to obtain all the 'Action's and 'Rule's.
computeRules
:: Verbosity
-> env
-> Rules env
-> IO (Map ActionId Action, IO (Map RuleId Rule, [MonitorFileOrDir]))
computeRules verbosity inputs (Rules rs) = do
(rulesT, actionFromId) <-
(`State.runStateT` Map.empty) $
(`Reader.runReaderT` verbosity) $
runActionsM $
rs inputs
let
getRules =
Writer.runWriterT $
(`State.execStateT` Map.empty) $
(`Reader.runReaderT` verbosity) $
runRulesT rulesT
return (actionFromId, getRules)
--------------------------------------------------------------------------------
-- API for keeping track of all declared rules
-- | Monadic API for constructing rules.
type RulesM a = ActionsM (RulesT IO a)
-- | Monad for defining actions.
newtype ActionsM a = ActionsM
{ runActionsM
:: Reader.ReaderT
Verbosity
(State.StateT (Map ActionId Action) IO)
a
}
deriving (Functor, Applicative, Monad, MonadFix)
-- NB: no 'MonadIO' instance; the 'IO' is only used internally,
-- and is not exposed to users.
-- | Monad transformer for defining rules. Usually wraps the 'IO' monad,
-- allowing @IO@ actions to be performed using @liftIO@.
newtype RulesT m a = RulesT
{ runRulesT
:: Reader.ReaderT
Verbosity
( State.StateT
(Map RuleId Rule)
(Writer.WriterT [MonitorFileOrDir] m)
)
a
}
deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
instance MonadTrans RulesT where
lift = RulesT . lift . lift . lift