summaryrefslogtreecommitdiffstats
path: root/crates/driver/src/resolve.rs
blob: 35915c026822dcf58bf47a15c47657b89432c7a1 (plain)
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
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::rc::Rc;

use common::types::TaskID;

use crate::args::TaskArgs;
use crate::context::{self, Context, OutputRef, TaskRef};

#[derive(Debug)]
pub struct DepChain<'ctx>(pub Vec<TaskRef<'ctx>>);

impl<'ctx> fmt::Display for DepChain<'ctx> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let mut first = true;
		for task in self.0.iter().rev() {
			if !first {
				write!(f, " -> ")?;
			}
			write!(f, "{}", task)?;

			first = false;
		}

		Ok(())
	}
}

impl<'ctx> From<TaskRef<'ctx>> for DepChain<'ctx> {
	fn from(task: TaskRef<'ctx>) -> Self {
		DepChain(vec![task])
	}
}

impl<'ctx> From<&TaskRef<'ctx>> for DepChain<'ctx> {
	fn from(task: &TaskRef<'ctx>) -> Self {
		task.clone().into()
	}
}

impl<'ctx> From<&'ctx TaskID> for DepChain<'ctx> {
	fn from(id: &'ctx TaskID) -> Self {
		TaskRef {
			id,
			args: Rc::new(TaskArgs::default()),
		}
		.into()
	}
}

#[derive(Debug)]
pub enum ErrorKind<'ctx> {
	Context(context::Error<'ctx>),
	OutputNotFound(&'ctx str),
	DependencyCycle,
}

#[derive(Debug)]
pub struct Error<'ctx> {
	pub dep_chain: DepChain<'ctx>,
	pub kind: ErrorKind<'ctx>,
}

impl<'ctx> Error<'ctx> {
	fn output_not_found(task: &TaskRef<'ctx>, output: &'ctx str) -> Self {
		Error {
			dep_chain: task.into(),
			kind: ErrorKind::OutputNotFound(output),
		}
	}

	fn dependency_cycle(task: &TaskRef<'ctx>) -> Self {
		Error {
			dep_chain: task.into(),
			kind: ErrorKind::DependencyCycle,
		}
	}

	fn extend(&mut self, task: &TaskRef<'ctx>) {
		self.dep_chain.0.push(task.clone());
	}
}

impl<'ctx> fmt::Display for Error<'ctx> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		let Error { dep_chain, kind } = self;
		match kind {
			ErrorKind::Context(err) => {
				write!(f, "{}: ", err)?;
			}
			ErrorKind::OutputNotFound(output) => {
				write!(f, "Output '{}' not found: ", output)?;
			}
			ErrorKind::DependencyCycle => {
				write!(f, "Dependency Cycle: ")?;
			}
		}
		dep_chain.fmt(f)
	}
}

impl<'ctx> From<context::Error<'ctx>> for Error<'ctx> {
	fn from(err: context::Error<'ctx>) -> Self {
		Error {
			dep_chain: err.task.into(),
			kind: ErrorKind::Context(err),
		}
	}
}

impl<'ctx> std::error::Error for Error<'ctx> {}

#[derive(Debug, PartialEq)]
enum ResolveState {
	Resolving,
	Resolved,
}

pub fn runtime_depends<'ctx, I>(
	ctx: &'ctx Context,
	deps: I,
) -> Result<HashSet<OutputRef>, Vec<Error>>
where
	I: IntoIterator<Item = OutputRef<'ctx>>,
{
	fn add_dep<'ctx>(
		ret: &mut HashSet<OutputRef<'ctx>>,
		ctx: &'ctx Context,
		dep: OutputRef<'ctx>,
	) -> Vec<Error<'ctx>> {
		if ret.contains(&dep) {
			return Vec::new();
		}

		let task = &dep.task;
		let task_def = match ctx.get(task) {
			Ok(task) => task,
			Err(err) => return vec![err.into()],
		};

		let output = match task_def.output.get(dep.output) {
			Some(output) => output,
			None => {
				return vec![Error::output_not_found(task, dep.output)];
			}
		};

		ret.insert(dep.clone());

		let mut errors = Vec::new();
		for runtime_dep in &output.runtime_depends {
			match ctx.output_ref(runtime_dep, &task.args, false) {
				Ok(output_ref) => {
					for mut error in add_dep(ret, ctx, output_ref) {
						error.extend(task);
						errors.push(error);
					}
				}
				Err(err) => {
					let mut err: Error = err.into();
					err.extend(task);
					errors.push(err);
				}
			};
		}
		errors
	}

	let mut ret = HashSet::new();
	let mut errors = Vec::new();

	for dep in deps {
		errors.extend(add_dep(&mut ret, ctx, dep));
	}

	if !errors.is_empty() {
		return Err(errors);
	}

	Ok(ret)
}

