js: cleanup 'public', property access syntax

This commit is contained in:
Dmitry Jemerov
2016-01-07 18:15:19 +01:00
parent 33ef7ad024
commit d6a11b839b
84 changed files with 643 additions and 654 deletions
@@ -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
}
}
@@ -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)
}
}
@@ -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"
}
}
@@ -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
@@ -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()
@@ -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))
}
@@ -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))
}
@@ -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
}
@@ -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"
}
}
@@ -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)
@@ -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 {
@@ -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)
@@ -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]
@@ -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"),
@@ -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)) {
@@ -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
}
@@ -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
@@ -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
@@ -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
@@ -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() {
@@ -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
@@ -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)
}