Got rid of "namespace" word in compiler code.

This commit is contained in:
Evgeny Gerashchenko
2014-01-10 22:25:23 +04:00
parent 093afeb05c
commit b41a3f8558
55 changed files with 194 additions and 191 deletions
@@ -114,9 +114,9 @@ public class CodegenTestsOnAndroidRunner {
[exec] at java.lang.reflect.Method.invokeNative(Native Method) [exec] at java.lang.reflect.Method.invokeNative(Native Method)
[exec] at org.jetbrains.jet.compiler.android.AbstractCodegenTestCaseOnAndroid.invokeBoxMethod(AbstractCodegenTestCaseOnAndroid.java:35) [exec] at org.jetbrains.jet.compiler.android.AbstractCodegenTestCaseOnAndroid.invokeBoxMethod(AbstractCodegenTestCaseOnAndroid.java:35)
[exec] ... 13 more [exec] ... 13 more
[exec] Caused by: java.lang.VerifyError: compiler_testData_codegen_regressions_kt344_jet.namespace$t6$foo$1 [exec] Caused by: java.lang.VerifyError: compiler_testData_codegen_boxWithStdlib_regressions_kt344_kt.Compiler_testData_codegen_boxWithStdlib_regressions_kt344_ktPackage$t6$foo$1
[exec] at compiler_testData_codegen_regressions_kt344_jet.namespace.t6(dummy.jet:94) [exec] at compiler_testData_codegen_boxWithStdlib_regressions_kt344_kt.Compiler_testData_codegen_boxWithStdlib_regressions_kt344_ktPackage.t6(dummy.jet:94)
[exec] at compiler_testData_codegen_regressions_kt344_jet.namespace.box(dummy.jet:185) [exec] at compiler_testData_codegen_boxWithStdlib_regressions_kt344_kt.Compiler_testData_codegen_boxWithStdlib_regressions_kt344_ktPackage.box(dummy.jet:185)
[exec] ... 16 more [exec] ... 16 more
[exec] ............... [exec] ...............
[exec] Error in testKt529: [exec] Error in testKt529:
@@ -180,10 +180,10 @@ public class CodegenTestsOnAndroidGenerator extends UsefulTestCase {
} }
} }
private static void generateTestMethod(Printer p, String testName, String namespace) { private static void generateTestMethod(Printer p, String testName, String packageName) {
p.println("public void test" + testName + "() throws Exception {"); p.println("public void test" + testName + "() throws Exception {");
p.pushIndent(); p.pushIndent();
p.println("invokeBoxMethod(\"" + namespace + "\", \"OK\");"); p.println("invokeBoxMethod(\"" + packageName + "\", \"OK\");");
p.popIndent(); p.popIndent();
p.println("}"); p.println("}");
p.println(); p.println();
@@ -349,7 +349,7 @@ public class FunctionCodegen extends ParentCodegenAwareImpl {
InstructionAdapter iv = new InstructionAdapter(mv); InstructionAdapter iv = new InstructionAdapter(mv);
Type[] argTypes = asmMethod.getArgumentTypes(); Type[] argTypes = asmMethod.getArgumentTypes();
// The first line of some namespace file is written to the line number attribute of a static delegate to allow to 'step into' it // The first line of some package file is written to the line number attribute of a static delegate to allow to 'step into' it
// This is similar to what javac does with bridge methods // This is similar to what javac does with bridge methods
Label label = new Label(); Label label = new Label();
iv.visitLabel(label); iv.visitLabel(label);
@@ -35,7 +35,7 @@ public abstract class JetFilesProvider {
return ServiceManager.getService(project, JetFilesProvider.class); return ServiceManager.getService(project, JetFilesProvider.class);
} }
public final Function<JetFile, Collection<JetFile>> allNamespaceFiles() { public final Function<JetFile, Collection<JetFile>> allPackageFiles() {
return new Function<JetFile, Collection<JetFile>>() { return new Function<JetFile, Collection<JetFile>>() {
@Override @Override
public Collection<JetFile> fun(JetFile file) { public Collection<JetFile> fun(JetFile file) {
@@ -529,7 +529,7 @@ public class JetExpressionParsing extends AbstractJetParsing {
* : functionLiteral * : functionLiteral
* : declaration * : declaration
* : SimpleName * : SimpleName
* : "package" // foo the root namespace * : "package" // for the root package
* ; * ;
*/ */
private void parseAtomicExpression() { private void parseAtomicExpression() {
@@ -37,7 +37,7 @@ public class JetImportDirective extends JetElementImpl {
return visitor.visitImportDirective(this, data); return visitor.visitImportDirective(this, data);
} }
public boolean isAbsoluteInRootNamespace() { public boolean isAbsoluteInRootPackage() {
return findChildByType(JetTokens.PACKAGE_KEYWORD) != null; return findChildByType(JetTokens.PACKAGE_KEYWORD) != null;
} }
@@ -301,8 +301,8 @@ public class JetPsiFactory {
importDirectiveBuilder.append(" as ").append(alias.asString()); importDirectiveBuilder.append(" as ").append(alias.asString());
} }
JetFile namespace = createFile(project, importDirectiveBuilder.toString()); JetFile file = createFile(project, importDirectiveBuilder.toString());
return namespace.getImportDirectives().iterator().next(); return file.getImportDirectives().iterator().next();
} }
@NotNull @NotNull
@@ -31,7 +31,7 @@ public class JetUserType extends JetTypeElement {
super(node); super(node);
} }
public boolean isAbsoluteInRootNamespace() { public boolean isAbsoluteInRootPackage() {
return findChildByType(JetTokens.PACKAGE_KEYWORD) != null; return findChildByType(JetTokens.PACKAGE_KEYWORD) != null;
} }
@@ -89,7 +89,7 @@ public class BindingContextUtils {
@Nullable @Nullable
public static JetFile getContainingFile(@NotNull BindingContext context, @NotNull DeclarationDescriptor declarationDescriptor) { public static JetFile getContainingFile(@NotNull BindingContext context, @NotNull DeclarationDescriptor declarationDescriptor) {
// declarationDescriptor may describe a synthesized element which doesn't have PSI // declarationDescriptor may describe a synthesized element which doesn't have PSI
// To workaround that, we find a top-level parent (which is inside a NamespaceDescriptor), which is guaranteed to have PSI // To workaround that, we find a top-level parent (which is inside a PackageFragmentDescriptor), which is guaranteed to have PSI
DeclarationDescriptor descriptor = DescriptorUtils.findTopLevelParent(declarationDescriptor); DeclarationDescriptor descriptor = DescriptorUtils.findTopLevelParent(declarationDescriptor);
if (descriptor == null) return null; if (descriptor == null) return null;
@@ -98,7 +98,7 @@ public class DeclarationResolver {
resolveFunctionAndPropertyHeaders(); resolveFunctionAndPropertyHeaders();
createFunctionsForDataClasses(); createFunctionsForDataClasses();
importsResolver.processMembersImports(); importsResolver.processMembersImports();
checkRedeclarationsInNamespaces(); checkRedeclarationsInPackages();
checkRedeclarationsInInnerClassNames(); checkRedeclarationsInInnerClassNames();
} }
@@ -161,12 +161,12 @@ public class DeclarationResolver {
} }
private void resolveFunctionAndPropertyHeaders() { private void resolveFunctionAndPropertyHeaders() {
for (Map.Entry<JetFile, WritableScope> entry : context.getNamespaceScopes().entrySet()) { for (Map.Entry<JetFile, WritableScope> entry : context.getFileScopes().entrySet()) {
JetFile namespace = entry.getKey(); JetFile file = entry.getKey();
WritableScope namespaceScope = entry.getValue(); WritableScope fileScope = entry.getValue();
PackageLikeBuilder packageBuilder = context.getPackageFragments().get(namespace).getBuilder(); PackageLikeBuilder packageBuilder = context.getPackageFragments().get(file).getBuilder();
resolveFunctionAndPropertyHeaders(namespace.getDeclarations(), namespaceScope, namespaceScope, namespaceScope, packageBuilder); resolveFunctionAndPropertyHeaders(file.getDeclarations(), fileScope, fileScope, fileScope, packageBuilder);
} }
for (Map.Entry<JetClassOrObject, MutableClassDescriptor> entry : context.getClasses().entrySet()) { for (Map.Entry<JetClassOrObject, MutableClassDescriptor> entry : context.getClasses().entrySet()) {
JetClassOrObject classOrObject = entry.getKey(); JetClassOrObject classOrObject = entry.getKey();
@@ -317,7 +317,7 @@ public class DeclarationResolver {
} }
} }
private void checkRedeclarationsInNamespaces() { private void checkRedeclarationsInPackages() {
for (MutablePackageFragmentDescriptor packageFragment : Sets.newHashSet(context.getPackageFragments().values())) { for (MutablePackageFragmentDescriptor packageFragment : Sets.newHashSet(context.getPackageFragments().values())) {
if (KotlinBuiltIns.BUILT_INS_PACKAGE_FQ_NAME.equals(packageFragment.getFqName())) { if (KotlinBuiltIns.BUILT_INS_PACKAGE_FQ_NAME.equals(packageFragment.getFqName())) {
// TODO: drop this after built-ins are fully rewritten to Kotlin // TODO: drop this after built-ins are fully rewritten to Kotlin
@@ -48,10 +48,10 @@ public interface Importer {
}; };
class StandardImporter implements Importer { class StandardImporter implements Importer {
private final WritableScope namespaceScope; private final WritableScope fileScope;
public StandardImporter(WritableScope namespaceScope) { public StandardImporter(WritableScope fileScope) {
this.namespaceScope = namespaceScope; this.fileScope = fileScope;
} }
@Override @Override
@@ -101,22 +101,22 @@ public interface Importer {
} }
for (JetScope scope : scopesToImport) { for (JetScope scope : scopesToImport) {
namespaceScope.importScope(createFilteringScope(scope, descriptor, platformToKotlinClassMap)); fileScope.importScope(createFilteringScope(scope, descriptor, platformToKotlinClassMap));
} }
} }
protected void importDeclarationAlias(@NotNull DeclarationDescriptor descriptor, @NotNull Name aliasName) { protected void importDeclarationAlias(@NotNull DeclarationDescriptor descriptor, @NotNull Name aliasName) {
if (descriptor instanceof ClassifierDescriptor) { if (descriptor instanceof ClassifierDescriptor) {
namespaceScope.importClassifierAlias(aliasName, (ClassifierDescriptor) descriptor); fileScope.importClassifierAlias(aliasName, (ClassifierDescriptor) descriptor);
} }
else if (descriptor instanceof PackageViewDescriptor) { else if (descriptor instanceof PackageViewDescriptor) {
namespaceScope.importPackageAlias(aliasName, (PackageViewDescriptor) descriptor); fileScope.importPackageAlias(aliasName, (PackageViewDescriptor) descriptor);
} }
else if (descriptor instanceof FunctionDescriptor) { else if (descriptor instanceof FunctionDescriptor) {
namespaceScope.importFunctionAlias(aliasName, (FunctionDescriptor) descriptor); fileScope.importFunctionAlias(aliasName, (FunctionDescriptor) descriptor);
} }
else if (descriptor instanceof VariableDescriptor) { else if (descriptor instanceof VariableDescriptor) {
namespaceScope.importVariableAlias(aliasName, (VariableDescriptor) descriptor); fileScope.importVariableAlias(aliasName, (VariableDescriptor) descriptor);
} }
} }
@@ -137,8 +137,8 @@ public interface Importer {
private final List<DelayedImportEntry> imports = Lists.newArrayList(); private final List<DelayedImportEntry> imports = Lists.newArrayList();
public DelayedImporter(@NotNull WritableScope namespaceScope) { public DelayedImporter(@NotNull WritableScope fileScope) {
super(namespaceScope); super(fileScope);
} }
@Override @Override
@@ -82,8 +82,8 @@ public class ImportsResolver {
private void processImports(@NotNull LookupMode lookupMode) { private void processImports(@NotNull LookupMode lookupMode) {
for (JetFile file : context.getPackageFragments().keySet()) { for (JetFile file : context.getPackageFragments().keySet()) {
WritableScope namespaceScope = context.getNamespaceScopes().get(file); WritableScope fileScope = context.getFileScopes().get(file);
processImportsInFile(lookupMode, namespaceScope, Lists.newArrayList(file.getImportDirectives())); processImportsInFile(lookupMode, fileScope, Lists.newArrayList(file.getImportDirectives()));
} }
for (JetScript script : context.getScripts().keySet()) { for (JetScript script : context.getScripts().keySet()) {
WritableScope scriptScope = context.getScriptScopes().get(script); WritableScope scriptScope = context.getScriptScopes().get(script);
@@ -97,7 +97,7 @@ public class ImportsResolver {
private static void processImportsInFile( private static void processImportsInFile(
LookupMode lookupMode, LookupMode lookupMode,
@NotNull WritableScope namespaceScope, @NotNull WritableScope fileScope,
@NotNull List<JetImportDirective> importDirectives, @NotNull List<JetImportDirective> importDirectives,
@NotNull ModuleDescriptor module, @NotNull ModuleDescriptor module,
@NotNull BindingTrace trace, @NotNull BindingTrace trace,
@@ -106,9 +106,9 @@ public class ImportsResolver {
) { ) {
@NotNull JetScope rootScope = module.getPackage(FqName.ROOT).getMemberScope(); @NotNull JetScope rootScope = module.getPackage(FqName.ROOT).getMemberScope();
Importer.DelayedImporter delayedImporter = new Importer.DelayedImporter(namespaceScope); Importer.DelayedImporter delayedImporter = new Importer.DelayedImporter(fileScope);
if (lookupMode == LookupMode.EVERYTHING) { if (lookupMode == LookupMode.EVERYTHING) {
namespaceScope.clearImports(); fileScope.clearImports();
} }
for (ImportPath defaultImportPath : module.getDefaultImports()) { for (ImportPath defaultImportPath : module.getDefaultImports()) {
@@ -116,7 +116,7 @@ public class ImportsResolver {
trace, "transient trace to resolve default imports"); //not to trace errors of default imports trace, "transient trace to resolve default imports"); //not to trace errors of default imports
JetImportDirective defaultImportDirective = importsFactory.createImportDirective(defaultImportPath); JetImportDirective defaultImportDirective = importsFactory.createImportDirective(defaultImportPath);
qualifiedExpressionResolver.processImportReference(defaultImportDirective, rootScope, namespaceScope, delayedImporter, qualifiedExpressionResolver.processImportReference(defaultImportDirective, rootScope, fileScope, delayedImporter,
temporaryTrace, module, lookupMode); temporaryTrace, module, lookupMode);
} }
@@ -124,7 +124,7 @@ public class ImportsResolver {
for (JetImportDirective importDirective : importDirectives) { for (JetImportDirective importDirective : importDirectives) {
Collection<? extends DeclarationDescriptor> descriptors = Collection<? extends DeclarationDescriptor> descriptors =
qualifiedExpressionResolver.processImportReference(importDirective, rootScope, namespaceScope, delayedImporter, qualifiedExpressionResolver.processImportReference(importDirective, rootScope, fileScope, delayedImporter,
trace, module, lookupMode); trace, module, lookupMode);
if (!descriptors.isEmpty()) { if (!descriptors.isEmpty()) {
resolvedDirectives.put(importDirective, descriptors); resolvedDirectives.put(importDirective, descriptors);
@@ -141,7 +141,7 @@ public class ImportsResolver {
if (lookupMode == LookupMode.EVERYTHING) { if (lookupMode == LookupMode.EVERYTHING) {
for (JetImportDirective importDirective : importDirectives) { for (JetImportDirective importDirective : importDirectives) {
reportUselessImport(importDirective, namespaceScope, resolvedDirectives, trace); reportUselessImport(importDirective, fileScope, resolvedDirectives, trace);
} }
} }
} }
@@ -163,7 +163,7 @@ public class ImportsResolver {
private static void reportUselessImport( private static void reportUselessImport(
@NotNull JetImportDirective importDirective, @NotNull JetImportDirective importDirective,
@NotNull WritableScope namespaceScope, @NotNull WritableScope fileScope,
@NotNull Map<JetImportDirective, Collection<? extends DeclarationDescriptor>> resolvedDirectives, @NotNull Map<JetImportDirective, Collection<? extends DeclarationDescriptor>> resolvedDirectives,
@NotNull BindingTrace trace @NotNull BindingTrace trace
) { ) {
@@ -181,13 +181,13 @@ public class ImportsResolver {
for (DeclarationDescriptor wasResolved : resolvedDirectives.get(importDirective)) { for (DeclarationDescriptor wasResolved : resolvedDirectives.get(importDirective)) {
DeclarationDescriptor isResolved = null; DeclarationDescriptor isResolved = null;
if (wasResolved instanceof ClassDescriptor) { if (wasResolved instanceof ClassDescriptor) {
isResolved = namespaceScope.getClassifier(aliasName); isResolved = fileScope.getClassifier(aliasName);
} }
else if (wasResolved instanceof VariableDescriptor) { else if (wasResolved instanceof VariableDescriptor) {
isResolved = namespaceScope.getLocalVariable(aliasName); isResolved = fileScope.getLocalVariable(aliasName);
} }
else if (wasResolved instanceof PackageViewDescriptor) { else if (wasResolved instanceof PackageViewDescriptor) {
isResolved = namespaceScope.getPackage(aliasName); isResolved = fileScope.getPackage(aliasName);
} }
if (isResolved == null || isResolved.equals(wasResolved)) { if (isResolved == null || isResolved.equals(wasResolved)) {
uselessHiddenImport = false; uselessHiddenImport = false;
@@ -24,7 +24,7 @@ import org.jetbrains.jet.lang.types.PackageType;
public class JetModuleUtil { public class JetModuleUtil {
public static PackageType getRootPackageType(JetElement expression) { public static PackageType getRootPackageType(JetElement expression) {
// TODO: this is a stub: at least the modules' root namespaces must be indexed here // TODO: this is a stub: at least the modules' root packages must be indexed here
return new PackageType(SpecialNames.ROOT_PACKAGE, JetScope.EMPTY, ReceiverValue.NO_RECEIVER); return new PackageType(SpecialNames.ROOT_PACKAGE, JetScope.EMPTY, ReceiverValue.NO_RECEIVER);
} }
} }
@@ -35,7 +35,7 @@ import java.util.Set;
import static org.jetbrains.jet.lang.diagnostics.Errors.*; import static org.jetbrains.jet.lang.diagnostics.Errors.*;
public class QualifiedExpressionResolver { public class QualifiedExpressionResolver {
private static final Predicate<DeclarationDescriptor> CLASSIFIERS_AND_NAMESPACES = new Predicate<DeclarationDescriptor>() { private static final Predicate<DeclarationDescriptor> CLASSIFIERS_AND_PACKAGE_VIEWS = new Predicate<DeclarationDescriptor>() {
@Override @Override
public boolean apply(@Nullable DeclarationDescriptor descriptor) { public boolean apply(@Nullable DeclarationDescriptor descriptor) {
return descriptor instanceof ClassifierDescriptor || descriptor instanceof PackageViewDescriptor; return descriptor instanceof ClassifierDescriptor || descriptor instanceof PackageViewDescriptor;
@@ -70,7 +70,7 @@ public class QualifiedExpressionResolver {
@NotNull ModuleDescriptor module, @NotNull ModuleDescriptor module,
@NotNull LookupMode lookupMode @NotNull LookupMode lookupMode
) { ) {
if (importDirective.isAbsoluteInRootNamespace()) { if (importDirective.isAbsoluteInRootPackage()) {
trace.report(UNSUPPORTED.on(importDirective, "TypeHierarchyResolver")); // TODO trace.report(UNSUPPORTED.on(importDirective, "TypeHierarchyResolver")); // TODO
return Collections.emptyList(); return Collections.emptyList();
} }
@@ -158,7 +158,7 @@ public class QualifiedExpressionResolver {
public Collection<? extends DeclarationDescriptor> lookupDescriptorsForUserType(@NotNull JetUserType userType, public Collection<? extends DeclarationDescriptor> lookupDescriptorsForUserType(@NotNull JetUserType userType,
@NotNull JetScope outerScope, @NotNull BindingTrace trace) { @NotNull JetScope outerScope, @NotNull BindingTrace trace) {
if (userType.isAbsoluteInRootNamespace()) { if (userType.isAbsoluteInRootPackage()) {
trace.report(Errors.UNSUPPORTED.on(userType, "package")); trace.report(Errors.UNSUPPORTED.on(userType, "package"));
return Collections.emptyList(); return Collections.emptyList();
} }
@@ -241,9 +241,9 @@ public class QualifiedExpressionResolver {
@NotNull @NotNull
public Collection<? extends DeclarationDescriptor> lookupDescriptorsForSimpleNameReference(@NotNull JetSimpleNameExpression referenceExpression, public Collection<? extends DeclarationDescriptor> lookupDescriptorsForSimpleNameReference(@NotNull JetSimpleNameExpression referenceExpression,
@NotNull JetScope outerScope, @NotNull JetScope scopeToCheckVisibility, @NotNull BindingTrace trace, @NotNull LookupMode lookupMode, boolean namespaceLevel, boolean storeResult) { @NotNull JetScope outerScope, @NotNull JetScope scopeToCheckVisibility, @NotNull BindingTrace trace, @NotNull LookupMode lookupMode, boolean packageLevel, boolean storeResult) {
LookupResult lookupResult = lookupSimpleNameReference(referenceExpression, outerScope, lookupMode, namespaceLevel); LookupResult lookupResult = lookupSimpleNameReference(referenceExpression, outerScope, lookupMode, packageLevel);
if (lookupResult == LookupResult.EMPTY) return Collections.emptyList(); if (lookupResult == LookupResult.EMPTY) return Collections.emptyList();
return filterAndStoreResolutionResult(Collections.singletonList((SuccessfulLookupResult)lookupResult), referenceExpression, trace, scopeToCheckVisibility, return filterAndStoreResolutionResult(Collections.singletonList((SuccessfulLookupResult)lookupResult), referenceExpression, trace, scopeToCheckVisibility,
lookupMode, storeResult); lookupMode, storeResult);
@@ -251,7 +251,7 @@ public class QualifiedExpressionResolver {
@NotNull @NotNull
private LookupResult lookupSimpleNameReference(@NotNull JetSimpleNameExpression referenceExpression, private LookupResult lookupSimpleNameReference(@NotNull JetSimpleNameExpression referenceExpression,
@NotNull JetScope outerScope, @NotNull LookupMode lookupMode, boolean namespaceLevel) { @NotNull JetScope outerScope, @NotNull LookupMode lookupMode, boolean packageLevel) {
Name referencedName = referenceExpression.getReferencedNameAsName(); Name referencedName = referenceExpression.getReferencedNameAsName();
@@ -275,7 +275,7 @@ public class QualifiedExpressionResolver {
descriptors.add(localVariable); descriptors.add(localVariable);
} }
} }
return new SuccessfulLookupResult(descriptors, outerScope, namespaceLevel); return new SuccessfulLookupResult(descriptors, outerScope, packageLevel);
} }
@NotNull @NotNull
@@ -305,17 +305,17 @@ public class QualifiedExpressionResolver {
Collection<DeclarationDescriptor> filteredDescriptors; Collection<DeclarationDescriptor> filteredDescriptors;
if (lookupMode == LookupMode.ONLY_CLASSES) { if (lookupMode == LookupMode.ONLY_CLASSES) {
filteredDescriptors = Collections2.filter(descriptors, CLASSIFIERS_AND_NAMESPACES); filteredDescriptors = Collections2.filter(descriptors, CLASSIFIERS_AND_PACKAGE_VIEWS);
} }
else { else {
filteredDescriptors = Sets.newLinkedHashSet(); filteredDescriptors = Sets.newLinkedHashSet();
//functions and properties can be imported if lookupResult.namespaceLevel == true //functions and properties can be imported if lookupResult.packageLevel == true
for (SuccessfulLookupResult lookupResult : lookupResults) { for (SuccessfulLookupResult lookupResult : lookupResults) {
if (lookupResult.namespaceLevel) { if (lookupResult.packageLevel) {
filteredDescriptors.addAll(lookupResult.descriptors); filteredDescriptors.addAll(lookupResult.descriptors);
continue; continue;
} }
filteredDescriptors.addAll(Collections2.filter(lookupResult.descriptors, CLASSIFIERS_AND_NAMESPACES)); filteredDescriptors.addAll(Collections2.filter(lookupResult.descriptors, CLASSIFIERS_AND_PACKAGE_VIEWS));
} }
} }
if (storeResult) { if (storeResult) {
@@ -338,7 +338,7 @@ public class QualifiedExpressionResolver {
JetScope resolutionScope = possibleResolutionScopes.iterator().next(); JetScope resolutionScope = possibleResolutionScopes.iterator().next();
// A special case - will fill all trace information // A special case - will fill all trace information
if (resolveClassNamespaceAmbiguity(canBeImportedDescriptors, referenceExpression, resolutionScope, trace, scopeToCheckVisibility)) { if (resolveClassPackageAmbiguity(canBeImportedDescriptors, referenceExpression, resolutionScope, trace, scopeToCheckVisibility)) {
return; return;
} }
@@ -379,14 +379,18 @@ public class QualifiedExpressionResolver {
} }
/** /**
* This method tries to resolve descriptors ambiguity between class descriptor and namespace descriptor for the same class. * This method tries to resolve descriptors ambiguity between class descriptor and package descriptor for the same class.
* It's ok choose class for expression reference resolution. * It's ok choose class for expression reference resolution.
* *
* @return <code>true</code> if method has successfully resolved ambiguity * @return <code>true</code> if method has successfully resolved ambiguity
*/ */
private boolean resolveClassNamespaceAmbiguity(@NotNull Collection<? extends DeclarationDescriptor> filteredDescriptors, private boolean resolveClassPackageAmbiguity(
@NotNull JetSimpleNameExpression referenceExpression, @NotNull JetScope resolutionScope, @NotNull BindingTrace trace, @NotNull Collection<? extends DeclarationDescriptor> filteredDescriptors,
@NotNull JetScope scopeToCheckVisibility) { @NotNull JetSimpleNameExpression referenceExpression,
@NotNull JetScope resolutionScope,
@NotNull BindingTrace trace,
@NotNull JetScope scopeToCheckVisibility
) {
if (filteredDescriptors.size() == 2) { if (filteredDescriptors.size() == 2) {
PackageViewDescriptor packageView = null; PackageViewDescriptor packageView = null;
@@ -430,14 +434,15 @@ public class QualifiedExpressionResolver {
private static class SuccessfulLookupResult implements LookupResult { private static class SuccessfulLookupResult implements LookupResult {
final Collection<? extends DeclarationDescriptor> descriptors; final Collection<? extends DeclarationDescriptor> descriptors;
final JetScope resolutionScope; final JetScope resolutionScope;
final boolean namespaceLevel; final boolean packageLevel;
private SuccessfulLookupResult(Collection<? extends DeclarationDescriptor> descriptors, private SuccessfulLookupResult(Collection<? extends DeclarationDescriptor> descriptors,
JetScope resolutionScope, JetScope resolutionScope,
boolean namespaceLevel) { boolean packageLevel
) {
this.descriptors = descriptors; this.descriptors = descriptors;
this.resolutionScope = resolutionScope; this.resolutionScope = resolutionScope;
this.namespaceLevel = namespaceLevel; this.packageLevel = packageLevel;
} }
} }
} }
@@ -52,7 +52,7 @@ public class TopDownAnalysisContext implements BodiesResolveContext {
private Map<JetDeclaration, CallableMemberDescriptor> members = null; private Map<JetDeclaration, CallableMemberDescriptor> members = null;
// File scopes - package scope extended with imports // File scopes - package scope extended with imports
protected final Map<JetFile, WritableScope> namespaceScopes = Maps.newHashMap(); protected final Map<JetFile, WritableScope> fileScopes = Maps.newHashMap();
public final Map<JetDeclarationContainer, DeclarationDescriptor> forDeferredResolver = Maps.newHashMap(); public final Map<JetDeclarationContainer, DeclarationDescriptor> forDeferredResolver = Maps.newHashMap();
@@ -110,8 +110,8 @@ public class TopDownAnalysisContext implements BodiesResolveContext {
return classes; return classes;
} }
public Map<JetFile, WritableScope> getNamespaceScopes() { public Map<JetFile, WritableScope> getFileScopes() {
return namespaceScopes; return fileScopes;
} }
public Map<JetFile, MutablePackageFragmentDescriptor> getPackageFragments() { public Map<JetFile, MutablePackageFragmentDescriptor> getPackageFragments() {
@@ -143,7 +143,7 @@ public class TopDownAnalyzer {
mutableClassDescriptor.lockScopes(); mutableClassDescriptor.lockScopes();
} }
Set<FqName> scriptFqNames = Sets.newHashSet(); Set<FqName> scriptFqNames = Sets.newHashSet();
for (JetFile file : context.getNamespaceScopes().keySet()) { for (JetFile file : context.getFileScopes().keySet()) {
if (file.isScript()) { if (file.isScript()) {
scriptFqNames.add(JetPsiUtil.getFQName(file)); scriptFqNames.add(JetPsiUtil.getFQName(file));
} }
@@ -213,13 +213,13 @@ public class TopDownAnalyzer {
// "depend on" builtins module // "depend on" builtins module
((ModuleDescriptorImpl) moduleDescriptor).addFragmentProvider(KotlinBuiltIns.getInstance().getBuiltInsModule().getPackageFragmentProvider()); ((ModuleDescriptorImpl) moduleDescriptor).addFragmentProvider(KotlinBuiltIns.getInstance().getBuiltInsModule().getPackageFragmentProvider());
// Import a scope that contains all top-level namespaces that come from dependencies // Import a scope that contains all top-level packages that come from dependencies
// This makes the namespaces visible at all, does not import themselves // This makes the package visible at all, does not import themselves
PackageViewDescriptor rootPackage = moduleDescriptor.getPackage(FqName.ROOT); PackageViewDescriptor rootPackage = moduleDescriptor.getPackage(FqName.ROOT);
assert rootPackage != null : "Coulnd't find root package for " + moduleDescriptor; assert rootPackage != null : "Coulnd't find root package for " + moduleDescriptor;
// dummy builder is used because "root" is module descriptor, // dummy builder is used because "root" is module descriptor,
// namespaces added to module explicitly in // packages added to module explicitly in
doProcess(rootPackage.getMemberScope(), new PackageLikeBuilderDummy(), files); doProcess(rootPackage.getMemberScope(), new PackageLikeBuilderDummy(), files);
} }
@@ -96,9 +96,9 @@ public class TypeHierarchyResolver {
) { ) {
{ {
// TODO: Very temp code - main goal is to remove recursion from collectNamespacesAndClassifiers // TODO: Very temp code - main goal is to remove recursion from collectPackageFragmentsAndClassifiers
Queue<JetDeclarationContainer> forDeferredResolve = new LinkedList<JetDeclarationContainer>(); Queue<JetDeclarationContainer> forDeferredResolve = new LinkedList<JetDeclarationContainer>();
forDeferredResolve.addAll(collectNamespacesAndClassifiers(outerScope, owner, declarations)); forDeferredResolve.addAll(collectPackageFragmentsAndClassifiers(outerScope, owner, declarations));
while (!forDeferredResolve.isEmpty()) { while (!forDeferredResolve.isEmpty()) {
JetDeclarationContainer declarationContainer = forDeferredResolve.poll(); JetDeclarationContainer declarationContainer = forDeferredResolve.poll();
@@ -110,14 +110,14 @@ public class TypeHierarchyResolver {
// Even more temp code // Even more temp code
if (descriptorForDeferredResolve instanceof MutableClassDescriptorLite) { if (descriptorForDeferredResolve instanceof MutableClassDescriptorLite) {
forDeferredResolve.addAll( forDeferredResolve.addAll(
collectNamespacesAndClassifiers( collectPackageFragmentsAndClassifiers(
scope, scope,
((MutableClassDescriptorLite) descriptorForDeferredResolve).getBuilder(), ((MutableClassDescriptorLite) descriptorForDeferredResolve).getBuilder(),
declarationContainer.getDeclarations())); declarationContainer.getDeclarations()));
} }
else if (descriptorForDeferredResolve instanceof MutablePackageFragmentDescriptor) { else if (descriptorForDeferredResolve instanceof MutablePackageFragmentDescriptor) {
forDeferredResolve.addAll( forDeferredResolve.addAll(
collectNamespacesAndClassifiers( collectPackageFragmentsAndClassifiers(
scope, scope,
((MutablePackageFragmentDescriptor) descriptorForDeferredResolve).getBuilder(), ((MutablePackageFragmentDescriptor) descriptorForDeferredResolve).getBuilder(),
declarationContainer.getDeclarations())); declarationContainer.getDeclarations()));
@@ -147,7 +147,7 @@ public class TypeHierarchyResolver {
} }
@NotNull @NotNull
private Collection<JetDeclarationContainer> collectNamespacesAndClassifiers( private Collection<JetDeclarationContainer> collectPackageFragmentsAndClassifiers(
@NotNull JetScope outerScope, @NotNull JetScope outerScope,
@NotNull PackageLikeBuilder owner, @NotNull PackageLikeBuilder owner,
@NotNull Iterable<? extends PsiElement> declarations @NotNull Iterable<? extends PsiElement> declarations
@@ -465,7 +465,7 @@ public class TypeHierarchyResolver {
WriteThroughScope packageScope = new WriteThroughScope(rootPlusPackageScope, packageFragment.getMemberScope(), WriteThroughScope packageScope = new WriteThroughScope(rootPlusPackageScope, packageFragment.getMemberScope(),
new TraceBasedRedeclarationHandler(trace), "package in file " + file.getName()); new TraceBasedRedeclarationHandler(trace), "package in file " + file.getName());
packageScope.changeLockLevel(WritableScope.LockLevel.BOTH); packageScope.changeLockLevel(WritableScope.LockLevel.BOTH);
context.getNamespaceScopes().put(file, packageScope); context.getFileScopes().put(file, packageScope);
if (file.isScript()) { if (file.isScript()) {
scriptHeaderResolver.processScriptHierarchy(file.getScript(), packageScope); scriptHeaderResolver.processScriptHierarchy(file.getScript(), packageScope);
@@ -560,7 +560,7 @@ public class TypeHierarchyResolver {
trace.record(BindingContext.FILE_TO_PACKAGE_FRAGMENT, file, fragment); trace.record(BindingContext.FILE_TO_PACKAGE_FRAGMENT, file, fragment);
// Register files corresponding to this namespace // Register files corresponding to this package
// The trace currently does not support bi-di multimaps that would handle this task nicer // The trace currently does not support bi-di multimaps that would handle this task nicer
FqName fqName = fragment.getFqName(); FqName fqName = fragment.getFqName();
Collection<JetFile> files = trace.get(PACKAGE_TO_FILES, fqName); Collection<JetFile> files = trace.get(PACKAGE_TO_FILES, fqName);
@@ -77,7 +77,7 @@ public class CallExpressionResolver {
} }
@Nullable @Nullable
private JetType lookupNamespaceOrClassObject(@NotNull JetSimpleNameExpression expression, @NotNull ExpressionTypingContext context) { private JetType lookupPackageOrClassObject(@NotNull JetSimpleNameExpression expression, @NotNull ExpressionTypingContext context) {
Name referencedName = expression.getReferencedNameAsName(); Name referencedName = expression.getReferencedNameAsName();
final ClassifierDescriptor classifier = context.scope.getClassifier(referencedName); final ClassifierDescriptor classifier = context.scope.getClassifier(referencedName);
if (classifier != null) { if (classifier != null) {
@@ -91,12 +91,12 @@ public class CallExpressionResolver {
} }
JetType[] result = new JetType[1]; JetType[] result = new JetType[1];
TemporaryBindingTrace temporaryTrace = TemporaryBindingTrace.create( TemporaryBindingTrace temporaryTrace = TemporaryBindingTrace.create(
context.trace, "trace for namespace/class object lookup of name", referencedName); context.trace, "trace for package/class object lookup of name", referencedName);
if (furtherNameLookup(expression, result, context.replaceBindingTrace(temporaryTrace))) { if (furtherNameLookup(expression, result, context.replaceBindingTrace(temporaryTrace))) {
temporaryTrace.commit(); temporaryTrace.commit();
return DataFlowUtils.checkType(result[0], expression, context); return DataFlowUtils.checkType(result[0], expression, context);
} }
// To report NO_CLASS_OBJECT when no namespace found // To report NO_CLASS_OBJECT when no package found
if (classifier != null) { if (classifier != null) {
if (classifier instanceof TypeParameterDescriptor) { if (classifier instanceof TypeParameterDescriptor) {
if (isLHSOfDot(expression)) { if (isLHSOfDot(expression)) {
@@ -172,10 +172,10 @@ public class CallExpressionResolver {
scopes.add(getStaticNestedClassesScope(classDescriptor)); scopes.add(getStaticNestedClassesScope(classDescriptor));
Name referencedName = expression.getReferencedNameAsName(); Name referencedName = expression.getReferencedNameAsName();
PackageViewDescriptor namespace = context.scope.getPackage(referencedName); PackageViewDescriptor packageView = context.scope.getPackage(referencedName);
if (namespace != null) { if (packageView != null) {
//for enums loaded from java binaries //for enums loaded from java binaries
scopes.add(namespace.getMemberScope()); scopes.add(packageView.getMemberScope());
} }
JetScope scope = new ChainedScope( JetScope scope = new ChainedScope(
@@ -265,11 +265,11 @@ public class CallExpressionResolver {
ExpressionTypingContext newContext = receiver.exists() ExpressionTypingContext newContext = receiver.exists()
? context.replaceScope(receiver.getType().getMemberScope()) ? context.replaceScope(receiver.getType().getMemberScope())
: context; : context;
TemporaryTraceAndCache temporaryForNamespaceOrClassObject = TemporaryTraceAndCache.create( TemporaryTraceAndCache temporaryForPackageOrClassObject = TemporaryTraceAndCache.create(
context, "trace to resolve as namespace or class object", nameExpression); context, "trace to resolve as package or class object", nameExpression);
JetType jetType = lookupNamespaceOrClassObject(nameExpression, newContext.replaceTraceAndCache(temporaryForNamespaceOrClassObject)); JetType jetType = lookupPackageOrClassObject(nameExpression, newContext.replaceTraceAndCache(temporaryForPackageOrClassObject));
if (jetType != null) { if (jetType != null) {
temporaryForNamespaceOrClassObject.commit(); temporaryForPackageOrClassObject.commit();
// Uncommitted changes in temp context // Uncommitted changes in temp context
context.trace.record(RESOLUTION_SCOPE, nameExpression, context.scope); context.trace.record(RESOLUTION_SCOPE, nameExpression, context.scope);
@@ -89,12 +89,12 @@ public class DataFlowValueFactory {
private static class IdentifierInfo { private static class IdentifierInfo {
public final Object id; public final Object id;
public final boolean isStable; public final boolean isStable;
public final boolean isNamespace; public final boolean isPackage;
private IdentifierInfo(Object id, boolean isStable, boolean isNamespace) { private IdentifierInfo(Object id, boolean isStable, boolean isPackage) {
this.id = id; this.id = id;
this.isStable = isStable; this.isStable = isStable;
this.isNamespace = isNamespace; this.isPackage = isPackage;
} }
} }
@@ -120,7 +120,7 @@ public class DataFlowValueFactory {
if (selectorInfo.id == null) { if (selectorInfo.id == null) {
return NO_IDENTIFIER_INFO; return NO_IDENTIFIER_INFO;
} }
if (receiverInfo == null || receiverInfo == NO_IDENTIFIER_INFO || receiverInfo.isNamespace) { if (receiverInfo == null || receiverInfo == NO_IDENTIFIER_INFO || receiverInfo.isPackage) {
return selectorInfo; return selectorInfo;
} }
return createInfo(Pair.create(receiverInfo.id, selectorInfo.id), receiverInfo.isStable && selectorInfo.isStable); return createInfo(Pair.create(receiverInfo.id, selectorInfo.id), receiverInfo.isStable && selectorInfo.isStable);
@@ -58,7 +58,7 @@ public class FileBasedPackageMemberDeclarationProvider extends AbstractPsiBasedD
protected void doCreateIndex(@NotNull Index index) { protected void doCreateIndex(@NotNull Index index) {
for (JetFile file : packageFiles) { for (JetFile file : packageFiles) {
for (JetDeclaration declaration : file.getDeclarations()) { for (JetDeclaration declaration : file.getDeclarations()) {
assert fqName.asString().equals(file.getPackageName()) : "Files declaration utils contains file with invalid namespace"; assert fqName.asString().equals(file.getPackageName()) : "Files declaration utils contains file with invalid package";
index.putToIndex(declaration); index.putToIndex(declaration);
} }
} }
@@ -51,7 +51,7 @@ public class StubClassBuilder extends ClassBuilder {
private final StubElement parent; private final StubElement parent;
private StubBuildingVisitor v; private StubBuildingVisitor v;
private final Stack<StubElement> parentStack; private final Stack<StubElement> parentStack;
private boolean isNamespace = false; private boolean isPackageClass = false;
public StubClassBuilder(@NotNull Stack<StubElement> parentStack) { public StubClassBuilder(@NotNull Stack<StubElement> parentStack) {
this.parentStack = parentStack; this.parentStack = parentStack;
@@ -85,11 +85,11 @@ public class StubClassBuilder extends ClassBuilder {
String packageClassName = PackageClassUtils.getPackageClassName(packageName); String packageClassName = PackageClassUtils.getPackageClassName(packageName);
if (name.equals(packageClassName) || name.endsWith("/" + packageClassName)) { if (name.equals(packageClassName) || name.endsWith("/" + packageClassName)) {
isNamespace = true; isPackageClass = true;
} }
} }
if (!isNamespace) { if (!isPackageClass) {
parentStack.push(v.getResult()); parentStack.push(v.getResult());
} }
@@ -150,7 +150,7 @@ public class StubClassBuilder extends ClassBuilder {
@Override @Override
public void done() { public void done() {
if (!isNamespace) { if (!isPackageClass) {
StubElement pop = parentStack.pop(); StubElement pop = parentStack.pop();
assert pop == v.getResult(); assert pop == v.getResult();
} }
@@ -220,8 +220,8 @@ public class JetTestUtils {
private JetTestUtils() { private JetTestUtils() {
} }
public static AnalyzeExhaust analyzeFile(@NotNull JetFile namespace) { public static AnalyzeExhaust analyzeFile(@NotNull JetFile file) {
return AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegration(namespace, Collections.<AnalyzerScriptParameter>emptyList()); return AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegration(file, Collections.<AnalyzerScriptParameter>emptyList());
} }
@NotNull @NotNull
@@ -47,8 +47,8 @@ public class JUnitUsageGenTest extends CodegenTestCase {
public void testKt1592() throws Exception { public void testKt1592() throws Exception {
loadFile("junit/kt1592.kt"); loadFile("junit/kt1592.kt");
Class<?> namespaceClass = generatePackageClass(); Class<?> packageClass = generatePackageClass();
Method method = namespaceClass.getMethod("foo", Method.class); Method method = packageClass.getMethod("foo", Method.class);
method.setAccessible(true); method.setAccessible(true);
Annotation annotation = method.getAnnotation(getCorrespondingAnnotationClass(Test.class)); Annotation annotation = method.getAnnotation(getCorrespondingAnnotationClass(Test.class));
assertEquals(ClassLoaderIsolationUtil.getAnnotationAttribute(annotation, "timeout"), 0l); assertEquals(ClassLoaderIsolationUtil.getAnnotationAttribute(annotation, "timeout"), 0l);
@@ -30,7 +30,7 @@ import java.util.Set;
import static org.jetbrains.jet.codegen.KotlinPackageAnnotationTest.collectCallableNames; import static org.jetbrains.jet.codegen.KotlinPackageAnnotationTest.collectCallableNames;
public class KotlinClassAnnotationTest extends CodegenTestCase { public class KotlinClassAnnotationTest extends CodegenTestCase {
public static final FqName NAMESPACE_NAME = new FqName("test"); public static final FqName PACKAGE_NAME = new FqName("test");
public static final FqNameUnsafe CLASS_NAME = new FqNameUnsafe("A"); public static final FqNameUnsafe CLASS_NAME = new FqNameUnsafe("A");
@Override @Override
@@ -40,13 +40,13 @@ public class KotlinClassAnnotationTest extends CodegenTestCase {
} }
public void testClassKotlinInfo() throws Exception { public void testClassKotlinInfo() throws Exception {
loadText("package " + NAMESPACE_NAME + "\n" + loadText("package " + PACKAGE_NAME + "\n" +
"\n" + "\n" +
"class " + CLASS_NAME + " {\n" + "class " + CLASS_NAME + " {\n" +
" fun foo() {}\n" + " fun foo() {}\n" +
" fun bar() = 42\n" + " fun bar() = 42\n" +
"}\n"); "}\n");
Class aClass = generateClass(NAMESPACE_NAME + "." + CLASS_NAME); Class aClass = generateClass(PACKAGE_NAME + "." + CLASS_NAME);
Class<? extends Annotation> annotationClass = getCorrespondingAnnotationClass(KotlinClass.class); Class<? extends Annotation> annotationClass = getCorrespondingAnnotationClass(KotlinClass.class);
assertTrue(aClass.isAnnotationPresent(annotationClass)); assertTrue(aClass.isAnnotationPresent(annotationClass));
@@ -33,7 +33,7 @@ import java.util.List;
import java.util.Set; import java.util.Set;
public class KotlinPackageAnnotationTest extends CodegenTestCase { public class KotlinPackageAnnotationTest extends CodegenTestCase {
public static final FqName NAMESPACE_NAME = new FqName("test"); public static final FqName PACKAGE_NAME = new FqName("test");
@Override @Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
@@ -42,7 +42,7 @@ public class KotlinPackageAnnotationTest extends CodegenTestCase {
} }
public void testPackageKotlinInfo() throws Exception { public void testPackageKotlinInfo() throws Exception {
loadText("package " + NAMESPACE_NAME + "\n" + loadText("package " + PACKAGE_NAME + "\n" +
"\n" + "\n" +
"fun foo() = 42\n" + "fun foo() = 42\n" +
"val bar = 239\n" + "val bar = 239\n" +
@@ -50,7 +50,7 @@ public class KotlinPackageAnnotationTest extends CodegenTestCase {
"class A\n" + "class A\n" +
"class B\n" + "class B\n" +
"object C\n"); "object C\n");
Class aClass = generateClass(PackageClassUtils.getPackageClassFqName(NAMESPACE_NAME).asString()); Class aClass = generateClass(PackageClassUtils.getPackageClassFqName(PACKAGE_NAME).asString());
Class<? extends Annotation> annotationClass = getCorrespondingAnnotationClass(KotlinPackage.class); Class<? extends Annotation> annotationClass = getCorrespondingAnnotationClass(KotlinPackage.class);
assertTrue(aClass.isAnnotationPresent(annotationClass)); assertTrue(aClass.isAnnotationPresent(annotationClass));
@@ -28,7 +28,7 @@ import org.jetbrains.jet.lang.resolve.name.FqName;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
public class KotlinPackageFragmentAnnotationTest extends CodegenTestCase { public class KotlinPackageFragmentAnnotationTest extends CodegenTestCase {
public static final FqName NAMESPACE_NAME = new FqName("test"); public static final FqName PACKAGE_NAME = new FqName("test");
@Override @Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
@@ -37,8 +37,8 @@ public class KotlinPackageFragmentAnnotationTest extends CodegenTestCase {
} }
public void testKotlinPackageFragmentIsWritten() throws Exception { public void testKotlinPackageFragmentIsWritten() throws Exception {
loadText("package " + NAMESPACE_NAME + "\n\nfun foo() = 42\n"); loadText("package " + PACKAGE_NAME + "\n\nfun foo() = 42\n");
String facadeFileName = JvmClassName.byFqNameWithoutInnerClasses(PackageClassUtils.getPackageClassFqName(NAMESPACE_NAME)).getInternalName() + ".class"; String facadeFileName = JvmClassName.byFqNameWithoutInnerClasses(PackageClassUtils.getPackageClassFqName(PACKAGE_NAME)).getInternalName() + ".class";
OutputFileCollection outputFiles = generateClassesInFile(); OutputFileCollection outputFiles = generateClassesInFile();
for (OutputFile outputFile : outputFiles.asList()) { for (OutputFile outputFile : outputFiles.asList()) {
@@ -333,7 +333,7 @@ public class LineNumberTest extends TestCaseWithTmpdir {
assertNotNull(file); assertNotNull(file);
ClassReader reader = new ClassReader(file.asByteArray()); ClassReader reader = new ClassReader(file.asByteArray());
// There must be exactly one line number attribute for each static delegate in namespace.class, and it should point to the first // There must be exactly one line number attribute for each static delegate in package facade class, and it should point to the first
// line. There are two static delegates in this test, hence the [1, 1] // line. There are two static delegates in this test, hence the [1, 1]
List<Integer> expectedLineNumbers = Arrays.asList(1, 1); List<Integer> expectedLineNumbers = Arrays.asList(1, 1);
List<Integer> actualLineNumbers = readAllLineNumbers(reader); List<Integer> actualLineNumbers = readAllLineNumbers(reader);
@@ -16,7 +16,6 @@
package org.jetbrains.jet.codegen; package org.jetbrains.jet.codegen;
import jet.IntRange;
import org.jetbrains.jet.ConfigurationKind; import org.jetbrains.jet.ConfigurationKind;
import java.awt.*; import java.awt.*;
@@ -27,7 +26,7 @@ import java.util.Arrays;
import static org.jetbrains.jet.codegen.CodegenTestUtil.assertIsCurrentTime; import static org.jetbrains.jet.codegen.CodegenTestUtil.assertIsCurrentTime;
public class NamespaceGenTest extends CodegenTestCase { public class PackageGenTest extends CodegenTestCase {
@Override @Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
@@ -74,7 +74,7 @@ public class PropertyGenTest extends CodegenTestCase {
assertNotNull(findDeclaredMethodByName(aClass, "setFoo")); assertNotNull(findDeclaredMethodByName(aClass, "setFoo"));
} }
public void testPrivatePropertyInNamespace() throws Exception { public void testPrivatePropertyInPackage() throws Exception {
loadText("private val x = 239"); loadText("private val x = 239");
Class nsClass = generatePackagePartClass(); Class nsClass = generatePackagePartClass();
Field[] fields = nsClass.getDeclaredFields(); Field[] fields = nsClass.getDeclaredFields();
@@ -135,7 +135,7 @@ public class PropertyGenTest extends CodegenTestCase {
assertEquals(610, getFoo.invoke(instance)); assertEquals(610, getFoo.invoke(instance));
} }
public void testInitializersForNamespaceProperties() throws Exception { public void testInitializersForTopLevelProperties() throws Exception {
loadText("val x = System.currentTimeMillis()"); loadText("val x = System.currentTimeMillis()");
Method method = generateFunction("getX"); Method method = generateFunction("getX");
method.setAccessible(true); method.setAccessible(true);
@@ -28,13 +28,13 @@ public class SourceInfoGenTest extends CodegenTestCase {
createEnvironmentWithMockJdkAndIdeaAnnotations(ConfigurationKind.JDK_ONLY); createEnvironmentWithMockJdkAndIdeaAnnotations(ConfigurationKind.JDK_ONLY);
} }
public void testSingleFileNamespace() { public void testSingleFilePackage() {
String producer = "sourceInfo/foo1.kt"; String producer = "sourceInfo/foo1.kt";
loadFiles(producer); loadFiles(producer);
assertEquals(producer, getProducerInfo("foo/FooPackage.class")); assertEquals(producer, getProducerInfo("foo/FooPackage.class"));
} }
public void testMultiFileNamespace() { public void testMultiFilePackage() {
loadFiles("sourceInfo/foo1.kt", "sourceInfo/foo2.kt"); loadFiles("sourceInfo/foo1.kt", "sourceInfo/foo2.kt");
assertEquals(null, getProducerInfo("foo/FooPackage.class")); assertEquals(null, getProducerInfo("foo/FooPackage.class"));
} }
@@ -56,7 +56,7 @@ import static org.jetbrains.jet.test.util.DescriptorValidator.ValidationVisitor.
import static org.jetbrains.jet.test.util.RecursiveDescriptorComparator.*; import static org.jetbrains.jet.test.util.RecursiveDescriptorComparator.*;
/* /*
The generated test compares namespace descriptors loaded from kotlin sources and read from compiled java. The generated test compares package descriptors loaded from kotlin sources and read from compiled java.
*/ */
public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir { public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
protected void doTestCompiledJava(@NotNull String javaFileName) throws Exception { protected void doTestCompiledJava(@NotNull String javaFileName) throws Exception {
@@ -153,7 +153,7 @@ public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
injectorForAnalyzer.getTopDownAnalyzer().analyzeFiles(environment.getSourceFiles(), Collections.<AnalyzerScriptParameter>emptyList()); injectorForAnalyzer.getTopDownAnalyzer().analyzeFiles(environment.getSourceFiles(), Collections.<AnalyzerScriptParameter>emptyList());
PackageViewDescriptor packageView = module.getPackage(TEST_PACKAGE_FQNAME); PackageViewDescriptor packageView = module.getPackage(TEST_PACKAGE_FQNAME);
assert packageView != null : "Test namespace not found"; assert packageView != null : "Test package not found";
checkJavaPackage(expectedFile, packageView, trace.getBindingContext(), DONT_INCLUDE_METHODS_OF_OBJECT); checkJavaPackage(expectedFile, packageView, trace.getBindingContext(), DONT_INCLUDE_METHODS_OF_OBJECT);
} }
@@ -166,10 +166,10 @@ public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
assertTrue(testPackageDir.mkdir()); assertTrue(testPackageDir.mkdir());
FileUtil.copy(originalJavaFile, new File(testPackageDir, originalJavaFile.getName())); FileUtil.copy(originalJavaFile, new File(testPackageDir, originalJavaFile.getName()));
Pair<PackageViewDescriptor, BindingContext> javaNamespaceAndContext = loadTestPackageAndBindingContextFromJavaRoot( Pair<PackageViewDescriptor, BindingContext> javaPackageAndContext = loadTestPackageAndBindingContextFromJavaRoot(
tmpdir, getTestRootDisposable(), ConfigurationKind.JDK_ONLY); tmpdir, getTestRootDisposable(), ConfigurationKind.JDK_ONLY);
checkJavaPackage(expectedFile, javaNamespaceAndContext.first, javaNamespaceAndContext.second, checkJavaPackage(expectedFile, javaPackageAndContext.first, javaPackageAndContext.second,
DONT_INCLUDE_METHODS_OF_OBJECT.withValidationStrategy(ALLOW_ERROR_TYPES)); DONT_INCLUDE_METHODS_OF_OBJECT.withValidationStrategy(ALLOW_ERROR_TYPES));
} }
@@ -207,7 +207,7 @@ public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
private static void checkForLoadErrorsAndCompare( private static void checkForLoadErrorsAndCompare(
@NotNull PackageViewDescriptor javaPackage, @NotNull PackageViewDescriptor javaPackage,
@NotNull BindingContext bindingContext, @NotNull BindingContext bindingContext,
@NotNull Runnable compareNamespacesRunnable @NotNull Runnable comparePackagesRunnable
) { ) {
boolean fail = false; boolean fail = false;
try { try {
@@ -225,7 +225,7 @@ public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
fail = true; fail = true;
} }
compareNamespacesRunnable.run(); comparePackagesRunnable.run();
if (fail) { if (fail) {
fail("See error above"); fail("See error above");
} }
@@ -81,7 +81,7 @@ public class CompileKotlinAgainstCustomBinariesTest extends TestCaseWithTmpdir {
); );
PackageViewDescriptor packageView = exhaust.getModuleDescriptor().getPackage(LoadDescriptorUtil.TEST_PACKAGE_FQNAME); PackageViewDescriptor packageView = exhaust.getModuleDescriptor().getPackage(LoadDescriptorUtil.TEST_PACKAGE_FQNAME);
assertNotNull("Failed to find namespace: " + LoadDescriptorUtil.TEST_PACKAGE_FQNAME, packageView); assertNotNull("Failed to find package: " + LoadDescriptorUtil.TEST_PACKAGE_FQNAME, packageView);
return packageView; return packageView;
} }
@@ -50,7 +50,7 @@ public abstract class AbstractLazyResolveDiagnosticsTest extends BaseDiagnostics
String txtFileRelativePath = path.replaceAll("\\.kt$|\\.ktscript", ".txt"); String txtFileRelativePath = path.replaceAll("\\.kt$|\\.ktscript", ".txt");
File txtFile = new File("compiler/testData/lazyResolve/diagnostics/" + txtFileRelativePath); File txtFile = new File("compiler/testData/lazyResolve/diagnostics/" + txtFileRelativePath);
// Only recurse into those namespaces mentioned in the files // Only recurse into those packages mentioned in the files
// Otherwise we'll be examining the whole JDK // Otherwise we'll be examining the whole JDK
final Set<Name> names = LazyResolveTestUtil.getTopLevelPackagesFromFileList(jetFiles); final Set<Name> names = LazyResolveTestUtil.getTopLevelPackagesFromFileList(jetFiles);
validateAndCompareDescriptors( validateAndCompareDescriptors(
@@ -46,12 +46,12 @@ public class LazyResolveStdlibLoadingTest extends KotlinTestWithEnvironmentManag
protected void doTestForGivenFiles( protected void doTestForGivenFiles(
List<JetFile> files List<JetFile> files
) { ) {
Set<Name> namespaceShortNames = LazyResolveTestUtil.getTopLevelPackagesFromFileList(files); Set<Name> packageShortNames = LazyResolveTestUtil.getTopLevelPackagesFromFileList(files);
ModuleDescriptor module = LazyResolveTestUtil.resolveEagerly(files, stdlibEnvironment); ModuleDescriptor module = LazyResolveTestUtil.resolveEagerly(files, stdlibEnvironment);
ModuleDescriptor lazyModule = LazyResolveTestUtil.resolveLazily(files, stdlibEnvironment); ModuleDescriptor lazyModule = LazyResolveTestUtil.resolveLazily(files, stdlibEnvironment);
for (Name name : namespaceShortNames) { for (Name name : packageShortNames) {
PackageViewDescriptor eager = module.getPackage(FqName.topLevel(name)); PackageViewDescriptor eager = module.getPackage(FqName.topLevel(name));
PackageViewDescriptor lazy = lazyModule.getPackage(FqName.topLevel(name)); PackageViewDescriptor lazy = lazyModule.getPackage(FqName.topLevel(name));
RecursiveDescriptorComparator.validateAndCompareDescriptors(eager, lazy, RecursiveDescriptorComparator.RECURSIVE, null); RecursiveDescriptorComparator.validateAndCompareDescriptors(eager, lazy, RecursiveDescriptorComparator.RECURSIVE, null);
@@ -269,7 +269,7 @@ public abstract class AbstractAnnotationDescriptorResolveTest extends JetLiteFix
context = analyzeExhaust.getBindingContext(); context = analyzeExhaust.getBindingContext();
PackageViewDescriptor packageView = analyzeExhaust.getModuleDescriptor().getPackage(PACKAGE); PackageViewDescriptor packageView = analyzeExhaust.getModuleDescriptor().getPackage(PACKAGE);
assertNotNull("Failed to find namespace: " + PACKAGE, packageView); assertNotNull("Failed to find package: " + PACKAGE, packageView);
return packageView; return packageView;
} }
@@ -155,7 +155,7 @@ public final class JavaFunctionResolver {
signatureErrors.addAll(effectiveSignature.getErrors()); signatureErrors.addAll(effectiveSignature.getErrors());
} }
else { else {
throw new IllegalStateException("Unknown class or namespace descriptor: " + ownerDescriptor); throw new IllegalStateException("Unknown class or package descriptor: " + ownerDescriptor);
} }
functionDescriptorImpl.initialize( functionDescriptorImpl.initialize(
@@ -263,7 +263,7 @@ public class AnnotationDescriptorDeserializer implements AnnotationDeserializer
} }
else if (isTrait(container) && kind == AnnotatedCallableKind.PROPERTY) { else if (isTrait(container) && kind == AnnotatedCallableKind.PROPERTY) {
PackageFragmentDescriptor containingPackage = DescriptorUtils.getParentOfType(container, PackageFragmentDescriptor.class); PackageFragmentDescriptor containingPackage = DescriptorUtils.getParentOfType(container, PackageFragmentDescriptor.class);
assert containingPackage != null : "Trait must have a namespace among his parents: " + container; assert containingPackage != null : "Trait must have a package fragment among his parents: " + container;
if (proto.hasExtension(JavaProtoBuf.implClassName)) { if (proto.hasExtension(JavaProtoBuf.implClassName)) {
Name tImplName = nameResolver.getName(proto.getExtension(JavaProtoBuf.implClassName)); Name tImplName = nameResolver.getName(proto.getExtension(JavaProtoBuf.implClassName));
+1 -1
View File
@@ -122,7 +122,7 @@ atomicExpression
: loop : loop
: SimpleName : SimpleName
: FieldName : FieldName
: "namespace" // for the root namespace : "package" // for the root package
; ;
label label
+1 -1
View File
@@ -83,7 +83,7 @@ bq. See [Nonlocal returns and jumps]
*/ */
/* Keywords: /* Keywords:
namespace package
as as
type type
class class
+1 -1
View File
@@ -32,7 +32,7 @@ selfType
; ;
userType userType
: ("namespace" ".")? simpleUserType{"."} : ("package" ".")? simpleUserType{"."}
; ;
simpleUserType simpleUserType
@@ -186,7 +186,7 @@ public class JetPositionManager implements PositionManager {
AnalyzeExhaust analyzeExhaust = AnalyzerFacadeWithCache.analyzeFileWithCache(file); AnalyzeExhaust analyzeExhaust = AnalyzerFacadeWithCache.analyzeFileWithCache(file);
analyzeExhaust.throwIfError(); analyzeExhaust.throwIfError();
Collection<JetFile> namespaceFiles = JetFilesProvider.getInstance(file.getProject()).allNamespaceFiles().fun(file); Collection<JetFile> namespaceFiles = JetFilesProvider.getInstance(file.getProject()).allPackageFiles().fun(file);
DelegatingBindingTrace bindingTrace = new DelegatingBindingTrace(analyzeExhaust.getBindingContext(), "trace created in JetPositionManager"); DelegatingBindingTrace bindingTrace = new DelegatingBindingTrace(analyzeExhaust.getBindingContext(), "trace created in JetPositionManager");
JetTypeMapper typeMapper = new JetTypeMapper(bindingTrace, ClassBuilderMode.FULL); JetTypeMapper typeMapper = new JetTypeMapper(bindingTrace, ClassBuilderMode.FULL);
@@ -64,7 +64,7 @@ public class DebuggerUtils {
return anyFile; return anyFile;
} }
Collection<JetFile> allNamespaceFiles = filesProvider.allNamespaceFiles().fun(anyFile); Collection<JetFile> allNamespaceFiles = filesProvider.allPackageFiles().fun(anyFile);
JetFile file = PsiCodegenPredictor.getFileForPackagePartName(allNamespaceFiles, className); JetFile file = PsiCodegenPredictor.getFileForPackagePartName(allNamespaceFiles, className);
if (file != null) { if (file != null) {
return file; return file;
@@ -36,18 +36,20 @@ public abstract class MultipleFilesTranslationTest extends BasicTest {
generateJavaScriptFiles(fullFilePaths, dirName, MainCallParameters.noCall(), ecmaVersions); generateJavaScriptFiles(fullFilePaths, dirName, MainCallParameters.noCall(), ecmaVersions);
} }
protected void runMultiFileTest(@NotNull String dirName, @NotNull String namespaceName, protected void runMultiFileTest(@NotNull String dirName, @NotNull String packageName,
@NotNull String functionName, @NotNull Object expectedResult) throws Exception { @NotNull String functionName, @NotNull Object expectedResult) throws Exception {
runMultiFileTests(DEFAULT_ECMA_VERSIONS, dirName, namespaceName, functionName, expectedResult); runMultiFileTests(DEFAULT_ECMA_VERSIONS, dirName, packageName, functionName, expectedResult);
} }
protected void runMultiFileTests(@NotNull Iterable<EcmaVersion> ecmaVersions, @NotNull String dirName, protected void runMultiFileTests(
@NotNull String namespaceName, @NotNull Iterable<EcmaVersion> ecmaVersions,
@NotNull String dirName,
@NotNull String packageName,
@NotNull String functionName, @NotNull String functionName,
@NotNull Object expectedResult) @NotNull Object expectedResult
throws Exception { ) throws Exception {
generateJsFromDir(dirName, ecmaVersions); generateJsFromDir(dirName, ecmaVersions);
runRhinoTests(dirName + ".kt", ecmaVersions, new RhinoFunctionResultChecker(namespaceName, functionName, expectedResult)); runRhinoTests(dirName + ".kt", ecmaVersions, new RhinoFunctionResultChecker(packageName, functionName, expectedResult));
} }
public void checkFooBoxIsTrue(@NotNull String dirName) throws Exception { public void checkFooBoxIsTrue(@NotNull String dirName) throws Exception {
@@ -77,11 +77,11 @@ public final class OutputPrefixPostfixTest extends SingleFileTranslationTest {
protected void runFunctionOutputTest( protected void runFunctionOutputTest(
@NotNull Iterable<EcmaVersion> ecmaVersions, @NotNull Iterable<EcmaVersion> ecmaVersions,
@NotNull String kotlinFilename, @NotNull String kotlinFilename,
@NotNull String namespaceName, @NotNull String packageName,
@NotNull String functionName, @NotNull String functionName,
@NotNull Object expectedResult @NotNull Object expectedResult
) throws Exception { ) throws Exception {
super.runFunctionOutputTest(ecmaVersions, kotlinFilename, namespaceName, functionName, expectedResult); super.runFunctionOutputTest(ecmaVersions, kotlinFilename, packageName, functionName, expectedResult);
for (EcmaVersion ecmaVersion : ecmaVersions) { for (EcmaVersion ecmaVersion : ecmaVersions) {
String output = FileUtil.loadFile(new File(getOutputFilePath(filename, ecmaVersion))); String output = FileUtil.loadFile(new File(getOutputFilePath(filename, ecmaVersion)));
@@ -31,17 +31,19 @@ public abstract class SingleFileTranslationTest extends BasicTest {
super(main); super(main);
} }
public void runFunctionOutputTest(@NotNull String kotlinFilename, @NotNull String namespaceName, public void runFunctionOutputTest(@NotNull String kotlinFilename, @NotNull String packageName,
@NotNull String functionName, @NotNull Object expectedResult) throws Exception { @NotNull String functionName, @NotNull Object expectedResult) throws Exception {
runFunctionOutputTest(DEFAULT_ECMA_VERSIONS, kotlinFilename, namespaceName, functionName, expectedResult); runFunctionOutputTest(DEFAULT_ECMA_VERSIONS, kotlinFilename, packageName, functionName, expectedResult);
} }
protected void runFunctionOutputTest(@NotNull Iterable<EcmaVersion> ecmaVersions, @NotNull String kotlinFilename, protected void runFunctionOutputTest(
@NotNull String namespaceName, @NotNull Iterable<EcmaVersion> ecmaVersions,
@NotNull String kotlinFilename,
@NotNull String packageName,
@NotNull String functionName, @NotNull String functionName,
@NotNull Object expectedResult) throws Exception { @NotNull Object expectedResult) throws Exception {
generateJavaScriptFiles(kotlinFilename, MainCallParameters.noCall(), ecmaVersions); generateJavaScriptFiles(kotlinFilename, MainCallParameters.noCall(), ecmaVersions);
runRhinoTests(kotlinFilename, ecmaVersions, new RhinoFunctionResultChecker(namespaceName, functionName, expectedResult)); runRhinoTests(kotlinFilename, ecmaVersions, new RhinoFunctionResultChecker(packageName, functionName, expectedResult));
} }
public void checkFooBoxIsTrue(@NotNull String filename, @NotNull Iterable<EcmaVersion> ecmaVersions) throws Exception { public void checkFooBoxIsTrue(@NotNull String filename, @NotNull Iterable<EcmaVersion> ecmaVersions) throws Exception {
@@ -25,8 +25,8 @@ import org.mozilla.javascript.NativeJavaObject;
*/ */
public class RhinoFunctionNativeObjectResultChecker extends RhinoFunctionResultChecker { public class RhinoFunctionNativeObjectResultChecker extends RhinoFunctionResultChecker {
public RhinoFunctionNativeObjectResultChecker(@Nullable String namespaceName, String functionName, Object expectedResult) { public RhinoFunctionNativeObjectResultChecker(@Nullable String packageName, String functionName, Object expectedResult) {
super(namespaceName, functionName, expectedResult); super(packageName, functionName, expectedResult);
} }
public RhinoFunctionNativeObjectResultChecker(String functionName, Object expectedResult) { public RhinoFunctionNativeObjectResultChecker(String functionName, Object expectedResult) {
@@ -28,17 +28,17 @@ import static org.junit.Assert.assertEquals;
public class RhinoFunctionResultChecker implements RhinoResultChecker { public class RhinoFunctionResultChecker implements RhinoResultChecker {
private final String moduleId; private final String moduleId;
private final String namespaceName; private final String packageName;
private final String functionName; private final String functionName;
private final Object expectedResult; private final Object expectedResult;
public RhinoFunctionResultChecker(@Nullable String namespaceName, String functionName, Object expectedResult) { public RhinoFunctionResultChecker(@Nullable String packageName, String functionName, Object expectedResult) {
this(Config.REWRITABLE_MODULE_NAME, namespaceName, functionName, expectedResult); this(Config.REWRITABLE_MODULE_NAME, packageName, functionName, expectedResult);
} }
public RhinoFunctionResultChecker(@Nullable String moduleId, @Nullable String namespaceName, String functionName, Object expectedResult) { public RhinoFunctionResultChecker(@Nullable String moduleId, @Nullable String packageName, String functionName, Object expectedResult) {
this.moduleId = moduleId; this.moduleId = moduleId;
this.namespaceName = namespaceName; this.packageName = packageName;
this.functionName = functionName; this.functionName = functionName;
this.expectedResult = expectedResult; this.expectedResult = expectedResult;
} }
@@ -56,8 +56,8 @@ public class RhinoFunctionResultChecker implements RhinoResultChecker {
protected void assertResultValid(Object result, Context context) { protected void assertResultValid(Object result, Context context) {
String ecmaVersion = context.getLanguageVersion() == Context.VERSION_1_8 ? "ecma5" : "ecma3"; String ecmaVersion = context.getLanguageVersion() == Context.VERSION_1_8 ? "ecma5" : "ecma3";
assertEquals("Result of " + namespaceName + "." + functionName + "() is not what expected (" + ecmaVersion + ")!", expectedResult, result); assertEquals("Result of " + packageName + "." + functionName + "() is not what expected (" + ecmaVersion + ")!", expectedResult, result);
String report = namespaceName + "." + functionName + "() = " + Context.toString(result); String report = packageName + "." + functionName + "() = " + Context.toString(result);
System.out.println(report); System.out.println(report);
} }
@@ -67,15 +67,15 @@ public class RhinoFunctionResultChecker implements RhinoResultChecker {
protected String functionCallString() { protected String functionCallString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (namespaceName != null) { if (packageName != null) {
sb.append("Kotlin.modules"); sb.append("Kotlin.modules");
if (moduleId.contains(".")) { if (moduleId.contains(".")) {
sb.append("['").append(moduleId).append("']"); sb.append("['").append(moduleId).append("']");
} else { } else {
sb.append(".").append(moduleId); sb.append(".").append(moduleId);
} }
if (namespaceName != Namer.getRootNamespaceName()) { if (packageName != Namer.getRootPackageName()) {
sb.append('.').append(namespaceName); sb.append('.').append(packageName);
} }
sb.append('.'); sb.append('.');
} }
@@ -36,7 +36,7 @@ public final class ExamplesTest extends SingleFileTranslationTest {
@Override @Override
public void runTest() throws Exception { public void runTest() throws Exception {
runFunctionOutputTest(filename, Namer.getRootNamespaceName(), "box", "OK"); runFunctionOutputTest(filename, Namer.getRootPackageName(), "box", "OK");
} }
public static Test suite() throws Exception { public static Test suite() throws Exception {
@@ -42,7 +42,7 @@ public final class MiscTest extends AbstractExpressionTest {
} }
public void testClassWithoutNamespace() throws Exception { public void testClassWithoutNamespace() throws Exception {
runFunctionOutputTest("classWithoutNamespace.kt", Namer.getRootNamespaceName(), "box", true); runFunctionOutputTest("classWithoutNamespace.kt", Namer.getRootPackageName(), "box", true);
} }
public void testIfElseAsExpressionWithThrow() throws Exception { public void testIfElseAsExpressionWithThrow() throws Exception {
@@ -156,7 +156,7 @@ public final class MiscTest extends AbstractExpressionTest {
//TODO: see http://youtrack.jetbrains.com/issue/KT-2564 //TODO: see http://youtrack.jetbrains.com/issue/KT-2564
@SuppressWarnings("UnusedDeclaration") @SuppressWarnings("UnusedDeclaration")
public void TODO_testNamespaceLevelVarInRoot() throws Exception { public void TODO_testNamespaceLevelVarInRoot() throws Exception {
runFunctionOutputTest("namespaceLevelVarInRoot.kt", Namer.getRootNamespaceName(), "box", "OK"); runFunctionOutputTest("namespaceLevelVarInRoot.kt", Namer.getRootPackageName(), "box", "OK");
} }
public void testLazyPropertyGetterNotCalledOnStart() throws Exception { public void testLazyPropertyGetterNotCalledOnStart() throws Exception {
@@ -62,7 +62,7 @@ public final class Namer {
} }
@NotNull @NotNull
public static String getRootNamespaceName() { public static String getRootPackageName() {
return ROOT_PACKAGE; return ROOT_PACKAGE;
} }
@@ -257,8 +257,8 @@ public final class Namer {
} }
@NotNull @NotNull
static String generateNamespaceName(@NotNull FqName packageFqName) { static String generatePackageName(@NotNull FqName packageFqName) {
return packageFqName.isRoot() ? getRootNamespaceName() : packageFqName.shortName().asString(); return packageFqName.isRoot() ? getRootPackageName() : packageFqName.shortName().asString();
} }
@NotNull @NotNull
@@ -188,7 +188,7 @@ public final class StaticContext {
return ContainerUtil.getOrCreate(packageNames, packageFqName, new Factory<JsName>() { return ContainerUtil.getOrCreate(packageNames, packageFqName, new Factory<JsName>() {
@Override @Override
public JsName create() { public JsName create() {
String name = Namer.generateNamespaceName(packageFqName); String name = Namer.generatePackageName(packageFqName);
return getRootScope().declareName(name); return getRootScope().declareName(name);
} }
}); });
@@ -412,7 +412,7 @@ public final class StaticContext {
if (!(descriptor instanceof PackageFragmentDescriptor)) { if (!(descriptor instanceof PackageFragmentDescriptor)) {
return null; return null;
} }
return getRootScope().innerScope("Namespace " + descriptor.getName()); return getRootScope().innerScope("Package " + descriptor.getName());
} }
}; };
//TODO: never get there //TODO: never get there
@@ -465,7 +465,7 @@ public final class StaticContext {
} }
}; };
//TODO: review and refactor //TODO: review and refactor
Rule<JsNameRef> packageLevelDeclarationsHaveEnclosingNamespacesNamesAsQualifier = new Rule<JsNameRef>() { Rule<JsNameRef> packageLevelDeclarationsHaveEnclosingPackagesNamesAsQualifier = new Rule<JsNameRef>() {
@Override @Override
public JsNameRef apply(@NotNull DeclarationDescriptor descriptor) { public JsNameRef apply(@NotNull DeclarationDescriptor descriptor) {
DeclarationDescriptor containingDescriptor = getContainingDeclaration(descriptor); DeclarationDescriptor containingDescriptor = getContainingDeclaration(descriptor);
@@ -525,7 +525,7 @@ public final class StaticContext {
addRule(libraryObjectsHaveKotlinQualifier); addRule(libraryObjectsHaveKotlinQualifier);
addRule(constructorHaveTheSameQualifierAsTheClass); addRule(constructorHaveTheSameQualifierAsTheClass);
addRule(standardObjectsHaveKotlinQualifier); addRule(standardObjectsHaveKotlinQualifier);
addRule(packageLevelDeclarationsHaveEnclosingNamespacesNamesAsQualifier); addRule(packageLevelDeclarationsHaveEnclosingPackagesNamesAsQualifier);
} }
} }
@@ -32,16 +32,16 @@ import java.util.*;
import static com.google.dart.compiler.backend.js.ast.JsVars.JsVar; import static com.google.dart.compiler.backend.js.ast.JsVars.JsVar;
import static org.jetbrains.k2js.translate.declaration.DefineInvocation.createDefineInvocation; import static org.jetbrains.k2js.translate.declaration.DefineInvocation.createDefineInvocation;
public final class NamespaceDeclarationTranslator extends AbstractTranslator { public final class PackageDeclarationTranslator extends AbstractTranslator {
private final Iterable<JetFile> files; private final Iterable<JetFile> files;
private final Map<PackageFragmentDescriptor, NamespaceTranslator> packageFragmentToTranslator = private final Map<PackageFragmentDescriptor, PackageTranslator> packageFragmentToTranslator =
new LinkedHashMap<PackageFragmentDescriptor, NamespaceTranslator>(); new LinkedHashMap<PackageFragmentDescriptor, PackageTranslator>();
public static List<JsStatement> translateFiles(@NotNull Collection<JetFile> files, @NotNull TranslationContext context) { public static List<JsStatement> translateFiles(@NotNull Collection<JetFile> files, @NotNull TranslationContext context) {
return new NamespaceDeclarationTranslator(files, context).translate(); return new PackageDeclarationTranslator(files, context).translate();
} }
private NamespaceDeclarationTranslator(@NotNull Iterable<JetFile> files, @NotNull TranslationContext context) { private PackageDeclarationTranslator(@NotNull Iterable<JetFile> files, @NotNull TranslationContext context) {
super(context); super(context);
this.files = files; this.files = files;
@@ -55,17 +55,17 @@ public final class NamespaceDeclarationTranslator extends AbstractTranslator {
for (JetFile file : files) { for (JetFile file : files) {
PackageFragmentDescriptor packageFragment = context().bindingContext().get(BindingContext.FILE_TO_PACKAGE_FRAGMENT, file); PackageFragmentDescriptor packageFragment = context().bindingContext().get(BindingContext.FILE_TO_PACKAGE_FRAGMENT, file);
NamespaceTranslator translator = packageFragmentToTranslator.get(packageFragment); PackageTranslator translator = packageFragmentToTranslator.get(packageFragment);
if (translator == null) { if (translator == null) {
createRootPackageDefineInvocationIfNeeded(packageFqNameToDefineInvocation); createRootPackageDefineInvocationIfNeeded(packageFqNameToDefineInvocation);
translator = new NamespaceTranslator(packageFragment, packageFqNameToDefineInvocation, context()); translator = new PackageTranslator(packageFragment, packageFqNameToDefineInvocation, context());
packageFragmentToTranslator.put(packageFragment, translator); packageFragmentToTranslator.put(packageFragment, translator);
} }
translator.translate(file); translator.translate(file);
} }
for (NamespaceTranslator translator : packageFragmentToTranslator.values()) { for (PackageTranslator translator : packageFragmentToTranslator.values()) {
translator.add(packageFqNameToDefineInvocation); translator.add(packageFqNameToDefineInvocation);
} }
@@ -84,6 +84,6 @@ public final class NamespaceDeclarationTranslator extends AbstractTranslator {
private JsVar getRootPackageDeclaration(@NotNull DefineInvocation defineInvocation) { private JsVar getRootPackageDeclaration(@NotNull DefineInvocation defineInvocation) {
JsExpression rootPackageVar = new JsInvocation(context().namer().rootPackageDefinitionMethodReference(), defineInvocation.asList()); JsExpression rootPackageVar = new JsInvocation(context().namer().rootPackageDefinitionMethodReference(), defineInvocation.asList());
return new JsVar(context().scope().declareName(Namer.getRootNamespaceName()), rootPackageVar); return new JsVar(context().scope().declareName(Namer.getRootPackageName()), rootPackageVar);
} }
} }
@@ -37,7 +37,7 @@ import java.util.Map;
import static org.jetbrains.k2js.translate.declaration.DefineInvocation.createDefineInvocation; import static org.jetbrains.k2js.translate.declaration.DefineInvocation.createDefineInvocation;
import static org.jetbrains.k2js.translate.expression.LiteralFunctionTranslator.createPlace; import static org.jetbrains.k2js.translate.expression.LiteralFunctionTranslator.createPlace;
final class NamespaceTranslator extends AbstractTranslator { final class PackageTranslator extends AbstractTranslator {
@NotNull @NotNull
private final PackageFragmentDescriptor descriptor; private final PackageFragmentDescriptor descriptor;
@@ -45,7 +45,7 @@ final class NamespaceTranslator extends AbstractTranslator {
private final NotNullLazyValue<Trinity<List<JsPropertyInitializer>, LabelGenerator, JsExpression>> definitionPlace; private final NotNullLazyValue<Trinity<List<JsPropertyInitializer>, LabelGenerator, JsExpression>> definitionPlace;
NamespaceTranslator( PackageTranslator(
@NotNull final PackageFragmentDescriptor descriptor, @NotNull final PackageFragmentDescriptor descriptor,
@NotNull final Map<FqName, DefineInvocation> packageFqNameToDefineInvocation, @NotNull final Map<FqName, DefineInvocation> packageFqNameToDefineInvocation,
@NotNull TranslationContext context @NotNull TranslationContext context
@@ -34,7 +34,7 @@ import org.jetbrains.k2js.facade.exceptions.UnsupportedFeatureException;
import org.jetbrains.k2js.translate.context.Namer; import org.jetbrains.k2js.translate.context.Namer;
import org.jetbrains.k2js.translate.context.StaticContext; import org.jetbrains.k2js.translate.context.StaticContext;
import org.jetbrains.k2js.translate.context.TranslationContext; import org.jetbrains.k2js.translate.context.TranslationContext;
import org.jetbrains.k2js.translate.declaration.NamespaceDeclarationTranslator; import org.jetbrains.k2js.translate.declaration.PackageDeclarationTranslator;
import org.jetbrains.k2js.translate.expression.ExpressionVisitor; import org.jetbrains.k2js.translate.expression.ExpressionVisitor;
import org.jetbrains.k2js.translate.expression.FunctionTranslator; import org.jetbrains.k2js.translate.expression.FunctionTranslator;
import org.jetbrains.k2js.translate.expression.PatternTranslator; import org.jetbrains.k2js.translate.expression.PatternTranslator;
@@ -135,7 +135,7 @@ public final class Translation {
TranslationContext context = TranslationContext.rootContext(staticContext, rootFunction); TranslationContext context = TranslationContext.rootContext(staticContext, rootFunction);
staticContext.initTranslators(context); staticContext.initTranslators(context);
statements.addAll(NamespaceDeclarationTranslator.translateFiles(files, context)); statements.addAll(PackageDeclarationTranslator.translateFiles(files, context));
defineModule(context, statements, config.getModuleId()); defineModule(context, statements, config.getModuleId());
if (mainCallParameters.shouldBeGenerated()) { if (mainCallParameters.shouldBeGenerated()) {
@@ -149,10 +149,10 @@ public final class Translation {
} }
private static void defineModule(@NotNull TranslationContext context, @NotNull List<JsStatement> statements, @NotNull String moduleId) { private static void defineModule(@NotNull TranslationContext context, @NotNull List<JsStatement> statements, @NotNull String moduleId) {
JsName rootNamespaceName = context.scope().findName(Namer.getRootNamespaceName()); JsName rootPackageName = context.scope().findName(Namer.getRootPackageName());
if (rootNamespaceName != null) { if (rootPackageName != null) {
statements.add(new JsInvocation(context.namer().kotlin("defineModule"), context.program().getStringLiteral(moduleId), statements.add(new JsInvocation(context.namer().kotlin("defineModule"), context.program().getStringLiteral(moduleId),
rootNamespaceName.makeRef()).makeStmt()); rootPackageName.makeRef()).makeStmt());
} }
} }
@@ -20,11 +20,6 @@ import com.google.dart.compiler.backend.js.ast.*;
import com.intellij.util.SmartList; import com.intellij.util.SmartList;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor;
import org.jetbrains.jet.lang.descriptors.FunctionDescriptor;
import org.jetbrains.jet.lang.descriptors.Modality;
import org.jetbrains.jet.lang.descriptors.PropertyDescriptor;
import org.jetbrains.jet.lang.psi.JetElement;
import org.jetbrains.k2js.translate.context.Namer; import org.jetbrains.k2js.translate.context.Namer;
import org.jetbrains.k2js.translate.context.TranslationContext; import org.jetbrains.k2js.translate.context.TranslationContext;
@@ -252,7 +247,7 @@ public final class JsAstUtils {
JsExpression parent = qualifier.getQualifier(); JsExpression parent = qualifier.getQualifier();
assert parent instanceof JsNameRef : "unexpected qualifier: " + parent + ", original: " + fullQualifier; assert parent instanceof JsNameRef : "unexpected qualifier: " + parent + ", original: " + fullQualifier;
if (((JsNameRef) parent).getQualifier() == null) { if (((JsNameRef) parent).getQualifier() == null) {
assert Namer.getRootNamespaceName().equals(((JsNameRef) parent).getIdent()); assert Namer.getRootPackageName().equals(((JsNameRef) parent).getIdent());
qualifier.setQualifier(newQualifier); qualifier.setQualifier(newQualifier);
return; return;
} }