@@ -5,11 +5,13 @@ import { LuaLibFeature, importLuaLibFeature } from "../utils/lualib";
5
5
export function usingTransformer ( context : TransformationContext ) : ts . TransformerFactory < ts . SourceFile > {
6
6
return ctx => sourceFile => {
7
7
function visit ( node : ts . Node ) : ts . Node {
8
- if ( ts . isBlock ( node ) ) {
8
+ if ( ts . isBlock ( node ) || ts . isSourceFile ( node ) ) {
9
9
const [ hasUsings , newStatements ] = transformBlockWithUsing ( context , node . statements , node ) ;
10
10
if ( hasUsings ) {
11
11
// Recurse visitor into updated block to find further usings
12
- const updatedBlock = ts . factory . updateBlock ( node , newStatements ) ;
12
+ const updatedBlock = ts . isBlock ( node )
13
+ ? ts . factory . updateBlock ( node , newStatements )
14
+ : ts . factory . updateSourceFile ( node , newStatements ) ;
13
15
const result = ts . visitEachChild ( updatedBlock , visit , ctx ) ;
14
16
15
17
// Set all the synthetic node parents to something that makes sense
@@ -29,7 +31,8 @@ export function usingTransformer(context: TransformationContext): ts.Transformer
29
31
}
30
32
return ts . visitEachChild ( node , visit , ctx ) ;
31
33
}
32
- return ts . visitEachChild ( sourceFile , visit , ctx ) ;
34
+ const transformedSourceFile = ts . visitEachChild ( sourceFile , visit , ctx ) ;
35
+ return visit ( transformedSourceFile ) as ts . SourceFile ;
33
36
} ;
34
37
}
35
38
@@ -40,7 +43,7 @@ function isUsingDeclarationList(node: ts.Node): node is ts.VariableStatement {
40
43
function transformBlockWithUsing (
41
44
context : TransformationContext ,
42
45
statements : ts . NodeArray < ts . Statement > | ts . Statement [ ] ,
43
- block : ts . Block
46
+ block : ts . Block | ts . SourceFile
44
47
) : [ true , ts . Statement [ ] ] | [ false ] {
45
48
const newStatements : ts . Statement [ ] = [ ] ;
46
49
@@ -102,7 +105,14 @@ function transformBlockWithUsing(
102
105
call = ts . factory . createAwaitExpression ( call ) ;
103
106
}
104
107
105
- if ( ts . isBlock ( block . parent ) && block . parent . statements [ block . parent . statements . length - 1 ] !== block ) {
108
+ if ( ts . isSourceFile ( block ) ) {
109
+ // If block is a sourcefile, don't insert a return statement into root code
110
+ newStatements . push ( ts . factory . createExpressionStatement ( call ) ) ;
111
+ } else if (
112
+ block . parent &&
113
+ ts . isBlock ( block . parent ) &&
114
+ block . parent . statements [ block . parent . statements . length - 1 ] !== block
115
+ ) {
106
116
// If this is a free-standing block in a function (not the last statement), dont return the value
107
117
newStatements . push ( ts . factory . createExpressionStatement ( call ) ) ;
108
118
} else {
0 commit comments