-
Notifications
You must be signed in to change notification settings - Fork 598
/
NextflowDSLImpl.groovy
1282 lines (1097 loc) · 54.4 KB
/
NextflowDSLImpl.groovy
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
/*
* Copyright 2013-2024, Seqera Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nextflow.ast
import static nextflow.Const.*
import static nextflow.ast.ASTHelpers.*
import static org.codehaus.groovy.ast.tools.GeneralUtils.*
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import nextflow.NF
import nextflow.script.BaseScript
import nextflow.script.BodyDef
import nextflow.script.IncludeDef
import nextflow.script.TaskClosure
import nextflow.script.TokenEvalCall
import nextflow.script.TokenEnvCall
import nextflow.script.TokenFileCall
import nextflow.script.TokenPathCall
import nextflow.script.TokenStdinCall
import nextflow.script.TokenStdoutCall
import nextflow.script.TokenValCall
import nextflow.script.TokenValRef
import nextflow.script.TokenVar
import org.codehaus.groovy.ast.ASTNode
import org.codehaus.groovy.ast.ClassCodeVisitorSupport
import org.codehaus.groovy.ast.ClassNode
import org.codehaus.groovy.ast.MethodNode
import org.codehaus.groovy.ast.Parameter
import org.codehaus.groovy.ast.VariableScope
import org.codehaus.groovy.ast.expr.ArgumentListExpression
import org.codehaus.groovy.ast.expr.BinaryExpression
import org.codehaus.groovy.ast.expr.CastExpression
import org.codehaus.groovy.ast.expr.ClosureExpression
import org.codehaus.groovy.ast.expr.ConstantExpression
import org.codehaus.groovy.ast.expr.Expression
import org.codehaus.groovy.ast.expr.GStringExpression
import org.codehaus.groovy.ast.expr.ListExpression
import org.codehaus.groovy.ast.expr.MapEntryExpression
import org.codehaus.groovy.ast.expr.MapExpression
import org.codehaus.groovy.ast.expr.MethodCallExpression
import org.codehaus.groovy.ast.expr.PropertyExpression
import org.codehaus.groovy.ast.expr.TupleExpression
import org.codehaus.groovy.ast.expr.UnaryMinusExpression
import org.codehaus.groovy.ast.expr.VariableExpression
import org.codehaus.groovy.ast.stmt.BlockStatement
import org.codehaus.groovy.ast.stmt.ExpressionStatement
import org.codehaus.groovy.ast.stmt.ReturnStatement
import org.codehaus.groovy.ast.stmt.Statement
import org.codehaus.groovy.control.CompilePhase
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.syntax.SyntaxException
import org.codehaus.groovy.syntax.Token
import org.codehaus.groovy.syntax.Types
import org.codehaus.groovy.transform.ASTTransformation
import org.codehaus.groovy.transform.GroovyASTTransformation
/**
* Implement some syntax sugars of Nextflow DSL scripting.
*
* @author Paolo Di Tommaso <paolo.ditommaso@gmail.com>
*/
@Slf4j
@CompileStatic
@GroovyASTTransformation(phase = CompilePhase.CONVERSION)
class NextflowDSLImpl implements ASTTransformation {
final static private String WORKFLOW_TAKE = 'take'
final static private String WORKFLOW_EMIT = 'emit'
final static private String WORKFLOW_MAIN = 'main'
final static private List<String> SCOPES = [WORKFLOW_TAKE, WORKFLOW_EMIT, WORKFLOW_MAIN]
final static public String PROCESS_WHEN = 'when'
final static public String PROCESS_STUB = 'stub'
static public String OUT_PREFIX = '$out'
static private Set<String> RESERVED_NAMES
static {
// method names implicitly defined by the groovy script SHELL
RESERVED_NAMES = ['main','run','runScript'] as Set
// existing method cannot be used for custom script definition
for( def method : BaseScript.getMethods() ) {
RESERVED_NAMES.add(method.name)
}
}
@Override
void visit(ASTNode[] astNodes, SourceUnit unit) {
createVisitor(unit).visitClass((ClassNode)astNodes[1])
}
/*
* create the code visitor
*/
protected ClassCodeVisitorSupport createVisitor( SourceUnit unit ) {
new DslCodeVisitor(unit)
}
@CompileStatic
static class DslCodeVisitor extends ClassCodeVisitorSupport {
final private SourceUnit unit
private String currentTaskName
private String currentLabel
private String bodyLabel
private Set<String> processNames = []
private Set<String> workflowNames = []
private Set<String> functionNames = []
private int anonymousWorkflow
protected SourceUnit getSourceUnit() { unit }
DslCodeVisitor(SourceUnit unit) {
this.unit = unit
}
@Override
void visitMethod(MethodNode node) {
if( node.public && !node.static && !node.synthetic && !node.metaDataMap?.'org.codehaus.groovy.ast.MethodNode.isScriptBody') {
if( !isIllegalName(node.name, node))
functionNames.add(node.name)
}
super.visitMethod(node)
}
@Override
void visitMethodCallExpression(MethodCallExpression methodCall) {
// pre-condition to be verified to apply the transformation
final preCondition = methodCall.objectExpression?.getText() == 'this'
final methodName = methodCall.getMethodAsString()
/*
* intercept the *process* method in order to transform the script closure
*/
if( methodName == 'process' && preCondition ) {
// clear block label
bodyLabel = null
currentLabel = null
currentTaskName = methodName
try {
convertProcessDef(methodCall,sourceUnit)
super.visitMethodCallExpression(methodCall)
}
finally {
currentTaskName = null
}
}
else if( methodName == 'workflow' && preCondition ) {
convertWorkflowDef(methodCall,sourceUnit)
super.visitMethodCallExpression(methodCall)
}
// just apply the default behavior
else {
super.visitMethodCallExpression(methodCall)
}
}
@Override
void visitExpressionStatement(ExpressionStatement stm) {
if( stm.text.startsWith('this.include(') && stm.getExpression() instanceof MethodCallExpression ) {
final methodCall = (MethodCallExpression)stm.getExpression()
convertIncludeDef(methodCall)
// this is necessary to invoke the `load` method on the include definition
final loadCall = new MethodCallExpression(methodCall, 'load0', new ArgumentListExpression(new VariableExpression('params')))
stm.setExpression(loadCall)
}
super.visitExpressionStatement(stm)
}
protected void convertIncludeDef(MethodCallExpression call) {
if( call.methodAsString=='include' && call.arguments instanceof ArgumentListExpression ) {
final allArgs = (ArgumentListExpression)call.arguments
if( allArgs.size() != 1 ) {
syntaxError(call, "Not a valid include definition -- it must specify the module path")
return
}
final arg = allArgs[0]
final newArgs = new ArgumentListExpression()
if( arg instanceof ConstantExpression ) {
newArgs.addExpression( createX(IncludeDef, arg) )
}
else if( arg instanceof VariableExpression ) {
// the name of the component i.e. process, workflow, etc to import
final component = arg.getName()
// wrap the name in a `TokenVar` type
final token = createX(TokenVar, new ConstantExpression(component))
// create a new `IncludeDef` object
newArgs.addExpression(createX(IncludeDef, token))
}
else if( arg instanceof CastExpression && arg.getExpression() instanceof VariableExpression) {
def cast = (CastExpression)arg
// the name of the component i.e. process, workflow, etc to import
final component = (cast.expression as VariableExpression).getName()
// wrap the name in a `TokenVar` type
final token = createX(TokenVar, new ConstantExpression(component))
// the alias to give it
final alias = constX(cast.type.name)
newArgs.addExpression( createX(IncludeDef, token, alias) )
}
else if( arg instanceof ClosureExpression ) {
// multiple modules inclusion
final block = (BlockStatement)arg.getCode()
final modulesList = new ListExpression()
for( Statement stm : block.statements ) {
if( stm instanceof ExpressionStatement ) {
CastExpression castX
VariableExpression varX
Expression moduleX
if( (varX=isVariableX(stm.expression)) ) {
def name = constX(varX.name)
moduleX = createX(IncludeDef.Module, name)
}
else if( (castX=isCastX(stm.expression)) && (varX=isVariableX(castX.expression)) ) {
def name = constX(varX.name)
final alias = constX(castX.type.name)
moduleX = createX(IncludeDef.Module, name, alias)
}
else {
syntaxError(call, "Not a valid include module name")
return
}
modulesList.addExpression(moduleX)
}
else {
syntaxError(call, "Not a valid include module name")
return
}
}
newArgs.addExpression( createX(IncludeDef, modulesList) )
}
else {
syntaxError(call, "Not a valid include definition -- it must specify the module path as a string")
return
}
call.setArguments(newArgs)
}
else if( call.objectExpression instanceof MethodCallExpression ) {
convertIncludeDef((MethodCallExpression)call.objectExpression)
}
}
/*
* this method transforms the DSL definition
*
* workflow foo {
* code
* }
*
* into a method invocation as
*
* workflow('foo', { -> code })
*
*/
protected void convertWorkflowDef(MethodCallExpression methodCall, SourceUnit unit) {
log.trace "Convert 'workflow' ${methodCall.arguments}"
assert methodCall.arguments instanceof ArgumentListExpression
def args = (ArgumentListExpression)methodCall.arguments
def len = args.size()
// anonymous workflow definition
if( len == 1 && args[0] instanceof ClosureExpression ) {
if( anonymousWorkflow++ > 0 ) {
unit.addError( new SyntaxException("Duplicate entry workflow definition", methodCall.lineNumber, methodCall.columnNumber+8))
return
}
def newArgs = new ArgumentListExpression()
def body = (ClosureExpression)args[0]
newArgs.addExpression( makeWorkflowDefWrapper(body,true) )
methodCall.setArguments( newArgs )
return
}
// extract the first argument which has to be a method-call expression
// the name of this method represent the *workflow* name
if( len != 1 || !args[0].class.isAssignableFrom(MethodCallExpression) ) {
log.debug "Missing name in workflow definition at line: ${methodCall.lineNumber}"
unit.addError( new SyntaxException("Workflow definition syntax error -- A string identifier must be provided after the `workflow` keyword", methodCall.lineNumber, methodCall.columnNumber+8))
return
}
final nested = args[0] as MethodCallExpression
final name = nested.getMethodAsString()
// check the process name is not defined yet
if( isIllegalName(name, methodCall) ) {
return
}
workflowNames.add(name)
// the nested method arguments are the arguments to be passed
// to the process definition, plus adding the process *name*
// as an extra item in the arguments list
args = (ArgumentListExpression)nested.getArguments()
len = args.size()
log.trace "Workflow name: $name with args: $args"
// make sure to add the 'name' after the map item
// (which represent the named parameter attributes)
def newArgs = new ArgumentListExpression()
// add the workflow body def
if( len != 1 || !(args[0] instanceof ClosureExpression)) {
syntaxError(methodCall, "Invalid workflow definition")
return
}
final body = (ClosureExpression)args[0]
newArgs.addExpression( constX(name) )
newArgs.addExpression( makeWorkflowDefWrapper(body,false) )
// set the new list as the new arguments
methodCall.setArguments( newArgs )
}
protected Statement normWorkflowParam(ExpressionStatement stat, String type, Set<String> uniqueNames, List<Statement> body) {
MethodCallExpression callx
VariableExpression varx
if( (callx=isMethodCallX(stat.expression)) && isThisX(callx.objectExpression) ) {
final name = "_${type}_${callx.methodAsString}"
return stmt( callThisX(name, callx.arguments) )
}
if( (varx=isVariableX(stat.expression)) ) {
final name = "_${type}_${varx.name}"
return stmt( callThisX(name) )
}
if( type == WORKFLOW_EMIT ) {
return createAssignX(stat, body, type, uniqueNames)
}
syntaxError(stat, "Workflow malformed parameter definition")
return stat
}
protected Statement createAssignX(ExpressionStatement stat, List<Statement> body, String type, Set<String> uniqueNames) {
BinaryExpression binx
MethodCallExpression callx
Expression args=null
if( (binx=isAssignX(stat.expression)) ) {
// keep the statement in body to allow it to be evaluated
body.add(stat)
// and create method call expr to capture the var name in the emission
final left = (VariableExpression)binx.leftExpression
final name = "_${type}_${left.name}"
return stmt( callThisX(name) )
}
if( (callx=isMethodCallX(stat.expression)) && callx.objectExpression.text!='this' && hasTo(callx)) {
// keep the args
args = callx.arguments
// replace the method call expression with a property
stat.expression = new PropertyExpression(callx.objectExpression, callx.method)
// then, fallback to default case
}
// wrap the expression into a assignment expression
final var = getNextName(uniqueNames)
final left = new VariableExpression(var)
final right = stat.expression
final token = new Token(Types.ASSIGN, '=', -1, -1)
final assign = new BinaryExpression(left, token, right)
body.add(stmt(assign))
// the call method statement for the emit declaration
final name="_${type}_${var}"
callx = args ? callThisX(name, args) : callThisX(name)
return stmt(callx)
}
protected boolean hasTo(MethodCallExpression callX) {
def tupleX = isTupleX(callX.arguments)
if( !tupleX ) return false
if( !tupleX.expressions ) return false
def mapX = isMapX(tupleX.expressions[0])
if( !mapX ) return false
def entry = mapX.getMapEntryExpressions().find { isConstX(it.keyExpression).text=='to' }
return entry != null
}
protected String getNextName(Set<String> allNames) {
String result
while( true ) {
result = OUT_PREFIX + allNames.size()
if( allNames.add(result) )
break
}
return result
}
protected Expression makeWorkflowDefWrapper( ClosureExpression closure, boolean anonymous ) {
final codeBlock = (BlockStatement) closure.code
final codeStms = codeBlock.statements
final scope = codeBlock.variableScope
final visited = new HashMap<String,Boolean>(5);
final emitNames = new LinkedHashSet<String>(codeStms.size())
final wrap = new ArrayList<Statement>(codeStms.size())
final body = new ArrayList<Statement>(codeStms.size())
final source = new StringBuilder()
String context = null
String previous = null
for( Statement stm : codeStms ) {
previous = context
context = stm.statementLabel ?: context
// check for changing context
if( context && context != previous ) {
if( visited[context] && visited[previous] ) {
syntaxError(stm, "Unexpected workflow `${context}` context here")
break
}
}
visited[context] = true
switch (context) {
case WORKFLOW_TAKE:
case WORKFLOW_EMIT:
if( !(stm instanceof ExpressionStatement) ) {
syntaxError(stm, "Workflow malformed parameter definition")
break
}
wrap.add(normWorkflowParam(stm as ExpressionStatement, context, emitNames, body))
break
case WORKFLOW_MAIN:
body.add(stm)
break
default:
if( context ) {
def opts = SCOPES.closest(context)
def msg = "Unknown execution scope '$context:'"
if( opts ) msg += " -- Did you mean ${opts.collect{"'$it'"}.join(', ')}"
syntaxError(stm, msg)
}
body.add(stm)
}
}
// read the closure source
readSource(closure, source, unit, true)
final bodyClosure = closureX(null, block(scope, body))
final invokeBody = makeScriptWrapper(bodyClosure, source.toString(), 'workflow', unit)
wrap.add( stmt(invokeBody) )
closureX(null, block(scope, wrap))
}
protected void syntaxError(ASTNode node, String message) {
int line = node.lineNumber
int coln = node.columnNumber
unit.addError( new SyntaxException(message,line,coln))
}
/**
* Transform a DSL `process` definition into a proper method invocation
*
* @param methodCall
* @param unit
*/
protected void convertProcessBlock( MethodCallExpression methodCall, SourceUnit unit ) {
log.trace "Apply task closure transformation to method call: $methodCall"
final args = methodCall.arguments as ArgumentListExpression
final lastArg = args.expressions.size()>0 ? args.getExpression(args.expressions.size()-1) : null
final isClosure = lastArg instanceof ClosureExpression
if( isClosure ) {
// the block holding all the statements defined in the process (closure) definition
final block = (lastArg as ClosureExpression).code as BlockStatement
/*
* iterate over the list of statements to:
* - converts the method after the 'input:' label as input parameters
* - converts the method after the 'output:' label as output parameters
* - collect all the statement after the 'exec:' label
*/
def source = new StringBuilder()
List<Statement> execStatements = []
List<Statement> whenStatements = []
def whenSource = new StringBuilder()
List<Statement> stubStatements = []
def stubSource = new StringBuilder()
def iterator = block.getStatements().iterator()
while( iterator.hasNext() ) {
// get next statement
Statement stm = iterator.next()
// keep track of current block label
currentLabel = stm.statementLabel ?: currentLabel
switch(currentLabel) {
case 'input':
if( stm instanceof ExpressionStatement ) {
fixLazyGString( stm )
fixStdinStdout( stm )
convertInputMethod( stm.getExpression() )
}
break
case 'output':
if( stm instanceof ExpressionStatement ) {
fixLazyGString( stm )
fixStdinStdout( stm )
convertOutputMethod( stm.getExpression() )
}
break
case 'exec':
bodyLabel = currentLabel
iterator.remove()
execStatements << stm
readSource(stm,source,unit)
break
case 'script':
case 'shell':
bodyLabel = currentLabel
iterator.remove()
execStatements << stm
readSource(stm,source,unit)
break
case PROCESS_STUB:
iterator.remove()
stubStatements << stm
readSource(stm,stubSource,unit)
break
// capture the statements in a when guard and remove from the current block
case PROCESS_WHEN:
if( iterator.hasNext() ) {
iterator.remove()
whenStatements << stm
readSource(stm,whenSource,unit)
break
}
// when entering in this branch means that this is the last statement,
// which is supposed to be the task command
// hence if no previous `when` statement has been processed, a syntax error is returned
else if( !whenStatements ) {
int line = methodCall.lineNumber
int coln = methodCall.columnNumber
unit.addError(new SyntaxException("Invalid process definition -- Empty `when` or missing `script` statement", line, coln))
return
}
else
break
default:
if(currentLabel) {
def line = stm.getLineNumber()
def coln = stm.getColumnNumber()
unit.addError(new SyntaxException("Invalid process definition -- Unknown keyword `$currentLabel`",line,coln))
return
}
fixLazyGString(stm)
fixDirectiveWithNegativeValue(stm) // Fixes #180
}
}
/*
* add the `when` block if found
*/
if( whenStatements ) {
addWhenGuardCall(whenStatements, whenSource, block)
}
/*
* add try `stub` block if found
*/
if( stubStatements ) {
final newBLock = addStubCall(stubStatements, stubSource, block)
newBLock.visit(new TaskCmdXformVisitor(unit))
}
/*
* wrap all the statements after the 'exec:' label by a new closure containing them (in a new block)
*/
final len = block.statements.size()
boolean done = false
if( execStatements ) {
// create a new Closure
def execBlock = new BlockStatement(execStatements, new VariableScope(block.variableScope))
def execClosure = new ClosureExpression( Parameter.EMPTY_ARRAY, execBlock )
// append the new block to the
// set the 'script' flag parameter
def wrap = makeScriptWrapper(execClosure, source, bodyLabel, unit)
block.addStatement( new ExpressionStatement(wrap) )
if( bodyLabel == 'script' )
block.visit(new TaskCmdXformVisitor(unit))
done = true
}
// when only the `stub` block is defined add an empty command
else if ( !bodyLabel && stubStatements ) {
final cmd = 'true'
final list = new ArrayList<Statement>(1);
list.add( new ExpressionStatement(constX(cmd)) )
final dummyBlock = new BlockStatement( list, new VariableScope(block.variableScope))
final dummyClosure = new ClosureExpression( Parameter.EMPTY_ARRAY, dummyBlock )
// append the new block to the
// set the 'script' flag parameter
final wrap = makeScriptWrapper(dummyClosure, cmd, 'script', unit)
block.addStatement( new ExpressionStatement(wrap) )
done = true
}
/*
* when the last statement is a string script, the 'script:' label can be omitted
*/
else if( len ) {
def stm = block.getStatements().get(len-1)
readSource(stm,source,unit)
if ( stm instanceof ReturnStatement ){
done = wrapExpressionWithClosure(block, stm.getExpression(), len, source, unit)
}
else if ( stm instanceof ExpressionStatement ) {
done = wrapExpressionWithClosure(block, stm.getExpression(), len, source, unit)
}
// apply command variables escape
stm.visit(new TaskCmdXformVisitor(unit))
}
if (!done) {
log.trace "Invalid 'process' definition -- Process must terminate with string expression"
int line = methodCall.lineNumber
int coln = methodCall.columnNumber
unit.addError( new SyntaxException("Invalid process definition -- Make sure the process ends with a script wrapped by quote characters",line,coln))
}
}
}
/**
* Converts a `when` block into a when method call expression. The when code is converted into a
* closure expression and set a `when` directive in the process configuration properties.
*
* See {@link nextflow.script.ProcessConfig#configProperties}
* See {@link nextflow.processor.TaskConfig#getGuard(java.lang.String)}
*/
protected BlockStatement addWhenGuardCall( List<Statement> statements, StringBuilder source, BlockStatement parent ) {
createBlock0(PROCESS_WHEN, statements, source, parent)
}
protected BlockStatement addStubCall(List<Statement> statements, StringBuilder source, BlockStatement parent ) {
createBlock0(PROCESS_STUB, statements, source, parent)
}
protected BlockStatement createBlock0( String blockName, List<Statement> statements, StringBuilder source, BlockStatement parent ) {
// wrap the code block into a closure expression
def block = new BlockStatement(statements, new VariableScope(parent.variableScope))
def closure = new ClosureExpression( Parameter.EMPTY_ARRAY, block )
// the closure expression is wrapped itself into a TaskClosure object
// in order to capture the closure source other than the closure code
List<Expression> newArgs = []
newArgs << closure
newArgs << new ConstantExpression(source.toString())
def whenObj = createX( TaskClosure, newArgs )
// creates a method call expression for the method `when`
def method = new MethodCallExpression(VariableExpression.THIS_EXPRESSION, blockName, whenObj)
parent.getStatements().add(0, new ExpressionStatement(method))
return block
}
/**
* Wrap the user provided piece of code, either a script or a closure with a {@code BodyDef} object
*
* @param closure
* @param source
* @param scriptOrNative
* @param unit
* @return a {@code BodyDef} object
*/
private Expression makeScriptWrapper( ClosureExpression closure, CharSequence source, String section, SourceUnit unit ) {
final List<Expression> newArgs = []
newArgs << (closure)
newArgs << ( new ConstantExpression(source.toString()) )
newArgs << ( new ConstantExpression(section) )
// collect all variable tokens and pass them as single list argument
final variables = fetchVariables(closure,unit)
final listArg = new ArrayList(variables.size())
for( TokenValRef var: variables ) {
def pName = new ConstantExpression(var.name)
def pLine = new ConstantExpression(var.lineNum)
def pCol = new ConstantExpression(var.colNum)
listArg << createX( TokenValRef, pName, pLine, pCol )
}
newArgs << ( new ListExpression(listArg) )
// invokes the BodyDef constructor
createX( BodyDef, newArgs )
}
/**
* Read the user provided script source string
*
* @param node
* @param buffer
* @param unit
*/
private void readSource( ASTNode node, StringBuilder buffer, SourceUnit unit, stripBrackets=false ) {
final colx = node.getColumnNumber()
final colz = node.getLastColumnNumber()
final first = node.getLineNumber()
final last = node.getLastLineNumber()
for( int i=first; i<=last; i++ ) {
def line = unit.source.getLine(i, null)
if( i==last ) {
line = line.substring(0,colz-1)
if( stripBrackets ) {
line = line.replaceFirst(/}.*$/,'')
if( !line.trim() ) continue
}
}
if( i==first ) {
line = line.substring(colx-1)
if( stripBrackets ) {
line = line.replaceFirst(/^.*\{/,'').trim()
if( !line.trim() ) continue
}
}
buffer.append(line) .append('\n')
}
}
protected void fixLazyGString( Statement stm ) {
if( stm instanceof ExpressionStatement && stm.getExpression() instanceof MethodCallExpression ) {
new GStringToLazyVisitor(unit).visitExpressionStatement(stm)
}
}
protected void fixDirectiveWithNegativeValue( Statement stm ) {
if( stm instanceof ExpressionStatement && stm.getExpression() instanceof BinaryExpression ) {
def binary = (BinaryExpression)stm.getExpression()
if(!(binary.leftExpression instanceof VariableExpression))
return
if( binary.operation.type != Types.MINUS )
return
// -- transform the binary expression into a method call expression
// where the left expression represents the method name to invoke
def methodName = ((VariableExpression)binary.leftExpression).name
// -- wrap the value into a minus operator
def value = (Expression)new UnaryMinusExpression( binary.rightExpression )
def args = new ArgumentListExpression( [value] )
// -- create the method call expression and replace it to the binary expression
def call = new MethodCallExpression(new VariableExpression('this'), methodName, args)
stm.setExpression(call)
}
}
protected void fixStdinStdout( ExpressionStatement stm ) {
// transform the following syntax:
// `stdin from x` --> stdin() from (x)
// `stdout into x` --> `stdout() into (x)`
VariableExpression varX
if( stm.expression instanceof PropertyExpression ) {
def expr = (PropertyExpression)stm.expression
def obj = expr.objectExpression
def prop = expr.property as ConstantExpression
def target = new VariableExpression(prop.text)
if( obj instanceof MethodCallExpression ) {
def methodCall = obj as MethodCallExpression
if( 'stdout' == methodCall.getMethodAsString() ) {
def stdout = new MethodCallExpression( new VariableExpression('this'), 'stdout', new ArgumentListExpression() )
def into = new MethodCallExpression(stdout, 'into', new ArgumentListExpression(target))
// remove replace the old one with the new one
stm.setExpression( into )
}
else if( 'stdin' == methodCall.getMethodAsString() ) {
def stdin = new MethodCallExpression( new VariableExpression('this'), 'stdin', new ArgumentListExpression() )
def from = new MethodCallExpression(stdin, 'from', new ArgumentListExpression(target))
// remove replace the old one with the new one
stm.setExpression( from )
}
}
}
// transform the following syntax:
// `stdout into (x,y,..)` --> `stdout() into (x,y,..)`
else if( stm.expression instanceof MethodCallExpression ) {
def methodCall = (MethodCallExpression)stm.expression
if( 'stdout' == methodCall.getMethodAsString() ) {
def args = methodCall.getArguments()
if( args instanceof ArgumentListExpression && args.getExpressions() && args.getExpression(0) instanceof MethodCallExpression ) {
def methodCall2 = (MethodCallExpression)args.getExpression(0)
def args2 = methodCall2.getArguments()
if( args2 instanceof ArgumentListExpression && methodCall2.methodAsString == 'into') {
def vars = args2.getExpressions()
def stdout = new MethodCallExpression( new VariableExpression('this'), 'stdout', new ArgumentListExpression() )
def into = new MethodCallExpression(stdout, 'into', new ArgumentListExpression(vars))
// remove replace the old one with the new one
stm.setExpression( into )
}
}
}
}
else if( (varX=isVariableX(stm.expression)) && (varX.name=='stdin' || varX.name=='stdout') && NF.isDsl2() ) {
final name = varX.name=='stdin' ? '_in_stdin' : '_out_stdout'
final call = new MethodCallExpression( new VariableExpression('this'), name, new ArgumentListExpression() )
// remove replace the old one with the new one
stm.setExpression(call)
}
}
/*
* handle *input* parameters
*/
protected void convertInputMethod( Expression expression ) {
log.trace "convert > input expression: $expression"
if( expression instanceof MethodCallExpression ) {
def methodCall = expression as MethodCallExpression
def methodName = methodCall.getMethodAsString()
def nested = methodCall.objectExpression instanceof MethodCallExpression
log.trace "convert > input method: $methodName"
if( methodName in ['val','env','file','each','set','stdin','path','tuple'] ) {
//this methods require a special prefix
if( !nested )
methodCall.setMethod( new ConstantExpression('_in_' + methodName) )
fixMethodCall(methodCall)
}
/*
* Handles a GString a file name, like this:
*
* input:
* file x name "$var_name" from q
*
*/
else if( methodName == 'name' && isWithinMethod(expression, 'file') ) {
varToConstX(methodCall.getArguments())
}
// invoke on the next method call
if( expression.objectExpression instanceof MethodCallExpression ) {
convertInputMethod(methodCall.objectExpression)
}
}
else if( expression instanceof PropertyExpression ) {
// invoke on the next method call
if( expression.objectExpression instanceof MethodCallExpression ) {
convertInputMethod(expression.objectExpression)
}
}
}
protected boolean isWithinMethod(MethodCallExpression method, String name) {
if( method.objectExpression instanceof MethodCallExpression ) {
return isWithinMethod(method.objectExpression as MethodCallExpression, name)
}
return method.getMethodAsString() == name
}
/**
* Transform a map entry `emit: something` into `emit: 'something'
* and `topic: something` into `topic: 'something'
* (ie. as a constant) in a map expression passed as argument to
* a method call. This allow the syntax
*
* output:
* path 'foo', emit: bar, topic: baz
*
* @param call
*/
protected void fixOutEmitAndTopicOptions(MethodCallExpression call) {
List<Expression> args = isTupleX(call.arguments)?.expressions
if( !args ) return
if( args.size()<2 && (args.size()!=1 || call.methodAsString!='_out_stdout')) return
MapExpression map = isMapX(args[0])
if( !map ) return
for( int i=0; i<map.mapEntryExpressions.size(); i++ ) {
final entry = map.mapEntryExpressions[i]
final key = isConstX(entry.keyExpression)
final val = isVariableX(entry.valueExpression)
if( key?.text == 'emit' && val ) {
map.mapEntryExpressions[i] = new MapEntryExpression(key, constX(val.text))
}
else if( key?.text == 'topic' && val ) {
map.mapEntryExpressions[i] = new MapEntryExpression(key, constX(val.text))
}
}
}
protected void convertOutputMethod( Expression expression ) {
log.trace "convert > output expression: $expression"
if( !(expression instanceof MethodCallExpression) ) {
return
}
def methodCall = expression as MethodCallExpression
def methodName = methodCall.getMethodAsString()
def nested = methodCall.objectExpression instanceof MethodCallExpression
log.trace "convert > output method: $methodName"
if( methodName in ['val','env','eval','file','set','stdout','path','tuple'] && !nested ) {
// prefix the method name with the string '_out_'
methodCall.setMethod( new ConstantExpression('_out_' + methodName) )
fixMethodCall(methodCall)
fixOutEmitAndTopicOptions(methodCall)
}
else if( methodName in ['into','mode'] ) {
fixMethodCall(methodCall)
}
// continue to traverse
if( methodCall.objectExpression instanceof MethodCallExpression ) {
convertOutputMethod(methodCall.objectExpression)
}
}
private boolean withinTupleMethod
private boolean withinEachMethod
/**
* This method converts the a method call argument from a Variable to a Constant value
* so that it is possible to reference variable that not yet exist
*
* @param methodCall The method object for which it is required to change args definition
* @param flagVariable Whenever append a flag specified if the variable replacement has been applied
* @param index The index of the argument to modify
* @return
*/
protected void fixMethodCall( MethodCallExpression methodCall ) {
final name = methodCall.methodAsString
withinTupleMethod = name == '_in_set' || name == '_out_set' || name == '_in_tuple' || name == '_out_tuple'
withinEachMethod = name == '_in_each'
try {
if( isOutputWithPropertyExpression(methodCall) ) {
// transform an output value declaration such
// output: val( obj.foo )
// to