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
use std::collections::{HashMap, HashSet};
use std::iter::{self, FromIterator};
use std::path::{Path, PathBuf};
use crate::analysis::{Kind, ModusSemantics};
use crate::logic::{Clause, IRTerm, Literal, Predicate};
use crate::modusfile::{self, Modusfile};
use crate::sld::{self, ClauseId, Proof, ResolutionError};
use crate::translate::translate_modusfile;
use crate::unification::Substitute;
use codespan_reporting::diagnostic::Diagnostic;
use serde::{Deserialize, Serialize};
const MODUS_LABEL: &str = "com.modus-continens.literal";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuildPlan {
pub nodes: Vec<BuildNode>,
pub dependencies: Vec<Vec<NodeId>>,
pub outputs: Vec<Output>,
}
impl BuildPlan {
pub fn new() -> BuildPlan {
BuildPlan {
nodes: Vec::new(),
dependencies: Vec::new(),
outputs: Vec::new(),
}
}
pub fn new_node(&mut self, node: BuildNode, deps: Vec<NodeId>) -> NodeId {
let id = self.nodes.len();
self.nodes.push(node);
self.dependencies.push(
HashSet::<_>::from_iter(deps.into_iter())
.into_iter()
.collect(),
);
debug_assert_eq!(self.nodes.len(), self.dependencies.len());
id
}
pub fn topological_order(&self) -> Vec<NodeId> {
let mut topological_order = Vec::with_capacity(self.nodes.len());
let mut seen = vec![false; self.nodes.len()];
fn dfs(
plan: &BuildPlan,
node: NodeId,
topological_order: &mut Vec<NodeId>,
seen: &mut Vec<bool>,
) {
if seen[node] {
return;
}
for &deps in plan.dependencies[node].iter() {
dfs(plan, deps, topological_order, seen);
}
topological_order.push(node);
seen[node] = true;
}
for output in self.outputs.iter() {
dfs(&self, output.node, &mut topological_order, &mut seen);
}
topological_order
}
}
#[derive(Debug)]
struct State {
current_node: Option<NodeId>,
cwd: String,
current_merge: Option<MergeNode>,
additional_envs: HashMap<String, String>,
}
impl State {
fn with_new_cwd<F: FnOnce(&mut Self)>(&mut self, new_cwd: String, f: F) {
let old_cwd = std::mem::replace(&mut self.cwd, new_cwd);
f(self);
self.cwd = old_cwd;
}
fn with_new_merge<F: FnOnce(&mut Self)>(&mut self, new_merge: MergeNode, f: F) -> MergeNode {
debug_assert!(self.current_merge.is_none());
self.current_merge = Some(new_merge);
f(self);
self.current_merge.take().unwrap()
}
fn has_base(&self) -> bool {
self.current_merge.is_some() || self.current_node.is_some()
}
fn set_node(&mut self, node: NodeId) {
debug_assert!(self.current_merge.is_none());
self.current_node = Some(node);
}
fn with_additional_envs<E: IntoIterator<Item = (String, String)>, F: FnOnce(&mut Self)>(
&mut self,
envs: E,
f: F,
) {
let old_envs = self.additional_envs.clone();
self.additional_envs.extend(envs);
f(self);
self.additional_envs = old_envs;
}
}
pub type NodeId = usize;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BuildNode {
From {
image_ref: String,
display_name: String,
},
FromScratch {
scratch_ref: Option<String>,
},
Run {
parent: NodeId,
command: String,
cwd: String,
additional_envs: HashMap<String, String>,
},
CopyFromImage {
parent: NodeId,
src_image: NodeId,
src_path: String,
dst_path: String,
},
CopyFromLocal {
parent: NodeId,
src_path: String,
dst_path: String,
},
SetWorkdir {
parent: NodeId,
new_workdir: String,
},
SetEntrypoint {
parent: NodeId,
new_entrypoint: Vec<String>,
},
SetLabel {
parent: NodeId,
label: String,
value: String,
},
Merge(MergeNode),
SetEnv {
parent: NodeId,
key: String,
value: String,
},
AppendEnvValue {
parent: NodeId,
key: String,
value: String,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MergeNode {
pub parent: NodeId,
pub operations: Vec<MergeOperation>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MergeOperation {
Run {
command: String,
cwd: String,
additional_envs: HashMap<String, String>,
},
CopyFromImage {
src_image: NodeId,
src_path: String,
dst_path: String,
},
CopyFromLocal {
src_path: String,
dst_path: String,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Output {
pub node: NodeId,
#[serde(skip)]
pub source_literal: Option<Literal>,
}
pub fn build_dag_from_proofs(
query_and_proofs: &[(Literal, Proof)],
rules: &Vec<Clause<IRTerm>>,
) -> BuildPlan {
let mut res = BuildPlan::new();
let mut image_literals: HashMap<Literal, NodeId> = HashMap::new();
fn process_image(
subtree: &[&Proof],
rules: &Vec<Clause<IRTerm>>,
res: &mut BuildPlan,
image_literals: &mut HashMap<Literal, NodeId>,
tag_with_literal: Option<String>,
) -> Option<NodeId> {
let mut curr_state = State {
current_node: None,
cwd: "".to_string(),
current_merge: None,
additional_envs: HashMap::new(),
};
fn process_tree(
proof: &Proof,
rules: &Vec<Clause<IRTerm>>,
res: &mut BuildPlan,
image_literals: &mut HashMap<Literal, NodeId>,
curr_state: &mut State,
) {
match proof.clause {
ClauseId::Query => {}
ClauseId::Builtin(ref intrinsic) => {
process_intrinsic(intrinsic, res, image_literals, curr_state);
debug_assert!(proof.children.is_empty());
return;
}
ClauseId::Rule(rid) => {
let substituted_lit = rules[rid].head.substitute(&proof.valuation);
debug_assert!(substituted_lit
.args
.iter()
.all(|x| x.as_constant().is_some()));
if !curr_state.has_base() {
if let Some(&node_id) = image_literals.get(&substituted_lit) {
curr_state.set_node(node_id);
return;
} else {
if let Some(node_id) = process_image(
&proof.children.iter().collect::<Vec<_>>()[..],
rules,
res,
image_literals,
Some(substituted_lit.to_string()),
) {
curr_state.set_node(node_id);
image_literals.insert(substituted_lit, node_id);
return;
} else {
return;
}
}
} else {
}
}
ClauseId::NegationCheck(_) => {}
}
process_children(
&proof.children.iter().collect::<Vec<_>>(),
rules,
res,
image_literals,
curr_state,
);
}
fn process_intrinsic(
intrinsic: &Literal,
res: &mut BuildPlan,
image_literals: &mut HashMap<Literal, NodeId>,
curr_state: &mut State,
) {
let name = &intrinsic.predicate.0[..];
assert!(!name.starts_with("_operator_"));
match name {
"from" => {
if curr_state.current_merge.is_some() {
panic!("You can not generate a new image inside a merge.");
}
if curr_state.has_base() {
panic!("from must be the first build instruction.");
}
if let Some(&existing_node) = image_literals.get(&intrinsic) {
curr_state.set_node(existing_node);
} else {
let image_ref = intrinsic.args[0].as_constant().unwrap().to_owned();
let new_node;
if &image_ref == "scratch" {
new_node =
res.new_node(BuildNode::FromScratch { scratch_ref: None }, vec![]);
} else {
new_node = res.new_node(
BuildNode::From {
display_name: image_ref.clone(),
image_ref,
},
vec![],
);
}
curr_state.set_node(new_node);
image_literals.insert(intrinsic.clone(), new_node);
}
}
"run" => {
let command = intrinsic.args[0].as_constant().unwrap().to_owned();
if let Some(ref mut curr_merge) = curr_state.current_merge {
curr_merge.operations.push(MergeOperation::Run {
command,
cwd: curr_state.cwd.clone(),
additional_envs: curr_state.additional_envs.clone(),
});
} else {
if !curr_state.has_base() {
panic!("No base layer yet.");
}
let parent = curr_state.current_node.unwrap();
curr_state.set_node(res.new_node(
BuildNode::Run {
parent: parent,
command: command,
cwd: curr_state.cwd.clone(),
additional_envs: curr_state.additional_envs.clone(),
},
vec![parent],
));
}
}
"copy" => {
let src_path = intrinsic.args[0].as_constant().unwrap().to_owned();
if src_path.starts_with("/") {
panic!("The source of a local copy can not be an absolute path.");
}
let dst_path = intrinsic.args[1].as_constant().unwrap();
let dst_path = join_path(&curr_state.cwd, dst_path);
if let Some(ref mut curr_merge) = curr_state.current_merge {
curr_merge
.operations
.push(MergeOperation::CopyFromLocal { src_path, dst_path });
} else {
if !curr_state.has_base() {
panic!("No base layer yet.");
}
let parent = curr_state.current_node.unwrap();
curr_state.set_node(res.new_node(
BuildNode::CopyFromLocal {
parent,
src_path,
dst_path,
},
vec![parent],
));
}
}
_ => {
}
}
}
fn process_operator(
subtree_in_op: &[&Proof],
op_name: &str,
lit: &Literal,
rules: &Vec<Clause<IRTerm>>,
res: &mut BuildPlan,
image_literals: &mut HashMap<Literal, NodeId>,
curr_state: &mut State,
) {
match op_name {
"copy" => {
let src_image = process_image(subtree_in_op, rules, res, image_literals, None)
.expect("Stuff inside this copy does not build an image.");
let src_path = lit.args[1].as_constant().unwrap().to_owned();
let dst_path = join_path(&curr_state.cwd, lit.args[2].as_constant().unwrap());
if let Some(ref mut curr_merge) = curr_state.current_merge {
curr_merge.operations.push(MergeOperation::CopyFromImage {
src_image,
src_path,
dst_path,
});
} else {
let parent = curr_state.current_node.expect("No base layer yet.");
let node = res.new_node(
BuildNode::CopyFromImage {
parent,
src_image,
src_path,
dst_path,
},
vec![parent, src_image],
);
curr_state.set_node(node);
}
}
"in_workdir" => {
let new_p = lit.args[1].as_constant().unwrap();
let new_cwd = join_path(&curr_state.cwd, new_p);
curr_state.with_new_cwd(new_cwd, |new_state| {
process_children(subtree_in_op, rules, res, image_literals, new_state);
});
}
"set_workdir" => {
if curr_state.current_merge.is_some() {
panic!("You can not generate a new image inside a merge.");
}
let img = process_image(subtree_in_op, rules, res, image_literals, None)
.expect("set_workdir should be applied to an image.");
if curr_state.has_base() {
panic!("set_workdir generates a new image, so it should be the first instruction.");
}
let new_p = lit.args[1].as_constant().unwrap();
curr_state.set_node(res.new_node(
BuildNode::SetWorkdir {
parent: img,
new_workdir: join_path(&curr_state.cwd, new_p),
},
vec![img],
));
}
"set_entrypoint" => {
if curr_state.current_merge.is_some() {
panic!("You can not generate a new image inside a merge.");
}
let img = process_image(subtree_in_op, rules, res, image_literals, None)
.expect("set_entrypoint should be applied to an image.");
if curr_state.has_base() {
panic!("set_entrypoint generates a new image, so it should be the first instruction.");
}
let entrypoint = lit
.args
.iter()
.skip(1)
.map(|x| x.as_constant().unwrap().to_owned())
.collect::<Vec<_>>();
curr_state.set_node(res.new_node(
BuildNode::SetEntrypoint {
parent: img,
new_entrypoint: entrypoint,
},
vec![img],
));
}
"merge" => {
if curr_state.current_merge.is_some() {
process_children(subtree_in_op, rules, res, image_literals, curr_state);
return;
}
if !curr_state.has_base() {
panic!("merge requires a base layer outside.");
}
let parent = curr_state.current_node.unwrap();
let merge_node = MergeNode {
parent,
operations: vec![],
};
let merge_node = curr_state.with_new_merge(merge_node, |new_state| {
process_children(subtree_in_op, rules, res, image_literals, new_state);
});
let mut deps: Vec<NodeId> = merge_node
.operations
.iter()
.filter_map(|x| match x {
MergeOperation::CopyFromImage { src_image, .. } => Some(*src_image),
MergeOperation::CopyFromLocal { .. } | MergeOperation::Run { .. } => {
None
}
})
.collect();
deps.push(parent);
curr_state.set_node(res.new_node(BuildNode::Merge(merge_node), deps));
}
"set_env" => {
if curr_state.current_merge.is_some() {
panic!("You can not generate a new image inside a merge.");
}
let img = process_image(subtree_in_op, rules, res, image_literals, None)
.expect("set_env should be applied to an image.");
if curr_state.has_base() {
panic!(
"set_env generates a new image, so it should be the first instruction."
);
}
let env_k = lit.args[1].as_constant().unwrap().to_owned();
let env_v = lit.args[2].as_constant().unwrap().to_owned();
curr_state.set_node(res.new_node(
BuildNode::SetEnv {
parent: img,
key: env_k,
value: env_v,
},
vec![img],
));
}
"append_path" => {
if curr_state.current_merge.is_some() {
panic!("You can not generate a new image inside a merge.");
}
let img = process_image(subtree_in_op, rules, res, image_literals, None)
.expect("append_path should be applied to an image.");
if curr_state.has_base() {
panic!(
"append_path generates a new image, so it should be the first instruction."
);
}
let append = format!(":{}", lit.args[1].as_constant().unwrap());
curr_state.set_node(res.new_node(
BuildNode::AppendEnvValue {
parent: img,
key: "PATH".to_owned(),
value: append,
},
vec![img],
));
}
"in_env" => {
let env_k = lit.args[1].as_constant().unwrap().to_owned();
let env_v = lit.args[2].as_constant().unwrap().to_owned();
curr_state.with_additional_envs([(env_k, env_v)], |new_state| {
process_children(subtree_in_op, rules, res, image_literals, new_state);
});
}
_ => {
panic!("Unkown operator: {}", op_name);
}
}
}
fn process_children(
children: &[&Proof],
rules: &Vec<Clause<IRTerm>>,
res: &mut BuildPlan,
image_literals: &mut HashMap<Literal, NodeId>,
curr_state: &mut State,
) {
let mut i = 0usize;
while i < children.len() {
let child = children[i];
if let ClauseId::Builtin(ref lit) = child.clause {
let name = &lit.predicate.0;
if let Some(op_name) = name
.strip_prefix("_operator_")
.and_then(|s| s.strip_suffix("_begin"))
{
let end_name = format!("_operator_{}_end", op_name);
let pair_id = lit.args[0].as_constant().unwrap();
let mut j = i + 1;
while !{
if let ClauseId::Builtin(ref lit) = children[j].clause {
lit.predicate.0 == end_name
&& lit.args[0].as_constant() == Some(pair_id)
} else {
false
}
} {
j += 1;
}
let subtree_in_op = &children[i + 1..j];
process_operator(
subtree_in_op,
op_name,
lit,
rules,
res,
image_literals,
curr_state,
);
i = j + 1;
continue;
}
}
process_tree(child, rules, res, image_literals, curr_state);
i += 1;
}
}
process_children(subtree, rules, res, image_literals, &mut curr_state);
debug_assert!(curr_state.current_merge.is_none());
if curr_state.current_node.is_some() && tag_with_literal.is_some() {
let node = curr_state.current_node.unwrap();
let tagged_node = res.new_node(
BuildNode::SetLabel {
parent: node,
label: MODUS_LABEL.to_owned(),
value: tag_with_literal.unwrap().to_owned(),
},
vec![node],
);
curr_state.set_node(tagged_node);
}
curr_state.current_node
}
for (query, proof) in query_and_proofs.into_iter() {
debug_assert!(query.args.iter().all(|x| x.as_constant().is_some()));
if let Some(&existing_node_id) = image_literals.get(&query) {
res.outputs.push(Output {
node: existing_node_id,
source_literal: Some(query.clone()),
});
continue;
}
if let Some(node_id) = process_image(
&[proof],
rules,
&mut res,
&mut image_literals,
Some(query.to_string()),
) {
image_literals.insert(query.clone(), node_id);
res.outputs.push(Output {
node: node_id,
source_literal: Some(query.clone()),
});
} else {
panic!("{} does not resolve to any docker instructions.", query);
}
}
res
}
fn join_path(base: &str, path: &str) -> String {
match Path::new(base).join(path).to_str() {
Some(s) => s.to_owned(),
None => panic!("Path containing invalid utf-8 are not allowed."),
}
}
pub fn plan_from_modusfile(
mf: Modusfile,
query: modusfile::Expression,
) -> Result<BuildPlan, Vec<Diagnostic<()>>> {
fn validate_query_expression(query: &modusfile::Expression) -> Result<(), Vec<Diagnostic<()>>> {
match query {
modusfile::Expression::Literal(_) => Ok(()),
modusfile::Expression::OperatorApplication(_, _, _) => {
Err(vec![Diagnostic::error().with_message(
"Operators in queries are currently unsupported.",
)])
}
modusfile::Expression::And(_, _, e1, e2) | modusfile::Expression::Or(_, _, e1, e2) => {
validate_query_expression(e1)?;
validate_query_expression(e2)
}
}
}
fn get_image_literal(
query: &modusfile::Expression,
mf_with_query: &Modusfile,
ir_q_clause: &Clause,
) -> Result<Literal<IRTerm>, Vec<Diagnostic<()>>> {
let mut errs = Vec::new();
if let Err(mut es) = validate_query_expression(query) {
errs.append(&mut es);
}
let query_lits = query.literals();
let kind_res = mf_with_query.kinds();
let image_count = query_lits
.iter()
.filter(|query_lit| kind_res.pred_kind.get(&query_lit.predicate) == Some(&Kind::Image))
.count();
if image_count != 1 {
errs.push(Diagnostic::error().with_message(format!("There must be exactly one image predicate in the query, but {image_count} were found.")));
}
let layer_count = query_lits
.iter()
.filter(|query_lit| kind_res.pred_kind.get(&query_lit.predicate) == Some(&Kind::Layer))
.count();
if layer_count > 0 {
errs.push(Diagnostic::error().with_message(format!(
"Layer predicates in queries are currently unsupported, but we found {layer_count}"
)));
}
if !errs.is_empty() {
return Err(errs);
}
let expression_image_literal = query_lits
.iter()
.find(|lit| kind_res.pred_kind.get(&lit.predicate) == Some(&Kind::Image))
.unwrap();
let image_literal = ir_q_clause
.body
.iter()
.find(|lit| lit.predicate == expression_image_literal.predicate)
.expect("should find matching predicate name after translation");
Ok(image_literal.clone())
}
let max_depth = 175;
let goal_pred = Predicate("_query".to_owned());
let user_clause = modusfile::ModusClause {
head: Literal {
positive: true,
position: None,
predicate: goal_pred.clone(),
args: Vec::new(),
},
body: Some(query.clone()),
};
let mf_with_query = Modusfile(mf.0.into_iter().chain(iter::once(user_clause)).collect());
let ir_clauses: Vec<Clause> = translate_modusfile(&mf_with_query);
let q_clause = ir_clauses
.iter()
.find(|c| c.head.predicate == goal_pred)
.expect("should find same predicate name after translation");
let query_goal = &q_clause.body;
let image_literal = get_image_literal(&query, &mf_with_query, q_clause)?;
let success_tree = Result::from(sld::sld(&ir_clauses, &query_goal, max_depth, false))?;
let proofs = sld::proofs(&success_tree, &ir_clauses, &query_goal);
let query_and_proofs = proofs
.into_iter()
.map(|(_, p)| (image_literal.substitute(&p.valuation), p))
.collect::<Vec<_>>();
Ok(build_dag_from_proofs(&query_and_proofs[..], &ir_clauses))
}