pub fn get_dependent_outputs<'ctx>(
	ctx: &'ctx Context,
	task_ref: &TaskRef<'ctx>,
) -> Result<HashSet<OutputRef<'ctx>>, Vec<Error<'ctx>>> {
	let deps: HashSet<_> = ctx
		.get_build_depends(task_ref)
		.map_err(|err| vec![err.into()])?
		.into_iter()
		.chain(
			ctx.get_host_depends(task_ref)
				.map_err(|err| vec![err.into()])?
				.into_iter(),
		)
		.collect();
	runtime_depends(ctx, deps)
}

pub fn get_dependent_tasks<'ctx>(
	ctx: &'ctx Context,
	task_ref: &TaskRef<'ctx>,
) -> Result<HashSet<TaskRef<'ctx>>, Vec<Error<'ctx>>> {
	Ok(ctx
		.get_inherit_depend(task_ref)
		.map_err(|err| vec![err.into()])?
		.into_iter()
		.chain(
			get_dependent_outputs(ctx, task_ref)?
				.into_iter()
				.map(|dep| dep.task),
		)
		.collect())
}

#[derive(Debug)]
pub struct Resolver<'ctx> {
	ctx: &'ctx Context,
	resolve_state: HashMap<TaskRef<'ctx>, ResolveState>,
}

impl<'ctx> Resolver<'ctx> {
	pub fn new(ctx: &'ctx Context) -> Self {
		Resolver {
			ctx,
			resolve_state: HashMap::new(),
		}
	}

	fn tasks_resolved(&self) -> bool {
		self.resolve_state
			.values()
			.all(|resolved| *resolved == ResolveState::Resolved)
	}

	fn add_task(&mut self, task: &TaskRef<'ctx>, output: Option<&'ctx str>) -> Vec<Error<'ctx>> {
		match self.resolve_state.get(task) {
			Some(ResolveState::Resolving) => return vec![Error::dependency_cycle(task)],
			Some(ResolveState::Resolved) => return vec![],
			None => (),
		}

		let task_def = match self.ctx.get(task) {
			Ok(task_def) => task_def,
			Err(err) => return vec![err.into()],
		};

		if let Some(task_output) = output {
			if !task_def.output.contains_key(task_output) {
				return vec![Error::output_not_found(task, task_output)];
			}
		}

		self.resolve_state
			.insert(task.clone(), ResolveState::Resolving);

		let mut ret = Vec::new();
		let mut handle_errors = |errors: Vec<Error<'ctx>>| {
			for mut error in errors {
				error.extend(task);
				ret.push(error);
			}
		};

		match self.ctx.get_inherit_depend(task) {
			Ok(Some(inherit)) => {
				handle_errors(self.add_task(&inherit, None));
			}
			Ok(None) => {}
			Err(err) => {
				handle_errors(vec![err.into()]);
			}
		}

		match get_dependent_outputs(self.ctx, task) {
			Ok(rdeps) => {
				for rdep in rdeps {
					handle_errors(self.add_task(&rdep.task, Some(rdep.output)));
				}
			}
			Err(errors) => {
				handle_errors(errors);
			}
		}

		if ret.is_empty() {
			*self
				.resolve_state
				.get_mut(task)
				.expect("Missing resolve_state") = ResolveState::Resolved;
		} else {
			self.resolve_state.remove(task);
		}

		ret
	}

	pub fn add_goal(&mut self, task: &TaskRef<'ctx>) -> Vec<Error<'ctx>> {
		let ret = self.add_task(task, None);
		debug_assert!(self.tasks_resolved());
		ret
	}

	pub fn into_taskset(self) -> HashSet<TaskRef<'ctx>> {
		debug_assert!(self.tasks_resolved());

		self.resolve_state
			.into_iter()
			.map(|entry| entry.0)
			.collect()
	}
}