@@ -4,8 +4,7 @@ import * as lua from "../../LuaAST";
44import { assert , castArray } from "../../utils" ;
55import { TransformationContext } from "../context" ;
66import { createExportedIdentifier , getIdentifierExportScope } from "./export" ;
7- import { peekScope , ScopeType } from "./scope" ;
8- import { isFunctionType } from "./typescript" ;
7+ import { peekScope , ScopeType , Scope } from "./scope" ;
98import { transformLuaLibFunction } from "./lualib" ;
109import { LuaLibFeature } from "../../LuaLib" ;
1110
@@ -129,6 +128,17 @@ export function createHoistableVariableDeclarationStatement(
129128 return declaration ;
130129}
131130
131+ function hasMultipleReferences ( scope : Scope , identifiers : lua . Identifier | lua . Identifier [ ] ) {
132+ const scopeSymbols = scope . referencedSymbols ;
133+ if ( ! scopeSymbols ) {
134+ return false ;
135+ }
136+
137+ const referenceLists = castArray ( identifiers ) . map ( i => i . symbolId && scopeSymbols . get ( i . symbolId ) ) ;
138+
139+ return referenceLists . some ( symbolRefs => symbolRefs && symbolRefs . length > 1 ) ;
140+ }
141+
132142export function createLocalOrExportedOrGlobalDeclaration (
133143 context : TransformationContext ,
134144 lhs : lua . Identifier | lua . Identifier [ ] ,
@@ -163,15 +173,8 @@ export function createLocalOrExportedOrGlobalDeclaration(
163173 const isTopLevelVariable = scope . type === ScopeType . File ;
164174
165175 if ( context . isModule || ! isTopLevelVariable ) {
166- const isPossibleWrappedFunction =
167- ! isFunctionDeclaration &&
168- tsOriginal &&
169- ts . isVariableDeclaration ( tsOriginal ) &&
170- tsOriginal . initializer &&
171- isFunctionType ( context , context . checker . getTypeAtLocation ( tsOriginal . initializer ) ) ;
172-
173- if ( isPossibleWrappedFunction || scope . type === ScopeType . Switch ) {
174- // Split declaration and assignment for wrapped function types to allow recursion
176+ if ( scope . type === ScopeType . Switch || ( ! isFunctionDeclaration && hasMultipleReferences ( scope , lhs ) ) ) {
177+ // Split declaration and assignment of identifiers that reference themselves in their declaration
175178 declaration = lua . createVariableDeclarationStatement ( lhs , undefined , tsOriginal ) ;
176179 assignment = lua . createAssignmentStatement ( lhs , rhs , tsOriginal ) ;
177180 } else {
0 commit comments