KT-3008 Change the way how modules are referenced in JS

This commit is contained in:
Alexey Andreev
2016-04-11 16:20:25 +03:00
parent 2909533522
commit 95b78e18df
24 changed files with 169 additions and 136 deletions
@@ -603,7 +603,7 @@ public final class DebugJsProtoBuf {
/** /**
* <code>repeated string importedModules = 3;</code> * <code>repeated string importedModules = 3;</code>
*/ */
com.google.protobuf.ByteString org.jetbrains.kotlin.protobuf.ByteString
getImportedModulesBytes(int index); getImportedModulesBytes(int index);
} }
/** /**
@@ -678,7 +678,7 @@ public final class DebugJsProtoBuf {
} }
case 26: { case 26: {
if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
importedModules_ = new com.google.protobuf.LazyStringArrayList(); importedModules_ = new org.jetbrains.kotlin.protobuf.LazyStringArrayList();
mutable_bitField0_ |= 0x00000004; mutable_bitField0_ |= 0x00000004;
} }
importedModules_.add(input.readBytes()); importedModules_.add(input.readBytes());
@@ -696,7 +696,7 @@ public final class DebugJsProtoBuf {
entry_ = java.util.Collections.unmodifiableList(entry_); entry_ = java.util.Collections.unmodifiableList(entry_);
} }
if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
importedModules_ = new com.google.protobuf.UnmodifiableLazyStringList(importedModules_); importedModules_ = new org.jetbrains.kotlin.protobuf.UnmodifiableLazyStringList(importedModules_);
} }
this.unknownFields = unknownFields.build(); this.unknownFields = unknownFields.build();
makeExtensionsImmutable(); makeExtensionsImmutable();
@@ -733,7 +733,7 @@ public final class DebugJsProtoBuf {
* Protobuf enum {@code org.jetbrains.kotlin.serialization.js.Library.Kind} * Protobuf enum {@code org.jetbrains.kotlin.serialization.js.Library.Kind}
*/ */
public enum Kind public enum Kind
implements com.google.protobuf.ProtocolMessageEnum { implements org.jetbrains.kotlin.protobuf.ProtocolMessageEnum {
/** /**
* <code>PLAIN = 1;</code> * <code>PLAIN = 1;</code>
*/ */
@@ -773,27 +773,27 @@ public final class DebugJsProtoBuf {
} }
} }
public static com.google.protobuf.Internal.EnumLiteMap<Kind> public static org.jetbrains.kotlin.protobuf.Internal.EnumLiteMap<Kind>
internalGetValueMap() { internalGetValueMap() {
return internalValueMap; return internalValueMap;
} }
private static com.google.protobuf.Internal.EnumLiteMap<Kind> private static org.jetbrains.kotlin.protobuf.Internal.EnumLiteMap<Kind>
internalValueMap = internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<Kind>() { new org.jetbrains.kotlin.protobuf.Internal.EnumLiteMap<Kind>() {
public Kind findValueByNumber(int number) { public Kind findValueByNumber(int number) {
return Kind.valueOf(number); return Kind.valueOf(number);
} }
}; };
public final com.google.protobuf.Descriptors.EnumValueDescriptor public final org.jetbrains.kotlin.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() { getValueDescriptor() {
return getDescriptor().getValues().get(index); return getDescriptor().getValues().get(index);
} }
public final com.google.protobuf.Descriptors.EnumDescriptor public final org.jetbrains.kotlin.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() { getDescriptorForType() {
return getDescriptor(); return getDescriptor();
} }
public static final com.google.protobuf.Descriptors.EnumDescriptor public static final org.jetbrains.kotlin.protobuf.Descriptors.EnumDescriptor
getDescriptor() { getDescriptor() {
return org.jetbrains.kotlin.serialization.js.DebugJsProtoBuf.Library.getDescriptor().getEnumTypes().get(0); return org.jetbrains.kotlin.serialization.js.DebugJsProtoBuf.Library.getDescriptor().getEnumTypes().get(0);
} }
@@ -801,7 +801,7 @@ public final class DebugJsProtoBuf {
private static final Kind[] VALUES = values(); private static final Kind[] VALUES = values();
public static Kind valueOf( public static Kind valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) { org.jetbrains.kotlin.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) { if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException( throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type."); "EnumValueDescriptor is not for this type.");
@@ -1446,7 +1446,7 @@ public final class DebugJsProtoBuf {
// repeated string importedModules = 3; // repeated string importedModules = 3;
public static final int IMPORTEDMODULES_FIELD_NUMBER = 3; public static final int IMPORTEDMODULES_FIELD_NUMBER = 3;
private com.google.protobuf.LazyStringList importedModules_; private org.jetbrains.kotlin.protobuf.LazyStringList importedModules_;
/** /**
* <code>repeated string importedModules = 3;</code> * <code>repeated string importedModules = 3;</code>
*/ */
@@ -1469,7 +1469,7 @@ public final class DebugJsProtoBuf {
/** /**
* <code>repeated string importedModules = 3;</code> * <code>repeated string importedModules = 3;</code>
*/ */
public com.google.protobuf.ByteString public org.jetbrains.kotlin.protobuf.ByteString
getImportedModulesBytes(int index) { getImportedModulesBytes(int index) {
return importedModules_.getByteString(index); return importedModules_.getByteString(index);
} }
@@ -1477,7 +1477,7 @@ public final class DebugJsProtoBuf {
private void initFields() { private void initFields() {
entry_ = java.util.Collections.emptyList(); entry_ = java.util.Collections.emptyList();
kind_ = org.jetbrains.kotlin.serialization.js.DebugJsProtoBuf.Library.Kind.PLAIN; kind_ = org.jetbrains.kotlin.serialization.js.DebugJsProtoBuf.Library.Kind.PLAIN;
importedModules_ = com.google.protobuf.LazyStringArrayList.EMPTY; importedModules_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
} }
private byte memoizedIsInitialized = -1; private byte memoizedIsInitialized = -1;
public final boolean isInitialized() { public final boolean isInitialized() {
@@ -1520,13 +1520,13 @@ public final class DebugJsProtoBuf {
.computeMessageSize(1, entry_.get(i)); .computeMessageSize(1, entry_.get(i));
} }
if (((bitField0_ & 0x00000001) == 0x00000001)) { if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeEnumSize(2, kind_.getNumber()); .computeEnumSize(2, kind_.getNumber());
} }
{ {
int dataSize = 0; int dataSize = 0;
for (int i = 0; i < importedModules_.size(); i++) { for (int i = 0; i < importedModules_.size(); i++) {
dataSize += com.google.protobuf.CodedOutputStream dataSize += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeBytesSizeNoTag(importedModules_.getByteString(i)); .computeBytesSizeNoTag(importedModules_.getByteString(i));
} }
size += dataSize; size += dataSize;
@@ -1657,7 +1657,7 @@ public final class DebugJsProtoBuf {
} }
kind_ = org.jetbrains.kotlin.serialization.js.DebugJsProtoBuf.Library.Kind.PLAIN; kind_ = org.jetbrains.kotlin.serialization.js.DebugJsProtoBuf.Library.Kind.PLAIN;
bitField0_ = (bitField0_ & ~0x00000002); bitField0_ = (bitField0_ & ~0x00000002);
importedModules_ = com.google.protobuf.LazyStringArrayList.EMPTY; importedModules_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000004); bitField0_ = (bitField0_ & ~0x00000004);
return this; return this;
} }
@@ -1701,7 +1701,7 @@ public final class DebugJsProtoBuf {
} }
result.kind_ = kind_; result.kind_ = kind_;
if (((bitField0_ & 0x00000004) == 0x00000004)) { if (((bitField0_ & 0x00000004) == 0x00000004)) {
importedModules_ = new com.google.protobuf.UnmodifiableLazyStringList( importedModules_ = new org.jetbrains.kotlin.protobuf.UnmodifiableLazyStringList(
importedModules_); importedModules_);
bitField0_ = (bitField0_ & ~0x00000004); bitField0_ = (bitField0_ & ~0x00000004);
} }
@@ -2071,10 +2071,10 @@ public final class DebugJsProtoBuf {
} }
// repeated string importedModules = 3; // repeated string importedModules = 3;
private com.google.protobuf.LazyStringList importedModules_ = com.google.protobuf.LazyStringArrayList.EMPTY; private org.jetbrains.kotlin.protobuf.LazyStringList importedModules_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
private void ensureImportedModulesIsMutable() { private void ensureImportedModulesIsMutable() {
if (!((bitField0_ & 0x00000004) == 0x00000004)) { if (!((bitField0_ & 0x00000004) == 0x00000004)) {
importedModules_ = new com.google.protobuf.LazyStringArrayList(importedModules_); importedModules_ = new org.jetbrains.kotlin.protobuf.LazyStringArrayList(importedModules_);
bitField0_ |= 0x00000004; bitField0_ |= 0x00000004;
} }
} }
@@ -2100,7 +2100,7 @@ public final class DebugJsProtoBuf {
/** /**
* <code>repeated string importedModules = 3;</code> * <code>repeated string importedModules = 3;</code>
*/ */
public com.google.protobuf.ByteString public org.jetbrains.kotlin.protobuf.ByteString
getImportedModulesBytes(int index) { getImportedModulesBytes(int index) {
return importedModules_.getByteString(index); return importedModules_.getByteString(index);
} }
@@ -2144,7 +2144,7 @@ public final class DebugJsProtoBuf {
* <code>repeated string importedModules = 3;</code> * <code>repeated string importedModules = 3;</code>
*/ */
public Builder clearImportedModules() { public Builder clearImportedModules() {
importedModules_ = com.google.protobuf.LazyStringArrayList.EMPTY; importedModules_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000004); bitField0_ = (bitField0_ & ~0x00000004);
onChanged(); onChanged();
return this; return this;
@@ -2153,7 +2153,7 @@ public final class DebugJsProtoBuf {
* <code>repeated string importedModules = 3;</code> * <code>repeated string importedModules = 3;</code>
*/ */
public Builder addImportedModulesBytes( public Builder addImportedModulesBytes(
com.google.protobuf.ByteString value) { org.jetbrains.kotlin.protobuf.ByteString value) {
if (value == null) { if (value == null) {
throw new NullPointerException(); throw new NullPointerException();
} }
+2 -12
View File
@@ -367,18 +367,6 @@
<file name="long.js"/> <file name="long.js"/>
</sources> </sources>
<sources dir="${js.stdlib.output.dir}">
<file name="${compiled.builtins.js}"/>
</sources>
<sources dir="${js.stdlib.output.dir}">
<file name="${compiled.stdlib.js}"/>
</sources>
<sources dir="${stdlib.js.dir}">
<file name="export_Kotlin_if_possible.js"/>
</sources>
<externs dir="${stdlib.js.dir}"> <externs dir="${stdlib.js.dir}">
<file name="externs.js"/> <file name="externs.js"/>
</externs> </externs>
@@ -388,6 +376,8 @@
<zipfileset file="${kotlin-home}/build.txt" prefix="META-INF"/> <zipfileset file="${kotlin-home}/build.txt" prefix="META-INF"/>
<zipfileset dir="${js.stdlib.output.dir}" prefix=""> <zipfileset dir="${js.stdlib.output.dir}" prefix="">
<include name="kotlin.js"/> <include name="kotlin.js"/>
<include name="${compiled.builtins.js}"/>
<include name="${compiled.stdlib.js}"/>
<include name="${compiled.stdlib.meta.js}"/> <include name="${compiled.stdlib.meta.js}"/>
<include name="stdlib/**"/> <include name="stdlib/**"/>
</zipfileset> </zipfileset>
@@ -48,6 +48,10 @@ public class K2JSCompilerArguments extends CommonCompilerArguments {
@ValueDescription("<version>") @ValueDescription("<version>")
public String target; public String target;
@Argument(value = "module-kind", description = "Kind of a module generated by compiler. Supported values are: plain (by default), " +
"amd, commonjs.")
public String moduleKind;
@Nullable @Nullable
@Argument(value = "main", description = "Whether a main function should be called; default '" + CALL + "' (main function will be auto detected)") @Argument(value = "main", description = "Whether a main function should be called; default '" + CALL + "' (main function will be auto detected)")
@ValueDescription("{" + CALL + "," + NO_CALL + "}") @ValueDescription("{" + CALL + "," + NO_CALL + "}")
@@ -58,6 +58,7 @@ import org.jetbrains.kotlin.js.facade.TranslationResult;
import org.jetbrains.kotlin.progress.ProgressIndicatorAndCompilationCanceledStatus; import org.jetbrains.kotlin.progress.ProgressIndicatorAndCompilationCanceledStatus;
import org.jetbrains.kotlin.psi.KtFile; import org.jetbrains.kotlin.psi.KtFile;
import org.jetbrains.kotlin.utils.ExceptionUtilsKt; import org.jetbrains.kotlin.utils.ExceptionUtilsKt;
import org.jetbrains.kotlin.serialization.js.ModuleKind;
import org.jetbrains.kotlin.utils.PathUtil; import org.jetbrains.kotlin.utils.PathUtil;
import java.io.File; import java.io.File;
@@ -243,8 +244,11 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
@Override @Override
protected void setupPlatformSpecificArgumentsAndServices( protected void setupPlatformSpecificArgumentsAndServices(
@NotNull CompilerConfiguration configuration, @NotNull K2JSCompilerArguments arguments, @NotNull Services services @NotNull CompilerConfiguration configuration, @NotNull K2JSCompilerArguments arguments,
@NotNull Services services
) { ) {
MessageCollector messageCollector = configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY);
if (arguments.target != null) { if (arguments.target != null) {
assert arguments.target == "v5" : "Unsupported ECMA version: " + arguments.target; assert arguments.target == "v5" : "Unsupported ECMA version: " + arguments.target;
} }
@@ -270,6 +274,27 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
} }
configuration.put(JSConfigurationKeys.LIBRARY_FILES, libraryFiles); configuration.put(JSConfigurationKeys.LIBRARY_FILES, libraryFiles);
String moduleKindName = arguments.moduleKind;
ModuleKind moduleKind = ModuleKind.PLAIN;
if (moduleKindName != null) {
moduleKindName = moduleKindName.toLowerCase();
if (moduleKindName.equals("plain")) {
moduleKind = ModuleKind.PLAIN;
}
else if (moduleKindName.equals("amd")) {
moduleKind = ModuleKind.AMD;
}
else if (moduleKindName.equals("commonjs")) {
moduleKind = ModuleKind.COMMON_JS;
}
else {
messageCollector.report(CompilerMessageSeverity.ERROR, "Unknown module kind: " + moduleKindName + ". " +
"valid values are: plain, amd, commonjs",
CompilerMessageLocation.NO_LOCATION);
}
}
configuration.put(JSConfigurationKeys.MODULE_KIND, moduleKind);
} }
private static MainCallParameters createMainCallParameters(String main) { private static MainCallParameters createMainCallParameters(String main) {
@@ -71,14 +71,12 @@ class KotlinJavascriptSerializerTest : TestCaseWithTmpdir() {
val config = LibrarySourcesConfig(environment.project, environment.configuration) val config = LibrarySourcesConfig(environment.project, environment.configuration)
val analysisResult = TopDownAnalyzerFacadeForJS.analyzeFiles(files, config) val analysisResult = TopDownAnalyzerFacadeForJS.analyzeFiles(files, config)
val description = JsModuleDescriptor( val description = JsModuleDescriptor(
name = MODULE_NAME, name = KotlinTestUtils.TEST_MODULE_NAME,
kind = ModuleKind.PLAIN, kind = ModuleKind.PLAIN,
imported = listOf(), imported = listOf(),
data = analysisResult.moduleDescriptor data = analysisResult.moduleDescriptor
); )
FileUtil.writeToFile(metaFile, KotlinJavascriptSerializationUtil.metadataAsString( FileUtil.writeToFile(metaFile, KotlinJavascriptSerializationUtil.metadataAsString(description))
KotlinTestUtils.TEST_MODULE_NAME, analysisResult.moduleDescriptor
))
} }
finally { finally {
Disposer.dispose(rootDisposable) Disposer.dispose(rootDisposable)
@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.js.config; package org.jetbrains.kotlin.js.config;
import org.jetbrains.kotlin.config.CompilerConfigurationKey; import org.jetbrains.kotlin.config.CompilerConfigurationKey;
import org.jetbrains.kotlin.serialization.js.ModuleKind;
import java.util.List; import java.util.List;
@@ -36,4 +37,7 @@ public class JSConfigurationKeys {
public static final CompilerConfigurationKey<Boolean> UNIT_TEST_CONFIG = public static final CompilerConfigurationKey<Boolean> UNIT_TEST_CONFIG =
CompilerConfigurationKey.create("unit test config"); CompilerConfigurationKey.create("unit test config");
public static final CompilerConfigurationKey<ModuleKind> MODULE_KIND =
CompilerConfigurationKey.create("module kind");
} }
@@ -23,6 +23,7 @@ import kotlin.Unit;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1; import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.config.CommonConfigurationKeys; import org.jetbrains.kotlin.config.CommonConfigurationKeys;
import org.jetbrains.kotlin.config.CompilerConfiguration; import org.jetbrains.kotlin.config.CompilerConfiguration;
import org.jetbrains.kotlin.descriptors.PackageFragmentProvider; import org.jetbrains.kotlin.descriptors.PackageFragmentProvider;
@@ -51,15 +52,6 @@ public abstract class JsConfig {
private final CompilerConfiguration configuration; private final CompilerConfiguration configuration;
private final LockBasedStorageManager storageManager = new LockBasedStorageManager(); private final LockBasedStorageManager storageManager = new LockBasedStorageManager();
private final List<KtFile> sourceFilesFromLibraries = new SmartList<KtFile>(); private final List<KtFile> sourceFilesFromLibraries = new SmartList<KtFile>();
@NotNull
private final EcmaVersion target;
@NotNull
private final String moduleId;
private final boolean sourcemap;
private final boolean metaInfo;
private final boolean kjsm;
@NotNull @NotNull
protected final List<KotlinJavascriptMetadata> metadata = new SmartList<KotlinJavascriptMetadata>(); protected final List<KotlinJavascriptMetadata> metadata = new SmartList<KotlinJavascriptMetadata>();
@@ -67,9 +59,6 @@ public abstract class JsConfig {
@Nullable @Nullable
private List<JsModuleDescriptor<ModuleDescriptorImpl>> moduleDescriptors = null; private List<JsModuleDescriptor<ModuleDescriptorImpl>> moduleDescriptors = null;
@NotNull
private final ModuleKind moduleKind;
private boolean initialized = false; private boolean initialized = false;
protected JsConfig(@NotNull Project project, @NotNull CompilerConfiguration configuration) { protected JsConfig(@NotNull Project project, @NotNull CompilerConfiguration configuration) {
@@ -94,7 +83,7 @@ public abstract class JsConfig {
@NotNull @NotNull
public ModuleKind getModuleKind() { public ModuleKind getModuleKind() {
return moduleKind; return configuration.getNotNull(JSConfigurationKeys.MODULE_KIND);
} }
public abstract boolean checkLibFilesAndReportErrors(@NotNull Function1<String, Unit> report); public abstract boolean checkLibFilesAndReportErrors(@NotNull Function1<String, Unit> report);
@@ -530,7 +530,7 @@ public final class JsProtoBuf {
/** /**
* <code>repeated string importedModules = 3;</code> * <code>repeated string importedModules = 3;</code>
*/ */
com.google.protobuf.ByteString org.jetbrains.kotlin.protobuf.ByteString
getImportedModulesBytes(int index); getImportedModulesBytes(int index);
} }
/** /**
@@ -595,7 +595,7 @@ public final class JsProtoBuf {
} }
case 26: { case 26: {
if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
importedModules_ = new com.google.protobuf.LazyStringArrayList(); importedModules_ = new org.jetbrains.kotlin.protobuf.LazyStringArrayList();
mutable_bitField0_ |= 0x00000004; mutable_bitField0_ |= 0x00000004;
} }
importedModules_.add(input.readBytes()); importedModules_.add(input.readBytes());
@@ -613,7 +613,7 @@ public final class JsProtoBuf {
entry_ = java.util.Collections.unmodifiableList(entry_); entry_ = java.util.Collections.unmodifiableList(entry_);
} }
if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
importedModules_ = new com.google.protobuf.UnmodifiableLazyStringList(importedModules_); importedModules_ = new org.jetbrains.kotlin.protobuf.UnmodifiableLazyStringList(importedModules_);
} }
makeExtensionsImmutable(); makeExtensionsImmutable();
} }
@@ -637,7 +637,7 @@ public final class JsProtoBuf {
* Protobuf enum {@code org.jetbrains.kotlin.serialization.js.Library.Kind} * Protobuf enum {@code org.jetbrains.kotlin.serialization.js.Library.Kind}
*/ */
public enum Kind public enum Kind
implements com.google.protobuf.Internal.EnumLite { implements org.jetbrains.kotlin.protobuf.Internal.EnumLite {
/** /**
* <code>PLAIN = 1;</code> * <code>PLAIN = 1;</code>
*/ */
@@ -677,13 +677,13 @@ public final class JsProtoBuf {
} }
} }
public static com.google.protobuf.Internal.EnumLiteMap<Kind> public static org.jetbrains.kotlin.protobuf.Internal.EnumLiteMap<Kind>
internalGetValueMap() { internalGetValueMap() {
return internalValueMap; return internalValueMap;
} }
private static com.google.protobuf.Internal.EnumLiteMap<Kind> private static org.jetbrains.kotlin.protobuf.Internal.EnumLiteMap<Kind>
internalValueMap = internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<Kind>() { new org.jetbrains.kotlin.protobuf.Internal.EnumLiteMap<Kind>() {
public Kind findValueByNumber(int number) { public Kind findValueByNumber(int number) {
return Kind.valueOf(number); return Kind.valueOf(number);
} }
@@ -1261,7 +1261,7 @@ public final class JsProtoBuf {
// repeated string importedModules = 3; // repeated string importedModules = 3;
public static final int IMPORTEDMODULES_FIELD_NUMBER = 3; public static final int IMPORTEDMODULES_FIELD_NUMBER = 3;
private com.google.protobuf.LazyStringList importedModules_; private org.jetbrains.kotlin.protobuf.LazyStringList importedModules_;
/** /**
* <code>repeated string importedModules = 3;</code> * <code>repeated string importedModules = 3;</code>
*/ */
@@ -1284,7 +1284,7 @@ public final class JsProtoBuf {
/** /**
* <code>repeated string importedModules = 3;</code> * <code>repeated string importedModules = 3;</code>
*/ */
public com.google.protobuf.ByteString public org.jetbrains.kotlin.protobuf.ByteString
getImportedModulesBytes(int index) { getImportedModulesBytes(int index) {
return importedModules_.getByteString(index); return importedModules_.getByteString(index);
} }
@@ -1292,7 +1292,7 @@ public final class JsProtoBuf {
private void initFields() { private void initFields() {
entry_ = java.util.Collections.emptyList(); entry_ = java.util.Collections.emptyList();
kind_ = org.jetbrains.kotlin.serialization.js.JsProtoBuf.Library.Kind.PLAIN; kind_ = org.jetbrains.kotlin.serialization.js.JsProtoBuf.Library.Kind.PLAIN;
importedModules_ = com.google.protobuf.LazyStringArrayList.EMPTY; importedModules_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
} }
private byte memoizedIsInitialized = -1; private byte memoizedIsInitialized = -1;
public final boolean isInitialized() { public final boolean isInitialized() {
@@ -1334,13 +1334,13 @@ public final class JsProtoBuf {
.computeMessageSize(1, entry_.get(i)); .computeMessageSize(1, entry_.get(i));
} }
if (((bitField0_ & 0x00000001) == 0x00000001)) { if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeEnumSize(2, kind_.getNumber()); .computeEnumSize(2, kind_.getNumber());
} }
{ {
int dataSize = 0; int dataSize = 0;
for (int i = 0; i < importedModules_.size(); i++) { for (int i = 0; i < importedModules_.size(); i++) {
dataSize += com.google.protobuf.CodedOutputStream dataSize += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeBytesSizeNoTag(importedModules_.getByteString(i)); .computeBytesSizeNoTag(importedModules_.getByteString(i));
} }
size += dataSize; size += dataSize;
@@ -1441,7 +1441,7 @@ public final class JsProtoBuf {
bitField0_ = (bitField0_ & ~0x00000001); bitField0_ = (bitField0_ & ~0x00000001);
kind_ = org.jetbrains.kotlin.serialization.js.JsProtoBuf.Library.Kind.PLAIN; kind_ = org.jetbrains.kotlin.serialization.js.JsProtoBuf.Library.Kind.PLAIN;
bitField0_ = (bitField0_ & ~0x00000002); bitField0_ = (bitField0_ & ~0x00000002);
importedModules_ = com.google.protobuf.LazyStringArrayList.EMPTY; importedModules_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000004); bitField0_ = (bitField0_ & ~0x00000004);
return this; return this;
} }
@@ -1476,7 +1476,7 @@ public final class JsProtoBuf {
} }
result.kind_ = kind_; result.kind_ = kind_;
if (((bitField0_ & 0x00000004) == 0x00000004)) { if (((bitField0_ & 0x00000004) == 0x00000004)) {
importedModules_ = new com.google.protobuf.UnmodifiableLazyStringList( importedModules_ = new org.jetbrains.kotlin.protobuf.UnmodifiableLazyStringList(
importedModules_); importedModules_);
bitField0_ = (bitField0_ & ~0x00000004); bitField0_ = (bitField0_ & ~0x00000004);
} }
@@ -1704,10 +1704,10 @@ public final class JsProtoBuf {
} }
// repeated string importedModules = 3; // repeated string importedModules = 3;
private com.google.protobuf.LazyStringList importedModules_ = com.google.protobuf.LazyStringArrayList.EMPTY; private org.jetbrains.kotlin.protobuf.LazyStringList importedModules_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
private void ensureImportedModulesIsMutable() { private void ensureImportedModulesIsMutable() {
if (!((bitField0_ & 0x00000004) == 0x00000004)) { if (!((bitField0_ & 0x00000004) == 0x00000004)) {
importedModules_ = new com.google.protobuf.LazyStringArrayList(importedModules_); importedModules_ = new org.jetbrains.kotlin.protobuf.LazyStringArrayList(importedModules_);
bitField0_ |= 0x00000004; bitField0_ |= 0x00000004;
} }
} }
@@ -1733,7 +1733,7 @@ public final class JsProtoBuf {
/** /**
* <code>repeated string importedModules = 3;</code> * <code>repeated string importedModules = 3;</code>
*/ */
public com.google.protobuf.ByteString public org.jetbrains.kotlin.protobuf.ByteString
getImportedModulesBytes(int index) { getImportedModulesBytes(int index) {
return importedModules_.getByteString(index); return importedModules_.getByteString(index);
} }
@@ -1777,7 +1777,7 @@ public final class JsProtoBuf {
* <code>repeated string importedModules = 3;</code> * <code>repeated string importedModules = 3;</code>
*/ */
public Builder clearImportedModules() { public Builder clearImportedModules() {
importedModules_ = com.google.protobuf.LazyStringArrayList.EMPTY; importedModules_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000004); bitField0_ = (bitField0_ & ~0x00000004);
return this; return this;
@@ -1786,7 +1786,7 @@ public final class JsProtoBuf {
* <code>repeated string importedModules = 3;</code> * <code>repeated string importedModules = 3;</code>
*/ */
public Builder addImportedModulesBytes( public Builder addImportedModulesBytes(
com.google.protobuf.ByteString value) { org.jetbrains.kotlin.protobuf.ByteString value) {
if (value == null) { if (value == null) {
throw new NullPointerException(); throw new NullPointerException();
} }
@@ -60,7 +60,7 @@ object KotlinJavascriptSerializationUtil {
kotlinModule: ModuleDescriptor): JsModuleDescriptor<PackageFragmentProvider?> { kotlinModule: ModuleDescriptor): JsModuleDescriptor<PackageFragmentProvider?> {
val prototype = metadata.toContentMap() val prototype = metadata.toContentMap()
val packageFragmentProvider = createPackageFragmentProvider(kotlinModule, prototype.contentMap, storageManager); val packageFragmentProvider = createPackageFragmentProvider(kotlinModule, prototype.contentMap, storageManager)
return JsModuleDescriptor(kotlinModule.name.asString(), prototype.kind, prototype.imported, packageFragmentProvider) return JsModuleDescriptor(kotlinModule.name.asString(), prototype.kind, prototype.imported, packageFragmentProvider)
} }
@@ -94,7 +94,7 @@ object KotlinJavascriptSerializationUtil {
ModuleKind.PLAIN -> JsProtoBuf.Library.Kind.PLAIN ModuleKind.PLAIN -> JsProtoBuf.Library.Kind.PLAIN
ModuleKind.AMD -> JsProtoBuf.Library.Kind.AMD ModuleKind.AMD -> JsProtoBuf.Library.Kind.AMD
ModuleKind.COMMON_JS -> JsProtoBuf.Library.Kind.COMMON_JS ModuleKind.COMMON_JS -> JsProtoBuf.Library.Kind.COMMON_JS
}; }
importedModules.forEach { contentBuilder.addImportedModules(it) } importedModules.forEach { contentBuilder.addImportedModules(it) }
@@ -197,8 +197,8 @@ public final class RhinoUtils {
runFileWithRhino(TEST_DATA_DIR_PATH + "kotlin_lib.js", context, scope); runFileWithRhino(TEST_DATA_DIR_PATH + "kotlin_lib.js", context, scope);
runFileWithRhino(TEST_DATA_DIR_PATH + "maps.js", context, scope); runFileWithRhino(TEST_DATA_DIR_PATH + "maps.js", context, scope);
runFileWithRhino(TEST_DATA_DIR_PATH + "long.js", context, scope); runFileWithRhino(TEST_DATA_DIR_PATH + "long.js", context, scope);
runFileWithRhino(DIST_DIR_JS_PATH + STDLIB_JS_FILE_NAME, context, scope);
runFileWithRhino(DIST_DIR_JS_PATH + BUILTINS_JS_FILE_NAME, context, scope); runFileWithRhino(DIST_DIR_JS_PATH + BUILTINS_JS_FILE_NAME, context, scope);
runFileWithRhino(DIST_DIR_JS_PATH + STDLIB_JS_FILE_NAME, context, scope);
//runFileWithRhino(pathToTestFilesRoot() + "jshint.js", context, scope); //runFileWithRhino(pathToTestFilesRoot() + "jshint.js", context, scope);
for (String jsLibrary : jsLibraries) { for (String jsLibrary : jsLibraries) {
runFileWithRhino(jsLibrary, context, scope); runFileWithRhino(jsLibrary, context, scope);
@@ -35,6 +35,12 @@ public class MultiModuleTestGenerated extends AbstractMultiModuleTest {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("js/js.translator/testData/multiModule/cases"), Pattern.compile("^([^\\.]+)$"), false); KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("js/js.translator/testData/multiModule/cases"), Pattern.compile("^([^\\.]+)$"), false);
} }
@TestMetadata("moduleAndVariableNameClash")
public void testModuleAndVariableNameClash() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("js/js.translator/testData/multiModule/cases/moduleAndVariableNameClash/");
doTest(fileName);
}
@TestMetadata("useElementsFromDefaultPackageInAnotherModule") @TestMetadata("useElementsFromDefaultPackageInAnotherModule")
public void testUseElementsFromDefaultPackageInAnotherModule() throws Exception { public void testUseElementsFromDefaultPackageInAnotherModule() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("js/js.translator/testData/multiModule/cases/useElementsFromDefaultPackageInAnotherModule/"); String fileName = KotlinTestUtils.navigationMetadata("js/js.translator/testData/multiModule/cases/useElementsFromDefaultPackageInAnotherModule/");
@@ -106,6 +106,8 @@ public final class Namer {
private static final JsNameRef JS_OBJECT = new JsNameRef("Object"); private static final JsNameRef JS_OBJECT = new JsNameRef("Object");
private static final JsNameRef JS_OBJECT_CREATE_FUNCTION = new JsNameRef("create", JS_OBJECT); private static final JsNameRef JS_OBJECT_CREATE_FUNCTION = new JsNameRef("create", JS_OBJECT);
public static final String LOCAL_MODULE_PREFIX = "$module$";
public static boolean isUndefined(@NotNull JsExpression expr) { public static boolean isUndefined(@NotNull JsExpression expr) {
if (expr instanceof JsPrefixOperation) { if (expr instanceof JsPrefixOperation) {
JsUnaryOperator op = ((JsPrefixOperation) expr).getOperator(); JsUnaryOperator op = ((JsPrefixOperation) expr).getOperator();
@@ -511,4 +513,30 @@ public final class Namer {
public static JsNameRef createInlineFunction() { public static JsNameRef createInlineFunction() {
return pureFqn(DEFINE_INLINE_FUNCTION, kotlinObject()); return pureFqn(DEFINE_INLINE_FUNCTION, kotlinObject());
} }
@NotNull
public static String suggestedModuleName(@NotNull String id) {
if (id.isEmpty()) {
return "_";
}
StringBuilder sb = new StringBuilder(id.length());
char c = id.charAt(0);
if (Character.isJavaIdentifierStart(c)) {
sb.append(c);
}
else {
sb.append('_');
if (Character.isJavaIdentifierPart(c)) {
sb.append(c);
}
}
for (int i = 1; i < id.length(); ++i) {
c = id.charAt(i);
sb.append(Character.isJavaIdentifierPart(c) ? c : '_');
}
return sb.toString();
}
} }
@@ -41,10 +41,7 @@ import org.jetbrains.kotlin.resolve.BindingTrace;
import org.jetbrains.kotlin.resolve.DescriptorUtils; import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForObject; import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForObject;
import java.util.List; import java.util.*;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import static org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils.*; import static org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils.*;
import static org.jetbrains.kotlin.js.translate.utils.JsAstUtils.pureFqn; import static org.jetbrains.kotlin.js.translate.utils.JsAstUtils.pureFqn;
@@ -556,13 +553,11 @@ public final class StaticContext {
JsName moduleId = importedModules.get(moduleName); JsName moduleId = importedModules.get(moduleName);
if (moduleId == null) { if (moduleId == null) {
moduleId = rootScope.declareFreshName(suggestedModuleName(moduleName)); moduleId = rootScope.declareFreshName(Namer.LOCAL_MODULE_PREFIX + Namer.suggestedModuleName(moduleName));
importedModules.put(moduleName, moduleId); importedModules.put(moduleName, moduleId);
} }
// TODO: use just generated moduleId to refer to module. This requires to rewrite how JS module is written
return JsAstUtils.replaceRootReference( return JsAstUtils.replaceRootReference(result, JsAstUtils.pureFqn(moduleId, null));
result, namer.getModuleReference(program.getStringLiteral(moduleName)));
} }
}; };
Rule<JsExpression> constructorOrCompanionObjectHasTheSameQualifierAsTheClass = new Rule<JsExpression>() { Rule<JsExpression> constructorOrCompanionObjectHasTheSameQualifierAsTheClass = new Rule<JsExpression>() {
@@ -656,40 +651,6 @@ public final class StaticContext {
} }
} }
private static String suggestedModuleName(String id) {
if (id.isEmpty()) {
return "_";
}
StringBuilder sb = new StringBuilder(id.length());
char c = id.charAt(0);
if (Character.isJavaIdentifierStart(c)) {
sb.append(c);
}
else {
sb.append('_');
if (Character.isJavaIdentifierPart(c)) {
sb.append(c);
}
}
sb.append(Character.isJavaIdentifierStart(c) ? c : '_');
for (int i = 1; i < id.length(); ++i) {
c = id.charAt(i);
sb.append(Character.isJavaIdentifierPart(c) ? c : '_');
}
return sb.toString();
}
@Nullable
private static ClassDescriptor getEnclosing(@Nullable DeclarationDescriptor descriptor) {
while (descriptor != null && !(descriptor instanceof ClassDescriptor)) {
descriptor = descriptor.getContainingDeclaration();
}
return (ClassDescriptor) descriptor;
}
private static JsExpression applySideEffects(JsExpression expression, DeclarationDescriptor descriptor) { private static JsExpression applySideEffects(JsExpression expression, DeclarationDescriptor descriptor) {
if (expression instanceof HasMetadata) { if (expression instanceof HasMetadata) {
if (descriptor instanceof FunctionDescriptor || if (descriptor instanceof FunctionDescriptor ||
@@ -42,6 +42,7 @@ import org.jetbrains.kotlin.js.translate.test.JSTestGenerator;
import org.jetbrains.kotlin.js.translate.test.JSTester; import org.jetbrains.kotlin.js.translate.test.JSTester;
import org.jetbrains.kotlin.js.translate.test.QUnitTester; import org.jetbrains.kotlin.js.translate.test.QUnitTester;
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils; import org.jetbrains.kotlin.js.translate.utils.JsAstUtils;
import org.jetbrains.kotlin.js.translate.utils.JsDescriptorUtils;
import org.jetbrains.kotlin.js.translate.utils.mutator.AssignToExpressionMutator; import org.jetbrains.kotlin.js.translate.utils.mutator.AssignToExpressionMutator;
import org.jetbrains.kotlin.psi.KtDeclarationWithBody; import org.jetbrains.kotlin.psi.KtDeclarationWithBody;
import org.jetbrains.kotlin.psi.KtExpression; import org.jetbrains.kotlin.psi.KtExpression;
@@ -51,6 +52,7 @@ import org.jetbrains.kotlin.resolve.BindingTrace;
import org.jetbrains.kotlin.resolve.bindingContextUtil.BindingContextUtilsKt; import org.jetbrains.kotlin.resolve.bindingContextUtil.BindingContextUtilsKt;
import org.jetbrains.kotlin.utils.ExceptionUtilsKt; import org.jetbrains.kotlin.utils.ExceptionUtilsKt;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@@ -196,9 +198,8 @@ public final class Translation {
) { ) {
StaticContext staticContext = StaticContext.generateStaticContext(bindingTrace, config, moduleDescriptor); StaticContext staticContext = StaticContext.generateStaticContext(bindingTrace, config, moduleDescriptor);
JsProgram program = staticContext.getProgram(); JsProgram program = staticContext.getProgram();
JsBlock block = program.getGlobalBlock();
JsFunction rootFunction = JsAstUtils.createPackage(block.getStatements(), program.getScope()); JsFunction rootFunction = JsAstUtils.createFunctionWithEmptyBody(program.getScope());
JsBlock rootBlock = rootFunction.getBody(); JsBlock rootBlock = rootFunction.getBody();
List<JsStatement> statements = rootBlock.getStatements(); List<JsStatement> statements = rootBlock.getStatements();
statements.add(program.getStringLiteral("use strict").makeStmt()); statements.add(program.getStringLiteral("use strict").makeStmt());
@@ -206,6 +207,31 @@ public final class Translation {
TranslationContext context = TranslationContext.rootContext(staticContext, rootFunction); TranslationContext context = TranslationContext.rootContext(staticContext, rootFunction);
statements.addAll(PackageDeclarationTranslator.translateFiles(files, context)); statements.addAll(PackageDeclarationTranslator.translateFiles(files, context));
defineModule(context, statements, config.getModuleId()); defineModule(context, statements, config.getModuleId());
statements.add(new JsReturn(program.getRootScope().declareName(Namer.getRootPackageName()).makeRef()));
mayBeGenerateTests(files, config, rootBlock, context);
JsBlock block = program.getGlobalBlock();
// Invoke function passing modules as arguments
// This should help minifier tool to recognize references to this modules as local variables and make them shorter.
List<JsExpression> invocationArgs = new ArrayList<JsExpression>(staticContext.getImportedModules().size() + 1);
JsName kotlinName = program.getScope().declareName(Namer.KOTLIN_NAME);
rootFunction.getParameters().add(new JsParameter((kotlinName)));
invocationArgs.add(kotlinName.makeRef());
for (String importedModule : staticContext.getImportedModules().keySet()) {
rootFunction.getParameters().add(new JsParameter(staticContext.getImportedModules().get(importedModule)));
JsName globalId = program.getScope().declareName(Namer.suggestedModuleName(importedModule));
invocationArgs.add(JsAstUtils.pureFqn(globalId, null));
}
JsInvocation invocation = new JsInvocation(rootFunction, invocationArgs);
String thisModuleName = JsDescriptorUtils.getModuleNameFromDescriptorName(moduleDescriptor);
JsName thisModuleId = program.getScope().declareName(Namer.suggestedModuleName(thisModuleName));
block.getStatements().add(JsAstUtils.newVar(thisModuleId,
new JsBinaryOperation(JsBinaryOperator.OR, thisModuleId.makeRef(), invocation)));
if (mainCallParameters.shouldBeGenerated()) { if (mainCallParameters.shouldBeGenerated()) {
JsStatement statement = generateCallToMain(context, files, mainCallParameters.arguments()); JsStatement statement = generateCallToMain(context, files, mainCallParameters.arguments());
@@ -213,7 +239,7 @@ public final class Translation {
statements.add(statement); statements.add(statement);
} }
} }
mayBeGenerateTests(files, config, rootBlock, context);
return context; return context;
} }
@@ -442,18 +442,6 @@ public final class JsAstUtils {
return dataDescriptor; return dataDescriptor;
} }
@NotNull
public static JsFunction createPackage(@NotNull List<JsStatement> to, @NotNull JsObjectScope scope) {
JsFunction packageBlockFunction = createFunctionWithEmptyBody(scope);
JsName kotlinObjectAsParameter = packageBlockFunction.getScope().declareNameUnsafe(Namer.KOTLIN_NAME);
packageBlockFunction.getParameters().add(new JsParameter(kotlinObjectAsParameter));
to.add(new JsInvocation(packageBlockFunction, Namer.kotlinObject()).makeStmt());
return packageBlockFunction;
}
@NotNull @NotNull
public static JsObjectLiteral wrapValue(@NotNull JsExpression label, @NotNull JsExpression value) { public static JsObjectLiteral wrapValue(@NotNull JsExpression label, @NotNull JsExpression value) {
return new JsObjectLiteral(Collections.singletonList(new JsPropertyInitializer(label, value))); return new JsObjectLiteral(Collections.singletonList(new JsPropertyInitializer(label, value)));
@@ -197,7 +197,7 @@ public final class JsDescriptorUtils {
return element.getContainingFile().getUserData(LibrarySourcesConfig.EXTERNAL_MODULE_NAME); return element.getContainingFile().getUserData(LibrarySourcesConfig.EXTERNAL_MODULE_NAME);
} }
private static String getModuleNameFromDescriptorName(DeclarationDescriptor descriptor) { public static String getModuleNameFromDescriptorName(DeclarationDescriptor descriptor) {
ModuleDescriptor moduleDescriptor = DescriptorUtils.getContainingModule(descriptor); ModuleDescriptor moduleDescriptor = DescriptorUtils.getContainingModule(descriptor);
String moduleName = moduleDescriptor.getName().asString(); String moduleName = moduleDescriptor.getName().asString();
return moduleName.substring(1, moduleName.length() - 1); return moduleName.substring(1, moduleName.length() - 1);
@@ -31,7 +31,7 @@ fun expandIsCalls(node: JsNode, context: TranslationContext) {
private class TypeCheckRewritingVisitor(private val context: TranslationContext) : JsVisitorWithContextImpl() { private class TypeCheckRewritingVisitor(private val context: TranslationContext) : JsVisitorWithContextImpl() {
private val scopes = Stack<JsScope>() private val scopes = Stack<JsScope>()
private val localVars = Stack<MutableSet<JsName>>() private val localVars = Stack<MutableSet<JsName>>().apply { push(mutableSetOf()) }
override fun visit(x: JsFunction, ctx: JsContext<*>): Boolean { override fun visit(x: JsFunction, ctx: JsContext<*>): Boolean {
scopes.push(x.scope) scopes.push(x.scope)
+1
View File
@@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
var Kotlin = Kotlin || {};
(function (Kotlin) { (function (Kotlin) {
"use strict"; "use strict";
+1 -1
View File
@@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
var Kotlin = {}; var Kotlin = Kotlin || {};
(function (Kotlin) { (function (Kotlin) {
'use strict'; 'use strict';
+2
View File
@@ -26,6 +26,8 @@
// distributed under the License is distributed on an "AS-IS" BASIS, // distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
var Kotlin = Kotlin || {};
(function (Kotlin) { (function (Kotlin) {
"use strict"; "use strict";
+2
View File
@@ -14,6 +14,8 @@
* limitations under the License. * limitations under the License.
*/ */
var Kotlin = Kotlin || {};
(function (Kotlin) { (function (Kotlin) {
"use strict"; "use strict";
@@ -0,0 +1,2 @@
module1->
main->module1
@@ -0,0 +1,6 @@
fun box(): String {
var module1 = bar()
assertEquals("bar", module1)
return "OK"
}
@@ -0,0 +1 @@
fun bar() = "bar"