forked from chanzuckerberg/miniwdl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree.py
More file actions
2138 lines (1852 loc) · 80.2 KB
/
Tree.py
File metadata and controls
2138 lines (1852 loc) · 80.2 KB
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
"""
Abstract syntax tree (AST) for WDL documents, containing tasks and workflows, which contain
declarations, calls, and scatter & if sections. The AST is typically constructed by
:func:`~WDL.load`.
The ``WDL.Tree.*`` classes are also exported by the base ``WDL`` module, i.e. ``WDL.Tree.Document``
can be abbreviated ``WDL.Document``.
.. inheritance-diagram:: WDL.Tree
"""
import os
import errno
import itertools
import asyncio
import hashlib
import base64
from typing import (
Any,
List,
Optional,
Dict,
Tuple,
Union,
Iterable,
Callable,
Generator,
Set,
NamedTuple,
Awaitable,
)
from abc import ABC, abstractmethod
from .Error import SourcePosition, SourceNode
from . import Type, Expr, Env, Error, StdLib, _parser, _util
class StructTypeDef(SourceNode):
"""WDL struct type definition"""
name: str
"""
:type: str
Name of the struct type (in the current document)
"""
members: Dict[str, Type.Base]
"""
:type: Dict[str, WDL.Type.Base]
Member names and types
"""
imported: "Optional[Tuple[Document,StructTypeDef]]"
"""
:type: Optional[Tuple[Document,StructTypeDef]]
If this struct is imported from another document, references that document and its definition
there. The referenced definition might itself be imported from yet another document.
"""
parameter_meta: Dict[str, Any]
""":type: Dict[str,Any]
``parameter_meta{}`` section as a JSON-like dict"""
meta: Dict[str, Any]
""":type: Dict[str,Any]
``meta{}`` section as a JSON-like dict"""
def __init__(
self,
pos: SourcePosition,
name: str,
members: Dict[str, Type.Base],
parameter_meta: Dict[str, Any],
meta: Dict[str, Any],
imported: "Optional[Tuple[Document,StructTypeDef]]" = None,
) -> None:
super().__init__(pos)
self.name = name
self.members = members
self.parameter_meta = parameter_meta
self.meta = meta
self.imported = imported
@property
def type_id(self) -> str:
"""
:type: str
A string canonically describing the member names and their types, excluding the struct type name; useful to
unify aliased struct types.
"""
return Type._struct_type_id(self.members)
class WorkflowNode(SourceNode, ABC):
"""
Base class for workflow "nodes" including declarations, calls, and scatter/if sections and
their bodies.
Each node has a human-readable ID string which is unique within the workflow. It also exposes
the set of workflow node IDs upon which it depends. Abstractly, workflow execution can proceed
by "visiting" each node once all of its dependencies have been visited, performing some
action(s) appropriate to the specific node type (such as evaluating a WDL expression and
binding a name in the environment, or executing a task and binding its outputs).
"""
workflow_node_id: str
"""
:type: str
Human-readable node ID unique within the current workflow
"""
scatter_depth: int
"""
:type: int
How many nested scatter sections the node lies within. This information is useful for runtime
dependency analysis in workflows with scatters. When scatter sections are nested within
conditional sections or vice versa, this counts the scatters only.
"""
_memo_workflow_node_dependencies: Optional[Set[str]] = None
def __init__(self, workflow_node_id: str, pos: SourcePosition):
super().__init__(pos)
self.workflow_node_id = workflow_node_id
self.scatter_depth = 0
@property
def workflow_node_dependencies(self) -> Set[str]:
"""
:type: Set[str]
Set of workflow node IDs on which this node depends. Available once workflow has been
typechecked.
"""
# in particular, requires all ident expressions have their referees resolved
# memoize
if self._memo_workflow_node_dependencies is None:
self._memo_workflow_node_dependencies = set(self._workflow_node_dependencies())
return self._memo_workflow_node_dependencies
@abstractmethod
def _workflow_node_dependencies(self) -> Iterable[str]:
# to be supplied by subclasses
raise NotImplementedError()
@abstractmethod
def add_to_type_env(
self, struct_types: Env.Bindings[Dict[str, Type.Base]], type_env: Env.Bindings[Type.Base]
) -> Env.Bindings[Type.Base]:
# typechecking helper -- add this node to the type environment; for sections, this includes
# everything in the section body as visible outside of the section.
raise NotImplementedError()
def _increment_scatter_depth(self) -> None:
for ch in self.children:
if isinstance(ch, WorkflowNode):
ch._increment_scatter_depth()
self.scatter_depth += 1
class Decl(WorkflowNode):
"""
A value declaration within a task or workflow.
Within a task, the declarations can be viewed as "workflow nodes" insofar as they must be
evaluated in an order consistent with their dependency structure, and ensured acyclic. The
"workflow node IDs" of a task's declarations are unique within the task only, and unrelated to
the top-level workflow, if any, in the WDL document.
"""
type: Type.Base
":type: WDL.Type.Base"
name: str
"""Declared value name
:type: str"""
expr: Optional[Expr.Base]
""":type: Optional[WDL.Expr.Base]
Bound expression, if any"""
decor: Dict[str, Any] # EXPERIMENTAL
""
def __init__(
self,
pos: SourcePosition,
type: Type.Base,
name: str,
expr: Optional[Expr.Base] = None,
id_prefix="decl",
) -> None:
super().__init__(id_prefix + "-" + name, pos)
self.type = type
self.name = name
self.expr = expr
self.decor = {}
def __str__(self) -> str:
if self.expr is None:
return "{} {}".format(str(self.type), self.name)
return "{} {} = {}".format(str(self.type), self.name, str(self.expr))
__repr__ = __str__
@property
def children(self) -> Iterable[SourceNode]:
""""""
if self.expr:
yield self.expr
def add_to_type_env(
self,
struct_types: Env.Bindings[Dict[str, Type.Base]],
type_env: Env.Bindings[Type.Base],
collision_ok: bool = False,
) -> Env.Bindings[Type.Base]:
# Add an appropriate binding in the type env, after checking for name
# collision.
if not collision_ok:
if self.name in type_env:
raise Error.MultipleDefinitions(self, "Multiple declarations of " + self.name)
if type_env.has_namespace(self.name):
raise Error.MultipleDefinitions(self, "Value/call name collision on " + self.name)
_resolve_struct_types(self.pos, self.type, struct_types)
if isinstance(self.type, Type.StructInstance):
return _add_struct_instance_to_type_env(self.name, self.type, type_env, ctx=self)
return type_env.bind(self.name, self.type, self)
def typecheck(
self,
type_env: Env.Bindings[Type.Base],
stdlib: StdLib.Base,
struct_types: Env.Bindings[Dict[str, Type.Base]],
check_quant: bool = True,
) -> None:
# Infer the expression's type and ensure it checks against the declared
# type. One time use!
if self.expr:
self.expr.infer_type(
type_env, stdlib, check_quant=check_quant, struct_types=struct_types
).typecheck(self.type)
def _workflow_node_dependencies(self) -> Iterable[str]:
yield from _expr_workflow_node_dependencies(self.expr)
class Task(SourceNode):
"""
WDL Task
"""
name: str
""":type: str"""
inputs: Optional[List[Decl]]
""":type: Optional[List[WDL.Tree.Decl]]
Declarations in the ``input{}`` task section, if it's present"""
postinputs: List[Decl]
""":type: List[WDL.Tree.Decl]
Declarations outside of the ``input{}`` task section"""
command: Expr.String
":type: WDL.Expr.String"
outputs: List[Decl]
""":type: List[WDL.Tree.Decl]
Output declarations"""
parameter_meta: Dict[str, Any]
""":type: Dict[str,Any]
``parameter_meta{}`` section as a JSON-like dict"""
runtime: Dict[str, Expr.Base]
""":type: Dict[str,WDL.Expr.Base]
``runtime{}`` section, with keys and corresponding expressions to be evaluated"""
requirements: Dict[str, Expr.Base]
""":type: Dict[str,WDL.Expr.Base]
``requirements{}`` section (for WDL 1.2+ tasks; refers to same dict as ``runtime``)"""
meta: Dict[str, Any]
""":type: Dict[str,Any]
``meta{}`` section as a JSON-like dict"""
effective_wdl_version: str
""":type: str
Effective WDL version of the containing document
"""
def __init__(
self,
pos: SourcePosition,
name: str,
inputs: Optional[List[Decl]],
postinputs: List[Decl],
command: Expr.String,
outputs: List[Decl],
parameter_meta: Dict[str, Any],
runtime: Dict[str, Expr.Base],
meta: Dict[str, Any],
) -> None:
super().__init__(pos)
self.name = name
self.inputs = inputs
self.postinputs = postinputs
self.command = command
self.outputs = outputs
self.parameter_meta = parameter_meta
self.runtime = runtime
self.requirements = self.runtime
self.meta = meta
self.effective_wdl_version = "1.0" # overridden by Document.__init__
# TODO: enforce validity constraints on parameter_meta and runtime
# TODO: if the input section exists, then all postinputs decls must be
# bound
@property
def available_inputs(self) -> Env.Bindings[Decl]:
""":type: WDL.Env.Bindings[WDL.Tree.Decl]
Yields the task's input declarations. This is all declarations in the
task's ``input{}`` section, if it's present. Otherwise, it's all
declarations in the task, excluding outputs. (This dichotomy bridges
pre-1.0 and 1.0+ WDL versions.)
Each input is at the top level of the Env, with no namespace.
"""
ans: Env.Bindings[Decl] = Env.Bindings()
if self.effective_wdl_version not in ("draft-2", "1.0"):
# synthetic placeholder to expose runtime overrides
ans = ans.bind("_runtime", Decl(self.pos, Type.Any(), "_runtime"))
for decl in reversed(self.inputs if self.inputs is not None else self.postinputs):
ans = ans.bind(decl.name, decl)
return ans
@property
def required_inputs(self) -> Env.Bindings[Decl]:
""":type: WDL.Env.Bindings[WDL.Tree.Decl]
Yields the input declarations which are required to call the task
(available inputs that are unbound and non-optional).
Each input is at the top level of the Env, with no namespace.
"""
ans: Env.Bindings[Decl] = Env.Bindings()
for b in reversed(list(self.available_inputs)):
assert isinstance(b, Env.Binding)
d: Decl = b.value
if d.expr is None and d.type.optional is False and not d.name.startswith("_"):
ans = Env.Bindings(b, ans)
return ans
@property
def effective_outputs(self) -> Env.Bindings[Type.Base]:
""":type: WDL.Env.Bindings[Type.Base]
Yields each task output with its type, at the top level of the Env with
no namespace. (Present for isomorphism with
``Workflow.effective_outputs``)
"""
ans: Env.Bindings[Type.Base] = Env.Bindings()
for decl in reversed(self.outputs):
ans = ans.bind(decl.name, decl.type, decl)
return ans
@property
def children(self) -> Iterable[SourceNode]:
""""""
for d in self.inputs or []:
yield d
for d in self.postinputs:
yield d
yield self.command
for d in self.outputs:
yield d
for _, ex in self.runtime.items():
yield ex
def typecheck(
self,
struct_types: Optional[Env.Bindings[Dict[str, Type.Base]]] = None,
check_quant: bool = True,
) -> None:
struct_types = struct_types or Env.Bindings()
# warm-up check: if input{} section exists then all postinput decls
# must be bound
if self.inputs is not None:
for decl in self.postinputs:
if not decl.type.optional and not decl.expr:
raise Error.StrayInputDeclaration(
self,
"unbound non-optional declaration {} {} outside task input{} section".format(
str(decl.type), decl.name, "{}"
),
)
# First collect a type environment for all the input & postinput
# declarations, so that we're prepared for possible forward-references
# in their right-hand side expressions.
type_env: Env.Bindings[Type.Base] = Env.Bindings()
for decl in (self.inputs or []) + self.postinputs:
type_env = decl.add_to_type_env(struct_types, type_env)
with Error.multi_context() as errors:
stdlib = StdLib.Base(self.effective_wdl_version)
# Pass through input & postinput declarations again, typecheck their
# right-hand side expressions against the type environment.
for decl in (self.inputs or []) + self.postinputs:
errors.try1(
lambda: decl.typecheck(
type_env, stdlib, check_quant=check_quant, struct_types=struct_types
)
)
# Typecheck the command (string)
errors.try1(
lambda: self.command.infer_type(
type_env, stdlib, check_quant=check_quant, struct_types=struct_types
).typecheck(Type.String())
)
for b in self.available_inputs:
errors.try1(lambda: _check_serializable_map_keys(b.value.type, b.name, b.value))
# Typecheck runtime expressions
for _, runtime_expr in self.runtime.items():
errors.try1(
(
lambda runtime_expr: lambda: runtime_expr.infer_type(
type_env, stdlib, check_quant=check_quant, struct_types=struct_types
)
)(runtime_expr)
) # .typecheck()
# (At this stage we don't care about the overall expression type, just that it
# typechecks internally.)
# Add output declarations to type environment
for decl in self.outputs:
type_env2 = errors.try1(
(lambda decl: lambda: decl.add_to_type_env(struct_types, type_env))(decl)
)
if type_env2:
type_env = type_env2
errors.maybe_raise()
# Typecheck the output expressions
stdlib = StdLib.TaskOutputs(self.effective_wdl_version)
for decl in self.outputs:
errors.try1(
lambda: decl.typecheck(type_env, stdlib, struct_types, check_quant=check_quant)
)
errors.try1(lambda: _check_serializable_map_keys(decl.type, decl.name, decl))
# check for cyclic dependencies among decls
_detect_cycles(
_decl_dependency_matrix([ch for ch in self.children if isinstance(ch, Decl)]) # type: ignore
)
_digest: str = ""
@property
def digest(self) -> str:
"""
Content digest of the task, for use e.g. as a cache key. The digest is an opaque string of
a few dozen alphanumeric characters, sensitive to the task's source code (with best effort
to exclude comments and whitespace).
"""
if self._digest:
return self._digest
sha256 = hashlib.sha256(self._digest_source().encode("utf-8")).digest()
self._digest = base64.b32encode(sha256[:20]).decode().lower()
return self._digest
def _digest_source(self) -> str:
doc = getattr(self, "parent", None)
assert isinstance(doc, Document)
# For now we just excerpt the task's source code, minus comments and blank lines, plus
# annotations for the WDL version and struct types.
source_lines = []
if doc.wdl_version:
source_lines.append("version " + doc.wdl_version)
# Insert comments describing struct types used in the task.
structs = _describe_struct_types(self)
for struct_name in sorted(structs.keys()):
source_lines.append(f"# {struct_name} :: {structs[struct_name]}")
# excerpt task{} from document
# Possible future improvements:
# excise the meta & parameter_meta sections
# normalize order of declarations
# normalize whitespace within lines (not leading/trailing)
source_lines += _source_excerpt(doc, self.pos, [self.command.pos])
return "\n".join(source_lines).strip()
class Call(WorkflowNode):
"""A call (within a workflow) to a task or sub-workflow"""
callee_id: List[str]
"""
:type: List[str]
The called task; either one string naming a task in the current document, or an import
namespace and task name.
"""
name: str
""":type: string
Call name, defaults to task/workflow name"""
after: List[str]
""":type: string
Call names on which this call depends (even if none of their outputs are used in this call's
inputs)
"""
_after_node_ids: Set[str]
inputs: Dict[str, Expr.Base]
"""
:type: Dict[str,WDL.Expr.Base]
Call inputs provided"""
callee: Optional[Union[Task, "Workflow"]]
"""
:type: Union[WDL.Tree.Task, WDL.Tree.Workflow]
Refers to the ``Task`` or imported ``Workflow`` object to be called (after AST typechecking)"""
def __init__(
self,
pos: SourcePosition,
callee_id: List[str],
alias: Optional[str],
inputs: Dict[str, Expr.Base],
after: Optional[List[str]] = None,
) -> None:
assert callee_id
self.callee_id = callee_id
self.name = alias if alias is not None else self.callee_id[-1]
super().__init__("call-" + self.name, pos)
self.inputs = inputs
self.callee = None
self.after = after if after is not None else list()
self._after_node_ids = set()
@property
def children(self) -> Iterable[SourceNode]:
""""""
for _, ex in self.inputs.items():
yield ex
def resolve(self, doc: "Document") -> None:
# Set self.callee to the Task/Workflow being called. Use exactly once
# prior to add_to_type_env() or typecheck_input()
if self.callee:
return
callee_doc = None
if len(self.callee_id) == 1:
callee_doc = doc
elif len(self.callee_id) == 2:
for imp in doc.imports:
if imp.namespace == self.callee_id[0]:
callee_doc = imp.doc
if callee_doc:
assert isinstance(callee_doc, Document)
wf = callee_doc.workflow
if isinstance(wf, Workflow) and wf.name == self.callee_id[-1]:
if callee_doc is doc:
raise Error.CircularDependencies(self)
if not wf.complete_calls or (wf.outputs is None and wf.effective_outputs):
raise Error.UncallableWorkflow(self, ".".join(self.callee_id))
self.callee = wf
else:
for task in callee_doc.tasks:
if task.name == self.callee_id[-1]:
self.callee = task
if self.callee is None:
raise Error.NoSuchTask(self, ".".join(self.callee_id))
assert doc.workflow
if self.name == doc.workflow.name:
raise Error.MultipleDefinitions(
self, "Call's name may not equal the containing workflow's"
)
assert isinstance(self.callee, (Task, Workflow))
def add_to_type_env(
self, struct_types: Env.Bindings[Dict[str, Type.Base]], type_env: Env.Bindings[Type.Base]
) -> Env.Bindings[Type.Base]:
# Add the call's outputs to the type environment under the appropriate
# namespace, after checking for namespace collisions.
assert self.callee
if self.name in type_env:
raise Error.MultipleDefinitions(self, "Value/call name collision on " + self.name)
if type_env.has_namespace(self.name):
raise Error.MultipleDefinitions(
self,
"Workflow has multiple calls named {}; give calls distinct names using `call {} as NAME ...`".format(
self.name, self.callee.name
),
)
# add a dummy _present binding to ensure the namespace exists even if callee has no outputs
return Env.merge(
self.effective_outputs, type_env.bind(self.name + "." + "_present", Type.Any(), self)
)
def typecheck_input(
self,
struct_types: Env.Bindings[Dict[str, Type.Base]],
type_env: Env.Bindings[Type.Base],
stdlib: StdLib.Base,
check_quant: bool,
) -> bool:
# Check the input expressions against the callee's inputs. One-time use.
# Returns True if the call supplies all required inputs, False otherwise.
assert self.callee
# first resolve each self.after to a node ID (possibly a Gather node)
for call_after in self.after:
try:
self._after_node_ids.add(
type_env.resolve_binding(call_after + "._present").info.workflow_node_id
)
except KeyError:
raise Error.NoSuchCall(self, call_after)
# Make a set of the input names which are required for this call
required_inputs = set(decl.name for decl in self.callee.required_inputs)
# typecheck call inputs against task/workflow input declarations
with Error.multi_context() as errors:
for name, expr in self.inputs.items():
try:
decl = self.callee.available_inputs[name]
# treat input with default as optional, with or without the ? type quantifier
decltype = decl.type.copy(optional=True) if decl.expr else decl.type
errors.try1(
(
lambda expr, decltype: lambda: expr.infer_type(
type_env, stdlib, check_quant=check_quant, struct_types=struct_types
).typecheck(decltype)
)(expr, decltype)
)
except KeyError:
errors.append(Error.NoSuchInput(expr, name))
if name in required_inputs:
required_inputs.remove(name)
assert (not required_inputs) == (not list(self.required_inputs))
return not required_inputs
@property
def available_inputs(self) -> Env.Bindings[Decl]:
""":type: WDL.Env.Bindings[WDL.Tree.Decl]
Yields the task/workflow inputs which are *not* supplied in the call
``inputs:``, and thus may be supplied at workflow launch; in namespaces
according to the call names.
"""
assert self.callee
supplied_inputs = set(self.inputs.keys())
return self.callee.available_inputs.filter(
lambda b: b.name not in supplied_inputs
).wrap_namespace(self.name)
@property
def required_inputs(self) -> Env.Bindings[Decl]:
""":type: WDL.Env.Bindings[WDL.Tree.Decl]
Yields the required task/workflow inputs which are *not* supplied in
the call ``inputs:`` (incomplete calls), and thus must be supplied at
workflow launch; in namespaces according to the call name.
"""
assert self.callee
supplied_inputs = set(self.inputs.keys())
return self.callee.required_inputs.filter(
lambda b: b.name not in supplied_inputs
).wrap_namespace(self.name)
@property
def effective_outputs(self) -> Env.Bindings[Type.Base]:
""":type: WDL.Env.Bindings[WDL.Tree.Decl]
Yields the effective outputs of the callee Task or Workflow, in a
namespace according to the call name.
"""
ans: Env.Bindings[Type.Base] = Env.Bindings()
assert self.callee
for outp in reversed(list(self.callee.effective_outputs)):
ans = ans.bind(self.name + "." + outp.name, outp.value, self)
return ans
def _workflow_node_dependencies(self) -> Iterable[str]:
assert (not self.after) == (not self._after_node_ids)
yield from self._after_node_ids
for expr in self.inputs.values():
yield from _expr_workflow_node_dependencies(expr)
class Gather(WorkflowNode):
"""
A ``Gather`` node symbolizes the operation to gather an array of declared values or call
outputs in a scatter section, or optional values from a conditional section. These operations
are implicit in the WDL syntax, but explicating them in the AST facilitates analysis of the
workflow's data types and dependency structure.
Each scatter/conditional section provides ``Gather`` nodes to expose the section body's
products to the rest of the workflow. When a :class:`WDL.Expr.Ident` elsewhere identifies a
node inside the section, its ``referee`` attribute is the corresponding ``Gather`` node, which
in turn references the interior node. The interior node might itself be another ``Gather``
node, from a nested scatter/conditional section.
"""
section: "WorkflowSection"
"""
:type: WorkflowSection
The ``Scatter``/``Conditional`` section implying this Gather operation
"""
referee: "Union[Decl, Call, Gather]"
"""
:type: Union[Decl, Call, Gather]
The ``Decl``, ``Call``, or sub-``Gather`` node from which this operation "gathers"
"""
def __init__(self, section: "WorkflowSection", referee: "Union[Decl, Call, Gather]") -> None:
super().__init__("gather-" + referee.workflow_node_id, referee.pos)
self.section = section
self.referee = referee
def add_to_type_env(
self, struct_types: Env.Bindings[Dict[str, Type.Base]], type_env: Env.Bindings[Type.Base]
) -> Env.Bindings[Type.Base]:
raise NotImplementedError()
def _workflow_node_dependencies(self) -> Iterable[str]:
yield self.referee.workflow_node_id
@property
def children(self) -> Iterable[SourceNode]:
""""""
# section & referee are NOT 'children' of Gather
return []
@property
def final_referee(self) -> Union[Decl, Call]:
"""
The ``Decl`` or ``Call`` node found at the end of the referee chain through any nested
``Gather`` nodes
"""
ans = self.referee
while isinstance(ans, Gather):
ans = ans.referee
assert isinstance(ans, (Decl, Call))
return ans
class WorkflowSection(WorkflowNode):
"""
Base class for workflow nodes representing scatter and conditional sections
"""
body: List[WorkflowNode]
"""
:type: List[WorkflowNode]
Section body, potentially including nested sections.
"""
gathers: Dict[str, Gather]
"""
:type: Dict[str, Gather]
``Gather`` nodes exposing the section body's products to the rest of the workflow. The dict is
keyed by ``workflow_node_id`` of the interior node, to expedite looking up the corresponding
gather node.
The section's body and gather nodes do not explicitly include the section node among their
dependencies. Such dependence is implicit because the body subgraph can be "instantiated" only
upon visiting the section node at runtime.
"""
_type_env: Optional[Env.Bindings[Type.Base]] = None
"""
After typechecking: the type environment, INSIDE the section, consisting of
- everything available outside of the section
- declarations and call outputs in the scatter (singletons)
- declarations & outputs gathered from sub-sections (arrays/optionals)
- the scatter variable, if applicable
"""
def __init__(self, body: List[WorkflowNode], *args, **kwargs):
super().__init__(*args, **kwargs)
self.body = body
# TODO: add dependency on self to each body node?
# populate gathers
self.gathers = dict()
for elt in self.body:
if isinstance(elt, (Decl, Call)):
# assert elt.workflow_node_id not in self.gathers
# ^ won't hold if the section has internal name collisions, which will be checked
# later upon building the type environment.
self.gathers[elt.workflow_node_id] = Gather(self, elt)
elif isinstance(elt, WorkflowSection):
# gather gathers!
for subgather in elt.gathers.values():
# assert subgather.workflow_node_id not in self.gathers
# id.
self.gathers[subgather.workflow_node_id] = Gather(self, subgather)
@property
def children(self) -> Iterable[SourceNode]:
""""""
for elt in self.body:
yield elt
for elt in self.gathers.values():
yield elt
@property
@abstractmethod
def effective_outputs(self) -> Env.Bindings[Type.Base]:
raise NotImplementedError()
class Scatter(WorkflowSection):
"""Workflow scatter section"""
variable: str
"""
:type: string
Scatter variable name"""
expr: Expr.Base
"""
:type: WDL.Expr.Base
Expression for the array over which to scatter"""
def __init__(
self, pos: SourcePosition, variable: str, expr: Expr.Base, body: List[WorkflowNode]
) -> None:
super().__init__(body, "scatter-L{}C{}-{}".format(pos.line, pos.column, variable), pos)
self.variable = variable
self.expr = expr
for body_node in self.body:
body_node._increment_scatter_depth()
# excluded our gather nodes, which are not "within" the section
@property
def children(self) -> Iterable[SourceNode]:
""""""
yield self.expr
yield from super().children
def add_to_type_env(
self, struct_types: Env.Bindings[Dict[str, Type.Base]], type_env: Env.Bindings[Type.Base]
) -> Env.Bindings[Type.Base]:
# Add declarations and call outputs in this section as they'll be
# available outside of the section (i.e. a declaration of type T is
# seen as Array[T] outside)
inner_type_env: Env.Bindings[Type.Base] = Env.Bindings()
for elt in self.body:
inner_type_env = elt.add_to_type_env(struct_types, inner_type_env)
# Subtlety: if the scatter array is statically nonempty, then so too
# are the arrayized values.
nonempty = isinstance(self.expr._type, Type.Array) and self.expr._type.nonempty
# array-ize each inner type binding and add gather nodes
def arrayize(binding: Env.Binding[Type.Base]) -> Env.Binding[Type.Base]:
return Env.Binding(
binding.name,
Type.Array(binding.value, nonempty=nonempty),
self.gathers[binding.info.workflow_node_id],
)
return Env.merge(inner_type_env.map(arrayize), type_env)
@property
def effective_outputs(self) -> Env.Bindings[Type.Base]:
# Yield the outputs of calls in this section and subsections, typed
# and namespaced appropriately, as they'll be propagated if the
# workflow lacks an explicit output{} section
nonempty = isinstance(self.expr._type, Type.Array) and self.expr._type.nonempty
inner_outputs: Env.Bindings[Type.Base] = Env.Bindings()
for elt in self.body:
if not isinstance(elt, Decl):
assert isinstance(elt, (Call, Scatter, Conditional))
inner_outputs = Env.merge(elt.effective_outputs, inner_outputs)
def arrayize(binding: Env.Binding[Type.Base]) -> Env.Binding[Type.Base]:
return Env.Binding(
binding.name,
Type.Array(binding.value, nonempty=nonempty),
self.gathers[binding.info.workflow_node_id],
)
return inner_outputs.map(arrayize)
def _workflow_node_dependencies(self) -> Iterable[str]:
yield from _expr_workflow_node_dependencies(self.expr)
class Conditional(WorkflowSection):
"""Workflow conditional (if) section"""
expr: Expr.Base
"""
:tree: WDL.Expr.Base
Boolean expression"""
def __init__(self, pos: SourcePosition, expr: Expr.Base, body: List[WorkflowNode]) -> None:
super().__init__(body, "if-L{}C{}".format(pos.line, pos.column), pos)
# TODO: add to id the name of 'shallowest' (closest to root) ident in expr
self.expr = expr
@property
def children(self) -> Iterable[SourceNode]:
""""""
yield self.expr
yield from super().children
def add_to_type_env(
self, struct_types: Env.Bindings[Dict[str, Type.Base]], type_env: Env.Bindings[Type.Base]
) -> Env.Bindings[Type.Base]:
# Add declarations and call outputs in this section as they'll be
# available outside of the section (i.e. a declaration of type T is
# seen as T? outside)
inner_type_env: Env.Bindings[Type.Base] = Env.Bindings()
for elt in self.body:
inner_type_env = elt.add_to_type_env(struct_types, inner_type_env)
# optional-ize each inner type binding and add gather nodes
def optionalize(binding: Env.Binding[Type.Base]) -> Env.Binding[Type.Base]:
return Env.Binding(
binding.name,
binding.value.copy(optional=True),
self.gathers[binding.info.workflow_node_id],
)
return Env.merge(inner_type_env.map(optionalize), type_env)
@property
def effective_outputs(self) -> Env.Bindings[Type.Base]:
# Yield the outputs of calls in this section and subsections, typed
# and namespaced appropriately, as they'll be propagated if the
# workflow lacks an explicit output{} section
inner_outputs: Env.Bindings[Type.Base] = Env.Bindings()
for elt in self.body:
if isinstance(elt, (Call, WorkflowSection)):
inner_outputs = Env.merge(elt.effective_outputs, inner_outputs)
def optionalize(binding: Env.Binding[Type.Base]) -> Env.Binding[Type.Base]:
return Env.Binding(
binding.name,
binding.value.copy(optional=True),
self.gathers[binding.info.workflow_node_id],
)
return inner_outputs.map(optionalize)
def _workflow_node_dependencies(self) -> Iterable[str]:
yield from _expr_workflow_node_dependencies(self.expr)
class Workflow(SourceNode):
name: str
":type: str"
inputs: Optional[List[Decl]]
""":type: List[WDL.Tree.Decl]
Declarations in the ``input{}`` workflow section, if it's present"""
body: List[WorkflowNode]
""":type: List[Union[WDL.Tree.Decl,WDL.Tree.Call,WDL.Tree.Scatter,WDL.Tree.Conditional]]
Workflow body in between ``input{}`` and ``output{}`` sections, if any
"""
outputs: Optional[List[Decl]]
""":type: Optional[List[WDL.Tree.Decl]]
Workflow output declarations, if the ``output{}`` section is present"""
# following two fields temporarily hold old-style (pre 1.0) outputs with
# bare identifiers or namespace wildcards. We postprocess them into
# full declarations as expected in WDL 1.0+.
_output_idents: List[List[str]]
_output_idents_pos: Optional[Error.SourcePosition]
parameter_meta: Dict[str, Any]
"""
:type: Dict[str,Any]