-
Notifications
You must be signed in to change notification settings - Fork 595
/
NextflowDSLImpl.groovy
1314 lines (1108 loc) · 53.1 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-2019, Centre for Genomic Regulation (CRG)
*
* 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 org.codehaus.groovy.ast.tools.GeneralUtils.*
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import nextflow.script.BaseScript
import nextflow.script.IncludeDef
import nextflow.script.TaskBody
import nextflow.script.TaskClosure
import nextflow.script.TokenEnvCall
import nextflow.script.TokenFileCall
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.ConstructorNode
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.ConstructorCallExpression
import org.codehaus.groovy.ast.expr.DeclarationExpression
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.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.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 {
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 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)
}
/**
* Creates a statement that invokes the {@link nextflow.script.ScriptMeta#setProcessNames(java.util.List)} (java.util.List)} method
* used to initialize the script with metadata collected during script parsing
*
* @return The method invocation statement
*/
protected Statement makeSetProcessNamesStm() {
final names = new ListExpression()
for( String it: processNames ) {
names.addExpression(new ConstantExpression(it.toString()))
}
// the method list argument
final args = new ArgumentListExpression()
args.addExpression(names)
// some magic code
// this generates the invocation of the method:
// nextflow.script.ScriptMeta.get(this).setProcessNames(<list of process names>)
final scriptMeta = new PropertyExpression( new PropertyExpression(new VariableExpression('nextflow'),'script'), 'ScriptMeta')
final thiz = new ArgumentListExpression(); thiz.addExpression( new VariableExpression('this') )
final meta = new MethodCallExpression( scriptMeta, 'get', thiz )
final call = new MethodCallExpression( meta, 'setProcessNames', args)
final stm = new ExpressionStatement(call)
return stm
}
/**
* Add to constructor a method call to inject parsed metadata
*
* @param node
*/
protected void injectMetadata(ClassNode node) {
for( ConstructorNode constructor : node.getDeclaredConstructors() ) {
def code = constructor.getCode()
if( code instanceof BlockStatement ) {
code.addStatement(makeSetProcessNamesStm())
}
else if( code instanceof ExpressionStatement ) {
def expr = code
def block = new BlockStatement()
block.addStatement(expr)
block.addStatement(makeSetProcessNamesStm())
constructor.setCode(block)
}
else
throw new IllegalStateException("Invalid constructor expression: $code")
}
}
@Override
protected void visitObjectInitializerStatements(ClassNode node) {
if( node.getSuperClass().getName() == BaseScript.getName() )
injectMetadata(node)
super.visitObjectInitializerStatements(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
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, 'load', new ArgumentListExpression())
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( newObj(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 = newObj(TokenVar, new ConstantExpression(component))
// create a new `IncludeDef` object
newArgs.addExpression(newObj(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 = newObj(TokenVar, new ConstantExpression(component))
// the alias to give it
final alias = constX(cast.type.name)
newArgs.addExpression( newObj(IncludeDef, token, alias) )
}
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 (ch1, ch2) {
* code
* }
*
* into a method invocation as
*
* workflow('foo', ['ch1':ch1, 'ch2':ch2], { -> 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( makeWorkflowBodyWrapper(body) )
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 == 0 || !(args[len-1] instanceof ClosureExpression)) {
syntaxError(methodCall, "Invalid workflow definition -- Missing definition block")
return
}
final body = (ClosureExpression)args[len-1]
newArgs.addExpression( makeWorkflowBodyWrapper(body) )
newArgs.addExpression( constX(name) )
newArgs.addExpression( makeArgsList(args) )
// set the new list as the new arguments
methodCall.setArguments( newArgs )
}
protected Expression makeWorkflowBodyWrapper( ClosureExpression closure ) {
// make a copy to clear closure implicit `it` parameter
def copy = new ClosureExpression(null, closure.code)
def buffer = new StringBuilder()
def block = (BlockStatement) closure.code
for( Statement stm : block.getStatements() )
readSource(stm, buffer, unit)
makeScriptWrapper(copy, buffer.toString(), 'workflow', unit)
}
protected void syntaxError(ASTNode node, String message) {
int line = node.lineNumber
int coln = node.columnNumber
unit.addError( new SyntaxException(message,line,coln))
}
protected ListExpression makeArgsList(ArgumentListExpression args) {
def result = new ArrayList<Expression>()
for( int i=0; i<args.size()-1; i++) {
def expr = args.getExpression(i)
if( expr instanceof VariableExpression ) {
def varX = expr as VariableExpression
result.add(constX(varX.name))
}
else {
throw new IllegalArgumentException("Unexpected input expression: $expr")
}
}
return new ListExpression(result)
}
/**
* 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()
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':
iterator.remove()
execStatements << stm
readSource(stm,source,unit)
break
case 'script':
case 'shell':
iterator.remove()
execStatements << stm
readSource(stm,source,unit)
break
// capture the statements in a when guard and remove from the current block
case '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)
}
/*
* 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, currentLabel, 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)
}
// set the 'script' flag
currentLabel = 'script'
}
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 void addWhenGuardCall( 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
def newArgs = []
newArgs << closure
newArgs << new ConstantExpression(source.toString())
def whenObj = newObj( TaskClosure, newArgs as Object[] )
// creates a method call expression for the method `when`
def method = new MethodCallExpression(VariableExpression.THIS_EXPRESSION, 'when', whenObj)
parent.getStatements().add(0, new ExpressionStatement(method))
}
/**
* Wrap the user provided piece of code, either a script or a closure with a {@code TaskBody} object
*
* @param closure
* @param source
* @param scriptOrNative
* @param unit
* @return a {@code TaskBody} object
*/
private Expression makeScriptWrapper( ClosureExpression closure, CharSequence source, String section, SourceUnit unit ) {
final newArgs = []
newArgs << (closure)
newArgs << ( new ConstantExpression(source.toString()) )
newArgs << ( new ConstantExpression(section) )
final variables = fetchVariables(closure,unit)
for( TokenValRef var: variables ) {
def pName = new ConstantExpression(var.name)
def pLine = new ConstantExpression(var.lineNum)
def pCol = new ConstantExpression(var.colNum)
newArgs << newObj( TokenValRef, pName, pLine, pCol )
}
// invokes the TaskBody constructor
newObj( TaskBody, newArgs as Object[] )
}
/**
* Read the user provided script source string
*
* @param statement
* @param buffer
* @param unit
*/
private void readSource( Statement statement, StringBuilder buffer, SourceUnit unit ) {
def line = statement.getLineNumber()
def last = statement.getLastLineNumber()
for( int i=line; i<=last; i++ ) {
buffer.append( unit.source.getLine(i, null) ) .append('\n')
}
}
@Deprecated
protected void fixGuards( Statement stm, SourceUnit unit ) {
if( stm instanceof ExpressionStatement && stm.getExpression() instanceof MethodCallExpression ) {
def method = stm.getExpression() as MethodCallExpression
if( method.arguments instanceof ArgumentListExpression ) {
def args = method.arguments as ArgumentListExpression
if( args.size() == 1 && args.getExpression(0) instanceof ClosureExpression ) {
// read the source code of the closure
def closure = args.getExpression(0) as ClosureExpression
def source = new StringBuilder()
readSource(closure.getCode(), source, unit)
// wrap the closure expression by a TaskClosure object invocation
def wrap = newObj( TaskClosure, closure, new ConstantExpression(source.toString()) )
// replace it with the original closure argument
args.expressions.set(0, wrap)
}
}
}
}
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)`
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 )
}
}
}
}
}
/*
* 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'] ) {
//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') ) {
withinFileMethod = true
varToConst(methodCall.getArguments())
withinFileMethod = false
}
// 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
}
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','file','set','stdout'] && !nested ) {
// prefix the method name with the string '_out_'
methodCall.setMethod( new ConstantExpression('_out_' + methodName) )
fixMethodCall(methodCall)
}
else if( methodName in ['into','mode'] ) {
fixMethodCall(methodCall)
}
// continue to traverse
if( methodCall.objectExpression instanceof MethodCallExpression ) {
convertOutputMethod(methodCall.objectExpression)
}
}
private boolean withinSetMethod
private boolean withinFileMethod
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
withinSetMethod = name == '_in_set' || name == '_out_set'
withinFileMethod = name == '_in_file' || name == '_out_file'
withinEachMethod = name == '_in_each'
try {
if( isOutputValWithPropertyExpression(methodCall) )
// transform an output value declaration such
// output: val( obj.foo )
// to
// output: val({ obj.foo })
wrapPropertyToClosure((ArgumentListExpression)methodCall.getArguments())
else
varToConst(methodCall.getArguments())
} finally {
withinSetMethod = false
withinFileMethod = false
withinEachMethod = false
}
}
protected boolean isOutputValWithPropertyExpression(MethodCallExpression methodCall) {
if( methodCall.methodAsString != '_out_val' )
return false
if( methodCall.getArguments() instanceof ArgumentListExpression ) {
def args = (ArgumentListExpression)methodCall.getArguments()
if( args.size() != 1 )
return false
return args.getExpression(0) instanceof PropertyExpression
}
return false
}
protected void wrapPropertyToClosure(ArgumentListExpression expr) {
def args = expr as ArgumentListExpression
def property = (PropertyExpression) args.getExpression(0)
def closure = wrapPropertyToClosure(property)
args.getExpressions().set(0, closure)
}
protected ClosureExpression wrapPropertyToClosure(PropertyExpression property) {
def block = new BlockStatement()
block.addStatement( new ExpressionStatement(property) )
def closure = new ClosureExpression( Parameter.EMPTY_ARRAY, block )
closure.variableScope = new VariableScope(block.variableScope)
return closure
}
protected Expression varToStr( Expression expr ) {
if( expr instanceof VariableExpression ) {
def name = ((VariableExpression) expr).getName()
return newObj( TokenVar, new ConstantExpression(name) )
}
else if( expr instanceof PropertyExpression ) {
// transform an output declaration such
// output: set val( obj.foo )
// to
// output: set val({ obj.foo })
return wrapPropertyToClosure(expr)
}
if( expr instanceof TupleExpression ) {
def i = 0
def list = expr.getExpressions()
for( Expression item : list ) {
list[i++] = varToStr(item)
}
return expr
}
return expr
}
protected Expression varToConst( Expression expr ) {
if( expr instanceof VariableExpression ) {
// when it is a variable expression, replace it with a constant representing
// the variable name
def name = ((VariableExpression) expr).getName()
/*
* the 'stdin' is used as placeholder for the standard input in the set definition. For example:
*
* input:
* set( stdin, .. ) from q
*/
if( name == 'stdin' && withinSetMethod )
return newObj( TokenStdinCall )
/*
* input:
* set( stdout, .. )
*/
else if ( name == 'stdout' && withinSetMethod )
return newObj( TokenStdoutCall )
else
return newObj( TokenVar, new ConstantExpression(name) )
}
if( expr instanceof MethodCallExpression ) {
def methodCall = expr as MethodCallExpression
/*
* replace 'file' method call in the set definition, for example:
*
* input:
* set( file(fasta:'*.fa'), .. ) from q
*/
if( methodCall.methodAsString == 'file' && (withinSetMethod || withinEachMethod) ) {
def args = (TupleExpression) varToConst(methodCall.arguments)
return newObj( TokenFileCall, args )
}
/*
* input:
* set( env(VAR_NAME) ) from q
*/
if( methodCall.methodAsString == 'env' && withinSetMethod ) {
def args = (TupleExpression) varToStr(methodCall.arguments)
return newObj( TokenEnvCall, args )
}
/*
* input:
* set val(x), .. from q
*/
if( methodCall.methodAsString == 'val' && withinSetMethod ) {
def args = (TupleExpression) varToStr(methodCall.arguments)
return newObj( TokenValCall, args )
}
}
// -- TupleExpression or ArgumentListExpression
if( expr instanceof TupleExpression ) {
def i = 0
def list = expr.getExpressions()
for( Expression item : list ) {
list[i++] = varToConst(item)
}
return expr
}
return expr
}
/**
* Creates a new {@code ConstructorCallExpression} for the specified class and arguments
*
* @param clazz The {@code Class} for which the create a constructor call expression
* @param args The arguments to be passed to the constructor
* @return The instance for the constructor call
*/
protected Expression newObj( Class clazz, TupleExpression args ) {
def type = new ClassNode(clazz)
return new ConstructorCallExpression(type,args)
}
/**
* Creates a new {@code ConstructorCallExpression} for the specified class and arguments
* specified using an open array. Te
*
* @param clazz The {@code Class} for which the create a constructor call expression
* @param args The arguments to be passed to the constructor, they will be wrapped by in a {@code ArgumentListExpression}
* @return The instance for the constructor call
*/
protected Expression newObj( Class clazz, Object... params ) {
def type = new ClassNode(clazz)
def args = new ArgumentListExpression( params as List<Expression>)
return new ConstructorCallExpression(type,args)
}
/**
* Wrap a generic expression with in a closure expression
*
* @param block The block to which the resulting closure has to be appended