js: cleanup 'public', property access syntax
This commit is contained in:
@@ -4,7 +4,7 @@
|
||||
|
||||
package com.google.dart.compiler.backend.js.ast
|
||||
|
||||
public object JsEmpty : SourceInfoAwareJsNode(), JsStatement {
|
||||
object JsEmpty : SourceInfoAwareJsNode(), JsStatement {
|
||||
|
||||
override fun accept(v: JsVisitor) {
|
||||
v.visitEmpty(this)
|
||||
|
||||
@@ -6,157 +6,157 @@ package com.google.dart.compiler.backend.js.ast
|
||||
|
||||
import com.google.dart.compiler.backend.js.ast.JsVars.JsVar
|
||||
|
||||
public abstract class JsVisitor {
|
||||
public open fun <T : JsNode?> accept(node: T) {
|
||||
abstract class JsVisitor {
|
||||
open fun <T : JsNode?> accept(node: T) {
|
||||
node?.accept(this)
|
||||
}
|
||||
|
||||
public fun <T : JsNode> acceptList(collection: List<T>) {
|
||||
fun <T : JsNode> acceptList(collection: List<T>) {
|
||||
for (node in collection) {
|
||||
accept(node)
|
||||
}
|
||||
}
|
||||
|
||||
public fun acceptLvalue(expression: JsExpression) {
|
||||
fun acceptLvalue(expression: JsExpression) {
|
||||
accept(expression)
|
||||
}
|
||||
|
||||
public fun <T : JsNode> acceptWithInsertRemove(collection: List<T>) {
|
||||
fun <T : JsNode> acceptWithInsertRemove(collection: List<T>) {
|
||||
for (node in collection) {
|
||||
accept(node)
|
||||
}
|
||||
}
|
||||
|
||||
public open fun visitArrayAccess(x: JsArrayAccess): Unit =
|
||||
open fun visitArrayAccess(x: JsArrayAccess): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitArray(x: JsArrayLiteral): Unit =
|
||||
open fun visitArray(x: JsArrayLiteral): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitBinaryExpression(x: JsBinaryOperation): Unit =
|
||||
open fun visitBinaryExpression(x: JsBinaryOperation): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitBlock(x: JsBlock): Unit =
|
||||
open fun visitBlock(x: JsBlock): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitBoolean(x: JsLiteral.JsBooleanLiteral): Unit =
|
||||
open fun visitBoolean(x: JsLiteral.JsBooleanLiteral): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitBreak(x: JsBreak): Unit =
|
||||
open fun visitBreak(x: JsBreak): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitCase(x: JsCase): Unit =
|
||||
open fun visitCase(x: JsCase): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitCatch(x: JsCatch): Unit =
|
||||
open fun visitCatch(x: JsCatch): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitConditional(x: JsConditional): Unit =
|
||||
open fun visitConditional(x: JsConditional): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitContinue(x: JsContinue): Unit =
|
||||
open fun visitContinue(x: JsContinue): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitDebugger(x: JsDebugger): Unit =
|
||||
open fun visitDebugger(x: JsDebugger): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitDefault(x: JsDefault): Unit =
|
||||
open fun visitDefault(x: JsDefault): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitDoWhile(x: JsDoWhile): Unit =
|
||||
open fun visitDoWhile(x: JsDoWhile): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitEmpty(x: JsEmpty): Unit =
|
||||
open fun visitEmpty(x: JsEmpty): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitExpressionStatement(x: JsExpressionStatement): Unit =
|
||||
open fun visitExpressionStatement(x: JsExpressionStatement): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitFor(x: JsFor): Unit =
|
||||
open fun visitFor(x: JsFor): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitForIn(x: JsForIn): Unit =
|
||||
open fun visitForIn(x: JsForIn): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitFunction(x: JsFunction): Unit =
|
||||
open fun visitFunction(x: JsFunction): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitIf(x: JsIf): Unit =
|
||||
open fun visitIf(x: JsIf): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitInvocation(invocation: JsInvocation): Unit =
|
||||
open fun visitInvocation(invocation: JsInvocation): Unit =
|
||||
visitElement(invocation)
|
||||
|
||||
public open fun visitLabel(x: JsLabel): Unit =
|
||||
open fun visitLabel(x: JsLabel): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitNameRef(nameRef: JsNameRef): Unit =
|
||||
open fun visitNameRef(nameRef: JsNameRef): Unit =
|
||||
visitElement(nameRef)
|
||||
|
||||
public open fun visitNew(x: JsNew): Unit =
|
||||
open fun visitNew(x: JsNew): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitNull(x: JsNullLiteral): Unit =
|
||||
open fun visitNull(x: JsNullLiteral): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitInt(x: JsNumberLiteral.JsIntLiteral): Unit =
|
||||
open fun visitInt(x: JsNumberLiteral.JsIntLiteral): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitDouble(x: JsNumberLiteral.JsDoubleLiteral): Unit =
|
||||
open fun visitDouble(x: JsNumberLiteral.JsDoubleLiteral): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitObjectLiteral(x: JsObjectLiteral): Unit =
|
||||
open fun visitObjectLiteral(x: JsObjectLiteral): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitParameter(x: JsParameter): Unit =
|
||||
open fun visitParameter(x: JsParameter): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitPostfixOperation(x: JsPostfixOperation): Unit =
|
||||
open fun visitPostfixOperation(x: JsPostfixOperation): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitPrefixOperation(x: JsPrefixOperation): Unit =
|
||||
open fun visitPrefixOperation(x: JsPrefixOperation): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitProgram(x: JsProgram): Unit =
|
||||
open fun visitProgram(x: JsProgram): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitProgramFragment(x: JsProgramFragment): Unit =
|
||||
open fun visitProgramFragment(x: JsProgramFragment): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitPropertyInitializer(x: JsPropertyInitializer): Unit =
|
||||
open fun visitPropertyInitializer(x: JsPropertyInitializer): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitRegExp(x: JsRegExp): Unit =
|
||||
open fun visitRegExp(x: JsRegExp): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitReturn(x: JsReturn): Unit =
|
||||
open fun visitReturn(x: JsReturn): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitString(x: JsStringLiteral): Unit =
|
||||
open fun visitString(x: JsStringLiteral): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visit(x: JsSwitch): Unit =
|
||||
open fun visit(x: JsSwitch): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitThis(x: JsLiteral.JsThisRef): Unit =
|
||||
open fun visitThis(x: JsLiteral.JsThisRef): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitThrow(x: JsThrow): Unit =
|
||||
open fun visitThrow(x: JsThrow): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitTry(x: JsTry): Unit =
|
||||
open fun visitTry(x: JsTry): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visit(x: JsVar): Unit =
|
||||
open fun visit(x: JsVar): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitVars(x: JsVars): Unit =
|
||||
open fun visitVars(x: JsVars): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitWhile(x: JsWhile): Unit =
|
||||
open fun visitWhile(x: JsWhile): Unit =
|
||||
visitElement(x)
|
||||
|
||||
public open fun visitDocComment(comment: JsDocComment): Unit =
|
||||
open fun visitDocComment(comment: JsDocComment): Unit =
|
||||
visitElement(comment)
|
||||
|
||||
protected open fun visitElement(node: JsNode) {
|
||||
|
||||
@@ -18,15 +18,15 @@ package com.google.dart.compiler.backend.js.ast
|
||||
|
||||
import java.util.Stack
|
||||
|
||||
public fun JsObjectScope(parent: JsScope, description: String): JsObjectScope = JsObjectScope(parent, description, null)
|
||||
fun JsObjectScope(parent: JsScope, description: String): JsObjectScope = JsObjectScope(parent, description, null)
|
||||
|
||||
public class JsObjectScope(parent: JsScope, description: String, scopeId: String?) : JsScope(parent, description, scopeId)
|
||||
class JsObjectScope(parent: JsScope, description: String, scopeId: String?) : JsScope(parent, description, scopeId)
|
||||
|
||||
public object JsDynamicScope : JsScope(null, "Scope for dynamic declarations", null) {
|
||||
object JsDynamicScope : JsScope(null, "Scope for dynamic declarations", null) {
|
||||
override fun doCreateName(name: String) = JsName(this, name)
|
||||
}
|
||||
|
||||
public open class JsFunctionScope(parent: JsScope, description: String) : JsScope(parent, description, null) {
|
||||
open class JsFunctionScope(parent: JsScope, description: String) : JsScope(parent, description, null) {
|
||||
|
||||
private val labelScopes = Stack<LabelScope>()
|
||||
private val topLabelScope: LabelScope?
|
||||
@@ -36,20 +36,20 @@ public open class JsFunctionScope(parent: JsScope, description: String) : JsScop
|
||||
|
||||
override fun hasOwnName(name: String): Boolean = RESERVED_WORDS.contains(name) || super.hasOwnName(name)
|
||||
|
||||
public open fun declareNameUnsafe(identifier: String): JsName = super.declareName(identifier)
|
||||
open fun declareNameUnsafe(identifier: String): JsName = super.declareName(identifier)
|
||||
|
||||
public open fun enterLabel(label: String): JsName {
|
||||
open fun enterLabel(label: String): JsName {
|
||||
val scope = LabelScope(topLabelScope, label)
|
||||
labelScopes.push(scope)
|
||||
return scope.labelName
|
||||
}
|
||||
|
||||
public open fun exitLabel() {
|
||||
open fun exitLabel() {
|
||||
assert(labelScopes.isNotEmpty()) { "No scope to exit from" }
|
||||
labelScopes.pop()
|
||||
}
|
||||
|
||||
public open fun findLabel(label: String): JsName? =
|
||||
open fun findLabel(label: String): JsName? =
|
||||
topLabelScope?.findName(label)
|
||||
|
||||
private inner class LabelScope(parent: LabelScope?, val ident: String) : JsScope(parent, "Label scope for $ident", null) {
|
||||
@@ -76,12 +76,12 @@ public open class JsFunctionScope(parent: JsScope, description: String) : JsScop
|
||||
override fun hasOwnName(name: String): Boolean =
|
||||
name in RESERVED_WORDS
|
||||
|| name == ident
|
||||
|| name == labelName?.getIdent()
|
||||
|| getParent()?.hasOwnName(name) ?: false
|
||||
|| name == labelName?.ident
|
||||
|| parent?.hasOwnName(name) ?: false
|
||||
}
|
||||
|
||||
companion object {
|
||||
public val RESERVED_WORDS: Set<String> = setOf(
|
||||
val RESERVED_WORDS: Set<String> = setOf(
|
||||
// keywords
|
||||
"await", "break", "case", "catch", "continue", "debugger", "default", "delete", "do", "else", "finally", "for", "function", "if",
|
||||
"in", "instanceof", "new", "return", "switch", "this", "throw", "try", "typeof", "var", "void", "while", "with",
|
||||
@@ -107,7 +107,7 @@ public open class JsFunctionScope(parent: JsScope, description: String) : JsScop
|
||||
}
|
||||
}
|
||||
|
||||
public class DelegatingJsFunctionScopeWithTemporaryParent(
|
||||
class DelegatingJsFunctionScopeWithTemporaryParent(
|
||||
private val delegatingScope: JsFunctionScope,
|
||||
parent: JsScope
|
||||
) : JsFunctionScope(parent, "<delegating scope to delegatingScope>") {
|
||||
|
||||
+8
-8
@@ -22,22 +22,22 @@ import com.intellij.psi.PsiElement
|
||||
import org.jetbrains.kotlin.descriptors.CallableDescriptor
|
||||
import org.jetbrains.kotlin.resolve.inline.InlineStrategy
|
||||
|
||||
public var JsName.staticRef: JsNode? by MetadataProperty(default = null)
|
||||
var JsName.staticRef: JsNode? by MetadataProperty(default = null)
|
||||
|
||||
// TODO: move this to module 'js.inliner' and change dependency on 'frontend' to dependency on 'descriptors'
|
||||
public var JsInvocation.inlineStrategy: InlineStrategy? by MetadataProperty(default = null)
|
||||
var JsInvocation.inlineStrategy: InlineStrategy? by MetadataProperty(default = null)
|
||||
|
||||
public var JsInvocation.descriptor: CallableDescriptor? by MetadataProperty(default = null)
|
||||
var JsInvocation.descriptor: CallableDescriptor? by MetadataProperty(default = null)
|
||||
|
||||
public var JsInvocation.psiElement: PsiElement? by MetadataProperty(default = null)
|
||||
var JsInvocation.psiElement: PsiElement? by MetadataProperty(default = null)
|
||||
|
||||
public var JsFunction.isLocal: Boolean by MetadataProperty(default = false)
|
||||
var JsFunction.isLocal: Boolean by MetadataProperty(default = false)
|
||||
|
||||
public var JsParameter.hasDefaultValue: Boolean by MetadataProperty(default = false)
|
||||
var JsParameter.hasDefaultValue: Boolean by MetadataProperty(default = false)
|
||||
|
||||
public var JsInvocation.typeCheck: TypeCheck? by MetadataProperty(default = null)
|
||||
var JsInvocation.typeCheck: TypeCheck? by MetadataProperty(default = null)
|
||||
|
||||
public enum class TypeCheck {
|
||||
enum class TypeCheck {
|
||||
TYPEOF,
|
||||
INSTANCEOF
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ import org.jetbrains.kotlin.resolve.lazy.ResolveSession
|
||||
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactory
|
||||
import org.jetbrains.kotlin.types.DynamicTypesAllowed
|
||||
|
||||
public fun createTopDownAnalyzerForJs(
|
||||
fun createTopDownAnalyzerForJs(
|
||||
moduleContext: ModuleContext,
|
||||
bindingTrace: BindingTrace,
|
||||
declarationProviderFactory: DeclarationProviderFactory
|
||||
|
||||
@@ -18,14 +18,14 @@ package org.jetbrains.kotlin.js
|
||||
|
||||
import org.jetbrains.kotlin.name.FqName
|
||||
|
||||
public enum class PredefinedAnnotation(fqName: String) {
|
||||
enum class PredefinedAnnotation(fqName: String) {
|
||||
LIBRARY("kotlin.js.library"),
|
||||
NATIVE("kotlin.js.native"),
|
||||
NATIVE_INVOKE("kotlin.js.nativeInvoke"),
|
||||
NATIVE_GETTER("kotlin.js.nativeGetter"),
|
||||
NATIVE_SETTER("kotlin.js.nativeSetter");
|
||||
|
||||
public val fqName: FqName = FqName(fqName)
|
||||
val fqName: FqName = FqName(fqName)
|
||||
|
||||
companion object {
|
||||
val WITH_CUSTOM_NAME = setOf(LIBRARY, NATIVE)
|
||||
|
||||
@@ -33,27 +33,27 @@ import org.jetbrains.kotlin.resolve.diagnostics.SuppressDiagnosticsByAnnotations
|
||||
|
||||
private val NATIVE_ANNOTATIONS = arrayOf(NATIVE.fqName, NATIVE_INVOKE.fqName, NATIVE_GETTER.fqName, NATIVE_SETTER.fqName)
|
||||
|
||||
public class SuppressUnusedParameterForJsNative : SuppressDiagnosticsByAnnotations(listOf(Errors.UNUSED_PARAMETER), *NATIVE_ANNOTATIONS)
|
||||
class SuppressUnusedParameterForJsNative : SuppressDiagnosticsByAnnotations(listOf(Errors.UNUSED_PARAMETER), *NATIVE_ANNOTATIONS)
|
||||
|
||||
public class SuppressNoBodyErrorsForNativeDeclarations : SuppressDiagnosticsByAnnotations(FUNCTION_NO_BODY_ERRORS + PROPERTY_NOT_INITIALIZED_ERRORS, *NATIVE_ANNOTATIONS)
|
||||
class SuppressNoBodyErrorsForNativeDeclarations : SuppressDiagnosticsByAnnotations(FUNCTION_NO_BODY_ERRORS + PROPERTY_NOT_INITIALIZED_ERRORS, *NATIVE_ANNOTATIONS)
|
||||
|
||||
public class SuppressUninitializedErrorsForNativeDeclarations : DiagnosticSuppressor {
|
||||
class SuppressUninitializedErrorsForNativeDeclarations : DiagnosticSuppressor {
|
||||
override fun isSuppressed(diagnostic: Diagnostic): Boolean {
|
||||
if (diagnostic.getFactory() != Errors.UNINITIALIZED_VARIABLE) return false
|
||||
if (diagnostic.factory != Errors.UNINITIALIZED_VARIABLE) return false
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val diagnosticWithParameters = diagnostic as DiagnosticWithParameters1<KtSimpleNameExpression, VariableDescriptor>
|
||||
|
||||
val variableDescriptor = diagnosticWithParameters.getA()
|
||||
val variableDescriptor = diagnosticWithParameters.a
|
||||
|
||||
return AnnotationsUtils.isNativeObject(variableDescriptor)
|
||||
}
|
||||
}
|
||||
|
||||
public class SuppressWarningsFromExternalModules : DiagnosticSuppressor {
|
||||
class SuppressWarningsFromExternalModules : DiagnosticSuppressor {
|
||||
override fun isSuppressed(diagnostic: Diagnostic): Boolean {
|
||||
val file = diagnostic.getPsiFile()
|
||||
return diagnostic.getSeverity() == Severity.WARNING &&
|
||||
val file = diagnostic.psiFile
|
||||
return diagnostic.severity == Severity.WARNING &&
|
||||
file is KtFile && file.getUserData(LibrarySourcesConfig.EXTERNAL_MODULE_NAME) != null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,14 +22,13 @@ import org.jetbrains.kotlin.descriptors.ModuleDescriptor
|
||||
import org.jetbrains.kotlin.resolve.BindingContext
|
||||
import org.jetbrains.kotlin.types.ErrorUtils
|
||||
|
||||
public class JsAnalysisResult(
|
||||
public val bindingTrace: BindingTrace,
|
||||
class JsAnalysisResult(
|
||||
val bindingTrace: BindingTrace,
|
||||
moduleDescriptor: ModuleDescriptor
|
||||
) : AnalysisResult(bindingTrace.getBindingContext(), moduleDescriptor) {
|
||||
) : AnalysisResult(bindingTrace.bindingContext, moduleDescriptor) {
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
public fun success(trace: BindingTrace, module: ModuleDescriptor): JsAnalysisResult {
|
||||
@JvmStatic fun success(trace: BindingTrace, module: ModuleDescriptor): JsAnalysisResult {
|
||||
return JsAnalysisResult(trace, module)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,28 +24,28 @@ import org.jetbrains.kotlin.resolve.DescriptorUtils
|
||||
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
|
||||
import org.jetbrains.kotlin.types.KotlinType
|
||||
|
||||
public val KotlinType.nameIfStandardType: Name?
|
||||
val KotlinType.nameIfStandardType: Name?
|
||||
get() {
|
||||
val descriptor = getConstructor().getDeclarationDescriptor()
|
||||
val descriptor = constructor.declarationDescriptor
|
||||
|
||||
if (descriptor?.getContainingDeclaration() == descriptor?.builtIns?.getBuiltInsPackageFragment()) {
|
||||
return descriptor?.getName()
|
||||
if (descriptor?.containingDeclaration == descriptor?.builtIns?.builtInsPackageFragment) {
|
||||
return descriptor?.name
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
public fun KotlinType.getJetTypeFqName(printTypeArguments: Boolean): String {
|
||||
val declaration = requireNotNull(getConstructor().getDeclarationDescriptor())
|
||||
fun KotlinType.getJetTypeFqName(printTypeArguments: Boolean): String {
|
||||
val declaration = requireNotNull(constructor.declarationDescriptor)
|
||||
if (declaration is TypeParameterDescriptor) {
|
||||
return StringUtil.join(declaration.getUpperBounds(), { type -> type.getJetTypeFqName(printTypeArguments) }, "&")
|
||||
return StringUtil.join(declaration.upperBounds, { type -> type.getJetTypeFqName(printTypeArguments) }, "&")
|
||||
}
|
||||
|
||||
val typeArguments = getArguments()
|
||||
val typeArguments = arguments
|
||||
val typeArgumentsAsString: String
|
||||
|
||||
if (printTypeArguments && !typeArguments.isEmpty()) {
|
||||
val joinedTypeArguments = StringUtil.join(typeArguments, { projection -> projection.getType().getJetTypeFqName(false) }, ", ")
|
||||
val joinedTypeArguments = StringUtil.join(typeArguments, { projection -> projection.type.getJetTypeFqName(false) }, ", ")
|
||||
|
||||
typeArgumentsAsString = "<" + joinedTypeArguments + ">"
|
||||
} else {
|
||||
@@ -55,4 +55,4 @@ public fun KotlinType.getJetTypeFqName(printTypeArguments: Boolean): String {
|
||||
return DescriptorUtils.getFqName(declaration).asString() + typeArgumentsAsString
|
||||
}
|
||||
|
||||
public fun ClassDescriptor.hasPrimaryConstructor(): Boolean = getUnsubstitutedPrimaryConstructor() != null
|
||||
fun ClassDescriptor.hasPrimaryConstructor(): Boolean = unsubstitutedPrimaryConstructor != null
|
||||
|
||||
@@ -25,7 +25,7 @@ import org.jetbrains.kotlin.resolve.ImportPath
|
||||
import org.jetbrains.kotlin.resolve.PlatformConfigurator
|
||||
import org.jetbrains.kotlin.resolve.TargetPlatform
|
||||
|
||||
public object JsPlatform : TargetPlatform("JS") {
|
||||
object JsPlatform : TargetPlatform("JS") {
|
||||
override val defaultModuleParameters = object : ModuleParameters {
|
||||
override val defaultImports: List<ImportPath> = ImmutableList.of(
|
||||
ImportPath("java.lang.*"),
|
||||
|
||||
@@ -26,7 +26,7 @@ import org.jetbrains.kotlin.resolve.PlatformConfigurator
|
||||
import org.jetbrains.kotlin.resolve.scopes.SyntheticScopes
|
||||
import org.jetbrains.kotlin.types.DynamicTypesAllowed
|
||||
|
||||
public object JsPlatformConfigurator : PlatformConfigurator(
|
||||
object JsPlatformConfigurator : PlatformConfigurator(
|
||||
DynamicTypesAllowed(),
|
||||
additionalDeclarationCheckers = listOf(NativeInvokeChecker(), NativeGetterChecker(), NativeSetterChecker(), ClassDeclarationChecker()),
|
||||
additionalCallCheckers = listOf(),
|
||||
|
||||
+1
-1
@@ -42,6 +42,6 @@ private val DIAGNOSTIC_FACTORY_TO_RENDERER by lazy {
|
||||
}
|
||||
}
|
||||
|
||||
public class DefaultErrorMessagesJs : DefaultErrorMessages.Extension {
|
||||
class DefaultErrorMessagesJs : DefaultErrorMessages.Extension {
|
||||
override fun getMap(): DiagnosticFactoryToRendererMap = DIAGNOSTIC_FACTORY_TO_RENDERER
|
||||
}
|
||||
|
||||
@@ -46,21 +46,19 @@ import org.jetbrains.kotlin.resolve.constants.TypedCompileTimeConstant
|
||||
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
|
||||
import org.jetbrains.kotlin.types.TypeUtils
|
||||
|
||||
public class JsCallChecker(
|
||||
class JsCallChecker(
|
||||
private val constantExpressionEvaluator: ConstantExpressionEvaluator
|
||||
) : CallChecker {
|
||||
|
||||
companion object {
|
||||
private val JS_PATTERN: DescriptorPredicate = PatternBuilder.pattern("kotlin.js.js(String)")
|
||||
|
||||
@JvmStatic
|
||||
public fun <F : CallableDescriptor?> ResolvedCall<F>.isJsCall(): Boolean {
|
||||
val descriptor = getResultingDescriptor()
|
||||
@JvmStatic fun <F : CallableDescriptor?> ResolvedCall<F>.isJsCall(): Boolean {
|
||||
val descriptor = resultingDescriptor
|
||||
return descriptor is SimpleFunctionDescriptor && JS_PATTERN.apply(descriptor)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
public fun extractStringValue(compileTimeConstant: CompileTimeConstant<*>?): String? {
|
||||
@JvmStatic fun extractStringValue(compileTimeConstant: CompileTimeConstant<*>?): String? {
|
||||
return ((compileTimeConstant as? TypedCompileTimeConstant<*>)?.constantValue as? StringValue)?.value
|
||||
}
|
||||
}
|
||||
@@ -68,10 +66,10 @@ public class JsCallChecker(
|
||||
override fun <F : CallableDescriptor> check(resolvedCall: ResolvedCall<F>, context: BasicCallResolutionContext) {
|
||||
if (context.isAnnotationContext || !resolvedCall.isJsCall()) return
|
||||
|
||||
val expression = resolvedCall.getCall().getCallElement()
|
||||
val expression = resolvedCall.call.callElement
|
||||
if (expression !is KtCallExpression) return
|
||||
|
||||
val arguments = expression.getValueArgumentList()?.getArguments()
|
||||
val arguments = expression.valueArgumentList?.arguments
|
||||
val argument = arguments?.firstOrNull()?.getArgumentExpression() ?: return
|
||||
|
||||
val trace = TemporaryBindingTrace.create(context.trace, "JsCallChecker")
|
||||
@@ -127,7 +125,7 @@ class JsCodeErrorReporter(
|
||||
JsCallData(reportRange, message)
|
||||
}
|
||||
else -> {
|
||||
val reportRange = nodeToReport.getTextRange()
|
||||
val reportRange = nodeToReport.textRange
|
||||
val codeRange = TextRange(code.offsetOf(startPosition), code.offsetOf(endPosition))
|
||||
JsCallDataWithCode(reportRange, message, code, codeRange)
|
||||
}
|
||||
@@ -139,8 +137,8 @@ class JsCodeErrorReporter(
|
||||
|
||||
private val CodePosition.absoluteOffset: Int
|
||||
get() {
|
||||
val quotesLength = nodeToReport.getFirstChild().getTextLength()
|
||||
return nodeToReport.getTextOffset() + quotesLength + code.offsetOf(this)
|
||||
val quotesLength = nodeToReport.firstChild.textLength
|
||||
return nodeToReport.textOffset + quotesLength + code.offsetOf(this)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,7 +172,7 @@ private fun String.offsetOf(position: CodePosition): Int {
|
||||
}
|
||||
|
||||
private val KtExpression.isConstantStringLiteral: Boolean
|
||||
get() = this is KtStringTemplateExpression && getEntries().all { it is KtLiteralStringTemplateEntry }
|
||||
get() = this is KtStringTemplateExpression && entries.all { it is KtLiteralStringTemplateEntry }
|
||||
|
||||
open class JsCallData(val reportRange: TextRange, val message: String)
|
||||
|
||||
|
||||
+2
-2
@@ -26,11 +26,11 @@ import org.jetbrains.kotlin.js.resolve.diagnostics.JsCallData
|
||||
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory1
|
||||
import org.jetbrains.kotlin.diagnostics.DiagnosticWithParameters1
|
||||
|
||||
public object JsCodePositioningStrategy : PositioningStrategy<PsiElement>() {
|
||||
object JsCodePositioningStrategy : PositioningStrategy<PsiElement>() {
|
||||
override fun markDiagnostic(diagnostic: ParametrizedDiagnostic<out PsiElement>): List<TextRange> {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val diagnosticWithParameters = diagnostic as DiagnosticWithParameters1<KtExpression, JsCallData>
|
||||
val textRange = diagnosticWithParameters.getA().reportRange
|
||||
val textRange = diagnosticWithParameters.a.reportRange
|
||||
return listOf(textRange)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ import org.jetbrains.kotlin.renderer.Renderer
|
||||
|
||||
object RenderFirstLineOfElementText : Renderer<PsiElement> {
|
||||
override fun render(element: PsiElement): String {
|
||||
val text = element.getText()
|
||||
val text = element.text
|
||||
val index = text.indexOf('\n')
|
||||
return if (index == -1) text else text.substring(0, index) + "..."
|
||||
}
|
||||
@@ -42,15 +42,15 @@ abstract class JsCallDataRenderer : Renderer<JsCallData> {
|
||||
object JsCallDataTextRenderer : JsCallDataRenderer() {
|
||||
override fun format(data: JsCallDataWithCode): String {
|
||||
val codeRange = data.codeRange
|
||||
val code = data.code.underlineAsText(codeRange.getStartOffset(), codeRange.getEndOffset())
|
||||
val code = data.code.underlineAsText(codeRange.startOffset, codeRange.endOffset)
|
||||
return "${data.message} in code:\n${code}"
|
||||
}
|
||||
}
|
||||
|
||||
public object JsCallDataHtmlRenderer : JsCallDataRenderer() {
|
||||
object JsCallDataHtmlRenderer : JsCallDataRenderer() {
|
||||
override fun format(data: JsCallDataWithCode): String {
|
||||
val codeRange = data.codeRange
|
||||
val code = data.code.underlineAsHtml(codeRange.getStartOffset(), codeRange.getEndOffset())
|
||||
val code = data.code.underlineAsHtml(codeRange.startOffset, codeRange.endOffset)
|
||||
return "${data.message} in code:<br><pre>${code}</pre>"
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,7 @@ public object JsCallDataHtmlRenderer : JsCallDataRenderer() {
|
||||
* var = 10;
|
||||
* ^^^^
|
||||
*/
|
||||
public fun String.underlineAsText(from: Int, to: Int): String {
|
||||
fun String.underlineAsText(from: Int, to: Int): String {
|
||||
val lines = StringBuilder()
|
||||
var marks = StringBuilder()
|
||||
var lineWasMarked = false
|
||||
@@ -98,7 +98,7 @@ public fun String.underlineAsText(from: Int, to: Int): String {
|
||||
return lines.toString()
|
||||
}
|
||||
|
||||
public fun String.underlineAsHtml(from: Int, to: Int): String {
|
||||
fun String.underlineAsHtml(from: Int, to: Int): String {
|
||||
val lines = StringBuilder()
|
||||
var openMarker = false
|
||||
val underlineStart = "<u>"
|
||||
|
||||
@@ -44,19 +44,19 @@ internal abstract class AbstractNativeAnnotationsChecker(private val requiredAnn
|
||||
diagnosticHolder: DiagnosticSink,
|
||||
bindingContext: BindingContext
|
||||
) {
|
||||
val annotationDescriptor = descriptor.getAnnotations().findAnnotation(requiredAnnotation.fqName) ?: return
|
||||
val annotationDescriptor = descriptor.annotations.findAnnotation(requiredAnnotation.fqName) ?: return
|
||||
|
||||
if (declaration !is KtNamedFunction || descriptor !is FunctionDescriptor) {
|
||||
return
|
||||
}
|
||||
|
||||
val isMember = !DescriptorUtils.isTopLevelDeclaration(descriptor) && descriptor.getVisibility() != Visibilities.LOCAL
|
||||
val isMember = !DescriptorUtils.isTopLevelDeclaration(descriptor) && descriptor.visibility != Visibilities.LOCAL
|
||||
val isExtension = DescriptorUtils.isExtension(descriptor)
|
||||
|
||||
if (isMember && (isExtension || !AnnotationsUtils.isNativeObject(descriptor)) ||
|
||||
!isMember && !isExtension
|
||||
) {
|
||||
diagnosticHolder.report(ErrorsJs.NATIVE_ANNOTATIONS_ALLOWED_ONLY_ON_MEMBER_OR_EXTENSION_FUN.on(declaration, annotationDescriptor.getType()))
|
||||
diagnosticHolder.report(ErrorsJs.NATIVE_ANNOTATIONS_ALLOWED_ONLY_ON_MEMBER_OR_EXTENSION_FUN.on(declaration, annotationDescriptor.type))
|
||||
}
|
||||
|
||||
additionalCheck(declaration, descriptor, diagnosticHolder)
|
||||
@@ -72,14 +72,14 @@ internal abstract class AbstractNativeIndexerChecker(
|
||||
) : AbstractNativeAnnotationsChecker(requiredAnnotation) {
|
||||
|
||||
override fun additionalCheck(declaration: KtNamedFunction, descriptor: FunctionDescriptor, diagnosticHolder: DiagnosticSink) {
|
||||
val parameters = descriptor.getValueParameters()
|
||||
val parameters = descriptor.valueParameters
|
||||
val builtIns = descriptor.builtIns
|
||||
if (parameters.size > 0) {
|
||||
val firstParamClassDescriptor = DescriptorUtils.getClassDescriptorForType(parameters.get(0).getType())
|
||||
val firstParamClassDescriptor = DescriptorUtils.getClassDescriptorForType(parameters.get(0).type)
|
||||
if (firstParamClassDescriptor != builtIns.string &&
|
||||
!DescriptorUtils.isSubclass(firstParamClassDescriptor, builtIns.number)
|
||||
) {
|
||||
diagnosticHolder.report(ErrorsJs.NATIVE_INDEXER_KEY_SHOULD_BE_STRING_OR_NUMBER.on(declaration.getValueParameters().firstOrNull(), indexerKind))
|
||||
diagnosticHolder.report(ErrorsJs.NATIVE_INDEXER_KEY_SHOULD_BE_STRING_OR_NUMBER.on(declaration.valueParameters.firstOrNull(), indexerKind))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ internal abstract class AbstractNativeIndexerChecker(
|
||||
diagnosticHolder.report(ErrorsJs.NATIVE_INDEXER_WRONG_PARAMETER_COUNT.on(declaration, requiredParametersCount, indexerKind))
|
||||
}
|
||||
|
||||
for (parameter in declaration.getValueParameters()) {
|
||||
for (parameter in declaration.valueParameters) {
|
||||
if (parameter.hasDefaultValue()) {
|
||||
diagnosticHolder.report(ErrorsJs.NATIVE_INDEXER_CAN_NOT_HAVE_DEFAULT_ARGUMENTS.on(parameter, indexerKind))
|
||||
}
|
||||
@@ -99,7 +99,7 @@ internal class NativeGetterChecker : AbstractNativeIndexerChecker(PredefinedAnno
|
||||
override fun additionalCheck(declaration: KtNamedFunction, descriptor: FunctionDescriptor, diagnosticHolder: DiagnosticSink) {
|
||||
super.additionalCheck(declaration, descriptor, diagnosticHolder)
|
||||
|
||||
val returnType = descriptor.getReturnType()
|
||||
val returnType = descriptor.returnType
|
||||
if (returnType != null && !TypeUtils.isNullableType(returnType)) {
|
||||
diagnosticHolder.report(ErrorsJs.NATIVE_GETTER_RETURN_TYPE_SHOULD_BE_NULLABLE.on(declaration))
|
||||
}
|
||||
@@ -110,13 +110,13 @@ internal class NativeSetterChecker : AbstractNativeIndexerChecker(PredefinedAnno
|
||||
override fun additionalCheck(declaration: KtNamedFunction, descriptor: FunctionDescriptor, diagnosticHolder: DiagnosticSink) {
|
||||
super.additionalCheck(declaration, descriptor, diagnosticHolder)
|
||||
|
||||
val returnType = descriptor.getReturnType()
|
||||
val returnType = descriptor.returnType
|
||||
if (returnType == null || KotlinBuiltIns.isUnit(returnType)) return
|
||||
|
||||
val parameters = descriptor.getValueParameters()
|
||||
val parameters = descriptor.valueParameters
|
||||
if (parameters.size < 2) return
|
||||
|
||||
val secondParameterType = parameters.get(1).getType()
|
||||
val secondParameterType = parameters.get(1).type
|
||||
if (secondParameterType.isSubtypeOf(returnType)) return
|
||||
|
||||
diagnosticHolder.report(ErrorsJs.NATIVE_SETTER_WRONG_RETURN_TYPE.on(declaration))
|
||||
|
||||
@@ -53,8 +53,7 @@ internal class ExpressionDecomposer private constructor(
|
||||
private var additionalStatements: MutableList<JsStatement> = SmartList()
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
public fun preserveEvaluationOrder(
|
||||
@JvmStatic fun preserveEvaluationOrder(
|
||||
scope: JsScope, statement: JsStatement, canBeExtractedByInliner: (JsNode)->Boolean
|
||||
): List<JsStatement> {
|
||||
val decomposer = with (statement) {
|
||||
@@ -73,12 +72,12 @@ internal class ExpressionDecomposer private constructor(
|
||||
|
||||
// TODO: add test case (after KT-7371 fix): var a = foo(), b = foo() + inlineBar()
|
||||
override fun visit(x: JsVars, ctx: JsContext<JsNode>): Boolean {
|
||||
val vars = x.getVars()
|
||||
val vars = x.vars
|
||||
var prevVars = SmartList<JsVars.JsVar>()
|
||||
|
||||
for (jsVar in vars) {
|
||||
if (jsVar in containsExtractable && prevVars.isNotEmpty()) {
|
||||
addStatement(JsVars(prevVars, x.isMultiline()))
|
||||
addStatement(JsVars(prevVars, x.isMultiline))
|
||||
prevVars = SmartList<JsVars.JsVar>()
|
||||
}
|
||||
|
||||
@@ -163,7 +162,7 @@ internal class ExpressionDecomposer private constructor(
|
||||
return
|
||||
}
|
||||
|
||||
if (operator.isAssignment()) {
|
||||
if (operator.isAssignment) {
|
||||
// Must be (someThingWithSideEffect).x = arg2, because arg1 can have side effect
|
||||
assert(arg1 is JsNameRef) { "Valid JavaScript left-hand side must be JsNameRef, got: $this" }
|
||||
val arg1AsRef = arg1 as JsNameRef
|
||||
@@ -177,7 +176,7 @@ internal class ExpressionDecomposer private constructor(
|
||||
}
|
||||
|
||||
override fun visit(x: JsArrayLiteral, ctx: JsContext<JsNode>): Boolean {
|
||||
val elements = x.getExpressions()
|
||||
val elements = x.expressions
|
||||
processByIndices(elements, elements.indicesOfExtractable)
|
||||
return false
|
||||
}
|
||||
@@ -238,19 +237,19 @@ internal class ExpressionDecomposer private constructor(
|
||||
|
||||
private abstract class Callable(hasArguments: HasArguments) {
|
||||
abstract var qualifier: JsExpression
|
||||
val arguments = hasArguments.getArguments()
|
||||
val arguments = hasArguments.arguments
|
||||
}
|
||||
|
||||
private class CallableInvocationAdapter(val invocation: JsInvocation) : Callable(invocation) {
|
||||
override var qualifier: JsExpression
|
||||
get() = invocation.getQualifier()
|
||||
set(value) = invocation.setQualifier(value)
|
||||
get() = invocation.qualifier
|
||||
set(value) = invocation.qualifier = value
|
||||
}
|
||||
|
||||
private class CallableNewAdapter(val jsnew: JsNew) : Callable(jsnew) {
|
||||
override var qualifier: JsExpression
|
||||
get() = jsnew.getConstructorExpression()
|
||||
set(value) = jsnew.setConstructorExpression(value)
|
||||
get() = jsnew.constructorExpression
|
||||
set(value) = jsnew.constructorExpression = value
|
||||
}
|
||||
|
||||
private fun Callable.process() {
|
||||
@@ -373,8 +372,8 @@ internal open class JsExpressionVisitor() : JsVisitorWithContextImpl() {
|
||||
override fun visit(x: JsFor, ctx: JsContext<JsNode>): Boolean = false
|
||||
|
||||
override fun visit(x: JsIf, ctx: JsContext<JsNode>): Boolean {
|
||||
val test = x.getIfExpression()
|
||||
x.setIfExpression(accept(test))
|
||||
val test = x.ifExpression
|
||||
x.ifExpression = accept(test)
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
@@ -38,13 +38,13 @@ private constructor(
|
||||
private val body: JsBlock
|
||||
private var resultExpr: JsExpression? = null
|
||||
private var breakLabel: JsLabel? = null
|
||||
private val currentStatement = inliningContext.statementContext.getCurrentNode()
|
||||
private val currentStatement = inliningContext.statementContext.currentNode
|
||||
|
||||
init {
|
||||
|
||||
val functionContext = inliningContext.functionContext
|
||||
invokedFunction = functionContext.getFunctionDefinition(call)
|
||||
body = invokedFunction.getBody().deepCopy()
|
||||
body = invokedFunction.body.deepCopy()
|
||||
isResultNeeded = isResultNeeded(call)
|
||||
namingContext = inliningContext.newNamingContext()
|
||||
}
|
||||
@@ -82,7 +82,7 @@ private constructor(
|
||||
}
|
||||
|
||||
private fun removeStatementsAfterTopReturn() {
|
||||
val statements = body.getStatements()
|
||||
val statements = body.statements
|
||||
|
||||
val statementsSize = statements.size
|
||||
for (i in 0..statementsSize - 1) {
|
||||
@@ -96,7 +96,7 @@ private constructor(
|
||||
}
|
||||
|
||||
private fun processReturns() {
|
||||
if (currentStatement is JsReturn && currentStatement.getExpression() === call) {
|
||||
if (currentStatement is JsReturn && currentStatement.expression === call) {
|
||||
inliningContext.statementContext.removeMe()
|
||||
return
|
||||
}
|
||||
@@ -109,11 +109,11 @@ private constructor(
|
||||
}
|
||||
|
||||
if (returnCount == 1) {
|
||||
val statements = body.getStatements()
|
||||
val statements = body.statements
|
||||
val lastTopLevelStatement = statements[statements.lastIndex]
|
||||
|
||||
if (lastTopLevelStatement is JsReturn) {
|
||||
resultExpr = lastTopLevelStatement.getExpression()
|
||||
resultExpr = lastTopLevelStatement.expression
|
||||
statements.removeAt(statements.lastIndex)
|
||||
return
|
||||
}
|
||||
@@ -135,10 +135,10 @@ private constructor(
|
||||
val visitor = ReturnReplacingVisitor(resultExpr as? JsNameRef, breakName.makeRef())
|
||||
visitor.accept(body)
|
||||
|
||||
val statements = body.getStatements()
|
||||
val statements = body.statements
|
||||
val last = statements.lastOrNull() as? JsBreak
|
||||
|
||||
if (last?.getLabel()?.getName() === breakLabel?.getName()) {
|
||||
if (last?.label?.name === breakLabel?.name) {
|
||||
statements.removeAt(statements.lastIndex)
|
||||
}
|
||||
}
|
||||
@@ -148,7 +148,7 @@ private constructor(
|
||||
|
||||
val existingReference = when (currentStatement) {
|
||||
is JsExpressionStatement -> {
|
||||
val expression = currentStatement.getExpression() as? JsBinaryOperation
|
||||
val expression = currentStatement.expression as? JsBinaryOperation
|
||||
expression?.getResultReference()
|
||||
}
|
||||
is JsVars -> currentStatement.getResultReference()
|
||||
@@ -169,7 +169,7 @@ private constructor(
|
||||
}
|
||||
|
||||
private fun JsVars.getResultReference(): JsNameRef? {
|
||||
val vars = getVars()
|
||||
val vars = vars
|
||||
val variable = vars.first()
|
||||
|
||||
// var a = expr1 + call() is ok, but we don't want to reuse 'a' for result,
|
||||
@@ -177,7 +177,7 @@ private constructor(
|
||||
// If there is more than one return, expr1 copies are undesirable.
|
||||
if (variable.initExpression !== call || vars.size > 1) return null
|
||||
|
||||
val varName = variable.getName()
|
||||
val varName = variable.name
|
||||
with (inliningContext.statementContext) {
|
||||
removeMe()
|
||||
addPrevious(newVar(varName, null))
|
||||
@@ -187,7 +187,7 @@ private constructor(
|
||||
}
|
||||
|
||||
private fun getArguments(): List<JsExpression> {
|
||||
val arguments = call.getArguments()
|
||||
val arguments = call.arguments
|
||||
if (isCallInvocation(call)) {
|
||||
return arguments.subList(1, arguments.size)
|
||||
}
|
||||
@@ -196,11 +196,11 @@ private constructor(
|
||||
}
|
||||
|
||||
private fun isResultNeeded(call: JsInvocation): Boolean {
|
||||
return currentStatement !is JsExpressionStatement || call != currentStatement.getExpression()
|
||||
return currentStatement !is JsExpressionStatement || call != currentStatement.expression
|
||||
}
|
||||
|
||||
private fun getParameters(): List<JsParameter> {
|
||||
return invokedFunction.getParameters()
|
||||
return invokedFunction.parameters
|
||||
}
|
||||
|
||||
private fun getResultLabel(): String {
|
||||
@@ -228,15 +228,14 @@ private constructor(
|
||||
|
||||
companion object {
|
||||
|
||||
@JvmStatic
|
||||
public fun getInlineableCallReplacement(call: JsInvocation, inliningContext: InliningContext): InlineableResult {
|
||||
@JvmStatic fun getInlineableCallReplacement(call: JsInvocation, inliningContext: InliningContext): InlineableResult {
|
||||
val mutator = FunctionInlineMutator(call, inliningContext)
|
||||
mutator.process()
|
||||
|
||||
var inlineableBody: JsStatement = mutator.body
|
||||
val breakLabel = mutator.breakLabel
|
||||
if (breakLabel != null) {
|
||||
breakLabel.setStatement(inlineableBody)
|
||||
breakLabel.statement = inlineableBody
|
||||
inlineableBody = breakLabel
|
||||
}
|
||||
|
||||
@@ -246,7 +245,7 @@ private constructor(
|
||||
@JvmStatic
|
||||
private fun getThisReplacement(call: JsInvocation): JsExpression? {
|
||||
if (isCallInvocation(call)) {
|
||||
return call.getArguments().get(0)
|
||||
return call.arguments.get(0)
|
||||
}
|
||||
|
||||
if (hasCallerQualifier(call)) {
|
||||
@@ -261,13 +260,12 @@ private constructor(
|
||||
return !thisRefs.isEmpty()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
public fun canBeExpression(function: JsFunction): Boolean {
|
||||
return canBeExpression(function.getBody())
|
||||
@JvmStatic fun canBeExpression(function: JsFunction): Boolean {
|
||||
return canBeExpression(function.body)
|
||||
}
|
||||
|
||||
private fun canBeExpression(body: JsBlock): Boolean {
|
||||
val statements = body.getStatements()
|
||||
val statements = body.statements
|
||||
return statements.size == 1 && statements.get(0) is JsReturn
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ import java.io.File
|
||||
*/
|
||||
private val DEFINE_MODULE_PATTERN = "(\\w+)\\.defineModule\\(\\s*(['\"])(\\w+)\\2\\s*,\\s*(\\w+)\\s*\\)".toRegex()
|
||||
|
||||
public class FunctionReader(private val context: TranslationContext) {
|
||||
class FunctionReader(private val context: TranslationContext) {
|
||||
/**
|
||||
* Maps module name to .js file content, that contains this module definition.
|
||||
* One file can contain more than one module definition.
|
||||
@@ -65,8 +65,8 @@ public class FunctionReader(private val context: TranslationContext) {
|
||||
private val moduleKotlinVariable = hashMapOf<String, String>()
|
||||
|
||||
init {
|
||||
val config = context.getConfig() as LibrarySourcesConfig
|
||||
val libs = config.getLibraries().map { File(it) }
|
||||
val config = context.config as LibrarySourcesConfig
|
||||
val libs = config.libraries.map { File(it) }
|
||||
|
||||
LibraryUtils.traverseJsLibraries(libs) { fileContent, path ->
|
||||
val matcher = DEFINE_MODULE_PATTERN.toPattern().matcher(fileContent)
|
||||
@@ -90,7 +90,7 @@ public class FunctionReader(private val context: TranslationContext) {
|
||||
|
||||
operator fun contains(descriptor: CallableDescriptor): Boolean {
|
||||
val moduleName = getExternalModuleName(descriptor)
|
||||
val currentModuleName = context.getConfig().getModuleId()
|
||||
val currentModuleName = context.config.moduleId
|
||||
return currentModuleName != moduleName && moduleName != null && moduleName in moduleJsDefinition
|
||||
}
|
||||
|
||||
@@ -133,8 +133,8 @@ private val Char.isWhitespaceOrComma: Boolean
|
||||
get() = this == ',' || this.isWhitespace()
|
||||
|
||||
private fun JsFunction.markInlineArguments(descriptor: CallableDescriptor) {
|
||||
val params = descriptor.getValueParameters()
|
||||
val paramsJs = getParameters()
|
||||
val params = descriptor.valueParameters
|
||||
val paramsJs = parameters
|
||||
val inlineFuns = IdentitySet<JsName>()
|
||||
val inlineExtensionFuns = IdentitySet<JsName>()
|
||||
val offset = if (descriptor.isExtension) 1 else 0
|
||||
@@ -142,11 +142,11 @@ private fun JsFunction.markInlineArguments(descriptor: CallableDescriptor) {
|
||||
for ((i, param) in params.withIndex()) {
|
||||
if (!CallExpressionTranslator.shouldBeInlined(descriptor)) continue
|
||||
|
||||
val type = param.getType()
|
||||
val type = param.type
|
||||
if (!KotlinBuiltIns.isFunctionOrExtensionFunctionType(type)) continue
|
||||
|
||||
val namesSet = if (KotlinBuiltIns.isExtensionFunctionType(type)) inlineExtensionFuns else inlineFuns
|
||||
namesSet.add(paramsJs[i + offset].getName())
|
||||
namesSet.add(paramsJs[i + offset].name)
|
||||
}
|
||||
|
||||
val visitor = object: JsVisitorWithContextImpl() {
|
||||
@@ -155,10 +155,10 @@ private fun JsFunction.markInlineArguments(descriptor: CallableDescriptor) {
|
||||
val namesSet: Set<JsName>
|
||||
|
||||
if (isCallInvocation(x)) {
|
||||
qualifier = (x.getQualifier() as? JsNameRef)?.getQualifier()
|
||||
qualifier = (x.qualifier as? JsNameRef)?.qualifier
|
||||
namesSet = inlineExtensionFuns
|
||||
} else {
|
||||
qualifier = x.getQualifier()
|
||||
qualifier = x.qualifier
|
||||
namesSet = inlineFuns
|
||||
}
|
||||
|
||||
@@ -174,15 +174,15 @@ private fun JsFunction.markInlineArguments(descriptor: CallableDescriptor) {
|
||||
}
|
||||
|
||||
private fun replaceExternalNames(function: JsFunction, externalReplacements: Map<String, JsExpression>) {
|
||||
val replacements = externalReplacements.filterKeys { !function.getScope().hasOwnName(it) }
|
||||
val replacements = externalReplacements.filterKeys { !function.scope.hasOwnName(it) }
|
||||
|
||||
if (replacements.isEmpty()) return
|
||||
|
||||
val visitor = object: JsVisitorWithContextImpl() {
|
||||
override fun endVisit(x: JsNameRef, ctx: JsContext<JsNode>) {
|
||||
if (x.getQualifier() != null) return
|
||||
if (x.qualifier != null) return
|
||||
|
||||
replacements[x.getIdent()]?.let {
|
||||
replacements[x.ident]?.let {
|
||||
ctx.replaceMe(it)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,21 +26,21 @@ internal class ReferenceTracker<Reference, RemoveCandidate : JsNode> {
|
||||
private val referenceFromTo = IdentityHashMap<Reference, MutableSet<Reference>>()
|
||||
private val visited = IdentitySet<Reference>()
|
||||
|
||||
public val removable: List<RemoveCandidate>
|
||||
val removable: List<RemoveCandidate>
|
||||
get() {
|
||||
return reachable
|
||||
.filter { !it.value }
|
||||
.map { removableCandidates.get(it.key)!! }
|
||||
}
|
||||
|
||||
public fun addCandidateForRemoval(reference: Reference, candidate: RemoveCandidate) {
|
||||
fun addCandidateForRemoval(reference: Reference, candidate: RemoveCandidate) {
|
||||
assert(!isKnown(reference)) { "Candidate for removal cannot be reassigned: $candidate" }
|
||||
|
||||
removableCandidates.put(reference, candidate)
|
||||
reachable.put(reference, false)
|
||||
}
|
||||
|
||||
public fun addRemovableReference(referrer: Reference, referenced: Reference) {
|
||||
fun addRemovableReference(referrer: Reference, referenced: Reference) {
|
||||
if (!isKnown(referenced)) return
|
||||
|
||||
getReferencedBy(referrer).add(referenced)
|
||||
@@ -50,7 +50,7 @@ internal class ReferenceTracker<Reference, RemoveCandidate : JsNode> {
|
||||
}
|
||||
}
|
||||
|
||||
public fun markReachable(reference: Reference) {
|
||||
fun markReachable(reference: Reference) {
|
||||
if (!isKnown(reference)) return
|
||||
|
||||
visited.add(reference)
|
||||
|
||||
+16
-16
@@ -31,11 +31,11 @@ import org.jetbrains.kotlin.js.translate.utils.JsAstUtils.flattenStatement
|
||||
*
|
||||
* @see isInitializer
|
||||
*/
|
||||
public fun removeDefaultInitializers(arguments: List<JsExpression>, parameters: List<JsParameter>, body: JsBlock) {
|
||||
fun removeDefaultInitializers(arguments: List<JsExpression>, parameters: List<JsParameter>, body: JsBlock) {
|
||||
val toRemove = getDefaultParamsNames(arguments, parameters, initialized = true)
|
||||
val toExpand = getDefaultParamsNames(arguments, parameters, initialized = false)
|
||||
|
||||
val statements = body.getStatements()
|
||||
val statements = body.statements
|
||||
val newStatements = statements.flatMap {
|
||||
val name = getNameFromInitializer(it)
|
||||
if (name != null && !isNameInitialized(name, it)) {
|
||||
@@ -46,7 +46,7 @@ public fun removeDefaultInitializers(arguments: List<JsExpression>, parameters:
|
||||
name != null && name in toRemove ->
|
||||
listOf<JsStatement>()
|
||||
name != null && name in toExpand ->
|
||||
flattenStatement((it as JsIf).getThenStatement()!!)
|
||||
flattenStatement((it as JsIf).thenStatement!!)
|
||||
else ->
|
||||
listOf(it)
|
||||
}
|
||||
@@ -58,9 +58,9 @@ public fun removeDefaultInitializers(arguments: List<JsExpression>, parameters:
|
||||
|
||||
private fun getNameFromInitializer(statement: JsStatement): JsName? {
|
||||
val ifStmt = (statement as? JsIf)
|
||||
val testExpr = ifStmt?.getIfExpression()
|
||||
val testExpr = ifStmt?.ifExpression
|
||||
|
||||
val elseStmt = ifStmt?.getElseStatement()
|
||||
val elseStmt = ifStmt?.elseStatement
|
||||
if (elseStmt == null && testExpr is JsBinaryOperation)
|
||||
return getNameFromInitializer(testExpr)
|
||||
|
||||
@@ -68,16 +68,16 @@ private fun getNameFromInitializer(statement: JsStatement): JsName? {
|
||||
}
|
||||
|
||||
private fun getNameFromInitializer(isInitializedExpr: JsBinaryOperation): JsName? {
|
||||
val arg1 = isInitializedExpr.getArg1()
|
||||
val arg2 = isInitializedExpr.getArg2()
|
||||
val op = isInitializedExpr.getOperator()
|
||||
val arg1 = isInitializedExpr.arg1
|
||||
val arg2 = isInitializedExpr.arg2
|
||||
val op = isInitializedExpr.operator
|
||||
|
||||
if (arg1 == null || arg2 == null || op == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (op == JsBinaryOperator.REF_EQ && isUndefined(arg2)) {
|
||||
return (arg1 as? JsNameRef)?.getName()
|
||||
return (arg1 as? JsNameRef)?.name
|
||||
}
|
||||
|
||||
return null
|
||||
@@ -91,17 +91,17 @@ private fun isNameInitialized(
|
||||
name: JsName,
|
||||
initializer: JsStatement
|
||||
): Boolean {
|
||||
val thenStmt = (initializer as JsIf).getThenStatement()!!
|
||||
val thenStmt = (initializer as JsIf).thenStatement!!
|
||||
val lastThenStmt = flattenStatement(thenStmt).last()
|
||||
|
||||
val expr = (lastThenStmt as? JsExpressionStatement)?.getExpression()
|
||||
val expr = (lastThenStmt as? JsExpressionStatement)?.expression
|
||||
if (expr !is JsBinaryOperation) return false
|
||||
|
||||
val op = expr.getOperator()
|
||||
if (!op.isAssignment()) return false
|
||||
val op = expr.operator
|
||||
if (!op.isAssignment) return false
|
||||
|
||||
val arg1 = expr.getArg1()
|
||||
if (arg1 is HasName && arg1.getName() === name) return true
|
||||
val arg1 = expr.arg1
|
||||
if (arg1 is HasName && arg1.name === name) return true
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -117,7 +117,7 @@ private fun getDefaultParamsNames(
|
||||
.filter { it.second.hasDefaultValue }
|
||||
.filter { initialized == !isUndefined(it.first) }
|
||||
|
||||
val names = relevantParams.map { it.second.getName() }
|
||||
val names = relevantParams.map { it.second.name }
|
||||
return names.toIdentitySet()
|
||||
}
|
||||
|
||||
|
||||
+7
-7
@@ -30,7 +30,7 @@ import org.jetbrains.kotlin.js.inline.util.collectFunctionReferencesInside
|
||||
* At now, it only removes unused local functions and function literals,
|
||||
* because named functions can be referenced from another module.
|
||||
*/
|
||||
public fun removeUnusedFunctionDefinitions(root: JsNode, functions: Map<JsName, JsFunction>) {
|
||||
fun removeUnusedFunctionDefinitions(root: JsNode, functions: Map<JsName, JsFunction>) {
|
||||
val removable = with(UnusedLocalFunctionsCollector(functions)) {
|
||||
process()
|
||||
accept(root)
|
||||
@@ -38,7 +38,7 @@ public fun removeUnusedFunctionDefinitions(root: JsNode, functions: Map<JsName,
|
||||
}
|
||||
|
||||
NodeRemover(JsPropertyInitializer::class.java) {
|
||||
val function = it.getValueExpr() as? JsFunction
|
||||
val function = it.valueExpr as? JsFunction
|
||||
function != null && function in removable
|
||||
}.accept(root)
|
||||
}
|
||||
@@ -48,10 +48,10 @@ private class UnusedLocalFunctionsCollector(functions: Map<JsName, JsFunction>)
|
||||
private val functions = functions
|
||||
private val processed = IdentitySet<JsFunction>()
|
||||
|
||||
public val removableFunctions: List<JsFunction>
|
||||
val removableFunctions: List<JsFunction>
|
||||
get() = tracker.removable
|
||||
|
||||
public fun process() {
|
||||
fun process() {
|
||||
functions.filter { it.value.isLocal }
|
||||
.forEach { tracker.addCandidateForRemoval(it.key, it.value) }
|
||||
|
||||
@@ -67,7 +67,7 @@ private class UnusedLocalFunctionsCollector(functions: Map<JsName, JsFunction>)
|
||||
}
|
||||
|
||||
override fun visit(x: JsPropertyInitializer, ctx: JsContext<*>): Boolean {
|
||||
val value = x.getValueExpr()
|
||||
val value = x.valueExpr
|
||||
|
||||
return when (value) {
|
||||
is JsFunction -> !wasProcessed(value)
|
||||
@@ -84,7 +84,7 @@ private class UnusedLocalFunctionsCollector(functions: Map<JsName, JsFunction>)
|
||||
}
|
||||
|
||||
override fun endVisit(x: JsNameRef, ctx: JsContext<*>) {
|
||||
val name = x.getName()
|
||||
val name = x.name
|
||||
if (isFunctionReference(x) && name != null) {
|
||||
tracker.markReachable(name)
|
||||
}
|
||||
@@ -103,7 +103,7 @@ private class UnusedLocalFunctionsCollector(functions: Map<JsName, JsFunction>)
|
||||
}
|
||||
|
||||
private fun isFunctionReference(nameRef: HasName?): Boolean {
|
||||
return nameRef?.getName()?.staticRef is JsFunction
|
||||
return nameRef?.name?.staticRef is JsFunction
|
||||
}
|
||||
|
||||
private fun wasProcessed(function: JsFunction?): Boolean = function != null && function in processed
|
||||
|
||||
+8
-8
@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.js.inline.util.collectReferencesInside
|
||||
*
|
||||
* Declaration can become unused, if inlining happened.
|
||||
*/
|
||||
public fun removeUnusedLocalFunctionDeclarations(root: JsNode) {
|
||||
fun removeUnusedLocalFunctionDeclarations(root: JsNode) {
|
||||
val removable =
|
||||
with(UnusedInstanceCollector()) {
|
||||
accept(root)
|
||||
@@ -42,15 +42,15 @@ public fun removeUnusedLocalFunctionDeclarations(root: JsNode) {
|
||||
private class UnusedInstanceCollector : JsVisitorWithContextImpl() {
|
||||
private val tracker = ReferenceTracker<JsName, JsStatement>()
|
||||
|
||||
public val removableDeclarations: List<JsStatement>
|
||||
val removableDeclarations: List<JsStatement>
|
||||
get() = tracker.removable
|
||||
|
||||
override fun visit(x: JsVars.JsVar, ctx: JsContext<*>): Boolean {
|
||||
if (!isLocalFunctionDeclaration(x)) return super.visit(x, ctx)
|
||||
|
||||
val name = x.getName()!!
|
||||
val statementContext = getLastStatementLevelContext()
|
||||
val currentStatement = statementContext.getCurrentNode()
|
||||
val name = x.name!!
|
||||
val statementContext = lastStatementLevelContext
|
||||
val currentStatement = statementContext.currentNode
|
||||
tracker.addCandidateForRemoval(name, currentStatement!!)
|
||||
|
||||
val references = collectReferencesInside(x)
|
||||
@@ -61,7 +61,7 @@ private class UnusedInstanceCollector : JsVisitorWithContextImpl() {
|
||||
}
|
||||
|
||||
override fun visit(x: JsNameRef, ctx: JsContext<*>): Boolean {
|
||||
val name = x.getName()
|
||||
val name = x.name
|
||||
|
||||
if (name != null) {
|
||||
tracker.markReachable(name)
|
||||
@@ -71,8 +71,8 @@ private class UnusedInstanceCollector : JsVisitorWithContextImpl() {
|
||||
}
|
||||
|
||||
private fun isLocalFunctionDeclaration(jsVar: JsVars.JsVar): Boolean {
|
||||
val name = jsVar.getName()
|
||||
val expr = jsVar.getInitExpression()
|
||||
val name = jsVar.name
|
||||
val expr = jsVar.initExpression
|
||||
val staticRef = name?.staticRef
|
||||
|
||||
return staticRef != null && staticRef == expr
|
||||
|
||||
@@ -44,19 +44,19 @@ abstract class FunctionContext(
|
||||
|
||||
protected abstract fun lookUpStaticFunction(functionName: JsName?): JsFunction?
|
||||
|
||||
public fun getFunctionDefinition(call: JsInvocation): JsFunction {
|
||||
fun getFunctionDefinition(call: JsInvocation): JsFunction {
|
||||
return getFunctionDefinitionImpl(call)!!
|
||||
}
|
||||
|
||||
public fun hasFunctionDefinition(call: JsInvocation): Boolean {
|
||||
fun hasFunctionDefinition(call: JsInvocation): Boolean {
|
||||
return getFunctionDefinitionImpl(call) != null
|
||||
}
|
||||
|
||||
public fun getScope(): JsScope {
|
||||
return function.getScope()
|
||||
fun getScope(): JsScope {
|
||||
return function.scope
|
||||
}
|
||||
|
||||
public fun declareFunctionConstructorCalls(arguments: List<JsExpression>) {
|
||||
fun declareFunctionConstructorCalls(arguments: List<JsExpression>) {
|
||||
val calls = ContainerUtil.findAll<JsExpression, JsInvocation>(arguments, JsInvocation::class.java)
|
||||
|
||||
for (call in calls) {
|
||||
@@ -73,7 +73,7 @@ abstract class FunctionContext(
|
||||
}
|
||||
}
|
||||
|
||||
public fun declareFunctionConstructorCall(call: JsInvocation) {
|
||||
fun declareFunctionConstructorCall(call: JsInvocation) {
|
||||
functionsWithClosure.put(call, null)
|
||||
}
|
||||
|
||||
@@ -112,16 +112,16 @@ abstract class FunctionContext(
|
||||
if (descriptor != null && descriptor in functionReader) return functionReader[descriptor]
|
||||
|
||||
/** remove ending `()` */
|
||||
var callQualifier = call.getQualifier()
|
||||
var callQualifier = call.qualifier
|
||||
|
||||
/** remove ending `.call()` */
|
||||
if (isCallInvocation(call)) {
|
||||
callQualifier = (callQualifier as JsNameRef).getQualifier()!!
|
||||
callQualifier = (callQualifier as JsNameRef).qualifier!!
|
||||
}
|
||||
|
||||
/** in case 4, 5 get ref (reduce 4, 5 to 2, 3 accordingly) */
|
||||
if (callQualifier is JsNameRef) {
|
||||
val staticRef = callQualifier.getName()?.staticRef
|
||||
val staticRef = callQualifier.name?.staticRef
|
||||
|
||||
callQualifier = when (staticRef) {
|
||||
is JsNameRef -> staticRef
|
||||
@@ -135,7 +135,7 @@ abstract class FunctionContext(
|
||||
val qualifier = callQualifier
|
||||
return when (qualifier) {
|
||||
is JsInvocation -> getFunctionWithClosure(qualifier)
|
||||
is JsNameRef -> lookUpStaticFunction(qualifier.getName())
|
||||
is JsNameRef -> lookUpStaticFunction(qualifier.name)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
@@ -180,8 +180,8 @@ abstract class FunctionContext(
|
||||
val innerClone = inner.deepCopy()
|
||||
|
||||
val namingContext = inliningContext.newNamingContext()
|
||||
val arguments = call.getArguments()
|
||||
val parameters = outer.getParameters()
|
||||
val arguments = call.arguments
|
||||
val parameters = outer.parameters
|
||||
aliasArgumentsIfNeeded(namingContext, arguments, parameters)
|
||||
namingContext.applyRenameTo(innerClone)
|
||||
|
||||
|
||||
@@ -20,8 +20,8 @@ import com.google.dart.compiler.backend.js.ast.JsContext
|
||||
import com.google.dart.compiler.backend.js.ast.JsStatement
|
||||
|
||||
interface InliningContext {
|
||||
public val statementContext: JsContext<JsStatement>
|
||||
public val functionContext: FunctionContext
|
||||
val statementContext: JsContext<JsStatement>
|
||||
val functionContext: FunctionContext
|
||||
|
||||
public fun newNamingContext(): NamingContext
|
||||
fun newNamingContext(): NamingContext
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ class NamingContext(
|
||||
private val declarations = ArrayList<JsVars>()
|
||||
private var addedDeclarations = false
|
||||
|
||||
public fun applyRenameTo(target: JsNode): JsNode {
|
||||
fun applyRenameTo(target: JsNode): JsNode {
|
||||
if (!addedDeclarations) {
|
||||
statementContext.addPrevious(declarations)
|
||||
addedDeclarations = true
|
||||
@@ -41,17 +41,17 @@ class NamingContext(
|
||||
return replaceNames(target, renamings)
|
||||
}
|
||||
|
||||
public fun replaceName(name: JsName, replacement: JsExpression) {
|
||||
fun replaceName(name: JsName, replacement: JsExpression) {
|
||||
assert(!renamings.containsKey(name)) { "$name has been renamed already" }
|
||||
|
||||
renamings.put(name, replacement)
|
||||
}
|
||||
|
||||
public fun getFreshName(candidate: String): JsName = scope.declareFreshName(candidate)
|
||||
fun getFreshName(candidate: String): JsName = scope.declareFreshName(candidate)
|
||||
|
||||
public fun getFreshName(candidate: JsName): JsName = getFreshName(candidate.getIdent())
|
||||
fun getFreshName(candidate: JsName): JsName = getFreshName(candidate.ident)
|
||||
|
||||
public fun newVar(name: JsName, value: JsExpression? = null) {
|
||||
fun newVar(name: JsName, value: JsExpression? = null) {
|
||||
val vars = JsAstUtils.newVar(name, value)
|
||||
declarations.add(vars)
|
||||
}
|
||||
|
||||
@@ -26,32 +26,32 @@ import org.jetbrains.kotlin.js.inline.util.collectors.InstanceCollector
|
||||
import org.jetbrains.kotlin.js.inline.util.collectors.PropertyCollector
|
||||
import org.jetbrains.kotlin.js.translate.expression.*
|
||||
|
||||
public fun collectFunctionReferencesInside(scope: JsNode): List<JsName> =
|
||||
fun collectFunctionReferencesInside(scope: JsNode): List<JsName> =
|
||||
collectReferencesInside(scope).filter { it.staticRef is JsFunction }
|
||||
|
||||
public fun collectReferencesInside(scope: JsNode): List<JsName> {
|
||||
fun collectReferencesInside(scope: JsNode): List<JsName> {
|
||||
return with(ReferenceNameCollector()) {
|
||||
accept(scope)
|
||||
references
|
||||
}
|
||||
}
|
||||
|
||||
public fun collectLocalNames(function: JsFunction): List<JsName> {
|
||||
val functionScope = function.getScope()
|
||||
fun collectLocalNames(function: JsFunction): List<JsName> {
|
||||
val functionScope = function.scope
|
||||
|
||||
return with(NameCollector(functionScope)) {
|
||||
accept(function.getBody())
|
||||
accept(function.body)
|
||||
names.values.toList()
|
||||
}
|
||||
}
|
||||
|
||||
public fun collectJsProperties(scope: JsNode): IdentityHashMap<JsName, JsExpression> {
|
||||
fun collectJsProperties(scope: JsNode): IdentityHashMap<JsName, JsExpression> {
|
||||
val collector = PropertyCollector()
|
||||
collector.accept(scope)
|
||||
return collector.properties
|
||||
}
|
||||
|
||||
public fun collectNamedFunctions(scope: JsNode): IdentityHashMap<JsName, JsFunction> {
|
||||
fun collectNamedFunctions(scope: JsNode): IdentityHashMap<JsName, JsFunction> {
|
||||
val namedFunctions = IdentityHashMap<JsName, JsFunction>()
|
||||
|
||||
for ((name, value) in collectJsProperties(scope)) {
|
||||
@@ -68,7 +68,7 @@ public fun collectNamedFunctions(scope: JsNode): IdentityHashMap<JsName, JsFunct
|
||||
return namedFunctions
|
||||
}
|
||||
|
||||
public fun <T : JsNode> collectInstances(klass: Class<T>, scope: JsNode): List<T> {
|
||||
fun <T : JsNode> collectInstances(klass: Class<T>, scope: JsNode): List<T> {
|
||||
return with(InstanceCollector(klass, visitNestedDeclarations = false)) {
|
||||
accept(scope)
|
||||
collected
|
||||
|
||||
@@ -19,11 +19,11 @@ package org.jetbrains.kotlin.js.inline.util
|
||||
import java.util.Collections
|
||||
import java.util.IdentityHashMap
|
||||
|
||||
public fun <T> IdentitySet(): MutableSet<T> {
|
||||
fun <T> IdentitySet(): MutableSet<T> {
|
||||
return Collections.newSetFromMap(IdentityHashMap<T, Boolean>())
|
||||
}
|
||||
|
||||
public fun <T> Collection<T>.toIdentitySet(): MutableSet<T> {
|
||||
fun <T> Collection<T>.toIdentitySet(): MutableSet<T> {
|
||||
val result = IdentitySet<T>()
|
||||
for (element in this) {
|
||||
result.add(element)
|
||||
@@ -32,7 +32,7 @@ public fun <T> Collection<T>.toIdentitySet(): MutableSet<T> {
|
||||
return result
|
||||
}
|
||||
|
||||
public fun <T> Sequence<T>.toIdentitySet(): MutableSet<T> {
|
||||
fun <T> Sequence<T>.toIdentitySet(): MutableSet<T> {
|
||||
val result = IdentitySet<T>()
|
||||
for (element in this) {
|
||||
result.add(element)
|
||||
@@ -41,7 +41,7 @@ public fun <T> Sequence<T>.toIdentitySet(): MutableSet<T> {
|
||||
return result
|
||||
}
|
||||
|
||||
public fun <T, R> Iterable<T>.zipWithDefault(
|
||||
fun <T, R> Iterable<T>.zipWithDefault(
|
||||
other: Iterable<R>,
|
||||
defaultT: T
|
||||
): List<Pair<T, R>> {
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ import com.google.dart.compiler.backend.js.ast.RecursiveJsVisitor
|
||||
import java.util.ArrayList
|
||||
|
||||
class InstanceCollector<T : JsNode>(val klass: Class<T>, val visitNestedDeclarations: Boolean) : RecursiveJsVisitor() {
|
||||
public val collected: MutableList<T> = ArrayList()
|
||||
val collected: MutableList<T> = ArrayList()
|
||||
|
||||
override fun visitFunction(x: JsFunction) {
|
||||
if (visitNestedDeclarations) {
|
||||
|
||||
@@ -26,7 +26,7 @@ import com.google.dart.compiler.backend.js.ast.JsVars
|
||||
import java.util.HashMap
|
||||
|
||||
class NameCollector(private val scope: JsScope) : RecursiveJsVisitor() {
|
||||
public val names: MutableMap<String, JsName> = HashMap()
|
||||
val names: MutableMap<String, JsName> = HashMap()
|
||||
|
||||
override fun visit(x: JsVars.JsVar) {
|
||||
super.visit(x)
|
||||
@@ -36,8 +36,8 @@ class NameCollector(private val scope: JsScope) : RecursiveJsVisitor() {
|
||||
override fun visitFunction(x: JsFunction) { }
|
||||
|
||||
private fun addNameIfNeeded(hasName: HasName?) {
|
||||
val name = hasName?.getName()
|
||||
val ident = name?.getIdent()
|
||||
val name = hasName?.name
|
||||
val ident = name?.ident
|
||||
|
||||
if (name == null || ident == null) return
|
||||
|
||||
|
||||
+4
-4
@@ -22,16 +22,16 @@ import org.jetbrains.kotlin.js.translate.expression.InlineMetadata
|
||||
import java.util.IdentityHashMap
|
||||
|
||||
class PropertyCollector : RecursiveJsVisitor() {
|
||||
public val properties: IdentityHashMap<JsName, JsExpression> = IdentityHashMap()
|
||||
val properties: IdentityHashMap<JsName, JsExpression> = IdentityHashMap()
|
||||
|
||||
override fun visitPropertyInitializer(x: JsPropertyInitializer) {
|
||||
super.visitPropertyInitializer(x)
|
||||
|
||||
val label = x.getLabelExpr() as? JsNameRef
|
||||
val name = label?.getName()
|
||||
val label = x.labelExpr as? JsNameRef
|
||||
val name = label?.name
|
||||
if (name == null) return
|
||||
|
||||
val value = x.getValueExpr()
|
||||
val value = x.valueExpr
|
||||
properties[name] = value
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -25,11 +25,11 @@ import org.jetbrains.kotlin.js.inline.util.IdentitySet
|
||||
class ReferenceNameCollector : JsVisitorWithContextImpl() {
|
||||
private val referenceSet = IdentitySet<JsName>()
|
||||
|
||||
public val references: List<JsName>
|
||||
val references: List<JsName>
|
||||
get() = referenceSet.toList()
|
||||
|
||||
override fun endVisit(x: JsNameRef, ctx: JsContext<*>) {
|
||||
val name = x.getName()
|
||||
val name = x.name
|
||||
if (name != null) {
|
||||
referenceSet.add(name)
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ package org.jetbrains.kotlin.js.inline.util
|
||||
import com.google.dart.compiler.backend.js.ast.JsFunction
|
||||
import com.google.dart.compiler.backend.js.ast.JsReturn
|
||||
|
||||
public fun isFunctionCreator(outer: JsFunction): Boolean =
|
||||
fun isFunctionCreator(outer: JsFunction): Boolean =
|
||||
outer.getInnerFunction() != null
|
||||
|
||||
/**
|
||||
@@ -33,12 +33,12 @@ public fun isFunctionCreator(outer: JsFunction): Boolean =
|
||||
* Inner functions can only be generated when lambda
|
||||
* with closure is created
|
||||
*/
|
||||
public fun JsFunction.getInnerFunction(): JsFunction? {
|
||||
val statements = getBody().getStatements()
|
||||
fun JsFunction.getInnerFunction(): JsFunction? {
|
||||
val statements = body.statements
|
||||
if (statements.size != 1) return null
|
||||
|
||||
val statement = statements.get(0)
|
||||
val returnExpr = (statement as? JsReturn)?.getExpression()
|
||||
val returnExpr = (statement as? JsReturn)?.expression
|
||||
|
||||
return returnExpr as? JsFunction
|
||||
}
|
||||
|
||||
@@ -31,9 +31,9 @@ import com.google.dart.compiler.backend.js.ast.metadata.staticRef
|
||||
*
|
||||
* @returns `f` for `_.foo.f()` call
|
||||
*/
|
||||
public fun getSimpleName(call: JsInvocation): JsName? {
|
||||
val qualifier = call.getQualifier()
|
||||
return (qualifier as? JsNameRef)?.getName()
|
||||
fun getSimpleName(call: JsInvocation): JsName? {
|
||||
val qualifier = call.qualifier
|
||||
return (qualifier as? JsNameRef)?.name
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -41,20 +41,20 @@ public fun getSimpleName(call: JsInvocation): JsName? {
|
||||
*
|
||||
* @returns first name ident (iterating through qualifier chain)
|
||||
*/
|
||||
public fun getSimpleIdent(call: JsInvocation): String? {
|
||||
var qualifier: JsExpression? = call.getQualifier()
|
||||
fun getSimpleIdent(call: JsInvocation): String? {
|
||||
var qualifier: JsExpression? = call.qualifier
|
||||
|
||||
qualifiers@ while (qualifier != null) {
|
||||
when (qualifier) {
|
||||
is JsInvocation -> {
|
||||
val callableQualifier = qualifier
|
||||
qualifier = callableQualifier.getQualifier()
|
||||
qualifier = callableQualifier.qualifier
|
||||
|
||||
if (isCallInvocation(callableQualifier)) {
|
||||
qualifier = (qualifier as? JsNameRef)?.getQualifier()
|
||||
qualifier = (qualifier as? JsNameRef)?.qualifier
|
||||
}
|
||||
}
|
||||
is HasName -> return qualifier.getName()?.getIdent()
|
||||
is HasName -> return qualifier.name?.ident
|
||||
else -> break@qualifiers
|
||||
}
|
||||
}
|
||||
@@ -67,7 +67,7 @@ public fun getSimpleIdent(call: JsInvocation): String? {
|
||||
*
|
||||
* Function creator is a function, that creates closure.
|
||||
*/
|
||||
public fun isFunctionCreatorInvocation(invocation: JsInvocation): Boolean {
|
||||
fun isFunctionCreatorInvocation(invocation: JsInvocation): Boolean {
|
||||
val staticRef = getStaticRef(invocation)
|
||||
return when (staticRef) {
|
||||
is JsFunction -> isFunctionCreator(staticRef)
|
||||
@@ -81,11 +81,11 @@ public fun isFunctionCreatorInvocation(invocation: JsInvocation): Boolean {
|
||||
* @return true if invocation is something like `x.call(thisReplacement)`
|
||||
* false otherwise
|
||||
*/
|
||||
public fun isCallInvocation(invocation: JsInvocation): Boolean {
|
||||
val qualifier = invocation.getQualifier() as? JsNameRef
|
||||
val arguments = invocation.getArguments()
|
||||
fun isCallInvocation(invocation: JsInvocation): Boolean {
|
||||
val qualifier = invocation.qualifier as? JsNameRef
|
||||
val arguments = invocation.arguments
|
||||
|
||||
return qualifier?.getIdent() == Namer.CALL_FUNCTION && arguments.isNotEmpty()
|
||||
return qualifier?.ident == Namer.CALL_FUNCTION && arguments.isNotEmpty()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -94,7 +94,7 @@ public fun isCallInvocation(invocation: JsInvocation): Boolean {
|
||||
* @return true, if invocation is similar to `something.f()`
|
||||
* false, if invocation is similar to `f()`
|
||||
*/
|
||||
public fun hasCallerQualifier(invocation: JsInvocation): Boolean {
|
||||
fun hasCallerQualifier(invocation: JsInvocation): Boolean {
|
||||
return getCallerQualifierImpl(invocation) != null
|
||||
}
|
||||
|
||||
@@ -106,18 +106,18 @@ public fun hasCallerQualifier(invocation: JsInvocation): Boolean {
|
||||
*
|
||||
* @throws AssertionError, if invocation does not have caller qualifier.
|
||||
*/
|
||||
public fun getCallerQualifier(invocation: JsInvocation): JsExpression {
|
||||
fun getCallerQualifier(invocation: JsInvocation): JsExpression {
|
||||
return getCallerQualifierImpl(invocation) ?:
|
||||
throw AssertionError("must check hasQualifier() before calling getQualifier")
|
||||
|
||||
}
|
||||
|
||||
private fun getCallerQualifierImpl(invocation: JsInvocation): JsExpression? {
|
||||
return (invocation.getQualifier() as? JsNameRef)?.getQualifier()
|
||||
return (invocation.qualifier as? JsNameRef)?.qualifier
|
||||
}
|
||||
|
||||
private fun getStaticRef(invocation: JsInvocation): JsNode? {
|
||||
val qualifier = invocation.getQualifier()
|
||||
val qualifierName = (qualifier as? HasName)?.getName()
|
||||
val qualifier = invocation.qualifier
|
||||
val qualifierName = (qualifier as? HasName)?.name
|
||||
return qualifierName?.staticRef
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ import com.google.dart.compiler.backend.js.ast.*
|
||||
import org.jetbrains.kotlin.js.inline.context.NamingContext
|
||||
import org.jetbrains.kotlin.js.inline.util.rewriters.LabelNameRefreshingVisitor
|
||||
|
||||
public fun aliasArgumentsIfNeeded(
|
||||
fun aliasArgumentsIfNeeded(
|
||||
context: NamingContext,
|
||||
arguments: List<JsExpression>,
|
||||
parameters: List<JsParameter>
|
||||
@@ -29,7 +29,7 @@ public fun aliasArgumentsIfNeeded(
|
||||
require(arguments.size <= parameters.size) { "arguments.size (${arguments.size}) should be less or equal to parameters.size (${parameters.size})" }
|
||||
|
||||
for ((arg, param) in arguments.zip(parameters)) {
|
||||
val paramName = param.getName()
|
||||
val paramName = param.name
|
||||
val replacement =
|
||||
if (arg.needToAlias()) {
|
||||
val freshName = context.getFreshName(paramName)
|
||||
@@ -44,7 +44,7 @@ public fun aliasArgumentsIfNeeded(
|
||||
|
||||
val defaultParams = parameters.subList(arguments.size, parameters.size)
|
||||
for (defaultParam in defaultParams) {
|
||||
val paramName = defaultParam.getName()
|
||||
val paramName = defaultParam.name
|
||||
val freshName = context.getFreshName(paramName)
|
||||
context.newVar(freshName)
|
||||
|
||||
@@ -55,7 +55,7 @@ public fun aliasArgumentsIfNeeded(
|
||||
/**
|
||||
* Makes function local names fresh in context
|
||||
*/
|
||||
public fun renameLocalNames(
|
||||
fun renameLocalNames(
|
||||
context: NamingContext,
|
||||
function: JsFunction
|
||||
) {
|
||||
@@ -65,14 +65,14 @@ public fun renameLocalNames(
|
||||
}
|
||||
}
|
||||
|
||||
public fun refreshLabelNames(
|
||||
fun refreshLabelNames(
|
||||
context: NamingContext,
|
||||
function: JsFunction
|
||||
) {
|
||||
val scope = function.getScope()
|
||||
val scope = function.scope
|
||||
if (scope !is JsFunctionScope) throw AssertionError("JsFunction is expected to have JsFunctionScope")
|
||||
|
||||
val visitor = LabelNameRefreshingVisitor(context, scope)
|
||||
visitor.accept(function.getBody())
|
||||
visitor.accept(function.body)
|
||||
context.applyRenameTo(function)
|
||||
}
|
||||
|
||||
@@ -26,10 +26,10 @@ import org.jetbrains.kotlin.js.inline.util.rewriters.ThisReplacingVisitor
|
||||
|
||||
import java.util.IdentityHashMap
|
||||
|
||||
public fun <T : JsNode> replaceNames(node: T, replaceMap: IdentityHashMap<JsName, JsExpression>): T {
|
||||
fun <T : JsNode> replaceNames(node: T, replaceMap: IdentityHashMap<JsName, JsExpression>): T {
|
||||
return NameReplacingVisitor(replaceMap).accept(node)!!
|
||||
}
|
||||
|
||||
public fun <T : JsNode> replaceThisReference(node: T, replacement: JsExpression) {
|
||||
fun <T : JsNode> replaceThisReference(node: T, replacement: JsExpression) {
|
||||
ThisReplacingVisitor(replacement).accept(node)
|
||||
}
|
||||
|
||||
+3
-3
@@ -27,10 +27,10 @@ class LabelNameRefreshingVisitor(val context: NamingContext, val functionScope:
|
||||
override fun visit(x: JsFunction, ctx: JsContext<*>): Boolean = false
|
||||
|
||||
override fun visit(x: JsLabel, ctx: JsContext<*>): Boolean {
|
||||
val labelName = x.getName()
|
||||
val freshName = functionScope.enterLabel(labelName.getIdent())
|
||||
val labelName = x.name
|
||||
val freshName = functionScope.enterLabel(labelName.ident)
|
||||
|
||||
if (freshName.getIdent() != labelName.getIdent()) {
|
||||
if (freshName.ident != labelName.ident) {
|
||||
context.replaceName(labelName, freshName.makeRef())
|
||||
}
|
||||
|
||||
|
||||
+5
-5
@@ -21,24 +21,24 @@ import com.google.dart.compiler.backend.js.ast.*
|
||||
class NameReplacingVisitor(private val replaceMap: Map<JsName, JsExpression>) : JsVisitorWithContextImpl() {
|
||||
|
||||
override fun endVisit(x: JsNameRef, ctx: JsContext<JsNode>) {
|
||||
val replacement = replaceMap[x.getName()]
|
||||
val replacement = replaceMap[x.name]
|
||||
if (replacement == null) return
|
||||
|
||||
ctx.replaceMe(replacement)
|
||||
}
|
||||
|
||||
override fun endVisit(x: JsVars.JsVar, ctx: JsContext<JsNode>) {
|
||||
val replacement = replaceMap[x.getName()]
|
||||
val replacement = replaceMap[x.name]
|
||||
if (replacement is HasName) {
|
||||
val replacementVar = JsVars.JsVar(replacement.getName(), x.getInitExpression())
|
||||
val replacementVar = JsVars.JsVar(replacement.name, x.initExpression)
|
||||
ctx.replaceMe(replacementVar)
|
||||
}
|
||||
}
|
||||
|
||||
override fun endVisit(x: JsLabel, ctx: JsContext<JsNode>) {
|
||||
val replacement = replaceMap[x.getName()]
|
||||
val replacement = replaceMap[x.name]
|
||||
if (replacement is HasName) {
|
||||
val replacementLabel = JsLabel(replacement.getName(), x.getStatement())
|
||||
val replacementLabel = JsLabel(replacement.name, x.statement)
|
||||
ctx.replaceMe(replacementLabel)
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -20,7 +20,7 @@ import com.google.dart.compiler.backend.js.ast.*
|
||||
import org.jetbrains.kotlin.js.inline.util.canHaveSideEffect
|
||||
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils
|
||||
|
||||
public class ReturnReplacingVisitor(private val resultRef: JsNameRef?, private val breakLabel: JsNameRef?) : JsVisitorWithContextImpl() {
|
||||
class ReturnReplacingVisitor(private val resultRef: JsNameRef?, private val breakLabel: JsNameRef?) : JsVisitorWithContextImpl() {
|
||||
|
||||
/**
|
||||
* Prevents replacing returns in object literal
|
||||
@@ -35,7 +35,7 @@ public class ReturnReplacingVisitor(private val resultRef: JsNameRef?, private v
|
||||
override fun endVisit(x: JsReturn, ctx: JsContext<JsNode>) {
|
||||
ctx.removeMe()
|
||||
|
||||
val returnReplacement = getReturnReplacement(x.getExpression())
|
||||
val returnReplacement = getReturnReplacement(x.expression)
|
||||
if (returnReplacement != null) {
|
||||
ctx.addNext(JsExpressionStatement(returnReplacement))
|
||||
}
|
||||
|
||||
@@ -21,25 +21,25 @@ import com.google.dart.compiler.backend.js.ast.*
|
||||
import com.google.dart.compiler.backend.js.ast.metadata.typeCheck
|
||||
import org.jetbrains.kotlin.js.translate.utils.jsAstUtils.any
|
||||
|
||||
public fun JsExpression.canHaveSideEffect(): Boolean =
|
||||
fun JsExpression.canHaveSideEffect(): Boolean =
|
||||
any { it is JsExpression && it.canHaveOwnSideEffect() }
|
||||
|
||||
public fun JsExpression.canHaveOwnSideEffect(): Boolean =
|
||||
fun JsExpression.canHaveOwnSideEffect(): Boolean =
|
||||
when (this) {
|
||||
is JsValueLiteral,
|
||||
is JsConditional,
|
||||
is JsArrayAccess,
|
||||
is JsArrayLiteral,
|
||||
is JsNameRef -> false
|
||||
is JsBinaryOperation -> getOperator().isAssignment()
|
||||
is JsBinaryOperation -> operator.isAssignment
|
||||
is JsInvocation -> !isFunctionCreatorInvocation(this)
|
||||
else -> true
|
||||
}
|
||||
|
||||
public fun JsExpression.needToAlias(): Boolean =
|
||||
fun JsExpression.needToAlias(): Boolean =
|
||||
any { it is JsExpression && it.shouldHaveOwnAlias() }
|
||||
|
||||
public fun JsExpression.shouldHaveOwnAlias(): Boolean =
|
||||
fun JsExpression.shouldHaveOwnAlias(): Boolean =
|
||||
when (this) {
|
||||
is JsThisRef,
|
||||
is JsConditional,
|
||||
|
||||
@@ -21,7 +21,7 @@ import com.google.dart.compiler.backend.js.ast.*
|
||||
import java.util.Stack
|
||||
|
||||
class ScopeContext(scope: JsScope) {
|
||||
private val rootScope = sequence(scope) { it.getParent() }.first { it is JsRootScope }
|
||||
private val rootScope = sequence(scope) { it.parent }.first { it is JsRootScope }
|
||||
private val scopes = Stack<JsScope>();
|
||||
|
||||
init {
|
||||
@@ -30,7 +30,7 @@ class ScopeContext(scope: JsScope) {
|
||||
|
||||
fun enterFunction(): JsFunction {
|
||||
val fn = JsFunction(currentScope, "<js function>")
|
||||
enterScope(fn.getScope())
|
||||
enterScope(fn.scope)
|
||||
return fn
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ class ScopeContext(scope: JsScope) {
|
||||
|
||||
fun enterCatch(ident: String): JsCatch {
|
||||
val jsCatch = JsCatch(currentScope, ident)
|
||||
enterScope(jsCatch.getScope())
|
||||
enterScope(jsCatch.scope)
|
||||
return jsCatch
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ package com.google.gwt.dev.js
|
||||
import com.google.gwt.dev.js.rhino.*
|
||||
import com.google.gwt.dev.js.parserExceptions.*
|
||||
|
||||
public object ThrowExceptionOnErrorReporter : ErrorReporter {
|
||||
object ThrowExceptionOnErrorReporter : ErrorReporter {
|
||||
override fun warning(message: String, startPosition: CodePosition, endPosition: CodePosition) {}
|
||||
|
||||
override fun error(message: String, startPosition: CodePosition, endPosition: CodePosition) =
|
||||
|
||||
@@ -20,9 +20,9 @@ import com.google.gwt.dev.js.rhino.CodePosition
|
||||
/**
|
||||
* Can be used in Error reporter to exit parser
|
||||
*/
|
||||
public class AbortParsingException : RuntimeException()
|
||||
class AbortParsingException : RuntimeException()
|
||||
|
||||
public class JsParserException(
|
||||
class JsParserException(
|
||||
message: String,
|
||||
val position: CodePosition
|
||||
) : RuntimeException("$message at $position")
|
||||
@@ -18,9 +18,9 @@ package org.jetbrains.kotlin.js.parser
|
||||
|
||||
import com.google.gwt.dev.js.rhino.*
|
||||
|
||||
public object ParserEvents {
|
||||
object ParserEvents {
|
||||
|
||||
public class OnFunctionParsingStart
|
||||
class OnFunctionParsingStart
|
||||
|
||||
public class OnFunctionParsingEnd(public val tokenStream: TokenStream)
|
||||
class OnFunctionParsingEnd(val tokenStream: TokenStream)
|
||||
}
|
||||
@@ -27,13 +27,13 @@ import java.util.*
|
||||
|
||||
private val FAKE_SOURCE_INFO = SourceInfoImpl(null, 0, 0, 0, 0)
|
||||
|
||||
public fun parse(code: String, reporter: ErrorReporter, scope: JsScope): List<JsStatement> {
|
||||
fun parse(code: String, reporter: ErrorReporter, scope: JsScope): List<JsStatement> {
|
||||
val insideFunction = scope is JsFunctionScope
|
||||
val node = parse(code, 0, reporter, insideFunction, Parser::parse)
|
||||
return node.toJsAst(scope, JsAstMapper::mapStatements)
|
||||
}
|
||||
|
||||
public fun parseFunction(code: String, offset: Int, reporter: ErrorReporter, scope: JsScope): JsFunction =
|
||||
fun parseFunction(code: String, offset: Int, reporter: ErrorReporter, scope: JsScope): JsFunction =
|
||||
parse(code, offset, reporter, insideFunction = false) {
|
||||
addObserver(FunctionParsingObserver())
|
||||
primaryExpr(it)
|
||||
@@ -69,7 +69,7 @@ private fun parse(
|
||||
Context.enter().setErrorReporter(reporter)
|
||||
|
||||
try {
|
||||
val ts = TokenStream(StringReader(code, offset), "<parser>", FAKE_SOURCE_INFO.getLine())
|
||||
val ts = TokenStream(StringReader(code, offset), "<parser>", FAKE_SOURCE_INFO.line)
|
||||
val parser = Parser(IRFactory(ts), insideFunction)
|
||||
return parser.parseAction(ts) as Node
|
||||
} finally {
|
||||
|
||||
+4
-4
@@ -21,8 +21,8 @@ import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
|
||||
import org.jetbrains.kotlin.serialization.DescriptorSerializer
|
||||
import org.jetbrains.kotlin.serialization.ProtoBuf
|
||||
|
||||
public object ClassSerializationUtil {
|
||||
public interface Sink {
|
||||
object ClassSerializationUtil {
|
||||
interface Sink {
|
||||
fun writeClass(classDescriptor: ClassDescriptor, classProto: ProtoBuf.Class)
|
||||
}
|
||||
|
||||
@@ -32,10 +32,10 @@ public object ClassSerializationUtil {
|
||||
val classProto = serializer.classProto(classDescriptor).build() ?: error("Class not serialized: $classDescriptor")
|
||||
sink.writeClass(classDescriptor, classProto)
|
||||
|
||||
serializeClasses(classDescriptor.getUnsubstitutedInnerClassesScope().getContributedDescriptors(), serializer, sink, skip)
|
||||
serializeClasses(classDescriptor.unsubstitutedInnerClassesScope.getContributedDescriptors(), serializer, sink, skip)
|
||||
}
|
||||
|
||||
public fun serializeClasses(descriptors: Collection<DeclarationDescriptor>, serializer: DescriptorSerializer, sink: Sink, skip: (DeclarationDescriptor) -> Boolean) {
|
||||
fun serializeClasses(descriptors: Collection<DeclarationDescriptor>, serializer: DescriptorSerializer, sink: Sink, skip: (DeclarationDescriptor) -> Boolean) {
|
||||
for (descriptor in descriptors) {
|
||||
if (descriptor is ClassDescriptor) {
|
||||
serializeClass(descriptor, serializer, sink, skip)
|
||||
|
||||
+2
-2
@@ -26,7 +26,7 @@ import org.jetbrains.kotlin.serialization.deserialization.NameResolverImpl
|
||||
import org.jetbrains.kotlin.storage.StorageManager
|
||||
import java.io.InputStream
|
||||
|
||||
public class KotlinJavascriptPackageFragment(
|
||||
class KotlinJavascriptPackageFragment(
|
||||
fqName: FqName,
|
||||
storageManager: StorageManager,
|
||||
module: ModuleDescriptor,
|
||||
@@ -36,7 +36,7 @@ public class KotlinJavascriptPackageFragment(
|
||||
|
||||
override val classIdToProto: Map<ClassId, ProtoBuf.Class>? get() = null
|
||||
|
||||
protected override fun loadClassNames(packageProto: ProtoBuf.Package): Collection<Name> {
|
||||
override fun loadClassNames(packageProto: ProtoBuf.Package): Collection<Name> {
|
||||
val classesStream = loadResourceSure(KotlinJavascriptSerializedResourcePaths.getClassesInPackageFilePath(fqName))
|
||||
val classesProto = JsProtoBuf.Classes.parseFrom(classesStream, serializedResourcePaths.extensionRegistry)
|
||||
return classesProto.classNameList?.map { id -> nameResolver.getName(id) } ?: listOf()
|
||||
|
||||
+9
-10
@@ -35,8 +35,8 @@ import java.util.*
|
||||
import java.util.zip.GZIPInputStream
|
||||
import java.util.zip.GZIPOutputStream
|
||||
|
||||
public object KotlinJavascriptSerializationUtil {
|
||||
public val CLASS_METADATA_FILE_EXTENSION: String = "kjsm"
|
||||
object KotlinJavascriptSerializationUtil {
|
||||
val CLASS_METADATA_FILE_EXTENSION: String = "kjsm"
|
||||
|
||||
private val PACKAGE_DEFAULT_BYTES = run {
|
||||
val stream = ByteArrayOutputStream()
|
||||
@@ -57,8 +57,7 @@ public object KotlinJavascriptSerializationUtil {
|
||||
stream.toByteArray()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
public fun createPackageFragmentProvider(moduleDescriptor: ModuleDescriptor, metadata: ByteArray, storageManager: StorageManager): PackageFragmentProvider? {
|
||||
@JvmStatic fun createPackageFragmentProvider(moduleDescriptor: ModuleDescriptor, metadata: ByteArray, storageManager: StorageManager): PackageFragmentProvider? {
|
||||
val contentMap = metadata.toContentMap()
|
||||
|
||||
val packageFqNames = getPackages(contentMap).map { FqName(it) }.toSet()
|
||||
@@ -82,7 +81,7 @@ public object KotlinJavascriptSerializationUtil {
|
||||
}
|
||||
}
|
||||
|
||||
public fun contentMapToByteArray(contentMap: Map<String, ByteArray>): ByteArray {
|
||||
fun contentMapToByteArray(contentMap: Map<String, ByteArray>): ByteArray {
|
||||
val contentBuilder = JsProtoBuf.Library.newBuilder()
|
||||
contentMap.forEach {
|
||||
val entry = JsProtoBuf.Library.FileEntry.newBuilder().setPath(it.key).setContent(ByteString.copyFrom(it.value)).build()
|
||||
@@ -97,7 +96,7 @@ public object KotlinJavascriptSerializationUtil {
|
||||
return byteStream.toByteArray()
|
||||
}
|
||||
|
||||
public fun metadataAsString(moduleName: String, moduleDescriptor: ModuleDescriptor): String =
|
||||
fun metadataAsString(moduleName: String, moduleDescriptor: ModuleDescriptor): String =
|
||||
KotlinJavascriptMetadataUtils.formatMetadataAsString(moduleName, moduleDescriptor.toBinaryMetadata())
|
||||
|
||||
fun serializePackage(module: ModuleDescriptor, fqName: FqName, writeFun: (String, ByteArray) -> Unit) {
|
||||
@@ -152,7 +151,7 @@ public object KotlinJavascriptSerializationUtil {
|
||||
val builder = JsProtoBuf.Classes.newBuilder()
|
||||
|
||||
for (descriptor in DescriptorSerializer.sort(classes)) {
|
||||
builder.addClassName(stringTable.getSimpleNameIndex(descriptor.getName()))
|
||||
builder.addClassName(stringTable.getSimpleNameIndex(descriptor.name))
|
||||
}
|
||||
|
||||
val classesProto = builder.build()
|
||||
@@ -168,7 +167,7 @@ public object KotlinJavascriptSerializationUtil {
|
||||
return KotlinJavascriptSerializedResourcePaths.getClassMetadataPath(classDescriptor.classId)
|
||||
}
|
||||
|
||||
public fun toContentMap(module: ModuleDescriptor): Map<String, ByteArray> {
|
||||
fun toContentMap(module: ModuleDescriptor): Map<String, ByteArray> {
|
||||
val contentMap = hashMapOf<String, ByteArray>()
|
||||
|
||||
getPackagesFqNames(module).forEach {
|
||||
@@ -221,7 +220,7 @@ public object KotlinJavascriptSerializationUtil {
|
||||
KotlinJavascriptSerializationUtil.contentMapToByteArray(toContentMap(this))
|
||||
}
|
||||
|
||||
public fun KotlinJavascriptMetadata.forEachFile(operation: (filePath: String, fileContent: ByteArray) -> Unit): Unit =
|
||||
fun KotlinJavascriptMetadata.forEachFile(operation: (filePath: String, fileContent: ByteArray) -> Unit): Unit =
|
||||
this.body.toContentMap().forEach { operation(it.key, it.value) }
|
||||
|
||||
private fun ByteArray.toContentMap(): Map<String, ByteArray> {
|
||||
@@ -230,7 +229,7 @@ private fun ByteArray.toContentMap(): Map<String, ByteArray> {
|
||||
gzipInputStream.close()
|
||||
|
||||
val contentMap: MutableMap<String, ByteArray> = hashMapOf()
|
||||
content.getEntryList().forEach { entry -> contentMap[entry.getPath()] = entry.getContent().toByteArray() }
|
||||
content.entryList.forEach { entry -> contentMap[entry.path] = entry.content.toByteArray() }
|
||||
|
||||
return contentMap
|
||||
}
|
||||
+5
-5
@@ -60,17 +60,17 @@ private val PACKAGE_CLASS_NAME_SUFFIX: String = "Package"
|
||||
private val DEFAULT_PACKAGE_CLASS_NAME: String = "_Default" + PACKAGE_CLASS_NAME_SUFFIX
|
||||
private val DEFAULT_PACKAGE_METAFILE_NAME: String = DEFAULT_PACKAGE_CLASS_NAME + "." + KotlinJavascriptSerializationUtil.CLASS_METADATA_FILE_EXTENSION
|
||||
|
||||
public fun FqName.isPackageClassFqName(): Boolean = !this.isRoot && getPackageClassFqName(this.parent()) == this
|
||||
fun FqName.isPackageClassFqName(): Boolean = !this.isRoot && getPackageClassFqName(this.parent()) == this
|
||||
|
||||
public fun isDefaultPackageMetafile(fileName: String): Boolean = fileName == DEFAULT_PACKAGE_METAFILE_NAME
|
||||
fun isDefaultPackageMetafile(fileName: String): Boolean = fileName == DEFAULT_PACKAGE_METAFILE_NAME
|
||||
|
||||
public fun isPackageMetadataFile(fileName: String): Boolean =
|
||||
fun isPackageMetadataFile(fileName: String): Boolean =
|
||||
KotlinJavascriptSerializedResourcePaths.getPackageFilePath(getPackageFqName(fileName)) == fileName
|
||||
|
||||
public fun isStringTableFile(fileName: String): Boolean =
|
||||
fun isStringTableFile(fileName: String): Boolean =
|
||||
KotlinJavascriptSerializedResourcePaths.getStringTableFilePath(getPackageFqName(fileName)) == fileName
|
||||
|
||||
public fun isClassesInPackageFile(fileName: String): Boolean =
|
||||
fun isClassesInPackageFile(fileName: String): Boolean =
|
||||
KotlinJavascriptSerializedResourcePaths.getClassesInPackageFilePath(getPackageFqName(fileName)) == fileName
|
||||
|
||||
private fun getPackageFqName(fileName: String): FqName = FqName(getPackageName(fileName))
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ package org.jetbrains.kotlin.serialization.js
|
||||
import org.jetbrains.kotlin.serialization.KotlinSerializerExtensionBase
|
||||
import org.jetbrains.kotlin.serialization.SerializerExtensionProtocol
|
||||
|
||||
public class KotlinJavascriptSerializerExtension : KotlinSerializerExtensionBase(JsSerializerProtocol)
|
||||
class KotlinJavascriptSerializerExtension : KotlinSerializerExtensionBase(JsSerializerProtocol)
|
||||
|
||||
object JsSerializerProtocol : SerializerExtensionProtocol(
|
||||
JsProtoBuf.constructorAnnotation, JsProtoBuf.classAnnotation, JsProtoBuf.functionAnnotation, JsProtoBuf.propertyAnnotation,
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ import org.jetbrains.kotlin.serialization.deserialization.*
|
||||
import org.jetbrains.kotlin.storage.StorageManager
|
||||
import java.io.InputStream
|
||||
|
||||
public fun createKotlinJavascriptPackageFragmentProvider(
|
||||
fun createKotlinJavascriptPackageFragmentProvider(
|
||||
storageManager: StorageManager,
|
||||
module: ModuleDescriptor,
|
||||
packageFqNames: Set<FqName>,
|
||||
|
||||
@@ -28,7 +28,7 @@ import java.io.File
|
||||
import java.util.ArrayList
|
||||
import java.util.LinkedHashMap
|
||||
|
||||
public abstract class MultipleModulesTranslationTest(main: String) : BasicTest(main) {
|
||||
abstract class MultipleModulesTranslationTest(main: String) : BasicTest(main) {
|
||||
|
||||
private val MAIN_MODULE_NAME: String = "main"
|
||||
private var dependencies: Map<String, List<String>>? = null
|
||||
@@ -86,7 +86,7 @@ public abstract class MultipleModulesTranslationTest(main: String) : BasicTest(m
|
||||
|
||||
private fun readModuleDependencies(testDataDir: String): Map<String, List<String>> {
|
||||
val dependenciesTxt = upsearchFile(testDataDir, "dependencies.txt")
|
||||
assert(dependenciesTxt.isFile()) { "moduleDependencies should not be null" }
|
||||
assert(dependenciesTxt.isFile) { "moduleDependencies should not be null" }
|
||||
|
||||
val result = LinkedHashMap<String, List<String>>()
|
||||
for (line in dependenciesTxt.readLines()) {
|
||||
@@ -105,7 +105,7 @@ public abstract class MultipleModulesTranslationTest(main: String) : BasicTest(m
|
||||
var dir: File? = File(startingDir)
|
||||
var file = File(dir, name)
|
||||
|
||||
while (dir != null && dir.isDirectory() && !file.isFile()) {
|
||||
while (dir != null && dir.isDirectory && !file.isFile) {
|
||||
dir = dir.parentFile
|
||||
file = File(dir, name)
|
||||
}
|
||||
|
||||
@@ -18,4 +18,4 @@ package org.jetbrains.kotlin.js.test.semantics
|
||||
|
||||
import org.jetbrains.kotlin.js.test.SingleFileTranslationTest
|
||||
|
||||
public abstract class AbstractReifiedTest : SingleFileTranslationTest("reified/")
|
||||
abstract class AbstractReifiedTest : SingleFileTranslationTest("reified/")
|
||||
+15
-15
@@ -20,34 +20,34 @@ import org.jetbrains.kotlin.js.test.AbstractSingleFileTranslationWithDirectivesT
|
||||
import org.jetbrains.kotlin.js.test.MultipleModulesTranslationTest
|
||||
import org.jetbrains.kotlin.js.test.SingleFileTranslationTest
|
||||
|
||||
public abstract class AbstractBlackBoxTest(d: String) : SingleFileTranslationTest(d) {
|
||||
abstract class AbstractBlackBoxTest(d: String) : SingleFileTranslationTest(d) {
|
||||
override fun doTest(filename: String) = checkBlackBoxIsOkByPath(filename)
|
||||
}
|
||||
|
||||
public abstract class AbstractBridgeTest : AbstractBlackBoxTest("bridges/")
|
||||
abstract class AbstractBridgeTest : AbstractBlackBoxTest("bridges/")
|
||||
|
||||
public abstract class AbstractCallableReferenceTest(main: String) : SingleFileTranslationTest("callableReference/" + main)
|
||||
abstract class AbstractCallableReferenceTest(main: String) : SingleFileTranslationTest("callableReference/" + main)
|
||||
|
||||
public abstract class AbstractCompanionObjectTest : SingleFileTranslationTest("objectIntrinsics/")
|
||||
abstract class AbstractCompanionObjectTest : SingleFileTranslationTest("objectIntrinsics/")
|
||||
|
||||
public abstract class AbstractDynamicTest : SingleFileTranslationTest("dynamic/")
|
||||
abstract class AbstractDynamicTest : SingleFileTranslationTest("dynamic/")
|
||||
|
||||
public abstract class AbstractFunctionExpressionTest : AbstractBlackBoxTest("functionExpression/")
|
||||
abstract class AbstractFunctionExpressionTest : AbstractBlackBoxTest("functionExpression/")
|
||||
|
||||
public abstract class AbstractInlineEvaluationOrderTest : AbstractSingleFileTranslationWithDirectivesTest("inlineEvaluationOrder/")
|
||||
abstract class AbstractInlineEvaluationOrderTest : AbstractSingleFileTranslationWithDirectivesTest("inlineEvaluationOrder/")
|
||||
|
||||
public abstract class AbstractInlineJsStdlibTest : AbstractSingleFileTranslationWithDirectivesTest("inlineStdlib/")
|
||||
abstract class AbstractInlineJsStdlibTest : AbstractSingleFileTranslationWithDirectivesTest("inlineStdlib/")
|
||||
|
||||
public abstract class AbstractInlineJsTest : AbstractSingleFileTranslationWithDirectivesTest("inline/")
|
||||
abstract class AbstractInlineJsTest : AbstractSingleFileTranslationWithDirectivesTest("inline/")
|
||||
|
||||
public abstract class AbstractJsCodeTest : AbstractSingleFileTranslationWithDirectivesTest("jsCode/")
|
||||
abstract class AbstractJsCodeTest : AbstractSingleFileTranslationWithDirectivesTest("jsCode/")
|
||||
|
||||
public abstract class AbstractLabelTest : AbstractSingleFileTranslationWithDirectivesTest("labels/")
|
||||
abstract class AbstractLabelTest : AbstractSingleFileTranslationWithDirectivesTest("labels/")
|
||||
|
||||
public abstract class AbstractMultiModuleTest : MultipleModulesTranslationTest("multiModule/")
|
||||
abstract class AbstractMultiModuleTest : MultipleModulesTranslationTest("multiModule/")
|
||||
|
||||
public abstract class AbstractInlineMultiModuleTest : MultipleModulesTranslationTest("inlineMultiModule/")
|
||||
abstract class AbstractInlineMultiModuleTest : MultipleModulesTranslationTest("inlineMultiModule/")
|
||||
|
||||
public abstract class AbstractReservedWordTest : SingleFileTranslationTest("reservedWords/")
|
||||
abstract class AbstractReservedWordTest : SingleFileTranslationTest("reservedWords/")
|
||||
|
||||
public abstract class AbstractSecondaryConstructorTest : AbstractBlackBoxTest("secondaryConstructors/")
|
||||
abstract class AbstractSecondaryConstructorTest : AbstractBlackBoxTest("secondaryConstructors/")
|
||||
|
||||
@@ -35,23 +35,23 @@ import org.jetbrains.kotlin.utils.fileUtils.readTextOrEmpty
|
||||
import java.io.File
|
||||
import java.util.ArrayList
|
||||
|
||||
public abstract class TranslationResult protected constructor(public val diagnostics: Diagnostics) {
|
||||
abstract class TranslationResult protected constructor(val diagnostics: Diagnostics) {
|
||||
|
||||
public class Fail(diagnostics: Diagnostics) : TranslationResult(diagnostics)
|
||||
class Fail(diagnostics: Diagnostics) : TranslationResult(diagnostics)
|
||||
|
||||
public class Success(
|
||||
class Success(
|
||||
private val config: Config,
|
||||
private val files: List<KtFile>,
|
||||
public val program: JsProgram,
|
||||
val program: JsProgram,
|
||||
diagnostics: Diagnostics,
|
||||
private val moduleDescriptor: ModuleDescriptor
|
||||
) : TranslationResult(diagnostics) {
|
||||
public fun getCode(): String = getCode(TextOutputImpl(), sourceMapBuilder = null)
|
||||
fun getCode(): String = getCode(TextOutputImpl(), sourceMapBuilder = null)
|
||||
|
||||
public fun getOutputFiles(outputFile: File, outputPrefixFile: File?, outputPostfixFile: File?): OutputFileCollection {
|
||||
fun getOutputFiles(outputFile: File, outputPrefixFile: File?, outputPostfixFile: File?): OutputFileCollection {
|
||||
val output = TextOutputImpl()
|
||||
val sourceMapBuilder = when {
|
||||
config.isSourcemap() -> SourceMap3Builder(outputFile, output, SourceMapBuilderConsumer())
|
||||
config.isSourcemap -> SourceMap3Builder(outputFile, output, SourceMapBuilderConsumer())
|
||||
else -> null
|
||||
}
|
||||
|
||||
@@ -59,20 +59,20 @@ public abstract class TranslationResult protected constructor(public val diagnos
|
||||
val prefix = outputPrefixFile?.readTextOrEmpty() ?: ""
|
||||
val postfix = outputPostfixFile?.readTextOrEmpty() ?: ""
|
||||
val sourceFiles = files.map {
|
||||
val virtualFile = it.getOriginalFile().getVirtualFile()
|
||||
val virtualFile = it.originalFile.virtualFile
|
||||
|
||||
when {
|
||||
virtualFile == null -> File(it.getName())
|
||||
virtualFile == null -> File(it.name)
|
||||
else -> VfsUtilCore.virtualToIoFile(virtualFile)
|
||||
}
|
||||
}
|
||||
|
||||
val jsFile = SimpleOutputFile(sourceFiles, outputFile.getName(), prefix + code + postfix)
|
||||
val jsFile = SimpleOutputFile(sourceFiles, outputFile.name, prefix + code + postfix)
|
||||
val outputFiles = arrayListOf<OutputFile>(jsFile)
|
||||
|
||||
if (config.isMetaInfo()) {
|
||||
val metaFileName = KotlinJavascriptMetadataUtils.replaceSuffix(outputFile.getName())
|
||||
val metaFileContent = KotlinJavascriptSerializationUtil.metadataAsString(config.getModuleId(), moduleDescriptor)
|
||||
if (config.isMetaInfo) {
|
||||
val metaFileName = KotlinJavascriptMetadataUtils.replaceSuffix(outputFile.name)
|
||||
val metaFileContent = KotlinJavascriptSerializationUtil.metadataAsString(config.moduleId, moduleDescriptor)
|
||||
val sourceFilesForMetaFile = ArrayList(sourceFiles)
|
||||
val jsMetaFile = SimpleOutputFile(sourceFilesForMetaFile, metaFileName, metaFileContent)
|
||||
outputFiles.add(jsMetaFile)
|
||||
@@ -87,7 +87,7 @@ public abstract class TranslationResult protected constructor(public val diagnos
|
||||
|
||||
if (sourceMapBuilder != null) {
|
||||
sourceMapBuilder.skipLinesAtBeginning(StringUtil.getLineBreakCount(prefix))
|
||||
val sourceMapFile = SimpleOutputFile(sourceFiles, sourceMapBuilder.getOutFile().getName(), sourceMapBuilder.build())
|
||||
val sourceMapFile = SimpleOutputFile(sourceFiles, sourceMapBuilder.outFile.name, sourceMapBuilder.build())
|
||||
outputFiles.add(sourceMapFile)
|
||||
}
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ interface CallInfo {
|
||||
abstract class AbstractCallInfo : CallInfo {
|
||||
override fun toString(): String {
|
||||
val location = DiagnosticUtils.atLocation(callableDescriptor)
|
||||
val name = callableDescriptor.getName().asString()
|
||||
val name = callableDescriptor.name.asString()
|
||||
return "callableDescriptor: $name at $location; dispatchReceiver: $dispatchReceiver; extensionReceiver: $extensionReceiver"
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,7 @@ fun TranslationContext.getCallInfo(resolvedCall: ResolvedCall<out FunctionDescri
|
||||
val argsBlock = JsBlock()
|
||||
val argumentsInfo = CallArgumentTranslator.translate(resolvedCall, explicitReceivers.extensionOrDispatchReceiver, this, argsBlock)
|
||||
val explicitReceiversCorrected =
|
||||
if (!argsBlock.isEmpty() && explicitReceivers.extensionOrDispatchReceiver != null) {
|
||||
if (!argsBlock.isEmpty && explicitReceivers.extensionOrDispatchReceiver != null) {
|
||||
val receiverOrThisRef =
|
||||
if (TranslationUtils.isCacheNeeded(explicitReceivers.extensionOrDispatchReceiver)) {
|
||||
val receiverOrThisRefVar = this.declareTemporary(explicitReceivers.extensionOrDispatchReceiver)
|
||||
@@ -106,10 +106,10 @@ private fun TranslationContext.getDispatchReceiver(receiverValue: ReceiverValue)
|
||||
}
|
||||
|
||||
private fun TranslationContext.createCallInfo(resolvedCall: ResolvedCall<out CallableDescriptor>, explicitReceivers: ExplicitReceivers): CallInfo {
|
||||
val receiverKind = resolvedCall.getExplicitReceiverKind()
|
||||
val receiverKind = resolvedCall.explicitReceiverKind
|
||||
|
||||
fun getDispatchReceiver(): JsExpression? {
|
||||
val receiverValue = resolvedCall.getDispatchReceiver() ?: return null
|
||||
val receiverValue = resolvedCall.dispatchReceiver ?: return null
|
||||
return when (receiverKind) {
|
||||
DISPATCH_RECEIVER, BOTH_RECEIVERS -> explicitReceivers.extensionOrDispatchReceiver
|
||||
else -> this.getDispatchReceiver(receiverValue)
|
||||
@@ -117,7 +117,7 @@ private fun TranslationContext.createCallInfo(resolvedCall: ResolvedCall<out Cal
|
||||
}
|
||||
|
||||
fun getExtensionReceiver(): JsExpression? {
|
||||
val receiverValue = resolvedCall.getExtensionReceiver() ?: return null
|
||||
val receiverValue = resolvedCall.extensionReceiver ?: return null
|
||||
return when (receiverKind) {
|
||||
EXTENSION_RECEIVER -> explicitReceivers.extensionOrDispatchReceiver
|
||||
BOTH_RECEIVERS -> explicitReceivers.extensionReceiver
|
||||
@@ -129,15 +129,15 @@ private fun TranslationContext.createCallInfo(resolvedCall: ResolvedCall<out Cal
|
||||
var extensionReceiver = getExtensionReceiver()
|
||||
var notNullConditional: JsConditional? = null
|
||||
|
||||
if (resolvedCall.isSafeCall()) {
|
||||
when (resolvedCall.getExplicitReceiverKind()) {
|
||||
if (resolvedCall.isSafeCall) {
|
||||
when (resolvedCall.explicitReceiverKind) {
|
||||
BOTH_RECEIVERS, EXTENSION_RECEIVER -> {
|
||||
notNullConditional = TranslationUtils.notNullConditional(extensionReceiver!!, JsLiteral.NULL, this)
|
||||
extensionReceiver = notNullConditional.getThenExpression()
|
||||
extensionReceiver = notNullConditional.thenExpression
|
||||
}
|
||||
else -> {
|
||||
notNullConditional = TranslationUtils.notNullConditional(dispatchReceiver!!, JsLiteral.NULL, this)
|
||||
dispatchReceiver = notNullConditional.getThenExpression()
|
||||
dispatchReceiver = notNullConditional.thenExpression
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -153,7 +153,7 @@ private fun TranslationContext.createCallInfo(resolvedCall: ResolvedCall<out Cal
|
||||
if (notNullConditionalForSafeCall == null) {
|
||||
return result
|
||||
} else {
|
||||
notNullConditionalForSafeCall.setThenExpression(result)
|
||||
notNullConditionalForSafeCall.thenExpression = result
|
||||
return notNullConditionalForSafeCall
|
||||
}
|
||||
}
|
||||
|
||||
+5
-5
@@ -31,7 +31,7 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
|
||||
|
||||
|
||||
val CallInfo.callableDescriptor: CallableDescriptor
|
||||
get() = resolvedCall.getResultingDescriptor().getOriginal()
|
||||
get() = resolvedCall.resultingDescriptor.original
|
||||
|
||||
fun CallInfo.isExtension(): Boolean = extensionReceiver != null
|
||||
|
||||
@@ -40,7 +40,7 @@ fun CallInfo.isMemberCall(): Boolean = dispatchReceiver != null
|
||||
fun CallInfo.isNative(): Boolean = AnnotationsUtils.isNativeObject(callableDescriptor)
|
||||
|
||||
fun CallInfo.isSuperInvocation(): Boolean {
|
||||
val dispatchReceiver = resolvedCall.getDispatchReceiver()
|
||||
val dispatchReceiver = resolvedCall.dispatchReceiver
|
||||
return dispatchReceiver is ExpressionReceiver && dispatchReceiver.expression is KtSuperExpression
|
||||
}
|
||||
|
||||
@@ -55,11 +55,11 @@ fun VariableAccessInfo.isGetAccess(): Boolean = value == null
|
||||
fun VariableAccessInfo.getAccessFunctionName(): String {
|
||||
val descriptor = variableDescriptor
|
||||
if (descriptor is PropertyDescriptor && descriptor.isExtension) {
|
||||
val propertyAccessorDescriptor = if (isGetAccess()) descriptor.getGetter() else descriptor.getSetter()
|
||||
return context.getNameForDescriptor(propertyAccessorDescriptor!!).getIdent()
|
||||
val propertyAccessorDescriptor = if (isGetAccess()) descriptor.getter else descriptor.setter
|
||||
return context.getNameForDescriptor(propertyAccessorDescriptor!!).ident
|
||||
}
|
||||
else {
|
||||
return Namer.getNameForAccessor(variableName.getIdent(), isGetAccess(), false)
|
||||
return Namer.getNameForAccessor(variableName.ident, isGetAccess(), false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-11
@@ -78,7 +78,7 @@ object CallTranslator {
|
||||
}
|
||||
|
||||
private fun ResolvedCall<out CallableDescriptor>.expectedReceivers(): Boolean {
|
||||
return this.getExplicitReceiverKind() != NO_EXPLICIT_RECEIVER
|
||||
return this.explicitReceiverKind != NO_EXPLICIT_RECEIVER
|
||||
}
|
||||
|
||||
private fun translateCall(context: TranslationContext,
|
||||
@@ -100,8 +100,8 @@ private fun translateCall(context: TranslationContext,
|
||||
}
|
||||
}
|
||||
|
||||
val call = resolvedCall.getCall()
|
||||
if (call.getCallType() == CallType.INVOKE && !isInvokeCallOnVariable(call)) {
|
||||
val call = resolvedCall.call
|
||||
if (call.callType == CallType.INVOKE && !isInvokeCallOnVariable(call)) {
|
||||
val explicitReceiversForInvoke = computeExplicitReceiversForInvoke(context, resolvedCall, explicitReceivers)
|
||||
return translateFunctionCall(context, resolvedCall, explicitReceiversForInvoke)
|
||||
}
|
||||
@@ -121,26 +121,26 @@ fun computeExplicitReceiversForInvoke(
|
||||
resolvedCall: ResolvedCall<out FunctionDescriptor>,
|
||||
explicitReceivers: ExplicitReceivers
|
||||
): ExplicitReceivers {
|
||||
val callElement = resolvedCall.getCall().getCallElement()
|
||||
val callElement = resolvedCall.call.callElement
|
||||
assert(explicitReceivers.extensionReceiver == null) { "'Invoke' call must have one receiver: $callElement" }
|
||||
|
||||
fun translateReceiverAsExpression(receiver: ReceiverValue?): JsExpression? =
|
||||
(receiver as? ExpressionReceiver)?.let { Translation.translateAsExpression(it.expression, context) }
|
||||
|
||||
val dispatchReceiver = resolvedCall.getDispatchReceiver()
|
||||
val extensionReceiver = resolvedCall.getExtensionReceiver()
|
||||
val dispatchReceiver = resolvedCall.dispatchReceiver
|
||||
val extensionReceiver = resolvedCall.extensionReceiver
|
||||
|
||||
if (dispatchReceiver != null && extensionReceiver != null && resolvedCall.getExplicitReceiverKind() == ExplicitReceiverKind.BOTH_RECEIVERS) {
|
||||
if (dispatchReceiver != null && extensionReceiver != null && resolvedCall.explicitReceiverKind == ExplicitReceiverKind.BOTH_RECEIVERS) {
|
||||
assert(explicitReceivers.extensionOrDispatchReceiver != null) {
|
||||
"No explicit receiver for 'invoke' resolved call with both receivers: $callElement, text: ${callElement.getText()}" +
|
||||
"No explicit receiver for 'invoke' resolved call with both receivers: $callElement, text: ${callElement.text}" +
|
||||
"Dispatch receiver: $dispatchReceiver Extension receiver: $extensionReceiver"
|
||||
}
|
||||
}
|
||||
else {
|
||||
assert(explicitReceivers.extensionOrDispatchReceiver == null) {
|
||||
"Non trivial explicit receiver ${explicitReceivers.extensionOrDispatchReceiver}\n" +
|
||||
"for 'invoke' resolved call: $callElement, text: ${callElement.getText()}\n" +
|
||||
"Dispatch receiver: $dispatchReceiver Extension receiver: $extensionReceiver"
|
||||
"Non trivial explicit receiver ${explicitReceivers.extensionOrDispatchReceiver}\n" +
|
||||
"for 'invoke' resolved call: $callElement, text: ${callElement.text}\n" +
|
||||
"Dispatch receiver: $dispatchReceiver Extension receiver: $extensionReceiver"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+12
-12
@@ -35,7 +35,7 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
|
||||
import org.jetbrains.kotlin.util.OperatorNameConventions
|
||||
import java.util.ArrayList
|
||||
|
||||
public fun CallArgumentTranslator.ArgumentsInfo.argsWithReceiver(receiver: JsExpression): List<JsExpression> {
|
||||
fun CallArgumentTranslator.ArgumentsInfo.argsWithReceiver(receiver: JsExpression): List<JsExpression> {
|
||||
val allArguments = ArrayList<JsExpression>(1 + reifiedArguments.size + valueArguments.size)
|
||||
allArguments.addAll(reifiedArguments)
|
||||
allArguments.add(receiver)
|
||||
@@ -107,7 +107,7 @@ object DefaultFunctionCallCase : FunctionCallCase() {
|
||||
}
|
||||
|
||||
val referenceToCall =
|
||||
if (callableDescriptor.getVisibility() == Visibilities.LOCAL) {
|
||||
if (callableDescriptor.visibility == Visibilities.LOCAL) {
|
||||
Namer.getFunctionCallRef(functionRef)
|
||||
}
|
||||
else {
|
||||
@@ -163,13 +163,13 @@ object NativeSetterCallCase : AnnotatedAsNativeXCallCase(PredefinedAnnotation.NA
|
||||
object InvokeIntrinsic : FunctionCallCase() {
|
||||
fun canApply(callInfo: FunctionCallInfo): Boolean {
|
||||
val callableDescriptor = callInfo.callableDescriptor
|
||||
if (callableDescriptor.getName() != OperatorNameConventions.INVOKE)
|
||||
if (callableDescriptor.name != OperatorNameConventions.INVOKE)
|
||||
return false
|
||||
val parameterCount = callableDescriptor.getValueParameters().size
|
||||
val funDeclaration = callableDescriptor.getContainingDeclaration()
|
||||
val parameterCount = callableDescriptor.valueParameters.size
|
||||
val funDeclaration = callableDescriptor.containingDeclaration
|
||||
|
||||
val reflectionTypes = callInfo.context.getReflectionTypes()
|
||||
return if (callableDescriptor.getExtensionReceiverParameter() == null)
|
||||
val reflectionTypes = callInfo.context.reflectionTypes
|
||||
return if (callableDescriptor.extensionReceiverParameter == null)
|
||||
funDeclaration == callableDescriptor.builtIns.getFunction(parameterCount) ||
|
||||
funDeclaration == reflectionTypes.getKFunction(parameterCount)
|
||||
else
|
||||
@@ -209,7 +209,7 @@ object ConstructorCallCase : FunctionCallCase() {
|
||||
val functionRef = if (isNative()) fqName else context.aliasOrValue(callableDescriptor) { fqName }
|
||||
|
||||
val constructorDescriptor = callableDescriptor as ConstructorDescriptor
|
||||
if(constructorDescriptor.isPrimary() || AnnotationsUtils.isNativeObject(constructorDescriptor)) {
|
||||
if(constructorDescriptor.isPrimary || AnnotationsUtils.isNativeObject(constructorDescriptor)) {
|
||||
return JsNew(functionRef, argumentsInfo.translateArguments)
|
||||
}
|
||||
else {
|
||||
@@ -233,11 +233,11 @@ object SuperCallCase : FunctionCallCase() {
|
||||
|
||||
object DynamicInvokeAndBracketAccessCallCase : FunctionCallCase() {
|
||||
fun canApply(callInfo: FunctionCallInfo): Boolean =
|
||||
callInfo.resolvedCall.getCall().getCallType() != Call.CallType.DEFAULT && callInfo.callableDescriptor.isDynamic()
|
||||
callInfo.resolvedCall.call.callType != Call.CallType.DEFAULT && callInfo.callableDescriptor.isDynamic()
|
||||
|
||||
override fun FunctionCallInfo.dispatchReceiver(): JsExpression {
|
||||
val arguments = argumentsInfo.translateArguments
|
||||
val callType = resolvedCall.getCall().getCallType()
|
||||
val callType = resolvedCall.call.callType
|
||||
return when (callType) {
|
||||
Call.CallType.INVOKE ->
|
||||
JsInvocation(dispatchReceiver!!, arguments)
|
||||
@@ -255,13 +255,13 @@ object DynamicInvokeAndBracketAccessCallCase : FunctionCallCase() {
|
||||
object DynamicOperatorCallCase : FunctionCallCase() {
|
||||
fun canApply(callInfo: FunctionCallInfo): Boolean =
|
||||
callInfo.callableDescriptor.isDynamic() &&
|
||||
callInfo.resolvedCall.getCall().getCallElement().let {
|
||||
callInfo.resolvedCall.call.callElement.let {
|
||||
it is KtOperationExpression &&
|
||||
PsiUtils.getOperationToken(it).let { (it == KtTokens.NOT_IN || OperatorTable.hasCorrespondingOperator(it)) }
|
||||
}
|
||||
|
||||
override fun FunctionCallInfo.dispatchReceiver(): JsExpression {
|
||||
val callElement = resolvedCall.getCall().getCallElement() as KtOperationExpression
|
||||
val callElement = resolvedCall.call.callElement as KtOperationExpression
|
||||
val operationToken = PsiUtils.getOperationToken(callElement)
|
||||
|
||||
val arguments = argumentsInfo.translateArguments
|
||||
|
||||
+6
-6
@@ -85,7 +85,7 @@ object DefaultVariableAccessCase : VariableAccessCase() {
|
||||
object DelegatePropertyAccessIntrinsic : DelegateIntrinsic<VariableAccessInfo> {
|
||||
override fun VariableAccessInfo.canBeApply(): Boolean {
|
||||
if(variableDescriptor is PropertyDescriptor) {
|
||||
return isGetAccess() || (variableDescriptor as PropertyDescriptor).isVar()
|
||||
return isGetAccess() || (variableDescriptor as PropertyDescriptor).isVar
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -100,20 +100,20 @@ object DelegatePropertyAccessIntrinsic : DelegateIntrinsic<VariableAccessInfo> {
|
||||
override fun VariableAccessInfo.getDescriptor(): CallableDescriptor {
|
||||
val propertyDescriptor = variableDescriptor as PropertyDescriptor
|
||||
return if (isGetAccess()) {
|
||||
propertyDescriptor.getGetter()!!
|
||||
propertyDescriptor.getter!!
|
||||
} else {
|
||||
propertyDescriptor.getSetter()!!
|
||||
propertyDescriptor.setter!!
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
object SuperPropertyAccessCase : VariableAccessCase() {
|
||||
override fun VariableAccessInfo.dispatchReceiver(): JsExpression {
|
||||
val variableName = context.program().getStringLiteral(this.variableName.getIdent())
|
||||
val variableName = context.program().getStringLiteral(this.variableName.ident)
|
||||
return if (isGetAccess())
|
||||
JsInvocation(context.namer().getCallGetProperty(), JsLiteral.THIS, dispatchReceiver!!, variableName)
|
||||
JsInvocation(context.namer().callGetProperty, JsLiteral.THIS, dispatchReceiver!!, variableName)
|
||||
else
|
||||
JsInvocation(context.namer().getCallSetProperty(), JsLiteral.THIS, dispatchReceiver!!, variableName, value!!)
|
||||
JsInvocation(context.namer().callSetProperty, JsLiteral.THIS, dispatchReceiver!!, variableName, value!!)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -37,12 +37,12 @@ class UsageTracker(
|
||||
val capturedDescriptorToJsName: Map<DeclarationDescriptor, JsName>
|
||||
get() = captured
|
||||
|
||||
public fun used(descriptor: DeclarationDescriptor) {
|
||||
fun used(descriptor: DeclarationDescriptor) {
|
||||
if (isCaptured(descriptor)) return
|
||||
|
||||
// local named function
|
||||
if (descriptor is FunctionDescriptor && descriptor.getVisibility() == Visibilities.LOCAL) {
|
||||
assert(!descriptor.getName().isSpecial()) { "Function with special name can not be captured, descriptor: $descriptor" }
|
||||
if (descriptor is FunctionDescriptor && descriptor.visibility == Visibilities.LOCAL) {
|
||||
assert(!descriptor.getName().isSpecial) { "Function with special name can not be captured, descriptor: $descriptor" }
|
||||
captureIfNeed(descriptor)
|
||||
}
|
||||
// local variable
|
||||
@@ -53,7 +53,7 @@ class UsageTracker(
|
||||
else if (descriptor is ReceiverParameterDescriptor) {
|
||||
captureIfNeed(descriptor)
|
||||
}
|
||||
else if (descriptor is TypeParameterDescriptor && descriptor.isReified()) {
|
||||
else if (descriptor is TypeParameterDescriptor && descriptor.isReified) {
|
||||
captureIfNeed(descriptor)
|
||||
}
|
||||
}
|
||||
@@ -77,9 +77,9 @@ class UsageTracker(
|
||||
}
|
||||
}
|
||||
|
||||
public fun UsageTracker.getNameForCapturedDescriptor(descriptor: DeclarationDescriptor): JsName? = capturedDescriptorToJsName.get(descriptor)
|
||||
fun UsageTracker.getNameForCapturedDescriptor(descriptor: DeclarationDescriptor): JsName? = capturedDescriptorToJsName.get(descriptor)
|
||||
|
||||
public fun UsageTracker.hasCapturedExceptContaining(): Boolean {
|
||||
fun UsageTracker.hasCapturedExceptContaining(): Boolean {
|
||||
val hasNotCaptured =
|
||||
capturedDescriptorToJsName.isEmpty() ||
|
||||
(capturedDescriptorToJsName.size == 1 && capturedDescriptorToJsName.containsKey(containingDescriptor))
|
||||
@@ -87,19 +87,19 @@ public fun UsageTracker.hasCapturedExceptContaining(): Boolean {
|
||||
return !hasNotCaptured
|
||||
}
|
||||
|
||||
public fun UsageTracker.isCaptured(descriptor: DeclarationDescriptor): Boolean = capturedDescriptorToJsName.containsKey(descriptor)
|
||||
fun UsageTracker.isCaptured(descriptor: DeclarationDescriptor): Boolean = capturedDescriptorToJsName.containsKey(descriptor)
|
||||
|
||||
// NOTE: don't use from other places to avoid name clashes! So, it is not in Namer.
|
||||
private fun ReceiverParameterDescriptor.getNameForCapturedReceiver(): String {
|
||||
|
||||
fun DeclarationDescriptor.getNameForCapturedDescriptor(namePostfix: String = ""): String {
|
||||
val name = this.getName()
|
||||
val nameAsString = if (name.isSpecial()) "" else name.asString()
|
||||
val name = this.name
|
||||
val nameAsString = if (name.isSpecial) "" else name.asString()
|
||||
|
||||
return CAPTURED_RECEIVER_NAME_PREFIX + nameAsString + namePostfix
|
||||
}
|
||||
|
||||
val containingDeclaration = this.getContainingDeclaration()
|
||||
val containingDeclaration = this.containingDeclaration
|
||||
|
||||
assert(containingDeclaration is MemberDescriptor) {
|
||||
"Unsupported descriptor type: ${containingDeclaration.javaClass}, " +
|
||||
@@ -107,7 +107,7 @@ private fun ReceiverParameterDescriptor.getNameForCapturedReceiver(): String {
|
||||
}
|
||||
|
||||
if (DescriptorUtils.isCompanionObject(containingDeclaration)) {
|
||||
return containingDeclaration.getContainingDeclaration()!!.getNameForCapturedDescriptor(namePostfix = "$")
|
||||
return containingDeclaration.containingDeclaration!!.getNameForCapturedDescriptor(namePostfix = "$")
|
||||
}
|
||||
|
||||
return containingDeclaration.getNameForCapturedDescriptor()
|
||||
|
||||
+22
-24
@@ -57,7 +57,7 @@ import java.util.*
|
||||
/**
|
||||
* Generates a definition of a single class.
|
||||
*/
|
||||
public class ClassTranslator private constructor(
|
||||
class ClassTranslator private constructor(
|
||||
private val classDeclaration: KtClassOrObject,
|
||||
context: TranslationContext
|
||||
) : AbstractTranslator(context) {
|
||||
@@ -74,7 +74,7 @@ public class ClassTranslator private constructor(
|
||||
return JsInvocation(context().namer().classCreateInvocation(descriptor), getClassCreateInvocationArguments(declarationContext))
|
||||
}
|
||||
|
||||
private fun isTrait(): Boolean = descriptor.getKind() == ClassKind.INTERFACE
|
||||
private fun isTrait(): Boolean = descriptor.kind == ClassKind.INTERFACE
|
||||
|
||||
private fun getClassCreateInvocationArguments(declarationContext: TranslationContext): List<JsExpression> {
|
||||
var context = declarationContext
|
||||
@@ -89,7 +89,7 @@ public class ClassTranslator private constructor(
|
||||
if (isTopLevelDeclaration) {
|
||||
var definitionPlace: DefinitionPlace? = null
|
||||
|
||||
if (!descriptor.getKind().isSingleton() && !isAnonymousObject(descriptor)) {
|
||||
if (!descriptor.kind.isSingleton && !isAnonymousObject(descriptor)) {
|
||||
qualifiedReference = context.getQualifiedReference(descriptor)
|
||||
val scope = context().getScopeForDescriptor(descriptor)
|
||||
definitionPlace = DefinitionPlace(scope as JsObjectScope, qualifiedReference, staticProperties)
|
||||
@@ -104,7 +104,7 @@ public class ClassTranslator private constructor(
|
||||
val delegationTranslator = DelegationTranslator(classDeclaration, context())
|
||||
if (!isTrait()) {
|
||||
val initializer = ClassInitializerTranslator(classDeclaration, context).generateInitializeMethod(delegationTranslator)
|
||||
invocationArguments.add(if (initializer.getBody().getStatements().isEmpty()) JsLiteral.NULL else initializer)
|
||||
invocationArguments.add(if (initializer.body.statements.isEmpty()) JsLiteral.NULL else initializer)
|
||||
}
|
||||
|
||||
translatePropertiesAsConstructorParameters(context, properties)
|
||||
@@ -148,9 +148,9 @@ public class ClassTranslator private constructor(
|
||||
private fun fixContextForCompanionObjectAccessing(context: TranslationContext): TranslationContext {
|
||||
// In Kotlin we can access to companion object members without qualifier just by name, but we should translate it to access with FQ name.
|
||||
// So create alias for companion object receiver parameter.
|
||||
val companionObjectDescriptor = descriptor.getCompanionObjectDescriptor()
|
||||
val companionObjectDescriptor = descriptor.companionObjectDescriptor
|
||||
if (companionObjectDescriptor != null) {
|
||||
val referenceToClass = translateAsFQReference(companionObjectDescriptor.getContainingDeclaration(), context)
|
||||
val referenceToClass = translateAsFQReference(companionObjectDescriptor.containingDeclaration, context)
|
||||
val companionObjectAccessor = Namer.getCompanionObjectAccessor(referenceToClass)
|
||||
val companionObjectReceiver = getReceiverParameterForDeclaration(companionObjectDescriptor)
|
||||
context.aliasingContext().registerAlias(companionObjectReceiver, companionObjectAccessor)
|
||||
@@ -159,7 +159,7 @@ public class ClassTranslator private constructor(
|
||||
// Overlap alias of companion object receiver for accessing from containing class(see previous if block),
|
||||
// because inside companion object we should use simple name for access.
|
||||
if (isCompanionObject(descriptor)) {
|
||||
return context.innerContextWithAliased(descriptor.getThisAsReceiverParameter(), JsLiteral.THIS)
|
||||
return context.innerContextWithAliased(descriptor.thisAsReceiverParameter, JsLiteral.THIS)
|
||||
}
|
||||
|
||||
return context
|
||||
@@ -188,9 +188,9 @@ public class ClassTranslator private constructor(
|
||||
|
||||
val supertypeConstructors = HashSet<TypeConstructor>()
|
||||
for (type in supertypes) {
|
||||
supertypeConstructors.add(type.getConstructor())
|
||||
supertypeConstructors.add(type.constructor)
|
||||
}
|
||||
val sortedAllSuperTypes = topologicallySortSuperclassesAndRecordAllInstances(descriptor.getDefaultType(), HashMap<TypeConstructor, Set<KotlinType>>(), HashSet<TypeConstructor>())
|
||||
val sortedAllSuperTypes = topologicallySortSuperclassesAndRecordAllInstances(descriptor.defaultType, HashMap<TypeConstructor, Set<KotlinType>>(), HashSet<TypeConstructor>())
|
||||
val supertypesRefs = ArrayList<JsExpression>()
|
||||
for (typeConstructor in sortedAllSuperTypes) {
|
||||
if (supertypeConstructors.contains(typeConstructor)) {
|
||||
@@ -215,10 +215,10 @@ public class ClassTranslator private constructor(
|
||||
}
|
||||
|
||||
private fun translateObjectInsideClass(outerClassContext: TranslationContext): JsExpression {
|
||||
val function = JsFunction(outerClassContext.scope(), JsBlock(), "initializer for " + descriptor.getName().asString())
|
||||
val function = JsFunction(outerClassContext.scope(), JsBlock(), "initializer for " + descriptor.name.asString())
|
||||
val funContext = outerClassContext.newFunctionBodyWithUsageTracker(function, descriptor)
|
||||
|
||||
function.getBody().getStatements().add(JsReturn(translate(funContext)))
|
||||
function.body.statements.add(JsReturn(translate(funContext)))
|
||||
|
||||
return function.withCapturedParameters(funContext, outerClassContext, descriptor)
|
||||
}
|
||||
@@ -240,7 +240,7 @@ public class ClassTranslator private constructor(
|
||||
}
|
||||
|
||||
private fun generateOtherBridges(properties: MutableList<JsPropertyInitializer>) {
|
||||
for (memberDescriptor in descriptor.getDefaultType().getMemberScope().getContributedDescriptors()) {
|
||||
for (memberDescriptor in descriptor.defaultType.memberScope.getContributedDescriptors()) {
|
||||
if (memberDescriptor is FunctionDescriptor) {
|
||||
val bridgesToGenerate = generateBridgesForFunctionDescriptor(memberDescriptor, identity())
|
||||
|
||||
@@ -256,7 +256,7 @@ public class ClassTranslator private constructor(
|
||||
val toDescriptor = bridge.to
|
||||
if (areNamesEqual(fromDescriptor, toDescriptor)) return
|
||||
|
||||
if (fromDescriptor.getKind().isReal() && fromDescriptor.getModality() != Modality.ABSTRACT && !toDescriptor.getKind().isReal())
|
||||
if (fromDescriptor.kind.isReal && fromDescriptor.modality != Modality.ABSTRACT && !toDescriptor.kind.isReal)
|
||||
return
|
||||
|
||||
properties.add(generateDelegateCall(fromDescriptor, toDescriptor, JsLiteral.THIS, context()))
|
||||
@@ -265,11 +265,11 @@ public class ClassTranslator private constructor(
|
||||
private fun areNamesEqual(first: FunctionDescriptor, second: FunctionDescriptor): Boolean {
|
||||
val firstName = context().getNameForDescriptor(first)
|
||||
val secondName = context().getNameForDescriptor(second)
|
||||
return firstName.getIdent() == secondName.getIdent()
|
||||
return firstName.ident == secondName.ident
|
||||
}
|
||||
|
||||
companion object {
|
||||
public fun translate(classDeclaration: KtClass, context: TranslationContext): List<JsPropertyInitializer> {
|
||||
fun translate(classDeclaration: KtClass, context: TranslationContext): List<JsPropertyInitializer> {
|
||||
val result = arrayListOf<JsPropertyInitializer>()
|
||||
|
||||
val classDescriptor = getClassDescriptor(context.bindingContext(), classDeclaration)
|
||||
@@ -285,19 +285,17 @@ public class ClassTranslator private constructor(
|
||||
return result
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
public fun generateClassCreation(classDeclaration: KtClassOrObject, context: TranslationContext): JsInvocation {
|
||||
@JvmStatic fun generateClassCreation(classDeclaration: KtClassOrObject, context: TranslationContext): JsInvocation {
|
||||
return ClassTranslator(classDeclaration, context).translate()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
public fun generateObjectLiteral(objectDeclaration: KtObjectDeclaration, context: TranslationContext): JsExpression {
|
||||
@JvmStatic fun generateObjectLiteral(objectDeclaration: KtObjectDeclaration, context: TranslationContext): JsExpression {
|
||||
return ClassTranslator(objectDeclaration, context).translateObjectLiteralExpression()
|
||||
}
|
||||
|
||||
private fun generateSecondaryConstructor(constructor: KtSecondaryConstructor, context: TranslationContext): JsPropertyInitializer {
|
||||
val constructorDescriptor = BindingUtils.getDescriptorForElement(context.bindingContext(), constructor) as ConstructorDescriptor
|
||||
val classDescriptor = constructorDescriptor.getContainingDeclaration()
|
||||
val classDescriptor = constructorDescriptor.containingDeclaration
|
||||
|
||||
val constructorScope = context.getScopeForDescriptor(constructorDescriptor)
|
||||
val thisName = constructorScope.declareName(Namer.ANOTHER_THIS_PARAMETER_NAME)
|
||||
@@ -306,9 +304,9 @@ public class ClassTranslator private constructor(
|
||||
val translationContext = context.innerContextWithAliased(receiverDescriptor, thisNameRef)
|
||||
|
||||
val constructorInitializer = FunctionTranslator.newInstance(constructor, translationContext).translateAsMethod()
|
||||
val constructorFunction = constructorInitializer.getValueExpr() as JsFunction
|
||||
val constructorFunction = constructorInitializer.valueExpr as JsFunction
|
||||
|
||||
constructorFunction.getParameters().add(JsParameter(thisName))
|
||||
constructorFunction.parameters.add(JsParameter(thisName))
|
||||
|
||||
val referenceToClass = context.getQualifiedReference(classDescriptor)
|
||||
|
||||
@@ -321,7 +319,7 @@ public class ClassTranslator private constructor(
|
||||
add(instanceVar)
|
||||
|
||||
val resolvedCall = BindingContextUtils.getDelegationConstructorCall(context.bindingContext(), constructorDescriptor)
|
||||
val delegationClassDescriptor = resolvedCall?.getResultingDescriptor()?.getContainingDeclaration()
|
||||
val delegationClassDescriptor = resolvedCall?.resultingDescriptor?.containingDeclaration
|
||||
|
||||
if (resolvedCall != null && !KotlinBuiltIns.isAny(delegationClassDescriptor!!)) {
|
||||
val superCall = CallTranslator.translate(context, resolvedCall)
|
||||
@@ -336,7 +334,7 @@ public class ClassTranslator private constructor(
|
||||
this
|
||||
}
|
||||
|
||||
with(constructorFunction.getBody().getStatements()) {
|
||||
with(constructorFunction.body.statements) {
|
||||
addAll(0, forAddToBeginning)
|
||||
add(JsReturn(thisNameRef))
|
||||
}
|
||||
|
||||
+22
-22
@@ -38,7 +38,7 @@ import org.jetbrains.kotlin.psi.KtDelegatedSuperTypeEntry
|
||||
import org.jetbrains.kotlin.resolve.DescriptorUtils
|
||||
import java.util.*
|
||||
|
||||
public class DelegationTranslator(
|
||||
class DelegationTranslator(
|
||||
private val classDeclaration: KtClassOrObject,
|
||||
context: TranslationContext
|
||||
) : AbstractTranslator(context) {
|
||||
@@ -54,13 +54,13 @@ public class DelegationTranslator(
|
||||
|
||||
init {
|
||||
for (specifier in delegationBySpecifiers) {
|
||||
val expression = specifier.getDelegateExpression() ?:
|
||||
throw IllegalArgumentException("delegate expression should not be null: ${specifier.getText()}")
|
||||
val expression = specifier.delegateExpression ?:
|
||||
throw IllegalArgumentException("delegate expression should not be null: ${specifier.text}")
|
||||
val descriptor = getSuperClass(specifier)
|
||||
val propertyDescriptor = CodegenUtil.getDelegatePropertyIfAny(expression, classDescriptor, bindingContext())
|
||||
|
||||
if (CodegenUtil.isFinalPropertyWithBackingField(propertyDescriptor, bindingContext())) {
|
||||
fields.put(specifier, Field(propertyDescriptor!!.getName().asString(), false))
|
||||
fields.put(specifier, Field(propertyDescriptor!!.name.asString(), false))
|
||||
}
|
||||
else {
|
||||
val classFqName = DescriptorUtils.getFqName(classDescriptor)
|
||||
@@ -71,18 +71,18 @@ public class DelegationTranslator(
|
||||
}
|
||||
}
|
||||
|
||||
public fun addInitCode(statements: MutableList<JsStatement>) {
|
||||
fun addInitCode(statements: MutableList<JsStatement>) {
|
||||
for (specifier in delegationBySpecifiers) {
|
||||
val field = fields.get(specifier)!!
|
||||
if (field.generateField) {
|
||||
val expression = specifier.getDelegateExpression()!!
|
||||
val expression = specifier.delegateExpression!!
|
||||
val delegateInitExpr = Translation.translateAsExpression(expression, context())
|
||||
statements.add(JsAstUtils.defineSimpleProperty(field.name, delegateInitExpr))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public fun generateDelegated(properties: MutableList<JsPropertyInitializer>) {
|
||||
fun generateDelegated(properties: MutableList<JsPropertyInitializer>) {
|
||||
for (specifier in delegationBySpecifiers) {
|
||||
generateDelegates(getSuperClass(specifier), fields.get(specifier)!!, properties)
|
||||
}
|
||||
@@ -109,7 +109,7 @@ public class DelegationTranslator(
|
||||
delegateName: String,
|
||||
properties: MutableList<JsPropertyInitializer>
|
||||
) {
|
||||
val propertyName: String = descriptor.getName().asString()
|
||||
val propertyName: String = descriptor.name.asString()
|
||||
|
||||
fun generateDelegateGetterFunction(getterDescriptor: PropertyGetterDescriptor): JsFunction {
|
||||
// TODO review: used wrong scope?
|
||||
@@ -126,21 +126,21 @@ public class DelegationTranslator(
|
||||
(JsNameRef(propertyName, delegateRef) as JsExpression) // TODO remove explicit type specification after resolving KT-5569
|
||||
}
|
||||
|
||||
val jsFunction = simpleReturnFunction(context().getScopeForDescriptor(getterDescriptor.getContainingDeclaration()), returnExpression)
|
||||
val jsFunction = simpleReturnFunction(context().getScopeForDescriptor(getterDescriptor.containingDeclaration), returnExpression)
|
||||
if (DescriptorUtils.isExtension(descriptor)) {
|
||||
val receiverName = jsFunction.getScope().declareName(Namer.getReceiverParameterName())
|
||||
jsFunction.getParameters().add(JsParameter(receiverName))
|
||||
val receiverName = jsFunction.scope.declareName(Namer.getReceiverParameterName())
|
||||
jsFunction.parameters.add(JsParameter(receiverName))
|
||||
}
|
||||
return jsFunction
|
||||
}
|
||||
|
||||
fun generateDelegateSetterFunction(setterDescriptor: PropertySetterDescriptor): JsFunction {
|
||||
val jsFunction = JsFunction(context().getScopeForDescriptor(setterDescriptor.getContainingDeclaration()),
|
||||
"setter for " + setterDescriptor.getName().asString())
|
||||
val jsFunction = JsFunction(context().getScopeForDescriptor(setterDescriptor.containingDeclaration),
|
||||
"setter for " + setterDescriptor.name.asString())
|
||||
|
||||
assert(setterDescriptor.getValueParameters().size == 1) { "Setter must have 1 parameter" }
|
||||
val defaultParameter = JsParameter(jsFunction.getScope().declareTemporary())
|
||||
val defaultParameterRef = defaultParameter.getName().makeRef()
|
||||
assert(setterDescriptor.valueParameters.size == 1) { "Setter must have 1 parameter" }
|
||||
val defaultParameter = JsParameter(jsFunction.scope.declareTemporary())
|
||||
val defaultParameterRef = defaultParameter.name.makeRef()
|
||||
|
||||
val delegateRefName = context().getScopeForDescriptor(setterDescriptor).declareName(delegateName)
|
||||
val delegateRef = JsNameRef(delegateRefName, JsLiteral.THIS)
|
||||
@@ -148,8 +148,8 @@ public class DelegationTranslator(
|
||||
val setExpression = if (DescriptorUtils.isExtension(descriptor)) {
|
||||
val setterName = context().getNameForDescriptor(setterDescriptor)
|
||||
val setterNameRef = JsNameRef(setterName, delegateRef)
|
||||
val extensionFunctionReceiverName = jsFunction.getScope().declareName(Namer.getReceiverParameterName())
|
||||
jsFunction.getParameters().add(JsParameter(extensionFunctionReceiverName))
|
||||
val extensionFunctionReceiverName = jsFunction.scope.declareName(Namer.getReceiverParameterName())
|
||||
jsFunction.parameters.add(JsParameter(extensionFunctionReceiverName))
|
||||
JsInvocation(setterNameRef, JsNameRef(extensionFunctionReceiverName), defaultParameterRef)
|
||||
}
|
||||
else {
|
||||
@@ -157,8 +157,8 @@ public class DelegationTranslator(
|
||||
JsAstUtils.assignment(propertyNameRef, defaultParameterRef)
|
||||
}
|
||||
|
||||
jsFunction.getParameters().add(defaultParameter)
|
||||
jsFunction.setBody(JsBlock(setExpression.makeStmt()))
|
||||
jsFunction.parameters.add(defaultParameter)
|
||||
jsFunction.body = JsBlock(setExpression.makeStmt())
|
||||
return jsFunction
|
||||
}
|
||||
|
||||
@@ -166,12 +166,12 @@ public class DelegationTranslator(
|
||||
translateFunctionAsEcma5PropertyDescriptor(function, accessorDescriptor, context())
|
||||
|
||||
fun generateDelegateGetter(): JsPropertyInitializer {
|
||||
val getterDescriptor = descriptor.getGetter() ?: throw IllegalStateException("Getter descriptor should not be null")
|
||||
val getterDescriptor = descriptor.getter ?: throw IllegalStateException("Getter descriptor should not be null")
|
||||
return generateDelegateAccessor(getterDescriptor, generateDelegateGetterFunction(getterDescriptor))
|
||||
}
|
||||
|
||||
fun generateDelegateSetter(): JsPropertyInitializer {
|
||||
val setterDescriptor = descriptor.getSetter() ?: throw IllegalStateException("Setter descriptor should not be null")
|
||||
val setterDescriptor = descriptor.setter ?: throw IllegalStateException("Setter descriptor should not be null")
|
||||
return generateDelegateAccessor(setterDescriptor, generateDelegateSetterFunction(setterDescriptor))
|
||||
}
|
||||
|
||||
|
||||
+6
-6
@@ -39,7 +39,7 @@ class FileDeclarationVisitor(
|
||||
|
||||
private val initializer = JsAstUtils.createFunctionWithEmptyBody(context.scope())
|
||||
private val initializerContext = context.contextWithScope(initializer)
|
||||
private val initializerStatements = initializer.getBody().getStatements()
|
||||
private val initializerStatements = initializer.body.statements
|
||||
private val initializerVisitor = InitializerVisitor(initializerStatements)
|
||||
|
||||
fun computeInitializer(): JsFunction? {
|
||||
@@ -50,21 +50,21 @@ class FileDeclarationVisitor(
|
||||
}
|
||||
}
|
||||
|
||||
public override fun visitClass(expression: KtClass, context: TranslationContext?): Void? {
|
||||
override fun visitClass(expression: KtClass, context: TranslationContext?): Void? {
|
||||
result.addAll(ClassTranslator.translate(expression, context!!))
|
||||
return null
|
||||
}
|
||||
|
||||
public override fun visitObjectDeclaration(declaration: KtObjectDeclaration, context: TranslationContext?): Void? {
|
||||
override fun visitObjectDeclaration(declaration: KtObjectDeclaration, context: TranslationContext?): Void? {
|
||||
InitializerUtils.generateObjectInitializer(declaration, initializerStatements, context!!)
|
||||
return null
|
||||
}
|
||||
|
||||
public override fun visitProperty(expression: KtProperty, context: TranslationContext?): Void? {
|
||||
override fun visitProperty(expression: KtProperty, context: TranslationContext?): Void? {
|
||||
context!! // hack
|
||||
|
||||
super.visitProperty(expression, context)
|
||||
val initializer = expression.getInitializer()
|
||||
val initializer = expression.initializer
|
||||
if (initializer != null) {
|
||||
val value = Translation.translateAsExpression(initializer, initializerContext)
|
||||
val propertyDescriptor: PropertyDescriptor = getPropertyDescriptor(context.bindingContext(), expression)
|
||||
@@ -78,7 +78,7 @@ class FileDeclarationVisitor(
|
||||
return null
|
||||
}
|
||||
|
||||
public override fun visitAnonymousInitializer(expression: KtAnonymousInitializer, context: TranslationContext?): Void? {
|
||||
override fun visitAnonymousInitializer(expression: KtAnonymousInitializer, context: TranslationContext?): Void? {
|
||||
expression.accept(initializerVisitor, initializerContext)
|
||||
return null
|
||||
}
|
||||
|
||||
+26
-26
@@ -43,18 +43,18 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
|
||||
* Translates single property /w accessors.
|
||||
*/
|
||||
|
||||
public fun translateAccessors(
|
||||
fun translateAccessors(
|
||||
descriptor: PropertyDescriptor,
|
||||
declaration: KtProperty?,
|
||||
result: MutableList<JsPropertyInitializer>,
|
||||
context: TranslationContext
|
||||
) {
|
||||
if (descriptor.getModality() == Modality.ABSTRACT || JsDescriptorUtils.isSimpleFinalProperty(descriptor)) return
|
||||
if (descriptor.modality == Modality.ABSTRACT || JsDescriptorUtils.isSimpleFinalProperty(descriptor)) return
|
||||
|
||||
PropertyTranslator(descriptor, declaration, context).translate(result)
|
||||
}
|
||||
|
||||
public fun translateAccessors(
|
||||
fun translateAccessors(
|
||||
descriptor: PropertyDescriptor,
|
||||
result: MutableList<JsPropertyInitializer>,
|
||||
context: TranslationContext
|
||||
@@ -62,7 +62,7 @@ public fun translateAccessors(
|
||||
translateAccessors(descriptor, null, result, context)
|
||||
}
|
||||
|
||||
public fun MutableList<JsPropertyInitializer>.addGetterAndSetter(
|
||||
fun MutableList<JsPropertyInitializer>.addGetterAndSetter(
|
||||
descriptor: PropertyDescriptor,
|
||||
context: TranslationContext,
|
||||
generateGetter: () -> JsPropertyInitializer,
|
||||
@@ -78,7 +78,7 @@ public fun MutableList<JsPropertyInitializer>.addGetterAndSetter(
|
||||
}
|
||||
|
||||
to.add(generateGetter())
|
||||
if (descriptor.isVar()) {
|
||||
if (descriptor.isVar) {
|
||||
to.add(generateSetter())
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,7 @@ private class PropertyTranslator(
|
||||
context: TranslationContext
|
||||
) : AbstractTranslator(context) {
|
||||
|
||||
private val propertyName: String = descriptor.getName().asString()
|
||||
private val propertyName: String = descriptor.name.asString()
|
||||
|
||||
fun translate(result: MutableList<JsPropertyInitializer>) {
|
||||
result.addGetterAndSetter(descriptor, context(), { generateGetter() }, { generateSetter() })
|
||||
@@ -101,20 +101,20 @@ private class PropertyTranslator(
|
||||
private fun generateSetter(): JsPropertyInitializer =
|
||||
if (hasCustomSetter()) translateCustomAccessor(getCustomSetterDeclaration()) else generateDefaultSetter()
|
||||
|
||||
private fun hasCustomGetter() = declaration?.getGetter() != null && getCustomGetterDeclaration().hasBody()
|
||||
private fun hasCustomGetter() = declaration?.getter != null && getCustomGetterDeclaration().hasBody()
|
||||
|
||||
private fun hasCustomSetter() = declaration?.getSetter() != null && getCustomSetterDeclaration().hasBody()
|
||||
private fun hasCustomSetter() = declaration?.setter != null && getCustomSetterDeclaration().hasBody()
|
||||
|
||||
private fun getCustomGetterDeclaration(): KtPropertyAccessor =
|
||||
declaration?.getGetter() ?:
|
||||
throw IllegalStateException("declaration and getter should not be null descriptor=${descriptor} declaration=${declaration}")
|
||||
declaration?.getter ?:
|
||||
throw IllegalStateException("declaration and getter should not be null descriptor=${descriptor} declaration=${declaration}")
|
||||
|
||||
private fun getCustomSetterDeclaration(): KtPropertyAccessor =
|
||||
declaration?.getSetter() ?:
|
||||
throw IllegalStateException("declaration and setter should not be null descriptor=${descriptor} declaration=${declaration}")
|
||||
declaration?.setter ?:
|
||||
throw IllegalStateException("declaration and setter should not be null descriptor=${descriptor} declaration=${declaration}")
|
||||
|
||||
private fun generateDefaultGetter(): JsPropertyInitializer {
|
||||
val getterDescriptor = descriptor.getGetter() ?: throw IllegalStateException("Getter descriptor should not be null")
|
||||
val getterDescriptor = descriptor.getter ?: throw IllegalStateException("Getter descriptor should not be null")
|
||||
return generateDefaultAccessor(getterDescriptor, generateDefaultGetterFunction(getterDescriptor))
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ private class PropertyTranslator(
|
||||
}
|
||||
|
||||
assert(!descriptor.isExtension) { "Unexpected extension property $descriptor}" }
|
||||
val scope = context().getScopeForDescriptor(getterDescriptor.getContainingDeclaration())
|
||||
val scope = context().getScopeForDescriptor(getterDescriptor.containingDeclaration)
|
||||
val result = backingFieldReference(context(), descriptor)
|
||||
val body = JsBlock(JsReturn(result))
|
||||
|
||||
@@ -137,7 +137,7 @@ private class PropertyTranslator(
|
||||
getterDescriptor: PropertyGetterDescriptor,
|
||||
delegatedCall: ResolvedCall<FunctionDescriptor>
|
||||
): JsFunction {
|
||||
val scope = context().getScopeForDescriptor(getterDescriptor.getContainingDeclaration())
|
||||
val scope = context().getScopeForDescriptor(getterDescriptor.containingDeclaration)
|
||||
val function = JsFunction(scope, JsBlock(), accessorDescription(getterDescriptor))
|
||||
|
||||
val delegateRef = getDelegateNameRef(propertyName)
|
||||
@@ -146,8 +146,8 @@ private class PropertyTranslator(
|
||||
)
|
||||
|
||||
if (getterDescriptor.isExtension) {
|
||||
val receiver = function.addParameter(getReceiverParameterName()).getName()
|
||||
val arguments = (delegatedJsCall as JsInvocation).getArguments()
|
||||
val receiver = function.addParameter(getReceiverParameterName()).name
|
||||
val arguments = (delegatedJsCall as JsInvocation).arguments
|
||||
arguments.set(0, receiver.makeRef())
|
||||
}
|
||||
|
||||
@@ -169,18 +169,18 @@ private class PropertyTranslator(
|
||||
}
|
||||
|
||||
private fun generateDefaultSetter(): JsPropertyInitializer {
|
||||
val setterDescriptor = descriptor.getSetter() ?: throw IllegalStateException("Setter descriptor should not be null")
|
||||
val setterDescriptor = descriptor.setter ?: throw IllegalStateException("Setter descriptor should not be null")
|
||||
return generateDefaultAccessor(setterDescriptor, generateDefaultSetterFunction(setterDescriptor))
|
||||
}
|
||||
|
||||
private fun generateDefaultSetterFunction(setterDescriptor: PropertySetterDescriptor): JsFunction {
|
||||
val containingScope = context().getScopeForDescriptor(setterDescriptor.getContainingDeclaration())
|
||||
val containingScope = context().getScopeForDescriptor(setterDescriptor.containingDeclaration)
|
||||
val function = JsFunction(containingScope, JsBlock(), accessorDescription(setterDescriptor))
|
||||
|
||||
assert(setterDescriptor.getValueParameters().size == 1) { "Setter must have 1 parameter" }
|
||||
val correspondingPropertyName = setterDescriptor.getCorrespondingProperty().getName().asString()
|
||||
val valueParameter = function.addParameter(correspondingPropertyName).getName()
|
||||
val withAliased = context().innerContextWithAliased(setterDescriptor.getValueParameters().get(0), valueParameter.makeRef())
|
||||
assert(setterDescriptor.valueParameters.size == 1) { "Setter must have 1 parameter" }
|
||||
val correspondingPropertyName = setterDescriptor.correspondingProperty.name.asString()
|
||||
val valueParameter = function.addParameter(correspondingPropertyName).name
|
||||
val withAliased = context().innerContextWithAliased(setterDescriptor.valueParameters.get(0), valueParameter.makeRef())
|
||||
val delegatedCall = context().bindingContext().get(BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, setterDescriptor)
|
||||
|
||||
if (delegatedCall != null) {
|
||||
@@ -191,8 +191,8 @@ private class PropertyTranslator(
|
||||
function.addStatement(delegatedJsCall.makeStmt())
|
||||
|
||||
if (setterDescriptor.isExtension) {
|
||||
val receiver = function.addParameter(getReceiverParameterName(), 0).getName()
|
||||
(delegatedJsCall as JsInvocation).getArguments().set(0, receiver.makeRef())
|
||||
val receiver = function.addParameter(getReceiverParameterName(), 0).name
|
||||
(delegatedJsCall as JsInvocation).arguments.set(0, receiver.makeRef())
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -221,7 +221,7 @@ private class PropertyTranslator(
|
||||
throw IllegalArgumentException("Unknown accessor type ${accessorDescriptor.javaClass}")
|
||||
}
|
||||
|
||||
val name = accessorDescriptor.getName().asString()
|
||||
val name = accessorDescriptor.name.asString()
|
||||
return "$accessorType for $name"
|
||||
}
|
||||
}
|
||||
|
||||
+9
-9
@@ -63,16 +63,16 @@ class CatchTranslator(
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
public fun translate(): JsCatch? {
|
||||
fun translate(): JsCatch? {
|
||||
if (catches.isEmpty()) return null
|
||||
|
||||
val firstCatch = catches.first()
|
||||
val catchParameter = firstCatch.getCatchParameter()
|
||||
val catchParameter = firstCatch.catchParameter
|
||||
val parameterName = context().getNameForElement(catchParameter!!)
|
||||
val parameterRef = parameterName.makeRef()
|
||||
|
||||
return JsCatch(context().scope(),
|
||||
parameterRef.getIdent(),
|
||||
parameterRef.ident,
|
||||
translateCatches(parameterRef, catches.iterator()))
|
||||
}
|
||||
|
||||
@@ -80,13 +80,13 @@ class CatchTranslator(
|
||||
if (!catches.hasNext()) return JsThrow(parameterRef)
|
||||
|
||||
val catch = catches.next()
|
||||
val param = catch.getCatchParameter()!!
|
||||
val param = catch.catchParameter!!
|
||||
val paramName = context().getNameForElement(param)
|
||||
val paramType = param.getTypeReference()!!
|
||||
val paramType = param.typeReference!!
|
||||
|
||||
val thenBlock = translateCatchBody(context(), catch)
|
||||
if (paramName.getIdent() != parameterRef.getIdent())
|
||||
thenBlock.getStatements().add(0, JsAstUtils.newVar(paramName, parameterRef))
|
||||
if (paramName.ident != parameterRef.ident)
|
||||
thenBlock.statements.add(0, JsAstUtils.newVar(paramName, parameterRef))
|
||||
|
||||
if (paramType.isThrowable) return thenBlock
|
||||
|
||||
@@ -99,12 +99,12 @@ class CatchTranslator(
|
||||
}
|
||||
|
||||
private fun translateCatchBody(context: TranslationContext, catchClause: KtCatchClause): JsBlock {
|
||||
val catchBody = catchClause.getCatchBody()
|
||||
val catchBody = catchClause.catchBody
|
||||
val jsCatchBody =
|
||||
if (catchBody != null)
|
||||
translateAsStatementAndMergeInBlockIfNeeded(catchBody, context)
|
||||
else
|
||||
context.getEmptyExpression().makeStmt()
|
||||
context.emptyExpression.makeStmt()
|
||||
|
||||
return convertToBlock(jsCatchBody)
|
||||
}
|
||||
|
||||
@@ -24,11 +24,11 @@ import org.jetbrains.kotlin.js.translate.utils.JsDescriptorUtils.*
|
||||
|
||||
private val METADATA_PROPERTIES_COUNT = 2
|
||||
|
||||
public class InlineMetadata(val tag: JsStringLiteral, val function: JsFunction) {
|
||||
class InlineMetadata(val tag: JsStringLiteral, val function: JsFunction) {
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun compose(function: JsFunction, descriptor: CallableDescriptor): InlineMetadata {
|
||||
val program = function.getScope().getProgram()
|
||||
val program = function.scope.program
|
||||
val tag = program.getStringLiteral(Namer.getFunctionTag(descriptor))
|
||||
return InlineMetadata(tag, function)
|
||||
}
|
||||
@@ -41,9 +41,9 @@ public class InlineMetadata(val tag: JsStringLiteral, val function: JsFunction)
|
||||
}
|
||||
|
||||
private fun decomposeCreateFunctionCall(call: JsInvocation): InlineMetadata? {
|
||||
if (Namer.CREATE_INLINE_FUNCTION != call.getQualifier()) return null
|
||||
if (Namer.CREATE_INLINE_FUNCTION != call.qualifier) return null
|
||||
|
||||
val arguments = call.getArguments()
|
||||
val arguments = call.arguments
|
||||
if (arguments.size != METADATA_PROPERTIES_COUNT) return null
|
||||
|
||||
val tag = arguments[0] as? JsStringLiteral
|
||||
@@ -54,7 +54,7 @@ public class InlineMetadata(val tag: JsStringLiteral, val function: JsFunction)
|
||||
}
|
||||
}
|
||||
|
||||
public val functionWithMetadata: JsExpression
|
||||
val functionWithMetadata: JsExpression
|
||||
get() {
|
||||
val propertiesList = listOf(tag, function)
|
||||
return JsInvocation(Namer.CREATE_INLINE_FUNCTION, propertiesList)
|
||||
|
||||
+11
-11
@@ -41,16 +41,16 @@ class LiteralFunctionTranslator(context: TranslationContext) : AbstractTranslato
|
||||
val lambda = invokingContext.getFunctionObject(descriptor)
|
||||
val functionContext = invokingContext.newFunctionBodyWithUsageTracker(lambda, descriptor)
|
||||
|
||||
FunctionTranslator.addParameters(lambda.getParameters(), descriptor, functionContext)
|
||||
FunctionTranslator.addParameters(lambda.parameters, descriptor, functionContext)
|
||||
val functionBody = translateFunctionBody(descriptor, declaration, functionContext)
|
||||
lambda.getBody().getStatements().addAll(functionBody.getStatements())
|
||||
lambda.body.statements.addAll(functionBody.statements)
|
||||
|
||||
val tracker = functionContext.usageTracker()!!
|
||||
|
||||
val isRecursive = tracker.isCaptured(descriptor)
|
||||
|
||||
if (isRecursive) {
|
||||
lambda.setName(tracker.getNameForCapturedDescriptor(descriptor))
|
||||
lambda.name = tracker.getNameForCapturedDescriptor(descriptor)
|
||||
}
|
||||
|
||||
if (tracker.hasCapturedExceptContaining()) {
|
||||
@@ -78,8 +78,8 @@ fun JsFunction.withCapturedParameters(context: TranslationContext, invokingConte
|
||||
val ref = invokingContext.define(descriptor, this)
|
||||
val invocation = JsInvocation(ref)
|
||||
|
||||
val invocationArguments = invocation.getArguments()
|
||||
val functionParameters = this.getParameters()
|
||||
val invocationArguments = invocation.arguments
|
||||
val functionParameters = this.parameters
|
||||
|
||||
val tracker = context.usageTracker()!!
|
||||
|
||||
@@ -149,13 +149,13 @@ private fun moveCapturedLocalInside(capturingFunction: JsFunction, capturedName:
|
||||
* `lambda` should capture x in this case
|
||||
*/
|
||||
private fun moveCapturedLocalInside(capturingFunction: JsFunction, capturedName: JsName, localFunAlias: JsInvocation): CapturedArgsParams {
|
||||
val capturedArgs = localFunAlias.getArguments()
|
||||
val capturedArgs = localFunAlias.arguments
|
||||
|
||||
val scope = capturingFunction.getInnerFunction()?.getScope()!!
|
||||
val scope = capturingFunction.getInnerFunction()?.scope!!
|
||||
val freshNames = getFreshNamesInScope(scope, capturedArgs)
|
||||
|
||||
val aliasCallArguments = freshNames.map { it.makeRef() }
|
||||
val alias = JsInvocation(localFunAlias.getQualifier(), aliasCallArguments)
|
||||
val alias = JsInvocation(localFunAlias.qualifier, aliasCallArguments)
|
||||
declareAliasInsideFunction(capturingFunction, capturedName, alias)
|
||||
|
||||
val capturedParameters = freshNames.map {JsParameter(it)}
|
||||
@@ -175,7 +175,7 @@ private fun getFreshNamesInScope(scope: JsScope, suggested: List<JsExpression>):
|
||||
throw AssertionError("Expected suggestion to be JsNameRef")
|
||||
}
|
||||
|
||||
val ident = suggestion.getIdent()
|
||||
val ident = suggestion.ident
|
||||
val name = scope.declareFreshName(ident)
|
||||
freshNames.add(name)
|
||||
}
|
||||
@@ -185,11 +185,11 @@ private fun getFreshNamesInScope(scope: JsScope, suggested: List<JsExpression>):
|
||||
|
||||
private fun JsFunction.addDeclaration(name: JsName, value: JsExpression?) {
|
||||
val declaration = JsAstUtils.newVar(name, value)
|
||||
this.getBody().getStatements().add(0, declaration)
|
||||
this.body.statements.add(0, declaration)
|
||||
}
|
||||
|
||||
private fun HasName.getStaticRef(): JsNode? {
|
||||
return this.getName()?.staticRef
|
||||
return this.name?.staticRef
|
||||
}
|
||||
|
||||
private fun isLocalInlineDeclaration(descriptor: CallableDescriptor): Boolean {
|
||||
|
||||
+22
-22
@@ -43,20 +43,20 @@ import org.jetbrains.kotlin.psi.KtWhileExpressionBase
|
||||
import org.jetbrains.kotlin.resolve.DescriptorUtils.getClassDescriptorForType
|
||||
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
|
||||
|
||||
public fun createWhile(doWhile: Boolean, expression: KtWhileExpressionBase, context: TranslationContext): JsNode {
|
||||
val conditionExpression = expression.getCondition() ?:
|
||||
throw IllegalArgumentException("condition expression should not be null: ${expression.getText()}")
|
||||
fun createWhile(doWhile: Boolean, expression: KtWhileExpressionBase, context: TranslationContext): JsNode {
|
||||
val conditionExpression = expression.condition ?:
|
||||
throw IllegalArgumentException("condition expression should not be null: ${expression.text}")
|
||||
val conditionBlock = JsBlock()
|
||||
var jsCondition = Translation.translateAsExpression(conditionExpression, context, conditionBlock)
|
||||
val isEmptyLoopCondition = isEmptyExpression(jsCondition)
|
||||
val body = expression.getBody()
|
||||
val body = expression.body
|
||||
var bodyStatement =
|
||||
if (body != null)
|
||||
Translation.translateAsStatementAndMergeInBlockIfNeeded(body, context)
|
||||
else
|
||||
JsEmpty
|
||||
|
||||
if (!conditionBlock.isEmpty()) {
|
||||
if (!conditionBlock.isEmpty) {
|
||||
val breakIfConditionIsFalseStatement = JsIf(not(jsCondition), JsBreak())
|
||||
val bodyBlock = convertToBlock(bodyStatement)
|
||||
jsCondition = JsLiteral.TRUE
|
||||
@@ -66,20 +66,20 @@ public fun createWhile(doWhile: Boolean, expression: KtWhileExpressionBase, cont
|
||||
val secondRun = context.declareTemporary(JsLiteral.FALSE)
|
||||
context.addStatementToCurrentBlock(secondRun.assignmentExpression().makeStmt())
|
||||
if (!isEmptyLoopCondition) {
|
||||
conditionBlock.getStatements().add(breakIfConditionIsFalseStatement)
|
||||
conditionBlock.statements.add(breakIfConditionIsFalseStatement)
|
||||
}
|
||||
val ifStatement = JsIf(secondRun.reference(), conditionBlock, assignment(secondRun.reference(), JsLiteral.TRUE).makeStmt())
|
||||
bodyBlock.getStatements().add(0, ifStatement)
|
||||
bodyBlock.statements.add(0, ifStatement)
|
||||
}
|
||||
else {
|
||||
// translate to: while (true) { <expr> if(!tmpExprVar) break; <body> }
|
||||
if (isEmptyLoopCondition) {
|
||||
bodyBlock.getStatements().clear()
|
||||
bodyBlock.statements.clear()
|
||||
context.addStatementsToCurrentBlockFrom(conditionBlock)
|
||||
}
|
||||
else {
|
||||
conditionBlock.getStatements().add(breakIfConditionIsFalseStatement)
|
||||
bodyBlock.getStatements().addAll(0, conditionBlock.getStatements())
|
||||
conditionBlock.statements.add(breakIfConditionIsFalseStatement)
|
||||
bodyBlock.statements.addAll(0, conditionBlock.statements)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,46 +90,46 @@ public fun createWhile(doWhile: Boolean, expression: KtWhileExpressionBase, cont
|
||||
}
|
||||
|
||||
val result = if (doWhile) JsDoWhile() else JsWhile()
|
||||
result.setCondition(jsCondition)
|
||||
result.setBody(bodyStatement)
|
||||
result.condition = jsCondition
|
||||
result.body = bodyStatement
|
||||
return result.source(expression)!!
|
||||
}
|
||||
|
||||
public fun translateForExpression(expression: KtForExpression, context: TranslationContext): JsStatement {
|
||||
fun translateForExpression(expression: KtForExpression, context: TranslationContext): JsStatement {
|
||||
val loopRange = getLoopRange(expression)
|
||||
val rangeType = getTypeForExpression(context.bindingContext(), loopRange)
|
||||
|
||||
fun isForOverRange(): Boolean {
|
||||
//TODO: better check
|
||||
//TODO: long range?
|
||||
return getClassDescriptorForType(rangeType).getName().asString() == "IntRange"
|
||||
return getClassDescriptorForType(rangeType).name.asString() == "IntRange"
|
||||
}
|
||||
|
||||
fun isForOverRangeLiteral(): Boolean =
|
||||
loopRange is KtBinaryExpression && loopRange.getOperationToken() == KtTokens.RANGE && isForOverRange()
|
||||
loopRange is KtBinaryExpression && loopRange.operationToken == KtTokens.RANGE && isForOverRange()
|
||||
|
||||
fun isForOverArray(): Boolean {
|
||||
//TODO: better check
|
||||
//TODO: IMPORTANT!
|
||||
return getClassDescriptorForType(rangeType).getName().asString() == "Array" ||
|
||||
getClassDescriptorForType(rangeType).getName().asString() == "IntArray"
|
||||
return getClassDescriptorForType(rangeType).name.asString() == "Array" ||
|
||||
getClassDescriptorForType(rangeType).name.asString() == "IntArray"
|
||||
}
|
||||
|
||||
val destructuringParameter: KtDestructuringDeclaration? = expression.getDestructuringParameter();
|
||||
val destructuringParameter: KtDestructuringDeclaration? = expression.destructuringParameter;
|
||||
|
||||
fun declareParameter(): JsName {
|
||||
val loopParameter = getLoopParameter(expression)
|
||||
if (loopParameter != null) {
|
||||
return context.getNameForElement(loopParameter)
|
||||
}
|
||||
assert(destructuringParameter != null) { "If loopParameter is null, multi parameter must be not null ${expression.getText()}" }
|
||||
assert(destructuringParameter != null) { "If loopParameter is null, multi parameter must be not null ${expression.text}" }
|
||||
return context.scope().declareTemporary()
|
||||
}
|
||||
|
||||
val parameterName: JsName = declareParameter()
|
||||
|
||||
fun translateBody(itemValue: JsExpression?): JsStatement? {
|
||||
val realBody = expression.getBody()?.let { Translation.translateAsStatementAndMergeInBlockIfNeeded(it, context) }
|
||||
val realBody = expression.body?.let { Translation.translateAsStatementAndMergeInBlockIfNeeded(it, context) }
|
||||
if (itemValue == null && destructuringParameter == null) {
|
||||
return realBody
|
||||
}
|
||||
@@ -143,14 +143,14 @@ public fun translateForExpression(expression: KtForExpression, context: Translat
|
||||
if (realBody == null) return JsBlock(currentVarInit)
|
||||
|
||||
val block = convertToBlock(realBody)
|
||||
block.getStatements().add(0, currentVarInit)
|
||||
block.statements.add(0, currentVarInit)
|
||||
return block
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: implement reverse semantics
|
||||
fun translateForOverLiteralRange(): JsStatement {
|
||||
if (loopRange !is KtBinaryExpression) throw IllegalStateException("expected JetBinaryExpression, but ${loopRange.getText()}")
|
||||
if (loopRange !is KtBinaryExpression) throw IllegalStateException("expected JetBinaryExpression, but ${loopRange.text}")
|
||||
|
||||
val startBlock = JsBlock()
|
||||
val leftExpression = TranslationUtils.translateLeftExpression(context, loopRange, startBlock)
|
||||
|
||||
@@ -24,17 +24,17 @@ import org.jetbrains.kotlin.js.translate.general.AbstractTranslator
|
||||
import org.jetbrains.kotlin.js.translate.general.Translation.translateAsStatementAndMergeInBlockIfNeeded
|
||||
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils.convertToBlock
|
||||
|
||||
public class TryTranslator(
|
||||
class TryTranslator(
|
||||
val expression: KtTryExpression,
|
||||
context: TranslationContext
|
||||
) : AbstractTranslator(context) {
|
||||
public fun translate(): JsTry {
|
||||
val tryBlock = translateAsBlock(expression.getTryBlock())
|
||||
fun translate(): JsTry {
|
||||
val tryBlock = translateAsBlock(expression.tryBlock)
|
||||
|
||||
val catchTranslator = CatchTranslator(expression.getCatchClauses(), context())
|
||||
val catchTranslator = CatchTranslator(expression.catchClauses, context())
|
||||
val catchBlock = catchTranslator.translate()
|
||||
|
||||
val finallyExpression = expression.getFinallyBlock()?.getFinalExpression()
|
||||
val finallyExpression = expression.finallyBlock?.finalExpression
|
||||
val finallyBlock = translateAsBlock(finallyExpression)
|
||||
|
||||
return JsTry(tryBlock, catchBlock, finallyBlock)
|
||||
|
||||
+2
-2
@@ -26,7 +26,7 @@ import org.jetbrains.kotlin.js.translate.utils.JsAstUtils.*
|
||||
import org.jetbrains.kotlin.utils.identity as ID
|
||||
|
||||
// TODO Move to FunctionCallCases
|
||||
public object LongOperationFIF : FunctionIntrinsicFactory {
|
||||
object LongOperationFIF : FunctionIntrinsicFactory {
|
||||
|
||||
val LONG_EQUALS_ANY = pattern("Long.equals")
|
||||
val LONG_BINARY_OPERATION_LONG = pattern("Long.compareTo|rangeTo|plus|minus|times|div|mod|and|or|xor(Long)")
|
||||
@@ -83,7 +83,7 @@ public object LongOperationFIF : FunctionIntrinsicFactory {
|
||||
if (intrinsic != null) BaseBinaryIntrinsic() { left, right -> intrinsic.applyFun(toLeft(left), toRight(right)) } else null
|
||||
|
||||
override fun getIntrinsic(descriptor: FunctionDescriptor): FunctionIntrinsic? {
|
||||
val operationName = descriptor.getName().asString()
|
||||
val operationName = descriptor.name.asString()
|
||||
return when {
|
||||
LONG_EQUALS_ANY.apply(descriptor) || LONG_BINARY_OPERATION_LONG.apply(descriptor) || LONG_BIT_SHIFTS.apply(descriptor) ->
|
||||
longBinaryIntrinsics[operationName]
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ import org.jetbrains.kotlin.js.translate.intrinsic.functions.basic.FunctionIntri
|
||||
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils.*
|
||||
import org.jetbrains.kotlin.utils.identity
|
||||
|
||||
public object NumberAndCharConversionFIF : CompositeFIF() {
|
||||
object NumberAndCharConversionFIF : CompositeFIF() {
|
||||
val USE_AS_IS = Predicates.or(
|
||||
pattern("Int.toInt|toFloat|toDouble"), pattern("Short.toShort|toInt|toFloat|toDouble"),
|
||||
pattern("Byte.toByte|toShort|toInt|toFloat|toDouble"), pattern("Float|Double.toFloat|toDouble"),
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ import org.jetbrains.kotlin.js.translate.context.TranslationContext
|
||||
import org.jetbrains.kotlin.js.translate.intrinsic.functions.basic.FunctionIntrinsic
|
||||
|
||||
|
||||
public object ProgressionCompanionFIF : CompositeFIF() {
|
||||
object ProgressionCompanionFIF : CompositeFIF() {
|
||||
init {
|
||||
val numberProgressionConstructor = CallProgressionConstructorIntrinsic("NumberProgression")
|
||||
for (type in arrayOf(PrimitiveType.BYTE, PrimitiveType.SHORT, PrimitiveType.INT)) {
|
||||
|
||||
+5
-5
@@ -37,20 +37,20 @@ class DefaultClassObjectIntrinsic(val fqName: FqName, val moduleName: String): O
|
||||
}
|
||||
}
|
||||
|
||||
public class ObjectIntrinsics {
|
||||
class ObjectIntrinsics {
|
||||
private val companionObjectMapping = CompanionObjectMapping(JsPlatform.builtIns)
|
||||
|
||||
public fun getIntrinsic(classDescriptor: ClassDescriptor): ObjectIntrinsic {
|
||||
fun getIntrinsic(classDescriptor: ClassDescriptor): ObjectIntrinsic {
|
||||
if (!companionObjectMapping.hasMappingToObject(classDescriptor)) return NO_OBJECT_INTRINSIC
|
||||
|
||||
val containingDeclaration = classDescriptor.getContainingDeclaration()
|
||||
val name = Name.identifier(containingDeclaration.getName().asString() + "CompanionObject")
|
||||
val containingDeclaration = classDescriptor.containingDeclaration
|
||||
val name = Name.identifier(containingDeclaration.name.asString() + "CompanionObject")
|
||||
|
||||
return DefaultClassObjectIntrinsic(FqName("kotlin.js.internal").child(name), LibrarySourcesConfig.STDLIB_JS_MODULE_NAME)
|
||||
}
|
||||
}
|
||||
|
||||
public interface ObjectIntrinsic {
|
||||
interface ObjectIntrinsic {
|
||||
fun apply(context: TranslationContext): JsExpression
|
||||
fun exists(): Boolean = true
|
||||
}
|
||||
|
||||
+2
-2
@@ -64,9 +64,9 @@ object CompareToBOIF : BinaryOperationIntrinsicFactory {
|
||||
}
|
||||
}
|
||||
|
||||
override public fun getSupportTokens() = OperatorConventions.COMPARISON_OPERATIONS
|
||||
override fun getSupportTokens() = OperatorConventions.COMPARISON_OPERATIONS
|
||||
|
||||
override public fun getIntrinsic(descriptor: FunctionDescriptor): BinaryOperationIntrinsic? {
|
||||
override fun getIntrinsic(descriptor: FunctionDescriptor): BinaryOperationIntrinsic? {
|
||||
if (descriptor.isDynamic()) return CompareToIntrinsic
|
||||
|
||||
if (!JsDescriptorUtils.isBuiltin(descriptor)) return null
|
||||
|
||||
+7
-7
@@ -61,8 +61,8 @@ object EqualsBOIF : BinaryOperationIntrinsicFactory {
|
||||
val resolvedCall = expression.getResolvedCall(context.bindingContext())
|
||||
val appliedToDynamic =
|
||||
resolvedCall != null &&
|
||||
with(resolvedCall.getDispatchReceiver()) {
|
||||
if (this != null) getType().isDynamic() else false
|
||||
with(resolvedCall.dispatchReceiver) {
|
||||
if (this != null) type.isDynamic() else false
|
||||
}
|
||||
|
||||
if (appliedToDynamic) {
|
||||
@@ -74,8 +74,8 @@ object EqualsBOIF : BinaryOperationIntrinsicFactory {
|
||||
}
|
||||
|
||||
private fun canUseSimpleEquals(expression: KtBinaryExpression, context: TranslationContext): Boolean {
|
||||
val left = expression.getLeft()
|
||||
assert(left != null) { "No left-hand side: " + expression.getText() }
|
||||
val left = expression.left
|
||||
assert(left != null) { "No left-hand side: " + expression.text }
|
||||
val typeName = JsDescriptorUtils.getNameIfStandardType(left!!, context)
|
||||
return typeName != null && NamePredicate.PRIMITIVE_NUMBERS_MAPPED_TO_PRIMITIVE_JS.apply(typeName)
|
||||
}
|
||||
@@ -88,13 +88,13 @@ object EqualsBOIF : BinaryOperationIntrinsicFactory {
|
||||
}
|
||||
}
|
||||
|
||||
override public fun getSupportTokens() = OperatorConventions.EQUALS_OPERATIONS
|
||||
override fun getSupportTokens() = OperatorConventions.EQUALS_OPERATIONS
|
||||
|
||||
override public fun getIntrinsic(descriptor: FunctionDescriptor): BinaryOperationIntrinsic? =
|
||||
override fun getIntrinsic(descriptor: FunctionDescriptor): BinaryOperationIntrinsic? =
|
||||
when {
|
||||
(LONG_EQUALS_ANY.apply(descriptor)) -> LONG_EQUALS_ANY_INTRINSIC
|
||||
|
||||
DescriptorUtils.isEnumClass(descriptor.getContainingDeclaration()) -> EnumEqualsIntrinsic
|
||||
DescriptorUtils.isEnumClass(descriptor.containingDeclaration) -> EnumEqualsIntrinsic
|
||||
|
||||
JsDescriptorUtils.isBuiltin(descriptor) ||
|
||||
TopLevelFIF.EQUALS_IN_ANY.apply(descriptor) -> EqualsIntrinsic
|
||||
|
||||
+3
-3
@@ -34,7 +34,7 @@ import org.jetbrains.kotlin.psi.KtBinaryExpression
|
||||
import org.jetbrains.kotlin.types.expressions.OperatorConventions
|
||||
import org.jetbrains.kotlin.utils.identity as ID
|
||||
|
||||
public object LongCompareToBOIF : BinaryOperationIntrinsicFactory {
|
||||
object LongCompareToBOIF : BinaryOperationIntrinsicFactory {
|
||||
|
||||
val FLOATING_POINT_COMPARE_TO_LONG_PATTERN = pattern("Double|Float.compareTo(Long)")
|
||||
val LONG_COMPARE_TO_FLOATING_POINT_PATTERN = pattern("Long.compareTo(Float|Double)")
|
||||
@@ -72,9 +72,9 @@ public object LongCompareToBOIF : BinaryOperationIntrinsicFactory {
|
||||
private val LONG_COMPARE_TO_CHAR = CompareToBinaryIntrinsic( ID(), { longFromInt(charToInt(it)) })
|
||||
private val LONG_COMPARE_TO_LONG = CompareToBinaryIntrinsic( ID(), ID() )
|
||||
|
||||
override public fun getSupportTokens() = OperatorConventions.COMPARISON_OPERATIONS
|
||||
override fun getSupportTokens() = OperatorConventions.COMPARISON_OPERATIONS
|
||||
|
||||
override public fun getIntrinsic(descriptor: FunctionDescriptor): BinaryOperationIntrinsic? {
|
||||
override fun getIntrinsic(descriptor: FunctionDescriptor): BinaryOperationIntrinsic? {
|
||||
if (JsDescriptorUtils.isBuiltin(descriptor)) {
|
||||
return when {
|
||||
FLOATING_POINT_COMPARE_TO_LONG_PATTERN.apply(descriptor) -> FLOATING_POINT_COMPARE_TO_LONG
|
||||
|
||||
+7
-7
@@ -26,20 +26,20 @@ import gnu.trove.THashMap
|
||||
import com.google.dart.compiler.backend.js.ast.JsExpression
|
||||
import com.google.common.collect.ImmutableSet
|
||||
|
||||
public interface BinaryOperationIntrinsic {
|
||||
interface BinaryOperationIntrinsic {
|
||||
|
||||
fun apply(expression: KtBinaryExpression, left: JsExpression, right: JsExpression, context: TranslationContext): JsExpression
|
||||
|
||||
fun exists(): Boolean
|
||||
}
|
||||
|
||||
public class BinaryOperationIntrinsics {
|
||||
class BinaryOperationIntrinsics {
|
||||
|
||||
private val intrinsicCache = THashMap<Pair<KtToken, FunctionDescriptor>, BinaryOperationIntrinsic>()
|
||||
|
||||
private val factories = listOf(LongCompareToBOIF, EqualsBOIF, CompareToBOIF)
|
||||
|
||||
public fun getIntrinsic(expression: KtBinaryExpression, context: TranslationContext): BinaryOperationIntrinsic {
|
||||
fun getIntrinsic(expression: KtBinaryExpression, context: TranslationContext): BinaryOperationIntrinsic {
|
||||
val token = getOperationToken(expression)
|
||||
val descriptor = getCallableDescriptorForOperationExpression(context.bindingContext(), expression)
|
||||
if (descriptor == null || descriptor !is FunctionDescriptor) {
|
||||
@@ -73,16 +73,16 @@ public class BinaryOperationIntrinsics {
|
||||
|
||||
interface BinaryOperationIntrinsicFactory {
|
||||
|
||||
public fun getSupportTokens(): ImmutableSet<out KtToken>
|
||||
fun getSupportTokens(): ImmutableSet<out KtToken>
|
||||
|
||||
public fun getIntrinsic(descriptor: FunctionDescriptor): BinaryOperationIntrinsic?
|
||||
fun getIntrinsic(descriptor: FunctionDescriptor): BinaryOperationIntrinsic?
|
||||
}
|
||||
|
||||
abstract class AbstractBinaryOperationIntrinsic : BinaryOperationIntrinsic {
|
||||
|
||||
public override abstract fun apply(expression: KtBinaryExpression, left: JsExpression, right: JsExpression, context: TranslationContext): JsExpression
|
||||
override abstract fun apply(expression: KtBinaryExpression, left: JsExpression, right: JsExpression, context: TranslationContext): JsExpression
|
||||
|
||||
public override fun exists(): Boolean = true
|
||||
override fun exists(): Boolean = true
|
||||
}
|
||||
|
||||
object NO_INTRINSIC : AbstractBinaryOperationIntrinsic() {
|
||||
|
||||
+20
-22
@@ -37,19 +37,19 @@ import org.jetbrains.kotlin.types.KotlinType
|
||||
import java.util.ArrayList
|
||||
import java.util.Collections
|
||||
|
||||
public class CallArgumentTranslator private constructor(
|
||||
class CallArgumentTranslator private constructor(
|
||||
private val resolvedCall: ResolvedCall<*>,
|
||||
private val receiver: JsExpression?,
|
||||
context: TranslationContext
|
||||
) : AbstractTranslator(context) {
|
||||
|
||||
public data class ArgumentsInfo(
|
||||
public val valueArguments: List<JsExpression>,
|
||||
public val hasSpreadOperator: Boolean,
|
||||
public val cachedReceiver: TemporaryConstVariable?,
|
||||
public val reifiedArguments: List<JsExpression> = listOf()
|
||||
data class ArgumentsInfo(
|
||||
val valueArguments: List<JsExpression>,
|
||||
val hasSpreadOperator: Boolean,
|
||||
val cachedReceiver: TemporaryConstVariable?,
|
||||
val reifiedArguments: List<JsExpression> = listOf()
|
||||
) {
|
||||
public val translateArguments: List<JsExpression>
|
||||
val translateArguments: List<JsExpression>
|
||||
get() = reifiedArguments + valueArguments
|
||||
}
|
||||
|
||||
@@ -58,13 +58,13 @@ public class CallArgumentTranslator private constructor(
|
||||
HAS_NOT_EMPTY_EXPRESSION_ARGUMENT
|
||||
}
|
||||
|
||||
private val isNativeFunctionCall = AnnotationsUtils.isNativeObject(resolvedCall.getCandidateDescriptor())
|
||||
private val isNativeFunctionCall = AnnotationsUtils.isNativeObject(resolvedCall.candidateDescriptor)
|
||||
|
||||
private fun removeLastUndefinedArguments(result: MutableList<JsExpression>) {
|
||||
var i = result.size - 1
|
||||
|
||||
while (i >= 0) {
|
||||
if (result.get(i) != context().namer().getUndefinedExpression()) {
|
||||
if (result.get(i) != context().namer().undefinedExpression) {
|
||||
break
|
||||
}
|
||||
i--
|
||||
@@ -74,7 +74,7 @@ public class CallArgumentTranslator private constructor(
|
||||
}
|
||||
|
||||
private fun translate(): ArgumentsInfo {
|
||||
val valueParameters = resolvedCall.getResultingDescriptor().getValueParameters()
|
||||
val valueParameters = resolvedCall.resultingDescriptor.valueParameters
|
||||
if (valueParameters.isEmpty()) {
|
||||
return ArgumentsInfo(listOf<JsExpression>(), false, null)
|
||||
}
|
||||
@@ -82,9 +82,9 @@ public class CallArgumentTranslator private constructor(
|
||||
var cachedReceiver: TemporaryConstVariable? = null
|
||||
|
||||
var result: MutableList<JsExpression> = ArrayList(valueParameters.size)
|
||||
val valueArgumentsByIndex = resolvedCall.getValueArgumentsByIndex()
|
||||
val valueArgumentsByIndex = resolvedCall.valueArgumentsByIndex
|
||||
if (valueArgumentsByIndex == null) {
|
||||
throw IllegalStateException("Failed to arrange value arguments by index: " + resolvedCall.getResultingDescriptor())
|
||||
throw IllegalStateException("Failed to arrange value arguments by index: " + resolvedCall.resultingDescriptor)
|
||||
}
|
||||
var argsBeforeVararg: List<JsExpression>? = null
|
||||
var argumentsShouldBeExtractedToTmpVars = false
|
||||
@@ -169,21 +169,19 @@ public class CallArgumentTranslator private constructor(
|
||||
|
||||
companion object {
|
||||
|
||||
@JvmStatic
|
||||
public fun translate(resolvedCall: ResolvedCall<*>, receiver: JsExpression?, context: TranslationContext): ArgumentsInfo {
|
||||
@JvmStatic fun translate(resolvedCall: ResolvedCall<*>, receiver: JsExpression?, context: TranslationContext): ArgumentsInfo {
|
||||
return translate(resolvedCall, receiver, context, context.dynamicContext().jsBlock())
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
public fun translate(resolvedCall: ResolvedCall<*>, receiver: JsExpression?, context: TranslationContext, block: JsBlock): ArgumentsInfo {
|
||||
@JvmStatic fun translate(resolvedCall: ResolvedCall<*>, receiver: JsExpression?, context: TranslationContext, block: JsBlock): ArgumentsInfo {
|
||||
val innerContext = context.innerBlock(block)
|
||||
val argumentTranslator = CallArgumentTranslator(resolvedCall, receiver, innerContext)
|
||||
val result = argumentTranslator.translate()
|
||||
context.moveVarsFrom(innerContext)
|
||||
val callDescriptor = resolvedCall.getCandidateDescriptor()
|
||||
val callDescriptor = resolvedCall.candidateDescriptor
|
||||
|
||||
if (CallExpressionTranslator.shouldBeInlined(callDescriptor)) {
|
||||
val typeArgs = resolvedCall.getTypeArguments()
|
||||
val typeArgs = resolvedCall.typeArguments
|
||||
return typeArgs.addReifiedTypeArgsTo(result, context)
|
||||
}
|
||||
|
||||
@@ -191,10 +189,10 @@ public class CallArgumentTranslator private constructor(
|
||||
}
|
||||
|
||||
private fun translateSingleArgument(actualArgument: ResolvedValueArgument, result: MutableList<JsExpression>, context: TranslationContext): ArgumentsKind {
|
||||
val valueArguments = actualArgument.getArguments()
|
||||
val valueArguments = actualArgument.arguments
|
||||
|
||||
if (actualArgument is DefaultValueArgument) {
|
||||
result.add(context.namer().getUndefinedExpression())
|
||||
result.add(context.namer().undefinedExpression)
|
||||
return ArgumentsKind.HAS_NOT_EMPTY_EXPRESSION_ARGUMENT
|
||||
}
|
||||
|
||||
@@ -344,8 +342,8 @@ private fun Map<TypeParameterDescriptor, KotlinType>.addReifiedTypeArgsTo(
|
||||
val reifiedTypeArguments = SmartList<JsExpression>()
|
||||
val patternTranslator = PatternTranslator.newInstance(context)
|
||||
|
||||
for (param in keys.sortedBy { it.getIndex() }) {
|
||||
if (!param.isReified()) continue
|
||||
for (param in keys.sortedBy { it.index }) {
|
||||
if (!param.isReified) continue
|
||||
|
||||
val argumentType = get(param)
|
||||
if (argumentType == null) continue
|
||||
|
||||
+11
-11
@@ -32,20 +32,20 @@ import java.util.ArrayList
|
||||
object CallableReferenceTranslator {
|
||||
|
||||
fun translate(expression: KtCallableReferenceExpression, context: TranslationContext): JsExpression {
|
||||
val descriptor = BindingUtils.getDescriptorForReferenceExpression(context.bindingContext(), expression.getCallableReference())
|
||||
val descriptor = BindingUtils.getDescriptorForReferenceExpression(context.bindingContext(), expression.callableReference)
|
||||
return when (descriptor) {
|
||||
is PropertyDescriptor ->
|
||||
translateForProperty(descriptor, context, expression)
|
||||
is FunctionDescriptor ->
|
||||
translateForFunction(descriptor, context, expression)
|
||||
else ->
|
||||
throw IllegalArgumentException("Expected property or function: ${descriptor}, expression=${expression.getText()}")
|
||||
throw IllegalArgumentException("Expected property or function: ${descriptor}, expression=${expression.text}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun reportNotSupported(context: TranslationContext, expression: KtCallableReferenceExpression): JsExpression {
|
||||
context.bindingTrace().report(ErrorsJs.REFERENCE_TO_BUILTIN_MEMBERS_NOT_SUPPORTED.on(expression, expression))
|
||||
return context.getEmptyExpression()
|
||||
return context.emptyExpression
|
||||
}
|
||||
|
||||
private fun translateForFunction(descriptor: FunctionDescriptor, context: TranslationContext, expression: KtCallableReferenceExpression): JsExpression {
|
||||
@@ -84,7 +84,7 @@ object CallableReferenceTranslator {
|
||||
|
||||
private fun isMember(descriptor: CallableDescriptor): Boolean = JsDescriptorUtils.getContainingDeclaration(descriptor) is ClassDescriptor
|
||||
|
||||
private fun isVar(descriptor: PropertyDescriptor): JsExpression = if (descriptor.isVar()) JsLiteral.TRUE else JsLiteral.FALSE
|
||||
private fun isVar(descriptor: PropertyDescriptor): JsExpression = if (descriptor.isVar) JsLiteral.TRUE else JsLiteral.FALSE
|
||||
|
||||
private fun translateForTopLevelProperty(descriptor: PropertyDescriptor, context: TranslationContext): JsExpression {
|
||||
val packageDescriptor = JsDescriptorUtils.getContainingDeclaration(descriptor)
|
||||
@@ -104,14 +104,14 @@ object CallableReferenceTranslator {
|
||||
}
|
||||
|
||||
private fun translateForExtensionProperty(descriptor: PropertyDescriptor, context: TranslationContext): JsExpression {
|
||||
val jsGetterNameRef = context.getQualifiedReference(descriptor.getGetter()!!)
|
||||
val propertyName = descriptor.getName()
|
||||
val jsGetterNameRef = context.getQualifiedReference(descriptor.getter!!)
|
||||
val propertyName = descriptor.name
|
||||
val jsPropertyNameAsString = context.program().getStringLiteral(propertyName.asString())
|
||||
val argumentList = ArrayList<JsExpression>(3)
|
||||
argumentList.add(jsPropertyNameAsString)
|
||||
argumentList.add(jsGetterNameRef)
|
||||
if (descriptor.isVar()) {
|
||||
val jsSetterNameRef = context.getQualifiedReference(descriptor.getSetter()!!)
|
||||
if (descriptor.isVar) {
|
||||
val jsSetterNameRef = context.getQualifiedReference(descriptor.setter!!)
|
||||
argumentList.add(jsSetterNameRef)
|
||||
}
|
||||
if (AnnotationsUtils.isNativeObject(descriptor))
|
||||
@@ -126,16 +126,16 @@ object CallableReferenceTranslator {
|
||||
}
|
||||
|
||||
private fun translateForExtensionFunction(descriptor: FunctionDescriptor, context: TranslationContext): JsExpression {
|
||||
val receiverParameterDescriptor = descriptor.getExtensionReceiverParameter()
|
||||
val receiverParameterDescriptor = descriptor.extensionReceiverParameter
|
||||
assert(receiverParameterDescriptor != null) { "receiverParameter for extension should not be null" }
|
||||
|
||||
val jsFunctionRef = ReferenceTranslator.translateAsFQReference(descriptor, context)
|
||||
if (descriptor.getVisibility() == Visibilities.LOCAL) {
|
||||
if (descriptor.visibility == Visibilities.LOCAL) {
|
||||
return JsInvocation(context.namer().callableRefForLocalExtensionFunctionReference(), jsFunctionRef)
|
||||
}
|
||||
|
||||
else if (AnnotationsUtils.isNativeObject(descriptor)) {
|
||||
val jetType = receiverParameterDescriptor!!.getType()
|
||||
val jetType = receiverParameterDescriptor!!.type
|
||||
val receiverClassDescriptor = DescriptorUtils.getClassDescriptorForType(jetType)
|
||||
return translateAsMemberFunctionReference(descriptor, receiverClassDescriptor, context)
|
||||
}
|
||||
|
||||
@@ -19,18 +19,18 @@ package org.jetbrains.kotlin.js.translate.utils.jsAstUtils
|
||||
import com.google.dart.compiler.backend.js.ast.*
|
||||
import org.jetbrains.kotlin.js.translate.context.Namer
|
||||
|
||||
public fun JsFunction.addStatement(stmt: JsStatement) {
|
||||
getBody().getStatements().add(stmt)
|
||||
fun JsFunction.addStatement(stmt: JsStatement) {
|
||||
body.statements.add(stmt)
|
||||
}
|
||||
|
||||
public fun JsFunction.addParameter(identifier: String, index: Int? = null): JsParameter {
|
||||
val name = getScope().declareFreshName(identifier)
|
||||
fun JsFunction.addParameter(identifier: String, index: Int? = null): JsParameter {
|
||||
val name = scope.declareFreshName(identifier)
|
||||
val parameter = JsParameter(name)
|
||||
|
||||
if (index == null) {
|
||||
getParameters().add(parameter)
|
||||
parameters.add(parameter)
|
||||
} else {
|
||||
getParameters().add(index, parameter)
|
||||
parameters.add(index, parameter)
|
||||
}
|
||||
|
||||
return parameter
|
||||
@@ -39,9 +39,9 @@ public fun JsFunction.addParameter(identifier: String, index: Int? = null): JsPa
|
||||
/**
|
||||
* Tests, if any node containing in receiver's AST matches, [predicate].
|
||||
*/
|
||||
public fun JsNode.any(predicate: (JsNode) -> Boolean): Boolean {
|
||||
fun JsNode.any(predicate: (JsNode) -> Boolean): Boolean {
|
||||
val visitor = object : RecursiveJsVisitor() {
|
||||
public var matched: Boolean = false
|
||||
var matched: Boolean = false
|
||||
|
||||
override fun visitElement(node: JsNode) {
|
||||
matched = matched || predicate(node)
|
||||
@@ -62,7 +62,7 @@ fun JsExpression.toInvocationWith(thisExpr: JsExpression): JsExpression {
|
||||
|
||||
when (this) {
|
||||
is JsNew -> {
|
||||
qualifier = Namer.getFunctionCallRef(getConstructorExpression())
|
||||
qualifier = Namer.getFunctionCallRef(constructorExpression)
|
||||
arguments = getArguments()
|
||||
// `new A(a, b, c)` -> `A.call($this, a, b, c)`
|
||||
return JsInvocation(qualifier, listOf(thisExpr) + arguments)
|
||||
@@ -77,26 +77,26 @@ fun JsExpression.toInvocationWith(thisExpr: JsExpression): JsExpression {
|
||||
}
|
||||
}
|
||||
|
||||
public var JsWhile.test: JsExpression
|
||||
get() = getCondition()
|
||||
set(value) = setCondition(value)
|
||||
var JsWhile.test: JsExpression
|
||||
get() = condition
|
||||
set(value) = condition = value
|
||||
|
||||
public var JsArrayAccess.index: JsExpression
|
||||
get() = getIndexExpression()
|
||||
set(value) = setIndexExpression(value)
|
||||
var JsArrayAccess.index: JsExpression
|
||||
get() = indexExpression
|
||||
set(value) = indexExpression = value
|
||||
|
||||
public var JsArrayAccess.array: JsExpression
|
||||
get() = getArrayExpression()
|
||||
set(value) = setArrayExpression(value)
|
||||
var JsArrayAccess.array: JsExpression
|
||||
get() = arrayExpression
|
||||
set(value) = arrayExpression = value
|
||||
|
||||
public var JsConditional.test: JsExpression
|
||||
get() = getTestExpression()
|
||||
set(value) = setTestExpression(value)
|
||||
var JsConditional.test: JsExpression
|
||||
get() = testExpression
|
||||
set(value) = testExpression = value
|
||||
|
||||
public var JsConditional.then: JsExpression
|
||||
get() = getThenExpression()
|
||||
set(value) = setThenExpression(value)
|
||||
var JsConditional.then: JsExpression
|
||||
get() = thenExpression
|
||||
set(value) = thenExpression = value
|
||||
|
||||
public var JsConditional.otherwise: JsExpression
|
||||
get() = getElseExpression()
|
||||
set(value) = setElseExpression(value)
|
||||
var JsConditional.otherwise: JsExpression
|
||||
get() = elseExpression
|
||||
set(value) = elseExpression = value
|
||||
|
||||
@@ -22,12 +22,12 @@ import com.google.dart.compiler.backend.js.ast.metadata.typeCheck
|
||||
import org.jetbrains.kotlin.js.translate.context.TranslationContext
|
||||
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils.*
|
||||
|
||||
public fun expandIsCalls(node: JsNode, context: TranslationContext) {
|
||||
fun expandIsCalls(node: JsNode, context: TranslationContext) {
|
||||
val visitor = object : JsVisitorWithContextImpl() {
|
||||
override fun visit(x: JsInvocation, ctx: JsContext<JsNode>): Boolean {
|
||||
val callee = x.getQualifier() as? JsInvocation
|
||||
val instance = x.getArguments().firstOrNull()
|
||||
val type = callee?.getArguments()?.firstOrNull()
|
||||
val callee = x.qualifier as? JsInvocation
|
||||
val instance = x.arguments.firstOrNull()
|
||||
val type = callee?.arguments?.firstOrNull()
|
||||
|
||||
val replacement = when (callee?.typeCheck) {
|
||||
TypeCheck.TYPEOF -> typeOfIs(instance!!, type as JsStringLiteral)
|
||||
|
||||
@@ -71,7 +71,7 @@ fun setInlineCallMetadata(
|
||||
|
||||
fun TranslationContext.aliasedName(descriptor: CallableDescriptor): JsName {
|
||||
val alias = getAliasForDescriptor(descriptor)
|
||||
val aliasName = (alias as? JsNameRef)?.getName()
|
||||
val aliasName = (alias as? JsNameRef)?.name
|
||||
|
||||
return aliasName ?: getNameForDescriptor(descriptor)
|
||||
}
|
||||
@@ -79,13 +79,13 @@ fun TranslationContext.aliasedName(descriptor: CallableDescriptor): JsName {
|
||||
val JsExpression?.name: JsName?
|
||||
get() = when (this) {
|
||||
is JsInvocation -> {
|
||||
val qualifier = this.getQualifier()
|
||||
val qualifier = this.qualifier
|
||||
|
||||
when {
|
||||
isCallInvocation(this) -> (qualifier as JsNameRef).getQualifier().name
|
||||
isCallInvocation(this) -> (qualifier as JsNameRef).qualifier.name
|
||||
else -> qualifier.name
|
||||
}
|
||||
}
|
||||
is JsNameRef -> this.getName()
|
||||
is JsNameRef -> this.name
|
||||
else -> null
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ import org.jetbrains.kotlin.js.translate.context.TranslationContext
|
||||
import org.jetbrains.kotlin.js.translate.utils.TranslationUtils.simpleReturnFunction
|
||||
import org.jetbrains.kotlin.resolve.DescriptorUtils
|
||||
|
||||
public fun generateDelegateCall(
|
||||
fun generateDelegateCall(
|
||||
fromDescriptor: FunctionDescriptor,
|
||||
toDescriptor: FunctionDescriptor,
|
||||
thisObject: JsExpression,
|
||||
@@ -44,14 +44,14 @@ public fun generateDelegateCall(
|
||||
args.add(JsNameRef(extensionFunctionReceiverName))
|
||||
}
|
||||
|
||||
for (param in fromDescriptor.getValueParameters()) {
|
||||
val paramName = param.getName().asString()
|
||||
for (param in fromDescriptor.valueParameters) {
|
||||
val paramName = param.name.asString()
|
||||
val jsParamName = functionScope.declareName(paramName)
|
||||
parameters.add(JsParameter(jsParamName))
|
||||
args.add(JsNameRef(jsParamName))
|
||||
}
|
||||
|
||||
val functionObject = simpleReturnFunction(context.getScopeForDescriptor(fromDescriptor), JsInvocation(overriddenMemberFunctionRef, args))
|
||||
functionObject.getParameters().addAll(parameters)
|
||||
functionObject.parameters.addAll(parameters)
|
||||
return JsPropertyInitializer(delegateMemberFunctionName.makeRef(), functionObject)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user