b247029955a66ffa817dae3d0bb6a0a82d554901
[scons.git] / src / engine / SCons / Taskmaster.py
1 """SCons.Taskmaster
2
3 Generic Taskmaster.
4
5 """
6
7 #
8 # Copyright (c) 2001 Steven Knight
9 #
10 # Permission is hereby granted, free of charge, to any person obtaining
11 # a copy of this software and associated documentation files (the
12 # "Software"), to deal in the Software without restriction, including
13 # without limitation the rights to use, copy, modify, merge, publish,
14 # distribute, sublicense, and/or sell copies of the Software, and to
15 # permit persons to whom the Software is furnished to do so, subject to
16 # the following conditions:
17 #
18 # The above copyright notice and this permission notice shall be included
19 # in all copies or substantial portions of the Software.
20 #
21 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
22 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
23 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 #
29
30 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
31
32
33
34
35 import SCons.Node
36 import string
37 import SCons.Errors
38 import copy
39
40 class Task:
41     """Default SCons build engine task.
42     
43     This controls the interaction of the actual building of node
44     and the rest of the engine.
45
46     This is expected to handle all of the normally-customizable
47     aspects of controlling a build, so any given application
48     *should* be able to do what it wants by sub-classing this
49     class and overriding methods as appropriate.  If an application
50     needs to customze something by sub-classing Taskmaster (or
51     some other build engine class), we should first try to migrate
52     that functionality into this class.
53     
54     Note that it's generally a good idea for sub-classes to call
55     these methods explicitly to update state, etc., rather than
56     roll their own interaction with Taskmaster from scratch."""
57     def __init__(self, tm, targets, top):
58         self.tm = tm
59         self.targets = targets
60         self.top = top
61
62     def execute(self):
63         if self.targets[0].get_state() != SCons.Node.up_to_date:
64             self.targets[0].build()
65
66     def get_target(self):
67         """Fetch the target being built or updated by this task.
68         """
69         return self.targets[0]
70
71     def set_tstates(self, state):
72         """Set all of the target nodes's states."""
73         for t in self.targets:
74             t.set_state(state)
75
76     def executed(self):
77         """Called when the task has been successfully executed.
78
79         This may have been a do-nothing operation (to preserve
80         build order), so check the node's state before updating
81         things.  Most importantly, this calls back to the
82         Taskmaster to put any node tasks waiting on this one
83         back on the pending list."""
84         if self.targets[0].get_state() == SCons.Node.executing:
85             self.set_tstates(SCons.Node.executed)
86             for t in self.targets:
87                 t.store_sigs()
88             parents = {}
89             for p in reduce(lambda x, y: x + y.get_parents(), self.targets, []):
90                 parents[p] = 1
91             ready = filter(lambda x: (x.get_state() == SCons.Node.pending
92                                       and x.children_are_executed()),
93                            parents.keys())
94             tasks = {}
95             for t in map(lambda r: r.task, ready):
96                 tasks[t] = 1
97             self.tm.pending_to_ready(tasks.keys())
98
99     def failed(self):
100         """Default action when a task fails:  stop the build."""
101         self.fail_stop()
102
103     def fail_stop(self):
104         """Explicit stop-the-build failure."""
105         self.set_tstates(SCons.Node.failed)
106         self.tm.stop()
107
108     def fail_continue(self):
109         """Explicit continue-the-build failure.
110
111         This sets failure status on the target nodes and all of
112         their dependent parent nodes.
113         """
114         nodes = {}
115         for t in self.targets:
116             def get_parents(node): return node.get_parents()
117             walker = SCons.Node.Walker(t, get_parents)
118             while 1:
119                 n = walker.next()
120                 if n == None: break
121                 nodes[n] = 1
122         pending = filter(lambda x: x.get_state() == SCons.Node.pending,
123                          nodes.keys())
124         tasks = {}
125         for t in map(lambda r: r.task, pending):
126             tasks[t] = 1
127         self.tm.pending_remove(tasks.keys())
128
129     def make_ready(self):
130         """Make a task ready for execution."""
131         state = SCons.Node.up_to_date
132         for t in self.targets:
133             bsig = self.tm.calc.bsig(t)
134             t.set_bsig(bsig)
135             if not self.tm.calc.current(t, bsig):
136                 state = SCons.Node.executing
137         self.set_tstates(state)
138         self.tm.add_ready(self)
139
140
141
142 class Calc:
143     def bsig(self, node):
144         """
145         """
146         return None
147
148     def current(self, node, sig):
149         """Default SCons build engine is-it-current function.
150     
151         This returns "always out of date," so every node is always
152         built/visited.
153         """
154         return 0
155
156
157
158 class Taskmaster:
159     """A generic Taskmaster for handling a bunch of targets.
160
161     Classes that override methods of this class should call
162     the base class method, so this class can do its thing.    
163     """
164
165     def __init__(self, targets=[], tasker=Task, calc=Calc()):
166         
167         def out_of_date(node):
168             # Scan the file before fetching its children().
169             node.scan()
170             return filter(lambda x: x.get_state() != SCons.Node.up_to_date,
171                           node.children())
172
173         def cycle_error(node, stack):
174             if node.builder:
175                 nodes = stack + [node]
176                 nodes.reverse()
177                 desc = "Dependency cycle: " + string.join(map(str, nodes), " -> ")
178                 raise SCons.Errors.UserError, desc
179
180         #XXX In Python 2.2 we can get rid of f1 and f2:
181         self.walkers = map(lambda x, f1=out_of_date, f2=cycle_error: SCons.Node.Walker(x, f1, f2),
182                            targets)
183         self.tasker = tasker
184         self.calc = calc
185         self.ready = []
186         self.pending = 0
187         
188         self._find_next_ready_node()
189
190     def next_task(self):
191         """Return the next task to be executed."""
192         if self.ready:
193             task = self.ready.pop()
194             if not self.ready:
195                 self._find_next_ready_node()
196             return task
197         else:
198             return None
199
200     def _find_next_ready_node(self):
201         """Find the next node that is ready to be built"""
202         while self.walkers:
203             n = self.walkers[0].next()
204             if n == None:
205                 self.walkers.pop(0)
206                 continue
207             if n.get_state():
208                 # The state is set, so someone has already been here
209                 # (finished or currently executing).  Find another one.
210                 continue
211             if not n.builder:
212                 # It's a source file, we don't need to build it,
213                 # but mark it as "up to date" so targets won't
214                 # wait for it.
215                 n.set_state(SCons.Node.up_to_date)
216                 # set the signature for non-derived files
217                 # here so they don't get recalculated over
218                 # and over again:
219                 n.set_csig(self.calc.csig(n))
220                 continue
221             try:
222                 tlist = n.builder.targets(n)
223             except AttributeError:
224                 tlist = [ n ]
225             task = self.tasker(self, tlist, self.walkers[0].is_done())
226             if not tlist[0].children_are_executed():
227                 for t in tlist:
228                     t.set_state(SCons.Node.pending)
229                     t.task = task
230                 self.pending = self.pending + 1
231                 continue
232             task.make_ready()
233             return
234             
235     def is_blocked(self):
236         return not self.ready and self.pending
237
238     def stop(self):
239         """Stop the current build completely."""
240         self.walkers = []
241         self.pending = 0
242         self.ready = []
243
244     def add_ready(self, task):
245         """Add a task to the ready queue.
246         """
247         self.ready.append(task)
248
249     def pending_to_ready(self, tasks):
250         """Move the specified tasks from the pending count
251         to the 'ready' queue.
252         """
253         self.pending_remove(tasks)
254         for t in tasks:
255             t.make_ready()
256
257     def pending_remove(self, tasks):
258         """Remove tasks from the pending count.
259         
260         We assume that the caller has already confirmed that
261         the nodes in this task are in pending state.
262         """
263         self.pending = self.pending - len(tasks)