From 927fb30fd491a9223c55f56e005b00b8d8f5ecd6 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Wed, 11 Apr 2012 20:09:32 +0400 Subject: [PATCH 001/147] Saved diagnostic parameters into them. --- .../lang/diagnostics/DiagnosticFactory1.java | 2 +- .../lang/diagnostics/DiagnosticFactory2.java | 2 +- .../lang/diagnostics/DiagnosticFactory3.java | 2 +- .../DiagnosticWithParameters1.java | 56 +++++++++++++++ .../DiagnosticWithParameters2.java | 63 +++++++++++++++++ .../DiagnosticWithParameters3.java | 70 +++++++++++++++++++ .../diagnostics/DiagnosticWithPsiElement.java | 1 + 7 files changed, 193 insertions(+), 3 deletions(-) create mode 100644 compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java create mode 100644 compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java create mode 100644 compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java index c6e1d9d3f91..139337eab2a 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java @@ -35,7 +35,7 @@ public class DiagnosticFactory1 extends DiagnosticFacto @NotNull public ParametrizedDiagnostic on(@NotNull E element, @NotNull A argument) { - return new DiagnosticWithPsiElement(element, this, severity, makeMessage(argument)); + return new DiagnosticWithParameters1(element, argument, this, severity, makeMessage(argument)); } protected DiagnosticFactory1(Severity severity, String message, PositioningStrategy positioningStrategy, Renderer renderer) { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java index 8eb63ff8c04..767326616f0 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java @@ -40,7 +40,7 @@ public class DiagnosticFactory2 extends DiagnosticFa @NotNull public ParametrizedDiagnostic on(@NotNull E element, @NotNull A a, @NotNull B b) { - return new DiagnosticWithPsiElement(element, this, severity, makeMessage(a, b)); + return new DiagnosticWithParameters2(element, a, b, this, severity, makeMessage(a, b)); } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java index caa5b8518e1..1ad9fda7b3e 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java @@ -67,6 +67,6 @@ public class DiagnosticFactory3 extends Diagnosti } @NotNull public ParametrizedDiagnostic on(@NotNull E element, @NotNull A a, @NotNull B b, @NotNull C c) { - return new DiagnosticWithPsiElement(element, this, severity, makeMessage(a, b, c)); + return new DiagnosticWithParameters3(element, a, b, c, this, severity, makeMessage(a, b, c)); } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java new file mode 100644 index 00000000000..ad757faf103 --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java @@ -0,0 +1,56 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.lang.diagnostics; + +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.PsiElement; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +/** + * @author Evgeny Gerashchenko + * @since 4/11/12 + */ +public class DiagnosticWithParameters1 extends AbstractDiagnostic { + private A a; + + public DiagnosticWithParameters1(@NotNull E psiElement, + @NotNull A a, + @NotNull DiagnosticFactory1 factory, + @NotNull Severity severity, + @NotNull String message) { + super(psiElement, factory, severity, message); + this.a = a; + } + + @NotNull + @Override + public DiagnosticFactory1 getFactory() { + return (DiagnosticFactory1)super.getFactory(); + } + + @Override + @NotNull + public List getTextRanges() { + return getFactory().getTextRanges(this); + } + + public A getA() { + return a; + } +} diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java new file mode 100644 index 00000000000..51690b5e7d8 --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java @@ -0,0 +1,63 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.lang.diagnostics; + +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.PsiElement; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +/** + * @author Evgeny Gerashchenko + * @since 4/11/12 + */ +public class DiagnosticWithParameters2 extends AbstractDiagnostic { + private A a; + private B b; + + public DiagnosticWithParameters2(@NotNull E psiElement, + @NotNull A a, + @NotNull B b, + @NotNull DiagnosticFactory2 factory, + @NotNull Severity severity, + @NotNull String message) { + super(psiElement, factory, severity, message); + this.a = a; + this.b = b; + } + + @NotNull + @Override + public DiagnosticFactory2 getFactory() { + return (DiagnosticFactory2)super.getFactory(); + } + + @Override + @NotNull + public List getTextRanges() { + return getFactory().getTextRanges(this); + } + + public A getA() { + return a; + } + + public B getB() { + return b; + } +} diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java new file mode 100644 index 00000000000..a57d8526e86 --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java @@ -0,0 +1,70 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.lang.diagnostics; + +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.PsiElement; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +/** + * @author Evgeny Gerashchenko + * @since 4/11/12 + */ +public class DiagnosticWithParameters3 extends AbstractDiagnostic { + private A a; + private B b; + private C c; + + public DiagnosticWithParameters3(@NotNull E psiElement, + @NotNull A a, + @NotNull B b, + @NotNull C c, + @NotNull DiagnosticFactory3 factory, + @NotNull Severity severity, + @NotNull String message) { + super(psiElement, factory, severity, message); + this.a = a; + this.b = b; + this.c = c; + } + + @NotNull + @Override + public DiagnosticFactory3 getFactory() { + return (DiagnosticFactory3)super.getFactory(); + } + + @Override + @NotNull + public List getTextRanges() { + return getFactory().getTextRanges(this); + } + + public A getA() { + return a; + } + + public B getB() { + return b; + } + + public C getC() { + return c; + } +} diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithPsiElement.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithPsiElement.java index a73ce08470a..5d7fe6c0a6e 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithPsiElement.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithPsiElement.java @@ -36,6 +36,7 @@ public class DiagnosticWithPsiElement extends AbstractDiag return (DiagnosticFactoryWithPsiElement)super.getFactory(); } + @Override @NotNull public List getTextRanges() { return getFactory().getTextRanges(this); From 03fac491919de5a2bf52a14eb75203c99bb7e1c9 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Wed, 11 Apr 2012 20:58:21 +0400 Subject: [PATCH 002/147] Got rid of storing diagnostic messages inside them: now they are generated on demand. --- .../jet/lang/diagnostics/AbstractDiagnostic.java | 12 +++--------- .../jet/lang/diagnostics/DiagnosticFactory.java | 6 +++++- .../jet/lang/diagnostics/DiagnosticFactory1.java | 2 +- .../jet/lang/diagnostics/DiagnosticFactory2.java | 4 ++-- .../jet/lang/diagnostics/DiagnosticFactory3.java | 4 ++-- .../diagnostics/DiagnosticWithParameters1.java | 11 ++++++++--- .../diagnostics/DiagnosticWithParameters2.java | 11 ++++++++--- .../diagnostics/DiagnosticWithParameters3.java | 11 ++++++++--- .../diagnostics/DiagnosticWithPsiElement.java | 16 ++++++++++++---- .../diagnostics/RedeclarationDiagnostic.java | 16 +++++++++++++++- .../UnresolvedReferenceDiagnostic.java | 12 +++++++++--- .../UnresolvedReferenceDiagnosticFactory.java | 13 +++++-------- .../tests/NamedArgumentsAndDefaultValues.jet | 2 +- 13 files changed, 79 insertions(+), 41 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnostic.java index 3e1622aa486..f2a57cfc6bb 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnostic.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnostic.java @@ -25,15 +25,15 @@ import org.jetbrains.annotations.NotNull; */ public abstract class AbstractDiagnostic implements ParametrizedDiagnostic { private final E psiElement; - private final String message; private final AbstractDiagnosticFactory factory; private final Severity severity; - public AbstractDiagnostic(@NotNull E psiElement, @NotNull AbstractDiagnosticFactory factory, @NotNull Severity severity, @NotNull String message) { + public AbstractDiagnostic(@NotNull E psiElement, + @NotNull AbstractDiagnosticFactory factory, + @NotNull Severity severity) { this.psiElement = psiElement; this.factory = factory; this.severity = severity; - this.message = message; } @NotNull @@ -48,12 +48,6 @@ public abstract class AbstractDiagnostic implements Parame return psiElement.getContainingFile(); } - @NotNull - @Override - public String getMessage() { - return message; - } - @NotNull @Override public Severity getSeverity() { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory.java index 5e893eef3f1..b1f03498b4f 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory.java @@ -38,8 +38,12 @@ public class DiagnosticFactory extends DiagnosticFactoryWi return new DiagnosticFactory(severity, message, positioningStrategy); } + String getMessage() { + return message; + } + @NotNull public ParametrizedDiagnostic on(@NotNull E element) { - return new DiagnosticWithPsiElement(element, this, severity, message); + return new DiagnosticWithPsiElement(element, this, severity); } } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java index 139337eab2a..f28aaa14a2b 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java @@ -35,7 +35,7 @@ public class DiagnosticFactory1 extends DiagnosticFacto @NotNull public ParametrizedDiagnostic on(@NotNull E element, @NotNull A argument) { - return new DiagnosticWithParameters1(element, argument, this, severity, makeMessage(argument)); + return new DiagnosticWithParameters1(element, argument, this, severity); } protected DiagnosticFactory1(Severity severity, String message, PositioningStrategy positioningStrategy, Renderer renderer) { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java index 767326616f0..c63687e00c3 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java @@ -26,7 +26,7 @@ public class DiagnosticFactory2 extends DiagnosticFa private final Renderer rendererForA; private final Renderer rendererForB; - private String makeMessage(@NotNull A a, @NotNull B b) { + protected String makeMessage(@NotNull A a, @NotNull B b) { return messageFormat.format(new Object[] {makeMessageForA(a), makeMessageForB(b)}); } @@ -40,7 +40,7 @@ public class DiagnosticFactory2 extends DiagnosticFa @NotNull public ParametrizedDiagnostic on(@NotNull E element, @NotNull A a, @NotNull B b) { - return new DiagnosticWithParameters2(element, a, b, this, severity, makeMessage(a, b)); + return new DiagnosticWithParameters2(element, a, b, this, severity); } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java index 1ad9fda7b3e..bc945a49bd1 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java @@ -50,7 +50,7 @@ public class DiagnosticFactory3 extends Diagnosti return new DiagnosticFactory3(severity, messageStub, positioningStrategy, rendererForA, rendererForB, rendererForC); } - private String makeMessage(@NotNull A a, @NotNull B b, @NotNull C c) { + protected String makeMessage(@NotNull A a, @NotNull B b, @NotNull C c) { return messageFormat.format(new Object[]{makeMessageForA(a), makeMessageForB(b), makeMessageForC(c)}); } @@ -67,6 +67,6 @@ public class DiagnosticFactory3 extends Diagnosti } @NotNull public ParametrizedDiagnostic on(@NotNull E element, @NotNull A a, @NotNull B b, @NotNull C c) { - return new DiagnosticWithParameters3(element, a, b, c, this, severity, makeMessage(a, b, c)); + return new DiagnosticWithParameters3(element, a, b, c, this, severity); } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java index ad757faf103..e02675d5c1a 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java @@ -32,9 +32,8 @@ public class DiagnosticWithParameters1 extends Abstract public DiagnosticWithParameters1(@NotNull E psiElement, @NotNull A a, @NotNull DiagnosticFactory1 factory, - @NotNull Severity severity, - @NotNull String message) { - super(psiElement, factory, severity, message); + @NotNull Severity severity) { + super(psiElement, factory, severity); this.a = a; } @@ -44,6 +43,12 @@ public class DiagnosticWithParameters1 extends Abstract return (DiagnosticFactory1)super.getFactory(); } + @NotNull + @Override + public String getMessage() { + return getFactory().makeMessage(a); + } + @Override @NotNull public List getTextRanges() { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java index 51690b5e7d8..031d5805a15 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java @@ -34,9 +34,8 @@ public class DiagnosticWithParameters2 extends Abstr @NotNull A a, @NotNull B b, @NotNull DiagnosticFactory2 factory, - @NotNull Severity severity, - @NotNull String message) { - super(psiElement, factory, severity, message); + @NotNull Severity severity) { + super(psiElement, factory, severity); this.a = a; this.b = b; } @@ -47,6 +46,12 @@ public class DiagnosticWithParameters2 extends Abstr return (DiagnosticFactory2)super.getFactory(); } + @NotNull + @Override + public String getMessage() { + return getFactory().makeMessage(a, b); + } + @Override @NotNull public List getTextRanges() { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java index a57d8526e86..82ee507aa85 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java @@ -36,9 +36,8 @@ public class DiagnosticWithParameters3 extends Ab @NotNull B b, @NotNull C c, @NotNull DiagnosticFactory3 factory, - @NotNull Severity severity, - @NotNull String message) { - super(psiElement, factory, severity, message); + @NotNull Severity severity) { + super(psiElement, factory, severity); this.a = a; this.b = b; this.c = c; @@ -50,6 +49,12 @@ public class DiagnosticWithParameters3 extends Ab return (DiagnosticFactory3)super.getFactory(); } + @NotNull + @Override + public String getMessage() { + return getFactory().makeMessage(a, b, c); + } + @Override @NotNull public List getTextRanges() { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithPsiElement.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithPsiElement.java index 5d7fe6c0a6e..603c0aed730 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithPsiElement.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithPsiElement.java @@ -26,14 +26,22 @@ import java.util.List; * @author svtk */ public class DiagnosticWithPsiElement extends AbstractDiagnostic { - public DiagnosticWithPsiElement(@NotNull E psiElement, @NotNull DiagnosticFactoryWithPsiElement factory, @NotNull Severity severity, @NotNull String message) { - super(psiElement, factory, severity, message); + public DiagnosticWithPsiElement(@NotNull E psiElement, + @NotNull DiagnosticFactory factory, + @NotNull Severity severity) { + super(psiElement, factory, severity); } @NotNull @Override - public DiagnosticFactoryWithPsiElement getFactory() { - return (DiagnosticFactoryWithPsiElement)super.getFactory(); + public DiagnosticFactory getFactory() { + return (DiagnosticFactory)super.getFactory(); + } + + @NotNull + @Override + public String getMessage() { + return getFactory().getMessage(); } @Override diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java index 33553f9ccdd..15f49087fd6 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java @@ -33,9 +33,23 @@ import java.util.List; */ public interface RedeclarationDiagnostic extends Diagnostic { class SimpleRedeclarationDiagnostic extends AbstractDiagnostic implements RedeclarationDiagnostic { + private String name; public SimpleRedeclarationDiagnostic(@NotNull PsiElement psiElement, @NotNull String name, RedeclarationDiagnosticFactory factory) { - super(psiElement, factory, factory.severity, factory.makeMessage(name)); + super(psiElement, factory, factory.severity); + this.name = name; + } + + @NotNull + @Override + public RedeclarationDiagnosticFactory getFactory() { + return (RedeclarationDiagnosticFactory)super.getFactory(); + } + + @NotNull + @Override + public String getMessage() { + return getFactory().makeMessage(name); } @NotNull diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java index 8b1f2242987..730c992d305 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java @@ -30,15 +30,21 @@ import static org.jetbrains.jet.lang.diagnostics.Severity.ERROR; * @author abreslav */ public class UnresolvedReferenceDiagnostic extends AbstractDiagnostic { + @NotNull + @Override + public UnresolvedReferenceDiagnosticFactory getFactory() { + return (UnresolvedReferenceDiagnosticFactory)super.getFactory(); + } - public UnresolvedReferenceDiagnostic(JetReferenceExpression referenceExpression, String message) { - super(referenceExpression, Errors.UNRESOLVED_REFERENCE, ERROR, message); + public UnresolvedReferenceDiagnostic(@NotNull JetReferenceExpression referenceExpression, + @NotNull UnresolvedReferenceDiagnosticFactory factory) { + super(referenceExpression, factory, ERROR); } @NotNull @Override public String getMessage() { - return super.getMessage() + ": " + getPsiElement().getText(); + return getFactory().getMessage() + ": " + getPsiElement().getText(); } @NotNull diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java index ddec486cf56..b4fd2e6e889 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java @@ -16,28 +16,25 @@ package org.jetbrains.jet.lang.diagnostics; -import com.intellij.openapi.util.TextRange; -import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.lang.psi.JetArrayAccessExpression; import org.jetbrains.jet.lang.psi.JetReferenceExpression; -import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; - -import java.util.List; /** * @author abreslav */ public class UnresolvedReferenceDiagnosticFactory extends AbstractDiagnosticFactory { - private final String message; private UnresolvedReferenceDiagnosticFactory(String message) { this.message = message; } + String getMessage() { + return message; + } + public UnresolvedReferenceDiagnostic on(@NotNull JetReferenceExpression reference) { - return new UnresolvedReferenceDiagnostic(reference, message); + return new UnresolvedReferenceDiagnostic(reference, this); } public static UnresolvedReferenceDiagnosticFactory create(String message) { diff --git a/compiler/testData/diagnostics/tests/NamedArgumentsAndDefaultValues.jet b/compiler/testData/diagnostics/tests/NamedArgumentsAndDefaultValues.jet index 8cfd720f404..161e6f7f743 100644 --- a/compiler/testData/diagnostics/tests/NamedArgumentsAndDefaultValues.jet +++ b/compiler/testData/diagnostics/tests/NamedArgumentsAndDefaultValues.jet @@ -19,5 +19,5 @@ fun test() { bar(1, 1, "") bar(1, 1, "") bar(1, z = "") - bar(1, zz = "", zz.foo) + bar(1, zz = "", zz.foo) } From 409d6b2da1687b34f2e0bbf783dbc14a436df6ca Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 12 Apr 2012 13:26:47 +0400 Subject: [PATCH 003/147] Renamed DiagnosticWithPsiElement to SimpleDiagnostic, DiagnosticFactory to SimpleDiagnosticFactory, so they relation is reflected in their names. --- .../jet/compiler/CompileSession.java | 4 +- .../jet/lang/diagnostics/Errors.java | 353 +++++++++++------- ...hPsiElement.java => SimpleDiagnostic.java} | 10 +- ...tory.java => SimpleDiagnosticFactory.java} | 12 +- 4 files changed, 236 insertions(+), 143 deletions(-) rename compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/{DiagnosticWithPsiElement.java => SimpleDiagnostic.java} (79%) rename compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/{DiagnosticFactory.java => SimpleDiagnosticFactory.java} (62%) diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java index 8b6c4a8d1f9..952f4cdb2c7 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java @@ -36,7 +36,7 @@ import org.jetbrains.jet.lang.descriptors.ClassOrNamespaceDescriptor; import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.descriptors.ModuleDescriptor; import org.jetbrains.jet.lang.diagnostics.Diagnostic; -import org.jetbrains.jet.lang.diagnostics.DiagnosticFactory; +import org.jetbrains.jet.lang.diagnostics.SimpleDiagnosticFactory; import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils; import org.jetbrains.jet.lang.diagnostics.Severity; import org.jetbrains.jet.lang.psi.JetFile; @@ -139,7 +139,7 @@ public class CompileSession { public void visitErrorElement(PsiErrorElement element) { String description = element.getErrorDescription(); String message = StringUtil.isEmpty(description) ? "Syntax error" : description; - Diagnostic diagnostic = DiagnosticFactory.create(Severity.ERROR, message).on(element); + Diagnostic diagnostic = SimpleDiagnosticFactory.create(Severity.ERROR, message).on(element); reportDiagnostic(messageCollector, diagnostic); } }); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java index e6ba102a7eb..991f03e296c 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java @@ -86,57 +86,90 @@ public interface Errors { DiagnosticFactory1 ILLEGAL_MODIFIER = DiagnosticFactory1.create(ERROR, "Illegal modifier ''{0}''"); DiagnosticFactory2 REDUNDANT_MODIFIER = DiagnosticFactory2.create(Severity.WARNING, "Modifier {0} is redundant because {1} is present"); - DiagnosticFactory ABSTRACT_MODIFIER_IN_TRAIT = DiagnosticFactory.create(WARNING, "Modifier ''{0}'' is redundant in trait", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); - DiagnosticFactory OPEN_MODIFIER_IN_TRAIT = DiagnosticFactory.create(WARNING, "Modifier ''{0}'' is redundant in trait", PositioningStrategies.positionModifier(JetTokens.OPEN_KEYWORD)); - DiagnosticFactory REDUNDANT_MODIFIER_IN_GETTER = DiagnosticFactory.create(WARNING, "Visibility modifiers are redundant in getter"); - DiagnosticFactory TRAIT_CAN_NOT_BE_FINAL = DiagnosticFactory.create(ERROR, "Trait can not be final"); - DiagnosticFactory TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM = DiagnosticFactory.create(ERROR, "Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly"); // TODO: message - DiagnosticFactory RETURN_NOT_ALLOWED = DiagnosticFactory.create(ERROR, "'return' is not allowed here"); - DiagnosticFactory PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE = DiagnosticFactory.create(ERROR, "Projections are not allowed for immediate arguments of a supertype", new PositioningStrategy() { - @NotNull - @Override - public List mark(@NotNull JetTypeProjection element) { - return markNode(element.getProjectionNode()); - } - }); - DiagnosticFactory LABEL_NAME_CLASH = DiagnosticFactory.create(WARNING, "There is more than one label with such a name in this scope"); - DiagnosticFactory EXPRESSION_EXPECTED_NAMESPACE_FOUND = DiagnosticFactory.create(ERROR, "Expression expected, but a namespace name found"); + SimpleDiagnosticFactory ABSTRACT_MODIFIER_IN_TRAIT = SimpleDiagnosticFactory + .create(WARNING, "Modifier ''{0}'' is redundant in trait", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + SimpleDiagnosticFactory OPEN_MODIFIER_IN_TRAIT = SimpleDiagnosticFactory + .create(WARNING, "Modifier ''{0}'' is redundant in trait", PositioningStrategies.positionModifier(JetTokens.OPEN_KEYWORD)); + SimpleDiagnosticFactory + REDUNDANT_MODIFIER_IN_GETTER = SimpleDiagnosticFactory.create(WARNING, "Visibility modifiers are redundant in getter"); + SimpleDiagnosticFactory TRAIT_CAN_NOT_BE_FINAL = SimpleDiagnosticFactory.create(ERROR, "Trait can not be final"); + SimpleDiagnosticFactory TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM = SimpleDiagnosticFactory.create(ERROR, + "Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly"); // TODO: message + SimpleDiagnosticFactory RETURN_NOT_ALLOWED = SimpleDiagnosticFactory.create(ERROR, "'return' is not allowed here"); + SimpleDiagnosticFactory PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE = SimpleDiagnosticFactory + .create(ERROR, "Projections are not allowed for immediate arguments of a supertype", + new PositioningStrategy() { + @NotNull + @Override + public List mark(@NotNull JetTypeProjection element) { + return markNode(element.getProjectionNode()); + } + }); + SimpleDiagnosticFactory + LABEL_NAME_CLASH = SimpleDiagnosticFactory.create(WARNING, "There is more than one label with such a name in this scope"); + SimpleDiagnosticFactory + EXPRESSION_EXPECTED_NAMESPACE_FOUND = SimpleDiagnosticFactory.create(ERROR, "Expression expected, but a namespace name found"); DiagnosticFactory1 CANNOT_IMPORT_FROM_ELEMENT = DiagnosticFactory1.create(ERROR, "Cannot import from ''{0}''", NAME); DiagnosticFactory1 CANNOT_BE_IMPORTED = DiagnosticFactory1.create(ERROR, "Cannot import ''{0}'', functions and properties can be imported only from packages", NAME); - DiagnosticFactory USELESS_HIDDEN_IMPORT = DiagnosticFactory.create(WARNING, "Useless import, it is hidden further"); - DiagnosticFactory USELESS_SIMPLE_IMPORT = DiagnosticFactory.create(WARNING, "Useless import, does nothing"); + SimpleDiagnosticFactory + USELESS_HIDDEN_IMPORT = SimpleDiagnosticFactory.create(WARNING, "Useless import, it is hidden further"); + SimpleDiagnosticFactory USELESS_SIMPLE_IMPORT = SimpleDiagnosticFactory.create(WARNING, "Useless import, does nothing"); - DiagnosticFactory CANNOT_INFER_PARAMETER_TYPE = DiagnosticFactory.create(ERROR, "Cannot infer a type for this parameter. To specify it explicitly use the {(p : Type) => ...} notation"); + SimpleDiagnosticFactory CANNOT_INFER_PARAMETER_TYPE = SimpleDiagnosticFactory + .create(ERROR, "Cannot infer a type for this parameter. To specify it explicitly use the {(p : Type) => ...} notation"); - DiagnosticFactory NO_BACKING_FIELD_ABSTRACT_PROPERTY = DiagnosticFactory.create(ERROR, "This property doesn't have a backing field, because it's abstract"); - DiagnosticFactory NO_BACKING_FIELD_CUSTOM_ACCESSORS = DiagnosticFactory.create(ERROR, "This property doesn't have a backing field, because it has custom accessors without reference to the backing field"); - DiagnosticFactory INACCESSIBLE_BACKING_FIELD = DiagnosticFactory.create(ERROR, "The backing field is not accessible here"); - DiagnosticFactory NOT_PROPERTY_BACKING_FIELD = DiagnosticFactory.create(ERROR, "The referenced variable is not a property and doesn't have backing field"); + SimpleDiagnosticFactory NO_BACKING_FIELD_ABSTRACT_PROPERTY = SimpleDiagnosticFactory + .create(ERROR, "This property doesn't have a backing field, because it's abstract"); + SimpleDiagnosticFactory NO_BACKING_FIELD_CUSTOM_ACCESSORS = SimpleDiagnosticFactory.create(ERROR, + "This property doesn't have a backing field, because it has custom accessors without reference to the backing field"); + SimpleDiagnosticFactory + INACCESSIBLE_BACKING_FIELD = SimpleDiagnosticFactory.create(ERROR, "The backing field is not accessible here"); + SimpleDiagnosticFactory NOT_PROPERTY_BACKING_FIELD = SimpleDiagnosticFactory + .create(ERROR, "The referenced variable is not a property and doesn't have backing field"); - DiagnosticFactory MIXING_NAMED_AND_POSITIONED_ARGUMENTS = DiagnosticFactory.create(ERROR, "Mixing named and positioned arguments in not allowed"); - DiagnosticFactory ARGUMENT_PASSED_TWICE = DiagnosticFactory.create(ERROR, "An argument is already passed for this parameter"); + SimpleDiagnosticFactory MIXING_NAMED_AND_POSITIONED_ARGUMENTS = SimpleDiagnosticFactory + .create(ERROR, "Mixing named and positioned arguments in not allowed"); + SimpleDiagnosticFactory + ARGUMENT_PASSED_TWICE = SimpleDiagnosticFactory.create(ERROR, "An argument is already passed for this parameter"); UnresolvedReferenceDiagnosticFactory NAMED_PARAMETER_NOT_FOUND = UnresolvedReferenceDiagnosticFactory.create("Cannot find a parameter with this name"); - DiagnosticFactory VARARG_OUTSIDE_PARENTHESES = DiagnosticFactory.create(ERROR, "Passing value as a vararg is only allowed inside a parenthesized argument list"); - DiagnosticFactory NON_VARARG_SPREAD = DiagnosticFactory.create(ERROR, "The spread operator (*foo) may only be applied in a vararg position"); + SimpleDiagnosticFactory VARARG_OUTSIDE_PARENTHESES = SimpleDiagnosticFactory + .create(ERROR, "Passing value as a vararg is only allowed inside a parenthesized argument list"); + SimpleDiagnosticFactory + NON_VARARG_SPREAD = SimpleDiagnosticFactory.create(ERROR, "The spread operator (*foo) may only be applied in a vararg position"); - DiagnosticFactory MANY_FUNCTION_LITERAL_ARGUMENTS = DiagnosticFactory.create(ERROR, "Only one function literal is allowed outside a parenthesized argument list"); - DiagnosticFactory PROPERTY_WITH_NO_TYPE_NO_INITIALIZER = DiagnosticFactory.create(ERROR, "This property must either have a type annotation or be initialized"); + SimpleDiagnosticFactory MANY_FUNCTION_LITERAL_ARGUMENTS = SimpleDiagnosticFactory + .create(ERROR, "Only one function literal is allowed outside a parenthesized argument list"); + SimpleDiagnosticFactory PROPERTY_WITH_NO_TYPE_NO_INITIALIZER = SimpleDiagnosticFactory + .create(ERROR, "This property must either have a type annotation or be initialized"); - DiagnosticFactory ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS = DiagnosticFactory.create(ERROR, "This property cannot be declared abstract", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); - DiagnosticFactory ABSTRACT_PROPERTY_NOT_IN_CLASS = DiagnosticFactory.create(ERROR, "A property may be abstract only when defined in a class or trait", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); - DiagnosticFactory ABSTRACT_PROPERTY_WITH_INITIALIZER = DiagnosticFactory.create(ERROR, "Property with initializer cannot be abstract"); - DiagnosticFactory ABSTRACT_PROPERTY_WITH_GETTER = DiagnosticFactory.create(ERROR, "Property with getter implementation cannot be abstract"); - DiagnosticFactory ABSTRACT_PROPERTY_WITH_SETTER = DiagnosticFactory.create(ERROR, "Property with setter implementation cannot be abstract"); + SimpleDiagnosticFactory ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS = SimpleDiagnosticFactory + .create(ERROR, "This property cannot be declared abstract", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + SimpleDiagnosticFactory ABSTRACT_PROPERTY_NOT_IN_CLASS = SimpleDiagnosticFactory + .create(ERROR, "A property may be abstract only when defined in a class or trait", + PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + SimpleDiagnosticFactory + ABSTRACT_PROPERTY_WITH_INITIALIZER = SimpleDiagnosticFactory.create(ERROR, "Property with initializer cannot be abstract"); + SimpleDiagnosticFactory + ABSTRACT_PROPERTY_WITH_GETTER = SimpleDiagnosticFactory.create(ERROR, "Property with getter implementation cannot be abstract"); + SimpleDiagnosticFactory + ABSTRACT_PROPERTY_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR, "Property with setter implementation cannot be abstract"); - DiagnosticFactory PACKAGE_MEMBER_CANNOT_BE_PROTECTED = DiagnosticFactory.create(ERROR, "Package member cannot be protected"); + SimpleDiagnosticFactory + PACKAGE_MEMBER_CANNOT_BE_PROTECTED = SimpleDiagnosticFactory.create(ERROR, "Package member cannot be protected"); - DiagnosticFactory GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY = DiagnosticFactory.create(ERROR, "Getter visibility must be the same as property visibility"); - DiagnosticFactory BACKING_FIELD_IN_TRAIT = DiagnosticFactory.create(ERROR, "Property in a trait cannot have a backing field", PositioningStrategies.POSITION_NAME_IDENTIFIER); - DiagnosticFactory MUST_BE_INITIALIZED = DiagnosticFactory.create(ERROR, "Property must be initialized", PositioningStrategies.POSITION_NAME_IDENTIFIER); - DiagnosticFactory MUST_BE_INITIALIZED_OR_BE_ABSTRACT = DiagnosticFactory.create(ERROR, "Property must be initialized or be abstract", PositioningStrategies.POSITION_NAME_IDENTIFIER); - DiagnosticFactory PROPERTY_INITIALIZER_IN_TRAIT = DiagnosticFactory.create(ERROR, "Property initializers are not allowed in traits"); - DiagnosticFactory PROPERTY_INITIALIZER_NO_BACKING_FIELD = DiagnosticFactory.create(ERROR, "Initializer is not allowed here because this property has no backing field"); + SimpleDiagnosticFactory GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY = SimpleDiagnosticFactory + .create(ERROR, "Getter visibility must be the same as property visibility"); + SimpleDiagnosticFactory BACKING_FIELD_IN_TRAIT = SimpleDiagnosticFactory + .create(ERROR, "Property in a trait cannot have a backing field", PositioningStrategies.POSITION_NAME_IDENTIFIER); + SimpleDiagnosticFactory MUST_BE_INITIALIZED = SimpleDiagnosticFactory + .create(ERROR, "Property must be initialized", PositioningStrategies.POSITION_NAME_IDENTIFIER); + SimpleDiagnosticFactory MUST_BE_INITIALIZED_OR_BE_ABSTRACT = SimpleDiagnosticFactory + .create(ERROR, "Property must be initialized or be abstract", PositioningStrategies.POSITION_NAME_IDENTIFIER); + SimpleDiagnosticFactory + PROPERTY_INITIALIZER_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR, "Property initializers are not allowed in traits"); + SimpleDiagnosticFactory PROPERTY_INITIALIZER_NO_BACKING_FIELD = SimpleDiagnosticFactory + .create(ERROR, "Initializer is not allowed here because this property has no backing field"); DiagnosticFactory3 ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS = DiagnosticFactory3.create(ERROR, "Abstract property {0} in non-abstract class {1}", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); DiagnosticFactory3 ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS = DiagnosticFactory3.create(ERROR, "Abstract function {0} in non-abstract class {1}", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); DiagnosticFactory1 ABSTRACT_FUNCTION_WITH_BODY = DiagnosticFactory1.create(ERROR, "A function {0} with body cannot be abstract", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); @@ -144,18 +177,28 @@ public interface Errors { DiagnosticFactory1 NON_MEMBER_ABSTRACT_FUNCTION = DiagnosticFactory1.create(ERROR, "Function {0} is not a class or trait member and cannot be abstract", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); DiagnosticFactory1 NON_MEMBER_FUNCTION_NO_BODY = DiagnosticFactory1.create(ERROR, "Function {0} must have a body", PositioningStrategies.POSITION_NAME_IDENTIFIER); - DiagnosticFactory NON_FINAL_MEMBER_IN_FINAL_CLASS = DiagnosticFactory.create(ERROR, "Non final member in a final class", PositioningStrategies.positionModifier(JetTokens.OPEN_KEYWORD)); + SimpleDiagnosticFactory NON_FINAL_MEMBER_IN_FINAL_CLASS = SimpleDiagnosticFactory + .create(ERROR, "Non final member in a final class", PositioningStrategies.positionModifier(JetTokens.OPEN_KEYWORD)); - DiagnosticFactory PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE = DiagnosticFactory.create(ERROR, "Public or protected member should specify a type", PositioningStrategies.POSITION_NAME_IDENTIFIER); + SimpleDiagnosticFactory PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE = SimpleDiagnosticFactory + .create(ERROR, "Public or protected member should specify a type", PositioningStrategies.POSITION_NAME_IDENTIFIER); - DiagnosticFactory PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT = DiagnosticFactory.create(ERROR, "Projections are not allowed on type arguments of functions and properties"); // TODO : better positioning - DiagnosticFactory SUPERTYPE_NOT_INITIALIZED = DiagnosticFactory.create(ERROR, "This type has a constructor, and thus must be initialized here"); - DiagnosticFactory SUPERTYPE_NOT_INITIALIZED_DEFAULT = DiagnosticFactory.create(ERROR, "Constructor invocation should be explicitly specified"); - DiagnosticFactory SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY = DiagnosticFactory.create(ERROR, "A secondary constructor may appear only in a class that has a primary constructor"); - DiagnosticFactory SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST = DiagnosticFactory.create(ERROR, "Secondary constructors must have an initializer list"); - DiagnosticFactory BY_IN_SECONDARY_CONSTRUCTOR = DiagnosticFactory.create(ERROR, "'by'-clause is only supported for primary constructors"); - DiagnosticFactory INITIALIZER_WITH_NO_ARGUMENTS = DiagnosticFactory.create(ERROR, "Constructor arguments required"); - DiagnosticFactory MANY_CALLS_TO_THIS = DiagnosticFactory.create(ERROR, "Only one call to 'this(...)' is allowed"); + SimpleDiagnosticFactory PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT = SimpleDiagnosticFactory + .create(ERROR, "Projections are not allowed on type arguments of functions and properties"); // TODO : better positioning + SimpleDiagnosticFactory SUPERTYPE_NOT_INITIALIZED = SimpleDiagnosticFactory + .create(ERROR, "This type has a constructor, and thus must be initialized here"); + SimpleDiagnosticFactory SUPERTYPE_NOT_INITIALIZED_DEFAULT = SimpleDiagnosticFactory + .create(ERROR, "Constructor invocation should be explicitly specified"); + SimpleDiagnosticFactory SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY = SimpleDiagnosticFactory + .create(ERROR, "A secondary constructor may appear only in a class that has a primary constructor"); + SimpleDiagnosticFactory SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST = SimpleDiagnosticFactory + .create(ERROR, "Secondary constructors must have an initializer list"); + SimpleDiagnosticFactory + BY_IN_SECONDARY_CONSTRUCTOR = SimpleDiagnosticFactory.create(ERROR, "'by'-clause is only supported for primary constructors"); + SimpleDiagnosticFactory + INITIALIZER_WITH_NO_ARGUMENTS = SimpleDiagnosticFactory.create(ERROR, "Constructor arguments required"); + SimpleDiagnosticFactory + MANY_CALLS_TO_THIS = SimpleDiagnosticFactory.create(ERROR, "Only one call to 'this(...)' is allowed"); DiagnosticFactory1 NOTHING_TO_OVERRIDE = DiagnosticFactory1.create(ERROR, "{0} overrides nothing", PositioningStrategies.positionModifier(JetTokens.OVERRIDE_KEYWORD), DescriptorRenderer.TEXT); DiagnosticFactory3 VIRTUAL_MEMBER_HIDDEN = DiagnosticFactory3.create(ERROR, "''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", PositioningStrategies.POSITION_NAME_IDENTIFIER, DescriptorRenderer.TEXT, DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); @@ -170,88 +213,123 @@ public interface Errors { DiagnosticFactory1 VARIABLE_WITH_REDUNDANT_INITIALIZER = DiagnosticFactory1.create(WARNING, "Variable ''{0}'' initializer is redundant", NAME); DiagnosticFactory2 UNUSED_VALUE = DiagnosticFactory2.create(WARNING, "The value ''{0}'' assigned to ''{1}'' is never used", ELEMENT_TEXT, TO_STRING); DiagnosticFactory1 UNUSED_CHANGED_VALUE = DiagnosticFactory1.create(WARNING, "The value changed at ''{0}'' is never used", ELEMENT_TEXT); - DiagnosticFactory UNUSED_EXPRESSION = DiagnosticFactory.create(WARNING, "The expression is unused"); - DiagnosticFactory UNUSED_FUNCTION_LITERAL = DiagnosticFactory.create(WARNING, "The function literal is unused. If you mean block, you can use 'run { ... }'"); + SimpleDiagnosticFactory UNUSED_EXPRESSION = SimpleDiagnosticFactory.create(WARNING, "The expression is unused"); + SimpleDiagnosticFactory UNUSED_FUNCTION_LITERAL = SimpleDiagnosticFactory + .create(WARNING, "The function literal is unused. If you mean block, you can use 'run { ... }'"); DiagnosticFactory1 VAL_REASSIGNMENT = DiagnosticFactory1.create(ERROR, "Val can not be reassigned", NAME); DiagnosticFactory1 INITIALIZATION_BEFORE_DECLARATION = DiagnosticFactory1.create(ERROR, "Variable cannot be initialized before declaration", NAME); - DiagnosticFactory VARIABLE_EXPECTED = DiagnosticFactory.create(ERROR, "Variable expected"); + SimpleDiagnosticFactory VARIABLE_EXPECTED = SimpleDiagnosticFactory.create(ERROR, "Variable expected"); DiagnosticFactory1 INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER = DiagnosticFactory1.create(ERROR, "This property has a custom setter, so initialization using backing field required", NAME); DiagnosticFactory1 INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER = DiagnosticFactory1.create(ERROR, "Setter of this property can be overridden, so initialization using backing field required", NAME); DiagnosticFactory1 FUNCTION_PARAMETERS_OF_INLINE_FUNCTION = DiagnosticFactory1.create(ERROR, "Function parameters of inline function can only be invoked", NAME); - DiagnosticFactory UNREACHABLE_CODE = DiagnosticFactory.create(ERROR, "Unreachable code"); + SimpleDiagnosticFactory UNREACHABLE_CODE = SimpleDiagnosticFactory.create(ERROR, "Unreachable code"); - DiagnosticFactory MANY_CLASS_OBJECTS = DiagnosticFactory.create(ERROR, "Only one class object is allowed per class"); - DiagnosticFactory CLASS_OBJECT_NOT_ALLOWED = DiagnosticFactory.create(ERROR, "A class object is not allowed here"); - DiagnosticFactory DELEGATION_IN_TRAIT = DiagnosticFactory.create(ERROR, "Traits cannot use delegation"); - DiagnosticFactory DELEGATION_NOT_TO_TRAIT = DiagnosticFactory.create(ERROR, "Only traits can be delegated to"); - DiagnosticFactory NO_CONSTRUCTOR = DiagnosticFactory.create(ERROR, "This class does not have a constructor"); - DiagnosticFactory NOT_A_CLASS = DiagnosticFactory.create(ERROR, "Not a class"); - DiagnosticFactory ILLEGAL_ESCAPE_SEQUENCE = DiagnosticFactory.create(ERROR, "Illegal escape sequence"); + SimpleDiagnosticFactory + MANY_CLASS_OBJECTS = SimpleDiagnosticFactory.create(ERROR, "Only one class object is allowed per class"); + SimpleDiagnosticFactory + CLASS_OBJECT_NOT_ALLOWED = SimpleDiagnosticFactory.create(ERROR, "A class object is not allowed here"); + SimpleDiagnosticFactory + DELEGATION_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR, "Traits cannot use delegation"); + SimpleDiagnosticFactory + DELEGATION_NOT_TO_TRAIT = SimpleDiagnosticFactory.create(ERROR, "Only traits can be delegated to"); + SimpleDiagnosticFactory NO_CONSTRUCTOR = SimpleDiagnosticFactory.create(ERROR, "This class does not have a constructor"); + SimpleDiagnosticFactory NOT_A_CLASS = SimpleDiagnosticFactory.create(ERROR, "Not a class"); + SimpleDiagnosticFactory + ILLEGAL_ESCAPE_SEQUENCE = SimpleDiagnosticFactory.create(ERROR, "Illegal escape sequence"); - DiagnosticFactory LOCAL_EXTENSION_PROPERTY = DiagnosticFactory.create(ERROR, "Local extension properties are not allowed"); - DiagnosticFactory LOCAL_VARIABLE_WITH_GETTER = DiagnosticFactory.create(ERROR, "Local variables are not allowed to have getters"); - DiagnosticFactory LOCAL_VARIABLE_WITH_SETTER = DiagnosticFactory.create(ERROR, "Local variables are not allowed to have setters"); - DiagnosticFactory VAL_WITH_SETTER = DiagnosticFactory.create(ERROR, "A 'val'-property cannot have a setter"); + SimpleDiagnosticFactory + LOCAL_EXTENSION_PROPERTY = SimpleDiagnosticFactory.create(ERROR, "Local extension properties are not allowed"); + SimpleDiagnosticFactory + LOCAL_VARIABLE_WITH_GETTER = SimpleDiagnosticFactory.create(ERROR, "Local variables are not allowed to have getters"); + SimpleDiagnosticFactory + LOCAL_VARIABLE_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR, "Local variables are not allowed to have setters"); + SimpleDiagnosticFactory + VAL_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR, "A 'val'-property cannot have a setter"); - DiagnosticFactory NO_GET_METHOD = DiagnosticFactory.create(ERROR, "No get method providing array access", PositioningStrategies.POSITION_ARRAY_ACCESS); - DiagnosticFactory NO_SET_METHOD = DiagnosticFactory.create(ERROR, "No set method providing array access", PositioningStrategies.POSITION_ARRAY_ACCESS); + SimpleDiagnosticFactory NO_GET_METHOD = SimpleDiagnosticFactory + .create(ERROR, "No get method providing array access", PositioningStrategies.POSITION_ARRAY_ACCESS); + SimpleDiagnosticFactory NO_SET_METHOD = SimpleDiagnosticFactory + .create(ERROR, "No set method providing array access", PositioningStrategies.POSITION_ARRAY_ACCESS); - DiagnosticFactory INC_DEC_SHOULD_NOT_RETURN_UNIT = DiagnosticFactory.create(ERROR, "Functions inc(), dec() shouldn't return Unit to be used by operators ++, --"); + SimpleDiagnosticFactory INC_DEC_SHOULD_NOT_RETURN_UNIT = SimpleDiagnosticFactory + .create(ERROR, "Functions inc(), dec() shouldn't return Unit to be used by operators ++, --"); DiagnosticFactory2 ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT = DiagnosticFactory2.create(ERROR, "Function ''{0}'' should return Unit to be used by corresponding operator ''{1}''", NAME, ELEMENT_TEXT); AmbiguousDescriptorDiagnosticFactory ASSIGN_OPERATOR_AMBIGUITY = AmbiguousDescriptorDiagnosticFactory.create("Assignment operators ambiguity: {0}"); - DiagnosticFactory EQUALS_MISSING = DiagnosticFactory.create(ERROR, "No method 'equals(Any?) : Boolean' available"); - DiagnosticFactory ASSIGNMENT_IN_EXPRESSION_CONTEXT = DiagnosticFactory.create(ERROR, "Assignments are not expressions, and only expressions are allowed in this context"); - DiagnosticFactory NAMESPACE_IS_NOT_AN_EXPRESSION = DiagnosticFactory.create(ERROR, "'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')"); + SimpleDiagnosticFactory + EQUALS_MISSING = SimpleDiagnosticFactory.create(ERROR, "No method 'equals(Any?) : Boolean' available"); + SimpleDiagnosticFactory ASSIGNMENT_IN_EXPRESSION_CONTEXT = SimpleDiagnosticFactory + .create(ERROR, "Assignments are not expressions, and only expressions are allowed in this context"); + SimpleDiagnosticFactory NAMESPACE_IS_NOT_AN_EXPRESSION = SimpleDiagnosticFactory + .create(ERROR, "'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')"); DiagnosticFactory1 SUPER_IS_NOT_AN_EXPRESSION = DiagnosticFactory1.create(ERROR, "{0} is not an expression, it can only be used on the left-hand side of a dot ('.')"); - DiagnosticFactory DECLARATION_IN_ILLEGAL_CONTEXT = DiagnosticFactory.create(ERROR, "Declarations are not allowed in this position"); - DiagnosticFactory SETTER_PARAMETER_WITH_DEFAULT_VALUE = DiagnosticFactory.create(ERROR, "Setter parameters can not have default values"); - DiagnosticFactory NO_THIS = DiagnosticFactory.create(ERROR, "'this' is not defined in this context"); - DiagnosticFactory SUPER_NOT_AVAILABLE = DiagnosticFactory.create(ERROR, "No supertypes are accessible in this context"); - DiagnosticFactory AMBIGUOUS_SUPER = DiagnosticFactory.create(ERROR, "Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super'"); - DiagnosticFactory ABSTRACT_SUPER_CALL = DiagnosticFactory.create(ERROR, "Abstract member cannot be accessed directly"); - DiagnosticFactory NOT_A_SUPERTYPE = DiagnosticFactory.create(ERROR, "Not a supertype"); - DiagnosticFactory TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER = DiagnosticFactory.create(WARNING, "Type arguments do not need to be specified in a 'super' qualifier"); - DiagnosticFactory USELESS_CAST_STATIC_ASSERT_IS_FINE = DiagnosticFactory.create(WARNING, "No cast needed, use ':' instead"); - DiagnosticFactory USELESS_CAST = DiagnosticFactory.create(WARNING, "No cast needed"); - DiagnosticFactory CAST_NEVER_SUCCEEDS = DiagnosticFactory.create(WARNING, "This cast can never succeed"); + SimpleDiagnosticFactory + DECLARATION_IN_ILLEGAL_CONTEXT = SimpleDiagnosticFactory.create(ERROR, "Declarations are not allowed in this position"); + SimpleDiagnosticFactory + SETTER_PARAMETER_WITH_DEFAULT_VALUE = SimpleDiagnosticFactory.create(ERROR, "Setter parameters can not have default values"); + SimpleDiagnosticFactory NO_THIS = SimpleDiagnosticFactory.create(ERROR, "'this' is not defined in this context"); + SimpleDiagnosticFactory + SUPER_NOT_AVAILABLE = SimpleDiagnosticFactory.create(ERROR, "No supertypes are accessible in this context"); + SimpleDiagnosticFactory AMBIGUOUS_SUPER = SimpleDiagnosticFactory + .create(ERROR, "Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super'"); + SimpleDiagnosticFactory + ABSTRACT_SUPER_CALL = SimpleDiagnosticFactory.create(ERROR, "Abstract member cannot be accessed directly"); + SimpleDiagnosticFactory NOT_A_SUPERTYPE = SimpleDiagnosticFactory.create(ERROR, "Not a supertype"); + SimpleDiagnosticFactory TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER = SimpleDiagnosticFactory + .create(WARNING, "Type arguments do not need to be specified in a 'super' qualifier"); + SimpleDiagnosticFactory + USELESS_CAST_STATIC_ASSERT_IS_FINE = SimpleDiagnosticFactory.create(WARNING, "No cast needed, use ':' instead"); + SimpleDiagnosticFactory USELESS_CAST = SimpleDiagnosticFactory.create(WARNING, "No cast needed"); + SimpleDiagnosticFactory + CAST_NEVER_SUCCEEDS = SimpleDiagnosticFactory.create(WARNING, "This cast can never succeed"); DiagnosticFactory1 WRONG_SETTER_PARAMETER_TYPE = DiagnosticFactory1.create(ERROR, "Setter parameter type must be equal to the type of the property, i.e. {0}", RENDER_TYPE);//, DiagnosticParameters.TYPE); DiagnosticFactory1 WRONG_GETTER_RETURN_TYPE = DiagnosticFactory1.create(ERROR, "Getter return type must be equal to the type of the property, i.e. {0}", RENDER_TYPE);//, DiagnosticParameters.TYPE); DiagnosticFactory1 NO_CLASS_OBJECT = DiagnosticFactory1.create(ERROR, "Please specify constructor invocation; classifier {0} does not have a class object", NAME); - DiagnosticFactory NO_GENERICS_IN_SUPERTYPE_SPECIFIER = DiagnosticFactory.create(ERROR, "Generic arguments of the base type must be specified"); + SimpleDiagnosticFactory NO_GENERICS_IN_SUPERTYPE_SPECIFIER = SimpleDiagnosticFactory + .create(ERROR, "Generic arguments of the base type must be specified"); - DiagnosticFactory HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY = DiagnosticFactory.create(ERROR, "An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext' property"); - DiagnosticFactory HAS_NEXT_MISSING = DiagnosticFactory.create(ERROR, "Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property"); - DiagnosticFactory HAS_NEXT_FUNCTION_AMBIGUITY = DiagnosticFactory.create(ERROR, "Function 'iterator().hasNext()' is ambiguous for this expression"); - DiagnosticFactory HAS_NEXT_MUST_BE_READABLE = DiagnosticFactory.create(ERROR, "The 'iterator().hasNext' property of the loop range must be readable"); + SimpleDiagnosticFactory HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY = SimpleDiagnosticFactory + .create(ERROR, "An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext' property"); + SimpleDiagnosticFactory HAS_NEXT_MISSING = SimpleDiagnosticFactory + .create(ERROR, "Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property"); + SimpleDiagnosticFactory HAS_NEXT_FUNCTION_AMBIGUITY = SimpleDiagnosticFactory + .create(ERROR, "Function 'iterator().hasNext()' is ambiguous for this expression"); + SimpleDiagnosticFactory HAS_NEXT_MUST_BE_READABLE = SimpleDiagnosticFactory + .create(ERROR, "The 'iterator().hasNext' property of the loop range must be readable"); DiagnosticFactory1 HAS_NEXT_PROPERTY_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", RENDER_TYPE); DiagnosticFactory1 HAS_NEXT_FUNCTION_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", RENDER_TYPE); - DiagnosticFactory NEXT_AMBIGUITY = DiagnosticFactory.create(ERROR, "Function 'iterator().next()' is ambiguous for this expression"); - DiagnosticFactory NEXT_MISSING = DiagnosticFactory.create(ERROR, "Loop range must have an 'iterator().next()' function"); - DiagnosticFactory ITERATOR_MISSING = DiagnosticFactory.create(ERROR, "For-loop range must have an iterator() method"); + SimpleDiagnosticFactory + NEXT_AMBIGUITY = SimpleDiagnosticFactory.create(ERROR, "Function 'iterator().next()' is ambiguous for this expression"); + SimpleDiagnosticFactory + NEXT_MISSING = SimpleDiagnosticFactory.create(ERROR, "Loop range must have an 'iterator().next()' function"); + SimpleDiagnosticFactory + ITERATOR_MISSING = SimpleDiagnosticFactory.create(ERROR, "For-loop range must have an iterator() method"); AmbiguousDescriptorDiagnosticFactory ITERATOR_AMBIGUITY = AmbiguousDescriptorDiagnosticFactory.create("Method 'iterator()' is ambiguous for this expression: {0}"); DiagnosticFactory1 COMPARE_TO_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "compareTo() must return Int, but returns {0}", RENDER_TYPE); DiagnosticFactory1 CALLEE_NOT_A_FUNCTION = DiagnosticFactory1.create(ERROR, "Expecting a function type, but found {0}", RENDER_TYPE); - DiagnosticFactory RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY = DiagnosticFactory.create(ERROR, "Returns are not allowed for functions with expression body. Use block body in '{...}'"); - DiagnosticFactory NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY = DiagnosticFactory.create(ERROR, "A 'return' expression required in a function with a block body ('{...}')", new PositioningStrategy() { - @NotNull - @Override - public List mark(@NotNull JetDeclarationWithBody element) { - JetExpression bodyExpression = element.getBodyExpression(); - if (!(bodyExpression instanceof JetBlockExpression)) return Collections.emptyList(); - JetBlockExpression blockExpression = (JetBlockExpression) bodyExpression; - TextRange lastBracketRange = blockExpression.getLastBracketRange(); - if (lastBracketRange == null) return Collections.emptyList(); - return markRange(lastBracketRange); - } - }); + SimpleDiagnosticFactory RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY = SimpleDiagnosticFactory + .create(ERROR, "Returns are not allowed for functions with expression body. Use block body in '{...}'"); + SimpleDiagnosticFactory NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY = SimpleDiagnosticFactory + .create(ERROR, "A 'return' expression required in a function with a block body ('{...}')", + new PositioningStrategy() { + @NotNull + @Override + public List mark(@NotNull JetDeclarationWithBody element) { + JetExpression bodyExpression = element.getBodyExpression(); + if (!(bodyExpression instanceof JetBlockExpression)) return Collections.emptyList(); + JetBlockExpression blockExpression = (JetBlockExpression)bodyExpression; + TextRange lastBracketRange = blockExpression.getLastBracketRange(); + if (lastBracketRange == null) return Collections.emptyList(); + return markRange(lastBracketRange); + } + }); DiagnosticFactory1 RETURN_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "This function must return a value of type {0}", RENDER_TYPE); DiagnosticFactory1 EXPECTED_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "Expected a value of type {0}", RENDER_TYPE); DiagnosticFactory1 ASSIGNMENT_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "Expected a value of type {0}. Assignment operation is not an expression, so it does not return any value", RENDER_TYPE); @@ -276,7 +354,7 @@ public interface Errors { DiagnosticFactory1 TOO_MANY_ARGUMENTS = DiagnosticFactory1.create(ERROR, "Too many arguments for {0}"); DiagnosticFactory1 ERROR_COMPILE_TIME_VALUE = DiagnosticFactory1.create(ERROR, "{0}"); - DiagnosticFactory ELSE_MISPLACED_IN_WHEN = DiagnosticFactory.create( + SimpleDiagnosticFactory ELSE_MISPLACED_IN_WHEN = SimpleDiagnosticFactory.create( ERROR, "'else' entry must be the last one in a when-expression", new PositioningStrategy() { @NotNull @Override @@ -287,7 +365,8 @@ public interface Errors { } }); - DiagnosticFactory NO_ELSE_IN_WHEN = new DiagnosticFactory(ERROR, "'when' expression must contain 'else' branch", new PositioningStrategy() { + SimpleDiagnosticFactory + NO_ELSE_IN_WHEN = new SimpleDiagnosticFactory(ERROR, "'when' expression must contain 'else' branch", new PositioningStrategy() { @NotNull @Override public List mark(@NotNull JetWhenExpression element) { @@ -295,40 +374,50 @@ public interface Errors { return markElement(element.getWhenKeywordElement()); } }); - DiagnosticFactory TYPE_MISMATCH_IN_RANGE = new DiagnosticFactory(ERROR, "Type mismatch: incompatible types of range and element checked in it", new PositioningStrategy() { + SimpleDiagnosticFactory TYPE_MISMATCH_IN_RANGE = new SimpleDiagnosticFactory(ERROR, "Type mismatch: incompatible types of range and element checked in it", new PositioningStrategy() { @NotNull @Override public List mark(@NotNull JetWhenConditionInRange condition) { return markElement(condition.getOperationReference()); } }); - DiagnosticFactory CYCLIC_INHERITANCE_HIERARCHY = DiagnosticFactory.create(ERROR, "There's a cycle in the inheritance hierarchy for this type"); + SimpleDiagnosticFactory CYCLIC_INHERITANCE_HIERARCHY = SimpleDiagnosticFactory + .create(ERROR, "There's a cycle in the inheritance hierarchy for this type"); - DiagnosticFactory MANY_CLASSES_IN_SUPERTYPE_LIST = DiagnosticFactory.create(ERROR, "Only one class may appear in a supertype list"); - DiagnosticFactory SUPERTYPE_NOT_A_CLASS_OR_TRAIT = DiagnosticFactory.create(ERROR, "Only classes and traits may serve as supertypes"); - DiagnosticFactory SUPERTYPE_INITIALIZED_IN_TRAIT = DiagnosticFactory.create(ERROR, "Traits cannot initialize supertypes"); - DiagnosticFactory CONSTRUCTOR_IN_TRAIT = DiagnosticFactory.create(ERROR, "A trait may not have a constructor"); - DiagnosticFactory SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED = DiagnosticFactory.create(WARNING, "Secondary constructors are not supported"); - DiagnosticFactory SUPERTYPE_APPEARS_TWICE = DiagnosticFactory.create(ERROR, "A supertype appears twice"); - DiagnosticFactory FINAL_SUPERTYPE = DiagnosticFactory.create(ERROR, "This type is final, so it cannot be inherited from"); + SimpleDiagnosticFactory + MANY_CLASSES_IN_SUPERTYPE_LIST = SimpleDiagnosticFactory.create(ERROR, "Only one class may appear in a supertype list"); + SimpleDiagnosticFactory + SUPERTYPE_NOT_A_CLASS_OR_TRAIT = SimpleDiagnosticFactory.create(ERROR, "Only classes and traits may serve as supertypes"); + SimpleDiagnosticFactory + SUPERTYPE_INITIALIZED_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR, "Traits cannot initialize supertypes"); + SimpleDiagnosticFactory CONSTRUCTOR_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR, "A trait may not have a constructor"); + SimpleDiagnosticFactory + SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED = SimpleDiagnosticFactory.create(WARNING, "Secondary constructors are not supported"); + SimpleDiagnosticFactory SUPERTYPE_APPEARS_TWICE = SimpleDiagnosticFactory.create(ERROR, "A supertype appears twice"); + SimpleDiagnosticFactory + FINAL_SUPERTYPE = SimpleDiagnosticFactory.create(ERROR, "This type is final, so it cannot be inherited from"); DiagnosticFactory1 ILLEGAL_SELECTOR = DiagnosticFactory1.create(ERROR, "Expression ''{0}'' cannot be a selector (occur after a dot)"); - DiagnosticFactory VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION = DiagnosticFactory.create(ERROR, "A type annotation is required on a value parameter"); - DiagnosticFactory BREAK_OR_CONTINUE_OUTSIDE_A_LOOP = DiagnosticFactory.create(ERROR, "'break' and 'continue' are only allowed inside a loop"); + SimpleDiagnosticFactory VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION = SimpleDiagnosticFactory + .create(ERROR, "A type annotation is required on a value parameter"); + SimpleDiagnosticFactory BREAK_OR_CONTINUE_OUTSIDE_A_LOOP = SimpleDiagnosticFactory + .create(ERROR, "'break' and 'continue' are only allowed inside a loop"); DiagnosticFactory1 NOT_A_LOOP_LABEL = DiagnosticFactory1.create(ERROR, "The label ''{0}'' does not denote a loop"); DiagnosticFactory1 NOT_A_RETURN_LABEL = DiagnosticFactory1.create(ERROR, "The label ''{0}'' does not reference to a context from which we can return"); - DiagnosticFactory ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR = DiagnosticFactory.create(ERROR, "Anonymous initializers are only allowed in the presence of a primary constructor"); - DiagnosticFactory NULLABLE_SUPERTYPE = DiagnosticFactory.create(ERROR, "A supertype cannot be nullable", new PositioningStrategy() { - @NotNull - @Override - public List mark(@NotNull JetNullableType element) { - return markNode(element.getQuestionMarkNode()); - } - }); + SimpleDiagnosticFactory ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR = SimpleDiagnosticFactory + .create(ERROR, "Anonymous initializers are only allowed in the presence of a primary constructor"); + SimpleDiagnosticFactory NULLABLE_SUPERTYPE = SimpleDiagnosticFactory + .create(ERROR, "A supertype cannot be nullable", new PositioningStrategy() { + @NotNull + @Override + public List mark(@NotNull JetNullableType element) { + return markNode(element.getQuestionMarkNode()); + } + }); DiagnosticFactory1 UNSAFE_CALL = DiagnosticFactory1.create(ERROR, "Only safe calls (?.) are allowed on a nullable receiver of type {0}", RENDER_TYPE); - DiagnosticFactory AMBIGUOUS_LABEL = DiagnosticFactory.create(ERROR, "Ambiguous label"); + SimpleDiagnosticFactory AMBIGUOUS_LABEL = SimpleDiagnosticFactory.create(ERROR, "Ambiguous label"); DiagnosticFactory1 UNSUPPORTED = DiagnosticFactory1.create(ERROR, "Unsupported [{0}]"); DiagnosticFactory1 UNNECESSARY_SAFE_CALL = DiagnosticFactory1.create(WARNING, "Unnecessary safe call on a non-null receiver of type {0}", RENDER_TYPE); DiagnosticFactory1 UNNECESSARY_NOT_NULL_ASSERTION = DiagnosticFactory1.create(WARNING, "Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", RENDER_TYPE); @@ -347,7 +436,8 @@ public interface Errors { DiagnosticFactory2 TYPE_MISMATCH_IN_TUPLE_PATTERN = DiagnosticFactory2.create(ERROR, "Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, TO_STRING); // TODO: message DiagnosticFactory2 TYPE_MISMATCH_IN_BINDING_PATTERN = DiagnosticFactory2.create(ERROR, "{0} must be a supertype of {1}. Use 'is' to match against {0}", RENDER_TYPE, RENDER_TYPE); DiagnosticFactory2 INCOMPATIBLE_TYPES = DiagnosticFactory2.create(ERROR, "Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE); - DiagnosticFactory EXPECTED_CONDITION = DiagnosticFactory.create(ERROR, "Expected condition of Boolean type"); + SimpleDiagnosticFactory + EXPECTED_CONDITION = SimpleDiagnosticFactory.create(ERROR, "Expected condition of Boolean type"); DiagnosticFactory1 CANNOT_CHECK_FOR_ERASED = DiagnosticFactory1.create(ERROR, "Cannot check for instance of erased type: {0}", RENDER_TYPE); DiagnosticFactory2 UNCHECKED_CAST = DiagnosticFactory2.create(WARNING, "Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE); @@ -438,9 +528,11 @@ public interface Errors { AmbiguousDescriptorDiagnosticFactory NONE_APPLICABLE = new AmbiguousDescriptorDiagnosticFactory("None of the following functions can be called with the arguments supplied: {0}"); DiagnosticFactory1 NO_VALUE_FOR_PARAMETER = DiagnosticFactory1.create(ERROR, "No value passed for parameter {0}", DescriptorRenderer.TEXT); DiagnosticFactory1 MISSING_RECEIVER = DiagnosticFactory1.create(ERROR, "A receiver of type {0} is required", RENDER_TYPE); - DiagnosticFactory NO_RECEIVER_ADMITTED = DiagnosticFactory.create(ERROR, "No receiver can be passed to this function or property"); + SimpleDiagnosticFactory + NO_RECEIVER_ADMITTED = SimpleDiagnosticFactory.create(ERROR, "No receiver can be passed to this function or property"); - DiagnosticFactory CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS = DiagnosticFactory.create(ERROR, "Can not create an instance of an abstract class"); + SimpleDiagnosticFactory CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS = SimpleDiagnosticFactory + .create(ERROR, "Can not create an instance of an abstract class"); DiagnosticFactory1 TYPE_INFERENCE_FAILED = DiagnosticFactory1.create(ERROR, "Type inference failed: {0}"); DiagnosticFactory1 WRONG_NUMBER_OF_TYPE_ARGUMENTS = DiagnosticFactory1.create(ERROR, "{0} type arguments expected", new Renderer() { @NotNull @@ -453,8 +545,9 @@ public interface Errors { DiagnosticFactory1 UNRESOLVED_IDE_TEMPLATE = DiagnosticFactory1.create(ERROR, "Unresolved IDE template: {0}"); - DiagnosticFactory DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED = DiagnosticFactory.create(WARNING, "This expression is treated as an argument to the function call on the previous line. " + - "Separate it with a semicolon (;) if it is not intended to be an argument."); + SimpleDiagnosticFactory DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED = SimpleDiagnosticFactory + .create(WARNING, "This expression is treated as an argument to the function call on the previous line. " + + "Separate it with a semicolon (;) if it is not intended to be an argument."); DiagnosticFactory1 NOT_AN_ANNOTATION_CLASS = DiagnosticFactory1.create(ERROR, "{0} is not an annotation class"); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithPsiElement.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/SimpleDiagnostic.java similarity index 79% rename from compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithPsiElement.java rename to compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/SimpleDiagnostic.java index 603c0aed730..ddd531f827d 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithPsiElement.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/SimpleDiagnostic.java @@ -25,17 +25,17 @@ import java.util.List; /** * @author svtk */ -public class DiagnosticWithPsiElement extends AbstractDiagnostic { - public DiagnosticWithPsiElement(@NotNull E psiElement, - @NotNull DiagnosticFactory factory, +public class SimpleDiagnostic extends AbstractDiagnostic { + public SimpleDiagnostic(@NotNull E psiElement, + @NotNull SimpleDiagnosticFactory factory, @NotNull Severity severity) { super(psiElement, factory, severity); } @NotNull @Override - public DiagnosticFactory getFactory() { - return (DiagnosticFactory)super.getFactory(); + public SimpleDiagnosticFactory getFactory() { + return (SimpleDiagnosticFactory)super.getFactory(); } @NotNull diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/SimpleDiagnosticFactory.java similarity index 62% rename from compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory.java rename to compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/SimpleDiagnosticFactory.java index b1f03498b4f..4a97b1e460b 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/SimpleDiagnosticFactory.java @@ -22,20 +22,20 @@ import org.jetbrains.annotations.NotNull; /** * @author svtk */ -public class DiagnosticFactory extends DiagnosticFactoryWithPsiElement { +public class SimpleDiagnosticFactory extends DiagnosticFactoryWithPsiElement { protected final String message; - protected DiagnosticFactory(Severity severity, String message, PositioningStrategy positioningStrategy) { + protected SimpleDiagnosticFactory(Severity severity, String message, PositioningStrategy positioningStrategy) { super(severity, positioningStrategy); this.message = message; } - public static DiagnosticFactory create(Severity severity, String message) { + public static SimpleDiagnosticFactory create(Severity severity, String message) { return create(severity, message, PositioningStrategies.DEFAULT); } - public static DiagnosticFactory create(Severity severity, String message, PositioningStrategy positioningStrategy) { - return new DiagnosticFactory(severity, message, positioningStrategy); + public static SimpleDiagnosticFactory create(Severity severity, String message, PositioningStrategy positioningStrategy) { + return new SimpleDiagnosticFactory(severity, message, positioningStrategy); } String getMessage() { @@ -44,6 +44,6 @@ public class DiagnosticFactory extends DiagnosticFactoryWi @NotNull public ParametrizedDiagnostic on(@NotNull E element) { - return new DiagnosticWithPsiElement(element, this, severity); + return new SimpleDiagnostic(element, this, severity); } } \ No newline at end of file From 6a13510741dacb4f74a3a1d146a0a95a99de6989 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 12 Apr 2012 13:56:53 +0400 Subject: [PATCH 004/147] Replaced Diagnostic.getMessage() with DiagnosticRenderer.render() calls. Made Diagnostic.getMessage() deprecated, introduced DiagnosticRender interface and default implementation for it. --- .../jet/compiler/CompileSession.java | 7 +-- .../compiler/DefaultDiagnosticRenderer.java | 39 ++++++++++++++++ .../jet/lang/diagnostics/Diagnostic.java | 1 + .../lang/diagnostics/DiagnosticHolder.java | 3 +- .../lang/diagnostics/DiagnosticRenderer.java | 30 ++++++++++++ .../tests/org/jetbrains/jet/JetTestUtils.java | 6 ++- .../jet/plugin/highlighter/JetPsiChecker.java | 10 ++-- idea/testData/checker/infos/Autocasts.jet | 46 +++++++++---------- 8 files changed, 107 insertions(+), 35 deletions(-) create mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java create mode 100644 compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java index 952f4cdb2c7..1e26ccf2fa9 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java @@ -35,10 +35,7 @@ import org.jetbrains.jet.lang.descriptors.ClassDescriptor; import org.jetbrains.jet.lang.descriptors.ClassOrNamespaceDescriptor; import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.descriptors.ModuleDescriptor; -import org.jetbrains.jet.lang.diagnostics.Diagnostic; -import org.jetbrains.jet.lang.diagnostics.SimpleDiagnosticFactory; -import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils; -import org.jetbrains.jet.lang.diagnostics.Severity; +import org.jetbrains.jet.lang.diagnostics.*; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; @@ -150,7 +147,7 @@ public class CompileSession { DiagnosticUtils.LineAndColumn lineAndColumn = DiagnosticUtils.getLineAndColumn(diagnostic); VirtualFile virtualFile = diagnostic.getPsiFile().getVirtualFile(); String path = virtualFile == null ? null : virtualFile.getPath(); - collector.report(diagnostic.getSeverity(), diagnostic.getMessage(), path, lineAndColumn.getLine(), lineAndColumn.getColumn()); + collector.report(diagnostic.getSeverity(), DefaultDiagnosticRenderer.INSTANCE.render(diagnostic), path, lineAndColumn.getLine(), lineAndColumn.getColumn()); } @NotNull diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java b/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java new file mode 100644 index 00000000000..55d4b2f9d8e --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java @@ -0,0 +1,39 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.compiler; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.lang.diagnostics.Diagnostic; +import org.jetbrains.jet.lang.diagnostics.DiagnosticRenderer; + +/** + * @author Evgeny Gerashchenko + * @since 4/12/12 + */ +public class DefaultDiagnosticRenderer implements DiagnosticRenderer { + public static final DefaultDiagnosticRenderer INSTANCE = new DefaultDiagnosticRenderer(); + + private DefaultDiagnosticRenderer() { + } + + @NotNull + @Override + public String render(@Nullable Diagnostic diagnostic) { + return diagnostic.getMessage(); + } +} diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Diagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Diagnostic.java index d4369a0513d..58049c26521 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Diagnostic.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Diagnostic.java @@ -31,6 +31,7 @@ public interface Diagnostic { @NotNull AbstractDiagnosticFactory getFactory(); + @Deprecated @NotNull String getMessage(); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticHolder.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticHolder.java index f0c110e14bd..c1f1472d2c5 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticHolder.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticHolder.java @@ -17,7 +17,6 @@ package org.jetbrains.jet.lang.diagnostics; import com.intellij.openapi.util.TextRange; -import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; @@ -38,7 +37,7 @@ public interface DiagnosticHolder { if (diagnostic.getSeverity() == Severity.ERROR) { PsiFile psiFile = diagnostic.getPsiFile(); List textRanges = diagnostic.getTextRanges(); - throw new IllegalStateException(diagnostic.getMessage() + DiagnosticUtils.atLocation(psiFile, textRanges.get(0))); + throw new IllegalStateException(diagnostic.getFactory().getName() + DiagnosticUtils.atLocation(psiFile, textRanges.get(0))); } } }; diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java new file mode 100644 index 00000000000..d820c6cdf11 --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java @@ -0,0 +1,30 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.lang.diagnostics; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * @author Evgeny Gerashchenko + * @since 4/12/12 + */ +public interface DiagnosticRenderer extends Renderer { + @NotNull + @Override + String render(@Nullable Diagnostic diagnostic); +} diff --git a/compiler/tests/org/jetbrains/jet/JetTestUtils.java b/compiler/tests/org/jetbrains/jet/JetTestUtils.java index 7ce129cc6d8..8bcd54cc0c8 100644 --- a/compiler/tests/org/jetbrains/jet/JetTestUtils.java +++ b/compiler/tests/org/jetbrains/jet/JetTestUtils.java @@ -26,6 +26,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.compiler.JetCoreEnvironment; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; +import org.jetbrains.jet.compiler.DefaultDiagnosticRenderer; import org.jetbrains.jet.lang.diagnostics.Diagnostic; import org.jetbrains.jet.lang.diagnostics.Severity; import org.jetbrains.jet.lang.diagnostics.UnresolvedReferenceDiagnostic; @@ -153,11 +154,14 @@ public class JetTestUtils { @Override public void report(@NotNull Diagnostic diagnostic) { if (diagnostic.getSeverity() == Severity.ERROR) { - throw new IllegalStateException(diagnostic.getMessage()); + throw new IllegalStateException(DefaultDiagnosticRenderer.INSTANCE.render(diagnostic)); } } }; + private JetTestUtils() { + } + public static AnalyzeExhaust analyzeFile(@NotNull JetFile namespace, @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory) { return AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegration(namespace, flowDataTraceFactory, CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR)); diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java b/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java index 3fcbddeae37..4bea587e9cd 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java @@ -33,6 +33,7 @@ import com.intellij.psi.PsiReference; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; +import org.jetbrains.jet.compiler.DefaultDiagnosticRenderer; import org.jetbrains.jet.lang.diagnostics.*; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetReferenceExpression; @@ -154,7 +155,7 @@ public class JetPsiChecker implements Annotator { for (TextRange range : mrr.getRanges()) { Annotation annotation = holder.createErrorAnnotation( range.shiftRight(referenceExpression.getTextOffset()), - diagnostic.getMessage()); + getMessage(diagnostic)); registerQuickFix(annotation, diagnostic); @@ -163,7 +164,7 @@ public class JetPsiChecker implements Annotator { } else { for (TextRange textRange : textRanges) { - Annotation annotation = holder.createErrorAnnotation(textRange, diagnostic.getMessage()); + Annotation annotation = holder.createErrorAnnotation(textRange, getMessage(diagnostic)); registerQuickFix(annotation, diagnostic); annotation.setHighlightType(ProblemHighlightType.LIKE_UNKNOWN_SYMBOL); } @@ -239,10 +240,11 @@ public class JetPsiChecker implements Annotator { @NotNull private static String getMessage(@NotNull Diagnostic diagnostic) { + String message = DefaultDiagnosticRenderer.INSTANCE.render(diagnostic); if (ApplicationManager.getApplication().isInternal() || ApplicationManager.getApplication().isUnitTestMode()) { - return "[" + diagnostic.getFactory().getName() + "] " + diagnostic.getMessage(); + return "[" + diagnostic.getFactory().getName() + "] " + message; } - return diagnostic.getMessage(); + return message; } @Nullable diff --git a/idea/testData/checker/infos/Autocasts.jet b/idea/testData/checker/infos/Autocasts.jet index 9bd17ee710a..b665d066470 100644 --- a/idea/testData/checker/infos/Autocasts.jet +++ b/idea/testData/checker/infos/Autocasts.jet @@ -8,19 +8,19 @@ class B() : A() { fun f9(a : A?) { a?.foo() - a?.bar() + a?.bar() if (a is B) { a.bar() a.foo() } a?.foo() - a?.bar() + a?.bar() if (!(a is B)) { - a?.bar() + a?.bar() a?.foo() } if (!(a is B) || a.bar() == #()) { - a?.bar() + a?.bar() } if (!(a is B)) { return; @@ -55,7 +55,7 @@ fun f11(a : A?) { is B -> a.bar() is A -> a.foo() is Any -> a.foo() - is Any? -> a.bar() + is Any? -> a.bar() else -> a?.foo() } } @@ -65,7 +65,7 @@ fun f12(a : A?) { is B -> a.bar() is A -> a.foo() is Any -> a.foo(); - is Any? -> a.bar() + is Any? -> a.bar() is val c : B -> c.foo() is val c is C -> c.bar() is val c is C -> a.bar() @@ -73,7 +73,7 @@ fun f12(a : A?) { } if (a is val b) { - a?.bar() + a?.bar() b?.foo() } if (a is val b is B) { @@ -90,17 +90,17 @@ fun f13(a : A?) { } else { a?.foo() - c.bar() + c.bar() } a?.foo() if (!(a is val c is B)) { a?.foo() - c.bar() + c.bar() } else { a.foo() - c.bar() + c.bar() } a?.foo() @@ -110,16 +110,16 @@ fun f13(a : A?) { } else { a?.foo() - c.bar() + c.bar() } if (!(a is val c is B) || !(a is val x is C)) { - x - c + x + c } else { - x - c + x + c } if (!(a is val c is B) || !(a is val c is C)) { @@ -127,21 +127,21 @@ fun f13(a : A?) { if (!(a is val c is B)) return a.bar() - c.foo() - c.bar() + c.foo() + c.bar() } fun f14(a : A?) { while (!(a is val c is B)) { } a.bar() - c.bar() + c.bar() } fun f15(a : A?) { do { } while (!(a is val c is B)) a.bar() - c.bar() + c.bar() } fun getStringLength(obj : Any) : Char? { @@ -217,20 +217,20 @@ fun declarationInsidePattern(x: #(Any, Any)): String = when(x) { is #(val a is S fun mergeAutocasts(a: Any?) { if (a is String || a is Int) { - a.compareTo("") + a.compareTo("") a.toString() } if (a is Int || a is String) { - a.compareTo("") + a.compareTo("") } when (a) { - is String, is Any -> a.compareTo("") + is String, is Any -> a.compareTo("") } if (a is String && a is Any) { val i: Int = a.compareTo("") } if (a is String && a.compareTo("") == 0) {} - if (a is String || a.compareTo("") == 0) {} + if (a is String || a.compareTo("") == 0) {} } //mutability From 46d929efa1d0e75bc38e18dc61bad42618003d29 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 12 Apr 2012 15:50:29 +0400 Subject: [PATCH 005/147] Introduced factory to renderer map in DefaultDiagnosticRenderer. Added first renderer there. --- .../compiler/DefaultDiagnosticRenderer.java | 48 +++++++++++++++++-- .../lang/diagnostics/DiagnosticRenderer.java | 4 +- .../DiagnosticWithParameters1.java | 1 + .../DiagnosticWithParameters2.java | 2 + .../DiagnosticWithParameters3.java | 3 ++ 5 files changed, 52 insertions(+), 6 deletions(-) diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java b/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java index 55d4b2f9d8e..c66171df830 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java @@ -16,24 +16,64 @@ package org.jetbrains.jet.compiler; +import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.lang.diagnostics.Diagnostic; -import org.jetbrains.jet.lang.diagnostics.DiagnosticRenderer; +import org.jetbrains.jet.lang.diagnostics.*; +import org.jetbrains.jet.lang.psi.JetFile; + +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.Map; + +import static org.jetbrains.jet.lang.diagnostics.Errors.EXCEPTION_WHILE_ANALYZING; /** * @author Evgeny Gerashchenko * @since 4/12/12 */ -public class DefaultDiagnosticRenderer implements DiagnosticRenderer { +public class DefaultDiagnosticRenderer implements DiagnosticRenderer { public static final DefaultDiagnosticRenderer INSTANCE = new DefaultDiagnosticRenderer(); + private final Map> factoryToRenderer = new HashMap>(); + private DefaultDiagnosticRenderer() { + factoryToRenderer.put(EXCEPTION_WHILE_ANALYZING, new DiagnosticWithParameters1Renderer("{0}", new Renderer() { + @NotNull + @Override + public String render(@Nullable Throwable e) { + return e.getClass().getSimpleName() + ": " + e.getMessage(); + } + })); } @NotNull @Override public String render(@Nullable Diagnostic diagnostic) { - return diagnostic.getMessage(); + if (diagnostic == null) { + throw new IllegalArgumentException("Diagnostic passed to diagnostic renderer cannot be null"); + } + DiagnosticRenderer renderer = factoryToRenderer.get(diagnostic.getFactory()); + if (renderer == null) { + return diagnostic.getMessage(); // TODO throw IllegalArgumentException instead + } + //noinspection unchecked + return renderer.render(diagnostic); + } + + private class DiagnosticWithParameters1Renderer implements DiagnosticRenderer> { + private final MessageFormat messageFormat; + private final Renderer rendererForA; + + private DiagnosticWithParameters1Renderer(@NotNull String message, @NotNull Renderer rendererForA) { + this.messageFormat = new MessageFormat(message); + this.rendererForA = rendererForA; + } + + @NotNull + @Override + public String render(@Nullable DiagnosticWithParameters1 diagnostic) { + return diagnostic == null ? "null" : messageFormat.format(new Object[]{rendererForA.render(diagnostic.getA())}); + } } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java index d820c6cdf11..8e0d505740e 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java @@ -23,8 +23,8 @@ import org.jetbrains.annotations.Nullable; * @author Evgeny Gerashchenko * @since 4/12/12 */ -public interface DiagnosticRenderer extends Renderer { +public interface DiagnosticRenderer extends Renderer { @NotNull @Override - String render(@Nullable Diagnostic diagnostic); + String render(@Nullable D diagnostic); } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java index e02675d5c1a..147e8da5c0e 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java @@ -55,6 +55,7 @@ public class DiagnosticWithParameters1 extends Abstract return getFactory().getTextRanges(this); } + @NotNull public A getA() { return a; } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java index 031d5805a15..fa7f24140b2 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java @@ -58,10 +58,12 @@ public class DiagnosticWithParameters2 extends Abstr return getFactory().getTextRanges(this); } + @NotNull public A getA() { return a; } + @NotNull public B getB() { return b; } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java index 82ee507aa85..ded5998fd7e 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java @@ -61,14 +61,17 @@ public class DiagnosticWithParameters3 extends Ab return getFactory().getTextRanges(this); } + @NotNull public A getA() { return a; } + @NotNull public B getB() { return b; } + @NotNull public C getC() { return c; } From 7be6fe84beac9cde4b354d3197afa27374762db2 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 12 Apr 2012 18:27:29 +0400 Subject: [PATCH 006/147] Made single parameter of Renderer.render() @NotNull, because argument was almost never @Nullable on call-sites. --- .../compiler/DefaultDiagnosticRenderer.java | 12 ++++------- .../AmbiguousDescriptorDiagnosticFactory.java | 2 +- .../lang/diagnostics/DiagnosticRenderer.java | 3 +-- .../jet/lang/diagnostics/Errors.java | 20 +++++++++---------- .../jet/lang/diagnostics/Renderer.java | 7 ++----- .../jet/lang/diagnostics/Renderers.java | 17 ++++++---------- .../jet/resolve/DescriptorRenderer.java | 3 +-- .../jet/resolve/ExpectedResolveData.java | 15 ++++++++++---- .../highlighter/JetLineMarkerProvider.java | 6 +++++- .../libraries/DecompiledDataFactory.java | 2 +- 10 files changed, 41 insertions(+), 46 deletions(-) diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java b/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java index c66171df830..16f97836827 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java @@ -18,7 +18,6 @@ package org.jetbrains.jet.compiler; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.diagnostics.*; import org.jetbrains.jet.lang.psi.JetFile; @@ -41,7 +40,7 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer factoryToRenderer.put(EXCEPTION_WHILE_ANALYZING, new DiagnosticWithParameters1Renderer("{0}", new Renderer() { @NotNull @Override - public String render(@Nullable Throwable e) { + public String render(@NotNull Throwable e) { return e.getClass().getSimpleName() + ": " + e.getMessage(); } })); @@ -49,10 +48,7 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer @NotNull @Override - public String render(@Nullable Diagnostic diagnostic) { - if (diagnostic == null) { - throw new IllegalArgumentException("Diagnostic passed to diagnostic renderer cannot be null"); - } + public String render(@NotNull Diagnostic diagnostic) { DiagnosticRenderer renderer = factoryToRenderer.get(diagnostic.getFactory()); if (renderer == null) { return diagnostic.getMessage(); // TODO throw IllegalArgumentException instead @@ -72,8 +68,8 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer @NotNull @Override - public String render(@Nullable DiagnosticWithParameters1 diagnostic) { - return diagnostic == null ? "null" : messageFormat.format(new Object[]{rendererForA.render(diagnostic.getA())}); + public String render(@NotNull DiagnosticWithParameters1 diagnostic) { + return messageFormat.format(new Object[]{rendererForA.render(diagnostic.getA())}); } } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java index 57cf016fdb4..4e69661a707 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java @@ -41,7 +41,7 @@ public class AmbiguousDescriptorDiagnosticFactory extends DiagnosticFactory1>>() { @NotNull @Override - public String render(@Nullable Collection> argument) { + public String render(@NotNull Collection> argument) { StringBuilder stringBuilder = new StringBuilder("\n"); for (ResolvedCall call : argument) { stringBuilder.append(DescriptorRenderer.TEXT.render(call.getResultingDescriptor())).append("\n"); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java index 8e0d505740e..c71d686fc0f 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java @@ -17,7 +17,6 @@ package org.jetbrains.jet.lang.diagnostics; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; /** * @author Evgeny Gerashchenko @@ -26,5 +25,5 @@ import org.jetbrains.annotations.Nullable; public interface DiagnosticRenderer extends Renderer { @NotNull @Override - String render(@Nullable D diagnostic); + String render(@NotNull D diagnostic); } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java index 991f03e296c..d50b57581bf 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java @@ -49,7 +49,7 @@ public interface Errors { DiagnosticFactory1 EXCEPTION_WHILE_ANALYZING = DiagnosticFactory1.create(ERROR, "{0}", new Renderer() { @NotNull @Override - public String render(@Nullable Throwable e) { + public String render(@NotNull Throwable e) { return e.getClass().getSimpleName() + ": " + e.getMessage(); } }); @@ -70,8 +70,7 @@ public interface Errors { new Renderer>() { @NotNull @Override - public String render(@Nullable Collection element) { - assert element != null; + public String render(@NotNull Collection element) { StringBuilder sb = new StringBuilder(); for (Iterator iterator = element.iterator(); iterator.hasNext(); ) { JetKeywordToken modifier = iterator.next(); @@ -337,8 +336,7 @@ public interface Errors { DiagnosticFactory1 EXPRESSION_EXPECTED = DiagnosticFactory1.create(ERROR, "{0} is not an expression, and only expression are allowed here", new Renderer() { @NotNull @Override - public String render(@Nullable JetExpression expression) { - assert expression != null; + public String render(@NotNull JetExpression expression) { String expressionType = expression.toString(); return expressionType.substring(0, 1) + expressionType.substring(1).toLowerCase(); } @@ -424,8 +422,8 @@ public interface Errors { DiagnosticFactory2 NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER = DiagnosticFactory2.create(ERROR, "{0} does not refer to a type parameter of {1}", new Renderer() { @NotNull @Override - public String render(@Nullable JetTypeConstraint typeConstraint) { - assert typeConstraint != null; + public String render(@NotNull JetTypeConstraint typeConstraint) { + //noinspection ConstantConditions return typeConstraint.getSubjectTypeParameterName().getReferencedName(); } }, NAME); @@ -446,7 +444,7 @@ public interface Errors { DiagnosticFactory3.create(ERROR, "Type parameter {0} of {1} has inconsistent values: {2}", NAME, DescriptorRenderer.TEXT, new Renderer>() { @NotNull @Override - public String render(@Nullable Collection types) { + public String render(@NotNull Collection types) { StringBuilder builder = new StringBuilder(); for (Iterator iterator = types.iterator(); iterator.hasNext(); ) { JetType jetType = iterator.next(); @@ -462,7 +460,8 @@ public interface Errors { DiagnosticFactory3 EQUALITY_NOT_APPLICABLE = DiagnosticFactory3.create(ERROR, "Operator {0} cannot be applied to {1} and {2}", new Renderer() { @NotNull @Override - public String render(@Nullable JetSimpleNameExpression nameExpression) { + public String render(@NotNull JetSimpleNameExpression nameExpression) { + //noinspection ConstantConditions return nameExpression.getReferencedName(); } }, TO_STRING, TO_STRING); @@ -537,8 +536,7 @@ public interface Errors { DiagnosticFactory1 WRONG_NUMBER_OF_TYPE_ARGUMENTS = DiagnosticFactory1.create(ERROR, "{0} type arguments expected", new Renderer() { @NotNull @Override - public String render(@Nullable Integer argument) { - assert argument != null; + public String render(@NotNull Integer argument) { return argument == 0 ? "No" : argument.toString(); } }); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Renderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Renderer.java index 3d427e03be6..5884b97e3ff 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Renderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Renderer.java @@ -16,15 +16,12 @@ package org.jetbrains.jet.lang.diagnostics; -import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; /** * @author abreslav */ -public interface Renderer

{ - +public interface Renderer { @NotNull - String render(@Nullable P element); + String render(@NotNull O object); } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Renderers.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Renderers.java index dcccc2d4f69..7136502cfe9 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Renderers.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Renderers.java @@ -18,7 +18,6 @@ package org.jetbrains.jet.lang.diagnostics; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.descriptors.Named; import org.jetbrains.jet.lang.psi.JetClass; import org.jetbrains.jet.lang.psi.JetClassOrObject; @@ -32,8 +31,8 @@ public class Renderers { public static final Renderer TO_STRING = new Renderer() { @NotNull @Override - public String render(@Nullable Object element) { - return element == null ? "null" : element.toString(); + public String render(@NotNull Object element) { + return element.toString(); } @Override @@ -45,8 +44,7 @@ public class Renderers { public static final Renderer NAME = new Renderer() { @NotNull @Override - public String render(@Nullable Object element) { - if (element == null) return "null"; + public String render(@NotNull Object element) { if (element instanceof Named) { return ((Named) element).getName(); } @@ -57,8 +55,7 @@ public class Renderers { public static final Renderer ELEMENT_TEXT = new Renderer() { @NotNull @Override - public String render(@Nullable PsiElement element) { - if (element == null) return "null"; + public String render(@NotNull PsiElement element) { return element.getText(); } }; @@ -66,8 +63,7 @@ public class Renderers { public static final Renderer RENDER_CLASS_OR_OBJECT = new Renderer() { @NotNull @Override - public String render(@Nullable JetClassOrObject classOrObject) { - assert classOrObject != null; + public String render(@NotNull JetClassOrObject classOrObject) { String name = classOrObject.getName() != null ? " '" + classOrObject.getName() + "'" : ""; if (classOrObject instanceof JetClass) { return "Class" + name; @@ -80,8 +76,7 @@ public class Renderers { public static final Renderer RENDER_TYPE = new Renderer() { @NotNull @Override - public String render(@Nullable JetType type) { - assert type != null; + public String render(@NotNull JetType type) { return DescriptorRenderer.TEXT.renderType(type); } }; diff --git a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java index ab314670626..aa98f28b710 100644 --- a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java @@ -209,8 +209,7 @@ public class DescriptorRenderer implements Renderer { @NotNull @Override - public String render(DeclarationDescriptor declarationDescriptor) { - if (declarationDescriptor == null) return lt() + "null>"; + public String render(@NotNull DeclarationDescriptor declarationDescriptor) { StringBuilder stringBuilder = new StringBuilder(); declarationDescriptor.accept(rootVisitor, stringBuilder); if (shouldRenderDefinedIn()) { diff --git a/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java b/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java index 2be4be17768..4ff2c59ebfb 100644 --- a/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java +++ b/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java @@ -23,6 +23,8 @@ import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.CompileCompilerDependenciesTest; import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; @@ -185,7 +187,7 @@ public abstract class ExpectedResolveData { assertTrue( "Must have been unresolved: " + renderReferenceInContext(referenceExpression) + - " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), + " but was resolved to " + renderNullableDescriptor(bindingContext.get(REFERENCE_TARGET, referenceExpression)), unresolvedReferences.contains(referenceExpression)); continue; } @@ -193,7 +195,7 @@ public abstract class ExpectedResolveData { assertTrue( "Must have been resolved to multiple descriptors: " + renderReferenceInContext(referenceExpression) + - " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), + " but was resolved to " + renderNullableDescriptor(bindingContext.get(REFERENCE_TARGET, referenceExpression)), bindingContext.get(AMBIGUOUS_REFERENCE_TARGET, referenceExpression) != null); continue; } @@ -201,7 +203,7 @@ public abstract class ExpectedResolveData { assertTrue( "Must have been resolved to null: " + renderReferenceInContext(referenceExpression) + - " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), + " but was resolved to " + renderNullableDescriptor(bindingContext.get(REFERENCE_TARGET, referenceExpression)), bindingContext.get(REFERENCE_TARGET, referenceExpression) == null ); continue; @@ -210,7 +212,7 @@ public abstract class ExpectedResolveData { assertTrue( "Must have been resolved to error: " + renderReferenceInContext(referenceExpression) + - " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), + " but was resolved to " + renderNullableDescriptor(bindingContext.get(REFERENCE_TARGET, referenceExpression)), ErrorUtils.isError(bindingContext.get(REFERENCE_TARGET, referenceExpression)) ); continue; @@ -355,4 +357,9 @@ public abstract class ExpectedResolveData { T result = (T) element; return result; } + + @NotNull + private static String renderNullableDescriptor(@Nullable DeclarationDescriptor d) { + return d == null ? "" : DescriptorRenderer.TEXT.render(d); + } } diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/JetLineMarkerProvider.java b/idea/src/org/jetbrains/jet/plugin/highlighter/JetLineMarkerProvider.java index bd9577948c6..aac93f48e64 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/JetLineMarkerProvider.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/JetLineMarkerProvider.java @@ -35,6 +35,7 @@ import com.intellij.util.PsiNavigateUtil; import org.jetbrains.jet.lang.descriptors.CallableMemberDescriptor; import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.descriptors.Modality; +import org.jetbrains.jet.lang.descriptors.SimpleFunctionDescriptor; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetNamedFunction; import org.jetbrains.jet.lang.psi.JetProperty; @@ -132,7 +133,10 @@ public class JetLineMarkerProvider implements LineMarkerProvider { public String getElementText(PsiElement element) { if (element instanceof JetNamedFunction) { JetNamedFunction function = (JetNamedFunction) element; - return DescriptorRenderer.HTML.render(bindingContext.get(BindingContext.FUNCTION, function)); + SimpleFunctionDescriptor fd = + bindingContext.get(BindingContext.FUNCTION, function); + assert fd != null; + return DescriptorRenderer.HTML.render(fd); } return super.getElementText(element); } diff --git a/idea/src/org/jetbrains/jet/plugin/libraries/DecompiledDataFactory.java b/idea/src/org/jetbrains/jet/plugin/libraries/DecompiledDataFactory.java index 4b499419098..f7c27060938 100644 --- a/idea/src/org/jetbrains/jet/plugin/libraries/DecompiledDataFactory.java +++ b/idea/src/org/jetbrains/jet/plugin/libraries/DecompiledDataFactory.java @@ -125,7 +125,7 @@ class DecompiledDataFactory { return r; } - private void appendDescriptor(DeclarationDescriptor descriptor, String indent) { + private void appendDescriptor(@NotNull DeclarationDescriptor descriptor, String indent) { int startOffset = myBuilder.length(); String renderedDescriptor = DescriptorRenderer.COMPACT.render(descriptor); renderedDescriptor = renderedDescriptor.replace("= ...", "= " + DECOMPILED_COMMENT); From 553ce9e5e0a60db36007df4ebb2919ba8d2f4a67 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 12 Apr 2012 20:21:09 +0400 Subject: [PATCH 007/147] Extracted DiagnosticWithParameters1Renderer, moved it along with DiagnosticRenderer to frontend module. --- .../compiler/DefaultDiagnosticRenderer.java | 20 +-------- .../{ => rendering}/DiagnosticRenderer.java | 4 +- .../DiagnosticWithParameters1Renderer.java | 44 +++++++++++++++++++ 3 files changed, 49 insertions(+), 19 deletions(-) rename compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/{ => rendering}/DiagnosticRenderer.java (84%) create mode 100644 compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java b/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java index 16f97836827..158ca104b80 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java @@ -16,12 +16,12 @@ package org.jetbrains.jet.compiler; -import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.diagnostics.*; +import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticRenderer; +import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticWithParameters1Renderer; import org.jetbrains.jet.lang.psi.JetFile; -import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; @@ -56,20 +56,4 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer //noinspection unchecked return renderer.render(diagnostic); } - - private class DiagnosticWithParameters1Renderer implements DiagnosticRenderer> { - private final MessageFormat messageFormat; - private final Renderer rendererForA; - - private DiagnosticWithParameters1Renderer(@NotNull String message, @NotNull Renderer rendererForA) { - this.messageFormat = new MessageFormat(message); - this.rendererForA = rendererForA; - } - - @NotNull - @Override - public String render(@NotNull DiagnosticWithParameters1 diagnostic) { - return messageFormat.format(new Object[]{rendererForA.render(diagnostic.getA())}); - } - } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticRenderer.java similarity index 84% rename from compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java rename to compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticRenderer.java index c71d686fc0f..ce843b367b2 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticRenderer.java @@ -14,9 +14,11 @@ * limitations under the License. */ -package org.jetbrains.jet.lang.diagnostics; +package org.jetbrains.jet.lang.diagnostics.rendering; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.diagnostics.Diagnostic; +import org.jetbrains.jet.lang.diagnostics.Renderer; /** * @author Evgeny Gerashchenko diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java new file mode 100644 index 00000000000..6ae1c64d191 --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java @@ -0,0 +1,44 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.lang.diagnostics.rendering; + +import com.intellij.psi.PsiElement; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.diagnostics.DiagnosticWithParameters1; +import org.jetbrains.jet.lang.diagnostics.Renderer; + +import java.text.MessageFormat; + +/** +* @author Evgeny Gerashchenko +* @since 4/12/12 +*/ +public class DiagnosticWithParameters1Renderer implements DiagnosticRenderer> { + private final MessageFormat messageFormat; + private final Renderer rendererForA; + + public DiagnosticWithParameters1Renderer(@NotNull String message, @NotNull Renderer rendererForA) { + this.messageFormat = new MessageFormat(message); + this.rendererForA = rendererForA; + } + + @NotNull + @Override + public String render(@NotNull DiagnosticWithParameters1 diagnostic) { + return messageFormat.format(new Object[]{rendererForA.render(diagnostic.getA())}); + } +} From cab1e0059634849fd3c1c0c7accac1fbef4dffc5 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 12 Apr 2012 20:54:36 +0400 Subject: [PATCH 008/147] Replaced unnecessary "E" type parameter in DiagnosticWithParameters1 with wildcard. --- .../jet/compiler/DefaultDiagnosticRenderer.java | 10 ++++++---- .../rendering/DiagnosticWithParameters1Renderer.java | 5 ++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java b/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java index 158ca104b80..de3c793c937 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java @@ -17,15 +17,17 @@ package org.jetbrains.jet.compiler; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.lang.diagnostics.*; +import org.jetbrains.jet.lang.diagnostics.AbstractDiagnosticFactory; +import org.jetbrains.jet.lang.diagnostics.Diagnostic; +import org.jetbrains.jet.lang.diagnostics.Renderer; import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticRenderer; import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticWithParameters1Renderer; -import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.diagnostics.rendering.SimpleDiagnosticRenderer; import java.util.HashMap; import java.util.Map; -import static org.jetbrains.jet.lang.diagnostics.Errors.EXCEPTION_WHILE_ANALYZING; +import static org.jetbrains.jet.lang.diagnostics.Errors.*; /** * @author Evgeny Gerashchenko @@ -37,7 +39,7 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer private final Map> factoryToRenderer = new HashMap>(); private DefaultDiagnosticRenderer() { - factoryToRenderer.put(EXCEPTION_WHILE_ANALYZING, new DiagnosticWithParameters1Renderer("{0}", new Renderer() { + factoryToRenderer.put(EXCEPTION_WHILE_ANALYZING, new DiagnosticWithParameters1Renderer("{0}", new Renderer() { @NotNull @Override public String render(@NotNull Throwable e) { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java index 6ae1c64d191..6031bdeea45 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java @@ -16,7 +16,6 @@ package org.jetbrains.jet.lang.diagnostics.rendering; -import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.diagnostics.DiagnosticWithParameters1; import org.jetbrains.jet.lang.diagnostics.Renderer; @@ -27,7 +26,7 @@ import java.text.MessageFormat; * @author Evgeny Gerashchenko * @since 4/12/12 */ -public class DiagnosticWithParameters1Renderer implements DiagnosticRenderer> { +public class DiagnosticWithParameters1Renderer implements DiagnosticRenderer> { private final MessageFormat messageFormat; private final Renderer rendererForA; @@ -38,7 +37,7 @@ public class DiagnosticWithParameters1Renderer implemen @NotNull @Override - public String render(@NotNull DiagnosticWithParameters1 diagnostic) { + public String render(@NotNull DiagnosticWithParameters1 diagnostic) { return messageFormat.format(new Object[]{rendererForA.render(diagnostic.getA())}); } } From c3c2c716d976905d17901939da8c7117d102d5df Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 12 Apr 2012 20:55:13 +0400 Subject: [PATCH 009/147] Introduced DiagnosticWithParameters2Renderer, DiagnosticWithParameters3Renderer, SimpleDiagnosticRenderer. --- .../DiagnosticWithParameters2Renderer.java | 47 ++++++++++++++++ .../DiagnosticWithParameters3Renderer.java | 53 +++++++++++++++++++ .../rendering/SimpleDiagnosticRenderer.java | 38 +++++++++++++ 3 files changed, 138 insertions(+) create mode 100644 compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters2Renderer.java create mode 100644 compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters3Renderer.java create mode 100644 compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/SimpleDiagnosticRenderer.java diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters2Renderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters2Renderer.java new file mode 100644 index 00000000000..758626891bb --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters2Renderer.java @@ -0,0 +1,47 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.lang.diagnostics.rendering; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.diagnostics.DiagnosticWithParameters2; +import org.jetbrains.jet.lang.diagnostics.Renderer; + +import java.text.MessageFormat; + +/** +* @author Evgeny Gerashchenko +* @since 4/12/12 +*/ +public class DiagnosticWithParameters2Renderer implements DiagnosticRenderer> { + private final MessageFormat messageFormat; + private final Renderer rendererForA; + private final Renderer rendererForB; + + public DiagnosticWithParameters2Renderer(@NotNull String message, @NotNull Renderer rendererForA, @NotNull Renderer rendererForB) { + this.messageFormat = new MessageFormat(message); + this.rendererForA = rendererForA; + this.rendererForB = rendererForB; + } + + @NotNull + @Override + public String render(@NotNull DiagnosticWithParameters2 diagnostic) { + return messageFormat.format(new Object[]{ + rendererForA.render(diagnostic.getA()), + rendererForB.render(diagnostic.getB())}); + } +} diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters3Renderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters3Renderer.java new file mode 100644 index 00000000000..b18385e6fc8 --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters3Renderer.java @@ -0,0 +1,53 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.lang.diagnostics.rendering; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.diagnostics.DiagnosticWithParameters3; +import org.jetbrains.jet.lang.diagnostics.Renderer; + +import java.text.MessageFormat; + +/** +* @author Evgeny Gerashchenko +* @since 4/12/12 +*/ +public class DiagnosticWithParameters3Renderer implements DiagnosticRenderer> { + private final MessageFormat messageFormat; + private final Renderer rendererForA; + private final Renderer rendererForB; + private final Renderer rendererForC; + + public DiagnosticWithParameters3Renderer(@NotNull String message, + @NotNull Renderer rendererForA, + @NotNull Renderer rendererForB, + @NotNull Renderer rendererForC) { + this.messageFormat = new MessageFormat(message); + this.rendererForA = rendererForA; + this.rendererForB = rendererForB; + this.rendererForC = rendererForC; + } + + @NotNull + @Override + public String render(@NotNull DiagnosticWithParameters3 diagnostic) { + return messageFormat.format(new Object[]{ + rendererForA.render(diagnostic.getA()), + rendererForB.render(diagnostic.getB()), + rendererForC.render(diagnostic.getC())}); + } +} diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/SimpleDiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/SimpleDiagnosticRenderer.java new file mode 100644 index 00000000000..0dd094f89f3 --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/SimpleDiagnosticRenderer.java @@ -0,0 +1,38 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.lang.diagnostics.rendering; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.diagnostics.Diagnostic; + +/** +* @author Evgeny Gerashchenko +* @since 4/12/12 +*/ +public class SimpleDiagnosticRenderer implements DiagnosticRenderer { + private final String message; + + public SimpleDiagnosticRenderer(@NotNull String message) { + this.message = message; + } + + @NotNull + @Override + public String render(@NotNull Diagnostic diagnostic) { + return message; + } +} From 8d599548ba670f4984c8e82e5563e1ef4f181742 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 13:07:52 +0400 Subject: [PATCH 010/147] Copied all diagnostic-rendering logic to DefaultDiagnosticRenderer. --- .../compiler/DefaultDiagnosticRenderer.java | 377 +++++++++++++++++- .../diagnostics/RedeclarationDiagnostic.java | 14 +- 2 files changed, 383 insertions(+), 8 deletions(-) diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java b/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java index de3c793c937..0277131abbc 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java @@ -17,17 +17,23 @@ package org.jetbrains.jet.compiler; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.lang.diagnostics.AbstractDiagnosticFactory; -import org.jetbrains.jet.lang.diagnostics.Diagnostic; -import org.jetbrains.jet.lang.diagnostics.Renderer; -import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticRenderer; -import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticWithParameters1Renderer; -import org.jetbrains.jet.lang.diagnostics.rendering.SimpleDiagnosticRenderer; +import org.jetbrains.jet.lang.descriptors.*; +import org.jetbrains.jet.lang.diagnostics.*; +import org.jetbrains.jet.lang.diagnostics.rendering.*; +import org.jetbrains.jet.lang.psi.*; +import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; +import org.jetbrains.jet.lang.resolve.calls.inference.SolutionStatus; +import org.jetbrains.jet.lang.types.JetType; +import org.jetbrains.jet.lexer.JetKeywordToken; +import org.jetbrains.jet.resolve.DescriptorRenderer; +import java.util.Collection; import java.util.HashMap; +import java.util.Iterator; import java.util.Map; import static org.jetbrains.jet.lang.diagnostics.Errors.*; +import static org.jetbrains.jet.lang.diagnostics.Renderers.*; /** * @author Evgeny Gerashchenko @@ -46,6 +52,318 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer return e.getClass().getSimpleName() + ": " + e.getMessage(); } })); + + factoryToRenderer.put(UNRESOLVED_REFERENCE, new UnresolvedReferenceDiagnosticRenderer("Unresolved reference: ")); + + factoryToRenderer.put(INVISIBLE_REFERENCE, new DiagnosticWithParameters2Renderer("Cannot access ''{0}'' in ''{1}''", NAME, NAME)); + factoryToRenderer.put(INVISIBLE_MEMBER, new DiagnosticWithParameters2Renderer("Cannot access ''{0}'' in ''{1}''", NAME, NAME)); + + factoryToRenderer.put(REDECLARATION, new RedeclarationDiagnosticRenderer("Redeclaration: ")); + factoryToRenderer.put(NAME_SHADOWING, new RedeclarationDiagnosticRenderer("Name shadowed: ")); + + factoryToRenderer.put(TYPE_MISMATCH, new DiagnosticWithParameters2Renderer("Type mismatch: inferred type is {1} but {0} was expected", RENDER_TYPE, RENDER_TYPE)); + factoryToRenderer.put(INCOMPATIBLE_MODIFIERS, new DiagnosticWithParameters1Renderer>("Incompatible modifiers: ''{0}''", new Renderer>() { + @NotNull + @Override + public String render(@NotNull Collection tokens) { + StringBuilder sb = new StringBuilder(); + for (Iterator iterator = tokens.iterator(); iterator.hasNext(); ) { + JetKeywordToken modifier = iterator.next(); + sb.append(modifier.getValue()); + if (iterator.hasNext()) { + sb.append(" "); + } + } + return sb.toString(); + } + } + )); + factoryToRenderer.put(ILLEGAL_MODIFIER, new DiagnosticWithParameters1Renderer("Illegal modifier ''{0}''", TO_STRING)); + + factoryToRenderer.put(REDUNDANT_MODIFIER, new DiagnosticWithParameters2Renderer("Modifier {0} is redundant because {1} is present", TO_STRING, TO_STRING)); + factoryToRenderer.put(ABSTRACT_MODIFIER_IN_TRAIT, new SimpleDiagnosticRenderer("Modifier ''{0}'' is redundant in trait")); + factoryToRenderer.put(OPEN_MODIFIER_IN_TRAIT, new SimpleDiagnosticRenderer("Modifier ''{0}'' is redundant in trait")); + factoryToRenderer.put(REDUNDANT_MODIFIER_IN_GETTER, new SimpleDiagnosticRenderer("Visibility modifiers are redundant in getter")); + factoryToRenderer.put(TRAIT_CAN_NOT_BE_FINAL, new SimpleDiagnosticRenderer("Trait can not be final")); + factoryToRenderer.put(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM, new SimpleDiagnosticRenderer("Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly")); // TODO: message + factoryToRenderer.put(RETURN_NOT_ALLOWED, new SimpleDiagnosticRenderer("'return' is not allowed here")); + factoryToRenderer.put(PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE, new SimpleDiagnosticRenderer("Projections are not allowed for immediate arguments of a supertype")); + factoryToRenderer.put(LABEL_NAME_CLASH, new SimpleDiagnosticRenderer("There is more than one label with such a name in this scope")); + factoryToRenderer.put(EXPRESSION_EXPECTED_NAMESPACE_FOUND, new SimpleDiagnosticRenderer("Expression expected, but a namespace name found")); + + factoryToRenderer.put(CANNOT_IMPORT_FROM_ELEMENT, new DiagnosticWithParameters1Renderer("Cannot import from ''{0}''", NAME)); + factoryToRenderer.put(CANNOT_BE_IMPORTED, new DiagnosticWithParameters1Renderer("Cannot import ''{0}'', functions and properties can be imported only from packages", NAME)); + factoryToRenderer.put(USELESS_HIDDEN_IMPORT, new SimpleDiagnosticRenderer("Useless import, it is hidden further")); + factoryToRenderer.put(USELESS_SIMPLE_IMPORT, new SimpleDiagnosticRenderer("Useless import, does nothing")); + + factoryToRenderer.put(CANNOT_INFER_PARAMETER_TYPE, new SimpleDiagnosticRenderer("Cannot infer a type for this parameter. To specify it explicitly use the {(p : Type) => ...} notation")); + + factoryToRenderer.put(NO_BACKING_FIELD_ABSTRACT_PROPERTY, new SimpleDiagnosticRenderer("This property doesn't have a backing field, because it's abstract")); + factoryToRenderer.put(NO_BACKING_FIELD_CUSTOM_ACCESSORS, new SimpleDiagnosticRenderer("This property doesn't have a backing field, because it has custom accessors without reference to the backing field")); + factoryToRenderer.put(INACCESSIBLE_BACKING_FIELD, new SimpleDiagnosticRenderer("The backing field is not accessible here")); + factoryToRenderer.put(NOT_PROPERTY_BACKING_FIELD, new SimpleDiagnosticRenderer("The referenced variable is not a property and doesn't have backing field")); + + factoryToRenderer.put(MIXING_NAMED_AND_POSITIONED_ARGUMENTS, new SimpleDiagnosticRenderer("Mixing named and positioned arguments in not allowed")); + factoryToRenderer.put(ARGUMENT_PASSED_TWICE, new SimpleDiagnosticRenderer("An argument is already passed for this parameter")); + factoryToRenderer.put(NAMED_PARAMETER_NOT_FOUND, new UnresolvedReferenceDiagnosticRenderer("Cannot find a parameter with this name: ")); + factoryToRenderer.put(VARARG_OUTSIDE_PARENTHESES, new SimpleDiagnosticRenderer("Passing value as a vararg is only allowed inside a parenthesized argument list")); + factoryToRenderer.put(NON_VARARG_SPREAD, new SimpleDiagnosticRenderer("The spread operator (*foo) may only be applied in a vararg position")); + + factoryToRenderer.put(MANY_FUNCTION_LITERAL_ARGUMENTS, new SimpleDiagnosticRenderer("Only one function literal is allowed outside a parenthesized argument list")); + factoryToRenderer.put(PROPERTY_WITH_NO_TYPE_NO_INITIALIZER, new SimpleDiagnosticRenderer("This property must either have a type annotation or be initialized")); + + factoryToRenderer.put(ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS, new SimpleDiagnosticRenderer("This property cannot be declared abstract")); + factoryToRenderer.put(ABSTRACT_PROPERTY_NOT_IN_CLASS, new SimpleDiagnosticRenderer("A property may be abstract only when defined in a class or trait")); + factoryToRenderer.put(ABSTRACT_PROPERTY_WITH_INITIALIZER, new SimpleDiagnosticRenderer("Property with initializer cannot be abstract")); + factoryToRenderer.put(ABSTRACT_PROPERTY_WITH_GETTER, new SimpleDiagnosticRenderer("Property with getter implementation cannot be abstract")); + factoryToRenderer.put(ABSTRACT_PROPERTY_WITH_SETTER, new SimpleDiagnosticRenderer("Property with setter implementation cannot be abstract")); + + factoryToRenderer.put(PACKAGE_MEMBER_CANNOT_BE_PROTECTED, new SimpleDiagnosticRenderer("Package member cannot be protected")); + + factoryToRenderer.put(GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY, new SimpleDiagnosticRenderer("Getter visibility must be the same as property visibility")); + factoryToRenderer.put(BACKING_FIELD_IN_TRAIT, new SimpleDiagnosticRenderer("Property in a trait cannot have a backing field")); + factoryToRenderer.put(MUST_BE_INITIALIZED, new SimpleDiagnosticRenderer("Property must be initialized")); + factoryToRenderer.put(MUST_BE_INITIALIZED_OR_BE_ABSTRACT, new SimpleDiagnosticRenderer("Property must be initialized or be abstract")); + factoryToRenderer.put(PROPERTY_INITIALIZER_IN_TRAIT, new SimpleDiagnosticRenderer("Property initializers are not allowed in traits")); + factoryToRenderer.put(PROPERTY_INITIALIZER_NO_BACKING_FIELD, new SimpleDiagnosticRenderer("Initializer is not allowed here because this property has no backing field")); + factoryToRenderer.put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, new DiagnosticWithParameters3Renderer("Abstract property {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING)); + factoryToRenderer.put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, new DiagnosticWithParameters3Renderer("Abstract function {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING)); + factoryToRenderer.put(ABSTRACT_FUNCTION_WITH_BODY, new DiagnosticWithParameters1Renderer("A function {0} with body cannot be abstract", TO_STRING)); + factoryToRenderer.put(NON_ABSTRACT_FUNCTION_WITH_NO_BODY, new DiagnosticWithParameters1Renderer("Method {0} without a body must be abstract", TO_STRING)); + factoryToRenderer.put(NON_MEMBER_ABSTRACT_FUNCTION, new DiagnosticWithParameters1Renderer("Function {0} is not a class or trait member and cannot be abstract", TO_STRING)); + + factoryToRenderer.put(NON_MEMBER_FUNCTION_NO_BODY, new DiagnosticWithParameters1Renderer("Function {0} must have a body", TO_STRING)); + factoryToRenderer.put(NON_FINAL_MEMBER_IN_FINAL_CLASS, new SimpleDiagnosticRenderer("Non final member in a final class")); + + factoryToRenderer.put(PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE, new SimpleDiagnosticRenderer("Public or protected member should specify a type")); + + factoryToRenderer.put(PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT, new SimpleDiagnosticRenderer("Projections are not allowed on type arguments of functions and properties")); // TODO : better positioning + factoryToRenderer.put(SUPERTYPE_NOT_INITIALIZED, new SimpleDiagnosticRenderer("This type has a constructor, and thus must be initialized here")); + factoryToRenderer.put(SUPERTYPE_NOT_INITIALIZED_DEFAULT, new SimpleDiagnosticRenderer("Constructor invocation should be explicitly specified")); + factoryToRenderer.put(SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY, new SimpleDiagnosticRenderer("A secondary constructor may appear only in a class that has a primary constructor")); + factoryToRenderer.put(SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST, new SimpleDiagnosticRenderer("Secondary constructors must have an initializer list")); + factoryToRenderer.put(BY_IN_SECONDARY_CONSTRUCTOR, new SimpleDiagnosticRenderer("'by'-clause is only supported for primary constructors")); + factoryToRenderer.put(INITIALIZER_WITH_NO_ARGUMENTS, new SimpleDiagnosticRenderer("Constructor arguments required")); + factoryToRenderer.put(MANY_CALLS_TO_THIS, new SimpleDiagnosticRenderer("Only one call to 'this(...)' is allowed")); + factoryToRenderer.put(NOTHING_TO_OVERRIDE, new DiagnosticWithParameters1Renderer("{0} overrides nothing", DescriptorRenderer.TEXT)); + factoryToRenderer.put(VIRTUAL_MEMBER_HIDDEN, new DiagnosticWithParameters3Renderer("''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); + + factoryToRenderer.put(ENUM_ENTRY_SHOULD_BE_INITIALIZED, new DiagnosticWithParameters1Renderer("Missing delegation specifier ''{0}''", NAME)); + factoryToRenderer.put(ENUM_ENTRY_ILLEGAL_TYPE, new DiagnosticWithParameters1Renderer("The type constructor of enum entry should be ''{0}''", NAME)); + + factoryToRenderer.put(UNINITIALIZED_VARIABLE, new DiagnosticWithParameters1Renderer("Variable ''{0}'' must be initialized", NAME)); + factoryToRenderer.put(UNINITIALIZED_PARAMETER, new DiagnosticWithParameters1Renderer("Parameter ''{0}'' is uninitialized here", NAME)); + factoryToRenderer.put(UNUSED_VARIABLE, new DiagnosticWithParameters1Renderer("Variable ''{0}'' is never used", NAME)); + factoryToRenderer.put(UNUSED_PARAMETER, new DiagnosticWithParameters1Renderer("Parameter ''{0}'' is never used", NAME)); + factoryToRenderer.put(ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE, new DiagnosticWithParameters1Renderer("Variable ''{0}'' is assigned but never accessed", NAME)); + factoryToRenderer.put(VARIABLE_WITH_REDUNDANT_INITIALIZER, new DiagnosticWithParameters1Renderer("Variable ''{0}'' initializer is redundant", NAME)); + factoryToRenderer.put(UNUSED_VALUE, new DiagnosticWithParameters2Renderer("The value ''{0}'' assigned to ''{1}'' is never used", ELEMENT_TEXT, TO_STRING)); + factoryToRenderer.put(UNUSED_CHANGED_VALUE, new DiagnosticWithParameters1Renderer("The value changed at ''{0}'' is never used", ELEMENT_TEXT)); + factoryToRenderer.put(UNUSED_EXPRESSION, new SimpleDiagnosticRenderer("The expression is unused")); + factoryToRenderer.put(UNUSED_FUNCTION_LITERAL, new SimpleDiagnosticRenderer("The function literal is unused. If you mean block, you can use 'run { ... }'")); + + factoryToRenderer.put(VAL_REASSIGNMENT, new DiagnosticWithParameters1Renderer("Val can not be reassigned", NAME)); + factoryToRenderer.put(INITIALIZATION_BEFORE_DECLARATION, new DiagnosticWithParameters1Renderer("Variable cannot be initialized before declaration", NAME)); + factoryToRenderer.put(VARIABLE_EXPECTED, new SimpleDiagnosticRenderer("Variable expected")); + + factoryToRenderer.put(INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER, new DiagnosticWithParameters1Renderer("This property has a custom setter, so initialization using backing field required", NAME)); + factoryToRenderer.put(INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER, new DiagnosticWithParameters1Renderer("Setter of this property can be overridden, so initialization using backing field required", NAME)); + + factoryToRenderer.put(FUNCTION_PARAMETERS_OF_INLINE_FUNCTION, new DiagnosticWithParameters1Renderer("Function parameters of inline function can only be invoked", NAME)); + + factoryToRenderer.put(UNREACHABLE_CODE, new SimpleDiagnosticRenderer("Unreachable code")); + + factoryToRenderer.put(MANY_CLASS_OBJECTS, new SimpleDiagnosticRenderer("Only one class object is allowed per class")); + factoryToRenderer.put(CLASS_OBJECT_NOT_ALLOWED, new SimpleDiagnosticRenderer("A class object is not allowed here")); + factoryToRenderer.put(DELEGATION_IN_TRAIT, new SimpleDiagnosticRenderer("Traits cannot use delegation")); + factoryToRenderer.put(DELEGATION_NOT_TO_TRAIT, new SimpleDiagnosticRenderer("Only traits can be delegated to")); + factoryToRenderer.put(NO_CONSTRUCTOR, new SimpleDiagnosticRenderer("This class does not have a constructor")); + factoryToRenderer.put(NOT_A_CLASS, new SimpleDiagnosticRenderer("Not a class")); + factoryToRenderer.put(ILLEGAL_ESCAPE_SEQUENCE, new SimpleDiagnosticRenderer("Illegal escape sequence")); + + factoryToRenderer.put(LOCAL_EXTENSION_PROPERTY, new SimpleDiagnosticRenderer("Local extension properties are not allowed")); + factoryToRenderer.put(LOCAL_VARIABLE_WITH_GETTER, new SimpleDiagnosticRenderer("Local variables are not allowed to have getters")); + factoryToRenderer.put(LOCAL_VARIABLE_WITH_SETTER, new SimpleDiagnosticRenderer("Local variables are not allowed to have setters")); + factoryToRenderer.put(VAL_WITH_SETTER, new SimpleDiagnosticRenderer("A 'val'-property cannot have a setter")); + + factoryToRenderer.put(NO_GET_METHOD, new SimpleDiagnosticRenderer("No get method providing array access")); + factoryToRenderer.put(NO_SET_METHOD, new SimpleDiagnosticRenderer("No set method providing array access")); + + factoryToRenderer.put(INC_DEC_SHOULD_NOT_RETURN_UNIT, new SimpleDiagnosticRenderer("Functions inc(), dec() shouldn't return Unit to be used by operators ++, --")); + factoryToRenderer.put(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT, new DiagnosticWithParameters2Renderer("Function ''{0}'' should return Unit to be used by corresponding operator ''{1}''", NAME, ELEMENT_TEXT)); + factoryToRenderer.put(ASSIGN_OPERATOR_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Assignment operators ambiguity: {0}")); + + factoryToRenderer.put(EQUALS_MISSING, new SimpleDiagnosticRenderer("No method 'equals(Any?) : Boolean' available")); + factoryToRenderer.put(ASSIGNMENT_IN_EXPRESSION_CONTEXT, new SimpleDiagnosticRenderer("Assignments are not expressions, and only expressions are allowed in this context")); + factoryToRenderer.put(NAMESPACE_IS_NOT_AN_EXPRESSION, new SimpleDiagnosticRenderer("'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')")); + factoryToRenderer.put(SUPER_IS_NOT_AN_EXPRESSION, new DiagnosticWithParameters1Renderer("{0} is not an expression, it can only be used on the left-hand side of a dot ('.')", TO_STRING)); + factoryToRenderer.put(DECLARATION_IN_ILLEGAL_CONTEXT, new SimpleDiagnosticRenderer("Declarations are not allowed in this position")); + factoryToRenderer.put(SETTER_PARAMETER_WITH_DEFAULT_VALUE, new SimpleDiagnosticRenderer("Setter parameters can not have default values")); + factoryToRenderer.put(NO_THIS, new SimpleDiagnosticRenderer("'this' is not defined in this context")); + factoryToRenderer.put(SUPER_NOT_AVAILABLE, new SimpleDiagnosticRenderer("No supertypes are accessible in this context")); + factoryToRenderer.put(AMBIGUOUS_SUPER, new SimpleDiagnosticRenderer("Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super'")); + factoryToRenderer.put(ABSTRACT_SUPER_CALL, new SimpleDiagnosticRenderer("Abstract member cannot be accessed directly")); + factoryToRenderer.put(NOT_A_SUPERTYPE, new SimpleDiagnosticRenderer("Not a supertype")); + factoryToRenderer.put(TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER, new SimpleDiagnosticRenderer("Type arguments do not need to be specified in a 'super' qualifier")); + factoryToRenderer.put(USELESS_CAST_STATIC_ASSERT_IS_FINE, new SimpleDiagnosticRenderer("No cast needed, use ':' instead")); + factoryToRenderer.put(USELESS_CAST, new SimpleDiagnosticRenderer("No cast needed")); + factoryToRenderer.put(CAST_NEVER_SUCCEEDS, new SimpleDiagnosticRenderer("This cast can never succeed")); + factoryToRenderer.put(WRONG_SETTER_PARAMETER_TYPE, new DiagnosticWithParameters1Renderer("Setter parameter type must be equal to the type of the property, i.e. {0}", RENDER_TYPE)); + factoryToRenderer.put(WRONG_GETTER_RETURN_TYPE, new DiagnosticWithParameters1Renderer("Getter return type must be equal to the type of the property, i.e. {0}", RENDER_TYPE)); + factoryToRenderer.put(NO_CLASS_OBJECT, new DiagnosticWithParameters1Renderer("Please specify constructor invocation; classifier {0} does not have a class object", NAME)); + factoryToRenderer.put(NO_GENERICS_IN_SUPERTYPE_SPECIFIER, new SimpleDiagnosticRenderer("Generic arguments of the base type must be specified")); + + factoryToRenderer.put(HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY, new SimpleDiagnosticRenderer("An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext' property")); + factoryToRenderer.put(HAS_NEXT_MISSING, new SimpleDiagnosticRenderer("Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property")); + factoryToRenderer.put(HAS_NEXT_FUNCTION_AMBIGUITY, new SimpleDiagnosticRenderer("Function 'iterator().hasNext()' is ambiguous for this expression")); + factoryToRenderer.put(HAS_NEXT_MUST_BE_READABLE, new SimpleDiagnosticRenderer("The 'iterator().hasNext' property of the loop range must be readable")); + factoryToRenderer.put(HAS_NEXT_PROPERTY_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", RENDER_TYPE)); + factoryToRenderer.put(HAS_NEXT_FUNCTION_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", RENDER_TYPE)); + factoryToRenderer.put(NEXT_AMBIGUITY, new SimpleDiagnosticRenderer("Function 'iterator().next()' is ambiguous for this expression")); + factoryToRenderer.put(NEXT_MISSING, new SimpleDiagnosticRenderer("Loop range must have an 'iterator().next()' function")); + factoryToRenderer.put(ITERATOR_MISSING, new SimpleDiagnosticRenderer("For-loop range must have an iterator() method")); + factoryToRenderer.put(ITERATOR_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Method 'iterator()' is ambiguous for this expression: {0}")); + + factoryToRenderer.put(COMPARE_TO_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("compareTo() must return Int, but returns {0}", RENDER_TYPE)); + factoryToRenderer.put(CALLEE_NOT_A_FUNCTION, new DiagnosticWithParameters1Renderer("Expecting a function type, but found {0}", RENDER_TYPE)); + + factoryToRenderer.put(RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY, new SimpleDiagnosticRenderer("Returns are not allowed for functions with expression body. Use block body in '{...}'")); + factoryToRenderer.put(NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY, new SimpleDiagnosticRenderer("A 'return' expression required in a function with a block body ('{...}')")); + factoryToRenderer.put(RETURN_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("This function must return a value of type {0}", RENDER_TYPE)); + factoryToRenderer.put(EXPECTED_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("Expected a value of type {0}", RENDER_TYPE)); + factoryToRenderer.put(ASSIGNMENT_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("Expected a value of type {0}. Assignment operation is not an expression, so it does not return any value", RENDER_TYPE)); + factoryToRenderer.put(IMPLICIT_CAST_TO_UNIT_OR_ANY, new DiagnosticWithParameters1Renderer("Type was casted to ''{0}''. Please specify ''{0}'' as expected type, if you mean such cast", RENDER_TYPE)); + factoryToRenderer.put(EXPRESSION_EXPECTED, new DiagnosticWithParameters1Renderer("{0} is not an expression, and only expression are allowed here", new Renderer() { + @NotNull + @Override + public String render(@NotNull JetExpression expression) { + String expressionType = expression.toString(); + return expressionType.substring(0, 1) + expressionType.substring(1).toLowerCase(); + } + })); + + factoryToRenderer.put(UPPER_BOUND_VIOLATED, new DiagnosticWithParameters1Renderer("An upper bound {0} is violated", RENDER_TYPE)); // TODO : Message + factoryToRenderer.put(FINAL_CLASS_OBJECT_UPPER_BOUND, new DiagnosticWithParameters1Renderer("{0} is a final type, and thus a class object cannot extend it", RENDER_TYPE)); + factoryToRenderer.put(FINAL_UPPER_BOUND, new DiagnosticWithParameters1Renderer("{0} is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE)); + factoryToRenderer.put(USELESS_ELVIS, new DiagnosticWithParameters1Renderer("Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE)); + factoryToRenderer.put(CONFLICTING_UPPER_BOUNDS, new DiagnosticWithParameters1Renderer("Upper bounds of {0} have empty intersection", NAME)); + factoryToRenderer.put(CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS, new DiagnosticWithParameters1Renderer("Class object upper bounds of {0} have empty intersection", NAME)); + + factoryToRenderer.put(TOO_MANY_ARGUMENTS, new DiagnosticWithParameters1Renderer("Too many arguments for {0}", TO_STRING)); + factoryToRenderer.put(ERROR_COMPILE_TIME_VALUE, new DiagnosticWithParameters1Renderer("{0}", TO_STRING)); + + factoryToRenderer.put(ELSE_MISPLACED_IN_WHEN, new SimpleDiagnosticRenderer("'else' entry must be the last one in a when-expression")); + + factoryToRenderer.put(NO_ELSE_IN_WHEN, new SimpleDiagnosticRenderer("'when' expression must contain 'else' branch")); + factoryToRenderer.put(TYPE_MISMATCH_IN_RANGE, new SimpleDiagnosticRenderer("Type mismatch: incompatible types of range and element checked in it")); + factoryToRenderer.put(CYCLIC_INHERITANCE_HIERARCHY, new SimpleDiagnosticRenderer("There's a cycle in the inheritance hierarchy for this type")); + + factoryToRenderer.put(MANY_CLASSES_IN_SUPERTYPE_LIST, new SimpleDiagnosticRenderer("Only one class may appear in a supertype list")); + factoryToRenderer.put(SUPERTYPE_NOT_A_CLASS_OR_TRAIT, new SimpleDiagnosticRenderer("Only classes and traits may serve as supertypes")); + factoryToRenderer.put(SUPERTYPE_INITIALIZED_IN_TRAIT, new SimpleDiagnosticRenderer("Traits cannot initialize supertypes")); + factoryToRenderer.put(CONSTRUCTOR_IN_TRAIT, new SimpleDiagnosticRenderer("A trait may not have a constructor")); + factoryToRenderer.put(SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED, new SimpleDiagnosticRenderer("Secondary constructors are not supported")); + factoryToRenderer.put(SUPERTYPE_APPEARS_TWICE, new SimpleDiagnosticRenderer("A supertype appears twice")); + factoryToRenderer.put(FINAL_SUPERTYPE, new SimpleDiagnosticRenderer("This type is final, so it cannot be inherited from")); + + factoryToRenderer.put(ILLEGAL_SELECTOR, new DiagnosticWithParameters1Renderer("Expression ''{0}'' cannot be a selector (occur after a dot)", TO_STRING)); + + factoryToRenderer.put(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION, new SimpleDiagnosticRenderer("A type annotation is required on a value parameter")); + factoryToRenderer.put(BREAK_OR_CONTINUE_OUTSIDE_A_LOOP, new SimpleDiagnosticRenderer("'break' and 'continue' are only allowed inside a loop")); + factoryToRenderer.put(NOT_A_LOOP_LABEL, new DiagnosticWithParameters1Renderer("The label ''{0}'' does not denote a loop", TO_STRING)); + factoryToRenderer.put(NOT_A_RETURN_LABEL, new DiagnosticWithParameters1Renderer("The label ''{0}'' does not reference to a context from which we can return", TO_STRING)); + + factoryToRenderer.put(ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR, new SimpleDiagnosticRenderer("Anonymous initializers are only allowed in the presence of a primary constructor")); + factoryToRenderer.put(NULLABLE_SUPERTYPE, new SimpleDiagnosticRenderer("A supertype cannot be nullable")); + factoryToRenderer.put(UNSAFE_CALL, new DiagnosticWithParameters1Renderer("Only safe calls (?.) are allowed on a nullable receiver of type {0}", RENDER_TYPE)); + factoryToRenderer.put(AMBIGUOUS_LABEL, new SimpleDiagnosticRenderer("Ambiguous label")); + factoryToRenderer.put(UNSUPPORTED, new DiagnosticWithParameters1Renderer("Unsupported [{0}]", TO_STRING)); + factoryToRenderer.put(UNNECESSARY_SAFE_CALL, new DiagnosticWithParameters1Renderer("Unnecessary safe call on a non-null receiver of type {0}", RENDER_TYPE)); + factoryToRenderer.put(UNNECESSARY_NOT_NULL_ASSERTION, new DiagnosticWithParameters1Renderer("Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", RENDER_TYPE)); + factoryToRenderer.put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, new DiagnosticWithParameters2Renderer("{0} does not refer to a type parameter of {1}", new Renderer() { + @NotNull + @Override + public String render(@NotNull JetTypeConstraint typeConstraint) { + //noinspection ConstantConditions + return typeConstraint.getSubjectTypeParameterName().getReferencedName(); + } + }, NAME)); + factoryToRenderer.put(AUTOCAST_IMPOSSIBLE, new DiagnosticWithParameters2Renderer("Automatic cast to {0} is impossible, because {1} could have changed since the is-check", RENDER_TYPE, NAME)); + + factoryToRenderer.put(TYPE_MISMATCH_IN_FOR_LOOP, new DiagnosticWithParameters2Renderer("The loop iterates over values of type {0} but the parameter is declared to be {1}", RENDER_TYPE, RENDER_TYPE)); + factoryToRenderer.put(TYPE_MISMATCH_IN_CONDITION, new DiagnosticWithParameters1Renderer("Condition must be of type Boolean, but was of type {0}", RENDER_TYPE)); + factoryToRenderer.put(TYPE_MISMATCH_IN_TUPLE_PATTERN, new DiagnosticWithParameters2Renderer("Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, TO_STRING)); // TODO: message + factoryToRenderer.put(TYPE_MISMATCH_IN_BINDING_PATTERN, new DiagnosticWithParameters2Renderer("{0} must be a supertype of {1}. Use 'is' to match against {0}", RENDER_TYPE, RENDER_TYPE)); + factoryToRenderer.put(INCOMPATIBLE_TYPES, new DiagnosticWithParameters2Renderer("Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE)); + factoryToRenderer.put(EXPECTED_CONDITION, new SimpleDiagnosticRenderer("Expected condition of Boolean type")); + + factoryToRenderer.put(CANNOT_CHECK_FOR_ERASED, new DiagnosticWithParameters1Renderer("Cannot check for instance of erased type: {0}", RENDER_TYPE)); + factoryToRenderer.put(UNCHECKED_CAST, new DiagnosticWithParameters2Renderer("Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE)); + + factoryToRenderer.put(INCONSISTENT_TYPE_PARAMETER_VALUES, new DiagnosticWithParameters3Renderer>("Type parameter {0} of {1} has inconsistent values: {2}", NAME, DescriptorRenderer.TEXT, new Renderer>() { + @NotNull + @Override + public String render(@NotNull Collection types) { + StringBuilder builder = new StringBuilder(); + for (Iterator iterator = types.iterator(); iterator.hasNext(); ) { + JetType jetType = iterator.next(); + builder.append(jetType); + if (iterator.hasNext()) { + builder.append(", "); + } + } + return builder.toString(); + } + })); + + factoryToRenderer.put(EQUALITY_NOT_APPLICABLE, new DiagnosticWithParameters3Renderer("Operator {0} cannot be applied to {1} and {2}", new Renderer() { + @NotNull + @Override + public String render(@NotNull JetSimpleNameExpression nameExpression) { + //noinspection ConstantConditions + return nameExpression.getReferencedName(); + } + }, TO_STRING, TO_STRING)); + + factoryToRenderer.put(OVERRIDING_FINAL_MEMBER, new DiagnosticWithParameters2Renderer("''{0}'' in ''{1}'' is final and cannot be overridden", NAME, NAME)); + factoryToRenderer.put(CANNOT_WEAKEN_ACCESS_PRIVILEGE, new DiagnosticWithParameters3Renderer("Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME)); + factoryToRenderer.put(CANNOT_CHANGE_ACCESS_PRIVILEGE, new DiagnosticWithParameters3Renderer("Cannot change access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME)); + + factoryToRenderer.put(RETURN_TYPE_MISMATCH_ON_OVERRIDE, new DiagnosticWithParameters2Renderer("Return type of {0} is not a subtype of the return type overridden member {1}", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); + + factoryToRenderer.put(VAR_OVERRIDDEN_BY_VAL, new DiagnosticWithParameters2Renderer("Var-property {0} cannot be overridden by val-property {1}", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); + + factoryToRenderer.put(ABSTRACT_MEMBER_NOT_IMPLEMENTED, new DiagnosticWithParameters2Renderer("{0} must be declared abstract or implement abstract member {1}", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT)); + + factoryToRenderer.put(MANY_IMPL_MEMBER_NOT_IMPLEMENTED, new DiagnosticWithParameters2Renderer("{0} must override {1} because it inherits many implementations of it", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT)); + + factoryToRenderer.put(CONFLICTING_OVERLOADS, new DiagnosticWithParameters2Renderer("{1} is already defined in ''{0}''", DescriptorRenderer.TEXT, TO_STRING)); + + + factoryToRenderer.put(RESULT_TYPE_MISMATCH, new DiagnosticWithParameters3Renderer("{0} must return {1} but returns {2}", TO_STRING, RENDER_TYPE, RENDER_TYPE)); + factoryToRenderer.put(UNSAFE_INFIX_CALL, new DiagnosticWithParameters3Renderer("Infix call corresponds to a dot-qualified call ''{0}.{1}({2})'' which is not allowed on a nullable receiver ''{0}''. Use '?.'-qualified call instead", TO_STRING, TO_STRING, TO_STRING)); + + factoryToRenderer.put(OVERLOAD_RESOLUTION_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Overload resolution ambiguity: {0}")); + factoryToRenderer.put(NONE_APPLICABLE, new AmbiguousDescriptorDiagnosticRenderer("None of the following functions can be called with the arguments supplied: {0}")); + factoryToRenderer.put(NO_VALUE_FOR_PARAMETER, new DiagnosticWithParameters1Renderer("No value passed for parameter {0}", DescriptorRenderer.TEXT)); + factoryToRenderer.put(MISSING_RECEIVER, new DiagnosticWithParameters1Renderer("A receiver of type {0} is required", RENDER_TYPE)); + factoryToRenderer.put(NO_RECEIVER_ADMITTED, new SimpleDiagnosticRenderer("No receiver can be passed to this function or property")); + + factoryToRenderer.put(CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS, new SimpleDiagnosticRenderer("Can not create an instance of an abstract class")); + factoryToRenderer.put(TYPE_INFERENCE_FAILED, new DiagnosticWithParameters1Renderer("Type inference failed: {0}", TO_STRING)); + factoryToRenderer.put(WRONG_NUMBER_OF_TYPE_ARGUMENTS, new DiagnosticWithParameters1Renderer("{0} type arguments expected", new Renderer() { + @NotNull + @Override + public String render(@NotNull Integer argument) { + return argument == 0 ? "No" : argument.toString(); + } + })); + + factoryToRenderer.put(UNRESOLVED_IDE_TEMPLATE, new DiagnosticWithParameters1Renderer("Unresolved IDE template: {0}", TO_STRING)); + + factoryToRenderer.put(DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED, new SimpleDiagnosticRenderer("This expression is treated as an argument to the function call on the previous line. Separate it with a semicolon (;) if it is not intended to be an argument.")); + + factoryToRenderer.put(NOT_AN_ANNOTATION_CLASS, new DiagnosticWithParameters1Renderer("{0} is not an annotation class", TO_STRING)); } @NotNull @@ -53,9 +371,54 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer public String render(@NotNull Diagnostic diagnostic) { DiagnosticRenderer renderer = factoryToRenderer.get(diagnostic.getFactory()); if (renderer == null) { - return diagnostic.getMessage(); // TODO throw IllegalArgumentException instead + throw new IllegalArgumentException("Don't know how to render diagnostic of type " + diagnostic.getFactory().getName()); } //noinspection unchecked return renderer.render(diagnostic); } + + private static class RedeclarationDiagnosticRenderer implements DiagnosticRenderer { + private String messagePrefix; + + private RedeclarationDiagnosticRenderer(@NotNull String messagePrefix) { + this.messagePrefix = messagePrefix; + } + + @NotNull + @Override + public String render(@NotNull RedeclarationDiagnostic diagnostic) { + return messagePrefix + diagnostic.getName(); + } + } + + private static class UnresolvedReferenceDiagnosticRenderer implements DiagnosticRenderer { + private String messagePrefix; + + private UnresolvedReferenceDiagnosticRenderer(@NotNull String messagePrefix) { + this.messagePrefix = messagePrefix; + } + + @NotNull + @Override + public String render(@NotNull UnresolvedReferenceDiagnostic diagnostic) { + return messagePrefix + diagnostic.getPsiElement().getText(); + } + } + + private static class AmbiguousDescriptorDiagnosticRenderer + extends DiagnosticWithParameters1Renderer>> { + private AmbiguousDescriptorDiagnosticRenderer(@NotNull String message) { + super(message, new Renderer>>() { + @NotNull + @Override + public String render(@NotNull Collection> argument) { + StringBuilder stringBuilder = new StringBuilder("\n"); + for (ResolvedCall call : argument) { + stringBuilder.append(DescriptorRenderer.TEXT.render(call.getResultingDescriptor())).append("\n"); + } + return stringBuilder.toString(); + } + }); + } + } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java index 15f49087fd6..acfa00a21cc 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java @@ -32,6 +32,8 @@ import java.util.List; * @author abreslav */ public interface RedeclarationDiagnostic extends Diagnostic { + String getName(); + class SimpleRedeclarationDiagnostic extends AbstractDiagnostic implements RedeclarationDiagnostic { private String name; @@ -52,6 +54,11 @@ public interface RedeclarationDiagnostic extends Diagnostic { return getFactory().makeMessage(name); } + @Override + public String getName() { + return name; + } + @NotNull @Override public List getTextRanges() { @@ -104,10 +111,15 @@ public interface RedeclarationDiagnostic extends Diagnostic { return factory; } + @Override + public String getName() { + return duplicatingDescriptor.getName(); + } + @NotNull @Override public String getMessage() { - return factory.makeMessage(duplicatingDescriptor.getName()); + return factory.makeMessage(getName()); } @NotNull From b0e09319a97d8f308b67b2a523aa8f70e54b1355 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 13:09:33 +0400 Subject: [PATCH 011/147] Moved DefaultDiagnosticRenderer from cli back to frontend to avoid run-time dependencies on cli where rendering diagnostics is needed. --- .../cli/src/org/jetbrains/jet/compiler/CompileSession.java | 1 + .../lang/diagnostics/rendering}/DefaultDiagnosticRenderer.java | 3 +-- compiler/tests/org/jetbrains/jet/JetTestUtils.java | 2 +- .../org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) rename compiler/{cli/src/org/jetbrains/jet/compiler => frontend/src/org/jetbrains/jet/lang/diagnostics/rendering}/DefaultDiagnosticRenderer.java (99%) diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java index 1e26ccf2fa9..95b6752337a 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java @@ -36,6 +36,7 @@ import org.jetbrains.jet.lang.descriptors.ClassOrNamespaceDescriptor; import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.descriptors.ModuleDescriptor; import org.jetbrains.jet.lang.diagnostics.*; +import org.jetbrains.jet.lang.diagnostics.rendering.DefaultDiagnosticRenderer; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java similarity index 99% rename from compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java rename to compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java index 0277131abbc..e1407e943a6 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/DefaultDiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java @@ -14,12 +14,11 @@ * limitations under the License. */ -package org.jetbrains.jet.compiler; +package org.jetbrains.jet.lang.diagnostics.rendering; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.diagnostics.*; -import org.jetbrains.jet.lang.diagnostics.rendering.*; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; import org.jetbrains.jet.lang.resolve.calls.inference.SolutionStatus; diff --git a/compiler/tests/org/jetbrains/jet/JetTestUtils.java b/compiler/tests/org/jetbrains/jet/JetTestUtils.java index 8bcd54cc0c8..a12c4693120 100644 --- a/compiler/tests/org/jetbrains/jet/JetTestUtils.java +++ b/compiler/tests/org/jetbrains/jet/JetTestUtils.java @@ -26,7 +26,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.compiler.JetCoreEnvironment; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; -import org.jetbrains.jet.compiler.DefaultDiagnosticRenderer; +import org.jetbrains.jet.lang.diagnostics.rendering.DefaultDiagnosticRenderer; import org.jetbrains.jet.lang.diagnostics.Diagnostic; import org.jetbrains.jet.lang.diagnostics.Severity; import org.jetbrains.jet.lang.diagnostics.UnresolvedReferenceDiagnostic; diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java b/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java index 4bea587e9cd..96d352074f4 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java @@ -33,7 +33,7 @@ import com.intellij.psi.PsiReference; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; -import org.jetbrains.jet.compiler.DefaultDiagnosticRenderer; +import org.jetbrains.jet.lang.diagnostics.rendering.DefaultDiagnosticRenderer; import org.jetbrains.jet.lang.diagnostics.*; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetReferenceExpression; From dff9f2e772126ad8a69518f28082c0d56c6454aa Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 13:12:48 +0400 Subject: [PATCH 012/147] Renamed map in DefaultDiagnosticRenderer to 'map' to reduce dazzling. --- .../rendering/DefaultDiagnosticRenderer.java | 502 +++++++++--------- 1 file changed, 251 insertions(+), 251 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java index e1407e943a6..f5e53b49d43 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java @@ -41,10 +41,10 @@ import static org.jetbrains.jet.lang.diagnostics.Renderers.*; public class DefaultDiagnosticRenderer implements DiagnosticRenderer { public static final DefaultDiagnosticRenderer INSTANCE = new DefaultDiagnosticRenderer(); - private final Map> factoryToRenderer = new HashMap>(); + private final Map> map = new HashMap>(); private DefaultDiagnosticRenderer() { - factoryToRenderer.put(EXCEPTION_WHILE_ANALYZING, new DiagnosticWithParameters1Renderer("{0}", new Renderer() { + map.put(EXCEPTION_WHILE_ANALYZING, new DiagnosticWithParameters1Renderer("{0}", new Renderer() { @NotNull @Override public String render(@NotNull Throwable e) { @@ -52,16 +52,16 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer } })); - factoryToRenderer.put(UNRESOLVED_REFERENCE, new UnresolvedReferenceDiagnosticRenderer("Unresolved reference: ")); + map.put(UNRESOLVED_REFERENCE, new UnresolvedReferenceDiagnosticRenderer("Unresolved reference: ")); - factoryToRenderer.put(INVISIBLE_REFERENCE, new DiagnosticWithParameters2Renderer("Cannot access ''{0}'' in ''{1}''", NAME, NAME)); - factoryToRenderer.put(INVISIBLE_MEMBER, new DiagnosticWithParameters2Renderer("Cannot access ''{0}'' in ''{1}''", NAME, NAME)); + map.put(INVISIBLE_REFERENCE, new DiagnosticWithParameters2Renderer("Cannot access ''{0}'' in ''{1}''", NAME, NAME)); + map.put(INVISIBLE_MEMBER, new DiagnosticWithParameters2Renderer("Cannot access ''{0}'' in ''{1}''", NAME, NAME)); - factoryToRenderer.put(REDECLARATION, new RedeclarationDiagnosticRenderer("Redeclaration: ")); - factoryToRenderer.put(NAME_SHADOWING, new RedeclarationDiagnosticRenderer("Name shadowed: ")); + map.put(REDECLARATION, new RedeclarationDiagnosticRenderer("Redeclaration: ")); + map.put(NAME_SHADOWING, new RedeclarationDiagnosticRenderer("Name shadowed: ")); - factoryToRenderer.put(TYPE_MISMATCH, new DiagnosticWithParameters2Renderer("Type mismatch: inferred type is {1} but {0} was expected", RENDER_TYPE, RENDER_TYPE)); - factoryToRenderer.put(INCOMPATIBLE_MODIFIERS, new DiagnosticWithParameters1Renderer>("Incompatible modifiers: ''{0}''", new Renderer>() { + map.put(TYPE_MISMATCH, new DiagnosticWithParameters2Renderer("Type mismatch: inferred type is {1} but {0} was expected", RENDER_TYPE, RENDER_TYPE)); + map.put(INCOMPATIBLE_MODIFIERS, new DiagnosticWithParameters1Renderer>("Incompatible modifiers: ''{0}''", new Renderer>() { @NotNull @Override public String render(@NotNull Collection tokens) { @@ -77,162 +77,162 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer } } )); - factoryToRenderer.put(ILLEGAL_MODIFIER, new DiagnosticWithParameters1Renderer("Illegal modifier ''{0}''", TO_STRING)); + map.put(ILLEGAL_MODIFIER, new DiagnosticWithParameters1Renderer("Illegal modifier ''{0}''", TO_STRING)); - factoryToRenderer.put(REDUNDANT_MODIFIER, new DiagnosticWithParameters2Renderer("Modifier {0} is redundant because {1} is present", TO_STRING, TO_STRING)); - factoryToRenderer.put(ABSTRACT_MODIFIER_IN_TRAIT, new SimpleDiagnosticRenderer("Modifier ''{0}'' is redundant in trait")); - factoryToRenderer.put(OPEN_MODIFIER_IN_TRAIT, new SimpleDiagnosticRenderer("Modifier ''{0}'' is redundant in trait")); - factoryToRenderer.put(REDUNDANT_MODIFIER_IN_GETTER, new SimpleDiagnosticRenderer("Visibility modifiers are redundant in getter")); - factoryToRenderer.put(TRAIT_CAN_NOT_BE_FINAL, new SimpleDiagnosticRenderer("Trait can not be final")); - factoryToRenderer.put(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM, new SimpleDiagnosticRenderer("Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly")); // TODO: message - factoryToRenderer.put(RETURN_NOT_ALLOWED, new SimpleDiagnosticRenderer("'return' is not allowed here")); - factoryToRenderer.put(PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE, new SimpleDiagnosticRenderer("Projections are not allowed for immediate arguments of a supertype")); - factoryToRenderer.put(LABEL_NAME_CLASH, new SimpleDiagnosticRenderer("There is more than one label with such a name in this scope")); - factoryToRenderer.put(EXPRESSION_EXPECTED_NAMESPACE_FOUND, new SimpleDiagnosticRenderer("Expression expected, but a namespace name found")); - - factoryToRenderer.put(CANNOT_IMPORT_FROM_ELEMENT, new DiagnosticWithParameters1Renderer("Cannot import from ''{0}''", NAME)); - factoryToRenderer.put(CANNOT_BE_IMPORTED, new DiagnosticWithParameters1Renderer("Cannot import ''{0}'', functions and properties can be imported only from packages", NAME)); - factoryToRenderer.put(USELESS_HIDDEN_IMPORT, new SimpleDiagnosticRenderer("Useless import, it is hidden further")); - factoryToRenderer.put(USELESS_SIMPLE_IMPORT, new SimpleDiagnosticRenderer("Useless import, does nothing")); - - factoryToRenderer.put(CANNOT_INFER_PARAMETER_TYPE, new SimpleDiagnosticRenderer("Cannot infer a type for this parameter. To specify it explicitly use the {(p : Type) => ...} notation")); - - factoryToRenderer.put(NO_BACKING_FIELD_ABSTRACT_PROPERTY, new SimpleDiagnosticRenderer("This property doesn't have a backing field, because it's abstract")); - factoryToRenderer.put(NO_BACKING_FIELD_CUSTOM_ACCESSORS, new SimpleDiagnosticRenderer("This property doesn't have a backing field, because it has custom accessors without reference to the backing field")); - factoryToRenderer.put(INACCESSIBLE_BACKING_FIELD, new SimpleDiagnosticRenderer("The backing field is not accessible here")); - factoryToRenderer.put(NOT_PROPERTY_BACKING_FIELD, new SimpleDiagnosticRenderer("The referenced variable is not a property and doesn't have backing field")); - - factoryToRenderer.put(MIXING_NAMED_AND_POSITIONED_ARGUMENTS, new SimpleDiagnosticRenderer("Mixing named and positioned arguments in not allowed")); - factoryToRenderer.put(ARGUMENT_PASSED_TWICE, new SimpleDiagnosticRenderer("An argument is already passed for this parameter")); - factoryToRenderer.put(NAMED_PARAMETER_NOT_FOUND, new UnresolvedReferenceDiagnosticRenderer("Cannot find a parameter with this name: ")); - factoryToRenderer.put(VARARG_OUTSIDE_PARENTHESES, new SimpleDiagnosticRenderer("Passing value as a vararg is only allowed inside a parenthesized argument list")); - factoryToRenderer.put(NON_VARARG_SPREAD, new SimpleDiagnosticRenderer("The spread operator (*foo) may only be applied in a vararg position")); - - factoryToRenderer.put(MANY_FUNCTION_LITERAL_ARGUMENTS, new SimpleDiagnosticRenderer("Only one function literal is allowed outside a parenthesized argument list")); - factoryToRenderer.put(PROPERTY_WITH_NO_TYPE_NO_INITIALIZER, new SimpleDiagnosticRenderer("This property must either have a type annotation or be initialized")); - - factoryToRenderer.put(ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS, new SimpleDiagnosticRenderer("This property cannot be declared abstract")); - factoryToRenderer.put(ABSTRACT_PROPERTY_NOT_IN_CLASS, new SimpleDiagnosticRenderer("A property may be abstract only when defined in a class or trait")); - factoryToRenderer.put(ABSTRACT_PROPERTY_WITH_INITIALIZER, new SimpleDiagnosticRenderer("Property with initializer cannot be abstract")); - factoryToRenderer.put(ABSTRACT_PROPERTY_WITH_GETTER, new SimpleDiagnosticRenderer("Property with getter implementation cannot be abstract")); - factoryToRenderer.put(ABSTRACT_PROPERTY_WITH_SETTER, new SimpleDiagnosticRenderer("Property with setter implementation cannot be abstract")); - - factoryToRenderer.put(PACKAGE_MEMBER_CANNOT_BE_PROTECTED, new SimpleDiagnosticRenderer("Package member cannot be protected")); - - factoryToRenderer.put(GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY, new SimpleDiagnosticRenderer("Getter visibility must be the same as property visibility")); - factoryToRenderer.put(BACKING_FIELD_IN_TRAIT, new SimpleDiagnosticRenderer("Property in a trait cannot have a backing field")); - factoryToRenderer.put(MUST_BE_INITIALIZED, new SimpleDiagnosticRenderer("Property must be initialized")); - factoryToRenderer.put(MUST_BE_INITIALIZED_OR_BE_ABSTRACT, new SimpleDiagnosticRenderer("Property must be initialized or be abstract")); - factoryToRenderer.put(PROPERTY_INITIALIZER_IN_TRAIT, new SimpleDiagnosticRenderer("Property initializers are not allowed in traits")); - factoryToRenderer.put(PROPERTY_INITIALIZER_NO_BACKING_FIELD, new SimpleDiagnosticRenderer("Initializer is not allowed here because this property has no backing field")); - factoryToRenderer.put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, new DiagnosticWithParameters3Renderer("Abstract property {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING)); - factoryToRenderer.put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, new DiagnosticWithParameters3Renderer("Abstract function {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING)); - factoryToRenderer.put(ABSTRACT_FUNCTION_WITH_BODY, new DiagnosticWithParameters1Renderer("A function {0} with body cannot be abstract", TO_STRING)); - factoryToRenderer.put(NON_ABSTRACT_FUNCTION_WITH_NO_BODY, new DiagnosticWithParameters1Renderer("Method {0} without a body must be abstract", TO_STRING)); - factoryToRenderer.put(NON_MEMBER_ABSTRACT_FUNCTION, new DiagnosticWithParameters1Renderer("Function {0} is not a class or trait member and cannot be abstract", TO_STRING)); - - factoryToRenderer.put(NON_MEMBER_FUNCTION_NO_BODY, new DiagnosticWithParameters1Renderer("Function {0} must have a body", TO_STRING)); - factoryToRenderer.put(NON_FINAL_MEMBER_IN_FINAL_CLASS, new SimpleDiagnosticRenderer("Non final member in a final class")); - - factoryToRenderer.put(PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE, new SimpleDiagnosticRenderer("Public or protected member should specify a type")); - - factoryToRenderer.put(PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT, new SimpleDiagnosticRenderer("Projections are not allowed on type arguments of functions and properties")); // TODO : better positioning - factoryToRenderer.put(SUPERTYPE_NOT_INITIALIZED, new SimpleDiagnosticRenderer("This type has a constructor, and thus must be initialized here")); - factoryToRenderer.put(SUPERTYPE_NOT_INITIALIZED_DEFAULT, new SimpleDiagnosticRenderer("Constructor invocation should be explicitly specified")); - factoryToRenderer.put(SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY, new SimpleDiagnosticRenderer("A secondary constructor may appear only in a class that has a primary constructor")); - factoryToRenderer.put(SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST, new SimpleDiagnosticRenderer("Secondary constructors must have an initializer list")); - factoryToRenderer.put(BY_IN_SECONDARY_CONSTRUCTOR, new SimpleDiagnosticRenderer("'by'-clause is only supported for primary constructors")); - factoryToRenderer.put(INITIALIZER_WITH_NO_ARGUMENTS, new SimpleDiagnosticRenderer("Constructor arguments required")); - factoryToRenderer.put(MANY_CALLS_TO_THIS, new SimpleDiagnosticRenderer("Only one call to 'this(...)' is allowed")); - factoryToRenderer.put(NOTHING_TO_OVERRIDE, new DiagnosticWithParameters1Renderer("{0} overrides nothing", DescriptorRenderer.TEXT)); - factoryToRenderer.put(VIRTUAL_MEMBER_HIDDEN, new DiagnosticWithParameters3Renderer("''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); - - factoryToRenderer.put(ENUM_ENTRY_SHOULD_BE_INITIALIZED, new DiagnosticWithParameters1Renderer("Missing delegation specifier ''{0}''", NAME)); - factoryToRenderer.put(ENUM_ENTRY_ILLEGAL_TYPE, new DiagnosticWithParameters1Renderer("The type constructor of enum entry should be ''{0}''", NAME)); - - factoryToRenderer.put(UNINITIALIZED_VARIABLE, new DiagnosticWithParameters1Renderer("Variable ''{0}'' must be initialized", NAME)); - factoryToRenderer.put(UNINITIALIZED_PARAMETER, new DiagnosticWithParameters1Renderer("Parameter ''{0}'' is uninitialized here", NAME)); - factoryToRenderer.put(UNUSED_VARIABLE, new DiagnosticWithParameters1Renderer("Variable ''{0}'' is never used", NAME)); - factoryToRenderer.put(UNUSED_PARAMETER, new DiagnosticWithParameters1Renderer("Parameter ''{0}'' is never used", NAME)); - factoryToRenderer.put(ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE, new DiagnosticWithParameters1Renderer("Variable ''{0}'' is assigned but never accessed", NAME)); - factoryToRenderer.put(VARIABLE_WITH_REDUNDANT_INITIALIZER, new DiagnosticWithParameters1Renderer("Variable ''{0}'' initializer is redundant", NAME)); - factoryToRenderer.put(UNUSED_VALUE, new DiagnosticWithParameters2Renderer("The value ''{0}'' assigned to ''{1}'' is never used", ELEMENT_TEXT, TO_STRING)); - factoryToRenderer.put(UNUSED_CHANGED_VALUE, new DiagnosticWithParameters1Renderer("The value changed at ''{0}'' is never used", ELEMENT_TEXT)); - factoryToRenderer.put(UNUSED_EXPRESSION, new SimpleDiagnosticRenderer("The expression is unused")); - factoryToRenderer.put(UNUSED_FUNCTION_LITERAL, new SimpleDiagnosticRenderer("The function literal is unused. If you mean block, you can use 'run { ... }'")); - - factoryToRenderer.put(VAL_REASSIGNMENT, new DiagnosticWithParameters1Renderer("Val can not be reassigned", NAME)); - factoryToRenderer.put(INITIALIZATION_BEFORE_DECLARATION, new DiagnosticWithParameters1Renderer("Variable cannot be initialized before declaration", NAME)); - factoryToRenderer.put(VARIABLE_EXPECTED, new SimpleDiagnosticRenderer("Variable expected")); - - factoryToRenderer.put(INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER, new DiagnosticWithParameters1Renderer("This property has a custom setter, so initialization using backing field required", NAME)); - factoryToRenderer.put(INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER, new DiagnosticWithParameters1Renderer("Setter of this property can be overridden, so initialization using backing field required", NAME)); - - factoryToRenderer.put(FUNCTION_PARAMETERS_OF_INLINE_FUNCTION, new DiagnosticWithParameters1Renderer("Function parameters of inline function can only be invoked", NAME)); - - factoryToRenderer.put(UNREACHABLE_CODE, new SimpleDiagnosticRenderer("Unreachable code")); - - factoryToRenderer.put(MANY_CLASS_OBJECTS, new SimpleDiagnosticRenderer("Only one class object is allowed per class")); - factoryToRenderer.put(CLASS_OBJECT_NOT_ALLOWED, new SimpleDiagnosticRenderer("A class object is not allowed here")); - factoryToRenderer.put(DELEGATION_IN_TRAIT, new SimpleDiagnosticRenderer("Traits cannot use delegation")); - factoryToRenderer.put(DELEGATION_NOT_TO_TRAIT, new SimpleDiagnosticRenderer("Only traits can be delegated to")); - factoryToRenderer.put(NO_CONSTRUCTOR, new SimpleDiagnosticRenderer("This class does not have a constructor")); - factoryToRenderer.put(NOT_A_CLASS, new SimpleDiagnosticRenderer("Not a class")); - factoryToRenderer.put(ILLEGAL_ESCAPE_SEQUENCE, new SimpleDiagnosticRenderer("Illegal escape sequence")); - - factoryToRenderer.put(LOCAL_EXTENSION_PROPERTY, new SimpleDiagnosticRenderer("Local extension properties are not allowed")); - factoryToRenderer.put(LOCAL_VARIABLE_WITH_GETTER, new SimpleDiagnosticRenderer("Local variables are not allowed to have getters")); - factoryToRenderer.put(LOCAL_VARIABLE_WITH_SETTER, new SimpleDiagnosticRenderer("Local variables are not allowed to have setters")); - factoryToRenderer.put(VAL_WITH_SETTER, new SimpleDiagnosticRenderer("A 'val'-property cannot have a setter")); - - factoryToRenderer.put(NO_GET_METHOD, new SimpleDiagnosticRenderer("No get method providing array access")); - factoryToRenderer.put(NO_SET_METHOD, new SimpleDiagnosticRenderer("No set method providing array access")); - - factoryToRenderer.put(INC_DEC_SHOULD_NOT_RETURN_UNIT, new SimpleDiagnosticRenderer("Functions inc(), dec() shouldn't return Unit to be used by operators ++, --")); - factoryToRenderer.put(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT, new DiagnosticWithParameters2Renderer("Function ''{0}'' should return Unit to be used by corresponding operator ''{1}''", NAME, ELEMENT_TEXT)); - factoryToRenderer.put(ASSIGN_OPERATOR_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Assignment operators ambiguity: {0}")); - - factoryToRenderer.put(EQUALS_MISSING, new SimpleDiagnosticRenderer("No method 'equals(Any?) : Boolean' available")); - factoryToRenderer.put(ASSIGNMENT_IN_EXPRESSION_CONTEXT, new SimpleDiagnosticRenderer("Assignments are not expressions, and only expressions are allowed in this context")); - factoryToRenderer.put(NAMESPACE_IS_NOT_AN_EXPRESSION, new SimpleDiagnosticRenderer("'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')")); - factoryToRenderer.put(SUPER_IS_NOT_AN_EXPRESSION, new DiagnosticWithParameters1Renderer("{0} is not an expression, it can only be used on the left-hand side of a dot ('.')", TO_STRING)); - factoryToRenderer.put(DECLARATION_IN_ILLEGAL_CONTEXT, new SimpleDiagnosticRenderer("Declarations are not allowed in this position")); - factoryToRenderer.put(SETTER_PARAMETER_WITH_DEFAULT_VALUE, new SimpleDiagnosticRenderer("Setter parameters can not have default values")); - factoryToRenderer.put(NO_THIS, new SimpleDiagnosticRenderer("'this' is not defined in this context")); - factoryToRenderer.put(SUPER_NOT_AVAILABLE, new SimpleDiagnosticRenderer("No supertypes are accessible in this context")); - factoryToRenderer.put(AMBIGUOUS_SUPER, new SimpleDiagnosticRenderer("Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super'")); - factoryToRenderer.put(ABSTRACT_SUPER_CALL, new SimpleDiagnosticRenderer("Abstract member cannot be accessed directly")); - factoryToRenderer.put(NOT_A_SUPERTYPE, new SimpleDiagnosticRenderer("Not a supertype")); - factoryToRenderer.put(TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER, new SimpleDiagnosticRenderer("Type arguments do not need to be specified in a 'super' qualifier")); - factoryToRenderer.put(USELESS_CAST_STATIC_ASSERT_IS_FINE, new SimpleDiagnosticRenderer("No cast needed, use ':' instead")); - factoryToRenderer.put(USELESS_CAST, new SimpleDiagnosticRenderer("No cast needed")); - factoryToRenderer.put(CAST_NEVER_SUCCEEDS, new SimpleDiagnosticRenderer("This cast can never succeed")); - factoryToRenderer.put(WRONG_SETTER_PARAMETER_TYPE, new DiagnosticWithParameters1Renderer("Setter parameter type must be equal to the type of the property, i.e. {0}", RENDER_TYPE)); - factoryToRenderer.put(WRONG_GETTER_RETURN_TYPE, new DiagnosticWithParameters1Renderer("Getter return type must be equal to the type of the property, i.e. {0}", RENDER_TYPE)); - factoryToRenderer.put(NO_CLASS_OBJECT, new DiagnosticWithParameters1Renderer("Please specify constructor invocation; classifier {0} does not have a class object", NAME)); - factoryToRenderer.put(NO_GENERICS_IN_SUPERTYPE_SPECIFIER, new SimpleDiagnosticRenderer("Generic arguments of the base type must be specified")); - - factoryToRenderer.put(HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY, new SimpleDiagnosticRenderer("An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext' property")); - factoryToRenderer.put(HAS_NEXT_MISSING, new SimpleDiagnosticRenderer("Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property")); - factoryToRenderer.put(HAS_NEXT_FUNCTION_AMBIGUITY, new SimpleDiagnosticRenderer("Function 'iterator().hasNext()' is ambiguous for this expression")); - factoryToRenderer.put(HAS_NEXT_MUST_BE_READABLE, new SimpleDiagnosticRenderer("The 'iterator().hasNext' property of the loop range must be readable")); - factoryToRenderer.put(HAS_NEXT_PROPERTY_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", RENDER_TYPE)); - factoryToRenderer.put(HAS_NEXT_FUNCTION_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", RENDER_TYPE)); - factoryToRenderer.put(NEXT_AMBIGUITY, new SimpleDiagnosticRenderer("Function 'iterator().next()' is ambiguous for this expression")); - factoryToRenderer.put(NEXT_MISSING, new SimpleDiagnosticRenderer("Loop range must have an 'iterator().next()' function")); - factoryToRenderer.put(ITERATOR_MISSING, new SimpleDiagnosticRenderer("For-loop range must have an iterator() method")); - factoryToRenderer.put(ITERATOR_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Method 'iterator()' is ambiguous for this expression: {0}")); - - factoryToRenderer.put(COMPARE_TO_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("compareTo() must return Int, but returns {0}", RENDER_TYPE)); - factoryToRenderer.put(CALLEE_NOT_A_FUNCTION, new DiagnosticWithParameters1Renderer("Expecting a function type, but found {0}", RENDER_TYPE)); - - factoryToRenderer.put(RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY, new SimpleDiagnosticRenderer("Returns are not allowed for functions with expression body. Use block body in '{...}'")); - factoryToRenderer.put(NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY, new SimpleDiagnosticRenderer("A 'return' expression required in a function with a block body ('{...}')")); - factoryToRenderer.put(RETURN_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("This function must return a value of type {0}", RENDER_TYPE)); - factoryToRenderer.put(EXPECTED_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("Expected a value of type {0}", RENDER_TYPE)); - factoryToRenderer.put(ASSIGNMENT_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("Expected a value of type {0}. Assignment operation is not an expression, so it does not return any value", RENDER_TYPE)); - factoryToRenderer.put(IMPLICIT_CAST_TO_UNIT_OR_ANY, new DiagnosticWithParameters1Renderer("Type was casted to ''{0}''. Please specify ''{0}'' as expected type, if you mean such cast", RENDER_TYPE)); - factoryToRenderer.put(EXPRESSION_EXPECTED, new DiagnosticWithParameters1Renderer("{0} is not an expression, and only expression are allowed here", new Renderer() { + map.put(REDUNDANT_MODIFIER, new DiagnosticWithParameters2Renderer("Modifier {0} is redundant because {1} is present", TO_STRING, TO_STRING)); + map.put(ABSTRACT_MODIFIER_IN_TRAIT, new SimpleDiagnosticRenderer("Modifier ''{0}'' is redundant in trait")); + map.put(OPEN_MODIFIER_IN_TRAIT, new SimpleDiagnosticRenderer("Modifier ''{0}'' is redundant in trait")); + map.put(REDUNDANT_MODIFIER_IN_GETTER, new SimpleDiagnosticRenderer("Visibility modifiers are redundant in getter")); + map.put(TRAIT_CAN_NOT_BE_FINAL, new SimpleDiagnosticRenderer("Trait can not be final")); + map.put(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM, new SimpleDiagnosticRenderer("Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly")); // TODO: message + map.put(RETURN_NOT_ALLOWED, new SimpleDiagnosticRenderer("'return' is not allowed here")); + map.put(PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE, new SimpleDiagnosticRenderer("Projections are not allowed for immediate arguments of a supertype")); + map.put(LABEL_NAME_CLASH, new SimpleDiagnosticRenderer("There is more than one label with such a name in this scope")); + map.put(EXPRESSION_EXPECTED_NAMESPACE_FOUND, new SimpleDiagnosticRenderer("Expression expected, but a namespace name found")); + + map.put(CANNOT_IMPORT_FROM_ELEMENT, new DiagnosticWithParameters1Renderer("Cannot import from ''{0}''", NAME)); + map.put(CANNOT_BE_IMPORTED, new DiagnosticWithParameters1Renderer("Cannot import ''{0}'', functions and properties can be imported only from packages", NAME)); + map.put(USELESS_HIDDEN_IMPORT, new SimpleDiagnosticRenderer("Useless import, it is hidden further")); + map.put(USELESS_SIMPLE_IMPORT, new SimpleDiagnosticRenderer("Useless import, does nothing")); + + map.put(CANNOT_INFER_PARAMETER_TYPE, new SimpleDiagnosticRenderer("Cannot infer a type for this parameter. To specify it explicitly use the {(p : Type) => ...} notation")); + + map.put(NO_BACKING_FIELD_ABSTRACT_PROPERTY, new SimpleDiagnosticRenderer("This property doesn't have a backing field, because it's abstract")); + map.put(NO_BACKING_FIELD_CUSTOM_ACCESSORS, new SimpleDiagnosticRenderer("This property doesn't have a backing field, because it has custom accessors without reference to the backing field")); + map.put(INACCESSIBLE_BACKING_FIELD, new SimpleDiagnosticRenderer("The backing field is not accessible here")); + map.put(NOT_PROPERTY_BACKING_FIELD, new SimpleDiagnosticRenderer("The referenced variable is not a property and doesn't have backing field")); + + map.put(MIXING_NAMED_AND_POSITIONED_ARGUMENTS, new SimpleDiagnosticRenderer("Mixing named and positioned arguments in not allowed")); + map.put(ARGUMENT_PASSED_TWICE, new SimpleDiagnosticRenderer("An argument is already passed for this parameter")); + map.put(NAMED_PARAMETER_NOT_FOUND, new UnresolvedReferenceDiagnosticRenderer("Cannot find a parameter with this name: ")); + map.put(VARARG_OUTSIDE_PARENTHESES, new SimpleDiagnosticRenderer("Passing value as a vararg is only allowed inside a parenthesized argument list")); + map.put(NON_VARARG_SPREAD, new SimpleDiagnosticRenderer("The spread operator (*foo) may only be applied in a vararg position")); + + map.put(MANY_FUNCTION_LITERAL_ARGUMENTS, new SimpleDiagnosticRenderer("Only one function literal is allowed outside a parenthesized argument list")); + map.put(PROPERTY_WITH_NO_TYPE_NO_INITIALIZER, new SimpleDiagnosticRenderer("This property must either have a type annotation or be initialized")); + + map.put(ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS, new SimpleDiagnosticRenderer("This property cannot be declared abstract")); + map.put(ABSTRACT_PROPERTY_NOT_IN_CLASS, new SimpleDiagnosticRenderer("A property may be abstract only when defined in a class or trait")); + map.put(ABSTRACT_PROPERTY_WITH_INITIALIZER, new SimpleDiagnosticRenderer("Property with initializer cannot be abstract")); + map.put(ABSTRACT_PROPERTY_WITH_GETTER, new SimpleDiagnosticRenderer("Property with getter implementation cannot be abstract")); + map.put(ABSTRACT_PROPERTY_WITH_SETTER, new SimpleDiagnosticRenderer("Property with setter implementation cannot be abstract")); + + map.put(PACKAGE_MEMBER_CANNOT_BE_PROTECTED, new SimpleDiagnosticRenderer("Package member cannot be protected")); + + map.put(GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY, new SimpleDiagnosticRenderer("Getter visibility must be the same as property visibility")); + map.put(BACKING_FIELD_IN_TRAIT, new SimpleDiagnosticRenderer("Property in a trait cannot have a backing field")); + map.put(MUST_BE_INITIALIZED, new SimpleDiagnosticRenderer("Property must be initialized")); + map.put(MUST_BE_INITIALIZED_OR_BE_ABSTRACT, new SimpleDiagnosticRenderer("Property must be initialized or be abstract")); + map.put(PROPERTY_INITIALIZER_IN_TRAIT, new SimpleDiagnosticRenderer("Property initializers are not allowed in traits")); + map.put(PROPERTY_INITIALIZER_NO_BACKING_FIELD, new SimpleDiagnosticRenderer("Initializer is not allowed here because this property has no backing field")); + map.put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, new DiagnosticWithParameters3Renderer("Abstract property {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING)); + map.put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, new DiagnosticWithParameters3Renderer("Abstract function {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING)); + map.put(ABSTRACT_FUNCTION_WITH_BODY, new DiagnosticWithParameters1Renderer("A function {0} with body cannot be abstract", TO_STRING)); + map.put(NON_ABSTRACT_FUNCTION_WITH_NO_BODY, new DiagnosticWithParameters1Renderer("Method {0} without a body must be abstract", TO_STRING)); + map.put(NON_MEMBER_ABSTRACT_FUNCTION, new DiagnosticWithParameters1Renderer("Function {0} is not a class or trait member and cannot be abstract", TO_STRING)); + + map.put(NON_MEMBER_FUNCTION_NO_BODY, new DiagnosticWithParameters1Renderer("Function {0} must have a body", TO_STRING)); + map.put(NON_FINAL_MEMBER_IN_FINAL_CLASS, new SimpleDiagnosticRenderer("Non final member in a final class")); + + map.put(PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE, new SimpleDiagnosticRenderer("Public or protected member should specify a type")); + + map.put(PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT, new SimpleDiagnosticRenderer("Projections are not allowed on type arguments of functions and properties")); // TODO : better positioning + map.put(SUPERTYPE_NOT_INITIALIZED, new SimpleDiagnosticRenderer("This type has a constructor, and thus must be initialized here")); + map.put(SUPERTYPE_NOT_INITIALIZED_DEFAULT, new SimpleDiagnosticRenderer("Constructor invocation should be explicitly specified")); + map.put(SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY, new SimpleDiagnosticRenderer("A secondary constructor may appear only in a class that has a primary constructor")); + map.put(SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST, new SimpleDiagnosticRenderer("Secondary constructors must have an initializer list")); + map.put(BY_IN_SECONDARY_CONSTRUCTOR, new SimpleDiagnosticRenderer("'by'-clause is only supported for primary constructors")); + map.put(INITIALIZER_WITH_NO_ARGUMENTS, new SimpleDiagnosticRenderer("Constructor arguments required")); + map.put(MANY_CALLS_TO_THIS, new SimpleDiagnosticRenderer("Only one call to 'this(...)' is allowed")); + map.put(NOTHING_TO_OVERRIDE, new DiagnosticWithParameters1Renderer("{0} overrides nothing", DescriptorRenderer.TEXT)); + map.put(VIRTUAL_MEMBER_HIDDEN, new DiagnosticWithParameters3Renderer("''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); + + map.put(ENUM_ENTRY_SHOULD_BE_INITIALIZED, new DiagnosticWithParameters1Renderer("Missing delegation specifier ''{0}''", NAME)); + map.put(ENUM_ENTRY_ILLEGAL_TYPE, new DiagnosticWithParameters1Renderer("The type constructor of enum entry should be ''{0}''", NAME)); + + map.put(UNINITIALIZED_VARIABLE, new DiagnosticWithParameters1Renderer("Variable ''{0}'' must be initialized", NAME)); + map.put(UNINITIALIZED_PARAMETER, new DiagnosticWithParameters1Renderer("Parameter ''{0}'' is uninitialized here", NAME)); + map.put(UNUSED_VARIABLE, new DiagnosticWithParameters1Renderer("Variable ''{0}'' is never used", NAME)); + map.put(UNUSED_PARAMETER, new DiagnosticWithParameters1Renderer("Parameter ''{0}'' is never used", NAME)); + map.put(ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE, new DiagnosticWithParameters1Renderer("Variable ''{0}'' is assigned but never accessed", NAME)); + map.put(VARIABLE_WITH_REDUNDANT_INITIALIZER, new DiagnosticWithParameters1Renderer("Variable ''{0}'' initializer is redundant", NAME)); + map.put(UNUSED_VALUE, new DiagnosticWithParameters2Renderer("The value ''{0}'' assigned to ''{1}'' is never used", ELEMENT_TEXT, TO_STRING)); + map.put(UNUSED_CHANGED_VALUE, new DiagnosticWithParameters1Renderer("The value changed at ''{0}'' is never used", ELEMENT_TEXT)); + map.put(UNUSED_EXPRESSION, new SimpleDiagnosticRenderer("The expression is unused")); + map.put(UNUSED_FUNCTION_LITERAL, new SimpleDiagnosticRenderer("The function literal is unused. If you mean block, you can use 'run { ... }'")); + + map.put(VAL_REASSIGNMENT, new DiagnosticWithParameters1Renderer("Val can not be reassigned", NAME)); + map.put(INITIALIZATION_BEFORE_DECLARATION, new DiagnosticWithParameters1Renderer("Variable cannot be initialized before declaration", NAME)); + map.put(VARIABLE_EXPECTED, new SimpleDiagnosticRenderer("Variable expected")); + + map.put(INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER, new DiagnosticWithParameters1Renderer("This property has a custom setter, so initialization using backing field required", NAME)); + map.put(INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER, new DiagnosticWithParameters1Renderer("Setter of this property can be overridden, so initialization using backing field required", NAME)); + + map.put(FUNCTION_PARAMETERS_OF_INLINE_FUNCTION, new DiagnosticWithParameters1Renderer("Function parameters of inline function can only be invoked", NAME)); + + map.put(UNREACHABLE_CODE, new SimpleDiagnosticRenderer("Unreachable code")); + + map.put(MANY_CLASS_OBJECTS, new SimpleDiagnosticRenderer("Only one class object is allowed per class")); + map.put(CLASS_OBJECT_NOT_ALLOWED, new SimpleDiagnosticRenderer("A class object is not allowed here")); + map.put(DELEGATION_IN_TRAIT, new SimpleDiagnosticRenderer("Traits cannot use delegation")); + map.put(DELEGATION_NOT_TO_TRAIT, new SimpleDiagnosticRenderer("Only traits can be delegated to")); + map.put(NO_CONSTRUCTOR, new SimpleDiagnosticRenderer("This class does not have a constructor")); + map.put(NOT_A_CLASS, new SimpleDiagnosticRenderer("Not a class")); + map.put(ILLEGAL_ESCAPE_SEQUENCE, new SimpleDiagnosticRenderer("Illegal escape sequence")); + + map.put(LOCAL_EXTENSION_PROPERTY, new SimpleDiagnosticRenderer("Local extension properties are not allowed")); + map.put(LOCAL_VARIABLE_WITH_GETTER, new SimpleDiagnosticRenderer("Local variables are not allowed to have getters")); + map.put(LOCAL_VARIABLE_WITH_SETTER, new SimpleDiagnosticRenderer("Local variables are not allowed to have setters")); + map.put(VAL_WITH_SETTER, new SimpleDiagnosticRenderer("A 'val'-property cannot have a setter")); + + map.put(NO_GET_METHOD, new SimpleDiagnosticRenderer("No get method providing array access")); + map.put(NO_SET_METHOD, new SimpleDiagnosticRenderer("No set method providing array access")); + + map.put(INC_DEC_SHOULD_NOT_RETURN_UNIT, new SimpleDiagnosticRenderer("Functions inc(), dec() shouldn't return Unit to be used by operators ++, --")); + map.put(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT, new DiagnosticWithParameters2Renderer("Function ''{0}'' should return Unit to be used by corresponding operator ''{1}''", NAME, ELEMENT_TEXT)); + map.put(ASSIGN_OPERATOR_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Assignment operators ambiguity: {0}")); + + map.put(EQUALS_MISSING, new SimpleDiagnosticRenderer("No method 'equals(Any?) : Boolean' available")); + map.put(ASSIGNMENT_IN_EXPRESSION_CONTEXT, new SimpleDiagnosticRenderer("Assignments are not expressions, and only expressions are allowed in this context")); + map.put(NAMESPACE_IS_NOT_AN_EXPRESSION, new SimpleDiagnosticRenderer("'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')")); + map.put(SUPER_IS_NOT_AN_EXPRESSION, new DiagnosticWithParameters1Renderer("{0} is not an expression, it can only be used on the left-hand side of a dot ('.')", TO_STRING)); + map.put(DECLARATION_IN_ILLEGAL_CONTEXT, new SimpleDiagnosticRenderer("Declarations are not allowed in this position")); + map.put(SETTER_PARAMETER_WITH_DEFAULT_VALUE, new SimpleDiagnosticRenderer("Setter parameters can not have default values")); + map.put(NO_THIS, new SimpleDiagnosticRenderer("'this' is not defined in this context")); + map.put(SUPER_NOT_AVAILABLE, new SimpleDiagnosticRenderer("No supertypes are accessible in this context")); + map.put(AMBIGUOUS_SUPER, new SimpleDiagnosticRenderer("Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super'")); + map.put(ABSTRACT_SUPER_CALL, new SimpleDiagnosticRenderer("Abstract member cannot be accessed directly")); + map.put(NOT_A_SUPERTYPE, new SimpleDiagnosticRenderer("Not a supertype")); + map.put(TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER, new SimpleDiagnosticRenderer("Type arguments do not need to be specified in a 'super' qualifier")); + map.put(USELESS_CAST_STATIC_ASSERT_IS_FINE, new SimpleDiagnosticRenderer("No cast needed, use ':' instead")); + map.put(USELESS_CAST, new SimpleDiagnosticRenderer("No cast needed")); + map.put(CAST_NEVER_SUCCEEDS, new SimpleDiagnosticRenderer("This cast can never succeed")); + map.put(WRONG_SETTER_PARAMETER_TYPE, new DiagnosticWithParameters1Renderer("Setter parameter type must be equal to the type of the property, i.e. {0}", RENDER_TYPE)); + map.put(WRONG_GETTER_RETURN_TYPE, new DiagnosticWithParameters1Renderer("Getter return type must be equal to the type of the property, i.e. {0}", RENDER_TYPE)); + map.put(NO_CLASS_OBJECT, new DiagnosticWithParameters1Renderer("Please specify constructor invocation; classifier {0} does not have a class object", NAME)); + map.put(NO_GENERICS_IN_SUPERTYPE_SPECIFIER, new SimpleDiagnosticRenderer("Generic arguments of the base type must be specified")); + + map.put(HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY, new SimpleDiagnosticRenderer("An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext' property")); + map.put(HAS_NEXT_MISSING, new SimpleDiagnosticRenderer("Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property")); + map.put(HAS_NEXT_FUNCTION_AMBIGUITY, new SimpleDiagnosticRenderer("Function 'iterator().hasNext()' is ambiguous for this expression")); + map.put(HAS_NEXT_MUST_BE_READABLE, new SimpleDiagnosticRenderer("The 'iterator().hasNext' property of the loop range must be readable")); + map.put(HAS_NEXT_PROPERTY_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", RENDER_TYPE)); + map.put(HAS_NEXT_FUNCTION_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", RENDER_TYPE)); + map.put(NEXT_AMBIGUITY, new SimpleDiagnosticRenderer("Function 'iterator().next()' is ambiguous for this expression")); + map.put(NEXT_MISSING, new SimpleDiagnosticRenderer("Loop range must have an 'iterator().next()' function")); + map.put(ITERATOR_MISSING, new SimpleDiagnosticRenderer("For-loop range must have an iterator() method")); + map.put(ITERATOR_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Method 'iterator()' is ambiguous for this expression: {0}")); + + map.put(COMPARE_TO_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("compareTo() must return Int, but returns {0}", RENDER_TYPE)); + map.put(CALLEE_NOT_A_FUNCTION, new DiagnosticWithParameters1Renderer("Expecting a function type, but found {0}", RENDER_TYPE)); + + map.put(RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY, new SimpleDiagnosticRenderer("Returns are not allowed for functions with expression body. Use block body in '{...}'")); + map.put(NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY, new SimpleDiagnosticRenderer("A 'return' expression required in a function with a block body ('{...}')")); + map.put(RETURN_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("This function must return a value of type {0}", RENDER_TYPE)); + map.put(EXPECTED_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("Expected a value of type {0}", RENDER_TYPE)); + map.put(ASSIGNMENT_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("Expected a value of type {0}. Assignment operation is not an expression, so it does not return any value", RENDER_TYPE)); + map.put(IMPLICIT_CAST_TO_UNIT_OR_ANY, new DiagnosticWithParameters1Renderer("Type was casted to ''{0}''. Please specify ''{0}'' as expected type, if you mean such cast", RENDER_TYPE)); + map.put(EXPRESSION_EXPECTED, new DiagnosticWithParameters1Renderer("{0} is not an expression, and only expression are allowed here", new Renderer() { @NotNull @Override public String render(@NotNull JetExpression expression) { @@ -241,45 +241,45 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer } })); - factoryToRenderer.put(UPPER_BOUND_VIOLATED, new DiagnosticWithParameters1Renderer("An upper bound {0} is violated", RENDER_TYPE)); // TODO : Message - factoryToRenderer.put(FINAL_CLASS_OBJECT_UPPER_BOUND, new DiagnosticWithParameters1Renderer("{0} is a final type, and thus a class object cannot extend it", RENDER_TYPE)); - factoryToRenderer.put(FINAL_UPPER_BOUND, new DiagnosticWithParameters1Renderer("{0} is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE)); - factoryToRenderer.put(USELESS_ELVIS, new DiagnosticWithParameters1Renderer("Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE)); - factoryToRenderer.put(CONFLICTING_UPPER_BOUNDS, new DiagnosticWithParameters1Renderer("Upper bounds of {0} have empty intersection", NAME)); - factoryToRenderer.put(CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS, new DiagnosticWithParameters1Renderer("Class object upper bounds of {0} have empty intersection", NAME)); - - factoryToRenderer.put(TOO_MANY_ARGUMENTS, new DiagnosticWithParameters1Renderer("Too many arguments for {0}", TO_STRING)); - factoryToRenderer.put(ERROR_COMPILE_TIME_VALUE, new DiagnosticWithParameters1Renderer("{0}", TO_STRING)); - - factoryToRenderer.put(ELSE_MISPLACED_IN_WHEN, new SimpleDiagnosticRenderer("'else' entry must be the last one in a when-expression")); - - factoryToRenderer.put(NO_ELSE_IN_WHEN, new SimpleDiagnosticRenderer("'when' expression must contain 'else' branch")); - factoryToRenderer.put(TYPE_MISMATCH_IN_RANGE, new SimpleDiagnosticRenderer("Type mismatch: incompatible types of range and element checked in it")); - factoryToRenderer.put(CYCLIC_INHERITANCE_HIERARCHY, new SimpleDiagnosticRenderer("There's a cycle in the inheritance hierarchy for this type")); - - factoryToRenderer.put(MANY_CLASSES_IN_SUPERTYPE_LIST, new SimpleDiagnosticRenderer("Only one class may appear in a supertype list")); - factoryToRenderer.put(SUPERTYPE_NOT_A_CLASS_OR_TRAIT, new SimpleDiagnosticRenderer("Only classes and traits may serve as supertypes")); - factoryToRenderer.put(SUPERTYPE_INITIALIZED_IN_TRAIT, new SimpleDiagnosticRenderer("Traits cannot initialize supertypes")); - factoryToRenderer.put(CONSTRUCTOR_IN_TRAIT, new SimpleDiagnosticRenderer("A trait may not have a constructor")); - factoryToRenderer.put(SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED, new SimpleDiagnosticRenderer("Secondary constructors are not supported")); - factoryToRenderer.put(SUPERTYPE_APPEARS_TWICE, new SimpleDiagnosticRenderer("A supertype appears twice")); - factoryToRenderer.put(FINAL_SUPERTYPE, new SimpleDiagnosticRenderer("This type is final, so it cannot be inherited from")); - - factoryToRenderer.put(ILLEGAL_SELECTOR, new DiagnosticWithParameters1Renderer("Expression ''{0}'' cannot be a selector (occur after a dot)", TO_STRING)); - - factoryToRenderer.put(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION, new SimpleDiagnosticRenderer("A type annotation is required on a value parameter")); - factoryToRenderer.put(BREAK_OR_CONTINUE_OUTSIDE_A_LOOP, new SimpleDiagnosticRenderer("'break' and 'continue' are only allowed inside a loop")); - factoryToRenderer.put(NOT_A_LOOP_LABEL, new DiagnosticWithParameters1Renderer("The label ''{0}'' does not denote a loop", TO_STRING)); - factoryToRenderer.put(NOT_A_RETURN_LABEL, new DiagnosticWithParameters1Renderer("The label ''{0}'' does not reference to a context from which we can return", TO_STRING)); - - factoryToRenderer.put(ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR, new SimpleDiagnosticRenderer("Anonymous initializers are only allowed in the presence of a primary constructor")); - factoryToRenderer.put(NULLABLE_SUPERTYPE, new SimpleDiagnosticRenderer("A supertype cannot be nullable")); - factoryToRenderer.put(UNSAFE_CALL, new DiagnosticWithParameters1Renderer("Only safe calls (?.) are allowed on a nullable receiver of type {0}", RENDER_TYPE)); - factoryToRenderer.put(AMBIGUOUS_LABEL, new SimpleDiagnosticRenderer("Ambiguous label")); - factoryToRenderer.put(UNSUPPORTED, new DiagnosticWithParameters1Renderer("Unsupported [{0}]", TO_STRING)); - factoryToRenderer.put(UNNECESSARY_SAFE_CALL, new DiagnosticWithParameters1Renderer("Unnecessary safe call on a non-null receiver of type {0}", RENDER_TYPE)); - factoryToRenderer.put(UNNECESSARY_NOT_NULL_ASSERTION, new DiagnosticWithParameters1Renderer("Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", RENDER_TYPE)); - factoryToRenderer.put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, new DiagnosticWithParameters2Renderer("{0} does not refer to a type parameter of {1}", new Renderer() { + map.put(UPPER_BOUND_VIOLATED, new DiagnosticWithParameters1Renderer("An upper bound {0} is violated", RENDER_TYPE)); // TODO : Message + map.put(FINAL_CLASS_OBJECT_UPPER_BOUND, new DiagnosticWithParameters1Renderer("{0} is a final type, and thus a class object cannot extend it", RENDER_TYPE)); + map.put(FINAL_UPPER_BOUND, new DiagnosticWithParameters1Renderer("{0} is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE)); + map.put(USELESS_ELVIS, new DiagnosticWithParameters1Renderer("Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE)); + map.put(CONFLICTING_UPPER_BOUNDS, new DiagnosticWithParameters1Renderer("Upper bounds of {0} have empty intersection", NAME)); + map.put(CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS, new DiagnosticWithParameters1Renderer("Class object upper bounds of {0} have empty intersection", NAME)); + + map.put(TOO_MANY_ARGUMENTS, new DiagnosticWithParameters1Renderer("Too many arguments for {0}", TO_STRING)); + map.put(ERROR_COMPILE_TIME_VALUE, new DiagnosticWithParameters1Renderer("{0}", TO_STRING)); + + map.put(ELSE_MISPLACED_IN_WHEN, new SimpleDiagnosticRenderer("'else' entry must be the last one in a when-expression")); + + map.put(NO_ELSE_IN_WHEN, new SimpleDiagnosticRenderer("'when' expression must contain 'else' branch")); + map.put(TYPE_MISMATCH_IN_RANGE, new SimpleDiagnosticRenderer("Type mismatch: incompatible types of range and element checked in it")); + map.put(CYCLIC_INHERITANCE_HIERARCHY, new SimpleDiagnosticRenderer("There's a cycle in the inheritance hierarchy for this type")); + + map.put(MANY_CLASSES_IN_SUPERTYPE_LIST, new SimpleDiagnosticRenderer("Only one class may appear in a supertype list")); + map.put(SUPERTYPE_NOT_A_CLASS_OR_TRAIT, new SimpleDiagnosticRenderer("Only classes and traits may serve as supertypes")); + map.put(SUPERTYPE_INITIALIZED_IN_TRAIT, new SimpleDiagnosticRenderer("Traits cannot initialize supertypes")); + map.put(CONSTRUCTOR_IN_TRAIT, new SimpleDiagnosticRenderer("A trait may not have a constructor")); + map.put(SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED, new SimpleDiagnosticRenderer("Secondary constructors are not supported")); + map.put(SUPERTYPE_APPEARS_TWICE, new SimpleDiagnosticRenderer("A supertype appears twice")); + map.put(FINAL_SUPERTYPE, new SimpleDiagnosticRenderer("This type is final, so it cannot be inherited from")); + + map.put(ILLEGAL_SELECTOR, new DiagnosticWithParameters1Renderer("Expression ''{0}'' cannot be a selector (occur after a dot)", TO_STRING)); + + map.put(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION, new SimpleDiagnosticRenderer("A type annotation is required on a value parameter")); + map.put(BREAK_OR_CONTINUE_OUTSIDE_A_LOOP, new SimpleDiagnosticRenderer("'break' and 'continue' are only allowed inside a loop")); + map.put(NOT_A_LOOP_LABEL, new DiagnosticWithParameters1Renderer("The label ''{0}'' does not denote a loop", TO_STRING)); + map.put(NOT_A_RETURN_LABEL, new DiagnosticWithParameters1Renderer("The label ''{0}'' does not reference to a context from which we can return", TO_STRING)); + + map.put(ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR, new SimpleDiagnosticRenderer("Anonymous initializers are only allowed in the presence of a primary constructor")); + map.put(NULLABLE_SUPERTYPE, new SimpleDiagnosticRenderer("A supertype cannot be nullable")); + map.put(UNSAFE_CALL, new DiagnosticWithParameters1Renderer("Only safe calls (?.) are allowed on a nullable receiver of type {0}", RENDER_TYPE)); + map.put(AMBIGUOUS_LABEL, new SimpleDiagnosticRenderer("Ambiguous label")); + map.put(UNSUPPORTED, new DiagnosticWithParameters1Renderer("Unsupported [{0}]", TO_STRING)); + map.put(UNNECESSARY_SAFE_CALL, new DiagnosticWithParameters1Renderer("Unnecessary safe call on a non-null receiver of type {0}", RENDER_TYPE)); + map.put(UNNECESSARY_NOT_NULL_ASSERTION, new DiagnosticWithParameters1Renderer("Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", RENDER_TYPE)); + map.put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, new DiagnosticWithParameters2Renderer("{0} does not refer to a type parameter of {1}", new Renderer() { @NotNull @Override public String render(@NotNull JetTypeConstraint typeConstraint) { @@ -287,19 +287,19 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer return typeConstraint.getSubjectTypeParameterName().getReferencedName(); } }, NAME)); - factoryToRenderer.put(AUTOCAST_IMPOSSIBLE, new DiagnosticWithParameters2Renderer("Automatic cast to {0} is impossible, because {1} could have changed since the is-check", RENDER_TYPE, NAME)); - - factoryToRenderer.put(TYPE_MISMATCH_IN_FOR_LOOP, new DiagnosticWithParameters2Renderer("The loop iterates over values of type {0} but the parameter is declared to be {1}", RENDER_TYPE, RENDER_TYPE)); - factoryToRenderer.put(TYPE_MISMATCH_IN_CONDITION, new DiagnosticWithParameters1Renderer("Condition must be of type Boolean, but was of type {0}", RENDER_TYPE)); - factoryToRenderer.put(TYPE_MISMATCH_IN_TUPLE_PATTERN, new DiagnosticWithParameters2Renderer("Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, TO_STRING)); // TODO: message - factoryToRenderer.put(TYPE_MISMATCH_IN_BINDING_PATTERN, new DiagnosticWithParameters2Renderer("{0} must be a supertype of {1}. Use 'is' to match against {0}", RENDER_TYPE, RENDER_TYPE)); - factoryToRenderer.put(INCOMPATIBLE_TYPES, new DiagnosticWithParameters2Renderer("Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE)); - factoryToRenderer.put(EXPECTED_CONDITION, new SimpleDiagnosticRenderer("Expected condition of Boolean type")); - - factoryToRenderer.put(CANNOT_CHECK_FOR_ERASED, new DiagnosticWithParameters1Renderer("Cannot check for instance of erased type: {0}", RENDER_TYPE)); - factoryToRenderer.put(UNCHECKED_CAST, new DiagnosticWithParameters2Renderer("Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE)); - - factoryToRenderer.put(INCONSISTENT_TYPE_PARAMETER_VALUES, new DiagnosticWithParameters3Renderer>("Type parameter {0} of {1} has inconsistent values: {2}", NAME, DescriptorRenderer.TEXT, new Renderer>() { + map.put(AUTOCAST_IMPOSSIBLE, new DiagnosticWithParameters2Renderer("Automatic cast to {0} is impossible, because {1} could have changed since the is-check", RENDER_TYPE, NAME)); + + map.put(TYPE_MISMATCH_IN_FOR_LOOP, new DiagnosticWithParameters2Renderer("The loop iterates over values of type {0} but the parameter is declared to be {1}", RENDER_TYPE, RENDER_TYPE)); + map.put(TYPE_MISMATCH_IN_CONDITION, new DiagnosticWithParameters1Renderer("Condition must be of type Boolean, but was of type {0}", RENDER_TYPE)); + map.put(TYPE_MISMATCH_IN_TUPLE_PATTERN, new DiagnosticWithParameters2Renderer("Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, TO_STRING)); // TODO: message + map.put(TYPE_MISMATCH_IN_BINDING_PATTERN, new DiagnosticWithParameters2Renderer("{0} must be a supertype of {1}. Use 'is' to match against {0}", RENDER_TYPE, RENDER_TYPE)); + map.put(INCOMPATIBLE_TYPES, new DiagnosticWithParameters2Renderer("Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE)); + map.put(EXPECTED_CONDITION, new SimpleDiagnosticRenderer("Expected condition of Boolean type")); + + map.put(CANNOT_CHECK_FOR_ERASED, new DiagnosticWithParameters1Renderer("Cannot check for instance of erased type: {0}", RENDER_TYPE)); + map.put(UNCHECKED_CAST, new DiagnosticWithParameters2Renderer("Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE)); + + map.put(INCONSISTENT_TYPE_PARAMETER_VALUES, new DiagnosticWithParameters3Renderer>("Type parameter {0} of {1} has inconsistent values: {2}", NAME, DescriptorRenderer.TEXT, new Renderer>() { @NotNull @Override public String render(@NotNull Collection types) { @@ -315,7 +315,7 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer } })); - factoryToRenderer.put(EQUALITY_NOT_APPLICABLE, new DiagnosticWithParameters3Renderer("Operator {0} cannot be applied to {1} and {2}", new Renderer() { + map.put(EQUALITY_NOT_APPLICABLE, new DiagnosticWithParameters3Renderer("Operator {0} cannot be applied to {1} and {2}", new Renderer() { @NotNull @Override public String render(@NotNull JetSimpleNameExpression nameExpression) { @@ -323,34 +323,34 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer return nameExpression.getReferencedName(); } }, TO_STRING, TO_STRING)); - - factoryToRenderer.put(OVERRIDING_FINAL_MEMBER, new DiagnosticWithParameters2Renderer("''{0}'' in ''{1}'' is final and cannot be overridden", NAME, NAME)); - factoryToRenderer.put(CANNOT_WEAKEN_ACCESS_PRIVILEGE, new DiagnosticWithParameters3Renderer("Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME)); - factoryToRenderer.put(CANNOT_CHANGE_ACCESS_PRIVILEGE, new DiagnosticWithParameters3Renderer("Cannot change access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME)); - - factoryToRenderer.put(RETURN_TYPE_MISMATCH_ON_OVERRIDE, new DiagnosticWithParameters2Renderer("Return type of {0} is not a subtype of the return type overridden member {1}", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); - - factoryToRenderer.put(VAR_OVERRIDDEN_BY_VAL, new DiagnosticWithParameters2Renderer("Var-property {0} cannot be overridden by val-property {1}", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); - - factoryToRenderer.put(ABSTRACT_MEMBER_NOT_IMPLEMENTED, new DiagnosticWithParameters2Renderer("{0} must be declared abstract or implement abstract member {1}", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT)); - - factoryToRenderer.put(MANY_IMPL_MEMBER_NOT_IMPLEMENTED, new DiagnosticWithParameters2Renderer("{0} must override {1} because it inherits many implementations of it", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT)); - - factoryToRenderer.put(CONFLICTING_OVERLOADS, new DiagnosticWithParameters2Renderer("{1} is already defined in ''{0}''", DescriptorRenderer.TEXT, TO_STRING)); - - - factoryToRenderer.put(RESULT_TYPE_MISMATCH, new DiagnosticWithParameters3Renderer("{0} must return {1} but returns {2}", TO_STRING, RENDER_TYPE, RENDER_TYPE)); - factoryToRenderer.put(UNSAFE_INFIX_CALL, new DiagnosticWithParameters3Renderer("Infix call corresponds to a dot-qualified call ''{0}.{1}({2})'' which is not allowed on a nullable receiver ''{0}''. Use '?.'-qualified call instead", TO_STRING, TO_STRING, TO_STRING)); - - factoryToRenderer.put(OVERLOAD_RESOLUTION_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Overload resolution ambiguity: {0}")); - factoryToRenderer.put(NONE_APPLICABLE, new AmbiguousDescriptorDiagnosticRenderer("None of the following functions can be called with the arguments supplied: {0}")); - factoryToRenderer.put(NO_VALUE_FOR_PARAMETER, new DiagnosticWithParameters1Renderer("No value passed for parameter {0}", DescriptorRenderer.TEXT)); - factoryToRenderer.put(MISSING_RECEIVER, new DiagnosticWithParameters1Renderer("A receiver of type {0} is required", RENDER_TYPE)); - factoryToRenderer.put(NO_RECEIVER_ADMITTED, new SimpleDiagnosticRenderer("No receiver can be passed to this function or property")); - - factoryToRenderer.put(CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS, new SimpleDiagnosticRenderer("Can not create an instance of an abstract class")); - factoryToRenderer.put(TYPE_INFERENCE_FAILED, new DiagnosticWithParameters1Renderer("Type inference failed: {0}", TO_STRING)); - factoryToRenderer.put(WRONG_NUMBER_OF_TYPE_ARGUMENTS, new DiagnosticWithParameters1Renderer("{0} type arguments expected", new Renderer() { + + map.put(OVERRIDING_FINAL_MEMBER, new DiagnosticWithParameters2Renderer("''{0}'' in ''{1}'' is final and cannot be overridden", NAME, NAME)); + map.put(CANNOT_WEAKEN_ACCESS_PRIVILEGE, new DiagnosticWithParameters3Renderer("Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME)); + map.put(CANNOT_CHANGE_ACCESS_PRIVILEGE, new DiagnosticWithParameters3Renderer("Cannot change access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME)); + + map.put(RETURN_TYPE_MISMATCH_ON_OVERRIDE, new DiagnosticWithParameters2Renderer("Return type of {0} is not a subtype of the return type overridden member {1}", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); + + map.put(VAR_OVERRIDDEN_BY_VAL, new DiagnosticWithParameters2Renderer("Var-property {0} cannot be overridden by val-property {1}", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); + + map.put(ABSTRACT_MEMBER_NOT_IMPLEMENTED, new DiagnosticWithParameters2Renderer("{0} must be declared abstract or implement abstract member {1}", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT)); + + map.put(MANY_IMPL_MEMBER_NOT_IMPLEMENTED, new DiagnosticWithParameters2Renderer("{0} must override {1} because it inherits many implementations of it", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT)); + + map.put(CONFLICTING_OVERLOADS, new DiagnosticWithParameters2Renderer("{1} is already defined in ''{0}''", DescriptorRenderer.TEXT, TO_STRING)); + + + map.put(RESULT_TYPE_MISMATCH, new DiagnosticWithParameters3Renderer("{0} must return {1} but returns {2}", TO_STRING, RENDER_TYPE, RENDER_TYPE)); + map.put(UNSAFE_INFIX_CALL, new DiagnosticWithParameters3Renderer("Infix call corresponds to a dot-qualified call ''{0}.{1}({2})'' which is not allowed on a nullable receiver ''{0}''. Use '?.'-qualified call instead", TO_STRING, TO_STRING, TO_STRING)); + + map.put(OVERLOAD_RESOLUTION_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Overload resolution ambiguity: {0}")); + map.put(NONE_APPLICABLE, new AmbiguousDescriptorDiagnosticRenderer("None of the following functions can be called with the arguments supplied: {0}")); + map.put(NO_VALUE_FOR_PARAMETER, new DiagnosticWithParameters1Renderer("No value passed for parameter {0}", DescriptorRenderer.TEXT)); + map.put(MISSING_RECEIVER, new DiagnosticWithParameters1Renderer("A receiver of type {0} is required", RENDER_TYPE)); + map.put(NO_RECEIVER_ADMITTED, new SimpleDiagnosticRenderer("No receiver can be passed to this function or property")); + + map.put(CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS, new SimpleDiagnosticRenderer("Can not create an instance of an abstract class")); + map.put(TYPE_INFERENCE_FAILED, new DiagnosticWithParameters1Renderer("Type inference failed: {0}", TO_STRING)); + map.put(WRONG_NUMBER_OF_TYPE_ARGUMENTS, new DiagnosticWithParameters1Renderer("{0} type arguments expected", new Renderer() { @NotNull @Override public String render(@NotNull Integer argument) { @@ -358,17 +358,17 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer } })); - factoryToRenderer.put(UNRESOLVED_IDE_TEMPLATE, new DiagnosticWithParameters1Renderer("Unresolved IDE template: {0}", TO_STRING)); - - factoryToRenderer.put(DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED, new SimpleDiagnosticRenderer("This expression is treated as an argument to the function call on the previous line. Separate it with a semicolon (;) if it is not intended to be an argument.")); - - factoryToRenderer.put(NOT_AN_ANNOTATION_CLASS, new DiagnosticWithParameters1Renderer("{0} is not an annotation class", TO_STRING)); + map.put(UNRESOLVED_IDE_TEMPLATE, new DiagnosticWithParameters1Renderer("Unresolved IDE template: {0}", TO_STRING)); + + map.put(DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED, new SimpleDiagnosticRenderer("This expression is treated as an argument to the function call on the previous line. Separate it with a semicolon (;) if it is not intended to be an argument.")); + + map.put(NOT_AN_ANNOTATION_CLASS, new DiagnosticWithParameters1Renderer("{0} is not an annotation class", TO_STRING)); } @NotNull @Override public String render(@NotNull Diagnostic diagnostic) { - DiagnosticRenderer renderer = factoryToRenderer.get(diagnostic.getFactory()); + DiagnosticRenderer renderer = map.get(diagnostic.getFactory()); if (renderer == null) { throw new IllegalArgumentException("Don't know how to render diagnostic of type " + diagnostic.getFactory().getName()); } From 555f1c9e6f4ab36407e511255774ac9f40a64043 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 13:16:06 +0400 Subject: [PATCH 013/147] Reformatted DefaultDiagnosticRenderer to fit it in screen. --- .../rendering/DefaultDiagnosticRenderer.java | 459 ++++++++++++------ 1 file changed, 300 insertions(+), 159 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java index f5e53b49d43..ce75f36e9c2 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java @@ -41,7 +41,8 @@ import static org.jetbrains.jet.lang.diagnostics.Renderers.*; public class DefaultDiagnosticRenderer implements DiagnosticRenderer { public static final DefaultDiagnosticRenderer INSTANCE = new DefaultDiagnosticRenderer(); - private final Map> map = new HashMap>(); + private final Map> map = + new HashMap>(); private DefaultDiagnosticRenderer() { map.put(EXCEPTION_WHILE_ANALYZING, new DiagnosticWithParameters1Renderer("{0}", new Renderer() { @@ -54,121 +55,178 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer map.put(UNRESOLVED_REFERENCE, new UnresolvedReferenceDiagnosticRenderer("Unresolved reference: ")); - map.put(INVISIBLE_REFERENCE, new DiagnosticWithParameters2Renderer("Cannot access ''{0}'' in ''{1}''", NAME, NAME)); - map.put(INVISIBLE_MEMBER, new DiagnosticWithParameters2Renderer("Cannot access ''{0}'' in ''{1}''", NAME, NAME)); + map.put(INVISIBLE_REFERENCE, + new DiagnosticWithParameters2Renderer("Cannot access ''{0}'' in ''{1}''", + NAME, NAME)); + map.put(INVISIBLE_MEMBER, + new DiagnosticWithParameters2Renderer("Cannot access ''{0}'' in ''{1}''", + NAME, NAME)); map.put(REDECLARATION, new RedeclarationDiagnosticRenderer("Redeclaration: ")); map.put(NAME_SHADOWING, new RedeclarationDiagnosticRenderer("Name shadowed: ")); - map.put(TYPE_MISMATCH, new DiagnosticWithParameters2Renderer("Type mismatch: inferred type is {1} but {0} was expected", RENDER_TYPE, RENDER_TYPE)); - map.put(INCOMPATIBLE_MODIFIERS, new DiagnosticWithParameters1Renderer>("Incompatible modifiers: ''{0}''", new Renderer>() { - @NotNull - @Override - public String render(@NotNull Collection tokens) { - StringBuilder sb = new StringBuilder(); - for (Iterator iterator = tokens.iterator(); iterator.hasNext(); ) { - JetKeywordToken modifier = iterator.next(); - sb.append(modifier.getValue()); - if (iterator.hasNext()) { - sb.append(" "); - } - } - return sb.toString(); - } - } - )); + map.put(TYPE_MISMATCH, + new DiagnosticWithParameters2Renderer("Type mismatch: inferred type is {1} but {0} was expected", + RENDER_TYPE, RENDER_TYPE)); + map.put(INCOMPATIBLE_MODIFIERS, + new DiagnosticWithParameters1Renderer>("Incompatible modifiers: ''{0}''", + new Renderer>() { + @NotNull + @Override + public String render(@NotNull Collection tokens) { + StringBuilder sb = new StringBuilder(); + for (Iterator iterator = + tokens.iterator(); + iterator.hasNext(); ) { + JetKeywordToken modifier = iterator.next(); + sb.append(modifier.getValue()); + if (iterator.hasNext()) { + sb.append(" "); + } + } + return sb.toString(); + } + } + )); map.put(ILLEGAL_MODIFIER, new DiagnosticWithParameters1Renderer("Illegal modifier ''{0}''", TO_STRING)); - map.put(REDUNDANT_MODIFIER, new DiagnosticWithParameters2Renderer("Modifier {0} is redundant because {1} is present", TO_STRING, TO_STRING)); + map.put(REDUNDANT_MODIFIER, + new DiagnosticWithParameters2Renderer("Modifier {0} is redundant because {1} is present", + TO_STRING, TO_STRING)); map.put(ABSTRACT_MODIFIER_IN_TRAIT, new SimpleDiagnosticRenderer("Modifier ''{0}'' is redundant in trait")); map.put(OPEN_MODIFIER_IN_TRAIT, new SimpleDiagnosticRenderer("Modifier ''{0}'' is redundant in trait")); map.put(REDUNDANT_MODIFIER_IN_GETTER, new SimpleDiagnosticRenderer("Visibility modifiers are redundant in getter")); map.put(TRAIT_CAN_NOT_BE_FINAL, new SimpleDiagnosticRenderer("Trait can not be final")); - map.put(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM, new SimpleDiagnosticRenderer("Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly")); // TODO: message + map.put(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM, new SimpleDiagnosticRenderer( + "Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly")); // TODO: message map.put(RETURN_NOT_ALLOWED, new SimpleDiagnosticRenderer("'return' is not allowed here")); - map.put(PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE, new SimpleDiagnosticRenderer("Projections are not allowed for immediate arguments of a supertype")); + map.put(PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE, + new SimpleDiagnosticRenderer("Projections are not allowed for immediate arguments of a supertype")); map.put(LABEL_NAME_CLASH, new SimpleDiagnosticRenderer("There is more than one label with such a name in this scope")); map.put(EXPRESSION_EXPECTED_NAMESPACE_FOUND, new SimpleDiagnosticRenderer("Expression expected, but a namespace name found")); - map.put(CANNOT_IMPORT_FROM_ELEMENT, new DiagnosticWithParameters1Renderer("Cannot import from ''{0}''", NAME)); - map.put(CANNOT_BE_IMPORTED, new DiagnosticWithParameters1Renderer("Cannot import ''{0}'', functions and properties can be imported only from packages", NAME)); + map.put(CANNOT_IMPORT_FROM_ELEMENT, + new DiagnosticWithParameters1Renderer("Cannot import from ''{0}''", NAME)); + map.put(CANNOT_BE_IMPORTED, new DiagnosticWithParameters1Renderer( + "Cannot import ''{0}'', functions and properties can be imported only from packages", NAME)); map.put(USELESS_HIDDEN_IMPORT, new SimpleDiagnosticRenderer("Useless import, it is hidden further")); map.put(USELESS_SIMPLE_IMPORT, new SimpleDiagnosticRenderer("Useless import, does nothing")); - map.put(CANNOT_INFER_PARAMETER_TYPE, new SimpleDiagnosticRenderer("Cannot infer a type for this parameter. To specify it explicitly use the {(p : Type) => ...} notation")); + map.put(CANNOT_INFER_PARAMETER_TYPE, new SimpleDiagnosticRenderer( + "Cannot infer a type for this parameter. To specify it explicitly use the {(p : Type) => ...} notation")); - map.put(NO_BACKING_FIELD_ABSTRACT_PROPERTY, new SimpleDiagnosticRenderer("This property doesn't have a backing field, because it's abstract")); - map.put(NO_BACKING_FIELD_CUSTOM_ACCESSORS, new SimpleDiagnosticRenderer("This property doesn't have a backing field, because it has custom accessors without reference to the backing field")); + map.put(NO_BACKING_FIELD_ABSTRACT_PROPERTY, + new SimpleDiagnosticRenderer("This property doesn't have a backing field, because it's abstract")); + map.put(NO_BACKING_FIELD_CUSTOM_ACCESSORS, new SimpleDiagnosticRenderer( + "This property doesn't have a backing field, because it has custom accessors without reference to the backing field")); map.put(INACCESSIBLE_BACKING_FIELD, new SimpleDiagnosticRenderer("The backing field is not accessible here")); - map.put(NOT_PROPERTY_BACKING_FIELD, new SimpleDiagnosticRenderer("The referenced variable is not a property and doesn't have backing field")); + map.put(NOT_PROPERTY_BACKING_FIELD, + new SimpleDiagnosticRenderer("The referenced variable is not a property and doesn't have backing field")); - map.put(MIXING_NAMED_AND_POSITIONED_ARGUMENTS, new SimpleDiagnosticRenderer("Mixing named and positioned arguments in not allowed")); + map.put(MIXING_NAMED_AND_POSITIONED_ARGUMENTS, + new SimpleDiagnosticRenderer("Mixing named and positioned arguments in not allowed")); map.put(ARGUMENT_PASSED_TWICE, new SimpleDiagnosticRenderer("An argument is already passed for this parameter")); map.put(NAMED_PARAMETER_NOT_FOUND, new UnresolvedReferenceDiagnosticRenderer("Cannot find a parameter with this name: ")); - map.put(VARARG_OUTSIDE_PARENTHESES, new SimpleDiagnosticRenderer("Passing value as a vararg is only allowed inside a parenthesized argument list")); + map.put(VARARG_OUTSIDE_PARENTHESES, + new SimpleDiagnosticRenderer("Passing value as a vararg is only allowed inside a parenthesized argument list")); map.put(NON_VARARG_SPREAD, new SimpleDiagnosticRenderer("The spread operator (*foo) may only be applied in a vararg position")); - map.put(MANY_FUNCTION_LITERAL_ARGUMENTS, new SimpleDiagnosticRenderer("Only one function literal is allowed outside a parenthesized argument list")); - map.put(PROPERTY_WITH_NO_TYPE_NO_INITIALIZER, new SimpleDiagnosticRenderer("This property must either have a type annotation or be initialized")); + map.put(MANY_FUNCTION_LITERAL_ARGUMENTS, + new SimpleDiagnosticRenderer("Only one function literal is allowed outside a parenthesized argument list")); + map.put(PROPERTY_WITH_NO_TYPE_NO_INITIALIZER, + new SimpleDiagnosticRenderer("This property must either have a type annotation or be initialized")); - map.put(ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS, new SimpleDiagnosticRenderer("This property cannot be declared abstract")); - map.put(ABSTRACT_PROPERTY_NOT_IN_CLASS, new SimpleDiagnosticRenderer("A property may be abstract only when defined in a class or trait")); + map.put(ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS, + new SimpleDiagnosticRenderer("This property cannot be declared abstract")); + map.put(ABSTRACT_PROPERTY_NOT_IN_CLASS, + new SimpleDiagnosticRenderer("A property may be abstract only when defined in a class or trait")); map.put(ABSTRACT_PROPERTY_WITH_INITIALIZER, new SimpleDiagnosticRenderer("Property with initializer cannot be abstract")); map.put(ABSTRACT_PROPERTY_WITH_GETTER, new SimpleDiagnosticRenderer("Property with getter implementation cannot be abstract")); map.put(ABSTRACT_PROPERTY_WITH_SETTER, new SimpleDiagnosticRenderer("Property with setter implementation cannot be abstract")); map.put(PACKAGE_MEMBER_CANNOT_BE_PROTECTED, new SimpleDiagnosticRenderer("Package member cannot be protected")); - map.put(GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY, new SimpleDiagnosticRenderer("Getter visibility must be the same as property visibility")); + map.put(GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY, + new SimpleDiagnosticRenderer("Getter visibility must be the same as property visibility")); map.put(BACKING_FIELD_IN_TRAIT, new SimpleDiagnosticRenderer("Property in a trait cannot have a backing field")); map.put(MUST_BE_INITIALIZED, new SimpleDiagnosticRenderer("Property must be initialized")); map.put(MUST_BE_INITIALIZED_OR_BE_ABSTRACT, new SimpleDiagnosticRenderer("Property must be initialized or be abstract")); map.put(PROPERTY_INITIALIZER_IN_TRAIT, new SimpleDiagnosticRenderer("Property initializers are not allowed in traits")); - map.put(PROPERTY_INITIALIZER_NO_BACKING_FIELD, new SimpleDiagnosticRenderer("Initializer is not allowed here because this property has no backing field")); - map.put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, new DiagnosticWithParameters3Renderer("Abstract property {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING)); - map.put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, new DiagnosticWithParameters3Renderer("Abstract function {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING)); - map.put(ABSTRACT_FUNCTION_WITH_BODY, new DiagnosticWithParameters1Renderer("A function {0} with body cannot be abstract", TO_STRING)); - map.put(NON_ABSTRACT_FUNCTION_WITH_NO_BODY, new DiagnosticWithParameters1Renderer("Method {0} without a body must be abstract", TO_STRING)); - map.put(NON_MEMBER_ABSTRACT_FUNCTION, new DiagnosticWithParameters1Renderer("Function {0} is not a class or trait member and cannot be abstract", TO_STRING)); + map.put(PROPERTY_INITIALIZER_NO_BACKING_FIELD, + new SimpleDiagnosticRenderer("Initializer is not allowed here because this property has no backing field")); + map.put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, + new DiagnosticWithParameters3Renderer("Abstract property {0} in non-abstract class {1}", + TO_STRING, TO_STRING, TO_STRING)); + map.put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, + new DiagnosticWithParameters3Renderer("Abstract function {0} in non-abstract class {1}", + TO_STRING, TO_STRING, TO_STRING)); + map.put(ABSTRACT_FUNCTION_WITH_BODY, + new DiagnosticWithParameters1Renderer("A function {0} with body cannot be abstract", TO_STRING)); + map.put(NON_ABSTRACT_FUNCTION_WITH_NO_BODY, + new DiagnosticWithParameters1Renderer("Method {0} without a body must be abstract", TO_STRING)); + map.put(NON_MEMBER_ABSTRACT_FUNCTION, new DiagnosticWithParameters1Renderer( + "Function {0} is not a class or trait member and cannot be abstract", TO_STRING)); - map.put(NON_MEMBER_FUNCTION_NO_BODY, new DiagnosticWithParameters1Renderer("Function {0} must have a body", TO_STRING)); + map.put(NON_MEMBER_FUNCTION_NO_BODY, + new DiagnosticWithParameters1Renderer("Function {0} must have a body", TO_STRING)); map.put(NON_FINAL_MEMBER_IN_FINAL_CLASS, new SimpleDiagnosticRenderer("Non final member in a final class")); map.put(PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE, new SimpleDiagnosticRenderer("Public or protected member should specify a type")); - map.put(PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT, new SimpleDiagnosticRenderer("Projections are not allowed on type arguments of functions and properties")); // TODO : better positioning + map.put(PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT, new SimpleDiagnosticRenderer( + "Projections are not allowed on type arguments of functions and properties")); // TODO : better positioning map.put(SUPERTYPE_NOT_INITIALIZED, new SimpleDiagnosticRenderer("This type has a constructor, and thus must be initialized here")); map.put(SUPERTYPE_NOT_INITIALIZED_DEFAULT, new SimpleDiagnosticRenderer("Constructor invocation should be explicitly specified")); - map.put(SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY, new SimpleDiagnosticRenderer("A secondary constructor may appear only in a class that has a primary constructor")); - map.put(SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST, new SimpleDiagnosticRenderer("Secondary constructors must have an initializer list")); + map.put(SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY, + new SimpleDiagnosticRenderer("A secondary constructor may appear only in a class that has a primary constructor")); + map.put(SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST, + new SimpleDiagnosticRenderer("Secondary constructors must have an initializer list")); map.put(BY_IN_SECONDARY_CONSTRUCTOR, new SimpleDiagnosticRenderer("'by'-clause is only supported for primary constructors")); map.put(INITIALIZER_WITH_NO_ARGUMENTS, new SimpleDiagnosticRenderer("Constructor arguments required")); map.put(MANY_CALLS_TO_THIS, new SimpleDiagnosticRenderer("Only one call to 'this(...)' is allowed")); - map.put(NOTHING_TO_OVERRIDE, new DiagnosticWithParameters1Renderer("{0} overrides nothing", DescriptorRenderer.TEXT)); - map.put(VIRTUAL_MEMBER_HIDDEN, new DiagnosticWithParameters3Renderer("''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); + map.put(NOTHING_TO_OVERRIDE, + new DiagnosticWithParameters1Renderer("{0} overrides nothing", DescriptorRenderer.TEXT)); + map.put(VIRTUAL_MEMBER_HIDDEN, + new DiagnosticWithParameters3Renderer( + "''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", DescriptorRenderer.TEXT, + DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); - map.put(ENUM_ENTRY_SHOULD_BE_INITIALIZED, new DiagnosticWithParameters1Renderer("Missing delegation specifier ''{0}''", NAME)); - map.put(ENUM_ENTRY_ILLEGAL_TYPE, new DiagnosticWithParameters1Renderer("The type constructor of enum entry should be ''{0}''", NAME)); + map.put(ENUM_ENTRY_SHOULD_BE_INITIALIZED, + new DiagnosticWithParameters1Renderer("Missing delegation specifier ''{0}''", NAME)); + map.put(ENUM_ENTRY_ILLEGAL_TYPE, + new DiagnosticWithParameters1Renderer("The type constructor of enum entry should be ''{0}''", NAME)); - map.put(UNINITIALIZED_VARIABLE, new DiagnosticWithParameters1Renderer("Variable ''{0}'' must be initialized", NAME)); - map.put(UNINITIALIZED_PARAMETER, new DiagnosticWithParameters1Renderer("Parameter ''{0}'' is uninitialized here", NAME)); + map.put(UNINITIALIZED_VARIABLE, + new DiagnosticWithParameters1Renderer("Variable ''{0}'' must be initialized", NAME)); + map.put(UNINITIALIZED_PARAMETER, + new DiagnosticWithParameters1Renderer("Parameter ''{0}'' is uninitialized here", NAME)); map.put(UNUSED_VARIABLE, new DiagnosticWithParameters1Renderer("Variable ''{0}'' is never used", NAME)); map.put(UNUSED_PARAMETER, new DiagnosticWithParameters1Renderer("Parameter ''{0}'' is never used", NAME)); - map.put(ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE, new DiagnosticWithParameters1Renderer("Variable ''{0}'' is assigned but never accessed", NAME)); - map.put(VARIABLE_WITH_REDUNDANT_INITIALIZER, new DiagnosticWithParameters1Renderer("Variable ''{0}'' initializer is redundant", NAME)); - map.put(UNUSED_VALUE, new DiagnosticWithParameters2Renderer("The value ''{0}'' assigned to ''{1}'' is never used", ELEMENT_TEXT, TO_STRING)); - map.put(UNUSED_CHANGED_VALUE, new DiagnosticWithParameters1Renderer("The value changed at ''{0}'' is never used", ELEMENT_TEXT)); + map.put(ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE, + new DiagnosticWithParameters1Renderer("Variable ''{0}'' is assigned but never accessed", NAME)); + map.put(VARIABLE_WITH_REDUNDANT_INITIALIZER, + new DiagnosticWithParameters1Renderer("Variable ''{0}'' initializer is redundant", NAME)); + map.put(UNUSED_VALUE, new DiagnosticWithParameters2Renderer( + "The value ''{0}'' assigned to ''{1}'' is never used", ELEMENT_TEXT, TO_STRING)); + map.put(UNUSED_CHANGED_VALUE, + new DiagnosticWithParameters1Renderer("The value changed at ''{0}'' is never used", ELEMENT_TEXT)); map.put(UNUSED_EXPRESSION, new SimpleDiagnosticRenderer("The expression is unused")); - map.put(UNUSED_FUNCTION_LITERAL, new SimpleDiagnosticRenderer("The function literal is unused. If you mean block, you can use 'run { ... }'")); + map.put(UNUSED_FUNCTION_LITERAL, + new SimpleDiagnosticRenderer("The function literal is unused. If you mean block, you can use 'run { ... }'")); map.put(VAL_REASSIGNMENT, new DiagnosticWithParameters1Renderer("Val can not be reassigned", NAME)); - map.put(INITIALIZATION_BEFORE_DECLARATION, new DiagnosticWithParameters1Renderer("Variable cannot be initialized before declaration", NAME)); + map.put(INITIALIZATION_BEFORE_DECLARATION, + new DiagnosticWithParameters1Renderer("Variable cannot be initialized before declaration", NAME)); map.put(VARIABLE_EXPECTED, new SimpleDiagnosticRenderer("Variable expected")); - map.put(INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER, new DiagnosticWithParameters1Renderer("This property has a custom setter, so initialization using backing field required", NAME)); - map.put(INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER, new DiagnosticWithParameters1Renderer("Setter of this property can be overridden, so initialization using backing field required", NAME)); + map.put(INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER, new DiagnosticWithParameters1Renderer( + "This property has a custom setter, so initialization using backing field required", NAME)); + map.put(INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER, new DiagnosticWithParameters1Renderer( + "Setter of this property can be overridden, so initialization using backing field required", NAME)); - map.put(FUNCTION_PARAMETERS_OF_INLINE_FUNCTION, new DiagnosticWithParameters1Renderer("Function parameters of inline function can only be invoked", NAME)); + map.put(FUNCTION_PARAMETERS_OF_INLINE_FUNCTION, + new DiagnosticWithParameters1Renderer("Function parameters of inline function can only be invoked", + NAME)); map.put(UNREACHABLE_CODE, new SimpleDiagnosticRenderer("Unreachable code")); @@ -188,65 +246,102 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer map.put(NO_GET_METHOD, new SimpleDiagnosticRenderer("No get method providing array access")); map.put(NO_SET_METHOD, new SimpleDiagnosticRenderer("No set method providing array access")); - map.put(INC_DEC_SHOULD_NOT_RETURN_UNIT, new SimpleDiagnosticRenderer("Functions inc(), dec() shouldn't return Unit to be used by operators ++, --")); - map.put(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT, new DiagnosticWithParameters2Renderer("Function ''{0}'' should return Unit to be used by corresponding operator ''{1}''", NAME, ELEMENT_TEXT)); + map.put(INC_DEC_SHOULD_NOT_RETURN_UNIT, + new SimpleDiagnosticRenderer("Functions inc(), dec() shouldn't return Unit to be used by operators ++, --")); + map.put(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT, + new DiagnosticWithParameters2Renderer( + "Function ''{0}'' should return Unit to be used by corresponding operator ''{1}''", NAME, ELEMENT_TEXT)); map.put(ASSIGN_OPERATOR_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Assignment operators ambiguity: {0}")); map.put(EQUALS_MISSING, new SimpleDiagnosticRenderer("No method 'equals(Any?) : Boolean' available")); - map.put(ASSIGNMENT_IN_EXPRESSION_CONTEXT, new SimpleDiagnosticRenderer("Assignments are not expressions, and only expressions are allowed in this context")); - map.put(NAMESPACE_IS_NOT_AN_EXPRESSION, new SimpleDiagnosticRenderer("'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')")); - map.put(SUPER_IS_NOT_AN_EXPRESSION, new DiagnosticWithParameters1Renderer("{0} is not an expression, it can only be used on the left-hand side of a dot ('.')", TO_STRING)); + map.put(ASSIGNMENT_IN_EXPRESSION_CONTEXT, + new SimpleDiagnosticRenderer("Assignments are not expressions, and only expressions are allowed in this context")); + map.put(NAMESPACE_IS_NOT_AN_EXPRESSION, + new SimpleDiagnosticRenderer("'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')")); + map.put(SUPER_IS_NOT_AN_EXPRESSION, new DiagnosticWithParameters1Renderer( + "{0} is not an expression, it can only be used on the left-hand side of a dot ('.')", TO_STRING)); map.put(DECLARATION_IN_ILLEGAL_CONTEXT, new SimpleDiagnosticRenderer("Declarations are not allowed in this position")); map.put(SETTER_PARAMETER_WITH_DEFAULT_VALUE, new SimpleDiagnosticRenderer("Setter parameters can not have default values")); map.put(NO_THIS, new SimpleDiagnosticRenderer("'this' is not defined in this context")); map.put(SUPER_NOT_AVAILABLE, new SimpleDiagnosticRenderer("No supertypes are accessible in this context")); - map.put(AMBIGUOUS_SUPER, new SimpleDiagnosticRenderer("Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super'")); + map.put(AMBIGUOUS_SUPER, new SimpleDiagnosticRenderer( + "Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super'")); map.put(ABSTRACT_SUPER_CALL, new SimpleDiagnosticRenderer("Abstract member cannot be accessed directly")); map.put(NOT_A_SUPERTYPE, new SimpleDiagnosticRenderer("Not a supertype")); - map.put(TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER, new SimpleDiagnosticRenderer("Type arguments do not need to be specified in a 'super' qualifier")); + map.put(TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER, + new SimpleDiagnosticRenderer("Type arguments do not need to be specified in a 'super' qualifier")); map.put(USELESS_CAST_STATIC_ASSERT_IS_FINE, new SimpleDiagnosticRenderer("No cast needed, use ':' instead")); map.put(USELESS_CAST, new SimpleDiagnosticRenderer("No cast needed")); map.put(CAST_NEVER_SUCCEEDS, new SimpleDiagnosticRenderer("This cast can never succeed")); - map.put(WRONG_SETTER_PARAMETER_TYPE, new DiagnosticWithParameters1Renderer("Setter parameter type must be equal to the type of the property, i.e. {0}", RENDER_TYPE)); - map.put(WRONG_GETTER_RETURN_TYPE, new DiagnosticWithParameters1Renderer("Getter return type must be equal to the type of the property, i.e. {0}", RENDER_TYPE)); - map.put(NO_CLASS_OBJECT, new DiagnosticWithParameters1Renderer("Please specify constructor invocation; classifier {0} does not have a class object", NAME)); + map.put(WRONG_SETTER_PARAMETER_TYPE, + new DiagnosticWithParameters1Renderer("Setter parameter type must be equal to the type of the property, i.e. {0}", + RENDER_TYPE)); + map.put(WRONG_GETTER_RETURN_TYPE, + new DiagnosticWithParameters1Renderer("Getter return type must be equal to the type of the property, i.e. {0}", + RENDER_TYPE)); + map.put(NO_CLASS_OBJECT, new DiagnosticWithParameters1Renderer( + "Please specify constructor invocation; classifier {0} does not have a class object", NAME)); map.put(NO_GENERICS_IN_SUPERTYPE_SPECIFIER, new SimpleDiagnosticRenderer("Generic arguments of the base type must be specified")); - map.put(HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY, new SimpleDiagnosticRenderer("An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext' property")); - map.put(HAS_NEXT_MISSING, new SimpleDiagnosticRenderer("Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property")); - map.put(HAS_NEXT_FUNCTION_AMBIGUITY, new SimpleDiagnosticRenderer("Function 'iterator().hasNext()' is ambiguous for this expression")); - map.put(HAS_NEXT_MUST_BE_READABLE, new SimpleDiagnosticRenderer("The 'iterator().hasNext' property of the loop range must be readable")); - map.put(HAS_NEXT_PROPERTY_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", RENDER_TYPE)); - map.put(HAS_NEXT_FUNCTION_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", RENDER_TYPE)); + map.put(HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY, + new SimpleDiagnosticRenderer("An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext' property")); + map.put(HAS_NEXT_MISSING, new SimpleDiagnosticRenderer( + "Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property")); + map.put(HAS_NEXT_FUNCTION_AMBIGUITY, + new SimpleDiagnosticRenderer("Function 'iterator().hasNext()' is ambiguous for this expression")); + map.put(HAS_NEXT_MUST_BE_READABLE, + new SimpleDiagnosticRenderer("The 'iterator().hasNext' property of the loop range must be readable")); + map.put(HAS_NEXT_PROPERTY_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer( + "The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", RENDER_TYPE)); + map.put(HAS_NEXT_FUNCTION_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer( + "The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", RENDER_TYPE)); map.put(NEXT_AMBIGUITY, new SimpleDiagnosticRenderer("Function 'iterator().next()' is ambiguous for this expression")); map.put(NEXT_MISSING, new SimpleDiagnosticRenderer("Loop range must have an 'iterator().next()' function")); map.put(ITERATOR_MISSING, new SimpleDiagnosticRenderer("For-loop range must have an iterator() method")); map.put(ITERATOR_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Method 'iterator()' is ambiguous for this expression: {0}")); - map.put(COMPARE_TO_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("compareTo() must return Int, but returns {0}", RENDER_TYPE)); - map.put(CALLEE_NOT_A_FUNCTION, new DiagnosticWithParameters1Renderer("Expecting a function type, but found {0}", RENDER_TYPE)); + map.put(COMPARE_TO_TYPE_MISMATCH, + new DiagnosticWithParameters1Renderer("compareTo() must return Int, but returns {0}", RENDER_TYPE)); + map.put(CALLEE_NOT_A_FUNCTION, + new DiagnosticWithParameters1Renderer("Expecting a function type, but found {0}", RENDER_TYPE)); - map.put(RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY, new SimpleDiagnosticRenderer("Returns are not allowed for functions with expression body. Use block body in '{...}'")); - map.put(NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY, new SimpleDiagnosticRenderer("A 'return' expression required in a function with a block body ('{...}')")); - map.put(RETURN_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("This function must return a value of type {0}", RENDER_TYPE)); + map.put(RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY, + new SimpleDiagnosticRenderer("Returns are not allowed for functions with expression body. Use block body in '{...}'")); + map.put(NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY, + new SimpleDiagnosticRenderer("A 'return' expression required in a function with a block body ('{...}')")); + map.put(RETURN_TYPE_MISMATCH, + new DiagnosticWithParameters1Renderer("This function must return a value of type {0}", RENDER_TYPE)); map.put(EXPECTED_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("Expected a value of type {0}", RENDER_TYPE)); - map.put(ASSIGNMENT_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("Expected a value of type {0}. Assignment operation is not an expression, so it does not return any value", RENDER_TYPE)); - map.put(IMPLICIT_CAST_TO_UNIT_OR_ANY, new DiagnosticWithParameters1Renderer("Type was casted to ''{0}''. Please specify ''{0}'' as expected type, if you mean such cast", RENDER_TYPE)); - map.put(EXPRESSION_EXPECTED, new DiagnosticWithParameters1Renderer("{0} is not an expression, and only expression are allowed here", new Renderer() { - @NotNull - @Override - public String render(@NotNull JetExpression expression) { - String expressionType = expression.toString(); - return expressionType.substring(0, 1) + expressionType.substring(1).toLowerCase(); - } - })); + map.put(ASSIGNMENT_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer( + "Expected a value of type {0}. Assignment operation is not an expression, so it does not return any value", RENDER_TYPE)); + map.put(IMPLICIT_CAST_TO_UNIT_OR_ANY, new DiagnosticWithParameters1Renderer( + "Type was casted to ''{0}''. Please specify ''{0}'' as expected type, if you mean such cast", RENDER_TYPE)); + map.put(EXPRESSION_EXPECTED, + new DiagnosticWithParameters1Renderer("{0} is not an expression, and only expression are allowed here", + new Renderer() { + @NotNull + @Override + public String render(@NotNull JetExpression expression) { + String expressionType = expression.toString(); + return expressionType.substring(0, 1) + + expressionType.substring(1).toLowerCase(); + } + })); - map.put(UPPER_BOUND_VIOLATED, new DiagnosticWithParameters1Renderer("An upper bound {0} is violated", RENDER_TYPE)); // TODO : Message - map.put(FINAL_CLASS_OBJECT_UPPER_BOUND, new DiagnosticWithParameters1Renderer("{0} is a final type, and thus a class object cannot extend it", RENDER_TYPE)); - map.put(FINAL_UPPER_BOUND, new DiagnosticWithParameters1Renderer("{0} is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE)); - map.put(USELESS_ELVIS, new DiagnosticWithParameters1Renderer("Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE)); - map.put(CONFLICTING_UPPER_BOUNDS, new DiagnosticWithParameters1Renderer("Upper bounds of {0} have empty intersection", NAME)); - map.put(CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS, new DiagnosticWithParameters1Renderer("Class object upper bounds of {0} have empty intersection", NAME)); + map.put(UPPER_BOUND_VIOLATED, + new DiagnosticWithParameters1Renderer("An upper bound {0} is violated", RENDER_TYPE)); // TODO : Message + map.put(FINAL_CLASS_OBJECT_UPPER_BOUND, + new DiagnosticWithParameters1Renderer("{0} is a final type, and thus a class object cannot extend it", + RENDER_TYPE)); + map.put(FINAL_UPPER_BOUND, new DiagnosticWithParameters1Renderer( + "{0} is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE)); + map.put(USELESS_ELVIS, new DiagnosticWithParameters1Renderer( + "Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE)); + map.put(CONFLICTING_UPPER_BOUNDS, + new DiagnosticWithParameters1Renderer("Upper bounds of {0} have empty intersection", NAME)); + map.put(CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS, + new DiagnosticWithParameters1Renderer("Class object upper bounds of {0} have empty intersection", + NAME)); map.put(TOO_MANY_ARGUMENTS, new DiagnosticWithParameters1Renderer("Too many arguments for {0}", TO_STRING)); map.put(ERROR_COMPILE_TIME_VALUE, new DiagnosticWithParameters1Renderer("{0}", TO_STRING)); @@ -254,7 +349,8 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer map.put(ELSE_MISPLACED_IN_WHEN, new SimpleDiagnosticRenderer("'else' entry must be the last one in a when-expression")); map.put(NO_ELSE_IN_WHEN, new SimpleDiagnosticRenderer("'when' expression must contain 'else' branch")); - map.put(TYPE_MISMATCH_IN_RANGE, new SimpleDiagnosticRenderer("Type mismatch: incompatible types of range and element checked in it")); + map.put(TYPE_MISMATCH_IN_RANGE, + new SimpleDiagnosticRenderer("Type mismatch: incompatible types of range and element checked in it")); map.put(CYCLIC_INHERITANCE_HIERARCHY, new SimpleDiagnosticRenderer("There's a cycle in the inheritance hierarchy for this type")); map.put(MANY_CLASSES_IN_SUPERTYPE_LIST, new SimpleDiagnosticRenderer("Only one class may appear in a supertype list")); @@ -265,57 +361,82 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer map.put(SUPERTYPE_APPEARS_TWICE, new SimpleDiagnosticRenderer("A supertype appears twice")); map.put(FINAL_SUPERTYPE, new SimpleDiagnosticRenderer("This type is final, so it cannot be inherited from")); - map.put(ILLEGAL_SELECTOR, new DiagnosticWithParameters1Renderer("Expression ''{0}'' cannot be a selector (occur after a dot)", TO_STRING)); + map.put(ILLEGAL_SELECTOR, + new DiagnosticWithParameters1Renderer("Expression ''{0}'' cannot be a selector (occur after a dot)", TO_STRING)); - map.put(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION, new SimpleDiagnosticRenderer("A type annotation is required on a value parameter")); + map.put(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION, + new SimpleDiagnosticRenderer("A type annotation is required on a value parameter")); map.put(BREAK_OR_CONTINUE_OUTSIDE_A_LOOP, new SimpleDiagnosticRenderer("'break' and 'continue' are only allowed inside a loop")); map.put(NOT_A_LOOP_LABEL, new DiagnosticWithParameters1Renderer("The label ''{0}'' does not denote a loop", TO_STRING)); - map.put(NOT_A_RETURN_LABEL, new DiagnosticWithParameters1Renderer("The label ''{0}'' does not reference to a context from which we can return", TO_STRING)); + map.put(NOT_A_RETURN_LABEL, + new DiagnosticWithParameters1Renderer("The label ''{0}'' does not reference to a context from which we can return", + TO_STRING)); - map.put(ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR, new SimpleDiagnosticRenderer("Anonymous initializers are only allowed in the presence of a primary constructor")); + map.put(ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR, + new SimpleDiagnosticRenderer("Anonymous initializers are only allowed in the presence of a primary constructor")); map.put(NULLABLE_SUPERTYPE, new SimpleDiagnosticRenderer("A supertype cannot be nullable")); - map.put(UNSAFE_CALL, new DiagnosticWithParameters1Renderer("Only safe calls (?.) are allowed on a nullable receiver of type {0}", RENDER_TYPE)); + map.put(UNSAFE_CALL, + new DiagnosticWithParameters1Renderer("Only safe calls (?.) are allowed on a nullable receiver of type {0}", + RENDER_TYPE)); map.put(AMBIGUOUS_LABEL, new SimpleDiagnosticRenderer("Ambiguous label")); map.put(UNSUPPORTED, new DiagnosticWithParameters1Renderer("Unsupported [{0}]", TO_STRING)); - map.put(UNNECESSARY_SAFE_CALL, new DiagnosticWithParameters1Renderer("Unnecessary safe call on a non-null receiver of type {0}", RENDER_TYPE)); - map.put(UNNECESSARY_NOT_NULL_ASSERTION, new DiagnosticWithParameters1Renderer("Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", RENDER_TYPE)); - map.put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, new DiagnosticWithParameters2Renderer("{0} does not refer to a type parameter of {1}", new Renderer() { - @NotNull - @Override - public String render(@NotNull JetTypeConstraint typeConstraint) { - //noinspection ConstantConditions - return typeConstraint.getSubjectTypeParameterName().getReferencedName(); - } - }, NAME)); - map.put(AUTOCAST_IMPOSSIBLE, new DiagnosticWithParameters2Renderer("Automatic cast to {0} is impossible, because {1} could have changed since the is-check", RENDER_TYPE, NAME)); - - map.put(TYPE_MISMATCH_IN_FOR_LOOP, new DiagnosticWithParameters2Renderer("The loop iterates over values of type {0} but the parameter is declared to be {1}", RENDER_TYPE, RENDER_TYPE)); - map.put(TYPE_MISMATCH_IN_CONDITION, new DiagnosticWithParameters1Renderer("Condition must be of type Boolean, but was of type {0}", RENDER_TYPE)); - map.put(TYPE_MISMATCH_IN_TUPLE_PATTERN, new DiagnosticWithParameters2Renderer("Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, TO_STRING)); // TODO: message - map.put(TYPE_MISMATCH_IN_BINDING_PATTERN, new DiagnosticWithParameters2Renderer("{0} must be a supertype of {1}. Use 'is' to match against {0}", RENDER_TYPE, RENDER_TYPE)); - map.put(INCOMPATIBLE_TYPES, new DiagnosticWithParameters2Renderer("Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE)); - map.put(EXPECTED_CONDITION, new SimpleDiagnosticRenderer("Expected condition of Boolean type")); - - map.put(CANNOT_CHECK_FOR_ERASED, new DiagnosticWithParameters1Renderer("Cannot check for instance of erased type: {0}", RENDER_TYPE)); - map.put(UNCHECKED_CAST, new DiagnosticWithParameters2Renderer("Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE)); - - map.put(INCONSISTENT_TYPE_PARAMETER_VALUES, new DiagnosticWithParameters3Renderer>("Type parameter {0} of {1} has inconsistent values: {2}", NAME, DescriptorRenderer.TEXT, new Renderer>() { + map.put(UNNECESSARY_SAFE_CALL, + new DiagnosticWithParameters1Renderer("Unnecessary safe call on a non-null receiver of type {0}", RENDER_TYPE)); + map.put(UNNECESSARY_NOT_NULL_ASSERTION, + new DiagnosticWithParameters1Renderer("Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", + RENDER_TYPE)); + map.put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, + new DiagnosticWithParameters2Renderer( + "{0} does not refer to a type parameter of {1}", new Renderer() { @NotNull @Override - public String render(@NotNull Collection types) { - StringBuilder builder = new StringBuilder(); - for (Iterator iterator = types.iterator(); iterator.hasNext(); ) { - JetType jetType = iterator.next(); - builder.append(jetType); - if (iterator.hasNext()) { - builder.append(", "); - } - } - return builder.toString(); + public String render(@NotNull JetTypeConstraint typeConstraint) { + //noinspection ConstantConditions + return typeConstraint.getSubjectTypeParameterName().getReferencedName(); } - })); + }, NAME)); + map.put(AUTOCAST_IMPOSSIBLE, new DiagnosticWithParameters2Renderer( + "Automatic cast to {0} is impossible, because {1} could have changed since the is-check", RENDER_TYPE, NAME)); - map.put(EQUALITY_NOT_APPLICABLE, new DiagnosticWithParameters3Renderer("Operator {0} cannot be applied to {1} and {2}", new Renderer() { + map.put(TYPE_MISMATCH_IN_FOR_LOOP, new DiagnosticWithParameters2Renderer( + "The loop iterates over values of type {0} but the parameter is declared to be {1}", RENDER_TYPE, RENDER_TYPE)); + map.put(TYPE_MISMATCH_IN_CONDITION, + new DiagnosticWithParameters1Renderer("Condition must be of type Boolean, but was of type {0}", RENDER_TYPE)); + map.put(TYPE_MISMATCH_IN_TUPLE_PATTERN, new DiagnosticWithParameters2Renderer( + "Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, TO_STRING)); // TODO: message + map.put(TYPE_MISMATCH_IN_BINDING_PATTERN, + new DiagnosticWithParameters2Renderer("{0} must be a supertype of {1}. Use 'is' to match against {0}", + RENDER_TYPE, RENDER_TYPE)); + map.put(INCOMPATIBLE_TYPES, + new DiagnosticWithParameters2Renderer("Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE)); + map.put(EXPECTED_CONDITION, new SimpleDiagnosticRenderer("Expected condition of Boolean type")); + + map.put(CANNOT_CHECK_FOR_ERASED, + new DiagnosticWithParameters1Renderer("Cannot check for instance of erased type: {0}", RENDER_TYPE)); + map.put(UNCHECKED_CAST, + new DiagnosticWithParameters2Renderer("Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE)); + + map.put(INCONSISTENT_TYPE_PARAMETER_VALUES, + new DiagnosticWithParameters3Renderer>( + "Type parameter {0} of {1} has inconsistent values: {2}", NAME, DescriptorRenderer.TEXT, + new Renderer>() { + @NotNull + @Override + public String render(@NotNull Collection types) { + StringBuilder builder = new StringBuilder(); + for (Iterator iterator = types.iterator(); iterator.hasNext(); ) { + JetType jetType = iterator.next(); + builder.append(jetType); + if (iterator.hasNext()) { + builder.append(", "); + } + } + return builder.toString(); + } + })); + + map.put(EQUALITY_NOT_APPLICABLE, new DiagnosticWithParameters3Renderer( + "Operator {0} cannot be applied to {1} and {2}", new Renderer() { @NotNull @Override public String render(@NotNull JetSimpleNameExpression nameExpression) { @@ -324,43 +445,63 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer } }, TO_STRING, TO_STRING)); - map.put(OVERRIDING_FINAL_MEMBER, new DiagnosticWithParameters2Renderer("''{0}'' in ''{1}'' is final and cannot be overridden", NAME, NAME)); - map.put(CANNOT_WEAKEN_ACCESS_PRIVILEGE, new DiagnosticWithParameters3Renderer("Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME)); - map.put(CANNOT_CHANGE_ACCESS_PRIVILEGE, new DiagnosticWithParameters3Renderer("Cannot change access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME)); + map.put(OVERRIDING_FINAL_MEMBER, new DiagnosticWithParameters2Renderer( + "''{0}'' in ''{1}'' is final and cannot be overridden", NAME, NAME)); + map.put(CANNOT_WEAKEN_ACCESS_PRIVILEGE, + new DiagnosticWithParameters3Renderer( + "Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME)); + map.put(CANNOT_CHANGE_ACCESS_PRIVILEGE, + new DiagnosticWithParameters3Renderer( + "Cannot change access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME)); - map.put(RETURN_TYPE_MISMATCH_ON_OVERRIDE, new DiagnosticWithParameters2Renderer("Return type of {0} is not a subtype of the return type overridden member {1}", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); + map.put(RETURN_TYPE_MISMATCH_ON_OVERRIDE, new DiagnosticWithParameters2Renderer( + "Return type of {0} is not a subtype of the return type overridden member {1}", DescriptorRenderer.TEXT, + DescriptorRenderer.TEXT)); - map.put(VAR_OVERRIDDEN_BY_VAL, new DiagnosticWithParameters2Renderer("Var-property {0} cannot be overridden by val-property {1}", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); + map.put(VAR_OVERRIDDEN_BY_VAL, new DiagnosticWithParameters2Renderer( + "Var-property {0} cannot be overridden by val-property {1}", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); - map.put(ABSTRACT_MEMBER_NOT_IMPLEMENTED, new DiagnosticWithParameters2Renderer("{0} must be declared abstract or implement abstract member {1}", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT)); + map.put(ABSTRACT_MEMBER_NOT_IMPLEMENTED, new DiagnosticWithParameters2Renderer( + "{0} must be declared abstract or implement abstract member {1}", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT)); - map.put(MANY_IMPL_MEMBER_NOT_IMPLEMENTED, new DiagnosticWithParameters2Renderer("{0} must override {1} because it inherits many implementations of it", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT)); + map.put(MANY_IMPL_MEMBER_NOT_IMPLEMENTED, new DiagnosticWithParameters2Renderer( + "{0} must override {1} because it inherits many implementations of it", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT)); - map.put(CONFLICTING_OVERLOADS, new DiagnosticWithParameters2Renderer("{1} is already defined in ''{0}''", DescriptorRenderer.TEXT, TO_STRING)); + map.put(CONFLICTING_OVERLOADS, + new DiagnosticWithParameters2Renderer("{1} is already defined in ''{0}''", + DescriptorRenderer.TEXT, TO_STRING)); - map.put(RESULT_TYPE_MISMATCH, new DiagnosticWithParameters3Renderer("{0} must return {1} but returns {2}", TO_STRING, RENDER_TYPE, RENDER_TYPE)); - map.put(UNSAFE_INFIX_CALL, new DiagnosticWithParameters3Renderer("Infix call corresponds to a dot-qualified call ''{0}.{1}({2})'' which is not allowed on a nullable receiver ''{0}''. Use '?.'-qualified call instead", TO_STRING, TO_STRING, TO_STRING)); + map.put(RESULT_TYPE_MISMATCH, + new DiagnosticWithParameters3Renderer("{0} must return {1} but returns {2}", TO_STRING, + RENDER_TYPE, RENDER_TYPE)); + map.put(UNSAFE_INFIX_CALL, new DiagnosticWithParameters3Renderer( + "Infix call corresponds to a dot-qualified call ''{0}.{1}({2})'' which is not allowed on a nullable receiver ''{0}''. Use '?.'-qualified call instead", + TO_STRING, TO_STRING, TO_STRING)); map.put(OVERLOAD_RESOLUTION_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Overload resolution ambiguity: {0}")); - map.put(NONE_APPLICABLE, new AmbiguousDescriptorDiagnosticRenderer("None of the following functions can be called with the arguments supplied: {0}")); - map.put(NO_VALUE_FOR_PARAMETER, new DiagnosticWithParameters1Renderer("No value passed for parameter {0}", DescriptorRenderer.TEXT)); + map.put(NONE_APPLICABLE, new AmbiguousDescriptorDiagnosticRenderer( + "None of the following functions can be called with the arguments supplied: {0}")); + map.put(NO_VALUE_FOR_PARAMETER, new DiagnosticWithParameters1Renderer("No value passed for parameter {0}", + DescriptorRenderer.TEXT)); map.put(MISSING_RECEIVER, new DiagnosticWithParameters1Renderer("A receiver of type {0} is required", RENDER_TYPE)); map.put(NO_RECEIVER_ADMITTED, new SimpleDiagnosticRenderer("No receiver can be passed to this function or property")); map.put(CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS, new SimpleDiagnosticRenderer("Can not create an instance of an abstract class")); map.put(TYPE_INFERENCE_FAILED, new DiagnosticWithParameters1Renderer("Type inference failed: {0}", TO_STRING)); - map.put(WRONG_NUMBER_OF_TYPE_ARGUMENTS, new DiagnosticWithParameters1Renderer("{0} type arguments expected", new Renderer() { - @NotNull - @Override - public String render(@NotNull Integer argument) { - return argument == 0 ? "No" : argument.toString(); - } - })); + map.put(WRONG_NUMBER_OF_TYPE_ARGUMENTS, + new DiagnosticWithParameters1Renderer("{0} type arguments expected", new Renderer() { + @NotNull + @Override + public String render(@NotNull Integer argument) { + return argument == 0 ? "No" : argument.toString(); + } + })); map.put(UNRESOLVED_IDE_TEMPLATE, new DiagnosticWithParameters1Renderer("Unresolved IDE template: {0}", TO_STRING)); - map.put(DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED, new SimpleDiagnosticRenderer("This expression is treated as an argument to the function call on the previous line. Separate it with a semicolon (;) if it is not intended to be an argument.")); + map.put(DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED, new SimpleDiagnosticRenderer( + "This expression is treated as an argument to the function call on the previous line. Separate it with a semicolon (;) if it is not intended to be an argument.")); map.put(NOT_AN_ANNOTATION_CLASS, new DiagnosticWithParameters1Renderer("{0} is not an annotation class", TO_STRING)); } From 9a917d7127afa628775fd43364f1e7039be6f383 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 13:16:44 +0400 Subject: [PATCH 014/147] Removed unused RedeclarationDiagnosticWithDeferredResolution. --- .../diagnostics/RedeclarationDiagnostic.java | 63 ------------------- 1 file changed, 63 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java index acfa00a21cc..fd0fea2237a 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java @@ -66,69 +66,6 @@ public interface RedeclarationDiagnostic extends Diagnostic { } } - class RedeclarationDiagnosticWithDeferredResolution implements RedeclarationDiagnostic { - - private final DeclarationDescriptor duplicatingDescriptor; - private final BindingContext contextToResolveToDeclaration; - private final RedeclarationDiagnosticFactory factory; - private PsiElement element; - - public RedeclarationDiagnosticWithDeferredResolution(@NotNull DeclarationDescriptor duplicatingDescriptor, @NotNull BindingContext contextToResolveToDeclaration, RedeclarationDiagnosticFactory factory) { - this.duplicatingDescriptor = duplicatingDescriptor; - this.contextToResolveToDeclaration = contextToResolveToDeclaration; - this.factory = factory; - } - - private PsiElement resolve() { - if (element == null) { - element = BindingContextUtils.descriptorToDeclaration(contextToResolveToDeclaration, duplicatingDescriptor); - assert element != null : "No element for descriptor: " + duplicatingDescriptor; - } - return element; - } - - @NotNull - @Override - public PsiElement getPsiElement() { - return resolve(); - } - - @NotNull - @Override - public List getTextRanges() { - return POSITION_REDECLARATION.mark(getPsiElement()); - } - - @NotNull - @Override - public PsiFile getPsiFile() { - return resolve().getContainingFile(); - } - - @NotNull - @Override - public AbstractDiagnosticFactory getFactory() { - return factory; - } - - @Override - public String getName() { - return duplicatingDescriptor.getName(); - } - - @NotNull - @Override - public String getMessage() { - return factory.makeMessage(getName()); - } - - @NotNull - @Override - public Severity getSeverity() { - return factory.severity; - } - } - PositioningStrategy POSITION_REDECLARATION = new PositioningStrategy() { @NotNull @Override From 623cbe7cca70b166daa07ec4a05f41d34e75a8e6 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 13:19:25 +0400 Subject: [PATCH 015/147] Moved 'Renderer' and 'Renderers' to diagnostics.rendering package. --- .../diagnostics/AmbiguousDescriptorDiagnosticFactory.java | 4 ++-- .../jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java | 2 ++ .../jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java | 2 ++ .../jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java | 2 ++ .../src/org/jetbrains/jet/lang/diagnostics/Errors.java | 4 ++-- .../jet/lang/diagnostics/UnusedElementDiagnosticFactory.java | 3 +++ .../lang/diagnostics/rendering/DefaultDiagnosticRenderer.java | 2 +- .../jet/lang/diagnostics/rendering/DiagnosticRenderer.java | 1 - .../rendering/DiagnosticWithParameters1Renderer.java | 1 - .../rendering/DiagnosticWithParameters2Renderer.java | 1 - .../rendering/DiagnosticWithParameters3Renderer.java | 1 - .../jet/lang/diagnostics/{ => rendering}/Renderer.java | 2 +- .../jet/lang/diagnostics/{ => rendering}/Renderers.java | 2 +- .../src/org/jetbrains/jet/resolve/DescriptorRenderer.java | 2 +- 14 files changed, 17 insertions(+), 12 deletions(-) rename compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/{ => rendering}/Renderer.java (93%) rename compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/{ => rendering}/Renderers.java (97%) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java index 4e69661a707..718cd1b4a87 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java @@ -18,8 +18,8 @@ package org.jetbrains.jet.lang.diagnostics; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.descriptors.CallableDescriptor; +import org.jetbrains.jet.lang.diagnostics.rendering.Renderer; import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; import org.jetbrains.jet.resolve.DescriptorRenderer; @@ -37,7 +37,7 @@ public class AmbiguousDescriptorDiagnosticFactory extends DiagnosticFactory1>> AMBIGUOUS_DESCRIPTOR_RENDERER = + private static Renderer>> AMBIGUOUS_DESCRIPTOR_RENDERER = new Renderer>>() { @NotNull @Override diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java index f28aaa14a2b..7a036578666 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java @@ -18,6 +18,8 @@ package org.jetbrains.jet.lang.diagnostics; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.diagnostics.rendering.Renderer; +import org.jetbrains.jet.lang.diagnostics.rendering.Renderers; /** * @author svtk diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java index c63687e00c3..8c376bc9068 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java @@ -18,6 +18,8 @@ package org.jetbrains.jet.lang.diagnostics; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.diagnostics.rendering.Renderer; +import org.jetbrains.jet.lang.diagnostics.rendering.Renderers; /** * @author abreslav diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java index bc945a49bd1..c79a062411a 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java @@ -18,6 +18,8 @@ package org.jetbrains.jet.lang.diagnostics; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.diagnostics.rendering.Renderer; +import org.jetbrains.jet.lang.diagnostics.rendering.Renderers; /** * @author svtk diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java index d50b57581bf..2298db7db08 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java @@ -21,8 +21,8 @@ import com.intellij.psi.PsiElement; import com.intellij.psi.PsiNameIdentifierOwner; import com.intellij.psi.impl.source.tree.LeafPsiElement; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.descriptors.*; +import org.jetbrains.jet.lang.diagnostics.rendering.Renderer; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.calls.inference.SolutionStatus; import org.jetbrains.jet.lang.types.JetType; @@ -37,7 +37,7 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; -import static org.jetbrains.jet.lang.diagnostics.Renderers.*; +import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.*; import static org.jetbrains.jet.lang.diagnostics.Severity.ERROR; import static org.jetbrains.jet.lang.diagnostics.Severity.WARNING; diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnusedElementDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnusedElementDiagnosticFactory.java index 19a297fd9be..82cb5dcdbd1 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnusedElementDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnusedElementDiagnosticFactory.java @@ -17,6 +17,9 @@ package org.jetbrains.jet.lang.diagnostics; import com.intellij.psi.PsiElement; +import org.jetbrains.jet.lang.diagnostics.rendering.Renderer; +import org.jetbrains.jet.lang.diagnostics.rendering.Renderers; + /** * @author svtk */ diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java index ce75f36e9c2..1e1b586397c 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java @@ -32,7 +32,7 @@ import java.util.Iterator; import java.util.Map; import static org.jetbrains.jet.lang.diagnostics.Errors.*; -import static org.jetbrains.jet.lang.diagnostics.Renderers.*; +import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.*; /** * @author Evgeny Gerashchenko diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticRenderer.java index ce843b367b2..324d8941830 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticRenderer.java @@ -18,7 +18,6 @@ package org.jetbrains.jet.lang.diagnostics.rendering; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.diagnostics.Diagnostic; -import org.jetbrains.jet.lang.diagnostics.Renderer; /** * @author Evgeny Gerashchenko diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java index 6031bdeea45..f005f2b343b 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java @@ -18,7 +18,6 @@ package org.jetbrains.jet.lang.diagnostics.rendering; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.diagnostics.DiagnosticWithParameters1; -import org.jetbrains.jet.lang.diagnostics.Renderer; import java.text.MessageFormat; diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters2Renderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters2Renderer.java index 758626891bb..d61591c2ba5 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters2Renderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters2Renderer.java @@ -18,7 +18,6 @@ package org.jetbrains.jet.lang.diagnostics.rendering; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.diagnostics.DiagnosticWithParameters2; -import org.jetbrains.jet.lang.diagnostics.Renderer; import java.text.MessageFormat; diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters3Renderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters3Renderer.java index b18385e6fc8..fbb42366840 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters3Renderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters3Renderer.java @@ -18,7 +18,6 @@ package org.jetbrains.jet.lang.diagnostics.rendering; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.diagnostics.DiagnosticWithParameters3; -import org.jetbrains.jet.lang.diagnostics.Renderer; import java.text.MessageFormat; diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Renderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/Renderer.java similarity index 93% rename from compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Renderer.java rename to compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/Renderer.java index 5884b97e3ff..a5bc6a660c8 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Renderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/Renderer.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.jetbrains.jet.lang.diagnostics; +package org.jetbrains.jet.lang.diagnostics.rendering; import org.jetbrains.annotations.NotNull; diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Renderers.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/Renderers.java similarity index 97% rename from compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Renderers.java rename to compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/Renderers.java index 7136502cfe9..8e42eb60b4e 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Renderers.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/Renderers.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.jetbrains.jet.lang.diagnostics; +package org.jetbrains.jet.lang.diagnostics.rendering; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; diff --git a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java index aa98f28b710..c9cb6cf9cc1 100644 --- a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java @@ -19,7 +19,7 @@ package org.jetbrains.jet.resolve; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.descriptors.*; -import org.jetbrains.jet.lang.diagnostics.Renderer; +import org.jetbrains.jet.lang.diagnostics.rendering.Renderer; import org.jetbrains.jet.lang.resolve.DescriptorUtils; import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverDescriptor; import org.jetbrains.jet.lang.types.JetType; From 4900839c09cb427224316dba6bab0f8fe145c2b4 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 14:03:17 +0400 Subject: [PATCH 016/147] Removed Diagnostic.getMessage() method. --- .../org/jetbrains/jet/checkers/CheckerTestUtil.java | 6 ------ .../jet/lang/diagnostics/AbstractDiagnostic.java | 1 - .../org/jetbrains/jet/lang/diagnostics/Diagnostic.java | 4 ---- .../lang/diagnostics/DiagnosticWithParameters1.java | 6 ------ .../lang/diagnostics/DiagnosticWithParameters2.java | 6 ------ .../lang/diagnostics/DiagnosticWithParameters3.java | 6 ------ .../jet/lang/diagnostics/RedeclarationDiagnostic.java | 10 ---------- .../jet/lang/diagnostics/SimpleDiagnostic.java | 6 ------ .../diagnostics/UnresolvedReferenceDiagnostic.java | 6 ------ 9 files changed, 51 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/checkers/CheckerTestUtil.java b/compiler/frontend/src/org/jetbrains/jet/checkers/CheckerTestUtil.java index 88e8988b2c5..3cf3bedd3f3 100644 --- a/compiler/frontend/src/org/jetbrains/jet/checkers/CheckerTestUtil.java +++ b/compiler/frontend/src/org/jetbrains/jet/checkers/CheckerTestUtil.java @@ -320,12 +320,6 @@ public class CheckerTestUtil { return SyntaxErrorDiagnosticFactory.instance; } - @NotNull - @Override - public String getMessage() { - throw new IllegalStateException(); - } - @NotNull @Override public Severity getSeverity() { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnostic.java index f2a57cfc6bb..33450c87fe2 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnostic.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnostic.java @@ -54,7 +54,6 @@ public abstract class AbstractDiagnostic implements Parame return severity; } - @Override @NotNull public E getPsiElement() { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Diagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Diagnostic.java index 58049c26521..8fcfbf18762 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Diagnostic.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Diagnostic.java @@ -31,10 +31,6 @@ public interface Diagnostic { @NotNull AbstractDiagnosticFactory getFactory(); - @Deprecated - @NotNull - String getMessage(); - @NotNull Severity getSeverity(); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java index 147e8da5c0e..50976c627c4 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters1.java @@ -43,12 +43,6 @@ public class DiagnosticWithParameters1 extends Abstract return (DiagnosticFactory1)super.getFactory(); } - @NotNull - @Override - public String getMessage() { - return getFactory().makeMessage(a); - } - @Override @NotNull public List getTextRanges() { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java index fa7f24140b2..272577dcfba 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters2.java @@ -46,12 +46,6 @@ public class DiagnosticWithParameters2 extends Abstr return (DiagnosticFactory2)super.getFactory(); } - @NotNull - @Override - public String getMessage() { - return getFactory().makeMessage(a, b); - } - @Override @NotNull public List getTextRanges() { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java index ded5998fd7e..febe21d7a5b 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticWithParameters3.java @@ -49,12 +49,6 @@ public class DiagnosticWithParameters3 extends Ab return (DiagnosticFactory3)super.getFactory(); } - @NotNull - @Override - public String getMessage() { - return getFactory().makeMessage(a, b, c); - } - @Override @NotNull public List getTextRanges() { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java index fd0fea2237a..e3080ba18e5 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java @@ -18,13 +18,9 @@ package org.jetbrains.jet.lang.diagnostics; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetNamedDeclaration; -import org.jetbrains.jet.lang.resolve.BindingContext; -import org.jetbrains.jet.lang.resolve.BindingContextUtils; import java.util.List; @@ -48,12 +44,6 @@ public interface RedeclarationDiagnostic extends Diagnostic { return (RedeclarationDiagnosticFactory)super.getFactory(); } - @NotNull - @Override - public String getMessage() { - return getFactory().makeMessage(name); - } - @Override public String getName() { return name; diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/SimpleDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/SimpleDiagnostic.java index ddd531f827d..5dbaf4f5123 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/SimpleDiagnostic.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/SimpleDiagnostic.java @@ -38,12 +38,6 @@ public class SimpleDiagnostic extends AbstractDiagnostic)super.getFactory(); } - @NotNull - @Override - public String getMessage() { - return getFactory().getMessage(); - } - @Override @NotNull public List getTextRanges() { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java index 730c992d305..938cb898250 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java @@ -41,12 +41,6 @@ public class UnresolvedReferenceDiagnostic extends AbstractDiagnostic getTextRanges() { From 2cbac0a5886acd3a215998cbccf43c6e8e05d735 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 14:04:29 +0400 Subject: [PATCH 017/147] Made AbstractDiagnosticFactory actually abstract. --- .../jet/lang/diagnostics/AbstractDiagnosticFactory.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnosticFactory.java index 8d6198a8a58..aeebc9f633f 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AbstractDiagnosticFactory.java @@ -19,7 +19,7 @@ package org.jetbrains.jet.lang.diagnostics; /** * @author abreslav */ -public class AbstractDiagnosticFactory { +public abstract class AbstractDiagnosticFactory { private String name = null; From a5d5eb53e2cbff98db230c5103e296bb2048681e Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 14:21:43 +0400 Subject: [PATCH 018/147] Fixed rendering syntax error diagnostics in CompileSession. --- .../jet/compiler/CompileSession.java | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java index 95b6752337a..458efc9ed12 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java @@ -54,6 +54,8 @@ import java.util.List; * @author yole */ public class CompileSession { + private static final SimpleDiagnosticFactory SYNTAX_ERROR_FACTORY = SimpleDiagnosticFactory.create(Severity.ERROR); + private final JetCoreEnvironment environment; private final MessageCollector messageCollector; private boolean stubs = false; @@ -137,7 +139,7 @@ public class CompileSession { public void visitErrorElement(PsiErrorElement element) { String description = element.getErrorDescription(); String message = StringUtil.isEmpty(description) ? "Syntax error" : description; - Diagnostic diagnostic = SimpleDiagnosticFactory.create(Severity.ERROR, message).on(element); + Diagnostic diagnostic = new SyntaxErrorDiagnostic(element, Severity.ERROR, message); reportDiagnostic(messageCollector, diagnostic); } }); @@ -148,7 +150,14 @@ public class CompileSession { DiagnosticUtils.LineAndColumn lineAndColumn = DiagnosticUtils.getLineAndColumn(diagnostic); VirtualFile virtualFile = diagnostic.getPsiFile().getVirtualFile(); String path = virtualFile == null ? null : virtualFile.getPath(); - collector.report(diagnostic.getSeverity(), DefaultDiagnosticRenderer.INSTANCE.render(diagnostic), path, lineAndColumn.getLine(), lineAndColumn.getColumn()); + String render; + if (diagnostic.getFactory() == SYNTAX_ERROR_FACTORY) { + render = ((SyntaxErrorDiagnostic)diagnostic).message; + } + else { + render = DefaultDiagnosticRenderer.INSTANCE.render(diagnostic); + } + collector.report(diagnostic.getSeverity(), render, path, lineAndColumn.getLine(), lineAndColumn.getColumn()); } @NotNull @@ -176,4 +185,13 @@ public class CompileSession { errorStream.println(messageRenderer.render(Severity.LOGGING, message, null, -1, -1)); } } + + private static class SyntaxErrorDiagnostic extends SimpleDiagnostic { + private String message; + + private SyntaxErrorDiagnostic(@NotNull PsiErrorElement psiElement, @NotNull Severity severity, String message) { + super(psiElement, SYNTAX_ERROR_FACTORY, severity); + this.message = message; + } + } } From 9b50cdfbe3532da63b66f4192bb8133bc2734058 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 14:23:00 +0400 Subject: [PATCH 019/147] Got rid of messages stored in SimpleDiagnosticFactory. --- .../jet/lang/diagnostics/Errors.java | 218 +++++++++--------- .../diagnostics/SimpleDiagnosticFactory.java | 18 +- 2 files changed, 115 insertions(+), 121 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java index 2298db7db08..f9bc2fde7bd 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java @@ -86,17 +86,17 @@ public interface Errors { DiagnosticFactory2 REDUNDANT_MODIFIER = DiagnosticFactory2.create(Severity.WARNING, "Modifier {0} is redundant because {1} is present"); SimpleDiagnosticFactory ABSTRACT_MODIFIER_IN_TRAIT = SimpleDiagnosticFactory - .create(WARNING, "Modifier ''{0}'' is redundant in trait", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + .create(WARNING, PositioningStrategies.POSITION_ABSTRACT_MODIFIER); SimpleDiagnosticFactory OPEN_MODIFIER_IN_TRAIT = SimpleDiagnosticFactory - .create(WARNING, "Modifier ''{0}'' is redundant in trait", PositioningStrategies.positionModifier(JetTokens.OPEN_KEYWORD)); + .create(WARNING, PositioningStrategies.positionModifier(JetTokens.OPEN_KEYWORD)); SimpleDiagnosticFactory - REDUNDANT_MODIFIER_IN_GETTER = SimpleDiagnosticFactory.create(WARNING, "Visibility modifiers are redundant in getter"); - SimpleDiagnosticFactory TRAIT_CAN_NOT_BE_FINAL = SimpleDiagnosticFactory.create(ERROR, "Trait can not be final"); - SimpleDiagnosticFactory TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM = SimpleDiagnosticFactory.create(ERROR, - "Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly"); // TODO: message - SimpleDiagnosticFactory RETURN_NOT_ALLOWED = SimpleDiagnosticFactory.create(ERROR, "'return' is not allowed here"); + REDUNDANT_MODIFIER_IN_GETTER = SimpleDiagnosticFactory.create(WARNING); + SimpleDiagnosticFactory TRAIT_CAN_NOT_BE_FINAL = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM = SimpleDiagnosticFactory.create(ERROR + ); // TODO: message + SimpleDiagnosticFactory RETURN_NOT_ALLOWED = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE = SimpleDiagnosticFactory - .create(ERROR, "Projections are not allowed for immediate arguments of a supertype", + .create(ERROR, new PositioningStrategy() { @NotNull @Override @@ -105,70 +105,70 @@ public interface Errors { } }); SimpleDiagnosticFactory - LABEL_NAME_CLASH = SimpleDiagnosticFactory.create(WARNING, "There is more than one label with such a name in this scope"); + LABEL_NAME_CLASH = SimpleDiagnosticFactory.create(WARNING); SimpleDiagnosticFactory - EXPRESSION_EXPECTED_NAMESPACE_FOUND = SimpleDiagnosticFactory.create(ERROR, "Expression expected, but a namespace name found"); + EXPRESSION_EXPECTED_NAMESPACE_FOUND = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory1 CANNOT_IMPORT_FROM_ELEMENT = DiagnosticFactory1.create(ERROR, "Cannot import from ''{0}''", NAME); DiagnosticFactory1 CANNOT_BE_IMPORTED = DiagnosticFactory1.create(ERROR, "Cannot import ''{0}'', functions and properties can be imported only from packages", NAME); SimpleDiagnosticFactory - USELESS_HIDDEN_IMPORT = SimpleDiagnosticFactory.create(WARNING, "Useless import, it is hidden further"); - SimpleDiagnosticFactory USELESS_SIMPLE_IMPORT = SimpleDiagnosticFactory.create(WARNING, "Useless import, does nothing"); + USELESS_HIDDEN_IMPORT = SimpleDiagnosticFactory.create(WARNING); + SimpleDiagnosticFactory USELESS_SIMPLE_IMPORT = SimpleDiagnosticFactory.create(WARNING); SimpleDiagnosticFactory CANNOT_INFER_PARAMETER_TYPE = SimpleDiagnosticFactory - .create(ERROR, "Cannot infer a type for this parameter. To specify it explicitly use the {(p : Type) => ...} notation"); + .create(ERROR); SimpleDiagnosticFactory NO_BACKING_FIELD_ABSTRACT_PROPERTY = SimpleDiagnosticFactory - .create(ERROR, "This property doesn't have a backing field, because it's abstract"); - SimpleDiagnosticFactory NO_BACKING_FIELD_CUSTOM_ACCESSORS = SimpleDiagnosticFactory.create(ERROR, - "This property doesn't have a backing field, because it has custom accessors without reference to the backing field"); + .create(ERROR); + SimpleDiagnosticFactory NO_BACKING_FIELD_CUSTOM_ACCESSORS = SimpleDiagnosticFactory.create(ERROR + ); SimpleDiagnosticFactory - INACCESSIBLE_BACKING_FIELD = SimpleDiagnosticFactory.create(ERROR, "The backing field is not accessible here"); + INACCESSIBLE_BACKING_FIELD = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory NOT_PROPERTY_BACKING_FIELD = SimpleDiagnosticFactory - .create(ERROR, "The referenced variable is not a property and doesn't have backing field"); + .create(ERROR); SimpleDiagnosticFactory MIXING_NAMED_AND_POSITIONED_ARGUMENTS = SimpleDiagnosticFactory - .create(ERROR, "Mixing named and positioned arguments in not allowed"); + .create(ERROR); SimpleDiagnosticFactory - ARGUMENT_PASSED_TWICE = SimpleDiagnosticFactory.create(ERROR, "An argument is already passed for this parameter"); + ARGUMENT_PASSED_TWICE = SimpleDiagnosticFactory.create(ERROR); UnresolvedReferenceDiagnosticFactory NAMED_PARAMETER_NOT_FOUND = UnresolvedReferenceDiagnosticFactory.create("Cannot find a parameter with this name"); SimpleDiagnosticFactory VARARG_OUTSIDE_PARENTHESES = SimpleDiagnosticFactory - .create(ERROR, "Passing value as a vararg is only allowed inside a parenthesized argument list"); + .create(ERROR); SimpleDiagnosticFactory - NON_VARARG_SPREAD = SimpleDiagnosticFactory.create(ERROR, "The spread operator (*foo) may only be applied in a vararg position"); + NON_VARARG_SPREAD = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory MANY_FUNCTION_LITERAL_ARGUMENTS = SimpleDiagnosticFactory - .create(ERROR, "Only one function literal is allowed outside a parenthesized argument list"); + .create(ERROR); SimpleDiagnosticFactory PROPERTY_WITH_NO_TYPE_NO_INITIALIZER = SimpleDiagnosticFactory - .create(ERROR, "This property must either have a type annotation or be initialized"); + .create(ERROR); SimpleDiagnosticFactory ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS = SimpleDiagnosticFactory - .create(ERROR, "This property cannot be declared abstract", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + .create(ERROR, PositioningStrategies.POSITION_ABSTRACT_MODIFIER); SimpleDiagnosticFactory ABSTRACT_PROPERTY_NOT_IN_CLASS = SimpleDiagnosticFactory - .create(ERROR, "A property may be abstract only when defined in a class or trait", + .create(ERROR, PositioningStrategies.POSITION_ABSTRACT_MODIFIER); SimpleDiagnosticFactory - ABSTRACT_PROPERTY_WITH_INITIALIZER = SimpleDiagnosticFactory.create(ERROR, "Property with initializer cannot be abstract"); + ABSTRACT_PROPERTY_WITH_INITIALIZER = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - ABSTRACT_PROPERTY_WITH_GETTER = SimpleDiagnosticFactory.create(ERROR, "Property with getter implementation cannot be abstract"); + ABSTRACT_PROPERTY_WITH_GETTER = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - ABSTRACT_PROPERTY_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR, "Property with setter implementation cannot be abstract"); + ABSTRACT_PROPERTY_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - PACKAGE_MEMBER_CANNOT_BE_PROTECTED = SimpleDiagnosticFactory.create(ERROR, "Package member cannot be protected"); + PACKAGE_MEMBER_CANNOT_BE_PROTECTED = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY = SimpleDiagnosticFactory - .create(ERROR, "Getter visibility must be the same as property visibility"); + .create(ERROR); SimpleDiagnosticFactory BACKING_FIELD_IN_TRAIT = SimpleDiagnosticFactory - .create(ERROR, "Property in a trait cannot have a backing field", PositioningStrategies.POSITION_NAME_IDENTIFIER); + .create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); SimpleDiagnosticFactory MUST_BE_INITIALIZED = SimpleDiagnosticFactory - .create(ERROR, "Property must be initialized", PositioningStrategies.POSITION_NAME_IDENTIFIER); + .create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); SimpleDiagnosticFactory MUST_BE_INITIALIZED_OR_BE_ABSTRACT = SimpleDiagnosticFactory - .create(ERROR, "Property must be initialized or be abstract", PositioningStrategies.POSITION_NAME_IDENTIFIER); + .create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); SimpleDiagnosticFactory - PROPERTY_INITIALIZER_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR, "Property initializers are not allowed in traits"); + PROPERTY_INITIALIZER_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory PROPERTY_INITIALIZER_NO_BACKING_FIELD = SimpleDiagnosticFactory - .create(ERROR, "Initializer is not allowed here because this property has no backing field"); + .create(ERROR); DiagnosticFactory3 ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS = DiagnosticFactory3.create(ERROR, "Abstract property {0} in non-abstract class {1}", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); DiagnosticFactory3 ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS = DiagnosticFactory3.create(ERROR, "Abstract function {0} in non-abstract class {1}", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); DiagnosticFactory1 ABSTRACT_FUNCTION_WITH_BODY = DiagnosticFactory1.create(ERROR, "A function {0} with body cannot be abstract", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); @@ -177,27 +177,27 @@ public interface Errors { DiagnosticFactory1 NON_MEMBER_FUNCTION_NO_BODY = DiagnosticFactory1.create(ERROR, "Function {0} must have a body", PositioningStrategies.POSITION_NAME_IDENTIFIER); SimpleDiagnosticFactory NON_FINAL_MEMBER_IN_FINAL_CLASS = SimpleDiagnosticFactory - .create(ERROR, "Non final member in a final class", PositioningStrategies.positionModifier(JetTokens.OPEN_KEYWORD)); + .create(ERROR, PositioningStrategies.positionModifier(JetTokens.OPEN_KEYWORD)); SimpleDiagnosticFactory PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE = SimpleDiagnosticFactory - .create(ERROR, "Public or protected member should specify a type", PositioningStrategies.POSITION_NAME_IDENTIFIER); + .create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); SimpleDiagnosticFactory PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT = SimpleDiagnosticFactory - .create(ERROR, "Projections are not allowed on type arguments of functions and properties"); // TODO : better positioning + .create(ERROR); // TODO : better positioning SimpleDiagnosticFactory SUPERTYPE_NOT_INITIALIZED = SimpleDiagnosticFactory - .create(ERROR, "This type has a constructor, and thus must be initialized here"); + .create(ERROR); SimpleDiagnosticFactory SUPERTYPE_NOT_INITIALIZED_DEFAULT = SimpleDiagnosticFactory - .create(ERROR, "Constructor invocation should be explicitly specified"); + .create(ERROR); SimpleDiagnosticFactory SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY = SimpleDiagnosticFactory - .create(ERROR, "A secondary constructor may appear only in a class that has a primary constructor"); + .create(ERROR); SimpleDiagnosticFactory SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST = SimpleDiagnosticFactory - .create(ERROR, "Secondary constructors must have an initializer list"); + .create(ERROR); SimpleDiagnosticFactory - BY_IN_SECONDARY_CONSTRUCTOR = SimpleDiagnosticFactory.create(ERROR, "'by'-clause is only supported for primary constructors"); + BY_IN_SECONDARY_CONSTRUCTOR = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - INITIALIZER_WITH_NO_ARGUMENTS = SimpleDiagnosticFactory.create(ERROR, "Constructor arguments required"); + INITIALIZER_WITH_NO_ARGUMENTS = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - MANY_CALLS_TO_THIS = SimpleDiagnosticFactory.create(ERROR, "Only one call to 'this(...)' is allowed"); + MANY_CALLS_TO_THIS = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory1 NOTHING_TO_OVERRIDE = DiagnosticFactory1.create(ERROR, "{0} overrides nothing", PositioningStrategies.positionModifier(JetTokens.OVERRIDE_KEYWORD), DescriptorRenderer.TEXT); DiagnosticFactory3 VIRTUAL_MEMBER_HIDDEN = DiagnosticFactory3.create(ERROR, "''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", PositioningStrategies.POSITION_NAME_IDENTIFIER, DescriptorRenderer.TEXT, DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); @@ -212,111 +212,111 @@ public interface Errors { DiagnosticFactory1 VARIABLE_WITH_REDUNDANT_INITIALIZER = DiagnosticFactory1.create(WARNING, "Variable ''{0}'' initializer is redundant", NAME); DiagnosticFactory2 UNUSED_VALUE = DiagnosticFactory2.create(WARNING, "The value ''{0}'' assigned to ''{1}'' is never used", ELEMENT_TEXT, TO_STRING); DiagnosticFactory1 UNUSED_CHANGED_VALUE = DiagnosticFactory1.create(WARNING, "The value changed at ''{0}'' is never used", ELEMENT_TEXT); - SimpleDiagnosticFactory UNUSED_EXPRESSION = SimpleDiagnosticFactory.create(WARNING, "The expression is unused"); + SimpleDiagnosticFactory UNUSED_EXPRESSION = SimpleDiagnosticFactory.create(WARNING); SimpleDiagnosticFactory UNUSED_FUNCTION_LITERAL = SimpleDiagnosticFactory - .create(WARNING, "The function literal is unused. If you mean block, you can use 'run { ... }'"); + .create(WARNING); DiagnosticFactory1 VAL_REASSIGNMENT = DiagnosticFactory1.create(ERROR, "Val can not be reassigned", NAME); DiagnosticFactory1 INITIALIZATION_BEFORE_DECLARATION = DiagnosticFactory1.create(ERROR, "Variable cannot be initialized before declaration", NAME); - SimpleDiagnosticFactory VARIABLE_EXPECTED = SimpleDiagnosticFactory.create(ERROR, "Variable expected"); + SimpleDiagnosticFactory VARIABLE_EXPECTED = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory1 INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER = DiagnosticFactory1.create(ERROR, "This property has a custom setter, so initialization using backing field required", NAME); DiagnosticFactory1 INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER = DiagnosticFactory1.create(ERROR, "Setter of this property can be overridden, so initialization using backing field required", NAME); DiagnosticFactory1 FUNCTION_PARAMETERS_OF_INLINE_FUNCTION = DiagnosticFactory1.create(ERROR, "Function parameters of inline function can only be invoked", NAME); - SimpleDiagnosticFactory UNREACHABLE_CODE = SimpleDiagnosticFactory.create(ERROR, "Unreachable code"); + SimpleDiagnosticFactory UNREACHABLE_CODE = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - MANY_CLASS_OBJECTS = SimpleDiagnosticFactory.create(ERROR, "Only one class object is allowed per class"); + MANY_CLASS_OBJECTS = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - CLASS_OBJECT_NOT_ALLOWED = SimpleDiagnosticFactory.create(ERROR, "A class object is not allowed here"); + CLASS_OBJECT_NOT_ALLOWED = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - DELEGATION_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR, "Traits cannot use delegation"); + DELEGATION_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - DELEGATION_NOT_TO_TRAIT = SimpleDiagnosticFactory.create(ERROR, "Only traits can be delegated to"); - SimpleDiagnosticFactory NO_CONSTRUCTOR = SimpleDiagnosticFactory.create(ERROR, "This class does not have a constructor"); - SimpleDiagnosticFactory NOT_A_CLASS = SimpleDiagnosticFactory.create(ERROR, "Not a class"); + DELEGATION_NOT_TO_TRAIT = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory NO_CONSTRUCTOR = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory NOT_A_CLASS = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - ILLEGAL_ESCAPE_SEQUENCE = SimpleDiagnosticFactory.create(ERROR, "Illegal escape sequence"); + ILLEGAL_ESCAPE_SEQUENCE = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - LOCAL_EXTENSION_PROPERTY = SimpleDiagnosticFactory.create(ERROR, "Local extension properties are not allowed"); + LOCAL_EXTENSION_PROPERTY = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - LOCAL_VARIABLE_WITH_GETTER = SimpleDiagnosticFactory.create(ERROR, "Local variables are not allowed to have getters"); + LOCAL_VARIABLE_WITH_GETTER = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - LOCAL_VARIABLE_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR, "Local variables are not allowed to have setters"); + LOCAL_VARIABLE_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - VAL_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR, "A 'val'-property cannot have a setter"); + VAL_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory NO_GET_METHOD = SimpleDiagnosticFactory - .create(ERROR, "No get method providing array access", PositioningStrategies.POSITION_ARRAY_ACCESS); + .create(ERROR, PositioningStrategies.POSITION_ARRAY_ACCESS); SimpleDiagnosticFactory NO_SET_METHOD = SimpleDiagnosticFactory - .create(ERROR, "No set method providing array access", PositioningStrategies.POSITION_ARRAY_ACCESS); + .create(ERROR, PositioningStrategies.POSITION_ARRAY_ACCESS); SimpleDiagnosticFactory INC_DEC_SHOULD_NOT_RETURN_UNIT = SimpleDiagnosticFactory - .create(ERROR, "Functions inc(), dec() shouldn't return Unit to be used by operators ++, --"); + .create(ERROR); DiagnosticFactory2 ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT = DiagnosticFactory2.create(ERROR, "Function ''{0}'' should return Unit to be used by corresponding operator ''{1}''", NAME, ELEMENT_TEXT); AmbiguousDescriptorDiagnosticFactory ASSIGN_OPERATOR_AMBIGUITY = AmbiguousDescriptorDiagnosticFactory.create("Assignment operators ambiguity: {0}"); SimpleDiagnosticFactory - EQUALS_MISSING = SimpleDiagnosticFactory.create(ERROR, "No method 'equals(Any?) : Boolean' available"); + EQUALS_MISSING = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory ASSIGNMENT_IN_EXPRESSION_CONTEXT = SimpleDiagnosticFactory - .create(ERROR, "Assignments are not expressions, and only expressions are allowed in this context"); + .create(ERROR); SimpleDiagnosticFactory NAMESPACE_IS_NOT_AN_EXPRESSION = SimpleDiagnosticFactory - .create(ERROR, "'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')"); + .create(ERROR); DiagnosticFactory1 SUPER_IS_NOT_AN_EXPRESSION = DiagnosticFactory1.create(ERROR, "{0} is not an expression, it can only be used on the left-hand side of a dot ('.')"); SimpleDiagnosticFactory - DECLARATION_IN_ILLEGAL_CONTEXT = SimpleDiagnosticFactory.create(ERROR, "Declarations are not allowed in this position"); + DECLARATION_IN_ILLEGAL_CONTEXT = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - SETTER_PARAMETER_WITH_DEFAULT_VALUE = SimpleDiagnosticFactory.create(ERROR, "Setter parameters can not have default values"); - SimpleDiagnosticFactory NO_THIS = SimpleDiagnosticFactory.create(ERROR, "'this' is not defined in this context"); + SETTER_PARAMETER_WITH_DEFAULT_VALUE = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory NO_THIS = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - SUPER_NOT_AVAILABLE = SimpleDiagnosticFactory.create(ERROR, "No supertypes are accessible in this context"); + SUPER_NOT_AVAILABLE = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory AMBIGUOUS_SUPER = SimpleDiagnosticFactory - .create(ERROR, "Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super'"); + .create(ERROR); SimpleDiagnosticFactory - ABSTRACT_SUPER_CALL = SimpleDiagnosticFactory.create(ERROR, "Abstract member cannot be accessed directly"); - SimpleDiagnosticFactory NOT_A_SUPERTYPE = SimpleDiagnosticFactory.create(ERROR, "Not a supertype"); + ABSTRACT_SUPER_CALL = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory NOT_A_SUPERTYPE = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER = SimpleDiagnosticFactory - .create(WARNING, "Type arguments do not need to be specified in a 'super' qualifier"); + .create(WARNING); SimpleDiagnosticFactory - USELESS_CAST_STATIC_ASSERT_IS_FINE = SimpleDiagnosticFactory.create(WARNING, "No cast needed, use ':' instead"); - SimpleDiagnosticFactory USELESS_CAST = SimpleDiagnosticFactory.create(WARNING, "No cast needed"); + USELESS_CAST_STATIC_ASSERT_IS_FINE = SimpleDiagnosticFactory.create(WARNING); + SimpleDiagnosticFactory USELESS_CAST = SimpleDiagnosticFactory.create(WARNING); SimpleDiagnosticFactory - CAST_NEVER_SUCCEEDS = SimpleDiagnosticFactory.create(WARNING, "This cast can never succeed"); + CAST_NEVER_SUCCEEDS = SimpleDiagnosticFactory.create(WARNING); DiagnosticFactory1 WRONG_SETTER_PARAMETER_TYPE = DiagnosticFactory1.create(ERROR, "Setter parameter type must be equal to the type of the property, i.e. {0}", RENDER_TYPE);//, DiagnosticParameters.TYPE); DiagnosticFactory1 WRONG_GETTER_RETURN_TYPE = DiagnosticFactory1.create(ERROR, "Getter return type must be equal to the type of the property, i.e. {0}", RENDER_TYPE);//, DiagnosticParameters.TYPE); DiagnosticFactory1 NO_CLASS_OBJECT = DiagnosticFactory1.create(ERROR, "Please specify constructor invocation; classifier {0} does not have a class object", NAME); SimpleDiagnosticFactory NO_GENERICS_IN_SUPERTYPE_SPECIFIER = SimpleDiagnosticFactory - .create(ERROR, "Generic arguments of the base type must be specified"); + .create(ERROR); SimpleDiagnosticFactory HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY = SimpleDiagnosticFactory - .create(ERROR, "An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext' property"); + .create(ERROR); SimpleDiagnosticFactory HAS_NEXT_MISSING = SimpleDiagnosticFactory - .create(ERROR, "Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property"); + .create(ERROR); SimpleDiagnosticFactory HAS_NEXT_FUNCTION_AMBIGUITY = SimpleDiagnosticFactory - .create(ERROR, "Function 'iterator().hasNext()' is ambiguous for this expression"); + .create(ERROR); SimpleDiagnosticFactory HAS_NEXT_MUST_BE_READABLE = SimpleDiagnosticFactory - .create(ERROR, "The 'iterator().hasNext' property of the loop range must be readable"); + .create(ERROR); DiagnosticFactory1 HAS_NEXT_PROPERTY_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", RENDER_TYPE); DiagnosticFactory1 HAS_NEXT_FUNCTION_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", RENDER_TYPE); SimpleDiagnosticFactory - NEXT_AMBIGUITY = SimpleDiagnosticFactory.create(ERROR, "Function 'iterator().next()' is ambiguous for this expression"); + NEXT_AMBIGUITY = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - NEXT_MISSING = SimpleDiagnosticFactory.create(ERROR, "Loop range must have an 'iterator().next()' function"); + NEXT_MISSING = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - ITERATOR_MISSING = SimpleDiagnosticFactory.create(ERROR, "For-loop range must have an iterator() method"); + ITERATOR_MISSING = SimpleDiagnosticFactory.create(ERROR); AmbiguousDescriptorDiagnosticFactory ITERATOR_AMBIGUITY = AmbiguousDescriptorDiagnosticFactory.create("Method 'iterator()' is ambiguous for this expression: {0}"); DiagnosticFactory1 COMPARE_TO_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "compareTo() must return Int, but returns {0}", RENDER_TYPE); DiagnosticFactory1 CALLEE_NOT_A_FUNCTION = DiagnosticFactory1.create(ERROR, "Expecting a function type, but found {0}", RENDER_TYPE); SimpleDiagnosticFactory RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY = SimpleDiagnosticFactory - .create(ERROR, "Returns are not allowed for functions with expression body. Use block body in '{...}'"); + .create(ERROR); SimpleDiagnosticFactory NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY = SimpleDiagnosticFactory - .create(ERROR, "A 'return' expression required in a function with a block body ('{...}')", + .create(ERROR, new PositioningStrategy() { @NotNull @Override @@ -353,7 +353,7 @@ public interface Errors { DiagnosticFactory1 ERROR_COMPILE_TIME_VALUE = DiagnosticFactory1.create(ERROR, "{0}"); SimpleDiagnosticFactory ELSE_MISPLACED_IN_WHEN = SimpleDiagnosticFactory.create( - ERROR, "'else' entry must be the last one in a when-expression", new PositioningStrategy() { + ERROR, new PositioningStrategy() { @NotNull @Override public List mark(@NotNull JetWhenEntry entry) { @@ -364,7 +364,7 @@ public interface Errors { }); SimpleDiagnosticFactory - NO_ELSE_IN_WHEN = new SimpleDiagnosticFactory(ERROR, "'when' expression must contain 'else' branch", new PositioningStrategy() { + NO_ELSE_IN_WHEN = new SimpleDiagnosticFactory(ERROR, new PositioningStrategy() { @NotNull @Override public List mark(@NotNull JetWhenExpression element) { @@ -372,7 +372,8 @@ public interface Errors { return markElement(element.getWhenKeywordElement()); } }); - SimpleDiagnosticFactory TYPE_MISMATCH_IN_RANGE = new SimpleDiagnosticFactory(ERROR, "Type mismatch: incompatible types of range and element checked in it", new PositioningStrategy() { + SimpleDiagnosticFactory TYPE_MISMATCH_IN_RANGE = new SimpleDiagnosticFactory(ERROR, + new PositioningStrategy() { @NotNull @Override public List mark(@NotNull JetWhenConditionInRange condition) { @@ -380,34 +381,34 @@ public interface Errors { } }); SimpleDiagnosticFactory CYCLIC_INHERITANCE_HIERARCHY = SimpleDiagnosticFactory - .create(ERROR, "There's a cycle in the inheritance hierarchy for this type"); + .create(ERROR); SimpleDiagnosticFactory - MANY_CLASSES_IN_SUPERTYPE_LIST = SimpleDiagnosticFactory.create(ERROR, "Only one class may appear in a supertype list"); + MANY_CLASSES_IN_SUPERTYPE_LIST = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - SUPERTYPE_NOT_A_CLASS_OR_TRAIT = SimpleDiagnosticFactory.create(ERROR, "Only classes and traits may serve as supertypes"); + SUPERTYPE_NOT_A_CLASS_OR_TRAIT = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - SUPERTYPE_INITIALIZED_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR, "Traits cannot initialize supertypes"); - SimpleDiagnosticFactory CONSTRUCTOR_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR, "A trait may not have a constructor"); + SUPERTYPE_INITIALIZED_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory CONSTRUCTOR_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED = SimpleDiagnosticFactory.create(WARNING, "Secondary constructors are not supported"); - SimpleDiagnosticFactory SUPERTYPE_APPEARS_TWICE = SimpleDiagnosticFactory.create(ERROR, "A supertype appears twice"); + SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED = SimpleDiagnosticFactory.create(WARNING); + SimpleDiagnosticFactory SUPERTYPE_APPEARS_TWICE = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory - FINAL_SUPERTYPE = SimpleDiagnosticFactory.create(ERROR, "This type is final, so it cannot be inherited from"); + FINAL_SUPERTYPE = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory1 ILLEGAL_SELECTOR = DiagnosticFactory1.create(ERROR, "Expression ''{0}'' cannot be a selector (occur after a dot)"); SimpleDiagnosticFactory VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION = SimpleDiagnosticFactory - .create(ERROR, "A type annotation is required on a value parameter"); + .create(ERROR); SimpleDiagnosticFactory BREAK_OR_CONTINUE_OUTSIDE_A_LOOP = SimpleDiagnosticFactory - .create(ERROR, "'break' and 'continue' are only allowed inside a loop"); + .create(ERROR); DiagnosticFactory1 NOT_A_LOOP_LABEL = DiagnosticFactory1.create(ERROR, "The label ''{0}'' does not denote a loop"); DiagnosticFactory1 NOT_A_RETURN_LABEL = DiagnosticFactory1.create(ERROR, "The label ''{0}'' does not reference to a context from which we can return"); SimpleDiagnosticFactory ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR = SimpleDiagnosticFactory - .create(ERROR, "Anonymous initializers are only allowed in the presence of a primary constructor"); + .create(ERROR); SimpleDiagnosticFactory NULLABLE_SUPERTYPE = SimpleDiagnosticFactory - .create(ERROR, "A supertype cannot be nullable", new PositioningStrategy() { + .create(ERROR, new PositioningStrategy() { @NotNull @Override public List mark(@NotNull JetNullableType element) { @@ -415,7 +416,7 @@ public interface Errors { } }); DiagnosticFactory1 UNSAFE_CALL = DiagnosticFactory1.create(ERROR, "Only safe calls (?.) are allowed on a nullable receiver of type {0}", RENDER_TYPE); - SimpleDiagnosticFactory AMBIGUOUS_LABEL = SimpleDiagnosticFactory.create(ERROR, "Ambiguous label"); + SimpleDiagnosticFactory AMBIGUOUS_LABEL = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory1 UNSUPPORTED = DiagnosticFactory1.create(ERROR, "Unsupported [{0}]"); DiagnosticFactory1 UNNECESSARY_SAFE_CALL = DiagnosticFactory1.create(WARNING, "Unnecessary safe call on a non-null receiver of type {0}", RENDER_TYPE); DiagnosticFactory1 UNNECESSARY_NOT_NULL_ASSERTION = DiagnosticFactory1.create(WARNING, "Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", RENDER_TYPE); @@ -435,7 +436,7 @@ public interface Errors { DiagnosticFactory2 TYPE_MISMATCH_IN_BINDING_PATTERN = DiagnosticFactory2.create(ERROR, "{0} must be a supertype of {1}. Use 'is' to match against {0}", RENDER_TYPE, RENDER_TYPE); DiagnosticFactory2 INCOMPATIBLE_TYPES = DiagnosticFactory2.create(ERROR, "Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE); SimpleDiagnosticFactory - EXPECTED_CONDITION = SimpleDiagnosticFactory.create(ERROR, "Expected condition of Boolean type"); + EXPECTED_CONDITION = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory1 CANNOT_CHECK_FOR_ERASED = DiagnosticFactory1.create(ERROR, "Cannot check for instance of erased type: {0}", RENDER_TYPE); DiagnosticFactory2 UNCHECKED_CAST = DiagnosticFactory2.create(WARNING, "Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE); @@ -528,10 +529,10 @@ public interface Errors { DiagnosticFactory1 NO_VALUE_FOR_PARAMETER = DiagnosticFactory1.create(ERROR, "No value passed for parameter {0}", DescriptorRenderer.TEXT); DiagnosticFactory1 MISSING_RECEIVER = DiagnosticFactory1.create(ERROR, "A receiver of type {0} is required", RENDER_TYPE); SimpleDiagnosticFactory - NO_RECEIVER_ADMITTED = SimpleDiagnosticFactory.create(ERROR, "No receiver can be passed to this function or property"); + NO_RECEIVER_ADMITTED = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS = SimpleDiagnosticFactory - .create(ERROR, "Can not create an instance of an abstract class"); + .create(ERROR); DiagnosticFactory1 TYPE_INFERENCE_FAILED = DiagnosticFactory1.create(ERROR, "Type inference failed: {0}"); DiagnosticFactory1 WRONG_NUMBER_OF_TYPE_ARGUMENTS = DiagnosticFactory1.create(ERROR, "{0} type arguments expected", new Renderer() { @NotNull @@ -544,8 +545,7 @@ public interface Errors { DiagnosticFactory1 UNRESOLVED_IDE_TEMPLATE = DiagnosticFactory1.create(ERROR, "Unresolved IDE template: {0}"); SimpleDiagnosticFactory DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED = SimpleDiagnosticFactory - .create(WARNING, "This expression is treated as an argument to the function call on the previous line. " + - "Separate it with a semicolon (;) if it is not intended to be an argument."); + .create(WARNING); DiagnosticFactory1 NOT_AN_ANNOTATION_CLASS = DiagnosticFactory1.create(ERROR, "{0} is not an annotation class"); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/SimpleDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/SimpleDiagnosticFactory.java index 4a97b1e460b..8b24829e98f 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/SimpleDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/SimpleDiagnosticFactory.java @@ -23,27 +23,21 @@ import org.jetbrains.annotations.NotNull; * @author svtk */ public class SimpleDiagnosticFactory extends DiagnosticFactoryWithPsiElement { - protected final String message; - protected SimpleDiagnosticFactory(Severity severity, String message, PositioningStrategy positioningStrategy) { + protected SimpleDiagnosticFactory(Severity severity, PositioningStrategy positioningStrategy) { super(severity, positioningStrategy); - this.message = message; } - public static SimpleDiagnosticFactory create(Severity severity, String message) { - return create(severity, message, PositioningStrategies.DEFAULT); + public static SimpleDiagnosticFactory create(Severity severity) { + return create(severity, PositioningStrategies.DEFAULT); } - public static SimpleDiagnosticFactory create(Severity severity, String message, PositioningStrategy positioningStrategy) { - return new SimpleDiagnosticFactory(severity, message, positioningStrategy); - } - - String getMessage() { - return message; + public static SimpleDiagnosticFactory create(Severity severity, PositioningStrategy positioningStrategy) { + return new SimpleDiagnosticFactory(severity, positioningStrategy); } @NotNull - public ParametrizedDiagnostic on(@NotNull E element) { + public SimpleDiagnostic on(@NotNull E element) { return new SimpleDiagnostic(element, this, severity); } } \ No newline at end of file From d64d2c857974f715f07a2f6f73a1200904dab551 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 14:27:33 +0400 Subject: [PATCH 020/147] Removed fields and methods for rendering error messages in DiagnosticFactoryWithMessageFormat and its subclasses. --- .../lang/diagnostics/DiagnosticFactory1.java | 11 --------- .../lang/diagnostics/DiagnosticFactory2.java | 16 ------------- .../lang/diagnostics/DiagnosticFactory3.java | 23 +------------------ .../DiagnosticFactoryWithMessageFormat.java | 9 +------- 4 files changed, 2 insertions(+), 57 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java index 7a036578666..4ac2abcdd3a 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java @@ -25,16 +25,6 @@ import org.jetbrains.jet.lang.diagnostics.rendering.Renderers; * @author svtk */ public class DiagnosticFactory1 extends DiagnosticFactoryWithMessageFormat { - private final Renderer renderer; - - protected String makeMessage(@NotNull A argument) { - return messageFormat.format(new Object[]{makeMessageFor(argument)}); - } - - protected String makeMessageFor(@NotNull A argument) { - return renderer.render(argument); - } - @NotNull public ParametrizedDiagnostic on(@NotNull E element, @NotNull A argument) { return new DiagnosticWithParameters1(element, argument, this, severity); @@ -42,7 +32,6 @@ public class DiagnosticFactory1 extends DiagnosticFacto protected DiagnosticFactory1(Severity severity, String message, PositioningStrategy positioningStrategy, Renderer renderer) { super(severity, message, positioningStrategy); - this.renderer = renderer; } public static DiagnosticFactory1 create(Severity severity, String message, PositioningStrategy positioningStrategy, Renderer renderer) { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java index 8c376bc9068..48726a9c574 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java @@ -25,20 +25,6 @@ import org.jetbrains.jet.lang.diagnostics.rendering.Renderers; * @author abreslav */ public class DiagnosticFactory2 extends DiagnosticFactoryWithMessageFormat { - private final Renderer rendererForA; - private final Renderer rendererForB; - - protected String makeMessage(@NotNull A a, @NotNull B b) { - return messageFormat.format(new Object[] {makeMessageForA(a), makeMessageForB(b)}); - } - - private String makeMessageForA(@NotNull A a) { - return rendererForA.render(a); - } - - private String makeMessageForB(@NotNull B b) { - return rendererForB.render(b); - } @NotNull public ParametrizedDiagnostic on(@NotNull E element, @NotNull A a, @NotNull B b) { @@ -48,8 +34,6 @@ public class DiagnosticFactory2 extends DiagnosticFa private DiagnosticFactory2(Severity severity, String message, PositioningStrategy positioningStrategy, Renderer rendererForA, Renderer rendererForB) { super(severity, message, positioningStrategy); - this.rendererForA = rendererForA; - this.rendererForB = rendererForB; } public static DiagnosticFactory2 create(Severity severity, String messageStub, PositioningStrategy positioningStrategy, Renderer rendererForA, Renderer rendererForB) { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java index c79a062411a..d38b9da9d42 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java @@ -25,15 +25,9 @@ import org.jetbrains.jet.lang.diagnostics.rendering.Renderers; * @author svtk */ public class DiagnosticFactory3 extends DiagnosticFactoryWithMessageFormat { - private final Renderer rendererForA; - private final Renderer rendererForB; - private final Renderer rendererForC; - + protected DiagnosticFactory3(Severity severity, String messageStub, PositioningStrategy positioningStrategy, Renderer rendererForA, Renderer rendererForB, Renderer rendererForC) { super(severity, messageStub, positioningStrategy); - this.rendererForA = rendererForA; - this.rendererForB = rendererForB; - this.rendererForC = rendererForC; } public static DiagnosticFactory3 create(Severity severity, String messageStub) { @@ -52,21 +46,6 @@ public class DiagnosticFactory3 extends Diagnosti return new DiagnosticFactory3(severity, messageStub, positioningStrategy, rendererForA, rendererForB, rendererForC); } - protected String makeMessage(@NotNull A a, @NotNull B b, @NotNull C c) { - return messageFormat.format(new Object[]{makeMessageForA(a), makeMessageForB(b), makeMessageForC(c)}); - } - - private String makeMessageForA(@NotNull A a) { - return rendererForA.render(a); - } - - private String makeMessageForB(@NotNull B b) { - return rendererForB.render(b); - } - - private String makeMessageForC(@NotNull C c) { - return rendererForC.render(c); - } @NotNull public ParametrizedDiagnostic on(@NotNull E element, @NotNull A a, @NotNull B b, @NotNull C c) { return new DiagnosticWithParameters3(element, a, b, c, this, severity); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactoryWithMessageFormat.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactoryWithMessageFormat.java index 9478ec5191d..95e64d22979 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactoryWithMessageFormat.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactoryWithMessageFormat.java @@ -24,14 +24,7 @@ import java.text.MessageFormat; * @author abreslav */ public abstract class DiagnosticFactoryWithMessageFormat extends DiagnosticFactoryWithPsiElement { - protected final MessageFormat messageFormat; - - public DiagnosticFactoryWithMessageFormat(Severity severity, String message) { - this(severity, message, PositioningStrategies.DEFAULT); - } - - public DiagnosticFactoryWithMessageFormat(Severity severity, String message, PositioningStrategy positioningStrategy) { + protected DiagnosticFactoryWithMessageFormat(Severity severity, String message, PositioningStrategy positioningStrategy) { super(severity, positioningStrategy); - this.messageFormat = new MessageFormat(message); } } From 11e4caaee3c0f8c0ec8f259afd16914b23dfdeef Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 14:34:53 +0400 Subject: [PATCH 021/147] Removed message formats and renderers passed to constructor parameters of DiagnosticFactoryWithMessageFormat and its subclasses. --- .../AmbiguousDescriptorDiagnosticFactory.java | 2 +- .../lang/diagnostics/DiagnosticFactory1.java | 22 +- .../lang/diagnostics/DiagnosticFactory2.java | 23 +- .../lang/diagnostics/DiagnosticFactory3.java | 22 +- .../DiagnosticFactoryWithMessageFormat.java | 2 +- .../jet/lang/diagnostics/Errors.java | 252 +++++++----------- .../UnusedElementDiagnosticFactory.java | 2 +- 7 files changed, 120 insertions(+), 205 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java index 718cd1b4a87..06eecc981a9 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java @@ -34,7 +34,7 @@ public class AmbiguousDescriptorDiagnosticFactory extends DiagnosticFactory1>> AMBIGUOUS_DESCRIPTOR_RENDERER = diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java index 4ac2abcdd3a..db3b08e5965 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java @@ -18,8 +18,6 @@ package org.jetbrains.jet.lang.diagnostics; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.lang.diagnostics.rendering.Renderer; -import org.jetbrains.jet.lang.diagnostics.rendering.Renderers; /** * @author svtk @@ -30,23 +28,15 @@ public class DiagnosticFactory1 extends DiagnosticFacto return new DiagnosticWithParameters1(element, argument, this, severity); } - protected DiagnosticFactory1(Severity severity, String message, PositioningStrategy positioningStrategy, Renderer renderer) { - super(severity, message, positioningStrategy); + protected DiagnosticFactory1(Severity severity, PositioningStrategy positioningStrategy) { + super(severity, positioningStrategy); } - public static DiagnosticFactory1 create(Severity severity, String message, PositioningStrategy positioningStrategy, Renderer renderer) { - return new DiagnosticFactory1(severity, message, positioningStrategy, renderer); + public static DiagnosticFactory1 create(Severity severity, PositioningStrategy positioningStrategy) { + return new DiagnosticFactory1(severity, positioningStrategy); } - public static DiagnosticFactory1 create(Severity severity, String message, PositioningStrategy positioningStrategy) { - return create(severity, message, positioningStrategy, Renderers.TO_STRING); - } - - public static DiagnosticFactory1 create(Severity severity, String message, Renderer renderer) { - return create(severity, message, PositioningStrategies.DEFAULT, renderer); - } - - public static DiagnosticFactory1 create(Severity severity, String message) { - return create(severity, message, PositioningStrategies.DEFAULT, Renderers.TO_STRING); + public static DiagnosticFactory1 create(Severity severity) { + return create(severity, PositioningStrategies.DEFAULT); } } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java index 48726a9c574..049b8824d38 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java @@ -18,8 +18,6 @@ package org.jetbrains.jet.lang.diagnostics; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.lang.diagnostics.rendering.Renderer; -import org.jetbrains.jet.lang.diagnostics.rendering.Renderers; /** * @author abreslav @@ -31,25 +29,16 @@ public class DiagnosticFactory2 extends DiagnosticFa return new DiagnosticWithParameters2(element, a, b, this, severity); } - - private DiagnosticFactory2(Severity severity, String message, PositioningStrategy positioningStrategy, Renderer rendererForA, Renderer rendererForB) { - super(severity, message, positioningStrategy); + private DiagnosticFactory2(Severity severity, PositioningStrategy positioningStrategy) { + super(severity, positioningStrategy); } - public static DiagnosticFactory2 create(Severity severity, String messageStub, PositioningStrategy positioningStrategy, Renderer rendererForA, Renderer rendererForB) { - return new DiagnosticFactory2(severity, messageStub, positioningStrategy, rendererForA, rendererForB); + public static DiagnosticFactory2 create(Severity severity, PositioningStrategy positioningStrategy) { + return new DiagnosticFactory2(severity, positioningStrategy); } - public static DiagnosticFactory2 create(Severity severity, String messageStub, PositioningStrategy positioningStrategy) { - return new DiagnosticFactory2(severity, messageStub, positioningStrategy, Renderers.TO_STRING, Renderers.TO_STRING); - } - - public static DiagnosticFactory2 create(Severity severity, String messageStub, Renderer rendererForA, Renderer rendererForB) { - return new DiagnosticFactory2(severity, messageStub, PositioningStrategies.DEFAULT, rendererForA, rendererForB); - } - - public static DiagnosticFactory2 create(Severity severity, String messageStub) { - return new DiagnosticFactory2(severity, messageStub, PositioningStrategies.DEFAULT, Renderers.TO_STRING, Renderers.TO_STRING); + public static DiagnosticFactory2 create(Severity severity) { + return new DiagnosticFactory2(severity, PositioningStrategies.DEFAULT); } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java index d38b9da9d42..678bb9b3dbf 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java @@ -18,32 +18,22 @@ package org.jetbrains.jet.lang.diagnostics; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.lang.diagnostics.rendering.Renderer; -import org.jetbrains.jet.lang.diagnostics.rendering.Renderers; /** * @author svtk */ public class DiagnosticFactory3 extends DiagnosticFactoryWithMessageFormat { - protected DiagnosticFactory3(Severity severity, String messageStub, PositioningStrategy positioningStrategy, Renderer rendererForA, Renderer rendererForB, Renderer rendererForC) { - super(severity, messageStub, positioningStrategy); + protected DiagnosticFactory3(Severity severity, PositioningStrategy positioningStrategy) { + super(severity, positioningStrategy); } - public static DiagnosticFactory3 create(Severity severity, String messageStub) { - return create(severity, messageStub, PositioningStrategies.DEFAULT); + public static DiagnosticFactory3 create(Severity severity) { + return create(severity, PositioningStrategies.DEFAULT); } - public static DiagnosticFactory3 create(Severity severity, String messageStub, PositioningStrategy positioningStrategy) { - return create(severity, messageStub, positioningStrategy, Renderers.TO_STRING, Renderers.TO_STRING, Renderers.TO_STRING); - } - - public static DiagnosticFactory3 create(Severity severity, String messageStub, Renderer rendererForA, Renderer rendererForB, Renderer rendererForC) { - return create(severity, messageStub, PositioningStrategies.DEFAULT, rendererForA, rendererForB, rendererForC); - } - - public static DiagnosticFactory3 create(Severity severity, String messageStub, PositioningStrategy positioningStrategy, Renderer rendererForA, Renderer rendererForB, Renderer rendererForC) { - return new DiagnosticFactory3(severity, messageStub, positioningStrategy, rendererForA, rendererForB, rendererForC); + public static DiagnosticFactory3 create(Severity severity, PositioningStrategy positioningStrategy) { + return new DiagnosticFactory3(severity, positioningStrategy); } @NotNull diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactoryWithMessageFormat.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactoryWithMessageFormat.java index 95e64d22979..a04b6d59dce 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactoryWithMessageFormat.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactoryWithMessageFormat.java @@ -24,7 +24,7 @@ import java.text.MessageFormat; * @author abreslav */ public abstract class DiagnosticFactoryWithMessageFormat extends DiagnosticFactoryWithPsiElement { - protected DiagnosticFactoryWithMessageFormat(Severity severity, String message, PositioningStrategy positioningStrategy) { + protected DiagnosticFactoryWithMessageFormat(Severity severity, PositioningStrategy positioningStrategy) { super(severity, positioningStrategy); } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java index f9bc2fde7bd..f382ed1fc54 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java @@ -22,19 +22,16 @@ import com.intellij.psi.PsiNameIdentifierOwner; import com.intellij.psi.impl.source.tree.LeafPsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.descriptors.*; -import org.jetbrains.jet.lang.diagnostics.rendering.Renderer; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.calls.inference.SolutionStatus; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lexer.JetKeywordToken; import org.jetbrains.jet.lexer.JetTokens; -import org.jetbrains.jet.resolve.DescriptorRenderer; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.Collections; -import java.util.Iterator; import java.util.List; import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.*; @@ -46,45 +43,25 @@ import static org.jetbrains.jet.lang.diagnostics.Severity.WARNING; */ public interface Errors { - DiagnosticFactory1 EXCEPTION_WHILE_ANALYZING = DiagnosticFactory1.create(ERROR, "{0}", new Renderer() { - @NotNull - @Override - public String render(@NotNull Throwable e) { - return e.getClass().getSimpleName() + ": " + e.getMessage(); - } - }); + DiagnosticFactory1 EXCEPTION_WHILE_ANALYZING = DiagnosticFactory1.create(ERROR); UnresolvedReferenceDiagnosticFactory UNRESOLVED_REFERENCE = UnresolvedReferenceDiagnosticFactory.create("Unresolved reference"); //Elements with "INVISIBLE_REFERENCE" error are marked as unresolved, unlike elements with "INVISIBLE_MEMBER" error - DiagnosticFactory2 INVISIBLE_REFERENCE = DiagnosticFactory2.create(ERROR, "Cannot access ''{0}'' in ''{1}''", NAME, NAME); - DiagnosticFactory2 INVISIBLE_MEMBER = DiagnosticFactory2.create(ERROR, "Cannot access ''{0}'' in ''{1}''", NAME, NAME); + DiagnosticFactory2 INVISIBLE_REFERENCE = DiagnosticFactory2.create(ERROR); + DiagnosticFactory2 INVISIBLE_MEMBER = DiagnosticFactory2.create(ERROR); RedeclarationDiagnosticFactory REDECLARATION = RedeclarationDiagnosticFactory.REDECLARATION; RedeclarationDiagnosticFactory NAME_SHADOWING = RedeclarationDiagnosticFactory.NAME_SHADOWING; - DiagnosticFactory2 TYPE_MISMATCH = DiagnosticFactory2.create(ERROR, "Type mismatch: inferred type is {1} but {0} was expected", - RENDER_TYPE, RENDER_TYPE); + DiagnosticFactory2 TYPE_MISMATCH = DiagnosticFactory2.create(ERROR + ); DiagnosticFactory1> INCOMPATIBLE_MODIFIERS = - DiagnosticFactory1.create(ERROR, "Incompatible modifiers: ''{0}''", - new Renderer>() { - @NotNull - @Override - public String render(@NotNull Collection element) { - StringBuilder sb = new StringBuilder(); - for (Iterator iterator = element.iterator(); iterator.hasNext(); ) { - JetKeywordToken modifier = iterator.next(); - sb.append(modifier.getValue()); - if (iterator.hasNext()) { - sb.append(" "); - } - } - return sb.toString(); - } - }); - DiagnosticFactory1 ILLEGAL_MODIFIER = DiagnosticFactory1.create(ERROR, "Illegal modifier ''{0}''"); + DiagnosticFactory1.create(ERROR + ); + DiagnosticFactory1 ILLEGAL_MODIFIER = DiagnosticFactory1.create(ERROR); - DiagnosticFactory2 REDUNDANT_MODIFIER = DiagnosticFactory2.create(Severity.WARNING, "Modifier {0} is redundant because {1} is present"); + DiagnosticFactory2 REDUNDANT_MODIFIER = DiagnosticFactory2.create(Severity.WARNING); SimpleDiagnosticFactory ABSTRACT_MODIFIER_IN_TRAIT = SimpleDiagnosticFactory .create(WARNING, PositioningStrategies.POSITION_ABSTRACT_MODIFIER); SimpleDiagnosticFactory OPEN_MODIFIER_IN_TRAIT = SimpleDiagnosticFactory @@ -109,8 +86,8 @@ public interface Errors { SimpleDiagnosticFactory EXPRESSION_EXPECTED_NAMESPACE_FOUND = SimpleDiagnosticFactory.create(ERROR); - DiagnosticFactory1 CANNOT_IMPORT_FROM_ELEMENT = DiagnosticFactory1.create(ERROR, "Cannot import from ''{0}''", NAME); - DiagnosticFactory1 CANNOT_BE_IMPORTED = DiagnosticFactory1.create(ERROR, "Cannot import ''{0}'', functions and properties can be imported only from packages", NAME); + DiagnosticFactory1 CANNOT_IMPORT_FROM_ELEMENT = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 CANNOT_BE_IMPORTED = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory USELESS_HIDDEN_IMPORT = SimpleDiagnosticFactory.create(WARNING); SimpleDiagnosticFactory USELESS_SIMPLE_IMPORT = SimpleDiagnosticFactory.create(WARNING); @@ -169,13 +146,19 @@ public interface Errors { PROPERTY_INITIALIZER_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory PROPERTY_INITIALIZER_NO_BACKING_FIELD = SimpleDiagnosticFactory .create(ERROR); - DiagnosticFactory3 ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS = DiagnosticFactory3.create(ERROR, "Abstract property {0} in non-abstract class {1}", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); - DiagnosticFactory3 ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS = DiagnosticFactory3.create(ERROR, "Abstract function {0} in non-abstract class {1}", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); - DiagnosticFactory1 ABSTRACT_FUNCTION_WITH_BODY = DiagnosticFactory1.create(ERROR, "A function {0} with body cannot be abstract", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); - DiagnosticFactory1 NON_ABSTRACT_FUNCTION_WITH_NO_BODY = DiagnosticFactory1.create(ERROR, "Method {0} without a body must be abstract", PositioningStrategies.POSITION_NAME_IDENTIFIER); - DiagnosticFactory1 NON_MEMBER_ABSTRACT_FUNCTION = DiagnosticFactory1.create(ERROR, "Function {0} is not a class or trait member and cannot be abstract", PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + DiagnosticFactory3 ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS = DiagnosticFactory3.create(ERROR, + PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + DiagnosticFactory3 ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS = DiagnosticFactory3.create(ERROR, + PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + DiagnosticFactory1 ABSTRACT_FUNCTION_WITH_BODY = DiagnosticFactory1.create(ERROR, + PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + DiagnosticFactory1 NON_ABSTRACT_FUNCTION_WITH_NO_BODY = DiagnosticFactory1.create(ERROR, + PositioningStrategies.POSITION_NAME_IDENTIFIER); + DiagnosticFactory1 NON_MEMBER_ABSTRACT_FUNCTION = DiagnosticFactory1.create(ERROR, + PositioningStrategies.POSITION_ABSTRACT_MODIFIER); - DiagnosticFactory1 NON_MEMBER_FUNCTION_NO_BODY = DiagnosticFactory1.create(ERROR, "Function {0} must have a body", PositioningStrategies.POSITION_NAME_IDENTIFIER); + DiagnosticFactory1 NON_MEMBER_FUNCTION_NO_BODY = DiagnosticFactory1.create(ERROR, + PositioningStrategies.POSITION_NAME_IDENTIFIER); SimpleDiagnosticFactory NON_FINAL_MEMBER_IN_FINAL_CLASS = SimpleDiagnosticFactory .create(ERROR, PositioningStrategies.positionModifier(JetTokens.OPEN_KEYWORD)); @@ -198,32 +181,34 @@ public interface Errors { INITIALIZER_WITH_NO_ARGUMENTS = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory MANY_CALLS_TO_THIS = SimpleDiagnosticFactory.create(ERROR); - DiagnosticFactory1 NOTHING_TO_OVERRIDE = DiagnosticFactory1.create(ERROR, "{0} overrides nothing", PositioningStrategies.positionModifier(JetTokens.OVERRIDE_KEYWORD), DescriptorRenderer.TEXT); - DiagnosticFactory3 VIRTUAL_MEMBER_HIDDEN = DiagnosticFactory3.create(ERROR, "''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", PositioningStrategies.POSITION_NAME_IDENTIFIER, DescriptorRenderer.TEXT, DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); + DiagnosticFactory1 NOTHING_TO_OVERRIDE = DiagnosticFactory1.create(ERROR, + PositioningStrategies.positionModifier(JetTokens.OVERRIDE_KEYWORD)); + DiagnosticFactory3 VIRTUAL_MEMBER_HIDDEN = DiagnosticFactory3.create(ERROR, + PositioningStrategies.POSITION_NAME_IDENTIFIER); - DiagnosticFactory1 ENUM_ENTRY_SHOULD_BE_INITIALIZED = DiagnosticFactory1.create(ERROR, "Missing delegation specifier ''{0}''", PositioningStrategies.POSITION_NAME_IDENTIFIER, NAME); - DiagnosticFactory1 ENUM_ENTRY_ILLEGAL_TYPE = DiagnosticFactory1.create(ERROR, "The type constructor of enum entry should be ''{0}''", NAME); + DiagnosticFactory1 ENUM_ENTRY_SHOULD_BE_INITIALIZED = DiagnosticFactory1.create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); + DiagnosticFactory1 ENUM_ENTRY_ILLEGAL_TYPE = DiagnosticFactory1.create(ERROR); - DiagnosticFactory1 UNINITIALIZED_VARIABLE = DiagnosticFactory1.create(ERROR, "Variable ''{0}'' must be initialized", NAME); - DiagnosticFactory1 UNINITIALIZED_PARAMETER = DiagnosticFactory1.create(ERROR, "Parameter ''{0}'' is uninitialized here", NAME); + DiagnosticFactory1 UNINITIALIZED_VARIABLE = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 UNINITIALIZED_PARAMETER = DiagnosticFactory1.create(ERROR); UnusedElementDiagnosticFactory UNUSED_VARIABLE = UnusedElementDiagnosticFactory.create(WARNING, "Variable ''{0}'' is never used", PositioningStrategies.POSITION_NAME_IDENTIFIER, NAME); UnusedElementDiagnosticFactory UNUSED_PARAMETER = UnusedElementDiagnosticFactory.create(WARNING, "Parameter ''{0}'' is never used", PositioningStrategies.POSITION_NAME_IDENTIFIER, NAME); UnusedElementDiagnosticFactory ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE = UnusedElementDiagnosticFactory.create(WARNING, "Variable ''{0}'' is assigned but never accessed", PositioningStrategies.POSITION_NAME_IDENTIFIER, NAME); - DiagnosticFactory1 VARIABLE_WITH_REDUNDANT_INITIALIZER = DiagnosticFactory1.create(WARNING, "Variable ''{0}'' initializer is redundant", NAME); - DiagnosticFactory2 UNUSED_VALUE = DiagnosticFactory2.create(WARNING, "The value ''{0}'' assigned to ''{1}'' is never used", ELEMENT_TEXT, TO_STRING); - DiagnosticFactory1 UNUSED_CHANGED_VALUE = DiagnosticFactory1.create(WARNING, "The value changed at ''{0}'' is never used", ELEMENT_TEXT); + DiagnosticFactory1 VARIABLE_WITH_REDUNDANT_INITIALIZER = DiagnosticFactory1.create(WARNING); + DiagnosticFactory2 UNUSED_VALUE = DiagnosticFactory2.create(WARNING); + DiagnosticFactory1 UNUSED_CHANGED_VALUE = DiagnosticFactory1.create(WARNING); SimpleDiagnosticFactory UNUSED_EXPRESSION = SimpleDiagnosticFactory.create(WARNING); SimpleDiagnosticFactory UNUSED_FUNCTION_LITERAL = SimpleDiagnosticFactory .create(WARNING); - DiagnosticFactory1 VAL_REASSIGNMENT = DiagnosticFactory1.create(ERROR, "Val can not be reassigned", NAME); - DiagnosticFactory1 INITIALIZATION_BEFORE_DECLARATION = DiagnosticFactory1.create(ERROR, "Variable cannot be initialized before declaration", NAME); + DiagnosticFactory1 VAL_REASSIGNMENT = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 INITIALIZATION_BEFORE_DECLARATION = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory VARIABLE_EXPECTED = SimpleDiagnosticFactory.create(ERROR); - DiagnosticFactory1 INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER = DiagnosticFactory1.create(ERROR, "This property has a custom setter, so initialization using backing field required", NAME); - DiagnosticFactory1 INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER = DiagnosticFactory1.create(ERROR, "Setter of this property can be overridden, so initialization using backing field required", NAME); + DiagnosticFactory1 INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER = DiagnosticFactory1.create(ERROR); - DiagnosticFactory1 FUNCTION_PARAMETERS_OF_INLINE_FUNCTION = DiagnosticFactory1.create(ERROR, "Function parameters of inline function can only be invoked", NAME); + DiagnosticFactory1 FUNCTION_PARAMETERS_OF_INLINE_FUNCTION = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory UNREACHABLE_CODE = SimpleDiagnosticFactory.create(ERROR); @@ -257,7 +242,7 @@ public interface Errors { SimpleDiagnosticFactory INC_DEC_SHOULD_NOT_RETURN_UNIT = SimpleDiagnosticFactory .create(ERROR); DiagnosticFactory2 ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT = - DiagnosticFactory2.create(ERROR, "Function ''{0}'' should return Unit to be used by corresponding operator ''{1}''", NAME, ELEMENT_TEXT); + DiagnosticFactory2.create(ERROR); AmbiguousDescriptorDiagnosticFactory ASSIGN_OPERATOR_AMBIGUITY = AmbiguousDescriptorDiagnosticFactory.create("Assignment operators ambiguity: {0}"); SimpleDiagnosticFactory @@ -266,7 +251,7 @@ public interface Errors { .create(ERROR); SimpleDiagnosticFactory NAMESPACE_IS_NOT_AN_EXPRESSION = SimpleDiagnosticFactory .create(ERROR); - DiagnosticFactory1 SUPER_IS_NOT_AN_EXPRESSION = DiagnosticFactory1.create(ERROR, "{0} is not an expression, it can only be used on the left-hand side of a dot ('.')"); + DiagnosticFactory1 SUPER_IS_NOT_AN_EXPRESSION = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory DECLARATION_IN_ILLEGAL_CONTEXT = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory @@ -286,9 +271,9 @@ public interface Errors { SimpleDiagnosticFactory USELESS_CAST = SimpleDiagnosticFactory.create(WARNING); SimpleDiagnosticFactory CAST_NEVER_SUCCEEDS = SimpleDiagnosticFactory.create(WARNING); - DiagnosticFactory1 WRONG_SETTER_PARAMETER_TYPE = DiagnosticFactory1.create(ERROR, "Setter parameter type must be equal to the type of the property, i.e. {0}", RENDER_TYPE);//, DiagnosticParameters.TYPE); - DiagnosticFactory1 WRONG_GETTER_RETURN_TYPE = DiagnosticFactory1.create(ERROR, "Getter return type must be equal to the type of the property, i.e. {0}", RENDER_TYPE);//, DiagnosticParameters.TYPE); - DiagnosticFactory1 NO_CLASS_OBJECT = DiagnosticFactory1.create(ERROR, "Please specify constructor invocation; classifier {0} does not have a class object", NAME); + DiagnosticFactory1 WRONG_SETTER_PARAMETER_TYPE = DiagnosticFactory1.create(ERROR);//, DiagnosticParameters.TYPE); + DiagnosticFactory1 WRONG_GETTER_RETURN_TYPE = DiagnosticFactory1.create(ERROR);//, DiagnosticParameters.TYPE); + DiagnosticFactory1 NO_CLASS_OBJECT = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory NO_GENERICS_IN_SUPERTYPE_SPECIFIER = SimpleDiagnosticFactory .create(ERROR); @@ -300,8 +285,8 @@ public interface Errors { .create(ERROR); SimpleDiagnosticFactory HAS_NEXT_MUST_BE_READABLE = SimpleDiagnosticFactory .create(ERROR); - DiagnosticFactory1 HAS_NEXT_PROPERTY_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", RENDER_TYPE); - DiagnosticFactory1 HAS_NEXT_FUNCTION_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", RENDER_TYPE); + DiagnosticFactory1 HAS_NEXT_PROPERTY_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 HAS_NEXT_FUNCTION_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory NEXT_AMBIGUITY = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory @@ -310,8 +295,8 @@ public interface Errors { ITERATOR_MISSING = SimpleDiagnosticFactory.create(ERROR); AmbiguousDescriptorDiagnosticFactory ITERATOR_AMBIGUITY = AmbiguousDescriptorDiagnosticFactory.create("Method 'iterator()' is ambiguous for this expression: {0}"); - DiagnosticFactory1 COMPARE_TO_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "compareTo() must return Int, but returns {0}", RENDER_TYPE); - DiagnosticFactory1 CALLEE_NOT_A_FUNCTION = DiagnosticFactory1.create(ERROR, "Expecting a function type, but found {0}", RENDER_TYPE); + DiagnosticFactory1 COMPARE_TO_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 CALLEE_NOT_A_FUNCTION = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY = SimpleDiagnosticFactory .create(ERROR); @@ -329,28 +314,21 @@ public interface Errors { return markRange(lastBracketRange); } }); - DiagnosticFactory1 RETURN_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "This function must return a value of type {0}", RENDER_TYPE); - DiagnosticFactory1 EXPECTED_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "Expected a value of type {0}", RENDER_TYPE); - DiagnosticFactory1 ASSIGNMENT_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR, "Expected a value of type {0}. Assignment operation is not an expression, so it does not return any value", RENDER_TYPE); - DiagnosticFactory1 IMPLICIT_CAST_TO_UNIT_OR_ANY = DiagnosticFactory1.create(WARNING, "Type was casted to ''{0}''. Please specify ''{0}'' as expected type, if you mean such cast", RENDER_TYPE); - DiagnosticFactory1 EXPRESSION_EXPECTED = DiagnosticFactory1.create(ERROR, "{0} is not an expression, and only expression are allowed here", new Renderer() { - @NotNull - @Override - public String render(@NotNull JetExpression expression) { - String expressionType = expression.toString(); - return expressionType.substring(0, 1) + expressionType.substring(1).toLowerCase(); - } - }); + DiagnosticFactory1 RETURN_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 EXPECTED_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 ASSIGNMENT_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 IMPLICIT_CAST_TO_UNIT_OR_ANY = DiagnosticFactory1.create(WARNING); + DiagnosticFactory1 EXPRESSION_EXPECTED = DiagnosticFactory1.create(ERROR); - DiagnosticFactory1 UPPER_BOUND_VIOLATED = DiagnosticFactory1.create(ERROR, "An upper bound {0} is violated", RENDER_TYPE); // TODO : Message - DiagnosticFactory1 FINAL_CLASS_OBJECT_UPPER_BOUND = DiagnosticFactory1.create(ERROR, "{0} is a final type, and thus a class object cannot extend it", RENDER_TYPE); - DiagnosticFactory1 FINAL_UPPER_BOUND = DiagnosticFactory1.create(WARNING, "{0} is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE); - DiagnosticFactory1 USELESS_ELVIS = DiagnosticFactory1.create(WARNING, "Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE); - DiagnosticFactory1 CONFLICTING_UPPER_BOUNDS = DiagnosticFactory1.create(ERROR, "Upper bounds of {0} have empty intersection", NAME); - DiagnosticFactory1 CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS = DiagnosticFactory1.create(ERROR, "Class object upper bounds of {0} have empty intersection", NAME); + DiagnosticFactory1 UPPER_BOUND_VIOLATED = DiagnosticFactory1.create(ERROR); // TODO : Message + DiagnosticFactory1 FINAL_CLASS_OBJECT_UPPER_BOUND = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 FINAL_UPPER_BOUND = DiagnosticFactory1.create(WARNING); + DiagnosticFactory1 USELESS_ELVIS = DiagnosticFactory1.create(WARNING); + DiagnosticFactory1 CONFLICTING_UPPER_BOUNDS = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS = DiagnosticFactory1.create(ERROR); - DiagnosticFactory1 TOO_MANY_ARGUMENTS = DiagnosticFactory1.create(ERROR, "Too many arguments for {0}"); - DiagnosticFactory1 ERROR_COMPILE_TIME_VALUE = DiagnosticFactory1.create(ERROR, "{0}"); + DiagnosticFactory1 TOO_MANY_ARGUMENTS = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 ERROR_COMPILE_TIME_VALUE = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory ELSE_MISPLACED_IN_WHEN = SimpleDiagnosticFactory.create( ERROR, new PositioningStrategy() { @@ -396,14 +374,14 @@ public interface Errors { SimpleDiagnosticFactory FINAL_SUPERTYPE = SimpleDiagnosticFactory.create(ERROR); - DiagnosticFactory1 ILLEGAL_SELECTOR = DiagnosticFactory1.create(ERROR, "Expression ''{0}'' cannot be a selector (occur after a dot)"); + DiagnosticFactory1 ILLEGAL_SELECTOR = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION = SimpleDiagnosticFactory .create(ERROR); SimpleDiagnosticFactory BREAK_OR_CONTINUE_OUTSIDE_A_LOOP = SimpleDiagnosticFactory .create(ERROR); - DiagnosticFactory1 NOT_A_LOOP_LABEL = DiagnosticFactory1.create(ERROR, "The label ''{0}'' does not denote a loop"); - DiagnosticFactory1 NOT_A_RETURN_LABEL = DiagnosticFactory1.create(ERROR, "The label ''{0}'' does not reference to a context from which we can return"); + DiagnosticFactory1 NOT_A_LOOP_LABEL = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 NOT_A_RETURN_LABEL = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR = SimpleDiagnosticFactory .create(ERROR); @@ -415,78 +393,52 @@ public interface Errors { return markNode(element.getQuestionMarkNode()); } }); - DiagnosticFactory1 UNSAFE_CALL = DiagnosticFactory1.create(ERROR, "Only safe calls (?.) are allowed on a nullable receiver of type {0}", RENDER_TYPE); + DiagnosticFactory1 UNSAFE_CALL = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory AMBIGUOUS_LABEL = SimpleDiagnosticFactory.create(ERROR); - DiagnosticFactory1 UNSUPPORTED = DiagnosticFactory1.create(ERROR, "Unsupported [{0}]"); - DiagnosticFactory1 UNNECESSARY_SAFE_CALL = DiagnosticFactory1.create(WARNING, "Unnecessary safe call on a non-null receiver of type {0}", RENDER_TYPE); - DiagnosticFactory1 UNNECESSARY_NOT_NULL_ASSERTION = DiagnosticFactory1.create(WARNING, "Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", RENDER_TYPE); - DiagnosticFactory2 NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER = DiagnosticFactory2.create(ERROR, "{0} does not refer to a type parameter of {1}", new Renderer() { - @NotNull - @Override - public String render(@NotNull JetTypeConstraint typeConstraint) { - //noinspection ConstantConditions - return typeConstraint.getSubjectTypeParameterName().getReferencedName(); - } - }, NAME); - DiagnosticFactory2 AUTOCAST_IMPOSSIBLE = DiagnosticFactory2.create(ERROR, "Automatic cast to {0} is impossible, because {1} could have changed since the is-check", RENDER_TYPE, NAME); + DiagnosticFactory1 UNSUPPORTED = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 UNNECESSARY_SAFE_CALL = DiagnosticFactory1.create(WARNING); + DiagnosticFactory1 UNNECESSARY_NOT_NULL_ASSERTION = DiagnosticFactory1.create(WARNING); + DiagnosticFactory2 NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER = DiagnosticFactory2.create(ERROR); + DiagnosticFactory2 AUTOCAST_IMPOSSIBLE = DiagnosticFactory2.create(ERROR); - DiagnosticFactory2 TYPE_MISMATCH_IN_FOR_LOOP = DiagnosticFactory2.create(ERROR, "The loop iterates over values of type {0} but the parameter is declared to be {1}", RENDER_TYPE, RENDER_TYPE); - DiagnosticFactory1 TYPE_MISMATCH_IN_CONDITION = DiagnosticFactory1.create(ERROR, "Condition must be of type Boolean, but was of type {0}", RENDER_TYPE); - DiagnosticFactory2 TYPE_MISMATCH_IN_TUPLE_PATTERN = DiagnosticFactory2.create(ERROR, "Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, TO_STRING); // TODO: message - DiagnosticFactory2 TYPE_MISMATCH_IN_BINDING_PATTERN = DiagnosticFactory2.create(ERROR, "{0} must be a supertype of {1}. Use 'is' to match against {0}", RENDER_TYPE, RENDER_TYPE); - DiagnosticFactory2 INCOMPATIBLE_TYPES = DiagnosticFactory2.create(ERROR, "Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE); + DiagnosticFactory2 TYPE_MISMATCH_IN_FOR_LOOP = DiagnosticFactory2.create(ERROR); + DiagnosticFactory1 TYPE_MISMATCH_IN_CONDITION = DiagnosticFactory1.create(ERROR); + DiagnosticFactory2 TYPE_MISMATCH_IN_TUPLE_PATTERN = DiagnosticFactory2.create(ERROR); // TODO: message + DiagnosticFactory2 TYPE_MISMATCH_IN_BINDING_PATTERN = DiagnosticFactory2.create(ERROR); + DiagnosticFactory2 INCOMPATIBLE_TYPES = DiagnosticFactory2.create(ERROR); SimpleDiagnosticFactory EXPECTED_CONDITION = SimpleDiagnosticFactory.create(ERROR); - DiagnosticFactory1 CANNOT_CHECK_FOR_ERASED = DiagnosticFactory1.create(ERROR, "Cannot check for instance of erased type: {0}", RENDER_TYPE); - DiagnosticFactory2 UNCHECKED_CAST = DiagnosticFactory2.create(WARNING, "Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE); + DiagnosticFactory1 CANNOT_CHECK_FOR_ERASED = DiagnosticFactory1.create(ERROR); + DiagnosticFactory2 UNCHECKED_CAST = DiagnosticFactory2.create(WARNING); DiagnosticFactory3> INCONSISTENT_TYPE_PARAMETER_VALUES = - DiagnosticFactory3.create(ERROR, "Type parameter {0} of {1} has inconsistent values: {2}", NAME, DescriptorRenderer.TEXT, new Renderer>() { - @NotNull - @Override - public String render(@NotNull Collection types) { - StringBuilder builder = new StringBuilder(); - for (Iterator iterator = types.iterator(); iterator.hasNext(); ) { - JetType jetType = iterator.next(); - builder.append(jetType); - if (iterator.hasNext()) { - builder.append(", "); - } - } - return builder.toString(); - } - }); + DiagnosticFactory3.create(ERROR); - DiagnosticFactory3 EQUALITY_NOT_APPLICABLE = DiagnosticFactory3.create(ERROR, "Operator {0} cannot be applied to {1} and {2}", new Renderer() { - @NotNull - @Override - public String render(@NotNull JetSimpleNameExpression nameExpression) { - //noinspection ConstantConditions - return nameExpression.getReferencedName(); - } - }, TO_STRING, TO_STRING); + DiagnosticFactory3 EQUALITY_NOT_APPLICABLE = DiagnosticFactory3.create(ERROR); - DiagnosticFactory2 OVERRIDING_FINAL_MEMBER = DiagnosticFactory2.create(ERROR, "''{0}'' in ''{1}'' is final and cannot be overridden", NAME, NAME); - DiagnosticFactory3 CANNOT_WEAKEN_ACCESS_PRIVILEGE = DiagnosticFactory3.create(ERROR, "Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", PositioningStrategies.POSITION_VISIBILITY_MODIFIER, TO_STRING, NAME, NAME); - DiagnosticFactory3 CANNOT_CHANGE_ACCESS_PRIVILEGE = DiagnosticFactory3.create(ERROR, "Cannot change access privilege ''{0}'' for ''{1}'' in ''{2}''", PositioningStrategies.POSITION_VISIBILITY_MODIFIER, TO_STRING, NAME, NAME); + DiagnosticFactory2 OVERRIDING_FINAL_MEMBER = DiagnosticFactory2.create(ERROR); + DiagnosticFactory3 CANNOT_WEAKEN_ACCESS_PRIVILEGE = DiagnosticFactory3.create(ERROR, + PositioningStrategies.POSITION_VISIBILITY_MODIFIER); + DiagnosticFactory3 CANNOT_CHANGE_ACCESS_PRIVILEGE = DiagnosticFactory3.create(ERROR, + PositioningStrategies.POSITION_VISIBILITY_MODIFIER); DiagnosticFactory2 RETURN_TYPE_MISMATCH_ON_OVERRIDE = - DiagnosticFactory2.create(ERROR, "Return type of {0} is not a subtype of the return type overridden member {1}", PositioningStrategies.POSITION_DECLARATION, DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); + DiagnosticFactory2.create(ERROR, PositioningStrategies.POSITION_DECLARATION); - DiagnosticFactory2 VAR_OVERRIDDEN_BY_VAL = DiagnosticFactory2.create(ERROR, "Var-property {0} cannot be overridden by val-property {1}", new PositioningStrategy() { + DiagnosticFactory2 VAR_OVERRIDDEN_BY_VAL = DiagnosticFactory2.create(ERROR, new PositioningStrategy() { @NotNull @Override public List mark(@NotNull JetProperty property) { return markNode(property.getValOrVarNode()); } - }, DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); + }); - DiagnosticFactory2 ABSTRACT_MEMBER_NOT_IMPLEMENTED = DiagnosticFactory2.create(ERROR, "{0} must be declared abstract or implement abstract member {1}", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT); + DiagnosticFactory2 ABSTRACT_MEMBER_NOT_IMPLEMENTED = DiagnosticFactory2.create(ERROR); - DiagnosticFactory2 MANY_IMPL_MEMBER_NOT_IMPLEMENTED = DiagnosticFactory2.create(ERROR, "{0} must override {1} because it inherits many implementations of it", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT); + DiagnosticFactory2 MANY_IMPL_MEMBER_NOT_IMPLEMENTED = DiagnosticFactory2.create(ERROR); - DiagnosticFactory2 CONFLICTING_OVERLOADS = DiagnosticFactory2.create(ERROR, "{1} is already defined in ''{0}''", new PositioningStrategy() { + DiagnosticFactory2 CONFLICTING_OVERLOADS = DiagnosticFactory2.create(ERROR, new PositioningStrategy() { @NotNull @Override public List mark(@NotNull JetDeclaration jetDeclaration) { @@ -518,36 +470,30 @@ public interface Errors { return markRange(jetDeclaration.getTextRange()); } } - }, DescriptorRenderer.TEXT, TO_STRING); + }); - DiagnosticFactory3 RESULT_TYPE_MISMATCH = DiagnosticFactory3.create(ERROR, "{0} must return {1} but returns {2}", TO_STRING, RENDER_TYPE, RENDER_TYPE); - DiagnosticFactory3 UNSAFE_INFIX_CALL = DiagnosticFactory3.create(ERROR, "Infix call corresponds to a dot-qualified call ''{0}.{1}({2})'' which is not allowed on a nullable receiver ''{0}''. Use '?.'-qualified call instead"); + DiagnosticFactory3 RESULT_TYPE_MISMATCH = DiagnosticFactory3.create(ERROR); + DiagnosticFactory3 UNSAFE_INFIX_CALL = DiagnosticFactory3.create(ERROR); AmbiguousDescriptorDiagnosticFactory OVERLOAD_RESOLUTION_AMBIGUITY = new AmbiguousDescriptorDiagnosticFactory("Overload resolution ambiguity: {0}"); AmbiguousDescriptorDiagnosticFactory NONE_APPLICABLE = new AmbiguousDescriptorDiagnosticFactory("None of the following functions can be called with the arguments supplied: {0}"); - DiagnosticFactory1 NO_VALUE_FOR_PARAMETER = DiagnosticFactory1.create(ERROR, "No value passed for parameter {0}", DescriptorRenderer.TEXT); - DiagnosticFactory1 MISSING_RECEIVER = DiagnosticFactory1.create(ERROR, "A receiver of type {0} is required", RENDER_TYPE); + DiagnosticFactory1 NO_VALUE_FOR_PARAMETER = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 MISSING_RECEIVER = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory NO_RECEIVER_ADMITTED = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS = SimpleDiagnosticFactory .create(ERROR); - DiagnosticFactory1 TYPE_INFERENCE_FAILED = DiagnosticFactory1.create(ERROR, "Type inference failed: {0}"); - DiagnosticFactory1 WRONG_NUMBER_OF_TYPE_ARGUMENTS = DiagnosticFactory1.create(ERROR, "{0} type arguments expected", new Renderer() { - @NotNull - @Override - public String render(@NotNull Integer argument) { - return argument == 0 ? "No" : argument.toString(); - } - }); + DiagnosticFactory1 TYPE_INFERENCE_FAILED = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 WRONG_NUMBER_OF_TYPE_ARGUMENTS = DiagnosticFactory1.create(ERROR); - DiagnosticFactory1 UNRESOLVED_IDE_TEMPLATE = DiagnosticFactory1.create(ERROR, "Unresolved IDE template: {0}"); + DiagnosticFactory1 UNRESOLVED_IDE_TEMPLATE = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED = SimpleDiagnosticFactory .create(WARNING); - DiagnosticFactory1 NOT_AN_ANNOTATION_CLASS = DiagnosticFactory1.create(ERROR, "{0} is not an annotation class"); + DiagnosticFactory1 NOT_AN_ANNOTATION_CLASS = DiagnosticFactory1.create(ERROR); // This field is needed to make the Initializer class load (interfaces cannot have static initializers) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnusedElementDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnusedElementDiagnosticFactory.java index 82cb5dcdbd1..416a4809603 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnusedElementDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnusedElementDiagnosticFactory.java @@ -25,7 +25,7 @@ import org.jetbrains.jet.lang.diagnostics.rendering.Renderers; */ public class UnusedElementDiagnosticFactory extends DiagnosticFactory1 { private UnusedElementDiagnosticFactory(Severity severity, String message, PositioningStrategy positioningStrategy, Renderer renderer) { - super(severity, message, positioningStrategy, renderer); + super(severity, positioningStrategy); } public static UnusedElementDiagnosticFactory create(Severity severity, String message, PositioningStrategy positioningStrategy, Renderer renderer) { From c957997943824fe59ac77ccf6b53138cd057397e Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 14:41:16 +0400 Subject: [PATCH 022/147] Removed message formats and renderers passed to constructor parameters of UnusedElementDiagnosticFactory and AmbiguousDescriptorDiagnosticFactory. --- .../AmbiguousDescriptorDiagnosticFactory.java | 22 +++---------------- .../jet/lang/diagnostics/Errors.java | 18 ++++++++------- .../UnusedElementDiagnosticFactory.java | 20 +++++------------ 3 files changed, 18 insertions(+), 42 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java index 06eecc981a9..809012d233b 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/AmbiguousDescriptorDiagnosticFactory.java @@ -17,11 +17,8 @@ package org.jetbrains.jet.lang.diagnostics; import com.intellij.psi.PsiElement; -import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.descriptors.CallableDescriptor; -import org.jetbrains.jet.lang.diagnostics.rendering.Renderer; import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; -import org.jetbrains.jet.resolve.DescriptorRenderer; import java.util.Collection; @@ -29,24 +26,11 @@ import java.util.Collection; * @author abreslav */ public class AmbiguousDescriptorDiagnosticFactory extends DiagnosticFactory1>> { - public static AmbiguousDescriptorDiagnosticFactory create(String messageTemplate) { - return new AmbiguousDescriptorDiagnosticFactory(messageTemplate); + public static AmbiguousDescriptorDiagnosticFactory create() { + return new AmbiguousDescriptorDiagnosticFactory(); } - public AmbiguousDescriptorDiagnosticFactory(String messageTemplate) { + public AmbiguousDescriptorDiagnosticFactory() { super(Severity.ERROR, PositioningStrategies.DEFAULT); } - - private static Renderer>> AMBIGUOUS_DESCRIPTOR_RENDERER = - new Renderer>>() { - @NotNull - @Override - public String render(@NotNull Collection> argument) { - StringBuilder stringBuilder = new StringBuilder("\n"); - for (ResolvedCall call : argument) { - stringBuilder.append(DescriptorRenderer.TEXT.render(call.getResultingDescriptor())).append("\n"); - } - return stringBuilder.toString(); - } - }; } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java index f382ed1fc54..4ceecb4bef3 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java @@ -34,7 +34,6 @@ import java.util.Collection; import java.util.Collections; import java.util.List; -import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.*; import static org.jetbrains.jet.lang.diagnostics.Severity.ERROR; import static org.jetbrains.jet.lang.diagnostics.Severity.WARNING; @@ -191,9 +190,12 @@ public interface Errors { DiagnosticFactory1 UNINITIALIZED_VARIABLE = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 UNINITIALIZED_PARAMETER = DiagnosticFactory1.create(ERROR); - UnusedElementDiagnosticFactory UNUSED_VARIABLE = UnusedElementDiagnosticFactory.create(WARNING, "Variable ''{0}'' is never used", PositioningStrategies.POSITION_NAME_IDENTIFIER, NAME); - UnusedElementDiagnosticFactory UNUSED_PARAMETER = UnusedElementDiagnosticFactory.create(WARNING, "Parameter ''{0}'' is never used", PositioningStrategies.POSITION_NAME_IDENTIFIER, NAME); - UnusedElementDiagnosticFactory ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE = UnusedElementDiagnosticFactory.create(WARNING, "Variable ''{0}'' is assigned but never accessed", PositioningStrategies.POSITION_NAME_IDENTIFIER, NAME); + UnusedElementDiagnosticFactory UNUSED_VARIABLE = UnusedElementDiagnosticFactory.create(WARNING, + PositioningStrategies.POSITION_NAME_IDENTIFIER); + UnusedElementDiagnosticFactory UNUSED_PARAMETER = UnusedElementDiagnosticFactory.create(WARNING, + PositioningStrategies.POSITION_NAME_IDENTIFIER); + UnusedElementDiagnosticFactory ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE = UnusedElementDiagnosticFactory.create(WARNING, + PositioningStrategies.POSITION_NAME_IDENTIFIER); DiagnosticFactory1 VARIABLE_WITH_REDUNDANT_INITIALIZER = DiagnosticFactory1.create(WARNING); DiagnosticFactory2 UNUSED_VALUE = DiagnosticFactory2.create(WARNING); DiagnosticFactory1 UNUSED_CHANGED_VALUE = DiagnosticFactory1.create(WARNING); @@ -243,7 +245,7 @@ public interface Errors { .create(ERROR); DiagnosticFactory2 ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT = DiagnosticFactory2.create(ERROR); - AmbiguousDescriptorDiagnosticFactory ASSIGN_OPERATOR_AMBIGUITY = AmbiguousDescriptorDiagnosticFactory.create("Assignment operators ambiguity: {0}"); + AmbiguousDescriptorDiagnosticFactory ASSIGN_OPERATOR_AMBIGUITY = AmbiguousDescriptorDiagnosticFactory.create(); SimpleDiagnosticFactory EQUALS_MISSING = SimpleDiagnosticFactory.create(ERROR); @@ -293,7 +295,7 @@ public interface Errors { NEXT_MISSING = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory ITERATOR_MISSING = SimpleDiagnosticFactory.create(ERROR); - AmbiguousDescriptorDiagnosticFactory ITERATOR_AMBIGUITY = AmbiguousDescriptorDiagnosticFactory.create("Method 'iterator()' is ambiguous for this expression: {0}"); + AmbiguousDescriptorDiagnosticFactory ITERATOR_AMBIGUITY = AmbiguousDescriptorDiagnosticFactory.create(); DiagnosticFactory1 COMPARE_TO_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 CALLEE_NOT_A_FUNCTION = DiagnosticFactory1.create(ERROR); @@ -476,8 +478,8 @@ public interface Errors { DiagnosticFactory3 RESULT_TYPE_MISMATCH = DiagnosticFactory3.create(ERROR); DiagnosticFactory3 UNSAFE_INFIX_CALL = DiagnosticFactory3.create(ERROR); - AmbiguousDescriptorDiagnosticFactory OVERLOAD_RESOLUTION_AMBIGUITY = new AmbiguousDescriptorDiagnosticFactory("Overload resolution ambiguity: {0}"); - AmbiguousDescriptorDiagnosticFactory NONE_APPLICABLE = new AmbiguousDescriptorDiagnosticFactory("None of the following functions can be called with the arguments supplied: {0}"); + AmbiguousDescriptorDiagnosticFactory OVERLOAD_RESOLUTION_AMBIGUITY = new AmbiguousDescriptorDiagnosticFactory(); + AmbiguousDescriptorDiagnosticFactory NONE_APPLICABLE = new AmbiguousDescriptorDiagnosticFactory(); DiagnosticFactory1 NO_VALUE_FOR_PARAMETER = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 MISSING_RECEIVER = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnusedElementDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnusedElementDiagnosticFactory.java index 416a4809603..a9c8ce304dd 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnusedElementDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnusedElementDiagnosticFactory.java @@ -17,30 +17,20 @@ package org.jetbrains.jet.lang.diagnostics; import com.intellij.psi.PsiElement; -import org.jetbrains.jet.lang.diagnostics.rendering.Renderer; -import org.jetbrains.jet.lang.diagnostics.rendering.Renderers; /** * @author svtk */ public class UnusedElementDiagnosticFactory extends DiagnosticFactory1 { - private UnusedElementDiagnosticFactory(Severity severity, String message, PositioningStrategy positioningStrategy, Renderer renderer) { + private UnusedElementDiagnosticFactory(Severity severity, PositioningStrategy positioningStrategy) { super(severity, positioningStrategy); } - public static UnusedElementDiagnosticFactory create(Severity severity, String message, PositioningStrategy positioningStrategy, Renderer renderer) { - return new UnusedElementDiagnosticFactory(severity, message, positioningStrategy, renderer); + public static UnusedElementDiagnosticFactory create(Severity severity, PositioningStrategy positioningStrategy) { + return new UnusedElementDiagnosticFactory(severity, positioningStrategy); } - public static UnusedElementDiagnosticFactory create(Severity severity, String message, PositioningStrategy positioningStrategy) { - return create(severity, message, positioningStrategy, Renderers.TO_STRING); - } - - public static UnusedElementDiagnosticFactory create(Severity severity, String message, Renderer renderer) { - return create(severity, message, PositioningStrategies.DEFAULT, renderer); - } - - public static UnusedElementDiagnosticFactory create(Severity severity, String message) { - return create(severity, message, PositioningStrategies.DEFAULT, Renderers.TO_STRING); + public static UnusedElementDiagnosticFactory create(Severity severity) { + return create(severity, PositioningStrategies.DEFAULT); } } From 613ddeb461d6e4d1cba43b1ed69a01f734026444 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 15:06:00 +0400 Subject: [PATCH 023/147] Removed diagnostic rendering from RedeclarationDiagnosticFactory and UnresolvedReferenceDiagnosticFactory. --- .../jet/lang/diagnostics/Errors.java | 8 +++---- .../RedeclarationDiagnosticFactory.java | 22 +------------------ .../UnresolvedReferenceDiagnosticFactory.java | 13 +++-------- 3 files changed, 8 insertions(+), 35 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java index 4ceecb4bef3..332b6075124 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java @@ -44,14 +44,14 @@ public interface Errors { DiagnosticFactory1 EXCEPTION_WHILE_ANALYZING = DiagnosticFactory1.create(ERROR); - UnresolvedReferenceDiagnosticFactory UNRESOLVED_REFERENCE = UnresolvedReferenceDiagnosticFactory.create("Unresolved reference"); + UnresolvedReferenceDiagnosticFactory UNRESOLVED_REFERENCE = UnresolvedReferenceDiagnosticFactory.create(); //Elements with "INVISIBLE_REFERENCE" error are marked as unresolved, unlike elements with "INVISIBLE_MEMBER" error DiagnosticFactory2 INVISIBLE_REFERENCE = DiagnosticFactory2.create(ERROR); DiagnosticFactory2 INVISIBLE_MEMBER = DiagnosticFactory2.create(ERROR); - RedeclarationDiagnosticFactory REDECLARATION = RedeclarationDiagnosticFactory.REDECLARATION; - RedeclarationDiagnosticFactory NAME_SHADOWING = RedeclarationDiagnosticFactory.NAME_SHADOWING; + RedeclarationDiagnosticFactory REDECLARATION = new RedeclarationDiagnosticFactory(ERROR); + RedeclarationDiagnosticFactory NAME_SHADOWING = new RedeclarationDiagnosticFactory(WARNING); DiagnosticFactory2 TYPE_MISMATCH = DiagnosticFactory2.create(ERROR ); @@ -107,7 +107,7 @@ public interface Errors { .create(ERROR); SimpleDiagnosticFactory ARGUMENT_PASSED_TWICE = SimpleDiagnosticFactory.create(ERROR); - UnresolvedReferenceDiagnosticFactory NAMED_PARAMETER_NOT_FOUND = UnresolvedReferenceDiagnosticFactory.create("Cannot find a parameter with this name"); + UnresolvedReferenceDiagnosticFactory NAMED_PARAMETER_NOT_FOUND = UnresolvedReferenceDiagnosticFactory.create(); SimpleDiagnosticFactory VARARG_OUTSIDE_PARENTHESES = SimpleDiagnosticFactory .create(ERROR); SimpleDiagnosticFactory diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java index 053238f2839..59d138f52c4 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java @@ -23,36 +23,16 @@ import org.jetbrains.annotations.NotNull; * @author abreslav */ public class RedeclarationDiagnosticFactory extends AbstractDiagnosticFactory { - - private final String name; final Severity severity; - private final String messagePrefix; - public static final RedeclarationDiagnosticFactory REDECLARATION = new RedeclarationDiagnosticFactory( - "REDECLARATION", Severity.ERROR, "Redeclaration: "); - public static final RedeclarationDiagnosticFactory NAME_SHADOWING = new RedeclarationDiagnosticFactory( - "NAME_SHADOWING", Severity.WARNING, "Name shadowed: "); - - public RedeclarationDiagnosticFactory(String name, Severity severity, String messagePrefix) { - this.name = name; + public RedeclarationDiagnosticFactory(Severity severity) { this.severity = severity; - this.messagePrefix = messagePrefix; } public RedeclarationDiagnostic on(@NotNull PsiElement duplicatingElement, @NotNull String name) { return new RedeclarationDiagnostic.SimpleRedeclarationDiagnostic(duplicatingElement, name, this); } - @NotNull - @Override - public String getName() { - return name; - } - - public String makeMessage(String identifier) { - return messagePrefix + identifier; - } - @Override public String toString() { return getName(); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java index b4fd2e6e889..4aee43e3422 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java @@ -23,21 +23,14 @@ import org.jetbrains.jet.lang.psi.JetReferenceExpression; * @author abreslav */ public class UnresolvedReferenceDiagnosticFactory extends AbstractDiagnosticFactory { - private final String message; - - private UnresolvedReferenceDiagnosticFactory(String message) { - this.message = message; - } - - String getMessage() { - return message; + private UnresolvedReferenceDiagnosticFactory() { } public UnresolvedReferenceDiagnostic on(@NotNull JetReferenceExpression reference) { return new UnresolvedReferenceDiagnostic(reference, this); } - public static UnresolvedReferenceDiagnosticFactory create(String message) { - return new UnresolvedReferenceDiagnosticFactory(message); + public static UnresolvedReferenceDiagnosticFactory create() { + return new UnresolvedReferenceDiagnosticFactory(); } } From 77ea513e42813ef3b29e0b4f99cf556e892ccbc6 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 15:16:14 +0400 Subject: [PATCH 024/147] Reformatted Errors, got rid of obsolete comments. --- .../jet/lang/diagnostics/Errors.java | 520 ++++++++---------- 1 file changed, 229 insertions(+), 291 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java index 332b6075124..2c74e53d6a3 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java @@ -47,17 +47,15 @@ public interface Errors { UnresolvedReferenceDiagnosticFactory UNRESOLVED_REFERENCE = UnresolvedReferenceDiagnosticFactory.create(); //Elements with "INVISIBLE_REFERENCE" error are marked as unresolved, unlike elements with "INVISIBLE_MEMBER" error - DiagnosticFactory2 INVISIBLE_REFERENCE = DiagnosticFactory2.create(ERROR); + DiagnosticFactory2 INVISIBLE_REFERENCE = + DiagnosticFactory2.create(ERROR); DiagnosticFactory2 INVISIBLE_MEMBER = DiagnosticFactory2.create(ERROR); RedeclarationDiagnosticFactory REDECLARATION = new RedeclarationDiagnosticFactory(ERROR); RedeclarationDiagnosticFactory NAME_SHADOWING = new RedeclarationDiagnosticFactory(WARNING); - DiagnosticFactory2 TYPE_MISMATCH = DiagnosticFactory2.create(ERROR - ); - DiagnosticFactory1> INCOMPATIBLE_MODIFIERS = - DiagnosticFactory1.create(ERROR - ); + DiagnosticFactory2 TYPE_MISMATCH = DiagnosticFactory2.create(ERROR); + DiagnosticFactory1> INCOMPATIBLE_MODIFIERS = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 ILLEGAL_MODIFIER = DiagnosticFactory1.create(ERROR); DiagnosticFactory2 REDUNDANT_MODIFIER = DiagnosticFactory2.create(Severity.WARNING); @@ -68,140 +66,111 @@ public interface Errors { SimpleDiagnosticFactory REDUNDANT_MODIFIER_IN_GETTER = SimpleDiagnosticFactory.create(WARNING); SimpleDiagnosticFactory TRAIT_CAN_NOT_BE_FINAL = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM = SimpleDiagnosticFactory.create(ERROR - ); // TODO: message + SimpleDiagnosticFactory TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory RETURN_NOT_ALLOWED = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE = SimpleDiagnosticFactory - .create(ERROR, - new PositioningStrategy() { - @NotNull - @Override - public List mark(@NotNull JetTypeProjection element) { - return markNode(element.getProjectionNode()); - } - }); - SimpleDiagnosticFactory - LABEL_NAME_CLASH = SimpleDiagnosticFactory.create(WARNING); - SimpleDiagnosticFactory - EXPRESSION_EXPECTED_NAMESPACE_FOUND = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE = + SimpleDiagnosticFactory.create(ERROR, + new PositioningStrategy() { + @NotNull + @Override + public List mark(@NotNull JetTypeProjection element) { + return markNode(element.getProjectionNode()); + } + }); + SimpleDiagnosticFactoryLABEL_NAME_CLASH = SimpleDiagnosticFactory.create(WARNING); + SimpleDiagnosticFactory EXPRESSION_EXPECTED_NAMESPACE_FOUND = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory1 CANNOT_IMPORT_FROM_ELEMENT = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 CANNOT_BE_IMPORTED = DiagnosticFactory1.create(ERROR); - SimpleDiagnosticFactory - USELESS_HIDDEN_IMPORT = SimpleDiagnosticFactory.create(WARNING); + SimpleDiagnosticFactoryUSELESS_HIDDEN_IMPORT = SimpleDiagnosticFactory.create(WARNING); SimpleDiagnosticFactory USELESS_SIMPLE_IMPORT = SimpleDiagnosticFactory.create(WARNING); - SimpleDiagnosticFactory CANNOT_INFER_PARAMETER_TYPE = SimpleDiagnosticFactory - .create(ERROR); + SimpleDiagnosticFactory CANNOT_INFER_PARAMETER_TYPE = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory NO_BACKING_FIELD_ABSTRACT_PROPERTY = SimpleDiagnosticFactory - .create(ERROR); + SimpleDiagnosticFactory NO_BACKING_FIELD_ABSTRACT_PROPERTY = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory NO_BACKING_FIELD_CUSTOM_ACCESSORS = SimpleDiagnosticFactory.create(ERROR ); - SimpleDiagnosticFactory - INACCESSIBLE_BACKING_FIELD = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory NOT_PROPERTY_BACKING_FIELD = SimpleDiagnosticFactory - .create(ERROR); + SimpleDiagnosticFactory INACCESSIBLE_BACKING_FIELD = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory NOT_PROPERTY_BACKING_FIELD = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory MIXING_NAMED_AND_POSITIONED_ARGUMENTS = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory - ARGUMENT_PASSED_TWICE = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory MIXING_NAMED_AND_POSITIONED_ARGUMENTS = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory ARGUMENT_PASSED_TWICE = SimpleDiagnosticFactory.create(ERROR); UnresolvedReferenceDiagnosticFactory NAMED_PARAMETER_NOT_FOUND = UnresolvedReferenceDiagnosticFactory.create(); - SimpleDiagnosticFactory VARARG_OUTSIDE_PARENTHESES = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory - NON_VARARG_SPREAD = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory VARARG_OUTSIDE_PARENTHESES = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory NON_VARARG_SPREAD = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory MANY_FUNCTION_LITERAL_ARGUMENTS = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory PROPERTY_WITH_NO_TYPE_NO_INITIALIZER = SimpleDiagnosticFactory - .create(ERROR); + SimpleDiagnosticFactory MANY_FUNCTION_LITERAL_ARGUMENTS = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory PROPERTY_WITH_NO_TYPE_NO_INITIALIZER = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS = SimpleDiagnosticFactory .create(ERROR, PositioningStrategies.POSITION_ABSTRACT_MODIFIER); - SimpleDiagnosticFactory ABSTRACT_PROPERTY_NOT_IN_CLASS = SimpleDiagnosticFactory - .create(ERROR, - PositioningStrategies.POSITION_ABSTRACT_MODIFIER); - SimpleDiagnosticFactory - ABSTRACT_PROPERTY_WITH_INITIALIZER = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - ABSTRACT_PROPERTY_WITH_GETTER = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - ABSTRACT_PROPERTY_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory ABSTRACT_PROPERTY_NOT_IN_CLASS = SimpleDiagnosticFactory.create(ERROR, + PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + SimpleDiagnosticFactory ABSTRACT_PROPERTY_WITH_INITIALIZER = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory ABSTRACT_PROPERTY_WITH_GETTER = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactoryABSTRACT_PROPERTY_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - PACKAGE_MEMBER_CANNOT_BE_PROTECTED = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory PACKAGE_MEMBER_CANNOT_BE_PROTECTED = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory BACKING_FIELD_IN_TRAIT = SimpleDiagnosticFactory - .create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); - SimpleDiagnosticFactory MUST_BE_INITIALIZED = SimpleDiagnosticFactory - .create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); - SimpleDiagnosticFactory MUST_BE_INITIALIZED_OR_BE_ABSTRACT = SimpleDiagnosticFactory - .create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); - SimpleDiagnosticFactory - PROPERTY_INITIALIZER_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory PROPERTY_INITIALIZER_NO_BACKING_FIELD = SimpleDiagnosticFactory - .create(ERROR); - DiagnosticFactory3 ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS = DiagnosticFactory3.create(ERROR, - PositioningStrategies.POSITION_ABSTRACT_MODIFIER); - DiagnosticFactory3 ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS = DiagnosticFactory3.create(ERROR, - PositioningStrategies.POSITION_ABSTRACT_MODIFIER); - DiagnosticFactory1 ABSTRACT_FUNCTION_WITH_BODY = DiagnosticFactory1.create(ERROR, - PositioningStrategies.POSITION_ABSTRACT_MODIFIER); - DiagnosticFactory1 NON_ABSTRACT_FUNCTION_WITH_NO_BODY = DiagnosticFactory1.create(ERROR, - PositioningStrategies.POSITION_NAME_IDENTIFIER); - DiagnosticFactory1 NON_MEMBER_ABSTRACT_FUNCTION = DiagnosticFactory1.create(ERROR, - PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + SimpleDiagnosticFactory GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory BACKING_FIELD_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR, + PositioningStrategies.POSITION_NAME_IDENTIFIER); + SimpleDiagnosticFactory MUST_BE_INITIALIZED = SimpleDiagnosticFactory.create(ERROR, + PositioningStrategies.POSITION_NAME_IDENTIFIER); + SimpleDiagnosticFactory MUST_BE_INITIALIZED_OR_BE_ABSTRACT = SimpleDiagnosticFactory.create(ERROR, + PositioningStrategies.POSITION_NAME_IDENTIFIER); + SimpleDiagnosticFactoryPROPERTY_INITIALIZER_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory PROPERTY_INITIALIZER_NO_BACKING_FIELD = SimpleDiagnosticFactory.create(ERROR); + DiagnosticFactory3 ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS = + DiagnosticFactory3.create(ERROR, PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + DiagnosticFactory3 ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS = + DiagnosticFactory3.create(ERROR,PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + DiagnosticFactory1 ABSTRACT_FUNCTION_WITH_BODY = + DiagnosticFactory1.create(ERROR, PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + DiagnosticFactory1 NON_ABSTRACT_FUNCTION_WITH_NO_BODY = + DiagnosticFactory1.create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); + DiagnosticFactory1 NON_MEMBER_ABSTRACT_FUNCTION = + DiagnosticFactory1.create(ERROR, PositioningStrategies.POSITION_ABSTRACT_MODIFIER); - DiagnosticFactory1 NON_MEMBER_FUNCTION_NO_BODY = DiagnosticFactory1.create(ERROR, - PositioningStrategies.POSITION_NAME_IDENTIFIER); - SimpleDiagnosticFactory NON_FINAL_MEMBER_IN_FINAL_CLASS = SimpleDiagnosticFactory - .create(ERROR, PositioningStrategies.positionModifier(JetTokens.OPEN_KEYWORD)); + DiagnosticFactory1 NON_MEMBER_FUNCTION_NO_BODY = + DiagnosticFactory1.create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); + SimpleDiagnosticFactory NON_FINAL_MEMBER_IN_FINAL_CLASS = + SimpleDiagnosticFactory.create(ERROR, PositioningStrategies.positionModifier(JetTokens.OPEN_KEYWORD)); - SimpleDiagnosticFactory PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE = SimpleDiagnosticFactory - .create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); + SimpleDiagnosticFactory PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE = + SimpleDiagnosticFactory.create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); - SimpleDiagnosticFactory PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT = SimpleDiagnosticFactory - .create(ERROR); // TODO : better positioning - SimpleDiagnosticFactory SUPERTYPE_NOT_INITIALIZED = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory SUPERTYPE_NOT_INITIALIZED_DEFAULT = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory - BY_IN_SECONDARY_CONSTRUCTOR = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - INITIALIZER_WITH_NO_ARGUMENTS = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - MANY_CALLS_TO_THIS = SimpleDiagnosticFactory.create(ERROR); - DiagnosticFactory1 NOTHING_TO_OVERRIDE = DiagnosticFactory1.create(ERROR, - PositioningStrategies.positionModifier(JetTokens.OVERRIDE_KEYWORD)); - DiagnosticFactory3 VIRTUAL_MEMBER_HIDDEN = DiagnosticFactory3.create(ERROR, - PositioningStrategies.POSITION_NAME_IDENTIFIER); + SimpleDiagnosticFactory PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT = + SimpleDiagnosticFactory.create(ERROR); // TODO : better positioning + SimpleDiagnosticFactory SUPERTYPE_NOT_INITIALIZED = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory SUPERTYPE_NOT_INITIALIZED_DEFAULT = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory BY_IN_SECONDARY_CONSTRUCTOR = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory INITIALIZER_WITH_NO_ARGUMENTS = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory MANY_CALLS_TO_THIS = SimpleDiagnosticFactory.create(ERROR); + DiagnosticFactory1 NOTHING_TO_OVERRIDE = + DiagnosticFactory1.create(ERROR, PositioningStrategies.positionModifier(JetTokens.OVERRIDE_KEYWORD)); + DiagnosticFactory3 + VIRTUAL_MEMBER_HIDDEN = DiagnosticFactory3.create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); - DiagnosticFactory1 ENUM_ENTRY_SHOULD_BE_INITIALIZED = DiagnosticFactory1.create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); + DiagnosticFactory1 ENUM_ENTRY_SHOULD_BE_INITIALIZED = + DiagnosticFactory1.create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); DiagnosticFactory1 ENUM_ENTRY_ILLEGAL_TYPE = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 UNINITIALIZED_VARIABLE = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 UNINITIALIZED_PARAMETER = DiagnosticFactory1.create(ERROR); - UnusedElementDiagnosticFactory UNUSED_VARIABLE = UnusedElementDiagnosticFactory.create(WARNING, - PositioningStrategies.POSITION_NAME_IDENTIFIER); - UnusedElementDiagnosticFactory UNUSED_PARAMETER = UnusedElementDiagnosticFactory.create(WARNING, - PositioningStrategies.POSITION_NAME_IDENTIFIER); - UnusedElementDiagnosticFactory ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE = UnusedElementDiagnosticFactory.create(WARNING, - PositioningStrategies.POSITION_NAME_IDENTIFIER); + UnusedElementDiagnosticFactory UNUSED_VARIABLE = + UnusedElementDiagnosticFactory.create(WARNING, PositioningStrategies.POSITION_NAME_IDENTIFIER); + UnusedElementDiagnosticFactory UNUSED_PARAMETER = + UnusedElementDiagnosticFactory.create(WARNING, PositioningStrategies.POSITION_NAME_IDENTIFIER); + UnusedElementDiagnosticFactory ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE = + UnusedElementDiagnosticFactory.create(WARNING, PositioningStrategies.POSITION_NAME_IDENTIFIER); DiagnosticFactory1 VARIABLE_WITH_REDUNDANT_INITIALIZER = DiagnosticFactory1.create(WARNING); DiagnosticFactory2 UNUSED_VALUE = DiagnosticFactory2.create(WARNING); DiagnosticFactory1 UNUSED_CHANGED_VALUE = DiagnosticFactory1.create(WARNING); SimpleDiagnosticFactory UNUSED_EXPRESSION = SimpleDiagnosticFactory.create(WARNING); - SimpleDiagnosticFactory UNUSED_FUNCTION_LITERAL = SimpleDiagnosticFactory - .create(WARNING); + SimpleDiagnosticFactory UNUSED_FUNCTION_LITERAL = SimpleDiagnosticFactory.create(WARNING); DiagnosticFactory1 VAL_REASSIGNMENT = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 INITIALIZATION_BEFORE_DECLARATION = DiagnosticFactory1.create(ERROR); @@ -214,115 +183,89 @@ public interface Errors { SimpleDiagnosticFactory UNREACHABLE_CODE = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - MANY_CLASS_OBJECTS = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - CLASS_OBJECT_NOT_ALLOWED = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - DELEGATION_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - DELEGATION_NOT_TO_TRAIT = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory MANY_CLASS_OBJECTS = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory CLASS_OBJECT_NOT_ALLOWED = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory DELEGATION_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory DELEGATION_NOT_TO_TRAIT = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory NO_CONSTRUCTOR = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory NOT_A_CLASS = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - ILLEGAL_ESCAPE_SEQUENCE = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory ILLEGAL_ESCAPE_SEQUENCE = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - LOCAL_EXTENSION_PROPERTY = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - LOCAL_VARIABLE_WITH_GETTER = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - LOCAL_VARIABLE_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - VAL_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory LOCAL_EXTENSION_PROPERTY = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory LOCAL_VARIABLE_WITH_GETTER = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory LOCAL_VARIABLE_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory VAL_WITH_SETTER = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory NO_GET_METHOD = SimpleDiagnosticFactory - .create(ERROR, PositioningStrategies.POSITION_ARRAY_ACCESS); - SimpleDiagnosticFactory NO_SET_METHOD = SimpleDiagnosticFactory - .create(ERROR, PositioningStrategies.POSITION_ARRAY_ACCESS); + SimpleDiagnosticFactory NO_GET_METHOD = + SimpleDiagnosticFactory.create(ERROR, PositioningStrategies.POSITION_ARRAY_ACCESS); + SimpleDiagnosticFactory NO_SET_METHOD = + SimpleDiagnosticFactory.create(ERROR, PositioningStrategies.POSITION_ARRAY_ACCESS); - SimpleDiagnosticFactory INC_DEC_SHOULD_NOT_RETURN_UNIT = SimpleDiagnosticFactory - .create(ERROR); + SimpleDiagnosticFactory INC_DEC_SHOULD_NOT_RETURN_UNIT = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory2 ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT = DiagnosticFactory2.create(ERROR); AmbiguousDescriptorDiagnosticFactory ASSIGN_OPERATOR_AMBIGUITY = AmbiguousDescriptorDiagnosticFactory.create(); - SimpleDiagnosticFactory - EQUALS_MISSING = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory ASSIGNMENT_IN_EXPRESSION_CONTEXT = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory NAMESPACE_IS_NOT_AN_EXPRESSION = SimpleDiagnosticFactory - .create(ERROR); + SimpleDiagnosticFactory EQUALS_MISSING = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory ASSIGNMENT_IN_EXPRESSION_CONTEXT = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory NAMESPACE_IS_NOT_AN_EXPRESSION = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory1 SUPER_IS_NOT_AN_EXPRESSION = DiagnosticFactory1.create(ERROR); - SimpleDiagnosticFactory - DECLARATION_IN_ILLEGAL_CONTEXT = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - SETTER_PARAMETER_WITH_DEFAULT_VALUE = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory DECLARATION_IN_ILLEGAL_CONTEXT = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory SETTER_PARAMETER_WITH_DEFAULT_VALUE = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory NO_THIS = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - SUPER_NOT_AVAILABLE = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory AMBIGUOUS_SUPER = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory - ABSTRACT_SUPER_CALL = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory SUPER_NOT_AVAILABLE = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory AMBIGUOUS_SUPER = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory ABSTRACT_SUPER_CALL = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory NOT_A_SUPERTYPE = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER = SimpleDiagnosticFactory - .create(WARNING); - SimpleDiagnosticFactory - USELESS_CAST_STATIC_ASSERT_IS_FINE = SimpleDiagnosticFactory.create(WARNING); + SimpleDiagnosticFactory TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER = SimpleDiagnosticFactory.create(WARNING); + SimpleDiagnosticFactory USELESS_CAST_STATIC_ASSERT_IS_FINE = SimpleDiagnosticFactory.create(WARNING); SimpleDiagnosticFactory USELESS_CAST = SimpleDiagnosticFactory.create(WARNING); - SimpleDiagnosticFactory - CAST_NEVER_SUCCEEDS = SimpleDiagnosticFactory.create(WARNING); - DiagnosticFactory1 WRONG_SETTER_PARAMETER_TYPE = DiagnosticFactory1.create(ERROR);//, DiagnosticParameters.TYPE); - DiagnosticFactory1 WRONG_GETTER_RETURN_TYPE = DiagnosticFactory1.create(ERROR);//, DiagnosticParameters.TYPE); + SimpleDiagnosticFactory CAST_NEVER_SUCCEEDS = SimpleDiagnosticFactory.create(WARNING); + DiagnosticFactory1 WRONG_SETTER_PARAMETER_TYPE = DiagnosticFactory1.create(ERROR); + DiagnosticFactory1 WRONG_GETTER_RETURN_TYPE = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 NO_CLASS_OBJECT = DiagnosticFactory1.create(ERROR); - SimpleDiagnosticFactory NO_GENERICS_IN_SUPERTYPE_SPECIFIER = SimpleDiagnosticFactory - .create(ERROR); + SimpleDiagnosticFactory NO_GENERICS_IN_SUPERTYPE_SPECIFIER = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory HAS_NEXT_MISSING = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory HAS_NEXT_FUNCTION_AMBIGUITY = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory HAS_NEXT_MUST_BE_READABLE = SimpleDiagnosticFactory - .create(ERROR); + SimpleDiagnosticFactory HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory HAS_NEXT_MISSING = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory HAS_NEXT_FUNCTION_AMBIGUITY = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory HAS_NEXT_MUST_BE_READABLE = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory1 HAS_NEXT_PROPERTY_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 HAS_NEXT_FUNCTION_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR); - SimpleDiagnosticFactory - NEXT_AMBIGUITY = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - NEXT_MISSING = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - ITERATOR_MISSING = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory NEXT_AMBIGUITY = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory NEXT_MISSING = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory ITERATOR_MISSING = SimpleDiagnosticFactory.create(ERROR); AmbiguousDescriptorDiagnosticFactory ITERATOR_AMBIGUITY = AmbiguousDescriptorDiagnosticFactory.create(); DiagnosticFactory1 COMPARE_TO_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 CALLEE_NOT_A_FUNCTION = DiagnosticFactory1.create(ERROR); - SimpleDiagnosticFactory RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY = SimpleDiagnosticFactory - .create(ERROR, - new PositioningStrategy() { - @NotNull - @Override - public List mark(@NotNull JetDeclarationWithBody element) { - JetExpression bodyExpression = element.getBodyExpression(); - if (!(bodyExpression instanceof JetBlockExpression)) return Collections.emptyList(); - JetBlockExpression blockExpression = (JetBlockExpression)bodyExpression; - TextRange lastBracketRange = blockExpression.getLastBracketRange(); - if (lastBracketRange == null) return Collections.emptyList(); - return markRange(lastBracketRange); - } - }); + SimpleDiagnosticFactory RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY = + SimpleDiagnosticFactory.create(ERROR, + new PositioningStrategy() { + @NotNull + @Override + public List mark(@NotNull JetDeclarationWithBody element) { + JetExpression bodyExpression = element.getBodyExpression(); + if (!(bodyExpression instanceof JetBlockExpression)) { + return Collections.emptyList(); + } + JetBlockExpression blockExpression = (JetBlockExpression)bodyExpression; + TextRange lastBracketRange = blockExpression.getLastBracketRange(); + if (lastBracketRange == null) { + return Collections.emptyList(); + } + return markRange(lastBracketRange); + } + }); DiagnosticFactory1 RETURN_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 EXPECTED_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 ASSIGNMENT_TYPE_MISMATCH = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 IMPLICIT_CAST_TO_UNIT_OR_ANY = DiagnosticFactory1.create(WARNING); DiagnosticFactory1 EXPRESSION_EXPECTED = DiagnosticFactory1.create(ERROR); - DiagnosticFactory1 UPPER_BOUND_VIOLATED = DiagnosticFactory1.create(ERROR); // TODO : Message + DiagnosticFactory1 UPPER_BOUND_VIOLATED = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 FINAL_CLASS_OBJECT_UPPER_BOUND = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 FINAL_UPPER_BOUND = DiagnosticFactory1.create(WARNING); DiagnosticFactory1 USELESS_ELVIS = DiagnosticFactory1.create(WARNING); @@ -332,8 +275,7 @@ public interface Errors { DiagnosticFactory1 TOO_MANY_ARGUMENTS = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 ERROR_COMPILE_TIME_VALUE = DiagnosticFactory1.create(ERROR); - SimpleDiagnosticFactory ELSE_MISPLACED_IN_WHEN = SimpleDiagnosticFactory.create( - ERROR, new PositioningStrategy() { + SimpleDiagnosticFactory ELSE_MISPLACED_IN_WHEN = SimpleDiagnosticFactory.create(ERROR, new PositioningStrategy() { @NotNull @Override public List mark(@NotNull JetWhenEntry entry) { @@ -352,127 +294,125 @@ public interface Errors { return markElement(element.getWhenKeywordElement()); } }); - SimpleDiagnosticFactory TYPE_MISMATCH_IN_RANGE = new SimpleDiagnosticFactory(ERROR, - new PositioningStrategy() { - @NotNull - @Override - public List mark(@NotNull JetWhenConditionInRange condition) { - return markElement(condition.getOperationReference()); - } - }); - SimpleDiagnosticFactory CYCLIC_INHERITANCE_HIERARCHY = SimpleDiagnosticFactory - .create(ERROR); + SimpleDiagnosticFactory TYPE_MISMATCH_IN_RANGE = + new SimpleDiagnosticFactory(ERROR, + new PositioningStrategy() { + @NotNull + @Override + public List mark(@NotNull JetWhenConditionInRange condition) { + return markElement(condition.getOperationReference()); + } + }); + SimpleDiagnosticFactory CYCLIC_INHERITANCE_HIERARCHY = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - MANY_CLASSES_IN_SUPERTYPE_LIST = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - SUPERTYPE_NOT_A_CLASS_OR_TRAIT = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - SUPERTYPE_INITIALIZED_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory MANY_CLASSES_IN_SUPERTYPE_LIST = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory SUPERTYPE_NOT_A_CLASS_OR_TRAIT = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory SUPERTYPE_INITIALIZED_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory CONSTRUCTOR_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED = SimpleDiagnosticFactory.create(WARNING); + SimpleDiagnosticFactory SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED = SimpleDiagnosticFactory.create(WARNING); SimpleDiagnosticFactory SUPERTYPE_APPEARS_TWICE = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory - FINAL_SUPERTYPE = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory FINAL_SUPERTYPE = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory1 ILLEGAL_SELECTOR = DiagnosticFactory1.create(ERROR); - SimpleDiagnosticFactory VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory BREAK_OR_CONTINUE_OUTSIDE_A_LOOP = SimpleDiagnosticFactory - .create(ERROR); + SimpleDiagnosticFactory VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory BREAK_OR_CONTINUE_OUTSIDE_A_LOOP = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory1 NOT_A_LOOP_LABEL = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 NOT_A_RETURN_LABEL = DiagnosticFactory1.create(ERROR); - SimpleDiagnosticFactory ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR = SimpleDiagnosticFactory - .create(ERROR); - SimpleDiagnosticFactory NULLABLE_SUPERTYPE = SimpleDiagnosticFactory - .create(ERROR, new PositioningStrategy() { - @NotNull - @Override - public List mark(@NotNull JetNullableType element) { - return markNode(element.getQuestionMarkNode()); - } - }); + SimpleDiagnosticFactory ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory NULLABLE_SUPERTYPE = SimpleDiagnosticFactory.create(ERROR, + new PositioningStrategy() { + @NotNull + @Override + public List mark(@NotNull JetNullableType element) { + return markNode(element.getQuestionMarkNode()); + } + }); DiagnosticFactory1 UNSAFE_CALL = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory AMBIGUOUS_LABEL = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory1 UNSUPPORTED = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 UNNECESSARY_SAFE_CALL = DiagnosticFactory1.create(WARNING); DiagnosticFactory1 UNNECESSARY_NOT_NULL_ASSERTION = DiagnosticFactory1.create(WARNING); - DiagnosticFactory2 NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER = DiagnosticFactory2.create(ERROR); + DiagnosticFactory2 NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER = + DiagnosticFactory2.create(ERROR); DiagnosticFactory2 AUTOCAST_IMPOSSIBLE = DiagnosticFactory2.create(ERROR); DiagnosticFactory2 TYPE_MISMATCH_IN_FOR_LOOP = DiagnosticFactory2.create(ERROR); DiagnosticFactory1 TYPE_MISMATCH_IN_CONDITION = DiagnosticFactory1.create(ERROR); - DiagnosticFactory2 TYPE_MISMATCH_IN_TUPLE_PATTERN = DiagnosticFactory2.create(ERROR); // TODO: message + DiagnosticFactory2 TYPE_MISMATCH_IN_TUPLE_PATTERN = DiagnosticFactory2.create(ERROR); DiagnosticFactory2 TYPE_MISMATCH_IN_BINDING_PATTERN = DiagnosticFactory2.create(ERROR); DiagnosticFactory2 INCOMPATIBLE_TYPES = DiagnosticFactory2.create(ERROR); - SimpleDiagnosticFactory - EXPECTED_CONDITION = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory EXPECTED_CONDITION = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory1 CANNOT_CHECK_FOR_ERASED = DiagnosticFactory1.create(ERROR); DiagnosticFactory2 UNCHECKED_CAST = DiagnosticFactory2.create(WARNING); - DiagnosticFactory3> INCONSISTENT_TYPE_PARAMETER_VALUES = + DiagnosticFactory3> + INCONSISTENT_TYPE_PARAMETER_VALUES = DiagnosticFactory3.create(ERROR); + + DiagnosticFactory3 EQUALITY_NOT_APPLICABLE = DiagnosticFactory3.create(ERROR); - DiagnosticFactory3 EQUALITY_NOT_APPLICABLE = DiagnosticFactory3.create(ERROR); - - DiagnosticFactory2 OVERRIDING_FINAL_MEMBER = DiagnosticFactory2.create(ERROR); - DiagnosticFactory3 CANNOT_WEAKEN_ACCESS_PRIVILEGE = DiagnosticFactory3.create(ERROR, - PositioningStrategies.POSITION_VISIBILITY_MODIFIER); - DiagnosticFactory3 CANNOT_CHANGE_ACCESS_PRIVILEGE = DiagnosticFactory3.create(ERROR, - PositioningStrategies.POSITION_VISIBILITY_MODIFIER); + DiagnosticFactory2 OVERRIDING_FINAL_MEMBER = + DiagnosticFactory2.create(ERROR); + DiagnosticFactory3 CANNOT_WEAKEN_ACCESS_PRIVILEGE = + DiagnosticFactory3.create(ERROR, PositioningStrategies.POSITION_VISIBILITY_MODIFIER); + DiagnosticFactory3 CANNOT_CHANGE_ACCESS_PRIVILEGE = + DiagnosticFactory3.create(ERROR, PositioningStrategies.POSITION_VISIBILITY_MODIFIER); DiagnosticFactory2 RETURN_TYPE_MISMATCH_ON_OVERRIDE = DiagnosticFactory2.create(ERROR, PositioningStrategies.POSITION_DECLARATION); - DiagnosticFactory2 VAR_OVERRIDDEN_BY_VAL = DiagnosticFactory2.create(ERROR, new PositioningStrategy() { - @NotNull - @Override - public List mark(@NotNull JetProperty property) { - return markNode(property.getValOrVarNode()); - } - }); - - DiagnosticFactory2 ABSTRACT_MEMBER_NOT_IMPLEMENTED = DiagnosticFactory2.create(ERROR); - - DiagnosticFactory2 MANY_IMPL_MEMBER_NOT_IMPLEMENTED = DiagnosticFactory2.create(ERROR); - - DiagnosticFactory2 CONFLICTING_OVERLOADS = DiagnosticFactory2.create(ERROR, new PositioningStrategy() { - @NotNull - @Override - public List mark(@NotNull JetDeclaration jetDeclaration) { - if (jetDeclaration instanceof JetNamedFunction) { - JetNamedFunction functionElement = (JetNamedFunction) jetDeclaration; - return markRange(new TextRange( - functionElement.getStartOfSignatureElement().getTextRange().getStartOffset(), - functionElement.getEndOfSignatureElement().getTextRange().getEndOffset() - )); - } - else if (jetDeclaration instanceof JetClass) { - // primary constructor - JetClass klass = (JetClass) jetDeclaration; - PsiElement nameAsDeclaration = klass.getNameIdentifier(); - if (nameAsDeclaration == null) { - return markRange(klass.getTextRange()); + DiagnosticFactory2 VAR_OVERRIDDEN_BY_VAL = + DiagnosticFactory2.create(ERROR, new PositioningStrategy() { + @NotNull + @Override + public List mark(@NotNull JetProperty property) { + return markNode(property.getValOrVarNode()); } - PsiElement primaryConstructorParameterList = klass.getPrimaryConstructorParameterList(); - if (primaryConstructorParameterList == null) { - return markRange(nameAsDeclaration.getTextRange()); + }); + + DiagnosticFactory2 ABSTRACT_MEMBER_NOT_IMPLEMENTED = + DiagnosticFactory2.create(ERROR); + + DiagnosticFactory2 MANY_IMPL_MEMBER_NOT_IMPLEMENTED = + DiagnosticFactory2.create(ERROR); + + DiagnosticFactory2 CONFLICTING_OVERLOADS = + DiagnosticFactory2.create(ERROR, new PositioningStrategy() { + @NotNull + @Override + public List mark(@NotNull JetDeclaration jetDeclaration) { + if (jetDeclaration instanceof JetNamedFunction) { + JetNamedFunction functionElement = (JetNamedFunction)jetDeclaration; + return markRange(new TextRange( + functionElement.getStartOfSignatureElement().getTextRange().getStartOffset(), + functionElement.getEndOfSignatureElement().getTextRange().getEndOffset() + )); + } + else if (jetDeclaration instanceof JetClass) { + // primary constructor + JetClass klass = (JetClass)jetDeclaration; + PsiElement nameAsDeclaration = klass.getNameIdentifier(); + if (nameAsDeclaration == null) { + return markRange(klass.getTextRange()); + } + PsiElement primaryConstructorParameterList = klass.getPrimaryConstructorParameterList(); + if (primaryConstructorParameterList == null) { + return markRange(nameAsDeclaration.getTextRange()); + } + return markRange(new TextRange( + nameAsDeclaration.getTextRange().getStartOffset(), + primaryConstructorParameterList.getTextRange().getEndOffset() + )); + } + else { + // safe way + return markRange(jetDeclaration.getTextRange()); + } } - return markRange(new TextRange( - nameAsDeclaration.getTextRange().getStartOffset(), - primaryConstructorParameterList.getTextRange().getEndOffset() - )); - } - else { - // safe way - return markRange(jetDeclaration.getTextRange()); - } - } - }); + }); DiagnosticFactory3 RESULT_TYPE_MISMATCH = DiagnosticFactory3.create(ERROR); @@ -482,18 +422,15 @@ public interface Errors { AmbiguousDescriptorDiagnosticFactory NONE_APPLICABLE = new AmbiguousDescriptorDiagnosticFactory(); DiagnosticFactory1 NO_VALUE_FOR_PARAMETER = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 MISSING_RECEIVER = DiagnosticFactory1.create(ERROR); - SimpleDiagnosticFactory - NO_RECEIVER_ADMITTED = SimpleDiagnosticFactory.create(ERROR); + SimpleDiagnosticFactory NO_RECEIVER_ADMITTED = SimpleDiagnosticFactory.create(ERROR); - SimpleDiagnosticFactory CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS = SimpleDiagnosticFactory - .create(ERROR); + SimpleDiagnosticFactory CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS = SimpleDiagnosticFactory.create(ERROR); DiagnosticFactory1 TYPE_INFERENCE_FAILED = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 WRONG_NUMBER_OF_TYPE_ARGUMENTS = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 UNRESOLVED_IDE_TEMPLATE = DiagnosticFactory1.create(ERROR); - SimpleDiagnosticFactory DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED = SimpleDiagnosticFactory - .create(WARNING); + SimpleDiagnosticFactory DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED = SimpleDiagnosticFactory.create(WARNING); DiagnosticFactory1 NOT_AN_ANNOTATION_CLASS = DiagnosticFactory1.create(ERROR); @@ -509,10 +446,11 @@ public interface Errors { try { Object value = field.get(null); if (value instanceof AbstractDiagnosticFactory) { - AbstractDiagnosticFactory factory = (AbstractDiagnosticFactory) value; + AbstractDiagnosticFactory factory = (AbstractDiagnosticFactory)value; factory.setName(field.getName()); } - } catch (IllegalAccessException e) { + } + catch (IllegalAccessException e) { throw new IllegalStateException(e); } } From be34ab252693ebfdbd710e61bcec0d79d0e7ecf7 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 15:17:50 +0400 Subject: [PATCH 025/147] Got rid of DiagnosticFactoryWithMessageFormat class. --- .../lang/diagnostics/DiagnosticFactory1.java | 2 +- .../lang/diagnostics/DiagnosticFactory2.java | 2 +- .../lang/diagnostics/DiagnosticFactory3.java | 2 +- .../DiagnosticFactoryWithMessageFormat.java | 30 ------------------- 4 files changed, 3 insertions(+), 33 deletions(-) delete mode 100644 compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactoryWithMessageFormat.java diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java index db3b08e5965..ebc4ebe4b23 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory1.java @@ -22,7 +22,7 @@ import org.jetbrains.annotations.NotNull; /** * @author svtk */ -public class DiagnosticFactory1 extends DiagnosticFactoryWithMessageFormat { +public class DiagnosticFactory1 extends DiagnosticFactoryWithPsiElement { @NotNull public ParametrizedDiagnostic on(@NotNull E element, @NotNull A argument) { return new DiagnosticWithParameters1(element, argument, this, severity); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java index 049b8824d38..5f63a87870b 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory2.java @@ -22,7 +22,7 @@ import org.jetbrains.annotations.NotNull; /** * @author abreslav */ -public class DiagnosticFactory2 extends DiagnosticFactoryWithMessageFormat { +public class DiagnosticFactory2 extends DiagnosticFactoryWithPsiElement { @NotNull public ParametrizedDiagnostic on(@NotNull E element, @NotNull A a, @NotNull B b) { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java index 678bb9b3dbf..2bb0deb23da 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactory3.java @@ -22,7 +22,7 @@ import org.jetbrains.annotations.NotNull; /** * @author svtk */ -public class DiagnosticFactory3 extends DiagnosticFactoryWithMessageFormat { +public class DiagnosticFactory3 extends DiagnosticFactoryWithPsiElement { protected DiagnosticFactory3(Severity severity, PositioningStrategy positioningStrategy) { super(severity, positioningStrategy); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactoryWithMessageFormat.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactoryWithMessageFormat.java deleted file mode 100644 index a04b6d59dce..00000000000 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticFactoryWithMessageFormat.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.lang.diagnostics; - -import com.intellij.psi.PsiElement; - -import java.text.MessageFormat; - -/** -* @author abreslav -*/ -public abstract class DiagnosticFactoryWithMessageFormat extends DiagnosticFactoryWithPsiElement { - protected DiagnosticFactoryWithMessageFormat(Severity severity, PositioningStrategy positioningStrategy) { - super(severity, positioningStrategy); - } -} From d1f35cfd9c1b1a864804f832a01e49227c2eafa2 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 15:16:14 +0400 Subject: [PATCH 026/147] Reformatted Errors, got rid of obsolete comments. --- .../lang/diagnostics/rendering/DefaultDiagnosticRenderer.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java index 1e1b586397c..7989922ec68 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java @@ -75,9 +75,7 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer @Override public String render(@NotNull Collection tokens) { StringBuilder sb = new StringBuilder(); - for (Iterator iterator = - tokens.iterator(); - iterator.hasNext(); ) { + for (Iterator iterator = tokens.iterator(); iterator.hasNext(); ) { JetKeywordToken modifier = iterator.next(); sb.append(modifier.getValue()); if (iterator.hasNext()) { From 545e559d5b4bbcac0311dc13df0670b168132dc5 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 15:46:28 +0400 Subject: [PATCH 027/147] Made UnresolvedReferenceDiagnostic subtype of DiagnosticWithParameters1 to simplify diagnostic renderer. --- .../UnresolvedReferenceDiagnostic.java | 29 ++----------------- .../UnresolvedReferenceDiagnosticFactory.java | 21 ++++++++++++-- .../rendering/DefaultDiagnosticRenderer.java | 18 ++---------- 3 files changed, 23 insertions(+), 45 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java index 938cb898250..ee443e2051c 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java @@ -16,38 +16,15 @@ package org.jetbrains.jet.lang.diagnostics; -import com.intellij.openapi.util.TextRange; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.lang.psi.JetArrayAccessExpression; import org.jetbrains.jet.lang.psi.JetReferenceExpression; -import java.util.Collections; -import java.util.List; - -import static org.jetbrains.jet.lang.diagnostics.Severity.ERROR; - /** * @author abreslav */ -public class UnresolvedReferenceDiagnostic extends AbstractDiagnostic { - @NotNull - @Override - public UnresolvedReferenceDiagnosticFactory getFactory() { - return (UnresolvedReferenceDiagnosticFactory)super.getFactory(); - } - +public class UnresolvedReferenceDiagnostic extends DiagnosticWithParameters1 { public UnresolvedReferenceDiagnostic(@NotNull JetReferenceExpression referenceExpression, - @NotNull UnresolvedReferenceDiagnosticFactory factory) { - super(referenceExpression, factory, ERROR); - } - - @NotNull - @Override - public List getTextRanges() { - JetReferenceExpression element = getPsiElement(); - if (element instanceof JetArrayAccessExpression) { - return ((JetArrayAccessExpression) element).getBracketRanges(); - } - return Collections.singletonList(element.getTextRange()); + @NotNull UnresolvedReferenceDiagnosticFactory factory, @NotNull Severity severity) { + super(referenceExpression, referenceExpression.getText(), factory, severity); } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java index 4aee43e3422..d3647c31363 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java @@ -16,18 +16,33 @@ package org.jetbrains.jet.lang.diagnostics; +import com.intellij.openapi.util.TextRange; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.psi.JetArrayAccessExpression; import org.jetbrains.jet.lang.psi.JetReferenceExpression; +import java.util.Collections; +import java.util.List; + /** * @author abreslav */ -public class UnresolvedReferenceDiagnosticFactory extends AbstractDiagnosticFactory { - private UnresolvedReferenceDiagnosticFactory() { +public class UnresolvedReferenceDiagnosticFactory extends DiagnosticFactory1 { + public UnresolvedReferenceDiagnosticFactory() { + super(Severity.ERROR, new PositioningStrategy() { + @NotNull + @Override + public List mark(@NotNull JetReferenceExpression element) { + if (element instanceof JetArrayAccessExpression) { + return ((JetArrayAccessExpression) element).getBracketRanges(); + } + return Collections.singletonList(element.getTextRange()); + } + }); } public UnresolvedReferenceDiagnostic on(@NotNull JetReferenceExpression reference) { - return new UnresolvedReferenceDiagnostic(reference, this); + return new UnresolvedReferenceDiagnostic(reference, this, severity); } public static UnresolvedReferenceDiagnosticFactory create() { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java index 7989922ec68..abcc949afbb 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java @@ -53,7 +53,7 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer } })); - map.put(UNRESOLVED_REFERENCE, new UnresolvedReferenceDiagnosticRenderer("Unresolved reference: ")); + map.put(UNRESOLVED_REFERENCE, new DiagnosticWithParameters1Renderer("Unresolved reference: {0}", TO_STRING)); map.put(INVISIBLE_REFERENCE, new DiagnosticWithParameters2Renderer("Cannot access ''{0}'' in ''{1}''", @@ -124,7 +124,7 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer map.put(MIXING_NAMED_AND_POSITIONED_ARGUMENTS, new SimpleDiagnosticRenderer("Mixing named and positioned arguments in not allowed")); map.put(ARGUMENT_PASSED_TWICE, new SimpleDiagnosticRenderer("An argument is already passed for this parameter")); - map.put(NAMED_PARAMETER_NOT_FOUND, new UnresolvedReferenceDiagnosticRenderer("Cannot find a parameter with this name: ")); + map.put(NAMED_PARAMETER_NOT_FOUND, new DiagnosticWithParameters1Renderer("Cannot find a parameter with this name: {0}", TO_STRING)); map.put(VARARG_OUTSIDE_PARENTHESES, new SimpleDiagnosticRenderer("Passing value as a vararg is only allowed inside a parenthesized argument list")); map.put(NON_VARARG_SPREAD, new SimpleDiagnosticRenderer("The spread operator (*foo) may only be applied in a vararg position")); @@ -529,20 +529,6 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer } } - private static class UnresolvedReferenceDiagnosticRenderer implements DiagnosticRenderer { - private String messagePrefix; - - private UnresolvedReferenceDiagnosticRenderer(@NotNull String messagePrefix) { - this.messagePrefix = messagePrefix; - } - - @NotNull - @Override - public String render(@NotNull UnresolvedReferenceDiagnostic diagnostic) { - return messagePrefix + diagnostic.getPsiElement().getText(); - } - } - private static class AmbiguousDescriptorDiagnosticRenderer extends DiagnosticWithParameters1Renderer>> { private AmbiguousDescriptorDiagnosticRenderer(@NotNull String message) { From 9f3f309625088715fae1c42d6226c85c7cbbbf30 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 15:50:57 +0400 Subject: [PATCH 028/147] Made RedeclarationDiagnostic simpler. --- .../diagnostics/RedeclarationDiagnostic.java | 49 +++++++++---------- .../RedeclarationDiagnosticFactory.java | 7 +-- 2 files changed, 23 insertions(+), 33 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java index e3080ba18e5..2e04e3eff8b 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java @@ -27,36 +27,31 @@ import java.util.List; /** * @author abreslav */ -public interface RedeclarationDiagnostic extends Diagnostic { - String getName(); +public class RedeclarationDiagnostic extends AbstractDiagnostic { + private String name; - class SimpleRedeclarationDiagnostic extends AbstractDiagnostic implements RedeclarationDiagnostic { - private String name; - - public SimpleRedeclarationDiagnostic(@NotNull PsiElement psiElement, @NotNull String name, RedeclarationDiagnosticFactory factory) { - super(psiElement, factory, factory.severity); - this.name = name; - } - - @NotNull - @Override - public RedeclarationDiagnosticFactory getFactory() { - return (RedeclarationDiagnosticFactory)super.getFactory(); - } - - @Override - public String getName() { - return name; - } - - @NotNull - @Override - public List getTextRanges() { - return POSITION_REDECLARATION.mark(getPsiElement()); - } + public RedeclarationDiagnostic(@NotNull PsiElement psiElement, @NotNull String name, RedeclarationDiagnosticFactory factory) { + super(psiElement, factory, factory.severity); + this.name = name; } - PositioningStrategy POSITION_REDECLARATION = new PositioningStrategy() { + @NotNull + @Override + public RedeclarationDiagnosticFactory getFactory() { + return (RedeclarationDiagnosticFactory)super.getFactory(); + } + + public String getName() { + return name; + } + + @NotNull + @Override + public List getTextRanges() { + return POSITION_REDECLARATION.mark(getPsiElement()); + } + + private static final PositioningStrategy POSITION_REDECLARATION = new PositioningStrategy() { @NotNull @Override public List mark(@NotNull PsiElement element) { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java index 59d138f52c4..a651060b00d 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java @@ -30,11 +30,6 @@ public class RedeclarationDiagnosticFactory extends AbstractDiagnosticFactory { } public RedeclarationDiagnostic on(@NotNull PsiElement duplicatingElement, @NotNull String name) { - return new RedeclarationDiagnostic.SimpleRedeclarationDiagnostic(duplicatingElement, name, this); - } - - @Override - public String toString() { - return getName(); + return new RedeclarationDiagnostic(duplicatingElement, name, this); } } From 4d05b6757c180237eba4ddb836969235c1148793 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 16:07:47 +0400 Subject: [PATCH 029/147] Made RedeclarationDiagnostic subtype of DiagnosticWithParameters1 to simplify diagnostic renderer. --- .../diagnostics/RedeclarationDiagnostic.java | 47 ++----------------- .../RedeclarationDiagnosticFactory.java | 32 +++++++++++-- .../rendering/DefaultDiagnosticRenderer.java | 18 +------ 3 files changed, 34 insertions(+), 63 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java index 2e04e3eff8b..093a90f6451 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java @@ -27,48 +27,9 @@ import java.util.List; /** * @author abreslav */ -public class RedeclarationDiagnostic extends AbstractDiagnostic { - private String name; - - public RedeclarationDiagnostic(@NotNull PsiElement psiElement, @NotNull String name, RedeclarationDiagnosticFactory factory) { - super(psiElement, factory, factory.severity); - this.name = name; +public class RedeclarationDiagnostic extends DiagnosticWithParameters1 { + public RedeclarationDiagnostic(@NotNull PsiElement psiElement, @NotNull String name, + @NotNull RedeclarationDiagnosticFactory factory, @NotNull Severity severity) { + super(psiElement, name, factory, severity); } - - @NotNull - @Override - public RedeclarationDiagnosticFactory getFactory() { - return (RedeclarationDiagnosticFactory)super.getFactory(); - } - - public String getName() { - return name; - } - - @NotNull - @Override - public List getTextRanges() { - return POSITION_REDECLARATION.mark(getPsiElement()); - } - - private static final PositioningStrategy POSITION_REDECLARATION = new PositioningStrategy() { - @NotNull - @Override - public List mark(@NotNull PsiElement element) { - if (element instanceof JetNamedDeclaration) { - PsiElement nameIdentifier = ((JetNamedDeclaration) element).getNameIdentifier(); - if (nameIdentifier != null) { - return markElement(nameIdentifier); - } - } - else if (element instanceof JetFile) { - JetFile file = (JetFile) element; - PsiElement nameIdentifier = file.getNamespaceHeader().getNameIdentifier(); - if (nameIdentifier != null) { - return markElement(nameIdentifier); - } - } - return markElement(element); - } - }; } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java index a651060b00d..bcf0598504f 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java @@ -16,20 +16,44 @@ package org.jetbrains.jet.lang.diagnostics; +import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.psi.JetNamedDeclaration; + +import java.util.List; /** * @author abreslav */ -public class RedeclarationDiagnosticFactory extends AbstractDiagnosticFactory { - final Severity severity; +public class RedeclarationDiagnosticFactory extends DiagnosticFactory1 { + private static final PositioningStrategy POSITION_REDECLARATION = new PositioningStrategy() { + @NotNull + @Override + public List mark(@NotNull PsiElement element) { + if (element instanceof JetNamedDeclaration) { + PsiElement nameIdentifier = ((JetNamedDeclaration) element).getNameIdentifier(); + if (nameIdentifier != null) { + return markElement(nameIdentifier); + } + } + else if (element instanceof JetFile) { + JetFile file = (JetFile) element; + PsiElement nameIdentifier = file.getNamespaceHeader().getNameIdentifier(); + if (nameIdentifier != null) { + return markElement(nameIdentifier); + } + } + return markElement(element); + } + }; public RedeclarationDiagnosticFactory(Severity severity) { - this.severity = severity; + super(severity, POSITION_REDECLARATION); } public RedeclarationDiagnostic on(@NotNull PsiElement duplicatingElement, @NotNull String name) { - return new RedeclarationDiagnostic(duplicatingElement, name, this); + return new RedeclarationDiagnostic(duplicatingElement, name, this, severity); } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java index abcc949afbb..43fce44d057 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java @@ -62,8 +62,8 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer new DiagnosticWithParameters2Renderer("Cannot access ''{0}'' in ''{1}''", NAME, NAME)); - map.put(REDECLARATION, new RedeclarationDiagnosticRenderer("Redeclaration: ")); - map.put(NAME_SHADOWING, new RedeclarationDiagnosticRenderer("Name shadowed: ")); + map.put(REDECLARATION, new DiagnosticWithParameters1Renderer("Redeclaration: {0}", NAME)); + map.put(NAME_SHADOWING, new DiagnosticWithParameters1Renderer("Name shadowed: {0}", NAME)); map.put(TYPE_MISMATCH, new DiagnosticWithParameters2Renderer("Type mismatch: inferred type is {1} but {0} was expected", @@ -515,20 +515,6 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer return renderer.render(diagnostic); } - private static class RedeclarationDiagnosticRenderer implements DiagnosticRenderer { - private String messagePrefix; - - private RedeclarationDiagnosticRenderer(@NotNull String messagePrefix) { - this.messagePrefix = messagePrefix; - } - - @NotNull - @Override - public String render(@NotNull RedeclarationDiagnostic diagnostic) { - return messagePrefix + diagnostic.getName(); - } - } - private static class AmbiguousDescriptorDiagnosticRenderer extends DiagnosticWithParameters1Renderer>> { private AmbiguousDescriptorDiagnosticRenderer(@NotNull String message) { From 1501883ded2836c19de67adb510420a2e3aa392b Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 16:19:16 +0400 Subject: [PATCH 030/147] Removed RedeclarationDiagnostic class, since it's not very useful. --- .../diagnostics/RedeclarationDiagnostic.java | 35 ------------------- .../RedeclarationDiagnosticFactory.java | 4 --- .../jet/plugin/highlighter/JetPsiChecker.java | 13 ++++--- 3 files changed, 6 insertions(+), 46 deletions(-) delete mode 100644 compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java deleted file mode 100644 index 093a90f6451..00000000000 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnostic.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.lang.diagnostics; - -import com.intellij.openapi.util.TextRange; -import com.intellij.psi.PsiElement; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.psi.JetNamedDeclaration; - -import java.util.List; - -/** - * @author abreslav - */ -public class RedeclarationDiagnostic extends DiagnosticWithParameters1 { - public RedeclarationDiagnostic(@NotNull PsiElement psiElement, @NotNull String name, - @NotNull RedeclarationDiagnosticFactory factory, @NotNull Severity severity) { - super(psiElement, name, factory, severity); - } -} diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java index bcf0598504f..023a7e8c077 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/RedeclarationDiagnosticFactory.java @@ -52,8 +52,4 @@ public class RedeclarationDiagnosticFactory extends DiagnosticFactory1 redeclarations, - @NotNull RedeclarationDiagnostic diagnostic, + @NotNull Diagnostic redeclarationDiagnostic, @NotNull AnnotationHolder holder) { - if (!redeclarations.add(diagnostic.getPsiElement())) return null; - List textRanges = diagnostic.getTextRanges(); + if (!redeclarations.add(redeclarationDiagnostic.getPsiElement())) return null; + List textRanges = redeclarationDiagnostic.getTextRanges(); if (textRanges.isEmpty()) return null; - return holder.createErrorAnnotation(textRanges.get(0), getMessage(diagnostic)); + return holder.createErrorAnnotation(textRanges.get(0), getMessage(redeclarationDiagnostic)); } } From dd3c9146cd3e145f6c5f4c1e30cc941ccc17e2b8 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 16:30:11 +0400 Subject: [PATCH 031/147] Removed UnresolvedReferenceDiagnostic class, since it's not very useful. --- .../UnresolvedReferenceDiagnostic.java | 30 ------------------- .../UnresolvedReferenceDiagnosticFactory.java | 4 +-- .../tests/org/jetbrains/jet/JetTestUtils.java | 7 ++--- .../jet/resolve/ExpectedResolveData.java | 7 ++--- .../highlighter/DebugInfoAnnotator.java | 6 ++-- .../jet/plugin/highlighter/JetPsiChecker.java | 5 ++-- 6 files changed, 13 insertions(+), 46 deletions(-) delete mode 100644 compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java deleted file mode 100644 index ee443e2051c..00000000000 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnostic.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.lang.diagnostics; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.lang.psi.JetReferenceExpression; - -/** - * @author abreslav - */ -public class UnresolvedReferenceDiagnostic extends DiagnosticWithParameters1 { - public UnresolvedReferenceDiagnostic(@NotNull JetReferenceExpression referenceExpression, - @NotNull UnresolvedReferenceDiagnosticFactory factory, @NotNull Severity severity) { - super(referenceExpression, referenceExpression.getText(), factory, severity); - } -} diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java index d3647c31363..fd80049556d 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/UnresolvedReferenceDiagnosticFactory.java @@ -41,8 +41,8 @@ public class UnresolvedReferenceDiagnosticFactory extends DiagnosticFactory1 on(@NotNull JetReferenceExpression reference) { + return new DiagnosticWithParameters1(reference, reference.getText(), this, severity); } public static UnresolvedReferenceDiagnosticFactory create() { diff --git a/compiler/tests/org/jetbrains/jet/JetTestUtils.java b/compiler/tests/org/jetbrains/jet/JetTestUtils.java index a12c4693120..de37982408a 100644 --- a/compiler/tests/org/jetbrains/jet/JetTestUtils.java +++ b/compiler/tests/org/jetbrains/jet/JetTestUtils.java @@ -26,10 +26,10 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.compiler.JetCoreEnvironment; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; +import org.jetbrains.jet.lang.diagnostics.UnresolvedReferenceDiagnosticFactory; import org.jetbrains.jet.lang.diagnostics.rendering.DefaultDiagnosticRenderer; import org.jetbrains.jet.lang.diagnostics.Diagnostic; import org.jetbrains.jet.lang.diagnostics.Severity; -import org.jetbrains.jet.lang.diagnostics.UnresolvedReferenceDiagnostic; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingTrace; @@ -102,9 +102,8 @@ public class JetTestUtils { @Override public void report(@NotNull Diagnostic diagnostic) { - if (diagnostic instanceof UnresolvedReferenceDiagnostic) { - UnresolvedReferenceDiagnostic unresolvedReferenceDiagnostic = (UnresolvedReferenceDiagnostic)diagnostic; - throw new IllegalStateException("Unresolved: " + unresolvedReferenceDiagnostic.getPsiElement().getText()); + if (diagnostic.getFactory() instanceof UnresolvedReferenceDiagnosticFactory) { + throw new IllegalStateException("Unresolved: " + diagnostic.getPsiElement().getText()); } } }; diff --git a/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java b/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java index 4ff2c59ebfb..bdca4724f4f 100644 --- a/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java +++ b/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java @@ -31,7 +31,7 @@ import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.diagnostics.Diagnostic; import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils; -import org.jetbrains.jet.lang.diagnostics.UnresolvedReferenceDiagnostic; +import org.jetbrains.jet.lang.diagnostics.UnresolvedReferenceDiagnosticFactory; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingContextUtils; @@ -146,9 +146,8 @@ public abstract class ExpectedResolveData { CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR)); BindingContext bindingContext = analyzeExhaust.getBindingContext(); for (Diagnostic diagnostic : bindingContext.getDiagnostics()) { - if (diagnostic instanceof UnresolvedReferenceDiagnostic) { - UnresolvedReferenceDiagnostic unresolvedReferenceDiagnostic = (UnresolvedReferenceDiagnostic) diagnostic; - unresolvedReferences.add(unresolvedReferenceDiagnostic.getPsiElement()); + if (diagnostic.getFactory() instanceof UnresolvedReferenceDiagnosticFactory) { + unresolvedReferences.add(diagnostic.getPsiElement()); } } diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/DebugInfoAnnotator.java b/idea/src/org/jetbrains/jet/plugin/highlighter/DebugInfoAnnotator.java index 9c873a73df0..0421c720cc7 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/DebugInfoAnnotator.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/DebugInfoAnnotator.java @@ -29,7 +29,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.JetNodeTypes; import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.diagnostics.Diagnostic; -import org.jetbrains.jet.lang.diagnostics.UnresolvedReferenceDiagnostic; +import org.jetbrains.jet.lang.diagnostics.UnresolvedReferenceDiagnosticFactory; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.types.ErrorUtils; @@ -72,8 +72,8 @@ public class DebugInfoAnnotator implements Annotator { final Set unresolvedReferences = Sets.newHashSet(); for (Diagnostic diagnostic : bindingContext.getDiagnostics()) { - if (diagnostic instanceof UnresolvedReferenceDiagnostic) { - unresolvedReferences.add(((UnresolvedReferenceDiagnostic) diagnostic).getPsiElement()); + if (diagnostic.getFactory() instanceof UnresolvedReferenceDiagnosticFactory) { + unresolvedReferences.add((JetReferenceExpression)diagnostic.getPsiElement()); } } diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java b/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java index e024c4a2813..ed012e03db0 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java @@ -146,9 +146,8 @@ public class JetPsiChecker implements Annotator { if (diagnostic.getFactory() == Errors.UNRESOLVED_IDE_TEMPLATE) { return; } - if (diagnostic instanceof UnresolvedReferenceDiagnostic) { - UnresolvedReferenceDiagnostic unresolvedReferenceDiagnostic = (UnresolvedReferenceDiagnostic)diagnostic; - JetReferenceExpression referenceExpression = unresolvedReferenceDiagnostic.getPsiElement(); + if (diagnostic.getFactory() instanceof UnresolvedReferenceDiagnosticFactory) { + JetReferenceExpression referenceExpression = (JetReferenceExpression)diagnostic.getPsiElement(); PsiReference reference = referenceExpression.getReference(); if (reference instanceof MultiRangeReference) { MultiRangeReference mrr = (MultiRangeReference)reference; From 13ac89a591c4c750317680eb8080bf73db653fff Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 16:38:39 +0400 Subject: [PATCH 032/147] Fixed bad error messages for ABSTRACT_MODIFIER_IN_TRAIT and OPEN_MODIFIER_IN_TRAIT. --- .../lang/diagnostics/rendering/DefaultDiagnosticRenderer.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java index 43fce44d057..305e4e74dc8 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java @@ -91,8 +91,8 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer map.put(REDUNDANT_MODIFIER, new DiagnosticWithParameters2Renderer("Modifier {0} is redundant because {1} is present", TO_STRING, TO_STRING)); - map.put(ABSTRACT_MODIFIER_IN_TRAIT, new SimpleDiagnosticRenderer("Modifier ''{0}'' is redundant in trait")); - map.put(OPEN_MODIFIER_IN_TRAIT, new SimpleDiagnosticRenderer("Modifier ''{0}'' is redundant in trait")); + map.put(ABSTRACT_MODIFIER_IN_TRAIT, new SimpleDiagnosticRenderer("Modifier ''abstract'' is redundant in trait")); + map.put(OPEN_MODIFIER_IN_TRAIT, new SimpleDiagnosticRenderer("Modifier ''open'' is redundant in trait")); map.put(REDUNDANT_MODIFIER_IN_GETTER, new SimpleDiagnosticRenderer("Visibility modifiers are redundant in getter")); map.put(TRAIT_CAN_NOT_BE_FINAL, new SimpleDiagnosticRenderer("Trait can not be final")); map.put(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM, new SimpleDiagnosticRenderer( From f559369f54d8cce81067f4693b0e6d4d3d559201 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 17:50:15 +0400 Subject: [PATCH 033/147] Simplified code in DefaultDiagnosticRenderer. Replaced direct renderer creation with calling generic "put" method: type arguments are not needed, descriptor renderer type specification is not needed. --- .../rendering/DefaultDiagnosticRenderer.java | 799 ++++++++---------- 1 file changed, 354 insertions(+), 445 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java index 305e4e74dc8..746ce87d618 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java @@ -16,12 +16,14 @@ package org.jetbrains.jet.lang.diagnostics.rendering; +import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.lang.descriptors.*; +import org.jetbrains.jet.lang.descriptors.CallableDescriptor; import org.jetbrains.jet.lang.diagnostics.*; -import org.jetbrains.jet.lang.psi.*; +import org.jetbrains.jet.lang.psi.JetExpression; +import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; +import org.jetbrains.jet.lang.psi.JetTypeConstraint; import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; -import org.jetbrains.jet.lang.resolve.calls.inference.SolutionStatus; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lexer.JetKeywordToken; import org.jetbrains.jet.resolve.DescriptorRenderer; @@ -40,468 +42,392 @@ import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.*; */ public class DefaultDiagnosticRenderer implements DiagnosticRenderer { public static final DefaultDiagnosticRenderer INSTANCE = new DefaultDiagnosticRenderer(); + private static final Renderer>> AMBIGUOUS_CALLS = + new Renderer>>() { + @NotNull + @Override + public String render(@NotNull Collection> argument) { + StringBuilder stringBuilder = new StringBuilder("\n"); + for (ResolvedCall call : argument) { + stringBuilder.append(DescriptorRenderer.TEXT.render(call.getResultingDescriptor())).append("\n"); + } + return stringBuilder.toString(); + } + }; private final Map> map = new HashMap>(); - private DefaultDiagnosticRenderer() { - map.put(EXCEPTION_WHILE_ANALYZING, new DiagnosticWithParameters1Renderer("{0}", new Renderer() { + protected final void put(SimpleDiagnosticFactory factory, String message) { + map.put(factory, new SimpleDiagnosticRenderer(message)); + } + + protected final void put(DiagnosticFactory1 factory, String message, Renderer rendererA) { + map.put(factory, new DiagnosticWithParameters1Renderer(message, rendererA)); + } + + protected final void put(DiagnosticFactory2 factory, + String message, + Renderer rendererA, + Renderer rendererB) { + map.put(factory, new DiagnosticWithParameters2Renderer(message, rendererA, rendererB)); + } + + protected final void put(DiagnosticFactory3 factory, + String message, + Renderer rendererA, + Renderer rendererB, + Renderer rendererC) { + map.put(factory, new DiagnosticWithParameters3Renderer(message, rendererA, rendererB, rendererC)); + } + + protected DefaultDiagnosticRenderer() { + put(EXCEPTION_WHILE_ANALYZING, "{0}", new Renderer() { @NotNull @Override public String render(@NotNull Throwable e) { return e.getClass().getSimpleName() + ": " + e.getMessage(); } - })); + }); - map.put(UNRESOLVED_REFERENCE, new DiagnosticWithParameters1Renderer("Unresolved reference: {0}", TO_STRING)); + put(UNRESOLVED_REFERENCE, "Unresolved reference: {0}", TO_STRING); - map.put(INVISIBLE_REFERENCE, - new DiagnosticWithParameters2Renderer("Cannot access ''{0}'' in ''{1}''", - NAME, NAME)); - map.put(INVISIBLE_MEMBER, - new DiagnosticWithParameters2Renderer("Cannot access ''{0}'' in ''{1}''", - NAME, NAME)); + put(INVISIBLE_REFERENCE, "Cannot access ''{0}'' in ''{1}''", NAME, NAME); + put(INVISIBLE_MEMBER, "Cannot access ''{0}'' in ''{1}''", NAME, NAME); - map.put(REDECLARATION, new DiagnosticWithParameters1Renderer("Redeclaration: {0}", NAME)); - map.put(NAME_SHADOWING, new DiagnosticWithParameters1Renderer("Name shadowed: {0}", NAME)); + put(REDECLARATION, "Redeclaration: {0}", NAME); + put(NAME_SHADOWING, "Name shadowed: {0}", NAME); - map.put(TYPE_MISMATCH, - new DiagnosticWithParameters2Renderer("Type mismatch: inferred type is {1} but {0} was expected", - RENDER_TYPE, RENDER_TYPE)); - map.put(INCOMPATIBLE_MODIFIERS, - new DiagnosticWithParameters1Renderer>("Incompatible modifiers: ''{0}''", - new Renderer>() { - @NotNull - @Override - public String render(@NotNull Collection tokens) { - StringBuilder sb = new StringBuilder(); - for (Iterator iterator = tokens.iterator(); iterator.hasNext(); ) { - JetKeywordToken modifier = iterator.next(); - sb.append(modifier.getValue()); - if (iterator.hasNext()) { - sb.append(" "); - } - } - return sb.toString(); - } - } - )); - map.put(ILLEGAL_MODIFIER, new DiagnosticWithParameters1Renderer("Illegal modifier ''{0}''", TO_STRING)); - - map.put(REDUNDANT_MODIFIER, - new DiagnosticWithParameters2Renderer("Modifier {0} is redundant because {1} is present", - TO_STRING, TO_STRING)); - map.put(ABSTRACT_MODIFIER_IN_TRAIT, new SimpleDiagnosticRenderer("Modifier ''abstract'' is redundant in trait")); - map.put(OPEN_MODIFIER_IN_TRAIT, new SimpleDiagnosticRenderer("Modifier ''open'' is redundant in trait")); - map.put(REDUNDANT_MODIFIER_IN_GETTER, new SimpleDiagnosticRenderer("Visibility modifiers are redundant in getter")); - map.put(TRAIT_CAN_NOT_BE_FINAL, new SimpleDiagnosticRenderer("Trait can not be final")); - map.put(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM, new SimpleDiagnosticRenderer( - "Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly")); // TODO: message - map.put(RETURN_NOT_ALLOWED, new SimpleDiagnosticRenderer("'return' is not allowed here")); - map.put(PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE, - new SimpleDiagnosticRenderer("Projections are not allowed for immediate arguments of a supertype")); - map.put(LABEL_NAME_CLASH, new SimpleDiagnosticRenderer("There is more than one label with such a name in this scope")); - map.put(EXPRESSION_EXPECTED_NAMESPACE_FOUND, new SimpleDiagnosticRenderer("Expression expected, but a namespace name found")); - - map.put(CANNOT_IMPORT_FROM_ELEMENT, - new DiagnosticWithParameters1Renderer("Cannot import from ''{0}''", NAME)); - map.put(CANNOT_BE_IMPORTED, new DiagnosticWithParameters1Renderer( - "Cannot import ''{0}'', functions and properties can be imported only from packages", NAME)); - map.put(USELESS_HIDDEN_IMPORT, new SimpleDiagnosticRenderer("Useless import, it is hidden further")); - map.put(USELESS_SIMPLE_IMPORT, new SimpleDiagnosticRenderer("Useless import, does nothing")); - - map.put(CANNOT_INFER_PARAMETER_TYPE, new SimpleDiagnosticRenderer( - "Cannot infer a type for this parameter. To specify it explicitly use the {(p : Type) => ...} notation")); - - map.put(NO_BACKING_FIELD_ABSTRACT_PROPERTY, - new SimpleDiagnosticRenderer("This property doesn't have a backing field, because it's abstract")); - map.put(NO_BACKING_FIELD_CUSTOM_ACCESSORS, new SimpleDiagnosticRenderer( - "This property doesn't have a backing field, because it has custom accessors without reference to the backing field")); - map.put(INACCESSIBLE_BACKING_FIELD, new SimpleDiagnosticRenderer("The backing field is not accessible here")); - map.put(NOT_PROPERTY_BACKING_FIELD, - new SimpleDiagnosticRenderer("The referenced variable is not a property and doesn't have backing field")); - - map.put(MIXING_NAMED_AND_POSITIONED_ARGUMENTS, - new SimpleDiagnosticRenderer("Mixing named and positioned arguments in not allowed")); - map.put(ARGUMENT_PASSED_TWICE, new SimpleDiagnosticRenderer("An argument is already passed for this parameter")); - map.put(NAMED_PARAMETER_NOT_FOUND, new DiagnosticWithParameters1Renderer("Cannot find a parameter with this name: {0}", TO_STRING)); - map.put(VARARG_OUTSIDE_PARENTHESES, - new SimpleDiagnosticRenderer("Passing value as a vararg is only allowed inside a parenthesized argument list")); - map.put(NON_VARARG_SPREAD, new SimpleDiagnosticRenderer("The spread operator (*foo) may only be applied in a vararg position")); - - map.put(MANY_FUNCTION_LITERAL_ARGUMENTS, - new SimpleDiagnosticRenderer("Only one function literal is allowed outside a parenthesized argument list")); - map.put(PROPERTY_WITH_NO_TYPE_NO_INITIALIZER, - new SimpleDiagnosticRenderer("This property must either have a type annotation or be initialized")); - - map.put(ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS, - new SimpleDiagnosticRenderer("This property cannot be declared abstract")); - map.put(ABSTRACT_PROPERTY_NOT_IN_CLASS, - new SimpleDiagnosticRenderer("A property may be abstract only when defined in a class or trait")); - map.put(ABSTRACT_PROPERTY_WITH_INITIALIZER, new SimpleDiagnosticRenderer("Property with initializer cannot be abstract")); - map.put(ABSTRACT_PROPERTY_WITH_GETTER, new SimpleDiagnosticRenderer("Property with getter implementation cannot be abstract")); - map.put(ABSTRACT_PROPERTY_WITH_SETTER, new SimpleDiagnosticRenderer("Property with setter implementation cannot be abstract")); - - map.put(PACKAGE_MEMBER_CANNOT_BE_PROTECTED, new SimpleDiagnosticRenderer("Package member cannot be protected")); - - map.put(GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY, - new SimpleDiagnosticRenderer("Getter visibility must be the same as property visibility")); - map.put(BACKING_FIELD_IN_TRAIT, new SimpleDiagnosticRenderer("Property in a trait cannot have a backing field")); - map.put(MUST_BE_INITIALIZED, new SimpleDiagnosticRenderer("Property must be initialized")); - map.put(MUST_BE_INITIALIZED_OR_BE_ABSTRACT, new SimpleDiagnosticRenderer("Property must be initialized or be abstract")); - map.put(PROPERTY_INITIALIZER_IN_TRAIT, new SimpleDiagnosticRenderer("Property initializers are not allowed in traits")); - map.put(PROPERTY_INITIALIZER_NO_BACKING_FIELD, - new SimpleDiagnosticRenderer("Initializer is not allowed here because this property has no backing field")); - map.put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, - new DiagnosticWithParameters3Renderer("Abstract property {0} in non-abstract class {1}", - TO_STRING, TO_STRING, TO_STRING)); - map.put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, - new DiagnosticWithParameters3Renderer("Abstract function {0} in non-abstract class {1}", - TO_STRING, TO_STRING, TO_STRING)); - map.put(ABSTRACT_FUNCTION_WITH_BODY, - new DiagnosticWithParameters1Renderer("A function {0} with body cannot be abstract", TO_STRING)); - map.put(NON_ABSTRACT_FUNCTION_WITH_NO_BODY, - new DiagnosticWithParameters1Renderer("Method {0} without a body must be abstract", TO_STRING)); - map.put(NON_MEMBER_ABSTRACT_FUNCTION, new DiagnosticWithParameters1Renderer( - "Function {0} is not a class or trait member and cannot be abstract", TO_STRING)); - - map.put(NON_MEMBER_FUNCTION_NO_BODY, - new DiagnosticWithParameters1Renderer("Function {0} must have a body", TO_STRING)); - map.put(NON_FINAL_MEMBER_IN_FINAL_CLASS, new SimpleDiagnosticRenderer("Non final member in a final class")); - - map.put(PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE, new SimpleDiagnosticRenderer("Public or protected member should specify a type")); - - map.put(PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT, new SimpleDiagnosticRenderer( - "Projections are not allowed on type arguments of functions and properties")); // TODO : better positioning - map.put(SUPERTYPE_NOT_INITIALIZED, new SimpleDiagnosticRenderer("This type has a constructor, and thus must be initialized here")); - map.put(SUPERTYPE_NOT_INITIALIZED_DEFAULT, new SimpleDiagnosticRenderer("Constructor invocation should be explicitly specified")); - map.put(SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY, - new SimpleDiagnosticRenderer("A secondary constructor may appear only in a class that has a primary constructor")); - map.put(SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST, - new SimpleDiagnosticRenderer("Secondary constructors must have an initializer list")); - map.put(BY_IN_SECONDARY_CONSTRUCTOR, new SimpleDiagnosticRenderer("'by'-clause is only supported for primary constructors")); - map.put(INITIALIZER_WITH_NO_ARGUMENTS, new SimpleDiagnosticRenderer("Constructor arguments required")); - map.put(MANY_CALLS_TO_THIS, new SimpleDiagnosticRenderer("Only one call to 'this(...)' is allowed")); - map.put(NOTHING_TO_OVERRIDE, - new DiagnosticWithParameters1Renderer("{0} overrides nothing", DescriptorRenderer.TEXT)); - map.put(VIRTUAL_MEMBER_HIDDEN, - new DiagnosticWithParameters3Renderer( - "''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", DescriptorRenderer.TEXT, - DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); - - map.put(ENUM_ENTRY_SHOULD_BE_INITIALIZED, - new DiagnosticWithParameters1Renderer("Missing delegation specifier ''{0}''", NAME)); - map.put(ENUM_ENTRY_ILLEGAL_TYPE, - new DiagnosticWithParameters1Renderer("The type constructor of enum entry should be ''{0}''", NAME)); - - map.put(UNINITIALIZED_VARIABLE, - new DiagnosticWithParameters1Renderer("Variable ''{0}'' must be initialized", NAME)); - map.put(UNINITIALIZED_PARAMETER, - new DiagnosticWithParameters1Renderer("Parameter ''{0}'' is uninitialized here", NAME)); - map.put(UNUSED_VARIABLE, new DiagnosticWithParameters1Renderer("Variable ''{0}'' is never used", NAME)); - map.put(UNUSED_PARAMETER, new DiagnosticWithParameters1Renderer("Parameter ''{0}'' is never used", NAME)); - map.put(ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE, - new DiagnosticWithParameters1Renderer("Variable ''{0}'' is assigned but never accessed", NAME)); - map.put(VARIABLE_WITH_REDUNDANT_INITIALIZER, - new DiagnosticWithParameters1Renderer("Variable ''{0}'' initializer is redundant", NAME)); - map.put(UNUSED_VALUE, new DiagnosticWithParameters2Renderer( - "The value ''{0}'' assigned to ''{1}'' is never used", ELEMENT_TEXT, TO_STRING)); - map.put(UNUSED_CHANGED_VALUE, - new DiagnosticWithParameters1Renderer("The value changed at ''{0}'' is never used", ELEMENT_TEXT)); - map.put(UNUSED_EXPRESSION, new SimpleDiagnosticRenderer("The expression is unused")); - map.put(UNUSED_FUNCTION_LITERAL, - new SimpleDiagnosticRenderer("The function literal is unused. If you mean block, you can use 'run { ... }'")); - - map.put(VAL_REASSIGNMENT, new DiagnosticWithParameters1Renderer("Val can not be reassigned", NAME)); - map.put(INITIALIZATION_BEFORE_DECLARATION, - new DiagnosticWithParameters1Renderer("Variable cannot be initialized before declaration", NAME)); - map.put(VARIABLE_EXPECTED, new SimpleDiagnosticRenderer("Variable expected")); - - map.put(INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER, new DiagnosticWithParameters1Renderer( - "This property has a custom setter, so initialization using backing field required", NAME)); - map.put(INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER, new DiagnosticWithParameters1Renderer( - "Setter of this property can be overridden, so initialization using backing field required", NAME)); - - map.put(FUNCTION_PARAMETERS_OF_INLINE_FUNCTION, - new DiagnosticWithParameters1Renderer("Function parameters of inline function can only be invoked", - NAME)); - - map.put(UNREACHABLE_CODE, new SimpleDiagnosticRenderer("Unreachable code")); - - map.put(MANY_CLASS_OBJECTS, new SimpleDiagnosticRenderer("Only one class object is allowed per class")); - map.put(CLASS_OBJECT_NOT_ALLOWED, new SimpleDiagnosticRenderer("A class object is not allowed here")); - map.put(DELEGATION_IN_TRAIT, new SimpleDiagnosticRenderer("Traits cannot use delegation")); - map.put(DELEGATION_NOT_TO_TRAIT, new SimpleDiagnosticRenderer("Only traits can be delegated to")); - map.put(NO_CONSTRUCTOR, new SimpleDiagnosticRenderer("This class does not have a constructor")); - map.put(NOT_A_CLASS, new SimpleDiagnosticRenderer("Not a class")); - map.put(ILLEGAL_ESCAPE_SEQUENCE, new SimpleDiagnosticRenderer("Illegal escape sequence")); - - map.put(LOCAL_EXTENSION_PROPERTY, new SimpleDiagnosticRenderer("Local extension properties are not allowed")); - map.put(LOCAL_VARIABLE_WITH_GETTER, new SimpleDiagnosticRenderer("Local variables are not allowed to have getters")); - map.put(LOCAL_VARIABLE_WITH_SETTER, new SimpleDiagnosticRenderer("Local variables are not allowed to have setters")); - map.put(VAL_WITH_SETTER, new SimpleDiagnosticRenderer("A 'val'-property cannot have a setter")); - - map.put(NO_GET_METHOD, new SimpleDiagnosticRenderer("No get method providing array access")); - map.put(NO_SET_METHOD, new SimpleDiagnosticRenderer("No set method providing array access")); - - map.put(INC_DEC_SHOULD_NOT_RETURN_UNIT, - new SimpleDiagnosticRenderer("Functions inc(), dec() shouldn't return Unit to be used by operators ++, --")); - map.put(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT, - new DiagnosticWithParameters2Renderer( - "Function ''{0}'' should return Unit to be used by corresponding operator ''{1}''", NAME, ELEMENT_TEXT)); - map.put(ASSIGN_OPERATOR_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Assignment operators ambiguity: {0}")); - - map.put(EQUALS_MISSING, new SimpleDiagnosticRenderer("No method 'equals(Any?) : Boolean' available")); - map.put(ASSIGNMENT_IN_EXPRESSION_CONTEXT, - new SimpleDiagnosticRenderer("Assignments are not expressions, and only expressions are allowed in this context")); - map.put(NAMESPACE_IS_NOT_AN_EXPRESSION, - new SimpleDiagnosticRenderer("'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')")); - map.put(SUPER_IS_NOT_AN_EXPRESSION, new DiagnosticWithParameters1Renderer( - "{0} is not an expression, it can only be used on the left-hand side of a dot ('.')", TO_STRING)); - map.put(DECLARATION_IN_ILLEGAL_CONTEXT, new SimpleDiagnosticRenderer("Declarations are not allowed in this position")); - map.put(SETTER_PARAMETER_WITH_DEFAULT_VALUE, new SimpleDiagnosticRenderer("Setter parameters can not have default values")); - map.put(NO_THIS, new SimpleDiagnosticRenderer("'this' is not defined in this context")); - map.put(SUPER_NOT_AVAILABLE, new SimpleDiagnosticRenderer("No supertypes are accessible in this context")); - map.put(AMBIGUOUS_SUPER, new SimpleDiagnosticRenderer( - "Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super'")); - map.put(ABSTRACT_SUPER_CALL, new SimpleDiagnosticRenderer("Abstract member cannot be accessed directly")); - map.put(NOT_A_SUPERTYPE, new SimpleDiagnosticRenderer("Not a supertype")); - map.put(TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER, - new SimpleDiagnosticRenderer("Type arguments do not need to be specified in a 'super' qualifier")); - map.put(USELESS_CAST_STATIC_ASSERT_IS_FINE, new SimpleDiagnosticRenderer("No cast needed, use ':' instead")); - map.put(USELESS_CAST, new SimpleDiagnosticRenderer("No cast needed")); - map.put(CAST_NEVER_SUCCEEDS, new SimpleDiagnosticRenderer("This cast can never succeed")); - map.put(WRONG_SETTER_PARAMETER_TYPE, - new DiagnosticWithParameters1Renderer("Setter parameter type must be equal to the type of the property, i.e. {0}", - RENDER_TYPE)); - map.put(WRONG_GETTER_RETURN_TYPE, - new DiagnosticWithParameters1Renderer("Getter return type must be equal to the type of the property, i.e. {0}", - RENDER_TYPE)); - map.put(NO_CLASS_OBJECT, new DiagnosticWithParameters1Renderer( - "Please specify constructor invocation; classifier {0} does not have a class object", NAME)); - map.put(NO_GENERICS_IN_SUPERTYPE_SPECIFIER, new SimpleDiagnosticRenderer("Generic arguments of the base type must be specified")); - - map.put(HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY, - new SimpleDiagnosticRenderer("An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext' property")); - map.put(HAS_NEXT_MISSING, new SimpleDiagnosticRenderer( - "Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property")); - map.put(HAS_NEXT_FUNCTION_AMBIGUITY, - new SimpleDiagnosticRenderer("Function 'iterator().hasNext()' is ambiguous for this expression")); - map.put(HAS_NEXT_MUST_BE_READABLE, - new SimpleDiagnosticRenderer("The 'iterator().hasNext' property of the loop range must be readable")); - map.put(HAS_NEXT_PROPERTY_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer( - "The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", RENDER_TYPE)); - map.put(HAS_NEXT_FUNCTION_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer( - "The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", RENDER_TYPE)); - map.put(NEXT_AMBIGUITY, new SimpleDiagnosticRenderer("Function 'iterator().next()' is ambiguous for this expression")); - map.put(NEXT_MISSING, new SimpleDiagnosticRenderer("Loop range must have an 'iterator().next()' function")); - map.put(ITERATOR_MISSING, new SimpleDiagnosticRenderer("For-loop range must have an iterator() method")); - map.put(ITERATOR_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Method 'iterator()' is ambiguous for this expression: {0}")); - - map.put(COMPARE_TO_TYPE_MISMATCH, - new DiagnosticWithParameters1Renderer("compareTo() must return Int, but returns {0}", RENDER_TYPE)); - map.put(CALLEE_NOT_A_FUNCTION, - new DiagnosticWithParameters1Renderer("Expecting a function type, but found {0}", RENDER_TYPE)); - - map.put(RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY, - new SimpleDiagnosticRenderer("Returns are not allowed for functions with expression body. Use block body in '{...}'")); - map.put(NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY, - new SimpleDiagnosticRenderer("A 'return' expression required in a function with a block body ('{...}')")); - map.put(RETURN_TYPE_MISMATCH, - new DiagnosticWithParameters1Renderer("This function must return a value of type {0}", RENDER_TYPE)); - map.put(EXPECTED_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer("Expected a value of type {0}", RENDER_TYPE)); - map.put(ASSIGNMENT_TYPE_MISMATCH, new DiagnosticWithParameters1Renderer( - "Expected a value of type {0}. Assignment operation is not an expression, so it does not return any value", RENDER_TYPE)); - map.put(IMPLICIT_CAST_TO_UNIT_OR_ANY, new DiagnosticWithParameters1Renderer( - "Type was casted to ''{0}''. Please specify ''{0}'' as expected type, if you mean such cast", RENDER_TYPE)); - map.put(EXPRESSION_EXPECTED, - new DiagnosticWithParameters1Renderer("{0} is not an expression, and only expression are allowed here", - new Renderer() { - @NotNull - @Override - public String render(@NotNull JetExpression expression) { - String expressionType = expression.toString(); - return expressionType.substring(0, 1) + - expressionType.substring(1).toLowerCase(); - } - })); - - map.put(UPPER_BOUND_VIOLATED, - new DiagnosticWithParameters1Renderer("An upper bound {0} is violated", RENDER_TYPE)); // TODO : Message - map.put(FINAL_CLASS_OBJECT_UPPER_BOUND, - new DiagnosticWithParameters1Renderer("{0} is a final type, and thus a class object cannot extend it", - RENDER_TYPE)); - map.put(FINAL_UPPER_BOUND, new DiagnosticWithParameters1Renderer( - "{0} is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE)); - map.put(USELESS_ELVIS, new DiagnosticWithParameters1Renderer( - "Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE)); - map.put(CONFLICTING_UPPER_BOUNDS, - new DiagnosticWithParameters1Renderer("Upper bounds of {0} have empty intersection", NAME)); - map.put(CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS, - new DiagnosticWithParameters1Renderer("Class object upper bounds of {0} have empty intersection", - NAME)); - - map.put(TOO_MANY_ARGUMENTS, new DiagnosticWithParameters1Renderer("Too many arguments for {0}", TO_STRING)); - map.put(ERROR_COMPILE_TIME_VALUE, new DiagnosticWithParameters1Renderer("{0}", TO_STRING)); - - map.put(ELSE_MISPLACED_IN_WHEN, new SimpleDiagnosticRenderer("'else' entry must be the last one in a when-expression")); - - map.put(NO_ELSE_IN_WHEN, new SimpleDiagnosticRenderer("'when' expression must contain 'else' branch")); - map.put(TYPE_MISMATCH_IN_RANGE, - new SimpleDiagnosticRenderer("Type mismatch: incompatible types of range and element checked in it")); - map.put(CYCLIC_INHERITANCE_HIERARCHY, new SimpleDiagnosticRenderer("There's a cycle in the inheritance hierarchy for this type")); - - map.put(MANY_CLASSES_IN_SUPERTYPE_LIST, new SimpleDiagnosticRenderer("Only one class may appear in a supertype list")); - map.put(SUPERTYPE_NOT_A_CLASS_OR_TRAIT, new SimpleDiagnosticRenderer("Only classes and traits may serve as supertypes")); - map.put(SUPERTYPE_INITIALIZED_IN_TRAIT, new SimpleDiagnosticRenderer("Traits cannot initialize supertypes")); - map.put(CONSTRUCTOR_IN_TRAIT, new SimpleDiagnosticRenderer("A trait may not have a constructor")); - map.put(SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED, new SimpleDiagnosticRenderer("Secondary constructors are not supported")); - map.put(SUPERTYPE_APPEARS_TWICE, new SimpleDiagnosticRenderer("A supertype appears twice")); - map.put(FINAL_SUPERTYPE, new SimpleDiagnosticRenderer("This type is final, so it cannot be inherited from")); - - map.put(ILLEGAL_SELECTOR, - new DiagnosticWithParameters1Renderer("Expression ''{0}'' cannot be a selector (occur after a dot)", TO_STRING)); - - map.put(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION, - new SimpleDiagnosticRenderer("A type annotation is required on a value parameter")); - map.put(BREAK_OR_CONTINUE_OUTSIDE_A_LOOP, new SimpleDiagnosticRenderer("'break' and 'continue' are only allowed inside a loop")); - map.put(NOT_A_LOOP_LABEL, new DiagnosticWithParameters1Renderer("The label ''{0}'' does not denote a loop", TO_STRING)); - map.put(NOT_A_RETURN_LABEL, - new DiagnosticWithParameters1Renderer("The label ''{0}'' does not reference to a context from which we can return", - TO_STRING)); - - map.put(ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR, - new SimpleDiagnosticRenderer("Anonymous initializers are only allowed in the presence of a primary constructor")); - map.put(NULLABLE_SUPERTYPE, new SimpleDiagnosticRenderer("A supertype cannot be nullable")); - map.put(UNSAFE_CALL, - new DiagnosticWithParameters1Renderer("Only safe calls (?.) are allowed on a nullable receiver of type {0}", - RENDER_TYPE)); - map.put(AMBIGUOUS_LABEL, new SimpleDiagnosticRenderer("Ambiguous label")); - map.put(UNSUPPORTED, new DiagnosticWithParameters1Renderer("Unsupported [{0}]", TO_STRING)); - map.put(UNNECESSARY_SAFE_CALL, - new DiagnosticWithParameters1Renderer("Unnecessary safe call on a non-null receiver of type {0}", RENDER_TYPE)); - map.put(UNNECESSARY_NOT_NULL_ASSERTION, - new DiagnosticWithParameters1Renderer("Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", - RENDER_TYPE)); - map.put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, - new DiagnosticWithParameters2Renderer( - "{0} does not refer to a type parameter of {1}", new Renderer() { - @NotNull - @Override - public String render(@NotNull JetTypeConstraint typeConstraint) { - //noinspection ConstantConditions - return typeConstraint.getSubjectTypeParameterName().getReferencedName(); + put(TYPE_MISMATCH, "Type mismatch: inferred type is {1} but {0} was expected", RENDER_TYPE, RENDER_TYPE); + put(INCOMPATIBLE_MODIFIERS, "Incompatible modifiers: ''{0}''", new Renderer>() { + @NotNull + @Override + public String render(@NotNull Collection tokens) { + StringBuilder sb = new StringBuilder(); + for (Iterator iterator = tokens.iterator(); iterator.hasNext(); ) { + JetKeywordToken modifier = iterator.next(); + sb.append(modifier.getValue()); + if (iterator.hasNext()) { + sb.append(" "); } - }, NAME)); - map.put(AUTOCAST_IMPOSSIBLE, new DiagnosticWithParameters2Renderer( - "Automatic cast to {0} is impossible, because {1} could have changed since the is-check", RENDER_TYPE, NAME)); + } + return sb.toString(); + } + }); + put(ILLEGAL_MODIFIER, "Illegal modifier ''{0}''", TO_STRING); - map.put(TYPE_MISMATCH_IN_FOR_LOOP, new DiagnosticWithParameters2Renderer( - "The loop iterates over values of type {0} but the parameter is declared to be {1}", RENDER_TYPE, RENDER_TYPE)); - map.put(TYPE_MISMATCH_IN_CONDITION, - new DiagnosticWithParameters1Renderer("Condition must be of type Boolean, but was of type {0}", RENDER_TYPE)); - map.put(TYPE_MISMATCH_IN_TUPLE_PATTERN, new DiagnosticWithParameters2Renderer( - "Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, TO_STRING)); // TODO: message - map.put(TYPE_MISMATCH_IN_BINDING_PATTERN, - new DiagnosticWithParameters2Renderer("{0} must be a supertype of {1}. Use 'is' to match against {0}", - RENDER_TYPE, RENDER_TYPE)); - map.put(INCOMPATIBLE_TYPES, - new DiagnosticWithParameters2Renderer("Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE)); - map.put(EXPECTED_CONDITION, new SimpleDiagnosticRenderer("Expected condition of Boolean type")); + put(REDUNDANT_MODIFIER, "Modifier {0} is redundant because {1} is present", TO_STRING, TO_STRING); + put(ABSTRACT_MODIFIER_IN_TRAIT, "Modifier ''abstract'' is redundant in trait"); + put(OPEN_MODIFIER_IN_TRAIT, "Modifier ''open'' is redundant in trait"); + put(REDUNDANT_MODIFIER_IN_GETTER, "Visibility modifiers are redundant in getter"); + put(TRAIT_CAN_NOT_BE_FINAL, "Trait can not be final"); + put(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM, + "Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly"); // TODO: message + put(RETURN_NOT_ALLOWED, "'return' is not allowed here"); + put(PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE, "Projections are not allowed for immediate arguments of a supertype"); + put(LABEL_NAME_CLASH, "There is more than one label with such a name in this scope"); + put(EXPRESSION_EXPECTED_NAMESPACE_FOUND, "Expression expected, but a namespace name found"); - map.put(CANNOT_CHECK_FOR_ERASED, - new DiagnosticWithParameters1Renderer("Cannot check for instance of erased type: {0}", RENDER_TYPE)); - map.put(UNCHECKED_CAST, - new DiagnosticWithParameters2Renderer("Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE)); + put(CANNOT_IMPORT_FROM_ELEMENT, "Cannot import from ''{0}''", NAME); + put(CANNOT_BE_IMPORTED, "Cannot import ''{0}'', functions and properties can be imported only from packages", NAME); + put(USELESS_HIDDEN_IMPORT, "Useless import, it is hidden further"); + put(USELESS_SIMPLE_IMPORT, "Useless import, does nothing"); - map.put(INCONSISTENT_TYPE_PARAMETER_VALUES, - new DiagnosticWithParameters3Renderer>( - "Type parameter {0} of {1} has inconsistent values: {2}", NAME, DescriptorRenderer.TEXT, - new Renderer>() { - @NotNull - @Override - public String render(@NotNull Collection types) { - StringBuilder builder = new StringBuilder(); - for (Iterator iterator = types.iterator(); iterator.hasNext(); ) { - JetType jetType = iterator.next(); - builder.append(jetType); - if (iterator.hasNext()) { - builder.append(", "); - } - } - return builder.toString(); - } - })); + put(CANNOT_INFER_PARAMETER_TYPE, + "Cannot infer a type for this parameter. To specify it explicitly use the {(p : Type) => ...} notation"); - map.put(EQUALITY_NOT_APPLICABLE, new DiagnosticWithParameters3Renderer( - "Operator {0} cannot be applied to {1} and {2}", new Renderer() { + put(NO_BACKING_FIELD_ABSTRACT_PROPERTY, "This property doesn't have a backing field, because it's abstract"); + put(NO_BACKING_FIELD_CUSTOM_ACCESSORS, + "This property doesn't have a backing field, because it has custom accessors without reference to the backing field"); + put(INACCESSIBLE_BACKING_FIELD, "The backing field is not accessible here"); + put(NOT_PROPERTY_BACKING_FIELD, "The referenced variable is not a property and doesn't have backing field"); + + put(MIXING_NAMED_AND_POSITIONED_ARGUMENTS, "Mixing named and positioned arguments in not allowed"); + put(ARGUMENT_PASSED_TWICE, "An argument is already passed for this parameter"); + put(NAMED_PARAMETER_NOT_FOUND, "Cannot find a parameter with this name: {0}", TO_STRING); + put(VARARG_OUTSIDE_PARENTHESES, "Passing value as a vararg is only allowed inside a parenthesized argument list"); + put(NON_VARARG_SPREAD, "The spread operator (*foo) may only be applied in a vararg position"); + + put(MANY_FUNCTION_LITERAL_ARGUMENTS, "Only one function literal is allowed outside a parenthesized argument list"); + put(PROPERTY_WITH_NO_TYPE_NO_INITIALIZER, "This property must either have a type annotation or be initialized"); + + put(ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS, "This property cannot be declared abstract"); + put(ABSTRACT_PROPERTY_NOT_IN_CLASS, "A property may be abstract only when defined in a class or trait"); + put(ABSTRACT_PROPERTY_WITH_INITIALIZER, "Property with initializer cannot be abstract"); + put(ABSTRACT_PROPERTY_WITH_GETTER, "Property with getter implementation cannot be abstract"); + put(ABSTRACT_PROPERTY_WITH_SETTER, "Property with setter implementation cannot be abstract"); + + put(PACKAGE_MEMBER_CANNOT_BE_PROTECTED, "Package member cannot be protected"); + + put(GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY, "Getter visibility must be the same as property visibility"); + put(BACKING_FIELD_IN_TRAIT, "Property in a trait cannot have a backing field"); + put(MUST_BE_INITIALIZED, "Property must be initialized"); + put(MUST_BE_INITIALIZED_OR_BE_ABSTRACT, "Property must be initialized or be abstract"); + put(PROPERTY_INITIALIZER_IN_TRAIT, "Property initializers are not allowed in traits"); + put(PROPERTY_INITIALIZER_NO_BACKING_FIELD, "Initializer is not allowed here because this property has no backing field"); + put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, "Abstract property {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING); + put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, "Abstract function {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING); + put(ABSTRACT_FUNCTION_WITH_BODY, "A function {0} with body cannot be abstract", TO_STRING); + put(NON_ABSTRACT_FUNCTION_WITH_NO_BODY, "Method {0} without a body must be abstract", TO_STRING); + put(NON_MEMBER_ABSTRACT_FUNCTION, "Function {0} is not a class or trait member and cannot be abstract", TO_STRING); + + put(NON_MEMBER_FUNCTION_NO_BODY, "Function {0} must have a body", TO_STRING); + put(NON_FINAL_MEMBER_IN_FINAL_CLASS, "Non final member in a final class"); + + put(PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE, "Public or protected member should specify a type"); + + put(PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT, + "Projections are not allowed on type arguments of functions and properties"); // TODO : better positioning + put(SUPERTYPE_NOT_INITIALIZED, "This type has a constructor, and thus must be initialized here"); + put(SUPERTYPE_NOT_INITIALIZED_DEFAULT, "Constructor invocation should be explicitly specified"); + put(SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY, "A secondary constructor may appear only in a class that has a primary constructor"); + put(SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST, "Secondary constructors must have an initializer list"); + put(BY_IN_SECONDARY_CONSTRUCTOR, "'by'-clause is only supported for primary constructors"); + put(INITIALIZER_WITH_NO_ARGUMENTS, "Constructor arguments required"); + put(MANY_CALLS_TO_THIS, "Only one call to 'this(...)' is allowed"); + put(NOTHING_TO_OVERRIDE, "{0} overrides nothing", DescriptorRenderer.TEXT); + put(VIRTUAL_MEMBER_HIDDEN, "''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", DescriptorRenderer.TEXT, + DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); + + put(ENUM_ENTRY_SHOULD_BE_INITIALIZED, "Missing delegation specifier ''{0}''", NAME); + put(ENUM_ENTRY_ILLEGAL_TYPE, "The type constructor of enum entry should be ''{0}''", NAME); + + put(UNINITIALIZED_VARIABLE, "Variable ''{0}'' must be initialized", NAME); + put(UNINITIALIZED_PARAMETER, "Parameter ''{0}'' is uninitialized here", NAME); + put(UNUSED_VARIABLE, "Variable ''{0}'' is never used", NAME); + put(UNUSED_PARAMETER, "Parameter ''{0}'' is never used", NAME); + put(ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE, "Variable ''{0}'' is assigned but never accessed", NAME); + put(VARIABLE_WITH_REDUNDANT_INITIALIZER, "Variable ''{0}'' initializer is redundant", NAME); + put(UNUSED_VALUE, "The value ''{0}'' assigned to ''{1}'' is never used", ELEMENT_TEXT, TO_STRING); + put(UNUSED_CHANGED_VALUE, "The value changed at ''{0}'' is never used", ELEMENT_TEXT); + put(UNUSED_EXPRESSION, "The expression is unused"); + put(UNUSED_FUNCTION_LITERAL, "The function literal is unused. If you mean block, you can use 'run { ... }'"); + + put(VAL_REASSIGNMENT, "Val can not be reassigned", NAME); + put(INITIALIZATION_BEFORE_DECLARATION, "Variable cannot be initialized before declaration", NAME); + put(VARIABLE_EXPECTED, "Variable expected"); + + put(INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER, + "This property has a custom setter, so initialization using backing field required", NAME); + put(INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER, + "Setter of this property can be overridden, so initialization using backing field required", NAME); + + put(FUNCTION_PARAMETERS_OF_INLINE_FUNCTION, "Function parameters of inline function can only be invoked", NAME); + + put(UNREACHABLE_CODE, "Unreachable code"); + + put(MANY_CLASS_OBJECTS, "Only one class object is allowed per class"); + put(CLASS_OBJECT_NOT_ALLOWED, "A class object is not allowed here"); + put(DELEGATION_IN_TRAIT, "Traits cannot use delegation"); + put(DELEGATION_NOT_TO_TRAIT, "Only traits can be delegated to"); + put(NO_CONSTRUCTOR, "This class does not have a constructor"); + put(NOT_A_CLASS, "Not a class"); + put(ILLEGAL_ESCAPE_SEQUENCE, "Illegal escape sequence"); + + put(LOCAL_EXTENSION_PROPERTY, "Local extension properties are not allowed"); + put(LOCAL_VARIABLE_WITH_GETTER, "Local variables are not allowed to have getters"); + put(LOCAL_VARIABLE_WITH_SETTER, "Local variables are not allowed to have setters"); + put(VAL_WITH_SETTER, "A 'val'-property cannot have a setter"); + + put(NO_GET_METHOD, "No get method providing array access"); + put(NO_SET_METHOD, "No set method providing array access"); + + put(INC_DEC_SHOULD_NOT_RETURN_UNIT, "Functions inc(), dec() shouldn't return Unit to be used by operators ++, --"); + put(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT, "Function ''{0}'' should return Unit to be used by corresponding operator ''{1}''", + NAME, ELEMENT_TEXT); + put(ASSIGN_OPERATOR_AMBIGUITY, "Assignment operators ambiguity: {0}", AMBIGUOUS_CALLS); + + put(EQUALS_MISSING, "No method 'equals(Any?) : Boolean' available"); + put(ASSIGNMENT_IN_EXPRESSION_CONTEXT, "Assignments are not expressions, and only expressions are allowed in this context"); + put(NAMESPACE_IS_NOT_AN_EXPRESSION, "'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')"); + put(SUPER_IS_NOT_AN_EXPRESSION, "{0} is not an expression, it can only be used on the left-hand side of a dot ('.')", TO_STRING); + put(DECLARATION_IN_ILLEGAL_CONTEXT, "Declarations are not allowed in this position"); + put(SETTER_PARAMETER_WITH_DEFAULT_VALUE, "Setter parameters can not have default values"); + put(NO_THIS, "'this' is not defined in this context"); + put(SUPER_NOT_AVAILABLE, "No supertypes are accessible in this context"); + put(AMBIGUOUS_SUPER, "Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super'"); + put(ABSTRACT_SUPER_CALL, "Abstract member cannot be accessed directly"); + put(NOT_A_SUPERTYPE, "Not a supertype"); + put(TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER, "Type arguments do not need to be specified in a 'super' qualifier"); + put(USELESS_CAST_STATIC_ASSERT_IS_FINE, "No cast needed, use ':' instead"); + put(USELESS_CAST, "No cast needed"); + put(CAST_NEVER_SUCCEEDS, "This cast can never succeed"); + put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property, i.e. {0}", RENDER_TYPE); + put(WRONG_GETTER_RETURN_TYPE, "Getter return type must be equal to the type of the property, i.e. {0}", RENDER_TYPE); + put(NO_CLASS_OBJECT, "Please specify constructor invocation; classifier {0} does not have a class object", NAME); + put(NO_GENERICS_IN_SUPERTYPE_SPECIFIER, "Generic arguments of the base type must be specified"); + + put(HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY, + "An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext' property"); + put(HAS_NEXT_MISSING, "Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property"); + put(HAS_NEXT_FUNCTION_AMBIGUITY, "Function 'iterator().hasNext()' is ambiguous for this expression"); + put(HAS_NEXT_MUST_BE_READABLE, "The 'iterator().hasNext' property of the loop range must be readable"); + put(HAS_NEXT_PROPERTY_TYPE_MISMATCH, "The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", + RENDER_TYPE); + put(HAS_NEXT_FUNCTION_TYPE_MISMATCH, "The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", + RENDER_TYPE); + put(NEXT_AMBIGUITY, "Function 'iterator().next()' is ambiguous for this expression"); + put(NEXT_MISSING, "Loop range must have an 'iterator().next()' function"); + put(ITERATOR_MISSING, "For-loop range must have an iterator() method"); + put(ITERATOR_AMBIGUITY, "Method 'iterator()' is ambiguous for this expression: {0}", AMBIGUOUS_CALLS); + + put(COMPARE_TO_TYPE_MISMATCH, "compareTo() must return Int, but returns {0}", RENDER_TYPE); + put(CALLEE_NOT_A_FUNCTION, "Expecting a function type, but found {0}", RENDER_TYPE); + + put(RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY, + "Returns are not allowed for functions with expression body. Use block body in '{...}'"); + put(NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY, "A 'return' expression required in a function with a block body ('{...}')"); + put(RETURN_TYPE_MISMATCH, "This function must return a value of type {0}", RENDER_TYPE); + put(EXPECTED_TYPE_MISMATCH, "Expected a value of type {0}", RENDER_TYPE); + put(ASSIGNMENT_TYPE_MISMATCH, + "Expected a value of type {0}. Assignment operation is not an expression, so it does not return any value", RENDER_TYPE); + put(IMPLICIT_CAST_TO_UNIT_OR_ANY, "Type was casted to ''{0}''. Please specify ''{0}'' as expected type, if you mean such cast", + RENDER_TYPE); + put(EXPRESSION_EXPECTED, "{0} is not an expression, and only expression are allowed here", new Renderer() { + @NotNull + @Override + public String render(@NotNull JetExpression expression) { + String expressionType = expression.toString(); + return expressionType.substring(0, 1) + + expressionType.substring(1).toLowerCase(); + } + }); + + put(UPPER_BOUND_VIOLATED, "An upper bound {0} is violated", RENDER_TYPE); // TODO : Message + put(FINAL_CLASS_OBJECT_UPPER_BOUND, "{0} is a final type, and thus a class object cannot extend it", RENDER_TYPE); + put(FINAL_UPPER_BOUND, "{0} is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE); + put(USELESS_ELVIS, "Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE); + put(CONFLICTING_UPPER_BOUNDS, "Upper bounds of {0} have empty intersection", NAME); + put(CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS, "Class object upper bounds of {0} have empty intersection", NAME); + + put(TOO_MANY_ARGUMENTS, "Too many arguments for {0}", TO_STRING); + put(ERROR_COMPILE_TIME_VALUE, "{0}", TO_STRING); + + put(ELSE_MISPLACED_IN_WHEN, "'else' entry must be the last one in a when-expression"); + + put(NO_ELSE_IN_WHEN, "'when' expression must contain 'else' branch"); + put(TYPE_MISMATCH_IN_RANGE, "Type mismatch: incompatible types of range and element checked in it"); + put(CYCLIC_INHERITANCE_HIERARCHY, "There's a cycle in the inheritance hierarchy for this type"); + + put(MANY_CLASSES_IN_SUPERTYPE_LIST, "Only one class may appear in a supertype list"); + put(SUPERTYPE_NOT_A_CLASS_OR_TRAIT, "Only classes and traits may serve as supertypes"); + put(SUPERTYPE_INITIALIZED_IN_TRAIT, "Traits cannot initialize supertypes"); + put(CONSTRUCTOR_IN_TRAIT, "A trait may not have a constructor"); + put(SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED, "Secondary constructors are not supported"); + put(SUPERTYPE_APPEARS_TWICE, "A supertype appears twice"); + put(FINAL_SUPERTYPE, "This type is final, so it cannot be inherited from"); + + put(ILLEGAL_SELECTOR, "Expression ''{0}'' cannot be a selector (occur after a dot)", TO_STRING); + + put(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION, "A type annotation is required on a value parameter"); + put(BREAK_OR_CONTINUE_OUTSIDE_A_LOOP, "'break' and 'continue' are only allowed inside a loop"); + put(NOT_A_LOOP_LABEL, "The label ''{0}'' does not denote a loop", TO_STRING); + put(NOT_A_RETURN_LABEL, "The label ''{0}'' does not reference to a context from which we can return", TO_STRING); + + put(ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR, "Anonymous initializers are only allowed in the presence of a primary constructor"); + put(NULLABLE_SUPERTYPE, "A supertype cannot be nullable"); + put(UNSAFE_CALL, "Only safe calls (?.) are allowed on a nullable receiver of type {0}", RENDER_TYPE); + put(AMBIGUOUS_LABEL, "Ambiguous label"); + put(UNSUPPORTED, "Unsupported [{0}]", TO_STRING); + put(UNNECESSARY_SAFE_CALL, "Unnecessary safe call on a non-null receiver of type {0}", RENDER_TYPE); + put(UNNECESSARY_NOT_NULL_ASSERTION, "Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", RENDER_TYPE); + put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, "{0} does not refer to a type parameter of {1}", new Renderer() { + @NotNull + @Override + public String render(@NotNull JetTypeConstraint typeConstraint) { + //noinspection ConstantConditions + return typeConstraint.getSubjectTypeParameterName().getReferencedName(); + } + }, NAME); + put(AUTOCAST_IMPOSSIBLE, "Automatic cast to {0} is impossible, because {1} could have changed since the is-check", RENDER_TYPE, + NAME); + + put(TYPE_MISMATCH_IN_FOR_LOOP, "The loop iterates over values of type {0} but the parameter is declared to be {1}", RENDER_TYPE, + RENDER_TYPE); + put(TYPE_MISMATCH_IN_CONDITION, "Condition must be of type Boolean, but was of type {0}", RENDER_TYPE); + put(TYPE_MISMATCH_IN_TUPLE_PATTERN, "Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, + TO_STRING); // TODO: message + put(TYPE_MISMATCH_IN_BINDING_PATTERN, "{0} must be a supertype of {1}. Use 'is' to match against {0}", RENDER_TYPE, RENDER_TYPE); + put(INCOMPATIBLE_TYPES, "Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE); + put(EXPECTED_CONDITION, "Expected condition of Boolean type"); + + put(CANNOT_CHECK_FOR_ERASED, "Cannot check for instance of erased type: {0}", RENDER_TYPE); + put(UNCHECKED_CAST, "Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE); + + put(INCONSISTENT_TYPE_PARAMETER_VALUES, "Type parameter {0} of {1} has inconsistent values: {2}", NAME, DescriptorRenderer.TEXT, + new Renderer>() { + @NotNull + @Override + public String render(@NotNull Collection types) { + StringBuilder builder = new StringBuilder(); + for (Iterator iterator = types.iterator(); iterator.hasNext(); ) { + JetType jetType = iterator.next(); + builder.append(jetType); + if (iterator.hasNext()) { + builder.append(", "); + } + } + return builder.toString(); + } + }); + + put(EQUALITY_NOT_APPLICABLE, "Operator {0} cannot be applied to {1} and {2}", new Renderer() { @NotNull @Override public String render(@NotNull JetSimpleNameExpression nameExpression) { //noinspection ConstantConditions return nameExpression.getReferencedName(); } - }, TO_STRING, TO_STRING)); + }, TO_STRING, TO_STRING); - map.put(OVERRIDING_FINAL_MEMBER, new DiagnosticWithParameters2Renderer( - "''{0}'' in ''{1}'' is final and cannot be overridden", NAME, NAME)); - map.put(CANNOT_WEAKEN_ACCESS_PRIVILEGE, - new DiagnosticWithParameters3Renderer( - "Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME)); - map.put(CANNOT_CHANGE_ACCESS_PRIVILEGE, - new DiagnosticWithParameters3Renderer( - "Cannot change access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME)); + put(OVERRIDING_FINAL_MEMBER, "''{0}'' in ''{1}'' is final and cannot be overridden", NAME, NAME); + put(CANNOT_WEAKEN_ACCESS_PRIVILEGE, "Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME); + put(CANNOT_CHANGE_ACCESS_PRIVILEGE, "Cannot change access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME); - map.put(RETURN_TYPE_MISMATCH_ON_OVERRIDE, new DiagnosticWithParameters2Renderer( - "Return type of {0} is not a subtype of the return type overridden member {1}", DescriptorRenderer.TEXT, - DescriptorRenderer.TEXT)); + put(RETURN_TYPE_MISMATCH_ON_OVERRIDE, "Return type of {0} is not a subtype of the return type overridden member {1}", + DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); - map.put(VAR_OVERRIDDEN_BY_VAL, new DiagnosticWithParameters2Renderer( - "Var-property {0} cannot be overridden by val-property {1}", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT)); + put(VAR_OVERRIDDEN_BY_VAL, "Var-property {0} cannot be overridden by val-property {1}", DescriptorRenderer.TEXT, + DescriptorRenderer.TEXT); - map.put(ABSTRACT_MEMBER_NOT_IMPLEMENTED, new DiagnosticWithParameters2Renderer( - "{0} must be declared abstract or implement abstract member {1}", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT)); + put(ABSTRACT_MEMBER_NOT_IMPLEMENTED, "{0} must be declared abstract or implement abstract member {1}", RENDER_CLASS_OR_OBJECT, + DescriptorRenderer.TEXT); - map.put(MANY_IMPL_MEMBER_NOT_IMPLEMENTED, new DiagnosticWithParameters2Renderer( - "{0} must override {1} because it inherits many implementations of it", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT)); + put(MANY_IMPL_MEMBER_NOT_IMPLEMENTED, "{0} must override {1} because it inherits many implementations of it", + RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT); - map.put(CONFLICTING_OVERLOADS, - new DiagnosticWithParameters2Renderer("{1} is already defined in ''{0}''", - DescriptorRenderer.TEXT, TO_STRING)); + put(CONFLICTING_OVERLOADS, "{1} is already defined in ''{0}''", DescriptorRenderer.TEXT, TO_STRING); - map.put(RESULT_TYPE_MISMATCH, - new DiagnosticWithParameters3Renderer("{0} must return {1} but returns {2}", TO_STRING, - RENDER_TYPE, RENDER_TYPE)); - map.put(UNSAFE_INFIX_CALL, new DiagnosticWithParameters3Renderer( - "Infix call corresponds to a dot-qualified call ''{0}.{1}({2})'' which is not allowed on a nullable receiver ''{0}''. Use '?.'-qualified call instead", - TO_STRING, TO_STRING, TO_STRING)); + put(RESULT_TYPE_MISMATCH, "{0} must return {1} but returns {2}", TO_STRING, RENDER_TYPE, RENDER_TYPE); + put(UNSAFE_INFIX_CALL, + "Infix call corresponds to a dot-qualified call ''{0}.{1}({2})'' which is not allowed on a nullable receiver ''{0}''. " + + "Use '?.'-qualified call instead", + TO_STRING, TO_STRING, TO_STRING); - map.put(OVERLOAD_RESOLUTION_AMBIGUITY, new AmbiguousDescriptorDiagnosticRenderer("Overload resolution ambiguity: {0}")); - map.put(NONE_APPLICABLE, new AmbiguousDescriptorDiagnosticRenderer( - "None of the following functions can be called with the arguments supplied: {0}")); - map.put(NO_VALUE_FOR_PARAMETER, new DiagnosticWithParameters1Renderer("No value passed for parameter {0}", - DescriptorRenderer.TEXT)); - map.put(MISSING_RECEIVER, new DiagnosticWithParameters1Renderer("A receiver of type {0} is required", RENDER_TYPE)); - map.put(NO_RECEIVER_ADMITTED, new SimpleDiagnosticRenderer("No receiver can be passed to this function or property")); + put(OVERLOAD_RESOLUTION_AMBIGUITY, "Overload resolution ambiguity: {0}", AMBIGUOUS_CALLS); + put(NONE_APPLICABLE, "None of the following functions can be called with the arguments supplied: {0}", AMBIGUOUS_CALLS); + put(NO_VALUE_FOR_PARAMETER, "No value passed for parameter {0}", DescriptorRenderer.TEXT); + put(MISSING_RECEIVER, "A receiver of type {0} is required", RENDER_TYPE); + put(NO_RECEIVER_ADMITTED, "No receiver can be passed to this function or property"); - map.put(CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS, new SimpleDiagnosticRenderer("Can not create an instance of an abstract class")); - map.put(TYPE_INFERENCE_FAILED, new DiagnosticWithParameters1Renderer("Type inference failed: {0}", TO_STRING)); - map.put(WRONG_NUMBER_OF_TYPE_ARGUMENTS, - new DiagnosticWithParameters1Renderer("{0} type arguments expected", new Renderer() { - @NotNull - @Override - public String render(@NotNull Integer argument) { - return argument == 0 ? "No" : argument.toString(); - } - })); + put(CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS, "Can not create an instance of an abstract class"); + put(TYPE_INFERENCE_FAILED, "Type inference failed: {0}", TO_STRING); + put(WRONG_NUMBER_OF_TYPE_ARGUMENTS, "{0} type arguments expected", new Renderer() { + @NotNull + @Override + public String render(@NotNull Integer argument) { + return argument == 0 ? "No" : argument.toString(); + } + }); - map.put(UNRESOLVED_IDE_TEMPLATE, new DiagnosticWithParameters1Renderer("Unresolved IDE template: {0}", TO_STRING)); + put(UNRESOLVED_IDE_TEMPLATE, "Unresolved IDE template: {0}", TO_STRING); - map.put(DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED, new SimpleDiagnosticRenderer( - "This expression is treated as an argument to the function call on the previous line. Separate it with a semicolon (;) if it is not intended to be an argument.")); + put(DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED, + "This expression is treated as an argument to the function call on the previous line. " + + "Separate it with a semicolon (;) if it is not intended to be an argument."); - map.put(NOT_AN_ANNOTATION_CLASS, new DiagnosticWithParameters1Renderer("{0} is not an annotation class", TO_STRING)); + put(NOT_AN_ANNOTATION_CLASS, "{0} is not an annotation class", TO_STRING); } @NotNull @@ -514,21 +440,4 @@ public class DefaultDiagnosticRenderer implements DiagnosticRenderer //noinspection unchecked return renderer.render(diagnostic); } - - private static class AmbiguousDescriptorDiagnosticRenderer - extends DiagnosticWithParameters1Renderer>> { - private AmbiguousDescriptorDiagnosticRenderer(@NotNull String message) { - super(message, new Renderer>>() { - @NotNull - @Override - public String render(@NotNull Collection> argument) { - StringBuilder stringBuilder = new StringBuilder("\n"); - for (ResolvedCall call : argument) { - stringBuilder.append(DescriptorRenderer.TEXT.render(call.getResultingDescriptor())).append("\n"); - } - return stringBuilder.toString(); - } - }); - } - } } From 6ac389cf8a8d445d7689e672f1b9e8dd23f37419 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 18:45:19 +0400 Subject: [PATCH 034/147] Extracted error messages from DefaultDiagnosticRenderer to special DefaultErrorMessages class. --- .../jet/lang/diagnostics/Errors.java | 5 +- .../rendering/DefaultDiagnosticRenderer.java | 406 +---------------- .../rendering/DefaultErrorMessages.java | 408 ++++++++++++++++++ .../DiagnosticFactoryToRendererMap.java | 62 +++ 4 files changed, 476 insertions(+), 405 deletions(-) create mode 100644 compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java create mode 100644 compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java index 2c74e53d6a3..628d07a338f 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java @@ -38,6 +38,8 @@ import static org.jetbrains.jet.lang.diagnostics.Severity.ERROR; import static org.jetbrains.jet.lang.diagnostics.Severity.WARNING; /** + * For error messages, see DefaultErrorMessages and IdeErrorMessages. + * * @author abreslav */ public interface Errors { @@ -326,7 +328,8 @@ public interface Errors { @NotNull @Override public List mark(@NotNull JetNullableType element) { - return markNode(element.getQuestionMarkNode()); + return markNode( + element.getQuestionMarkNode()); } }); DiagnosticFactory1 UNSAFE_CALL = DiagnosticFactory1.create(ERROR); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java index 746ce87d618..6453e0465e7 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java @@ -16,25 +16,8 @@ package org.jetbrains.jet.lang.diagnostics.rendering; -import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.lang.descriptors.CallableDescriptor; -import org.jetbrains.jet.lang.diagnostics.*; -import org.jetbrains.jet.lang.psi.JetExpression; -import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; -import org.jetbrains.jet.lang.psi.JetTypeConstraint; -import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; -import org.jetbrains.jet.lang.types.JetType; -import org.jetbrains.jet.lexer.JetKeywordToken; -import org.jetbrains.jet.resolve.DescriptorRenderer; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import static org.jetbrains.jet.lang.diagnostics.Errors.*; -import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.*; +import org.jetbrains.jet.lang.diagnostics.Diagnostic; /** * @author Evgeny Gerashchenko @@ -42,393 +25,8 @@ import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.*; */ public class DefaultDiagnosticRenderer implements DiagnosticRenderer { public static final DefaultDiagnosticRenderer INSTANCE = new DefaultDiagnosticRenderer(); - private static final Renderer>> AMBIGUOUS_CALLS = - new Renderer>>() { - @NotNull - @Override - public String render(@NotNull Collection> argument) { - StringBuilder stringBuilder = new StringBuilder("\n"); - for (ResolvedCall call : argument) { - stringBuilder.append(DescriptorRenderer.TEXT.render(call.getResultingDescriptor())).append("\n"); - } - return stringBuilder.toString(); - } - }; - private final Map> map = - new HashMap>(); - - protected final void put(SimpleDiagnosticFactory factory, String message) { - map.put(factory, new SimpleDiagnosticRenderer(message)); - } - - protected final void put(DiagnosticFactory1 factory, String message, Renderer rendererA) { - map.put(factory, new DiagnosticWithParameters1Renderer(message, rendererA)); - } - - protected final void put(DiagnosticFactory2 factory, - String message, - Renderer rendererA, - Renderer rendererB) { - map.put(factory, new DiagnosticWithParameters2Renderer(message, rendererA, rendererB)); - } - - protected final void put(DiagnosticFactory3 factory, - String message, - Renderer rendererA, - Renderer rendererB, - Renderer rendererC) { - map.put(factory, new DiagnosticWithParameters3Renderer(message, rendererA, rendererB, rendererC)); - } - - protected DefaultDiagnosticRenderer() { - put(EXCEPTION_WHILE_ANALYZING, "{0}", new Renderer() { - @NotNull - @Override - public String render(@NotNull Throwable e) { - return e.getClass().getSimpleName() + ": " + e.getMessage(); - } - }); - - put(UNRESOLVED_REFERENCE, "Unresolved reference: {0}", TO_STRING); - - put(INVISIBLE_REFERENCE, "Cannot access ''{0}'' in ''{1}''", NAME, NAME); - put(INVISIBLE_MEMBER, "Cannot access ''{0}'' in ''{1}''", NAME, NAME); - - put(REDECLARATION, "Redeclaration: {0}", NAME); - put(NAME_SHADOWING, "Name shadowed: {0}", NAME); - - put(TYPE_MISMATCH, "Type mismatch: inferred type is {1} but {0} was expected", RENDER_TYPE, RENDER_TYPE); - put(INCOMPATIBLE_MODIFIERS, "Incompatible modifiers: ''{0}''", new Renderer>() { - @NotNull - @Override - public String render(@NotNull Collection tokens) { - StringBuilder sb = new StringBuilder(); - for (Iterator iterator = tokens.iterator(); iterator.hasNext(); ) { - JetKeywordToken modifier = iterator.next(); - sb.append(modifier.getValue()); - if (iterator.hasNext()) { - sb.append(" "); - } - } - return sb.toString(); - } - }); - put(ILLEGAL_MODIFIER, "Illegal modifier ''{0}''", TO_STRING); - - put(REDUNDANT_MODIFIER, "Modifier {0} is redundant because {1} is present", TO_STRING, TO_STRING); - put(ABSTRACT_MODIFIER_IN_TRAIT, "Modifier ''abstract'' is redundant in trait"); - put(OPEN_MODIFIER_IN_TRAIT, "Modifier ''open'' is redundant in trait"); - put(REDUNDANT_MODIFIER_IN_GETTER, "Visibility modifiers are redundant in getter"); - put(TRAIT_CAN_NOT_BE_FINAL, "Trait can not be final"); - put(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM, - "Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly"); // TODO: message - put(RETURN_NOT_ALLOWED, "'return' is not allowed here"); - put(PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE, "Projections are not allowed for immediate arguments of a supertype"); - put(LABEL_NAME_CLASH, "There is more than one label with such a name in this scope"); - put(EXPRESSION_EXPECTED_NAMESPACE_FOUND, "Expression expected, but a namespace name found"); - - put(CANNOT_IMPORT_FROM_ELEMENT, "Cannot import from ''{0}''", NAME); - put(CANNOT_BE_IMPORTED, "Cannot import ''{0}'', functions and properties can be imported only from packages", NAME); - put(USELESS_HIDDEN_IMPORT, "Useless import, it is hidden further"); - put(USELESS_SIMPLE_IMPORT, "Useless import, does nothing"); - - put(CANNOT_INFER_PARAMETER_TYPE, - "Cannot infer a type for this parameter. To specify it explicitly use the {(p : Type) => ...} notation"); - - put(NO_BACKING_FIELD_ABSTRACT_PROPERTY, "This property doesn't have a backing field, because it's abstract"); - put(NO_BACKING_FIELD_CUSTOM_ACCESSORS, - "This property doesn't have a backing field, because it has custom accessors without reference to the backing field"); - put(INACCESSIBLE_BACKING_FIELD, "The backing field is not accessible here"); - put(NOT_PROPERTY_BACKING_FIELD, "The referenced variable is not a property and doesn't have backing field"); - - put(MIXING_NAMED_AND_POSITIONED_ARGUMENTS, "Mixing named and positioned arguments in not allowed"); - put(ARGUMENT_PASSED_TWICE, "An argument is already passed for this parameter"); - put(NAMED_PARAMETER_NOT_FOUND, "Cannot find a parameter with this name: {0}", TO_STRING); - put(VARARG_OUTSIDE_PARENTHESES, "Passing value as a vararg is only allowed inside a parenthesized argument list"); - put(NON_VARARG_SPREAD, "The spread operator (*foo) may only be applied in a vararg position"); - - put(MANY_FUNCTION_LITERAL_ARGUMENTS, "Only one function literal is allowed outside a parenthesized argument list"); - put(PROPERTY_WITH_NO_TYPE_NO_INITIALIZER, "This property must either have a type annotation or be initialized"); - - put(ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS, "This property cannot be declared abstract"); - put(ABSTRACT_PROPERTY_NOT_IN_CLASS, "A property may be abstract only when defined in a class or trait"); - put(ABSTRACT_PROPERTY_WITH_INITIALIZER, "Property with initializer cannot be abstract"); - put(ABSTRACT_PROPERTY_WITH_GETTER, "Property with getter implementation cannot be abstract"); - put(ABSTRACT_PROPERTY_WITH_SETTER, "Property with setter implementation cannot be abstract"); - - put(PACKAGE_MEMBER_CANNOT_BE_PROTECTED, "Package member cannot be protected"); - - put(GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY, "Getter visibility must be the same as property visibility"); - put(BACKING_FIELD_IN_TRAIT, "Property in a trait cannot have a backing field"); - put(MUST_BE_INITIALIZED, "Property must be initialized"); - put(MUST_BE_INITIALIZED_OR_BE_ABSTRACT, "Property must be initialized or be abstract"); - put(PROPERTY_INITIALIZER_IN_TRAIT, "Property initializers are not allowed in traits"); - put(PROPERTY_INITIALIZER_NO_BACKING_FIELD, "Initializer is not allowed here because this property has no backing field"); - put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, "Abstract property {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING); - put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, "Abstract function {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING); - put(ABSTRACT_FUNCTION_WITH_BODY, "A function {0} with body cannot be abstract", TO_STRING); - put(NON_ABSTRACT_FUNCTION_WITH_NO_BODY, "Method {0} without a body must be abstract", TO_STRING); - put(NON_MEMBER_ABSTRACT_FUNCTION, "Function {0} is not a class or trait member and cannot be abstract", TO_STRING); - - put(NON_MEMBER_FUNCTION_NO_BODY, "Function {0} must have a body", TO_STRING); - put(NON_FINAL_MEMBER_IN_FINAL_CLASS, "Non final member in a final class"); - - put(PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE, "Public or protected member should specify a type"); - - put(PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT, - "Projections are not allowed on type arguments of functions and properties"); // TODO : better positioning - put(SUPERTYPE_NOT_INITIALIZED, "This type has a constructor, and thus must be initialized here"); - put(SUPERTYPE_NOT_INITIALIZED_DEFAULT, "Constructor invocation should be explicitly specified"); - put(SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY, "A secondary constructor may appear only in a class that has a primary constructor"); - put(SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST, "Secondary constructors must have an initializer list"); - put(BY_IN_SECONDARY_CONSTRUCTOR, "'by'-clause is only supported for primary constructors"); - put(INITIALIZER_WITH_NO_ARGUMENTS, "Constructor arguments required"); - put(MANY_CALLS_TO_THIS, "Only one call to 'this(...)' is allowed"); - put(NOTHING_TO_OVERRIDE, "{0} overrides nothing", DescriptorRenderer.TEXT); - put(VIRTUAL_MEMBER_HIDDEN, "''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", DescriptorRenderer.TEXT, - DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); - - put(ENUM_ENTRY_SHOULD_BE_INITIALIZED, "Missing delegation specifier ''{0}''", NAME); - put(ENUM_ENTRY_ILLEGAL_TYPE, "The type constructor of enum entry should be ''{0}''", NAME); - - put(UNINITIALIZED_VARIABLE, "Variable ''{0}'' must be initialized", NAME); - put(UNINITIALIZED_PARAMETER, "Parameter ''{0}'' is uninitialized here", NAME); - put(UNUSED_VARIABLE, "Variable ''{0}'' is never used", NAME); - put(UNUSED_PARAMETER, "Parameter ''{0}'' is never used", NAME); - put(ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE, "Variable ''{0}'' is assigned but never accessed", NAME); - put(VARIABLE_WITH_REDUNDANT_INITIALIZER, "Variable ''{0}'' initializer is redundant", NAME); - put(UNUSED_VALUE, "The value ''{0}'' assigned to ''{1}'' is never used", ELEMENT_TEXT, TO_STRING); - put(UNUSED_CHANGED_VALUE, "The value changed at ''{0}'' is never used", ELEMENT_TEXT); - put(UNUSED_EXPRESSION, "The expression is unused"); - put(UNUSED_FUNCTION_LITERAL, "The function literal is unused. If you mean block, you can use 'run { ... }'"); - - put(VAL_REASSIGNMENT, "Val can not be reassigned", NAME); - put(INITIALIZATION_BEFORE_DECLARATION, "Variable cannot be initialized before declaration", NAME); - put(VARIABLE_EXPECTED, "Variable expected"); - - put(INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER, - "This property has a custom setter, so initialization using backing field required", NAME); - put(INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER, - "Setter of this property can be overridden, so initialization using backing field required", NAME); - - put(FUNCTION_PARAMETERS_OF_INLINE_FUNCTION, "Function parameters of inline function can only be invoked", NAME); - - put(UNREACHABLE_CODE, "Unreachable code"); - - put(MANY_CLASS_OBJECTS, "Only one class object is allowed per class"); - put(CLASS_OBJECT_NOT_ALLOWED, "A class object is not allowed here"); - put(DELEGATION_IN_TRAIT, "Traits cannot use delegation"); - put(DELEGATION_NOT_TO_TRAIT, "Only traits can be delegated to"); - put(NO_CONSTRUCTOR, "This class does not have a constructor"); - put(NOT_A_CLASS, "Not a class"); - put(ILLEGAL_ESCAPE_SEQUENCE, "Illegal escape sequence"); - - put(LOCAL_EXTENSION_PROPERTY, "Local extension properties are not allowed"); - put(LOCAL_VARIABLE_WITH_GETTER, "Local variables are not allowed to have getters"); - put(LOCAL_VARIABLE_WITH_SETTER, "Local variables are not allowed to have setters"); - put(VAL_WITH_SETTER, "A 'val'-property cannot have a setter"); - - put(NO_GET_METHOD, "No get method providing array access"); - put(NO_SET_METHOD, "No set method providing array access"); - - put(INC_DEC_SHOULD_NOT_RETURN_UNIT, "Functions inc(), dec() shouldn't return Unit to be used by operators ++, --"); - put(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT, "Function ''{0}'' should return Unit to be used by corresponding operator ''{1}''", - NAME, ELEMENT_TEXT); - put(ASSIGN_OPERATOR_AMBIGUITY, "Assignment operators ambiguity: {0}", AMBIGUOUS_CALLS); - - put(EQUALS_MISSING, "No method 'equals(Any?) : Boolean' available"); - put(ASSIGNMENT_IN_EXPRESSION_CONTEXT, "Assignments are not expressions, and only expressions are allowed in this context"); - put(NAMESPACE_IS_NOT_AN_EXPRESSION, "'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')"); - put(SUPER_IS_NOT_AN_EXPRESSION, "{0} is not an expression, it can only be used on the left-hand side of a dot ('.')", TO_STRING); - put(DECLARATION_IN_ILLEGAL_CONTEXT, "Declarations are not allowed in this position"); - put(SETTER_PARAMETER_WITH_DEFAULT_VALUE, "Setter parameters can not have default values"); - put(NO_THIS, "'this' is not defined in this context"); - put(SUPER_NOT_AVAILABLE, "No supertypes are accessible in this context"); - put(AMBIGUOUS_SUPER, "Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super'"); - put(ABSTRACT_SUPER_CALL, "Abstract member cannot be accessed directly"); - put(NOT_A_SUPERTYPE, "Not a supertype"); - put(TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER, "Type arguments do not need to be specified in a 'super' qualifier"); - put(USELESS_CAST_STATIC_ASSERT_IS_FINE, "No cast needed, use ':' instead"); - put(USELESS_CAST, "No cast needed"); - put(CAST_NEVER_SUCCEEDS, "This cast can never succeed"); - put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property, i.e. {0}", RENDER_TYPE); - put(WRONG_GETTER_RETURN_TYPE, "Getter return type must be equal to the type of the property, i.e. {0}", RENDER_TYPE); - put(NO_CLASS_OBJECT, "Please specify constructor invocation; classifier {0} does not have a class object", NAME); - put(NO_GENERICS_IN_SUPERTYPE_SPECIFIER, "Generic arguments of the base type must be specified"); - - put(HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY, - "An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext' property"); - put(HAS_NEXT_MISSING, "Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property"); - put(HAS_NEXT_FUNCTION_AMBIGUITY, "Function 'iterator().hasNext()' is ambiguous for this expression"); - put(HAS_NEXT_MUST_BE_READABLE, "The 'iterator().hasNext' property of the loop range must be readable"); - put(HAS_NEXT_PROPERTY_TYPE_MISMATCH, "The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", - RENDER_TYPE); - put(HAS_NEXT_FUNCTION_TYPE_MISMATCH, "The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", - RENDER_TYPE); - put(NEXT_AMBIGUITY, "Function 'iterator().next()' is ambiguous for this expression"); - put(NEXT_MISSING, "Loop range must have an 'iterator().next()' function"); - put(ITERATOR_MISSING, "For-loop range must have an iterator() method"); - put(ITERATOR_AMBIGUITY, "Method 'iterator()' is ambiguous for this expression: {0}", AMBIGUOUS_CALLS); - - put(COMPARE_TO_TYPE_MISMATCH, "compareTo() must return Int, but returns {0}", RENDER_TYPE); - put(CALLEE_NOT_A_FUNCTION, "Expecting a function type, but found {0}", RENDER_TYPE); - - put(RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY, - "Returns are not allowed for functions with expression body. Use block body in '{...}'"); - put(NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY, "A 'return' expression required in a function with a block body ('{...}')"); - put(RETURN_TYPE_MISMATCH, "This function must return a value of type {0}", RENDER_TYPE); - put(EXPECTED_TYPE_MISMATCH, "Expected a value of type {0}", RENDER_TYPE); - put(ASSIGNMENT_TYPE_MISMATCH, - "Expected a value of type {0}. Assignment operation is not an expression, so it does not return any value", RENDER_TYPE); - put(IMPLICIT_CAST_TO_UNIT_OR_ANY, "Type was casted to ''{0}''. Please specify ''{0}'' as expected type, if you mean such cast", - RENDER_TYPE); - put(EXPRESSION_EXPECTED, "{0} is not an expression, and only expression are allowed here", new Renderer() { - @NotNull - @Override - public String render(@NotNull JetExpression expression) { - String expressionType = expression.toString(); - return expressionType.substring(0, 1) + - expressionType.substring(1).toLowerCase(); - } - }); - - put(UPPER_BOUND_VIOLATED, "An upper bound {0} is violated", RENDER_TYPE); // TODO : Message - put(FINAL_CLASS_OBJECT_UPPER_BOUND, "{0} is a final type, and thus a class object cannot extend it", RENDER_TYPE); - put(FINAL_UPPER_BOUND, "{0} is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE); - put(USELESS_ELVIS, "Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE); - put(CONFLICTING_UPPER_BOUNDS, "Upper bounds of {0} have empty intersection", NAME); - put(CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS, "Class object upper bounds of {0} have empty intersection", NAME); - - put(TOO_MANY_ARGUMENTS, "Too many arguments for {0}", TO_STRING); - put(ERROR_COMPILE_TIME_VALUE, "{0}", TO_STRING); - - put(ELSE_MISPLACED_IN_WHEN, "'else' entry must be the last one in a when-expression"); - - put(NO_ELSE_IN_WHEN, "'when' expression must contain 'else' branch"); - put(TYPE_MISMATCH_IN_RANGE, "Type mismatch: incompatible types of range and element checked in it"); - put(CYCLIC_INHERITANCE_HIERARCHY, "There's a cycle in the inheritance hierarchy for this type"); - - put(MANY_CLASSES_IN_SUPERTYPE_LIST, "Only one class may appear in a supertype list"); - put(SUPERTYPE_NOT_A_CLASS_OR_TRAIT, "Only classes and traits may serve as supertypes"); - put(SUPERTYPE_INITIALIZED_IN_TRAIT, "Traits cannot initialize supertypes"); - put(CONSTRUCTOR_IN_TRAIT, "A trait may not have a constructor"); - put(SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED, "Secondary constructors are not supported"); - put(SUPERTYPE_APPEARS_TWICE, "A supertype appears twice"); - put(FINAL_SUPERTYPE, "This type is final, so it cannot be inherited from"); - - put(ILLEGAL_SELECTOR, "Expression ''{0}'' cannot be a selector (occur after a dot)", TO_STRING); - - put(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION, "A type annotation is required on a value parameter"); - put(BREAK_OR_CONTINUE_OUTSIDE_A_LOOP, "'break' and 'continue' are only allowed inside a loop"); - put(NOT_A_LOOP_LABEL, "The label ''{0}'' does not denote a loop", TO_STRING); - put(NOT_A_RETURN_LABEL, "The label ''{0}'' does not reference to a context from which we can return", TO_STRING); - - put(ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR, "Anonymous initializers are only allowed in the presence of a primary constructor"); - put(NULLABLE_SUPERTYPE, "A supertype cannot be nullable"); - put(UNSAFE_CALL, "Only safe calls (?.) are allowed on a nullable receiver of type {0}", RENDER_TYPE); - put(AMBIGUOUS_LABEL, "Ambiguous label"); - put(UNSUPPORTED, "Unsupported [{0}]", TO_STRING); - put(UNNECESSARY_SAFE_CALL, "Unnecessary safe call on a non-null receiver of type {0}", RENDER_TYPE); - put(UNNECESSARY_NOT_NULL_ASSERTION, "Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", RENDER_TYPE); - put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, "{0} does not refer to a type parameter of {1}", new Renderer() { - @NotNull - @Override - public String render(@NotNull JetTypeConstraint typeConstraint) { - //noinspection ConstantConditions - return typeConstraint.getSubjectTypeParameterName().getReferencedName(); - } - }, NAME); - put(AUTOCAST_IMPOSSIBLE, "Automatic cast to {0} is impossible, because {1} could have changed since the is-check", RENDER_TYPE, - NAME); - - put(TYPE_MISMATCH_IN_FOR_LOOP, "The loop iterates over values of type {0} but the parameter is declared to be {1}", RENDER_TYPE, - RENDER_TYPE); - put(TYPE_MISMATCH_IN_CONDITION, "Condition must be of type Boolean, but was of type {0}", RENDER_TYPE); - put(TYPE_MISMATCH_IN_TUPLE_PATTERN, "Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, - TO_STRING); // TODO: message - put(TYPE_MISMATCH_IN_BINDING_PATTERN, "{0} must be a supertype of {1}. Use 'is' to match against {0}", RENDER_TYPE, RENDER_TYPE); - put(INCOMPATIBLE_TYPES, "Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE); - put(EXPECTED_CONDITION, "Expected condition of Boolean type"); - - put(CANNOT_CHECK_FOR_ERASED, "Cannot check for instance of erased type: {0}", RENDER_TYPE); - put(UNCHECKED_CAST, "Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE); - - put(INCONSISTENT_TYPE_PARAMETER_VALUES, "Type parameter {0} of {1} has inconsistent values: {2}", NAME, DescriptorRenderer.TEXT, - new Renderer>() { - @NotNull - @Override - public String render(@NotNull Collection types) { - StringBuilder builder = new StringBuilder(); - for (Iterator iterator = types.iterator(); iterator.hasNext(); ) { - JetType jetType = iterator.next(); - builder.append(jetType); - if (iterator.hasNext()) { - builder.append(", "); - } - } - return builder.toString(); - } - }); - - put(EQUALITY_NOT_APPLICABLE, "Operator {0} cannot be applied to {1} and {2}", new Renderer() { - @NotNull - @Override - public String render(@NotNull JetSimpleNameExpression nameExpression) { - //noinspection ConstantConditions - return nameExpression.getReferencedName(); - } - }, TO_STRING, TO_STRING); - - put(OVERRIDING_FINAL_MEMBER, "''{0}'' in ''{1}'' is final and cannot be overridden", NAME, NAME); - put(CANNOT_WEAKEN_ACCESS_PRIVILEGE, "Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME); - put(CANNOT_CHANGE_ACCESS_PRIVILEGE, "Cannot change access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME); - - put(RETURN_TYPE_MISMATCH_ON_OVERRIDE, "Return type of {0} is not a subtype of the return type overridden member {1}", - DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); - - put(VAR_OVERRIDDEN_BY_VAL, "Var-property {0} cannot be overridden by val-property {1}", DescriptorRenderer.TEXT, - DescriptorRenderer.TEXT); - - put(ABSTRACT_MEMBER_NOT_IMPLEMENTED, "{0} must be declared abstract or implement abstract member {1}", RENDER_CLASS_OR_OBJECT, - DescriptorRenderer.TEXT); - - put(MANY_IMPL_MEMBER_NOT_IMPLEMENTED, "{0} must override {1} because it inherits many implementations of it", - RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT); - - put(CONFLICTING_OVERLOADS, "{1} is already defined in ''{0}''", DescriptorRenderer.TEXT, TO_STRING); - - - put(RESULT_TYPE_MISMATCH, "{0} must return {1} but returns {2}", TO_STRING, RENDER_TYPE, RENDER_TYPE); - put(UNSAFE_INFIX_CALL, - "Infix call corresponds to a dot-qualified call ''{0}.{1}({2})'' which is not allowed on a nullable receiver ''{0}''. " + - "Use '?.'-qualified call instead", - TO_STRING, TO_STRING, TO_STRING); - - put(OVERLOAD_RESOLUTION_AMBIGUITY, "Overload resolution ambiguity: {0}", AMBIGUOUS_CALLS); - put(NONE_APPLICABLE, "None of the following functions can be called with the arguments supplied: {0}", AMBIGUOUS_CALLS); - put(NO_VALUE_FOR_PARAMETER, "No value passed for parameter {0}", DescriptorRenderer.TEXT); - put(MISSING_RECEIVER, "A receiver of type {0} is required", RENDER_TYPE); - put(NO_RECEIVER_ADMITTED, "No receiver can be passed to this function or property"); - - put(CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS, "Can not create an instance of an abstract class"); - put(TYPE_INFERENCE_FAILED, "Type inference failed: {0}", TO_STRING); - put(WRONG_NUMBER_OF_TYPE_ARGUMENTS, "{0} type arguments expected", new Renderer() { - @NotNull - @Override - public String render(@NotNull Integer argument) { - return argument == 0 ? "No" : argument.toString(); - } - }); - - put(UNRESOLVED_IDE_TEMPLATE, "Unresolved IDE template: {0}", TO_STRING); - - put(DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED, - "This expression is treated as an argument to the function call on the previous line. " + - "Separate it with a semicolon (;) if it is not intended to be an argument."); - - put(NOT_AN_ANNOTATION_CLASS, "{0} is not an annotation class", TO_STRING); - } + private final DiagnosticFactoryToRendererMap map = DefaultErrorMessages.MAP; @NotNull @Override diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java new file mode 100644 index 00000000000..f9954ace34c --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -0,0 +1,408 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.lang.diagnostics.rendering; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.descriptors.CallableDescriptor; +import org.jetbrains.jet.lang.psi.JetExpression; +import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; +import org.jetbrains.jet.lang.psi.JetTypeConstraint; +import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; +import org.jetbrains.jet.lang.types.JetType; +import org.jetbrains.jet.lexer.JetKeywordToken; +import org.jetbrains.jet.resolve.DescriptorRenderer; + +import java.util.Collection; +import java.util.Iterator; + +import static org.jetbrains.jet.lang.diagnostics.Errors.*; +import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.*; +import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.RENDER_TYPE; +import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.TO_STRING; + +/** + * @author Evgeny Gerashchenko + * @since 4/13/12 + */ +public class DefaultErrorMessages { + public static final DiagnosticFactoryToRendererMap MAP = new DiagnosticFactoryToRendererMap(); + + private static final Renderer>> AMBIGUOUS_CALLS = + new Renderer>>() { + @NotNull + @Override + public String render(@NotNull Collection> argument) { + StringBuilder stringBuilder = new StringBuilder("\n"); + for (ResolvedCall call : argument) { + stringBuilder.append(DescriptorRenderer.TEXT.render(call.getResultingDescriptor())).append("\n"); + } + return stringBuilder.toString(); + } + }; + + static { + MAP.put(EXCEPTION_WHILE_ANALYZING, "{0}", new Renderer() { + @NotNull + @Override + public String render(@NotNull Throwable e) { + return e.getClass().getSimpleName() + ": " + e.getMessage(); + } + }); + + MAP.put(UNRESOLVED_REFERENCE, "Unresolved reference: {0}", TO_STRING); + + MAP.put(INVISIBLE_REFERENCE, "Cannot access ''{0}'' in ''{1}''", NAME, NAME); + MAP.put(INVISIBLE_MEMBER, "Cannot access ''{0}'' in ''{1}''", NAME, NAME); + + MAP.put(REDECLARATION, "Redeclaration: {0}", NAME); + MAP.put(NAME_SHADOWING, "Name shadowed: {0}", NAME); + + MAP.put(TYPE_MISMATCH, "Type mismatch: inferred type is {1} but {0} was expected", RENDER_TYPE, RENDER_TYPE); + MAP.put(INCOMPATIBLE_MODIFIERS, "Incompatible modifiers: ''{0}''", new Renderer>() { + @NotNull + @Override + public String render(@NotNull Collection tokens) { + StringBuilder sb = new StringBuilder(); + for (Iterator iterator = tokens.iterator(); iterator.hasNext(); ) { + JetKeywordToken modifier = iterator.next(); + sb.append(modifier.getValue()); + if (iterator.hasNext()) { + sb.append(" "); + } + } + return sb.toString(); + } + }); + MAP.put(ILLEGAL_MODIFIER, "Illegal modifier ''{0}''", TO_STRING); + + MAP.put(REDUNDANT_MODIFIER, "Modifier {0} is redundant because {1} is present", TO_STRING, TO_STRING); + MAP.put(ABSTRACT_MODIFIER_IN_TRAIT, "Modifier ''abstract'' is redundant in trait"); + MAP.put(OPEN_MODIFIER_IN_TRAIT, "Modifier ''open'' is redundant in trait"); + MAP.put(REDUNDANT_MODIFIER_IN_GETTER, "Visibility modifiers are redundant in getter"); + MAP.put(TRAIT_CAN_NOT_BE_FINAL, "Trait can not be final"); + MAP.put(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM, + "Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly"); // TODO: message + MAP.put(RETURN_NOT_ALLOWED, "'return' is not allowed here"); + MAP.put(PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE, "Projections are not allowed for immediate arguments of a supertype"); + MAP.put(LABEL_NAME_CLASH, "There is more than one label with such a name in this scope"); + MAP.put(EXPRESSION_EXPECTED_NAMESPACE_FOUND, "Expression expected, but a namespace name found"); + + MAP.put(CANNOT_IMPORT_FROM_ELEMENT, "Cannot import from ''{0}''", NAME); + MAP.put(CANNOT_BE_IMPORTED, "Cannot import ''{0}'', functions and properties can be imported only from packages", NAME); + MAP.put(USELESS_HIDDEN_IMPORT, "Useless import, it is hidden further"); + MAP.put(USELESS_SIMPLE_IMPORT, "Useless import, does nothing"); + + MAP.put(CANNOT_INFER_PARAMETER_TYPE, + "Cannot infer a type for this parameter. To specify it explicitly use the {(p : Type) => ...} notation"); + + MAP.put(NO_BACKING_FIELD_ABSTRACT_PROPERTY, "This property doesn't have a backing field, because it's abstract"); + MAP.put(NO_BACKING_FIELD_CUSTOM_ACCESSORS, + "This property doesn't have a backing field, because it has custom accessors without reference to the backing field"); + MAP.put(INACCESSIBLE_BACKING_FIELD, "The backing field is not accessible here"); + MAP.put(NOT_PROPERTY_BACKING_FIELD, "The referenced variable is not a property and doesn't have backing field"); + + MAP.put(MIXING_NAMED_AND_POSITIONED_ARGUMENTS, "Mixing named and positioned arguments in not allowed"); + MAP.put(ARGUMENT_PASSED_TWICE, "An argument is already passed for this parameter"); + MAP.put(NAMED_PARAMETER_NOT_FOUND, "Cannot find a parameter with this name: {0}", TO_STRING); + MAP.put(VARARG_OUTSIDE_PARENTHESES, "Passing value as a vararg is only allowed inside a parenthesized argument list"); + MAP.put(NON_VARARG_SPREAD, "The spread operator (*foo) may only be applied in a vararg position"); + + MAP.put(MANY_FUNCTION_LITERAL_ARGUMENTS, "Only one function literal is allowed outside a parenthesized argument list"); + MAP.put(PROPERTY_WITH_NO_TYPE_NO_INITIALIZER, "This property must either have a type annotation or be initialized"); + + MAP.put(ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS, "This property cannot be declared abstract"); + MAP.put(ABSTRACT_PROPERTY_NOT_IN_CLASS, "A property may be abstract only when defined in a class or trait"); + MAP.put(ABSTRACT_PROPERTY_WITH_INITIALIZER, "Property with initializer cannot be abstract"); + MAP.put(ABSTRACT_PROPERTY_WITH_GETTER, "Property with getter implementation cannot be abstract"); + MAP.put(ABSTRACT_PROPERTY_WITH_SETTER, "Property with setter implementation cannot be abstract"); + + MAP.put(PACKAGE_MEMBER_CANNOT_BE_PROTECTED, "Package member cannot be protected"); + + MAP.put(GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY, "Getter visibility must be the same as property visibility"); + MAP.put(BACKING_FIELD_IN_TRAIT, "Property in a trait cannot have a backing field"); + MAP.put(MUST_BE_INITIALIZED, "Property must be initialized"); + MAP.put(MUST_BE_INITIALIZED_OR_BE_ABSTRACT, "Property must be initialized or be abstract"); + MAP.put(PROPERTY_INITIALIZER_IN_TRAIT, "Property initializers are not allowed in traits"); + MAP.put(PROPERTY_INITIALIZER_NO_BACKING_FIELD, "Initializer is not allowed here because this property has no backing field"); + MAP.put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, "Abstract property {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING); + MAP.put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, "Abstract function {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING); + MAP.put(ABSTRACT_FUNCTION_WITH_BODY, "A function {0} with body cannot be abstract", TO_STRING); + MAP.put(NON_ABSTRACT_FUNCTION_WITH_NO_BODY, "Method {0} without a body must be abstract", TO_STRING); + MAP.put(NON_MEMBER_ABSTRACT_FUNCTION, "Function {0} is not a class or trait member and cannot be abstract", TO_STRING); + + MAP.put(NON_MEMBER_FUNCTION_NO_BODY, "Function {0} must have a body", TO_STRING); + MAP.put(NON_FINAL_MEMBER_IN_FINAL_CLASS, "Non final member in a final class"); + + MAP.put(PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE, "Public or protected member should specify a type"); + + MAP.put(PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT, + "Projections are not allowed on type arguments of functions and properties"); // TODO : better positioning + MAP.put(SUPERTYPE_NOT_INITIALIZED, "This type has a constructor, and thus must be initialized here"); + MAP.put(SUPERTYPE_NOT_INITIALIZED_DEFAULT, "Constructor invocation should be explicitly specified"); + MAP.put(SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY, "A secondary constructor may appear only in a class that has a primary constructor"); + MAP.put(SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST, "Secondary constructors must have an initializer list"); + MAP.put(BY_IN_SECONDARY_CONSTRUCTOR, "'by'-clause is only supported for primary constructors"); + MAP.put(INITIALIZER_WITH_NO_ARGUMENTS, "Constructor arguments required"); + MAP.put(MANY_CALLS_TO_THIS, "Only one call to 'this(...)' is allowed"); + MAP.put(NOTHING_TO_OVERRIDE, "{0} overrides nothing", DescriptorRenderer.TEXT); + MAP.put(VIRTUAL_MEMBER_HIDDEN, "''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", DescriptorRenderer.TEXT, + DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); + + MAP.put(ENUM_ENTRY_SHOULD_BE_INITIALIZED, "Missing delegation specifier ''{0}''", NAME); + MAP.put(ENUM_ENTRY_ILLEGAL_TYPE, "The type constructor of enum entry should be ''{0}''", NAME); + + MAP.put(UNINITIALIZED_VARIABLE, "Variable ''{0}'' must be initialized", NAME); + MAP.put(UNINITIALIZED_PARAMETER, "Parameter ''{0}'' is uninitialized here", NAME); + MAP.put(UNUSED_VARIABLE, "Variable ''{0}'' is never used", NAME); + MAP.put(UNUSED_PARAMETER, "Parameter ''{0}'' is never used", NAME); + MAP.put(ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE, "Variable ''{0}'' is assigned but never accessed", NAME); + MAP.put(VARIABLE_WITH_REDUNDANT_INITIALIZER, "Variable ''{0}'' initializer is redundant", NAME); + MAP.put(UNUSED_VALUE, "The value ''{0}'' assigned to ''{1}'' is never used", ELEMENT_TEXT, TO_STRING); + MAP.put(UNUSED_CHANGED_VALUE, "The value changed at ''{0}'' is never used", ELEMENT_TEXT); + MAP.put(UNUSED_EXPRESSION, "The expression is unused"); + MAP.put(UNUSED_FUNCTION_LITERAL, "The function literal is unused. If you mean block, you can use 'run { ... }'"); + + MAP.put(VAL_REASSIGNMENT, "Val can not be reassigned", NAME); + MAP.put(INITIALIZATION_BEFORE_DECLARATION, "Variable cannot be initialized before declaration", NAME); + MAP.put(VARIABLE_EXPECTED, "Variable expected"); + + MAP.put(INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER, + "This property has a custom setter, so initialization using backing field required", NAME); + MAP.put(INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER, + "Setter of this property can be overridden, so initialization using backing field required", NAME); + + MAP.put(FUNCTION_PARAMETERS_OF_INLINE_FUNCTION, "Function parameters of inline function can only be invoked", NAME); + + MAP.put(UNREACHABLE_CODE, "Unreachable code"); + + MAP.put(MANY_CLASS_OBJECTS, "Only one class object is allowed per class"); + MAP.put(CLASS_OBJECT_NOT_ALLOWED, "A class object is not allowed here"); + MAP.put(DELEGATION_IN_TRAIT, "Traits cannot use delegation"); + MAP.put(DELEGATION_NOT_TO_TRAIT, "Only traits can be delegated to"); + MAP.put(NO_CONSTRUCTOR, "This class does not have a constructor"); + MAP.put(NOT_A_CLASS, "Not a class"); + MAP.put(ILLEGAL_ESCAPE_SEQUENCE, "Illegal escape sequence"); + + MAP.put(LOCAL_EXTENSION_PROPERTY, "Local extension properties are not allowed"); + MAP.put(LOCAL_VARIABLE_WITH_GETTER, "Local variables are not allowed to have getters"); + MAP.put(LOCAL_VARIABLE_WITH_SETTER, "Local variables are not allowed to have setters"); + MAP.put(VAL_WITH_SETTER, "A 'val'-property cannot have a setter"); + + MAP.put(NO_GET_METHOD, "No get method providing array access"); + MAP.put(NO_SET_METHOD, "No set method providing array access"); + + MAP.put(INC_DEC_SHOULD_NOT_RETURN_UNIT, "Functions inc(), dec() shouldn't return Unit to be used by operators ++, --"); + MAP.put(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT, "Function ''{0}'' should return Unit to be used by corresponding operator ''{1}''", + NAME, ELEMENT_TEXT); + MAP.put(ASSIGN_OPERATOR_AMBIGUITY, "Assignment operators ambiguity: {0}", AMBIGUOUS_CALLS); + + MAP.put(EQUALS_MISSING, "No method 'equals(Any?) : Boolean' available"); + MAP.put(ASSIGNMENT_IN_EXPRESSION_CONTEXT, "Assignments are not expressions, and only expressions are allowed in this context"); + MAP.put(NAMESPACE_IS_NOT_AN_EXPRESSION, "'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')"); + MAP.put(SUPER_IS_NOT_AN_EXPRESSION, "{0} is not an expression, it can only be used on the left-hand side of a dot ('.')", TO_STRING); + MAP.put(DECLARATION_IN_ILLEGAL_CONTEXT, "Declarations are not allowed in this position"); + MAP.put(SETTER_PARAMETER_WITH_DEFAULT_VALUE, "Setter parameters can not have default values"); + MAP.put(NO_THIS, "'this' is not defined in this context"); + MAP.put(SUPER_NOT_AVAILABLE, "No supertypes are accessible in this context"); + MAP.put(AMBIGUOUS_SUPER, "Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super'"); + MAP.put(ABSTRACT_SUPER_CALL, "Abstract member cannot be accessed directly"); + MAP.put(NOT_A_SUPERTYPE, "Not a supertype"); + MAP.put(TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER, "Type arguments do not need to be specified in a 'super' qualifier"); + MAP.put(USELESS_CAST_STATIC_ASSERT_IS_FINE, "No cast needed, use ':' instead"); + MAP.put(USELESS_CAST, "No cast needed"); + MAP.put(CAST_NEVER_SUCCEEDS, "This cast can never succeed"); + MAP.put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property, i.e. {0}", RENDER_TYPE); + MAP.put(WRONG_GETTER_RETURN_TYPE, "Getter return type must be equal to the type of the property, i.e. {0}", RENDER_TYPE); + MAP.put(NO_CLASS_OBJECT, "Please specify constructor invocation; classifier {0} does not have a class object", NAME); + MAP.put(NO_GENERICS_IN_SUPERTYPE_SPECIFIER, "Generic arguments of the base type must be specified"); + + MAP.put(HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY, + "An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext' property"); + MAP.put(HAS_NEXT_MISSING, "Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property"); + MAP.put(HAS_NEXT_FUNCTION_AMBIGUITY, "Function 'iterator().hasNext()' is ambiguous for this expression"); + MAP.put(HAS_NEXT_MUST_BE_READABLE, "The 'iterator().hasNext' property of the loop range must be readable"); + MAP.put(HAS_NEXT_PROPERTY_TYPE_MISMATCH, "The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", + RENDER_TYPE); + MAP.put(HAS_NEXT_FUNCTION_TYPE_MISMATCH, "The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", + RENDER_TYPE); + MAP.put(NEXT_AMBIGUITY, "Function 'iterator().next()' is ambiguous for this expression"); + MAP.put(NEXT_MISSING, "Loop range must have an 'iterator().next()' function"); + MAP.put(ITERATOR_MISSING, "For-loop range must have an iterator() method"); + MAP.put(ITERATOR_AMBIGUITY, "Method 'iterator()' is ambiguous for this expression: {0}", AMBIGUOUS_CALLS); + + MAP.put(COMPARE_TO_TYPE_MISMATCH, "compareTo() must return Int, but returns {0}", RENDER_TYPE); + MAP.put(CALLEE_NOT_A_FUNCTION, "Expecting a function type, but found {0}", RENDER_TYPE); + + MAP.put(RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY, + "Returns are not allowed for functions with expression body. Use block body in '{...}'"); + MAP.put(NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY, "A 'return' expression required in a function with a block body ('{...}')"); + MAP.put(RETURN_TYPE_MISMATCH, "This function must return a value of type {0}", RENDER_TYPE); + MAP.put(EXPECTED_TYPE_MISMATCH, "Expected a value of type {0}", RENDER_TYPE); + MAP.put(ASSIGNMENT_TYPE_MISMATCH, + "Expected a value of type {0}. Assignment operation is not an expression, so it does not return any value", RENDER_TYPE); + MAP.put(IMPLICIT_CAST_TO_UNIT_OR_ANY, "Type was casted to ''{0}''. Please specify ''{0}'' as expected type, if you mean such cast", + RENDER_TYPE); + MAP.put(EXPRESSION_EXPECTED, "{0} is not an expression, and only expression are allowed here", new Renderer() { + @NotNull + @Override + public String render(@NotNull JetExpression expression) { + String expressionType = expression.toString(); + return expressionType.substring(0, 1) + + expressionType.substring(1).toLowerCase(); + } + }); + + MAP.put(UPPER_BOUND_VIOLATED, "An upper bound {0} is violated", RENDER_TYPE); // TODO : Message + MAP.put(FINAL_CLASS_OBJECT_UPPER_BOUND, "{0} is a final type, and thus a class object cannot extend it", RENDER_TYPE); + MAP.put(FINAL_UPPER_BOUND, "{0} is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE); + MAP.put(USELESS_ELVIS, "Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE); + MAP.put(CONFLICTING_UPPER_BOUNDS, "Upper bounds of {0} have empty intersection", NAME); + MAP.put(CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS, "Class object upper bounds of {0} have empty intersection", NAME); + + MAP.put(TOO_MANY_ARGUMENTS, "Too many arguments for {0}", TO_STRING); + MAP.put(ERROR_COMPILE_TIME_VALUE, "{0}", TO_STRING); + + MAP.put(ELSE_MISPLACED_IN_WHEN, "'else' entry must be the last one in a when-expression"); + + MAP.put(NO_ELSE_IN_WHEN, "'when' expression must contain 'else' branch"); + MAP.put(TYPE_MISMATCH_IN_RANGE, "Type mismatch: incompatible types of range and element checked in it"); + MAP.put(CYCLIC_INHERITANCE_HIERARCHY, "There's a cycle in the inheritance hierarchy for this type"); + + MAP.put(MANY_CLASSES_IN_SUPERTYPE_LIST, "Only one class may appear in a supertype list"); + MAP.put(SUPERTYPE_NOT_A_CLASS_OR_TRAIT, "Only classes and traits may serve as supertypes"); + MAP.put(SUPERTYPE_INITIALIZED_IN_TRAIT, "Traits cannot initialize supertypes"); + MAP.put(CONSTRUCTOR_IN_TRAIT, "A trait may not have a constructor"); + MAP.put(SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED, "Secondary constructors are not supported"); + MAP.put(SUPERTYPE_APPEARS_TWICE, "A supertype appears twice"); + MAP.put(FINAL_SUPERTYPE, "This type is final, so it cannot be inherited from"); + + MAP.put(ILLEGAL_SELECTOR, "Expression ''{0}'' cannot be a selector (occur after a dot)", TO_STRING); + + MAP.put(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION, "A type annotation is required on a value parameter"); + MAP.put(BREAK_OR_CONTINUE_OUTSIDE_A_LOOP, "'break' and 'continue' are only allowed inside a loop"); + MAP.put(NOT_A_LOOP_LABEL, "The label ''{0}'' does not denote a loop", TO_STRING); + MAP.put(NOT_A_RETURN_LABEL, "The label ''{0}'' does not reference to a context from which we can return", TO_STRING); + + MAP.put(ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR, "Anonymous initializers are only allowed in the presence of a primary constructor"); + MAP.put(NULLABLE_SUPERTYPE, "A supertype cannot be nullable"); + MAP.put(UNSAFE_CALL, "Only safe calls (?.) are allowed on a nullable receiver of type {0}", RENDER_TYPE); + MAP.put(AMBIGUOUS_LABEL, "Ambiguous label"); + MAP.put(UNSUPPORTED, "Unsupported [{0}]", TO_STRING); + MAP.put(UNNECESSARY_SAFE_CALL, "Unnecessary safe call on a non-null receiver of type {0}", RENDER_TYPE); + MAP.put(UNNECESSARY_NOT_NULL_ASSERTION, "Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", RENDER_TYPE); + MAP.put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, "{0} does not refer to a type parameter of {1}", new Renderer() { + @NotNull + @Override + public String render(@NotNull JetTypeConstraint typeConstraint) { + //noinspection ConstantConditions + return typeConstraint.getSubjectTypeParameterName().getReferencedName(); + } + }, NAME); + MAP.put(AUTOCAST_IMPOSSIBLE, "Automatic cast to {0} is impossible, because {1} could have changed since the is-check", RENDER_TYPE, + NAME); + + MAP.put(TYPE_MISMATCH_IN_FOR_LOOP, "The loop iterates over values of type {0} but the parameter is declared to be {1}", RENDER_TYPE, + RENDER_TYPE); + MAP.put(TYPE_MISMATCH_IN_CONDITION, "Condition must be of type Boolean, but was of type {0}", RENDER_TYPE); + MAP.put(TYPE_MISMATCH_IN_TUPLE_PATTERN, "Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, + TO_STRING); // TODO: message + MAP.put(TYPE_MISMATCH_IN_BINDING_PATTERN, "{0} must be a supertype of {1}. Use 'is' to match against {0}", RENDER_TYPE, RENDER_TYPE); + MAP.put(INCOMPATIBLE_TYPES, "Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE); + MAP.put(EXPECTED_CONDITION, "Expected condition of Boolean type"); + + MAP.put(CANNOT_CHECK_FOR_ERASED, "Cannot check for instance of erased type: {0}", RENDER_TYPE); + MAP.put(UNCHECKED_CAST, "Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE); + + MAP.put(INCONSISTENT_TYPE_PARAMETER_VALUES, "Type parameter {0} of {1} has inconsistent values: {2}", NAME, DescriptorRenderer.TEXT, + new Renderer>() { + @NotNull + @Override + public String render(@NotNull Collection types) { + StringBuilder builder = new StringBuilder(); + for (Iterator iterator = types.iterator(); iterator.hasNext(); ) { + JetType jetType = iterator.next(); + builder.append(jetType); + if (iterator.hasNext()) { + builder.append(", "); + } + } + return builder.toString(); + } + }); + + MAP.put(EQUALITY_NOT_APPLICABLE, "Operator {0} cannot be applied to {1} and {2}", new Renderer() { + @NotNull + @Override + public String render(@NotNull JetSimpleNameExpression nameExpression) { + //noinspection ConstantConditions + return nameExpression.getReferencedName(); + } + }, TO_STRING, TO_STRING); + + MAP.put(OVERRIDING_FINAL_MEMBER, "''{0}'' in ''{1}'' is final and cannot be overridden", NAME, NAME); + MAP.put(CANNOT_WEAKEN_ACCESS_PRIVILEGE, "Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME); + MAP.put(CANNOT_CHANGE_ACCESS_PRIVILEGE, "Cannot change access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME); + + MAP.put(RETURN_TYPE_MISMATCH_ON_OVERRIDE, "Return type of {0} is not a subtype of the return type overridden member {1}", + DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); + + MAP.put(VAR_OVERRIDDEN_BY_VAL, "Var-property {0} cannot be overridden by val-property {1}", DescriptorRenderer.TEXT, + DescriptorRenderer.TEXT); + + MAP.put(ABSTRACT_MEMBER_NOT_IMPLEMENTED, "{0} must be declared abstract or implement abstract member {1}", RENDER_CLASS_OR_OBJECT, + DescriptorRenderer.TEXT); + + MAP.put(MANY_IMPL_MEMBER_NOT_IMPLEMENTED, "{0} must override {1} because it inherits many implementations of it", + RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT); + + MAP.put(CONFLICTING_OVERLOADS, "{1} is already defined in ''{0}''", DescriptorRenderer.TEXT, TO_STRING); + + + MAP.put(RESULT_TYPE_MISMATCH, "{0} must return {1} but returns {2}", TO_STRING, RENDER_TYPE, RENDER_TYPE); + MAP.put(UNSAFE_INFIX_CALL, + "Infix call corresponds to a dot-qualified call ''{0}.{1}({2})'' which is not allowed on a nullable receiver ''{0}''. " + + "Use '?.'-qualified call instead", + TO_STRING, TO_STRING, TO_STRING); + + MAP.put(OVERLOAD_RESOLUTION_AMBIGUITY, "Overload resolution ambiguity: {0}", AMBIGUOUS_CALLS); + MAP.put(NONE_APPLICABLE, "None of the following functions can be called with the arguments supplied: {0}", AMBIGUOUS_CALLS); + MAP.put(NO_VALUE_FOR_PARAMETER, "No value passed for parameter {0}", DescriptorRenderer.TEXT); + MAP.put(MISSING_RECEIVER, "A receiver of type {0} is required", RENDER_TYPE); + MAP.put(NO_RECEIVER_ADMITTED, "No receiver can be passed to this function or property"); + + MAP.put(CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS, "Can not create an instance of an abstract class"); + MAP.put(TYPE_INFERENCE_FAILED, "Type inference failed: {0}", TO_STRING); + MAP.put(WRONG_NUMBER_OF_TYPE_ARGUMENTS, "{0} type arguments expected", new Renderer() { + @NotNull + @Override + public String render(@NotNull Integer argument) { + return argument == 0 ? "No" : argument.toString(); + } + }); + + MAP.put(UNRESOLVED_IDE_TEMPLATE, "Unresolved IDE template: {0}", TO_STRING); + + MAP.put(DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED, + "This expression is treated as an argument to the function call on the previous line. " + + "Separate it with a semicolon (;) if it is not intended to be an argument."); + + MAP.put(NOT_AN_ANNOTATION_CLASS, "{0} is not an annotation class", TO_STRING); + } + + private DefaultErrorMessages() { + } +} diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java new file mode 100644 index 00000000000..3172e3f9144 --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java @@ -0,0 +1,62 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.lang.diagnostics.rendering; + +import com.intellij.psi.PsiElement; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.lang.diagnostics.*; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Evgeny Gerashchenko + * @since 4/13/12 + */ +public class DiagnosticFactoryToRendererMap { + private final Map> map = + new HashMap>(); + + public final void put(SimpleDiagnosticFactory factory, String message) { + map.put(factory, new SimpleDiagnosticRenderer(message)); + } + + public final void put(DiagnosticFactory1 factory, String message, Renderer rendererA) { + map.put(factory, new DiagnosticWithParameters1Renderer(message, rendererA)); + } + + public final void put(DiagnosticFactory2 factory, + String message, + Renderer rendererA, + Renderer rendererB) { + map.put(factory, new DiagnosticWithParameters2Renderer(message, rendererA, rendererB)); + } + + public final void put(DiagnosticFactory3 factory, + String message, + Renderer rendererA, + Renderer rendererB, + Renderer rendererC) { + map.put(factory, new DiagnosticWithParameters3Renderer(message, rendererA, rendererB, rendererC)); + } + + @Nullable + public final DiagnosticRenderer get(@NotNull AbstractDiagnosticFactory factory) { + return map.get(factory); + } +} From c1a9630051266e5fb742de3d4a55c85c9bbd2926 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 18:50:30 +0400 Subject: [PATCH 035/147] Moved AMBIGUOUS_CALLS from DefaultErrorMessages to Renderers. --- .../rendering/DefaultErrorMessages.java | 15 -------------- .../lang/diagnostics/rendering/Renderers.java | 20 +++++++++++++++++++ 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java index f9954ace34c..f0cae982a4c 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -17,11 +17,9 @@ package org.jetbrains.jet.lang.diagnostics.rendering; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.lang.descriptors.CallableDescriptor; import org.jetbrains.jet.lang.psi.JetExpression; import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; import org.jetbrains.jet.lang.psi.JetTypeConstraint; -import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lexer.JetKeywordToken; import org.jetbrains.jet.resolve.DescriptorRenderer; @@ -41,19 +39,6 @@ import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.TO_STRING; public class DefaultErrorMessages { public static final DiagnosticFactoryToRendererMap MAP = new DiagnosticFactoryToRendererMap(); - private static final Renderer>> AMBIGUOUS_CALLS = - new Renderer>>() { - @NotNull - @Override - public String render(@NotNull Collection> argument) { - StringBuilder stringBuilder = new StringBuilder("\n"); - for (ResolvedCall call : argument) { - stringBuilder.append(DescriptorRenderer.TEXT.render(call.getResultingDescriptor())).append("\n"); - } - return stringBuilder.toString(); - } - }; - static { MAP.put(EXCEPTION_WHILE_ANALYZING, "{0}", new Renderer() { @NotNull diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/Renderers.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/Renderers.java index 8e42eb60b4e..16527b27a30 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/Renderers.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/Renderers.java @@ -18,12 +18,16 @@ package org.jetbrains.jet.lang.diagnostics.rendering; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.descriptors.CallableDescriptor; import org.jetbrains.jet.lang.descriptors.Named; import org.jetbrains.jet.lang.psi.JetClass; import org.jetbrains.jet.lang.psi.JetClassOrObject; +import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.resolve.DescriptorRenderer; +import java.util.Collection; + /** * @author svtk */ @@ -80,4 +84,20 @@ public class Renderers { return DescriptorRenderer.TEXT.renderType(type); } }; + + public static final Renderer>> AMBIGUOUS_CALLS = + new Renderer>>() { + @NotNull + @Override + public String render(@NotNull Collection> argument) { + StringBuilder stringBuilder = new StringBuilder("\n"); + for (ResolvedCall call : argument) { + stringBuilder.append(DescriptorRenderer.TEXT.render(call.getResultingDescriptor())).append("\n"); + } + return stringBuilder.toString(); + } + }; + + private Renderers() { + } } From 370af95c8750e63f07f6c4baaaccce28e39d89d3 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 19:00:53 +0400 Subject: [PATCH 036/147] Introduced DispatchingDiagnosticRenderer, which replaced DefaultDiagnosticRenderer. --- .../jet/compiler/CompileSession.java | 4 ++-- .../rendering/DefaultErrorMessages.java | 2 ++ ...ava => DispatchingDiagnosticRenderer.java} | 22 +++++++++++-------- .../tests/org/jetbrains/jet/JetTestUtils.java | 4 ++-- .../jet/plugin/highlighter/JetPsiChecker.java | 4 ++-- 5 files changed, 21 insertions(+), 15 deletions(-) rename compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/{DefaultDiagnosticRenderer.java => DispatchingDiagnosticRenderer.java} (56%) diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java index 458efc9ed12..7bb24420e5a 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java @@ -36,7 +36,7 @@ import org.jetbrains.jet.lang.descriptors.ClassOrNamespaceDescriptor; import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.descriptors.ModuleDescriptor; import org.jetbrains.jet.lang.diagnostics.*; -import org.jetbrains.jet.lang.diagnostics.rendering.DefaultDiagnosticRenderer; +import org.jetbrains.jet.lang.diagnostics.rendering.DefaultErrorMessages; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; @@ -155,7 +155,7 @@ public class CompileSession { render = ((SyntaxErrorDiagnostic)diagnostic).message; } else { - render = DefaultDiagnosticRenderer.INSTANCE.render(diagnostic); + render = DefaultErrorMessages.RENDERER.render(diagnostic); } collector.report(diagnostic.getSeverity(), render, path, lineAndColumn.getLine(), lineAndColumn.getColumn()); } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java index f0cae982a4c..f83c2a65983 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -17,6 +17,7 @@ package org.jetbrains.jet.lang.diagnostics.rendering; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.diagnostics.Diagnostic; import org.jetbrains.jet.lang.psi.JetExpression; import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; import org.jetbrains.jet.lang.psi.JetTypeConstraint; @@ -38,6 +39,7 @@ import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.TO_STRING; */ public class DefaultErrorMessages { public static final DiagnosticFactoryToRendererMap MAP = new DiagnosticFactoryToRendererMap(); + public static final DiagnosticRenderer RENDERER = new DispatchingDiagnosticRenderer(MAP); static { MAP.put(EXCEPTION_WHILE_ANALYZING, "{0}", new Renderer() { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DispatchingDiagnosticRenderer.java similarity index 56% rename from compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java rename to compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DispatchingDiagnosticRenderer.java index 6453e0465e7..7a580b14556 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DispatchingDiagnosticRenderer.java @@ -21,21 +21,25 @@ import org.jetbrains.jet.lang.diagnostics.Diagnostic; /** * @author Evgeny Gerashchenko - * @since 4/12/12 + * @since 4/13/12 */ -public class DefaultDiagnosticRenderer implements DiagnosticRenderer { - public static final DefaultDiagnosticRenderer INSTANCE = new DefaultDiagnosticRenderer(); +public class DispatchingDiagnosticRenderer implements DiagnosticRenderer { + private final DiagnosticFactoryToRendererMap[] maps; - private final DiagnosticFactoryToRendererMap map = DefaultErrorMessages.MAP; + public DispatchingDiagnosticRenderer(DiagnosticFactoryToRendererMap... maps) { + this.maps = maps; + } @NotNull @Override public String render(@NotNull Diagnostic diagnostic) { - DiagnosticRenderer renderer = map.get(diagnostic.getFactory()); - if (renderer == null) { - throw new IllegalArgumentException("Don't know how to render diagnostic of type " + diagnostic.getFactory().getName()); + for (DiagnosticFactoryToRendererMap map : maps) { + DiagnosticRenderer renderer = map.get(diagnostic.getFactory()); + if (renderer != null) { + //noinspection unchecked + return renderer.render(diagnostic); + } } - //noinspection unchecked - return renderer.render(diagnostic); + throw new IllegalArgumentException("Don't know how to render diagnostic of type " + diagnostic.getFactory().getName()); } } diff --git a/compiler/tests/org/jetbrains/jet/JetTestUtils.java b/compiler/tests/org/jetbrains/jet/JetTestUtils.java index de37982408a..d206a7b1e97 100644 --- a/compiler/tests/org/jetbrains/jet/JetTestUtils.java +++ b/compiler/tests/org/jetbrains/jet/JetTestUtils.java @@ -27,9 +27,9 @@ import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.compiler.JetCoreEnvironment; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.diagnostics.UnresolvedReferenceDiagnosticFactory; -import org.jetbrains.jet.lang.diagnostics.rendering.DefaultDiagnosticRenderer; import org.jetbrains.jet.lang.diagnostics.Diagnostic; import org.jetbrains.jet.lang.diagnostics.Severity; +import org.jetbrains.jet.lang.diagnostics.rendering.DefaultErrorMessages; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingTrace; @@ -153,7 +153,7 @@ public class JetTestUtils { @Override public void report(@NotNull Diagnostic diagnostic) { if (diagnostic.getSeverity() == Severity.ERROR) { - throw new IllegalStateException(DefaultDiagnosticRenderer.INSTANCE.render(diagnostic)); + throw new IllegalStateException(DefaultErrorMessages.RENDERER.render(diagnostic)); } } }; diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java b/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java index ed012e03db0..7ea6b579896 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java @@ -33,8 +33,8 @@ import com.intellij.psi.PsiReference; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; -import org.jetbrains.jet.lang.diagnostics.rendering.DefaultDiagnosticRenderer; import org.jetbrains.jet.lang.diagnostics.*; +import org.jetbrains.jet.lang.diagnostics.rendering.DefaultErrorMessages; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetReferenceExpression; import org.jetbrains.jet.lang.resolve.BindingContext; @@ -238,7 +238,7 @@ public class JetPsiChecker implements Annotator { @NotNull private static String getMessage(@NotNull Diagnostic diagnostic) { - String message = DefaultDiagnosticRenderer.INSTANCE.render(diagnostic); + String message = DefaultErrorMessages.RENDERER.render(diagnostic); if (ApplicationManager.getApplication().isInternal() || ApplicationManager.getApplication().isUnitTestMode()) { return "[" + diagnostic.getFactory().getName() + "] " + message; } From abb53d4a1805b778150ad6e88490f7b2cd4c73dc Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 19:31:08 +0400 Subject: [PATCH 037/147] Introduced IdeErrorMessages, which is now used along with DefaultErrorMessages in IDEA plugin. --- .../plugin/highlighter/IdeErrorMessages.java | 39 +++++++++++++++++++ .../jet/plugin/highlighter/JetPsiChecker.java | 2 +- 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java new file mode 100644 index 00000000000..e7dafaeb274 --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -0,0 +1,39 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.plugin.highlighter; + +import org.jetbrains.jet.lang.diagnostics.Diagnostic; +import org.jetbrains.jet.lang.diagnostics.rendering.DefaultErrorMessages; +import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticFactoryToRendererMap; +import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticRenderer; +import org.jetbrains.jet.lang.diagnostics.rendering.DispatchingDiagnosticRenderer; + +/** + * @author Evgeny Gerashchenko + * @since 4/13/12 + */ +public class IdeErrorMessages { + public static final DiagnosticFactoryToRendererMap MAP = new DiagnosticFactoryToRendererMap(); + public static final DiagnosticRenderer RENDERER = new DispatchingDiagnosticRenderer(MAP, DefaultErrorMessages.MAP); + + static { + // TODO + } + + private IdeErrorMessages() { + } +} diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java b/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java index 7ea6b579896..4428919d6b9 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java @@ -238,7 +238,7 @@ public class JetPsiChecker implements Annotator { @NotNull private static String getMessage(@NotNull Diagnostic diagnostic) { - String message = DefaultErrorMessages.RENDERER.render(diagnostic); + String message = IdeErrorMessages.RENDERER.render(diagnostic); if (ApplicationManager.getApplication().isInternal() || ApplicationManager.getApplication().isUnitTestMode()) { return "[" + diagnostic.getFactory().getName() + "] " + message; } From 28c8b06344e2882d632003e5a049ae942624ca8d Mon Sep 17 00:00:00 2001 From: Daniel Penkin Date: Fri, 13 Apr 2012 21:21:17 +0400 Subject: [PATCH 038/147] Added String.split(Char) --- libraries/stdlib/src/kotlin/Strings.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libraries/stdlib/src/kotlin/Strings.kt b/libraries/stdlib/src/kotlin/Strings.kt index e1519a90928..65320efde8a 100644 --- a/libraries/stdlib/src/kotlin/Strings.kt +++ b/libraries/stdlib/src/kotlin/Strings.kt @@ -60,6 +60,8 @@ public inline fun String.format(format : String, vararg args : Any?) : String = public inline fun String.split(regex : String) : Array = (this as java.lang.String).split(regex) as Array +public inline fun String.split(ch : Char) : Array = (this as java.lang.String).split(java.util.regex.Pattern.quote(ch.toString())) as Array + public inline fun String.substring(beginIndex : Int) : String = (this as java.lang.String).substring(beginIndex).sure() public inline fun String.substring(beginIndex : Int, endIndex : Int) : String = (this as java.lang.String).substring(beginIndex, endIndex).sure() From a2f27496aa7e451d7dac20e3424426b912f707fa Mon Sep 17 00:00:00 2001 From: Daniel Penkin Date: Fri, 13 Apr 2012 21:29:30 +0400 Subject: [PATCH 039/147] Added test for String.split(Char) --- libraries/stdlib/test/StringTest.kt | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/libraries/stdlib/test/StringTest.kt b/libraries/stdlib/test/StringTest.kt index cf11b34702a..f12c7a89185 100644 --- a/libraries/stdlib/test/StringTest.kt +++ b/libraries/stdlib/test/StringTest.kt @@ -46,4 +46,18 @@ class StringTest() : TestCase() { assertEquals(77.toLong(), "77".toLong()) } + fun testSplitByChar() { + val s = "ab\n[|^$&\\]^cd" + var list = s.split('b'); + assertEquals(2, list.size) + assertEquals("a", list[0]) + assertEquals("\n[|^$&\\]^cd", list[1]) + list = s.split('^') + assertEquals(3, list.size) + assertEquals("cd", list[2]) + list = s.split('.') + assertEquals(1, list.size) + assertEquals(s, list[0]) + } + } From a947d392d4a0b7e1d6b4bc9ea20746ff16c574b3 Mon Sep 17 00:00:00 2001 From: Daniel Penkin Date: Fri, 13 Apr 2012 22:01:16 +0400 Subject: [PATCH 040/147] Added startsWith(Char) and endsWith(Char) for String --- libraries/stdlib/src/kotlin/Strings.kt | 4 ++++ libraries/stdlib/test/StringTest.kt | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/libraries/stdlib/src/kotlin/Strings.kt b/libraries/stdlib/src/kotlin/Strings.kt index 65320efde8a..422d023b5bd 100644 --- a/libraries/stdlib/src/kotlin/Strings.kt +++ b/libraries/stdlib/src/kotlin/Strings.kt @@ -70,10 +70,14 @@ public inline fun String.startsWith(prefix: String) : Boolean = (this as java.la public inline fun String.startsWith(prefix: String, toffset: Int) : Boolean = (this as java.lang.String).startsWith(prefix, toffset) +public inline fun String.startsWith(ch: Char) : Boolean = (this as java.lang.String).startsWith(ch.toString()) + public inline fun String.contains(seq: CharSequence) : Boolean = (this as java.lang.String).contains(seq) public inline fun String.endsWith(suffix: String) : Boolean = (this as java.lang.String).endsWith(suffix) +public inline fun String.endsWith(ch: Char) : Boolean = (this as java.lang.String).endsWith(ch.toString()) + inline val String.size : Int get() = length() diff --git a/libraries/stdlib/test/StringTest.kt b/libraries/stdlib/test/StringTest.kt index f12c7a89185..33741d058f9 100644 --- a/libraries/stdlib/test/StringTest.kt +++ b/libraries/stdlib/test/StringTest.kt @@ -60,4 +60,16 @@ class StringTest() : TestCase() { assertEquals(s, list[0]) } + fun testStartsWithChar() { + assertTrue("abcd".startsWith('a')) + assertFalse("abcd".startsWith('b')) + assertFalse("".startsWith('a')) + } + + fun testEndsWithChar() { + assertTrue("abcd".endsWith('d')) + assertFalse("abcd".endsWith('b')) + assertFalse("".endsWith('a')) + } + } From 6fb0f79de988189d884dcac5f887273fa5e03da5 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 13 Apr 2012 19:31:40 +0400 Subject: [PATCH 041/147] Made JetPsiChecker aware of HTML diagnostics. --- .../jet/plugin/highlighter/JetPsiChecker.java | 42 ++++++++++++++----- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java b/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java index 4428919d6b9..c11debd4cdd 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/JetPsiChecker.java @@ -30,6 +30,7 @@ import com.intellij.openapi.util.TextRange; import com.intellij.psi.MultiRangeReference; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; +import com.intellij.xml.util.XmlStringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; @@ -152,9 +153,8 @@ public class JetPsiChecker implements Annotator { if (reference instanceof MultiRangeReference) { MultiRangeReference mrr = (MultiRangeReference)reference; for (TextRange range : mrr.getRanges()) { - Annotation annotation = holder.createErrorAnnotation( - range.shiftRight(referenceExpression.getTextOffset()), - getMessage(diagnostic)); + Annotation annotation = holder.createErrorAnnotation(range.shiftRight(referenceExpression.getTextOffset()), getDefaultMessage(diagnostic)); + annotation.setTooltip(getMessage(diagnostic)); registerQuickFix(annotation, diagnostic); @@ -163,7 +163,8 @@ public class JetPsiChecker implements Annotator { } else { for (TextRange textRange : textRanges) { - Annotation annotation = holder.createErrorAnnotation(textRange, getMessage(diagnostic)); + Annotation annotation = holder.createErrorAnnotation(textRange, getDefaultMessage(diagnostic)); + annotation.setTooltip(getMessage(diagnostic)); registerQuickFix(annotation, diagnostic); annotation.setHighlightType(ProblemHighlightType.LIKE_UNKNOWN_SYMBOL); } @@ -174,9 +175,9 @@ public class JetPsiChecker implements Annotator { if (diagnostic.getFactory() == Errors.ILLEGAL_ESCAPE_SEQUENCE) { for (TextRange textRange : diagnostic.getTextRanges()) { - Annotation annotation = holder.createErrorAnnotation(textRange, getMessage(diagnostic)); + Annotation annotation = holder.createErrorAnnotation(textRange, getDefaultMessage(diagnostic)); + annotation.setTooltip(getMessage(diagnostic)); annotation.setTextAttributes(JetHighlightingColors.INVALID_STRING_ESCAPE); - //annotation.setEnforcedTextAttributes(TextAttributes.merge(JetHighlightingColors.INVALID_STRING_ESCAPE.getDefaultAttributes(), annotation.getTextAttributes().getDefaultAttributes())); } return; } @@ -188,7 +189,8 @@ public class JetPsiChecker implements Annotator { // Generic annotation for (TextRange textRange : textRanges) { - Annotation errorAnnotation = holder.createErrorAnnotation(textRange, getMessage(diagnostic)); + Annotation errorAnnotation = holder.createErrorAnnotation(textRange, getDefaultMessage(diagnostic)); + errorAnnotation.setTooltip(getMessage(diagnostic)); registerQuickFix(errorAnnotation, diagnostic); if (diagnostic.getFactory() == Errors.INVISIBLE_REFERENCE) { @@ -198,7 +200,8 @@ public class JetPsiChecker implements Annotator { } else if (diagnostic.getSeverity() == Severity.WARNING) { for (TextRange textRange : textRanges) { - Annotation annotation = holder.createWarningAnnotation(textRange, getMessage(diagnostic)); + Annotation annotation = holder.createWarningAnnotation(textRange, getDefaultMessage(diagnostic)); + annotation.setTooltip(getMessage(diagnostic)); registerQuickFix(annotation, diagnostic); if (diagnostic.getFactory() instanceof UnusedElementDiagnosticFactory) { @@ -240,7 +243,24 @@ public class JetPsiChecker implements Annotator { private static String getMessage(@NotNull Diagnostic diagnostic) { String message = IdeErrorMessages.RENDERER.render(diagnostic); if (ApplicationManager.getApplication().isInternal() || ApplicationManager.getApplication().isUnitTestMode()) { - return "[" + diagnostic.getFactory().getName() + "] " + message; + String factoryName = diagnostic.getFactory().getName(); + if (message.startsWith("")) { + message = String.format("[%s] %s", factoryName, message.substring("".length())); + } else { + message = String.format("[%s] %s", factoryName, message); + } + } + if (!message.startsWith("")) { + message = "" + XmlStringUtil.escapeString(message) + ""; + } + return message; + } + + @NotNull + private static String getDefaultMessage(@NotNull Diagnostic diagnostic) { + String message = DefaultErrorMessages.RENDERER.render(diagnostic); + if (ApplicationManager.getApplication().isInternal() || ApplicationManager.getApplication().isUnitTestMode()) { + return String.format("[%s] %s", diagnostic.getFactory().getName(), message); } return message; } @@ -252,6 +272,8 @@ public class JetPsiChecker implements Annotator { if (!redeclarations.add(redeclarationDiagnostic.getPsiElement())) return null; List textRanges = redeclarationDiagnostic.getTextRanges(); if (textRanges.isEmpty()) return null; - return holder.createErrorAnnotation(textRanges.get(0), getMessage(redeclarationDiagnostic)); + Annotation annotation = holder.createErrorAnnotation(textRanges.get(0), ""); + annotation.setTooltip(getMessage(redeclarationDiagnostic)); + return annotation; } } From 8d1860a5f3e362c192ce6363ea421015052a7cff Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Mon, 16 Apr 2012 17:29:02 +0400 Subject: [PATCH 042/147] Added immutability flag in DiagnosticFactoryToRendererMap. --- .../rendering/DefaultErrorMessages.java | 2 ++ .../DiagnosticFactoryToRendererMap.java | 27 ++++++++++++++----- .../plugin/highlighter/IdeErrorMessages.java | 1 + 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java index f83c2a65983..2cda78e8617 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -388,6 +388,8 @@ public class DefaultErrorMessages { "Separate it with a semicolon (;) if it is not intended to be an argument."); MAP.put(NOT_AN_ANNOTATION_CLASS, "{0} is not an annotation class", TO_STRING); + + MAP.setImmutable(); } private DefaultErrorMessages() { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java index 3172e3f9144..96067f8fd53 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java @@ -28,35 +28,50 @@ import java.util.Map; * @author Evgeny Gerashchenko * @since 4/13/12 */ -public class DiagnosticFactoryToRendererMap { +public final class DiagnosticFactoryToRendererMap { private final Map> map = new HashMap>(); + private boolean immutable = false; - public final void put(SimpleDiagnosticFactory factory, String message) { + private void checkMutability() { + if (immutable) { + throw new IllegalStateException("factory to renderer map is already immutable"); + } + } + + public void put(SimpleDiagnosticFactory factory, String message) { + checkMutability(); map.put(factory, new SimpleDiagnosticRenderer(message)); } - public final void put(DiagnosticFactory1 factory, String message, Renderer rendererA) { + public void put(DiagnosticFactory1 factory, String message, Renderer rendererA) { + checkMutability(); map.put(factory, new DiagnosticWithParameters1Renderer(message, rendererA)); } - public final void put(DiagnosticFactory2 factory, + public void put(DiagnosticFactory2 factory, String message, Renderer rendererA, Renderer rendererB) { + checkMutability(); map.put(factory, new DiagnosticWithParameters2Renderer(message, rendererA, rendererB)); } - public final void put(DiagnosticFactory3 factory, + public void put(DiagnosticFactory3 factory, String message, Renderer rendererA, Renderer rendererB, Renderer rendererC) { + checkMutability(); map.put(factory, new DiagnosticWithParameters3Renderer(message, rendererA, rendererB, rendererC)); } @Nullable - public final DiagnosticRenderer get(@NotNull AbstractDiagnosticFactory factory) { + public DiagnosticRenderer get(@NotNull AbstractDiagnosticFactory factory) { return map.get(factory); } + + public void setImmutable() { + immutable = false; + } } diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index e7dafaeb274..9d58c574412 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -32,6 +32,7 @@ public class IdeErrorMessages { static { // TODO + MAP.setImmutable(); } private IdeErrorMessages() { From 0f1406cf778d36b3d4438a374242bcc3aa273497 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Mon, 16 Apr 2012 23:42:09 +0400 Subject: [PATCH 043/147] Fixed some default error messages. --- .../rendering/DefaultErrorMessages.java | 74 +++++++++---------- 1 file changed, 36 insertions(+), 38 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java index 2cda78e8617..4f158e39693 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -76,11 +76,11 @@ public class DefaultErrorMessages { }); MAP.put(ILLEGAL_MODIFIER, "Illegal modifier ''{0}''", TO_STRING); - MAP.put(REDUNDANT_MODIFIER, "Modifier {0} is redundant because {1} is present", TO_STRING, TO_STRING); + MAP.put(REDUNDANT_MODIFIER, "Modifier ''{0}'' is redundant because ''{1}'' is present", TO_STRING, TO_STRING); MAP.put(ABSTRACT_MODIFIER_IN_TRAIT, "Modifier ''abstract'' is redundant in trait"); MAP.put(OPEN_MODIFIER_IN_TRAIT, "Modifier ''open'' is redundant in trait"); MAP.put(REDUNDANT_MODIFIER_IN_GETTER, "Visibility modifiers are redundant in getter"); - MAP.put(TRAIT_CAN_NOT_BE_FINAL, "Trait can not be final"); + MAP.put(TRAIT_CAN_NOT_BE_FINAL, "Trait cannot be final"); MAP.put(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM, "Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly"); // TODO: message MAP.put(RETURN_NOT_ALLOWED, "'return' is not allowed here"); @@ -125,19 +125,18 @@ public class DefaultErrorMessages { MAP.put(MUST_BE_INITIALIZED_OR_BE_ABSTRACT, "Property must be initialized or be abstract"); MAP.put(PROPERTY_INITIALIZER_IN_TRAIT, "Property initializers are not allowed in traits"); MAP.put(PROPERTY_INITIALIZER_NO_BACKING_FIELD, "Initializer is not allowed here because this property has no backing field"); - MAP.put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, "Abstract property {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING); - MAP.put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, "Abstract function {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING); - MAP.put(ABSTRACT_FUNCTION_WITH_BODY, "A function {0} with body cannot be abstract", TO_STRING); - MAP.put(NON_ABSTRACT_FUNCTION_WITH_NO_BODY, "Method {0} without a body must be abstract", TO_STRING); - MAP.put(NON_MEMBER_ABSTRACT_FUNCTION, "Function {0} is not a class or trait member and cannot be abstract", TO_STRING); + MAP.put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, "Abstract property ''{0}'' in non-abstract class ''{1}''", NAME, NAME, TO_STRING); // TODO remove useless parameter + MAP.put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, "Abstract function ''{0}'' in non-abstract class ''{1}''", NAME, NAME, TO_STRING); // TODO remove useless parameter + MAP.put(ABSTRACT_FUNCTION_WITH_BODY, "A function ''{0}'' with body cannot be abstract", NAME); + MAP.put(NON_ABSTRACT_FUNCTION_WITH_NO_BODY, "Function ''{0}'' without a body must be abstract", NAME); + MAP.put(NON_MEMBER_ABSTRACT_FUNCTION, "Function ''{0}'' is not a class or trait member and cannot be abstract", NAME); - MAP.put(NON_MEMBER_FUNCTION_NO_BODY, "Function {0} must have a body", TO_STRING); - MAP.put(NON_FINAL_MEMBER_IN_FINAL_CLASS, "Non final member in a final class"); + MAP.put(NON_MEMBER_FUNCTION_NO_BODY, "Function ''{0}'' must have a body", NAME); + MAP.put(NON_FINAL_MEMBER_IN_FINAL_CLASS, "Non-final member in a final class"); - MAP.put(PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE, "Public or protected member should specify a type"); + MAP.put(PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE, "Public or protected member should have specified type"); - MAP.put(PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT, - "Projections are not allowed on type arguments of functions and properties"); // TODO : better positioning + MAP.put(PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT, "Projections are not allowed on type arguments of functions and properties"); MAP.put(SUPERTYPE_NOT_INITIALIZED, "This type has a constructor, and thus must be initialized here"); MAP.put(SUPERTYPE_NOT_INITIALIZED_DEFAULT, "Constructor invocation should be explicitly specified"); MAP.put(SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY, "A secondary constructor may appear only in a class that has a primary constructor"); @@ -145,9 +144,8 @@ public class DefaultErrorMessages { MAP.put(BY_IN_SECONDARY_CONSTRUCTOR, "'by'-clause is only supported for primary constructors"); MAP.put(INITIALIZER_WITH_NO_ARGUMENTS, "Constructor arguments required"); MAP.put(MANY_CALLS_TO_THIS, "Only one call to 'this(...)' is allowed"); - MAP.put(NOTHING_TO_OVERRIDE, "{0} overrides nothing", DescriptorRenderer.TEXT); - MAP.put(VIRTUAL_MEMBER_HIDDEN, "''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", DescriptorRenderer.TEXT, - DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); + MAP.put(NOTHING_TO_OVERRIDE, "''{0}'' overrides nothing", NAME); + MAP.put(VIRTUAL_MEMBER_HIDDEN, "''{0}'' hides member of supertype ''{2}'' and needs ''override'' modifier", NAME, NAME, NAME); MAP.put(ENUM_ENTRY_SHOULD_BE_INITIALIZED, "Missing delegation specifier ''{0}''", NAME); MAP.put(ENUM_ENTRY_ILLEGAL_TYPE, "The type constructor of enum entry should be ''{0}''", NAME); @@ -163,7 +161,7 @@ public class DefaultErrorMessages { MAP.put(UNUSED_EXPRESSION, "The expression is unused"); MAP.put(UNUSED_FUNCTION_LITERAL, "The function literal is unused. If you mean block, you can use 'run { ... }'"); - MAP.put(VAL_REASSIGNMENT, "Val can not be reassigned", NAME); + MAP.put(VAL_REASSIGNMENT, "Val cannot be reassigned", NAME); MAP.put(INITIALIZATION_BEFORE_DECLARATION, "Variable cannot be initialized before declaration", NAME); MAP.put(VARIABLE_EXPECTED, "Variable expected"); @@ -197,12 +195,12 @@ public class DefaultErrorMessages { NAME, ELEMENT_TEXT); MAP.put(ASSIGN_OPERATOR_AMBIGUITY, "Assignment operators ambiguity: {0}", AMBIGUOUS_CALLS); - MAP.put(EQUALS_MISSING, "No method 'equals(Any?) : Boolean' available"); + MAP.put(EQUALS_MISSING, "No method 'equals(jet.Any?) : jet.Boolean' available"); MAP.put(ASSIGNMENT_IN_EXPRESSION_CONTEXT, "Assignments are not expressions, and only expressions are allowed in this context"); MAP.put(NAMESPACE_IS_NOT_AN_EXPRESSION, "'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')"); - MAP.put(SUPER_IS_NOT_AN_EXPRESSION, "{0} is not an expression, it can only be used on the left-hand side of a dot ('.')", TO_STRING); + MAP.put(SUPER_IS_NOT_AN_EXPRESSION, "''{0}'' is not an expression, it can only be used on the left-hand side of a dot ('.')", TO_STRING); MAP.put(DECLARATION_IN_ILLEGAL_CONTEXT, "Declarations are not allowed in this position"); - MAP.put(SETTER_PARAMETER_WITH_DEFAULT_VALUE, "Setter parameters can not have default values"); + MAP.put(SETTER_PARAMETER_WITH_DEFAULT_VALUE, "Setter parameters cannot have default values"); MAP.put(NO_THIS, "'this' is not defined in this context"); MAP.put(SUPER_NOT_AVAILABLE, "No supertypes are accessible in this context"); MAP.put(AMBIGUOUS_SUPER, "Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super'"); @@ -212,9 +210,9 @@ public class DefaultErrorMessages { MAP.put(USELESS_CAST_STATIC_ASSERT_IS_FINE, "No cast needed, use ':' instead"); MAP.put(USELESS_CAST, "No cast needed"); MAP.put(CAST_NEVER_SUCCEEDS, "This cast can never succeed"); - MAP.put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property, i.e. {0}", RENDER_TYPE); - MAP.put(WRONG_GETTER_RETURN_TYPE, "Getter return type must be equal to the type of the property, i.e. {0}", RENDER_TYPE); - MAP.put(NO_CLASS_OBJECT, "Please specify constructor invocation; classifier {0} does not have a class object", NAME); + MAP.put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property, i.e. ''{0}''", RENDER_TYPE); + MAP.put(WRONG_GETTER_RETURN_TYPE, "Getter return type must be equal to the type of the property, i.e. ''{0}''", RENDER_TYPE); + MAP.put(NO_CLASS_OBJECT, "Please specify constructor invocation; classifier ''{0}'' does not have a class object", NAME); MAP.put(NO_GENERICS_IN_SUPERTYPE_SPECIFIER, "Generic arguments of the base type must be specified"); MAP.put(HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY, @@ -222,16 +220,16 @@ public class DefaultErrorMessages { MAP.put(HAS_NEXT_MISSING, "Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property"); MAP.put(HAS_NEXT_FUNCTION_AMBIGUITY, "Function 'iterator().hasNext()' is ambiguous for this expression"); MAP.put(HAS_NEXT_MUST_BE_READABLE, "The 'iterator().hasNext' property of the loop range must be readable"); - MAP.put(HAS_NEXT_PROPERTY_TYPE_MISMATCH, "The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", + MAP.put(HAS_NEXT_PROPERTY_TYPE_MISMATCH, "The type of ''iterator().hasNext'' property of the loop range must be jet.Boolean, but is {0}", RENDER_TYPE); - MAP.put(HAS_NEXT_FUNCTION_TYPE_MISMATCH, "The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", + MAP.put(HAS_NEXT_FUNCTION_TYPE_MISMATCH, "The ''iterator().hasNext()'' function of the loop range must return jet.Boolean, but returns {0}", RENDER_TYPE); MAP.put(NEXT_AMBIGUITY, "Function 'iterator().next()' is ambiguous for this expression"); MAP.put(NEXT_MISSING, "Loop range must have an 'iterator().next()' function"); MAP.put(ITERATOR_MISSING, "For-loop range must have an iterator() method"); - MAP.put(ITERATOR_AMBIGUITY, "Method 'iterator()' is ambiguous for this expression: {0}", AMBIGUOUS_CALLS); + MAP.put(ITERATOR_AMBIGUITY, "Method ''iterator()'' is ambiguous for this expression: {0}", AMBIGUOUS_CALLS); - MAP.put(COMPARE_TO_TYPE_MISMATCH, "compareTo() must return Int, but returns {0}", RENDER_TYPE); + MAP.put(COMPARE_TO_TYPE_MISMATCH, "''compareTo()'' must return jet.Int, but returns {0}", RENDER_TYPE); MAP.put(CALLEE_NOT_A_FUNCTION, "Expecting a function type, but found {0}", RENDER_TYPE); MAP.put(RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY, @@ -253,14 +251,14 @@ public class DefaultErrorMessages { } }); - MAP.put(UPPER_BOUND_VIOLATED, "An upper bound {0} is violated", RENDER_TYPE); // TODO : Message - MAP.put(FINAL_CLASS_OBJECT_UPPER_BOUND, "{0} is a final type, and thus a class object cannot extend it", RENDER_TYPE); - MAP.put(FINAL_UPPER_BOUND, "{0} is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE); + MAP.put(UPPER_BOUND_VIOLATED, "Type argument is not within its bounds: should be subtype of ''{0}''", RENDER_TYPE); + MAP.put(FINAL_CLASS_OBJECT_UPPER_BOUND, "''{0}'' is a final type, and thus a class object cannot extend it", RENDER_TYPE); + MAP.put(FINAL_UPPER_BOUND, "''{0}'' is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE); MAP.put(USELESS_ELVIS, "Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE); MAP.put(CONFLICTING_UPPER_BOUNDS, "Upper bounds of {0} have empty intersection", NAME); MAP.put(CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS, "Class object upper bounds of {0} have empty intersection", NAME); - MAP.put(TOO_MANY_ARGUMENTS, "Too many arguments for {0}", TO_STRING); + MAP.put(TOO_MANY_ARGUMENTS, "Too many arguments for {0}", DescriptorRenderer.TEXT); MAP.put(ERROR_COMPILE_TIME_VALUE, "{0}", TO_STRING); MAP.put(ELSE_MISPLACED_IN_WHEN, "'else' entry must be the last one in a when-expression"); @@ -299,12 +297,12 @@ public class DefaultErrorMessages { return typeConstraint.getSubjectTypeParameterName().getReferencedName(); } }, NAME); - MAP.put(AUTOCAST_IMPOSSIBLE, "Automatic cast to {0} is impossible, because {1} could have changed since the is-check", RENDER_TYPE, + MAP.put(AUTOCAST_IMPOSSIBLE, "Automatic cast to ''{0}'' is impossible, because ''{1}'' could have changed since the is-check", RENDER_TYPE, NAME); MAP.put(TYPE_MISMATCH_IN_FOR_LOOP, "The loop iterates over values of type {0} but the parameter is declared to be {1}", RENDER_TYPE, RENDER_TYPE); - MAP.put(TYPE_MISMATCH_IN_CONDITION, "Condition must be of type Boolean, but was of type {0}", RENDER_TYPE); + MAP.put(TYPE_MISMATCH_IN_CONDITION, "Condition must be of type jet.Boolean, but is of type {0}", RENDER_TYPE); MAP.put(TYPE_MISMATCH_IN_TUPLE_PATTERN, "Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, TO_STRING); // TODO: message MAP.put(TYPE_MISMATCH_IN_BINDING_PATTERN, "{0} must be a supertype of {1}. Use 'is' to match against {0}", RENDER_TYPE, RENDER_TYPE); @@ -314,7 +312,7 @@ public class DefaultErrorMessages { MAP.put(CANNOT_CHECK_FOR_ERASED, "Cannot check for instance of erased type: {0}", RENDER_TYPE); MAP.put(UNCHECKED_CAST, "Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE); - MAP.put(INCONSISTENT_TYPE_PARAMETER_VALUES, "Type parameter {0} of {1} has inconsistent values: {2}", NAME, DescriptorRenderer.TEXT, + MAP.put(INCONSISTENT_TYPE_PARAMETER_VALUES, "Type parameter {0} of ''{1}'' has inconsistent values: {2}", NAME, NAME, new Renderer>() { @NotNull @Override @@ -344,8 +342,8 @@ public class DefaultErrorMessages { MAP.put(CANNOT_WEAKEN_ACCESS_PRIVILEGE, "Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME); MAP.put(CANNOT_CHANGE_ACCESS_PRIVILEGE, "Cannot change access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME); - MAP.put(RETURN_TYPE_MISMATCH_ON_OVERRIDE, "Return type of {0} is not a subtype of the return type overridden member {1}", - DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); + MAP.put(RETURN_TYPE_MISMATCH_ON_OVERRIDE, "Return type of ''{0}'' is not a subtype of the return type of overridden member {1}", + NAME, DescriptorRenderer.TEXT); MAP.put(VAR_OVERRIDDEN_BY_VAL, "Var-property {0} cannot be overridden by val-property {1}", DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); @@ -367,11 +365,11 @@ public class DefaultErrorMessages { MAP.put(OVERLOAD_RESOLUTION_AMBIGUITY, "Overload resolution ambiguity: {0}", AMBIGUOUS_CALLS); MAP.put(NONE_APPLICABLE, "None of the following functions can be called with the arguments supplied: {0}", AMBIGUOUS_CALLS); - MAP.put(NO_VALUE_FOR_PARAMETER, "No value passed for parameter {0}", DescriptorRenderer.TEXT); + MAP.put(NO_VALUE_FOR_PARAMETER, "No value passed for parameter {0}", NAME); MAP.put(MISSING_RECEIVER, "A receiver of type {0} is required", RENDER_TYPE); MAP.put(NO_RECEIVER_ADMITTED, "No receiver can be passed to this function or property"); - MAP.put(CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS, "Can not create an instance of an abstract class"); + MAP.put(CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS, "Cannot create an instance of an abstract class"); MAP.put(TYPE_INFERENCE_FAILED, "Type inference failed: {0}", TO_STRING); MAP.put(WRONG_NUMBER_OF_TYPE_ARGUMENTS, "{0} type arguments expected", new Renderer() { @NotNull @@ -387,7 +385,7 @@ public class DefaultErrorMessages { "This expression is treated as an argument to the function call on the previous line. " + "Separate it with a semicolon (;) if it is not intended to be an argument."); - MAP.put(NOT_AN_ANNOTATION_CLASS, "{0} is not an annotation class", TO_STRING); + MAP.put(NOT_AN_ANNOTATION_CLASS, "''{0}'' is not an annotation class", TO_STRING); MAP.setImmutable(); } From 2f0760c85bdced225276b56dea4b70fa15072dfa Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Mon, 16 Apr 2012 23:45:14 +0400 Subject: [PATCH 044/147] Removed useless diagnostic parameters for ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS and ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS --- .../src/org/jetbrains/jet/lang/diagnostics/Errors.java | 8 ++++---- .../lang/diagnostics/rendering/DefaultErrorMessages.java | 4 ++-- .../jetbrains/jet/lang/resolve/DeclarationsChecker.java | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java index 628d07a338f..7dc3b71fe62 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java @@ -123,10 +123,10 @@ public interface Errors { PositioningStrategies.POSITION_NAME_IDENTIFIER); SimpleDiagnosticFactoryPROPERTY_INITIALIZER_IN_TRAIT = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory PROPERTY_INITIALIZER_NO_BACKING_FIELD = SimpleDiagnosticFactory.create(ERROR); - DiagnosticFactory3 ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS = - DiagnosticFactory3.create(ERROR, PositioningStrategies.POSITION_ABSTRACT_MODIFIER); - DiagnosticFactory3 ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS = - DiagnosticFactory3.create(ERROR,PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + DiagnosticFactory2 ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS = + DiagnosticFactory2.create(ERROR, PositioningStrategies.POSITION_ABSTRACT_MODIFIER); + DiagnosticFactory2 ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS = + DiagnosticFactory2.create(ERROR,PositioningStrategies.POSITION_ABSTRACT_MODIFIER); DiagnosticFactory1 ABSTRACT_FUNCTION_WITH_BODY = DiagnosticFactory1.create(ERROR, PositioningStrategies.POSITION_ABSTRACT_MODIFIER); DiagnosticFactory1 NON_ABSTRACT_FUNCTION_WITH_NO_BODY = diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java index 4f158e39693..9a42b6cb85e 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -125,8 +125,8 @@ public class DefaultErrorMessages { MAP.put(MUST_BE_INITIALIZED_OR_BE_ABSTRACT, "Property must be initialized or be abstract"); MAP.put(PROPERTY_INITIALIZER_IN_TRAIT, "Property initializers are not allowed in traits"); MAP.put(PROPERTY_INITIALIZER_NO_BACKING_FIELD, "Initializer is not allowed here because this property has no backing field"); - MAP.put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, "Abstract property ''{0}'' in non-abstract class ''{1}''", NAME, NAME, TO_STRING); // TODO remove useless parameter - MAP.put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, "Abstract function ''{0}'' in non-abstract class ''{1}''", NAME, NAME, TO_STRING); // TODO remove useless parameter + MAP.put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, "Abstract property ''{0}'' in non-abstract class ''{1}''", NAME, NAME); + MAP.put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, "Abstract function ''{0}'' in non-abstract class ''{1}''", NAME, NAME); MAP.put(ABSTRACT_FUNCTION_WITH_BODY, "A function ''{0}'' with body cannot be abstract", NAME); MAP.put(NON_ABSTRACT_FUNCTION_WITH_NO_BODY, "Function ''{0}'' without a body must be abstract", NAME); MAP.put(NON_MEMBER_ABSTRACT_FUNCTION, "Function ''{0}'' is not a class or trait member and cannot be abstract", NAME); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DeclarationsChecker.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DeclarationsChecker.java index 8d4a4b70de8..c3108cb8bcc 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DeclarationsChecker.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DeclarationsChecker.java @@ -181,7 +181,7 @@ public class DeclarationsChecker { if (!(classDescriptor.getModality() == Modality.ABSTRACT) && classDescriptor.getKind() != ClassKind.ENUM_CLASS) { JetClass classElement = (JetClass) BindingContextUtils.classDescriptorToDeclaration(trace.getBindingContext(), classDescriptor); String name = property.getName(); - trace.report(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS.on(property, name != null ? name : "", classDescriptor, classElement)); + trace.report(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS.on(property, name != null ? name : "", classDescriptor)); return; } if (classDescriptor.getKind() == ClassKind.TRAIT) { @@ -252,7 +252,7 @@ public class DeclarationsChecker { boolean inAbstractClass = classDescriptor.getModality() == Modality.ABSTRACT; if (hasAbstractModifier && !inAbstractClass && !inTrait && !inEnum) { JetClass classElement = (JetClass) BindingContextUtils.classDescriptorToDeclaration(trace.getBindingContext(), classDescriptor); - trace.report(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS.on(function, functionDescriptor.getName(), classDescriptor, classElement)); + trace.report(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS.on(function, functionDescriptor.getName(), classDescriptor)); } if (hasAbstractModifier && inTrait) { trace.report(ABSTRACT_MODIFIER_IN_TRAIT.on(function)); From 61a26ef5d9dc83672fa55840791f539cfcb1822f Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 17 Apr 2012 00:06:48 +0400 Subject: [PATCH 045/147] Added first HTML error message, for TYPE_MISMATCH diagnostic. --- .../jetbrains/jet/plugin/highlighter/IdeErrorMessages.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index 9d58c574412..feaf3a0af9b 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -22,6 +22,9 @@ import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticFactoryToRendererM import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticRenderer; import org.jetbrains.jet.lang.diagnostics.rendering.DispatchingDiagnosticRenderer; +import static org.jetbrains.jet.lang.diagnostics.Errors.TYPE_MISMATCH; +import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.RENDER_TYPE; + /** * @author Evgeny Gerashchenko * @since 4/13/12 @@ -31,7 +34,7 @@ public class IdeErrorMessages { public static final DiagnosticRenderer RENDERER = new DispatchingDiagnosticRenderer(MAP, DefaultErrorMessages.MAP); static { - // TODO + MAP.put(TYPE_MISMATCH, "Type mismatch.
Required:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); MAP.setImmutable(); } From d9cfde431bb3e0e2d65762c92cb312c8352e908f Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 17 Apr 2012 00:54:03 +0400 Subject: [PATCH 046/147] Added "expected type" parameter to WRONG_SETTER_PARAMETER_TYPE and WRONG_GETTER_RETURN_TYPE diagnostics. --- .../src/org/jetbrains/jet/lang/diagnostics/Errors.java | 4 ++-- .../jet/lang/diagnostics/rendering/DefaultErrorMessages.java | 4 ++-- .../org/jetbrains/jet/lang/resolve/DescriptorResolver.java | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java index 7dc3b71fe62..8159fbd9a7e 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java @@ -223,8 +223,8 @@ public interface Errors { SimpleDiagnosticFactory USELESS_CAST_STATIC_ASSERT_IS_FINE = SimpleDiagnosticFactory.create(WARNING); SimpleDiagnosticFactory USELESS_CAST = SimpleDiagnosticFactory.create(WARNING); SimpleDiagnosticFactory CAST_NEVER_SUCCEEDS = SimpleDiagnosticFactory.create(WARNING); - DiagnosticFactory1 WRONG_SETTER_PARAMETER_TYPE = DiagnosticFactory1.create(ERROR); - DiagnosticFactory1 WRONG_GETTER_RETURN_TYPE = DiagnosticFactory1.create(ERROR); + DiagnosticFactory2 WRONG_SETTER_PARAMETER_TYPE = DiagnosticFactory2.create(ERROR); + DiagnosticFactory2 WRONG_GETTER_RETURN_TYPE = DiagnosticFactory2.create(ERROR); DiagnosticFactory1 NO_CLASS_OBJECT = DiagnosticFactory1.create(ERROR); SimpleDiagnosticFactory NO_GENERICS_IN_SUPERTYPE_SPECIFIER = SimpleDiagnosticFactory.create(ERROR); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java index 9a42b6cb85e..0a7aa886531 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -210,8 +210,8 @@ public class DefaultErrorMessages { MAP.put(USELESS_CAST_STATIC_ASSERT_IS_FINE, "No cast needed, use ':' instead"); MAP.put(USELESS_CAST, "No cast needed"); MAP.put(CAST_NEVER_SUCCEEDS, "This cast can never succeed"); - MAP.put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property, i.e. ''{0}''", RENDER_TYPE); - MAP.put(WRONG_GETTER_RETURN_TYPE, "Getter return type must be equal to the type of the property, i.e. ''{0}''", RENDER_TYPE); + MAP.put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property, i.e. ''{0}''", RENDER_TYPE, RENDER_TYPE); + MAP.put(WRONG_GETTER_RETURN_TYPE, "Getter return type must be equal to the type of the property, i.e. ''{0}''", RENDER_TYPE, RENDER_TYPE); MAP.put(NO_CLASS_OBJECT, "Please specify constructor invocation; classifier ''{0}'' does not have a class object", NAME); MAP.put(NO_GENERICS_IN_SUPERTYPE_SPECIFIER, "Generic arguments of the base type must be specified"); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java index 50802066804..d5337fb40c9 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java @@ -723,7 +723,7 @@ public class DescriptorResolver { JetType inType = propertyDescriptor.getType(); if (inType != null) { if (!TypeUtils.equalTypes(type, inType)) { - trace.report(WRONG_SETTER_PARAMETER_TYPE.on(typeReference, inType)); + trace.report(WRONG_SETTER_PARAMETER_TYPE.on(typeReference, inType, type)); } } else { @@ -776,7 +776,7 @@ public class DescriptorResolver { if (returnTypeReference != null) { returnType = typeResolver.resolveType(scope, returnTypeReference, trace, true); if (outType != null && !TypeUtils.equalTypes(returnType, outType)) { - trace.report(WRONG_GETTER_RETURN_TYPE.on(returnTypeReference, propertyDescriptor.getReturnType())); + trace.report(WRONG_GETTER_RETURN_TYPE.on(returnTypeReference, propertyDescriptor.getReturnType(), outType)); } } From 17d290a5da5dda8e85ed2449168e9f2a30ac6a22 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 17 Apr 2012 00:58:02 +0400 Subject: [PATCH 047/147] Added HTML error message for WRONG_SETTER_PARAMETER_TYPE and WRONG_GETTER_RETURN_TYPE diagnostics. --- .../jet/plugin/highlighter/IdeErrorMessages.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index feaf3a0af9b..3bd41ac2bf1 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -23,6 +23,8 @@ import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticRenderer; import org.jetbrains.jet.lang.diagnostics.rendering.DispatchingDiagnosticRenderer; import static org.jetbrains.jet.lang.diagnostics.Errors.TYPE_MISMATCH; +import static org.jetbrains.jet.lang.diagnostics.Errors.WRONG_GETTER_RETURN_TYPE; +import static org.jetbrains.jet.lang.diagnostics.Errors.WRONG_SETTER_PARAMETER_TYPE; import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.RENDER_TYPE; /** @@ -34,7 +36,13 @@ public class IdeErrorMessages { public static final DiagnosticRenderer RENDERER = new DispatchingDiagnosticRenderer(MAP, DefaultErrorMessages.MAP); static { - MAP.put(TYPE_MISMATCH, "Type mismatch.
Required:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); + MAP.put(TYPE_MISMATCH, "Type mismatch.
Required:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); + + MAP.put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property." + + "
Expected:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); + MAP.put(WRONG_GETTER_RETURN_TYPE, "Getter return type must be equal to the type of the property." + + "
Expected:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); + MAP.setImmutable(); } From 42c079ce98a1d39ed50a5e4e0ec80ab27f4765c1 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 17 Apr 2012 01:45:57 +0400 Subject: [PATCH 048/147] Added "actual type" parameter for UPPER_BOUND_VIOLATED diagnostic. --- .../frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java | 2 +- .../jet/lang/diagnostics/rendering/DefaultErrorMessages.java | 2 +- .../src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java index 8159fbd9a7e..a75cf063278 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java @@ -267,7 +267,7 @@ public interface Errors { DiagnosticFactory1 IMPLICIT_CAST_TO_UNIT_OR_ANY = DiagnosticFactory1.create(WARNING); DiagnosticFactory1 EXPRESSION_EXPECTED = DiagnosticFactory1.create(ERROR); - DiagnosticFactory1 UPPER_BOUND_VIOLATED = DiagnosticFactory1.create(ERROR); + DiagnosticFactory2 UPPER_BOUND_VIOLATED = DiagnosticFactory2.create(ERROR); DiagnosticFactory1 FINAL_CLASS_OBJECT_UPPER_BOUND = DiagnosticFactory1.create(ERROR); DiagnosticFactory1 FINAL_UPPER_BOUND = DiagnosticFactory1.create(WARNING); DiagnosticFactory1 USELESS_ELVIS = DiagnosticFactory1.create(WARNING); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java index 0a7aa886531..0e8a1e60029 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -251,7 +251,7 @@ public class DefaultErrorMessages { } }); - MAP.put(UPPER_BOUND_VIOLATED, "Type argument is not within its bounds: should be subtype of ''{0}''", RENDER_TYPE); + MAP.put(UPPER_BOUND_VIOLATED, "Type argument is not within its bounds: should be subtype of ''{0}''", RENDER_TYPE, RENDER_TYPE); MAP.put(FINAL_CLASS_OBJECT_UPPER_BOUND, "''{0}'' is a final type, and thus a class object cannot extend it", RENDER_TYPE); MAP.put(FINAL_UPPER_BOUND, "''{0}'' is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE); MAP.put(USELESS_ELVIS, "Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java index d5337fb40c9..7e2053561ca 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java @@ -919,7 +919,7 @@ public class DescriptorResolver { for (JetType bound : typeParameterDescriptor.getUpperBounds()) { JetType substitutedBound = substitutor.safeSubstitute(bound, Variance.INVARIANT); if (!JetTypeChecker.INSTANCE.isSubtypeOf(typeArgument, substitutedBound)) { - trace.report(UPPER_BOUND_VIOLATED.on(argumentTypeReference, substitutedBound)); + trace.report(UPPER_BOUND_VIOLATED.on(argumentTypeReference, substitutedBound, typeArgument)); } } } From d7e9a77fdb627518a4661689d88ca1b0745326be Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 17 Apr 2012 01:51:48 +0400 Subject: [PATCH 049/147] Added IDE error message for UPPER_BOUND_VIOLATED. --- .../jet/plugin/highlighter/IdeErrorMessages.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index 3bd41ac2bf1..f7507daff65 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -22,9 +22,7 @@ import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticFactoryToRendererM import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticRenderer; import org.jetbrains.jet.lang.diagnostics.rendering.DispatchingDiagnosticRenderer; -import static org.jetbrains.jet.lang.diagnostics.Errors.TYPE_MISMATCH; -import static org.jetbrains.jet.lang.diagnostics.Errors.WRONG_GETTER_RETURN_TYPE; -import static org.jetbrains.jet.lang.diagnostics.Errors.WRONG_SETTER_PARAMETER_TYPE; +import static org.jetbrains.jet.lang.diagnostics.Errors.*; import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.RENDER_TYPE; /** @@ -39,9 +37,12 @@ public class IdeErrorMessages { MAP.put(TYPE_MISMATCH, "Type mismatch.
Required:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); MAP.put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property." + - "
Expected:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); + "
Expected:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); MAP.put(WRONG_GETTER_RETURN_TYPE, "Getter return type must be equal to the type of the property." + - "
Expected:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); + "
Expected:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); + + MAP.put(UPPER_BOUND_VIOLATED, "Type argument is not within its bounds." + + "
Expected:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); MAP.setImmutable(); } From 5a69231b92fb0a741789532bb33f67a3f722a16d Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 17 Apr 2012 02:11:58 +0400 Subject: [PATCH 050/147] Added IDE error message for TYPE_MISMATCH_IN_FOR_LOOP. --- .../jet/plugin/highlighter/IdeErrorMessages.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index f7507daff65..93a79b93e4d 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -37,12 +37,19 @@ public class IdeErrorMessages { MAP.put(TYPE_MISMATCH, "Type mismatch.
Required:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); MAP.put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property." + - "
Expected:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); + "" + + "
Expected:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); MAP.put(WRONG_GETTER_RETURN_TYPE, "Getter return type must be equal to the type of the property." + - "
Expected:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); + "" + + "
Expected:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); MAP.put(UPPER_BOUND_VIOLATED, "Type argument is not within its bounds." + - "
Expected:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); + "" + + "
Expected:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); + + MAP.put(TYPE_MISMATCH_IN_FOR_LOOP, "Loop parameter type mismatch." + + "" + + "
Iterated values:{0}
Parameter:{1}
", RENDER_TYPE, RENDER_TYPE); MAP.setImmutable(); } From 1123a4f438a342a57d62355f19e8dfb06081113d Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 17 Apr 2012 02:24:09 +0400 Subject: [PATCH 051/147] Clarified error message for TYPE_MISMATCH_IN_BINDING_PATTERN. --- .../diagnostics/rendering/DefaultErrorMessages.java | 2 +- idea/testData/checker/infos/Autocasts.jet | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java index 0e8a1e60029..a4bb1c5feac 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -305,7 +305,7 @@ public class DefaultErrorMessages { MAP.put(TYPE_MISMATCH_IN_CONDITION, "Condition must be of type jet.Boolean, but is of type {0}", RENDER_TYPE); MAP.put(TYPE_MISMATCH_IN_TUPLE_PATTERN, "Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, TO_STRING); // TODO: message - MAP.put(TYPE_MISMATCH_IN_BINDING_PATTERN, "{0} must be a supertype of {1}. Use 'is' to match against {0}", RENDER_TYPE, RENDER_TYPE); + MAP.put(TYPE_MISMATCH_IN_BINDING_PATTERN, "{0} is not a supertype of {1}. Use ''is'' to match against {0}", RENDER_TYPE, RENDER_TYPE); MAP.put(INCOMPATIBLE_TYPES, "Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE); MAP.put(EXPECTED_CONDITION, "Expected condition of Boolean type"); diff --git a/idea/testData/checker/infos/Autocasts.jet b/idea/testData/checker/infos/Autocasts.jet index b665d066470..75c9df003e7 100644 --- a/idea/testData/checker/infos/Autocasts.jet +++ b/idea/testData/checker/infos/Autocasts.jet @@ -66,7 +66,7 @@ fun f12(a : A?) { is A -> a.foo() is Any -> a.foo(); is Any? -> a.bar() - is val c : B -> c.foo() + is val c : B -> c.foo() is val c is C -> c.bar() is val c is C -> a.bar() else -> a?.foo() @@ -237,17 +237,17 @@ fun mergeAutocasts(a: Any?) { fun f(): String { var a: Any = 11 if (a is String) { - val i: String = a - a.compareTo("f") - val f: Function0 = { a } - return a + val i: String = a + a.compareTo("f") + val f: Function0 = { a } + return a } return "" } fun foo(var a: Any): Int { if (a is Int) { - return a + return a } return 1 } From c1dde845081b449a36dd56ff16d1b8811d43c629 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 17 Apr 2012 02:25:11 +0400 Subject: [PATCH 052/147] Boolean -> jet.Boolean --- .../jet/lang/diagnostics/rendering/DefaultErrorMessages.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java index a4bb1c5feac..d3b9e1076ec 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -307,7 +307,7 @@ public class DefaultErrorMessages { TO_STRING); // TODO: message MAP.put(TYPE_MISMATCH_IN_BINDING_PATTERN, "{0} is not a supertype of {1}. Use ''is'' to match against {0}", RENDER_TYPE, RENDER_TYPE); MAP.put(INCOMPATIBLE_TYPES, "Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE); - MAP.put(EXPECTED_CONDITION, "Expected condition of Boolean type"); + MAP.put(EXPECTED_CONDITION, "Expected condition of jet.Boolean type"); MAP.put(CANNOT_CHECK_FOR_ERASED, "Cannot check for instance of erased type: {0}", RENDER_TYPE); MAP.put(UNCHECKED_CAST, "Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE); From 886ec6a162346ea9f4d773b286e1b6404896bafe Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 17 Apr 2012 02:26:43 +0400 Subject: [PATCH 053/147] Clarified EQUALITY_NOT_APPLICABLE error message. --- .../jet/lang/diagnostics/rendering/DefaultErrorMessages.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java index d3b9e1076ec..3caee29565e 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -329,14 +329,14 @@ public class DefaultErrorMessages { } }); - MAP.put(EQUALITY_NOT_APPLICABLE, "Operator {0} cannot be applied to {1} and {2}", new Renderer() { + MAP.put(EQUALITY_NOT_APPLICABLE, "Operator ''{0}'' cannot be applied to ''{1}'' and ''{2}''", new Renderer() { @NotNull @Override public String render(@NotNull JetSimpleNameExpression nameExpression) { //noinspection ConstantConditions return nameExpression.getReferencedName(); } - }, TO_STRING, TO_STRING); + }, RENDER_TYPE, RENDER_TYPE); MAP.put(OVERRIDING_FINAL_MEMBER, "''{0}'' in ''{1}'' is final and cannot be overridden", NAME, NAME); MAP.put(CANNOT_WEAKEN_ACCESS_PRIVILEGE, "Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME); From b0843ce65601e27ba3f0206420fffec6b42f79f0 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 17 Apr 2012 02:45:55 +0400 Subject: [PATCH 054/147] Added IDE error message for RETURN_TYPE_MISMATCH_ON_OVERRIDE. --- .../plugin/highlighter/IdeErrorMessages.java | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index 93a79b93e4d..25aa8b9adf2 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -16,13 +16,14 @@ package org.jetbrains.jet.plugin.highlighter; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.descriptors.CallableMemberDescriptor; import org.jetbrains.jet.lang.diagnostics.Diagnostic; -import org.jetbrains.jet.lang.diagnostics.rendering.DefaultErrorMessages; -import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticFactoryToRendererMap; -import org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticRenderer; -import org.jetbrains.jet.lang.diagnostics.rendering.DispatchingDiagnosticRenderer; +import org.jetbrains.jet.lang.diagnostics.rendering.*; +import org.jetbrains.jet.resolve.DescriptorRenderer; import static org.jetbrains.jet.lang.diagnostics.Errors.*; +import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.NAME; import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.RENDER_TYPE; /** @@ -51,6 +52,16 @@ public class IdeErrorMessages { "" + "
Iterated values:{0}
Parameter:{1}
", RENDER_TYPE, RENDER_TYPE); + MAP.put(RETURN_TYPE_MISMATCH_ON_OVERRIDE, "Return type is ''{0}'', which is not a subtype of overridden
" + + "{1}", + new Renderer() { + @NotNull + @Override + public String render(@NotNull CallableMemberDescriptor object) { + return DescriptorRenderer.TEXT.renderType(object.getReturnType()); + } + }, DescriptorRenderer.HTML); + MAP.setImmutable(); } From 529c416f359eeed89dc75e0b4b4d49fbe25b1df8 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 17 Apr 2012 11:25:39 +0400 Subject: [PATCH 055/147] Added IDE error message for VAR_OVERRIDDEN_BY_VAL. --- .../org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index 25aa8b9adf2..14b280abb3d 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -62,6 +62,9 @@ public class IdeErrorMessages { } }, DescriptorRenderer.HTML); + MAP.put(VAR_OVERRIDDEN_BY_VAL, "Val-property cannot override var-property
" + + "{1}", DescriptorRenderer.HTML, DescriptorRenderer.HTML); + MAP.setImmutable(); } From 3cc1a6990566b0cb5279fee01e8e2e3b86ab7132 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 17 Apr 2012 12:06:30 +0400 Subject: [PATCH 056/147] Added IDE error messages for ABSTRACT_MEMBER_NOT_IMPLEMENTED and MANY_IMPL_MEMBER_NOT_IMPLEMENTED. --- .../jet/plugin/highlighter/IdeErrorMessages.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index 14b280abb3d..5d61d3e7bca 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -23,8 +23,9 @@ import org.jetbrains.jet.lang.diagnostics.rendering.*; import org.jetbrains.jet.resolve.DescriptorRenderer; import static org.jetbrains.jet.lang.diagnostics.Errors.*; -import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.NAME; +import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.RENDER_CLASS_OR_OBJECT; import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.RENDER_TYPE; +import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.TO_STRING; /** * @author Evgeny Gerashchenko @@ -65,6 +66,13 @@ public class IdeErrorMessages { MAP.put(VAR_OVERRIDDEN_BY_VAL, "Val-property cannot override var-property
" + "{1}", DescriptorRenderer.HTML, DescriptorRenderer.HTML); + MAP.put(ABSTRACT_MEMBER_NOT_IMPLEMENTED, "{0} must be declared abstract or implement abstract member
" + + "{1}", RENDER_CLASS_OR_OBJECT, + DescriptorRenderer.HTML); + + MAP.put(MANY_IMPL_MEMBER_NOT_IMPLEMENTED, "{0} must override {1}
because it inherits many implementations of it", + RENDER_CLASS_OR_OBJECT, DescriptorRenderer.HTML); + MAP.setImmutable(); } From a2a9d6847b6e06cd7d2c3956e817b1a641b5cfe8 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 17 Apr 2012 12:08:48 +0400 Subject: [PATCH 057/147] Added IDE error messages for CONFLICTING_OVERLOADS. --- .../org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java | 1 + 1 file changed, 1 insertion(+) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index 5d61d3e7bca..d22dda9ae86 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -72,6 +72,7 @@ public class IdeErrorMessages { MAP.put(MANY_IMPL_MEMBER_NOT_IMPLEMENTED, "{0} must override {1}
because it inherits many implementations of it", RENDER_CLASS_OR_OBJECT, DescriptorRenderer.HTML); + MAP.put(CONFLICTING_OVERLOADS, "{1}
is already defined in ''{0}''", DescriptorRenderer.HTML, TO_STRING); MAP.setImmutable(); } From a723d6b073e27e089e1cde855995867ba7e76153 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 17 Apr 2012 12:17:19 +0400 Subject: [PATCH 058/147] Added IDE error messages for RESULT_TYPE_MISMATCH. --- .../jetbrains/jet/plugin/highlighter/IdeErrorMessages.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index d22dda9ae86..1c8fa601204 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -74,6 +74,10 @@ public class IdeErrorMessages { RENDER_CLASS_OR_OBJECT, DescriptorRenderer.HTML); MAP.put(CONFLICTING_OVERLOADS, "{1}
is already defined in ''{0}''", DescriptorRenderer.HTML, TO_STRING); + MAP.put(RESULT_TYPE_MISMATCH, "Function return type mismatch." + + "" + + "
Expected:{1}
Found:{2}
", TO_STRING, RENDER_TYPE, RENDER_TYPE); + MAP.setImmutable(); } From 5692032530055f93b028da0be19ebdb2c1840705 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Wed, 18 Apr 2012 13:53:49 +0400 Subject: [PATCH 059/147] Added javadoc link to DefaultErrorMessages --- .../org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index 1c8fa601204..ff119974dcf 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -28,6 +28,8 @@ import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.RENDER_TYPE import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.TO_STRING; /** + * @see DefaultErrorMessages + * * @author Evgeny Gerashchenko * @since 4/13/12 */ From a45a7ae631e0863551f94d2c49135e25ce2b3f0d Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Wed, 18 Apr 2012 18:03:31 +0400 Subject: [PATCH 060/147] Made renderers added to DiagnosticWithParametersXRenderer nullable. --- .../DiagnosticFactoryToRendererMap.java | 22 ++++++------ .../rendering/DiagnosticRendererUtil.java | 34 +++++++++++++++++++ .../DiagnosticWithParameters1Renderer.java | 7 ++-- .../DiagnosticWithParameters2Renderer.java | 9 +++-- .../DiagnosticWithParameters3Renderer.java | 15 ++++---- 5 files changed, 65 insertions(+), 22 deletions(-) create mode 100644 compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticRendererUtil.java diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java index 96067f8fd53..cf5615bfa5b 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java @@ -39,29 +39,29 @@ public final class DiagnosticFactoryToRendererMap { } } - public void put(SimpleDiagnosticFactory factory, String message) { + public void put(@NotNull SimpleDiagnosticFactory factory, @NotNull String message) { checkMutability(); map.put(factory, new SimpleDiagnosticRenderer(message)); } - public void put(DiagnosticFactory1 factory, String message, Renderer rendererA) { + public void put(@NotNull DiagnosticFactory1 factory, @NotNull String message, @Nullable Renderer rendererA) { checkMutability(); map.put(factory, new DiagnosticWithParameters1Renderer
(message, rendererA)); } - public void put(DiagnosticFactory2 factory, - String message, - Renderer rendererA, - Renderer rendererB) { + public void put(@NotNull DiagnosticFactory2 factory, + @NotNull String message, + @Nullable Renderer rendererA, + @Nullable Renderer rendererB) { checkMutability(); map.put(factory, new DiagnosticWithParameters2Renderer(message, rendererA, rendererB)); } - public void put(DiagnosticFactory3 factory, - String message, - Renderer rendererA, - Renderer rendererB, - Renderer rendererC) { + public void put(@NotNull DiagnosticFactory3 factory, + @NotNull String message, + @Nullable Renderer rendererA, + @Nullable Renderer rendererB, + @Nullable Renderer rendererC) { checkMutability(); map.put(factory, new DiagnosticWithParameters3Renderer(message, rendererA, rendererB, rendererC)); } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticRendererUtil.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticRendererUtil.java new file mode 100644 index 00000000000..6fdd8653ee0 --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticRendererUtil.java @@ -0,0 +1,34 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.lang.diagnostics.rendering; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * @author Evgeny Gerashchenko + * @since 4/18/12 + */ +public class DiagnosticRendererUtil { + private DiagnosticRendererUtil() { + } + + @NotNull + public static

Object renderParameter(@NotNull P parameter, @Nullable Renderer

renderer) { + return renderer == null ? parameter : renderer.render(parameter); + } +} diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java index f005f2b343b..5727b40beda 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters1Renderer.java @@ -17,10 +17,13 @@ package org.jetbrains.jet.lang.diagnostics.rendering; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.diagnostics.DiagnosticWithParameters1; import java.text.MessageFormat; +import static org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticRendererUtil.renderParameter; + /** * @author Evgeny Gerashchenko * @since 4/12/12 @@ -29,7 +32,7 @@ public class DiagnosticWithParameters1Renderer implements DiagnosticRenderer< private final MessageFormat messageFormat; private final Renderer rendererForA; - public DiagnosticWithParameters1Renderer(@NotNull String message, @NotNull Renderer rendererForA) { + public DiagnosticWithParameters1Renderer(@NotNull String message, @Nullable Renderer rendererForA) { this.messageFormat = new MessageFormat(message); this.rendererForA = rendererForA; } @@ -37,6 +40,6 @@ public class DiagnosticWithParameters1Renderer implements DiagnosticRenderer< @NotNull @Override public String render(@NotNull DiagnosticWithParameters1 diagnostic) { - return messageFormat.format(new Object[]{rendererForA.render(diagnostic.getA())}); + return messageFormat.format(new Object[]{renderParameter(diagnostic.getA(), rendererForA)}); } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters2Renderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters2Renderer.java index d61591c2ba5..506f7cbe767 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters2Renderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters2Renderer.java @@ -17,10 +17,13 @@ package org.jetbrains.jet.lang.diagnostics.rendering; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.diagnostics.DiagnosticWithParameters2; import java.text.MessageFormat; +import static org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticRendererUtil.renderParameter; + /** * @author Evgeny Gerashchenko * @since 4/12/12 @@ -30,7 +33,7 @@ public class DiagnosticWithParameters2Renderer implements DiagnosticRender private final Renderer rendererForA; private final Renderer rendererForB; - public DiagnosticWithParameters2Renderer(@NotNull String message, @NotNull Renderer rendererForA, @NotNull Renderer rendererForB) { + public DiagnosticWithParameters2Renderer(@NotNull String message, @Nullable Renderer rendererForA, @Nullable Renderer rendererForB) { this.messageFormat = new MessageFormat(message); this.rendererForA = rendererForA; this.rendererForB = rendererForB; @@ -40,7 +43,7 @@ public class DiagnosticWithParameters2Renderer implements DiagnosticRender @Override public String render(@NotNull DiagnosticWithParameters2 diagnostic) { return messageFormat.format(new Object[]{ - rendererForA.render(diagnostic.getA()), - rendererForB.render(diagnostic.getB())}); + renderParameter(diagnostic.getA(), rendererForA), + renderParameter(diagnostic.getB(), rendererForB)}); } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters3Renderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters3Renderer.java index fbb42366840..e831df6b0e3 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters3Renderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticWithParameters3Renderer.java @@ -17,10 +17,13 @@ package org.jetbrains.jet.lang.diagnostics.rendering; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.diagnostics.DiagnosticWithParameters3; import java.text.MessageFormat; +import static org.jetbrains.jet.lang.diagnostics.rendering.DiagnosticRendererUtil.renderParameter; + /** * @author Evgeny Gerashchenko * @since 4/12/12 @@ -32,9 +35,9 @@ public class DiagnosticWithParameters3Renderer implements DiagnosticRen private final Renderer rendererForC; public DiagnosticWithParameters3Renderer(@NotNull String message, - @NotNull Renderer rendererForA, - @NotNull Renderer rendererForB, - @NotNull Renderer rendererForC) { + @Nullable Renderer rendererForA, + @Nullable Renderer rendererForB, + @Nullable Renderer rendererForC) { this.messageFormat = new MessageFormat(message); this.rendererForA = rendererForA; this.rendererForB = rendererForB; @@ -45,8 +48,8 @@ public class DiagnosticWithParameters3Renderer implements DiagnosticRen @Override public String render(@NotNull DiagnosticWithParameters3 diagnostic) { return messageFormat.format(new Object[]{ - rendererForA.render(diagnostic.getA()), - rendererForB.render(diagnostic.getB()), - rendererForC.render(diagnostic.getC())}); + renderParameter(diagnostic.getA(), rendererForA), + renderParameter(diagnostic.getB(), rendererForB), + renderParameter(diagnostic.getC(), rendererForC)}); } } From 515b79c2406bc8b51fc9b6fa432762a40e6e1eb6 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Wed, 18 Apr 2012 18:14:32 +0400 Subject: [PATCH 061/147] Better error message for WRONG_NUMBER_OF_TYPE_ARGUMENTS. "1 type arguments" will not be shown anymore. --- .../lang/diagnostics/rendering/DefaultErrorMessages.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java index 3caee29565e..4fe79cf4405 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -371,13 +371,7 @@ public class DefaultErrorMessages { MAP.put(CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS, "Cannot create an instance of an abstract class"); MAP.put(TYPE_INFERENCE_FAILED, "Type inference failed: {0}", TO_STRING); - MAP.put(WRONG_NUMBER_OF_TYPE_ARGUMENTS, "{0} type arguments expected", new Renderer() { - @NotNull - @Override - public String render(@NotNull Integer argument) { - return argument == 0 ? "No" : argument.toString(); - } - }); + MAP.put(WRONG_NUMBER_OF_TYPE_ARGUMENTS, "{0,choice,0#No type arguments|1#Type argument|1<{0,number,integer} type argument} expected", null); MAP.put(UNRESOLVED_IDE_TEMPLATE, "Unresolved IDE template: {0}", TO_STRING); From a824b81aa5ece5b988be1c1fa43a37d255406741 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Wed, 18 Apr 2012 18:18:25 +0400 Subject: [PATCH 062/147] Minor refactoring renderer for INCOMPATIBLE_MODIFIERS. --- .../lang/diagnostics/rendering/DefaultErrorMessages.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java index 4fe79cf4405..e9a1481b09a 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -64,12 +64,11 @@ public class DefaultErrorMessages { @Override public String render(@NotNull Collection tokens) { StringBuilder sb = new StringBuilder(); - for (Iterator iterator = tokens.iterator(); iterator.hasNext(); ) { - JetKeywordToken modifier = iterator.next(); - sb.append(modifier.getValue()); - if (iterator.hasNext()) { + for (JetKeywordToken token : tokens) { + if (sb.length() != 0) { sb.append(" "); } + sb.append(token.getValue()); } return sb.toString(); } From 7a605ccee2f5fcd5f5c3fd02badf979cdf53a8c9 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Wed, 18 Apr 2012 20:05:26 +0400 Subject: [PATCH 063/147] Added IDE error message for ASSIGN_OPERATOR_AMBIGUITY. --- .../plugin/highlighter/IdeErrorMessages.java | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index ff119974dcf..57b7b3b9b9c 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -17,15 +17,17 @@ package org.jetbrains.jet.plugin.highlighter; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.descriptors.CallableDescriptor; import org.jetbrains.jet.lang.descriptors.CallableMemberDescriptor; import org.jetbrains.jet.lang.diagnostics.Diagnostic; import org.jetbrains.jet.lang.diagnostics.rendering.*; +import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; import org.jetbrains.jet.resolve.DescriptorRenderer; +import java.util.Collection; + import static org.jetbrains.jet.lang.diagnostics.Errors.*; -import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.RENDER_CLASS_OR_OBJECT; -import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.RENDER_TYPE; -import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.TO_STRING; +import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.*; /** * @see DefaultErrorMessages @@ -40,6 +42,20 @@ public class IdeErrorMessages { static { MAP.put(TYPE_MISMATCH, "Type mismatch.
Required:{0}
Found:{1}
", RENDER_TYPE, RENDER_TYPE); + MAP.put(ASSIGN_OPERATOR_AMBIGUITY, "Assignment operators ambiguity. All these functions match.

", new Renderer>>() { + @NotNull + @Override + public String render(@NotNull Collection> calls) { + StringBuilder stringBuilder = new StringBuilder(""); + for (ResolvedCall call : calls) { + stringBuilder.append("
  • "); + stringBuilder.append(DescriptorRenderer.HTML.render(call.getResultingDescriptor())).append("\n"); + stringBuilder.append("
  • "); + } + return stringBuilder.toString(); + } + }); + MAP.put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property." + "" + "
    Expected:{0}
    Found:{1}
    ", RENDER_TYPE, RENDER_TYPE); From 625101b68d68c58a3bf48fca034c8cdf0d2e9359 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Wed, 18 Apr 2012 20:28:46 +0400 Subject: [PATCH 064/147] Added IDE error message for ITERATOR_AMBIGUITY. --- .../plugin/highlighter/IdeErrorMessages.java | 32 +++++++++++-------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index 57b7b3b9b9c..4425b6aacff 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -39,22 +39,26 @@ public class IdeErrorMessages { public static final DiagnosticFactoryToRendererMap MAP = new DiagnosticFactoryToRendererMap(); public static final DiagnosticRenderer RENDERER = new DispatchingDiagnosticRenderer(MAP, DefaultErrorMessages.MAP); + private static final Renderer>> HTML_AMBIGUOUS_CALLS = + new Renderer>>() { + @NotNull + @Override + public String render(@NotNull Collection> calls) { + StringBuilder stringBuilder = new StringBuilder(""); + for (ResolvedCall call : calls) { + stringBuilder.append("
  • "); + stringBuilder.append(DescriptorRenderer.HTML.render(call.getResultingDescriptor())).append("\n"); + stringBuilder.append("
  • "); + } + return stringBuilder.toString(); + } + }; + static { MAP.put(TYPE_MISMATCH, "Type mismatch.
    Required:{0}
    Found:{1}
    ", RENDER_TYPE, RENDER_TYPE); - MAP.put(ASSIGN_OPERATOR_AMBIGUITY, "Assignment operators ambiguity. All these functions match.
      {0}
    ", new Renderer>>() { - @NotNull - @Override - public String render(@NotNull Collection> calls) { - StringBuilder stringBuilder = new StringBuilder(""); - for (ResolvedCall call : calls) { - stringBuilder.append("
  • "); - stringBuilder.append(DescriptorRenderer.HTML.render(call.getResultingDescriptor())).append("\n"); - stringBuilder.append("
  • "); - } - return stringBuilder.toString(); - } - }); + MAP.put(ASSIGN_OPERATOR_AMBIGUITY, "Assignment operators ambiguity. All these functions match.
      {0}
    ", + HTML_AMBIGUOUS_CALLS); MAP.put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property." + "" + @@ -63,6 +67,8 @@ public class IdeErrorMessages { "
    Expected:{0}
    " + "
    Expected:{0}
    Found:{1}
    ", RENDER_TYPE, RENDER_TYPE); + MAP.put(ITERATOR_AMBIGUITY, "Method ''iterator()'' is ambiguous for this expression.
      {0}
    ", HTML_AMBIGUOUS_CALLS); + MAP.put(UPPER_BOUND_VIOLATED, "Type argument is not within its bounds." + "" + "
    Expected:{0}
    Found:{1}
    ", RENDER_TYPE, RENDER_TYPE); From 7e1059d3bd76742d62d6adfe228e41f47fbe5fa6 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Wed, 18 Apr 2012 20:36:43 +0400 Subject: [PATCH 065/147] Added IDE error messages for OVERLOAD_RESOLUTION_AMBIGUITY and NONE_APPLICABLE. --- .../org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index 4425b6aacff..d8cc81dfaa0 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -102,6 +102,9 @@ public class IdeErrorMessages { "" + "
    Expected:{1}
    Found:{2}
    ", TO_STRING, RENDER_TYPE, RENDER_TYPE); + MAP.put(OVERLOAD_RESOLUTION_AMBIGUITY, "Overload resolution ambiguity. All these functions match.
      {0}
    ", HTML_AMBIGUOUS_CALLS); + MAP.put(NONE_APPLICABLE, "None of the following functions can be called with the arguments supplied.
      {0}
    ", HTML_AMBIGUOUS_CALLS); + MAP.setImmutable(); } From 99acd9cdf0d12b0cd7e3c26ce50fccd46e3aea41 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Wed, 18 Apr 2012 21:25:04 +0400 Subject: [PATCH 066/147] Fixed rendering "defined in ..." DescriptorRenderer, now it doesn't render "." --- .../jet/resolve/DescriptorRenderer.java | 14 +++----- compiler/testData/renderer/Classes.kt | 36 +++++++++---------- compiler/testData/renderer/FunctionTypes.kt | 16 ++++----- compiler/testData/renderer/GlobalFunctions.kt | 18 +++++----- .../testData/renderer/GlobalProperties.kt | 14 ++++---- compiler/testData/renderer/TupleTypes.kt | 20 +++++------ 6 files changed, 56 insertions(+), 62 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java index c9cb6cf9cc1..a09b73ef863 100644 --- a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java @@ -21,6 +21,8 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.diagnostics.rendering.Renderer; import org.jetbrains.jet.lang.resolve.DescriptorUtils; +import org.jetbrains.jet.lang.resolve.FqName; +import org.jetbrains.jet.lang.resolve.FqNameUnsafe; import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverDescriptor; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.TypeProjection; @@ -227,7 +229,8 @@ public class DescriptorRenderer implements Renderer { final DeclarationDescriptor containingDeclaration = declarationDescriptor.getContainingDeclaration(); if (containingDeclaration != null) { - renderFullyQualifiedName(containingDeclaration, stringBuilder); + FqNameUnsafe fqName = DescriptorUtils.getFQName(containingDeclaration); + stringBuilder.append(FqName.ROOT.toUnsafe().equals(fqName) ? "root package" : escape(fqName.getFqName())); } } @@ -244,15 +247,6 @@ public class DescriptorRenderer implements Renderer { return s; } - private void renderFullyQualifiedName(DeclarationDescriptor descriptor, StringBuilder stringBuilder) { - DeclarationDescriptor containingDeclaration = descriptor.getContainingDeclaration(); - if (containingDeclaration != null) { - renderFullyQualifiedName(containingDeclaration, stringBuilder); - stringBuilder.append("."); - } - stringBuilder.append(escape(descriptor.getName())); - } - private class RenderDeclarationDescriptorVisitor extends DeclarationDescriptorVisitor { @Override diff --git a/compiler/testData/renderer/Classes.kt b/compiler/testData/renderer/Classes.kt index ecdd7945e3c..e5e9b52e2fc 100644 --- a/compiler/testData/renderer/Classes.kt +++ b/compiler/testData/renderer/Classes.kt @@ -29,21 +29,21 @@ private enum class TheEnum(val rgb : Int) { VAL1 : TheEnum(0xFF0000) } -//package rendererTest defined in . -//internal final annotation class TheAnnotation defined in ..rendererTest -//public open class TheClass defined in ..rendererTest -// defined in ..rendererTest.TheClass -// defined in ..rendererTest.TheClass -//private final val privateVal : jet.Int defined in ..rendererTest.TheClass -//internal final val shouldBeFinal : jet.Int defined in ..rendererTest.TheClass -//protected abstract fun foo() : Unit defined in ..rendererTest.TheClass -//private final class Inner defined in ..rendererTest.TheClass -//internal final class InternalClass defined in ..rendererTest -//internal trait TheTrait defined in ..rendererTest -//internal abstract fun abstractFun() : Unit defined in ..rendererTest.TheTrait -//object : rendererTest.TheClass defined in ..rendererTest.TheTrait -//internal final fun classObjectFunction() : jet.Int defined in ..rendererTest.TheTrait. -//private final enum class TheEnum defined in ..rendererTest -//value-parameter val rgb : jet.Int defined in ..rendererTest.TheEnum. -//internal final class VAL1 : rendererTest.TheEnum defined in ..rendererTest.TheEnum.class-object-for-TheEnum -//internal final val VAL1 : rendererTest.TheEnum.class-object-for-TheEnum.VAL1 defined in ..rendererTest.TheEnum.class-object-for-TheEnum +//package rendererTest defined in root package +//internal final annotation class TheAnnotation defined in rendererTest +//public open class TheClass defined in rendererTest +// defined in rendererTest.TheClass +// defined in rendererTest.TheClass +//private final val privateVal : jet.Int defined in rendererTest.TheClass +//internal final val shouldBeFinal : jet.Int defined in rendererTest.TheClass +//protected abstract fun foo() : Unit defined in rendererTest.TheClass +//private final class Inner defined in rendererTest.TheClass +//internal final class InternalClass defined in rendererTest +//internal trait TheTrait defined in rendererTest +//internal abstract fun abstractFun() : Unit defined in rendererTest.TheTrait +//object : rendererTest.TheClass defined in rendererTest.TheTrait +//internal final fun classObjectFunction() : jet.Int defined in rendererTest.TheTrait. +//private final enum class TheEnum defined in rendererTest +//value-parameter val rgb : jet.Int defined in rendererTest.TheEnum. +//internal final class VAL1 : rendererTest.TheEnum defined in rendererTest.TheEnum.class-object-for-TheEnum +//internal final val VAL1 : rendererTest.TheEnum.class-object-for-TheEnum.VAL1 defined in rendererTest.TheEnum.class-object-for-TheEnum diff --git a/compiler/testData/renderer/FunctionTypes.kt b/compiler/testData/renderer/FunctionTypes.kt index 425c01d91be..9cb510a4e36 100644 --- a/compiler/testData/renderer/FunctionTypes.kt +++ b/compiler/testData/renderer/FunctionTypes.kt @@ -8,11 +8,11 @@ var v6 : Int.(String, Int) -> Unit var v7 : ExtensionFunction1 -//internal final var v1 : () -> Unit defined in . -//internal final var v2 : (jet.Int) -> jet.Int defined in . -//internal final var v3 : (jet.Int, #(jet.String, jet.String)) -> jet.String defined in . -//internal final var v4 : (jet.Int) -> jet.String defined in . -//internal final var v4 : (() -> jet.Int, (#(jet.String, jet.String)) -> Unit) -> jet.String defined in . -//internal final var v5 : jet.Int.() -> jet.Int defined in . -//internal final var v6 : jet.Int.(jet.String, jet.Int) -> Unit defined in . -//internal final var v7 : jet.Int.(jet.String) -> jet.Boolean defined in . +//internal final var v1 : () -> Unit defined in root package +//internal final var v2 : (jet.Int) -> jet.Int defined in root package +//internal final var v3 : (jet.Int, #(jet.String, jet.String)) -> jet.String defined in root package +//internal final var v4 : (jet.Int) -> jet.String defined in root package +//internal final var v4 : (() -> jet.Int, (#(jet.String, jet.String)) -> Unit) -> jet.String defined in root package +//internal final var v5 : jet.Int.() -> jet.Int defined in root package +//internal final var v6 : jet.Int.(jet.String, jet.Int) -> Unit defined in root package +//internal final var v7 : jet.Int.(jet.String) -> jet.Boolean defined in root package diff --git a/compiler/testData/renderer/GlobalFunctions.kt b/compiler/testData/renderer/GlobalFunctions.kt index 21a4d40204a..1a415f1b80f 100644 --- a/compiler/testData/renderer/GlobalFunctions.kt +++ b/compiler/testData/renderer/GlobalFunctions.kt @@ -10,12 +10,12 @@ private fun prv(a : String, b : Int = 5) = 5 public fun Int.ext() : Int {} -//package rendererTest defined in . -//public final fun pub() : Unit defined in ..rendererTest -//internal final fun int() : jet.String defined in ..rendererTest -//internal final fun int2(val ints : jet.IntArray) : jet.Int defined in ..rendererTest -//value-parameter vararg val ints : jet.IntArray defined in ..rendererTest.int2 -//private final fun prv(val a : jet.String, val b : jet.Int = ...) : jet.Int defined in ..rendererTest -//value-parameter val a : jet.String defined in ..rendererTest.prv -//value-parameter val b : jet.Int defined in ..rendererTest.prv -//public final fun jet.Int.ext() : jet.Int defined in ..rendererTest \ No newline at end of file +//package rendererTest defined in root package +//public final fun pub() : Unit defined in rendererTest +//internal final fun int() : jet.String defined in rendererTest +//internal final fun int2(val ints : jet.IntArray) : jet.Int defined in rendererTest +//value-parameter vararg val ints : jet.IntArray defined in rendererTest.int2 +//private final fun prv(val a : jet.String, val b : jet.Int = ...) : jet.Int defined in rendererTest +//value-parameter val a : jet.String defined in rendererTest.prv +//value-parameter val b : jet.Int defined in rendererTest.prv +//public final fun jet.Int.ext() : jet.Int defined in rendererTest \ No newline at end of file diff --git a/compiler/testData/renderer/GlobalProperties.kt b/compiler/testData/renderer/GlobalProperties.kt index 943674128cd..25ff60f9d0a 100644 --- a/compiler/testData/renderer/GlobalProperties.kt +++ b/compiler/testData/renderer/GlobalProperties.kt @@ -11,10 +11,10 @@ private var private = 5 public val Int.ext : Int get() {} -//package rendererTest defined in . -//public final val pub : jet.String defined in ..rendererTest -//internal final var int : jet.String defined in ..rendererTest -//internal final val int2 : jet.Int defined in ..rendererTest -//private final var private : jet.Int defined in ..rendererTest -//public final val jet.Int.ext : jet.Int defined in ..rendererTest -//public final fun jet.Int.get-ext() : jet.Int defined in ..rendererTest \ No newline at end of file +//package rendererTest defined in root package +//public final val pub : jet.String defined in rendererTest +//internal final var int : jet.String defined in rendererTest +//internal final val int2 : jet.Int defined in rendererTest +//private final var private : jet.Int defined in rendererTest +//public final val jet.Int.ext : jet.Int defined in rendererTest +//public final fun jet.Int.get-ext() : jet.Int defined in rendererTest \ No newline at end of file diff --git a/compiler/testData/renderer/TupleTypes.kt b/compiler/testData/renderer/TupleTypes.kt index 73f1ecb3e50..184bf00bc9f 100644 --- a/compiler/testData/renderer/TupleTypes.kt +++ b/compiler/testData/renderer/TupleTypes.kt @@ -9,13 +9,13 @@ var v8 : #(Int, String, String) var v9 : Tuple2 var v10 : Tuple3? -//internal final var v1 : Unit defined in . -//internal final var v2 : Unit? defined in . -//internal final var v3 : Unit defined in . -//internal final var v4 : Unit? defined in . -//internal final var v5 : Unit defined in . -//internal final var v6 : #(jet.Int) defined in . -//internal final var v7 : #(jet.Int)? defined in . -//internal final var v8 : #(jet.Int, jet.String, jet.String) defined in . -//internal final var v9 : #(jet.Int, jet.String) defined in . -//internal final var v10 : #(jet.Int, jet.Int, jet.Int)? defined in . +//internal final var v1 : Unit defined in root package +//internal final var v2 : Unit? defined in root package +//internal final var v3 : Unit defined in root package +//internal final var v4 : Unit? defined in root package +//internal final var v5 : Unit defined in root package +//internal final var v6 : #(jet.Int) defined in root package +//internal final var v7 : #(jet.Int)? defined in root package +//internal final var v8 : #(jet.Int, jet.String, jet.String) defined in root package +//internal final var v9 : #(jet.Int, jet.String) defined in root package +//internal final var v10 : #(jet.Int, jet.Int, jet.Int)? defined in root package From 12abe1a5ee0a74070ac430eeecbcf69c21fa5093 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 19 Apr 2012 15:54:07 +0400 Subject: [PATCH 067/147] Fixed error for TYPE_MISMATCH_IN_TUPLE_PATTERN. --- .../jet/lang/diagnostics/rendering/DefaultErrorMessages.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java index e9a1481b09a..6022304b0b6 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -302,8 +302,7 @@ public class DefaultErrorMessages { MAP.put(TYPE_MISMATCH_IN_FOR_LOOP, "The loop iterates over values of type {0} but the parameter is declared to be {1}", RENDER_TYPE, RENDER_TYPE); MAP.put(TYPE_MISMATCH_IN_CONDITION, "Condition must be of type jet.Boolean, but is of type {0}", RENDER_TYPE); - MAP.put(TYPE_MISMATCH_IN_TUPLE_PATTERN, "Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, - TO_STRING); // TODO: message + MAP.put(TYPE_MISMATCH_IN_TUPLE_PATTERN, "Type mismatch: subject is of type {0} but the pattern is a {1}-tuple", RENDER_TYPE, TO_STRING); MAP.put(TYPE_MISMATCH_IN_BINDING_PATTERN, "{0} is not a supertype of {1}. Use ''is'' to match against {0}", RENDER_TYPE, RENDER_TYPE); MAP.put(INCOMPATIBLE_TYPES, "Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE); MAP.put(EXPECTED_CONDITION, "Expected condition of jet.Boolean type"); From d28aed6494ce67944df0c12e596f3795217c9ff8 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 19 Apr 2012 16:12:16 +0400 Subject: [PATCH 068/147] Improved positioning for PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT. --- .../org/jetbrains/jet/lang/diagnostics/Errors.java | 11 ++--------- .../jet/lang/diagnostics/PositioningStrategies.java | 9 +++++++++ .../tests/ProjectionOnFunctionArgumentErrror.jet | 2 +- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java index a75cf063278..65582adaac5 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java @@ -71,14 +71,7 @@ public interface Errors { SimpleDiagnosticFactory TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory RETURN_NOT_ALLOWED = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE = - SimpleDiagnosticFactory.create(ERROR, - new PositioningStrategy() { - @NotNull - @Override - public List mark(@NotNull JetTypeProjection element) { - return markNode(element.getProjectionNode()); - } - }); + SimpleDiagnosticFactory.create(ERROR, PositioningStrategies.PROJECTION_MODIFIER); SimpleDiagnosticFactoryLABEL_NAME_CLASH = SimpleDiagnosticFactory.create(WARNING); SimpleDiagnosticFactory EXPRESSION_EXPECTED_NAMESPACE_FOUND = SimpleDiagnosticFactory.create(ERROR); @@ -143,7 +136,7 @@ public interface Errors { SimpleDiagnosticFactory.create(ERROR, PositioningStrategies.POSITION_NAME_IDENTIFIER); SimpleDiagnosticFactory PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT = - SimpleDiagnosticFactory.create(ERROR); // TODO : better positioning + SimpleDiagnosticFactory.create(ERROR, PositioningStrategies.PROJECTION_MODIFIER); SimpleDiagnosticFactory SUPERTYPE_NOT_INITIALIZED = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory SUPERTYPE_NOT_INITIALIZED_DEFAULT = SimpleDiagnosticFactory.create(ERROR); SimpleDiagnosticFactory SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY = SimpleDiagnosticFactory.create(ERROR); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/PositioningStrategies.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/PositioningStrategies.java index 5cfdb034a23..e25aaa85e88 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/PositioningStrategies.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/PositioningStrategies.java @@ -28,6 +28,7 @@ import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lexer.JetKeywordToken; import org.jetbrains.jet.lexer.JetTokens; +import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -133,4 +134,12 @@ public class PositioningStrategies { return result; } }; + + public static PositioningStrategy PROJECTION_MODIFIER = new PositioningStrategy() { + @NotNull + @Override + public List mark(@NotNull JetTypeProjection element) { + return markNode(element.getProjectionNode()); + } + }; } \ No newline at end of file diff --git a/compiler/testData/diagnostics/tests/ProjectionOnFunctionArgumentErrror.jet b/compiler/testData/diagnostics/tests/ProjectionOnFunctionArgumentErrror.jet index e8b80c8f4ca..3248de9941e 100644 --- a/compiler/testData/diagnostics/tests/ProjectionOnFunctionArgumentErrror.jet +++ b/compiler/testData/diagnostics/tests/ProjectionOnFunctionArgumentErrror.jet @@ -1,4 +1,4 @@ fun test() { fun foo(){} - foo<in Int>() + foo<in Int>() } From 1559f983aaacb2a174bc84c0d367f58f121ca889 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 19 Apr 2012 16:30:34 +0400 Subject: [PATCH 069/147] Made soft keywords bold in DescriptorRenderer. --- .../org/jetbrains/jet/resolve/DescriptorRenderer.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java index a09b73ef863..7d8ddddf43b 100644 --- a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java @@ -308,22 +308,23 @@ public class DescriptorRenderer implements Renderer { } private void renderVisibility(Visibility visibility, StringBuilder builder) { - builder.append(visibility).append(" "); + builder.append(renderKeyword(visibility.toString())).append(" "); } private void renderModality(Modality modality, StringBuilder builder) { + String keyword = ""; switch (modality) { case FINAL: - builder.append("final"); + keyword = "final"; break; case OPEN: - builder.append("open"); + keyword = "open"; break; case ABSTRACT: - builder.append("abstract"); + keyword = "abstract"; break; } - builder.append(" "); + builder.append(renderKeyword(keyword)).append(" "); } @Override From 85ce85383be0c0838fca0ca2503cc9c3ac0573ff Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 19 Apr 2012 18:46:45 +0400 Subject: [PATCH 070/147] Added rendering variance for type parameters in DescriptorRenderer. --- .../src/org/jetbrains/jet/resolve/DescriptorRenderer.java | 8 +++++++- compiler/testData/renderer/Classes.kt | 4 ++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java index 7d8ddddf43b..a2ff448bc28 100644 --- a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java @@ -469,7 +469,13 @@ public class DescriptorRenderer implements Renderer { } protected void renderTypeParameter(TypeParameterDescriptor descriptor, StringBuilder builder) { - if (!descriptor.isReified()) { + if (descriptor.isReified()) { + String variance = descriptor.getVariance().toString(); + if (!variance.isEmpty()) { + builder.append(renderKeyword(variance)).append(" "); + } + } + else { builder.append(renderKeyword("erased")).append(" "); } renderName(descriptor, builder); diff --git a/compiler/testData/renderer/Classes.kt b/compiler/testData/renderer/Classes.kt index e5e9b52e2fc..e69596a832a 100644 --- a/compiler/testData/renderer/Classes.kt +++ b/compiler/testData/renderer/Classes.kt @@ -31,8 +31,8 @@ private enum class TheEnum(val rgb : Int) { //package rendererTest defined in root package //internal final annotation class TheAnnotation defined in rendererTest -//public open class TheClass defined in rendererTest -// defined in rendererTest.TheClass +//public open class TheClass defined in rendererTest +// defined in rendererTest.TheClass // defined in rendererTest.TheClass //private final val privateVal : jet.Int defined in rendererTest.TheClass //internal final val shouldBeFinal : jet.Int defined in rendererTest.TheClass From 4aae7a7dd19c23f059dee0cd83292c0e2ea59ddc Mon Sep 17 00:00:00 2001 From: cy6erGn0m Date: Thu, 19 Apr 2012 21:29:30 +0400 Subject: [PATCH 071/147] Added utility functions for simple file reading by lines and by byte blocks --- libraries/stdlib/src/kotlin/io/Files.kt | 55 +++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/libraries/stdlib/src/kotlin/io/Files.kt b/libraries/stdlib/src/kotlin/io/Files.kt index 960c9093b59..e217a6921ee 100644 --- a/libraries/stdlib/src/kotlin/io/Files.kt +++ b/libraries/stdlib/src/kotlin/io/Files.kt @@ -3,6 +3,8 @@ package kotlin.io import java.io.* import java.nio.charset.* import java.util.NoSuchElementException +import java.util.List +import java.util.ArrayList import java.net.URL @@ -147,3 +149,56 @@ public fun File.copyTo(file: File, bufferSize: Int = defaultBufferSize): Long { } } } + +/** + * Reads file by byte blocks and calls closure for each block read. Block size depends on implementation but never less than 512. + * This functions passes byte array and amount of bytes in this buffer to the closure function. + * + * You can use this function for huge files + */ +fun File.forEachBlock(closure : (ByteArray, Int) -> Unit) : Unit { + val arr = ByteArray(4096) + val fis = FileInputStream(this) + + try { + do { + val size = fis.read(arr) + if (size == -1) { + break + } else if (size > 0) { + closure(arr, size) + } + } while(true) + } finally { + fis.close() + } +} + +/** + * Reads file line by line. Default charset is UTF-8. + * + * You may use this function on huge files + */ +fun File.forEachLine (charset : String = "UTF-8", closure : (line : String) -> Unit) : Unit { + val reader = BufferedReader(InputStreamReader(FileInputStream(this), charset)) + try { + reader.forEachLine(closure) + } finally { + reader.close() + } +} + +/** + * Reads file content as strings list. By default uses UTF-8 charset. + * + * Do not use this function for huge files. + */ +fun File.readLines(charset : String = "UTF-8") : List { + val rs = ArrayList() + + this.forEachLine(charset) { (line : String) : Unit -> + rs.add(line); + } + + return rs +} From de893bb675c884ea0b9f7e698b8e7ecdc4fa99db Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Fri, 20 Apr 2012 20:34:58 +0400 Subject: [PATCH 072/147] Refresh VFS to prevent sporadic test failures --- .../jetbrains/jet/plugin/libraries/AbstractLibrariesTest.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/idea/tests/org/jetbrains/jet/plugin/libraries/AbstractLibrariesTest.java b/idea/tests/org/jetbrains/jet/plugin/libraries/AbstractLibrariesTest.java index d534e506ec2..4b225a785ef 100644 --- a/idea/tests/org/jetbrains/jet/plugin/libraries/AbstractLibrariesTest.java +++ b/idea/tests/org/jetbrains/jet/plugin/libraries/AbstractLibrariesTest.java @@ -25,6 +25,7 @@ import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileVisitor; +import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.testFramework.PlatformTestCase; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.cli.KotlinCompiler; @@ -66,6 +67,9 @@ public abstract class AbstractLibrariesTest extends PlatformTestCase { libraryDir = LocalFileSystem.getInstance().findFileByIoFile(libraryIoDir); assertNotNull(libraryDir); + ((NewVirtualFile)libraryDir).markDirtyRecursively(); + libraryDir.refresh(false, true); + ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { From 1f7c435a246b3d638417baa93cb9e7b2f685045d Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 19 Apr 2012 18:58:40 +0400 Subject: [PATCH 073/147] Removed val/var soft keywords in renderer for functions --- .../jetbrains/jet/resolve/DescriptorRenderer.java | 14 ++++++++++---- compiler/testData/renderer/GlobalFunctions.kt | 4 ++-- idea/testData/libraries/decompiled/namespace.kt | 10 +++++----- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java index a2ff448bc28..60c36f8f7fb 100644 --- a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java @@ -81,7 +81,7 @@ public class DescriptorRenderer implements Renderer { @Override public Void visitValueParameterDescriptor(ValueParameterDescriptor descriptor, StringBuilder builder) { - super.visitVariableDescriptor(descriptor, builder); + super.visitVariableDescriptor(descriptor, builder, true); if (descriptor.hasDefaultValue()) { builder.append(" = ..."); } @@ -260,9 +260,13 @@ public class DescriptorRenderer implements Renderer { @Override public Void visitVariableDescriptor(VariableDescriptor descriptor, StringBuilder builder) { + return visitVariableDescriptor(descriptor, builder, false); + } + + protected Void visitVariableDescriptor(VariableDescriptor descriptor, StringBuilder builder, boolean skipValVar) { String typeString = renderPropertyPrefixAndComputeTypeString( builder, - descriptor.isVar(), + skipValVar ? null : descriptor.isVar(), Collections.emptyList(), ReceiverDescriptor.NO_RECEIVER, descriptor.getType()); @@ -273,13 +277,15 @@ public class DescriptorRenderer implements Renderer { private String renderPropertyPrefixAndComputeTypeString( @NotNull StringBuilder builder, - boolean isVar, + @Nullable Boolean isVar, @NotNull List typeParameters, @NotNull ReceiverDescriptor receiver, @Nullable JetType outType) { String typeString = lt() + "no type>"; if (outType != null) { - builder.append(renderKeyword(isVar ? "var" : "val")).append(" "); + if (isVar != null) { + builder.append(renderKeyword(isVar ? "var" : "val")).append(" "); + } typeString = renderType(outType); } diff --git a/compiler/testData/renderer/GlobalFunctions.kt b/compiler/testData/renderer/GlobalFunctions.kt index 1a415f1b80f..2f834c7fd8d 100644 --- a/compiler/testData/renderer/GlobalFunctions.kt +++ b/compiler/testData/renderer/GlobalFunctions.kt @@ -13,9 +13,9 @@ public fun Int.ext() : Int {} //package rendererTest defined in root package //public final fun pub() : Unit defined in rendererTest //internal final fun int() : jet.String defined in rendererTest -//internal final fun int2(val ints : jet.IntArray) : jet.Int defined in rendererTest +//internal final fun int2(ints : jet.IntArray) : jet.Int defined in rendererTest //value-parameter vararg val ints : jet.IntArray defined in rendererTest.int2 -//private final fun prv(val a : jet.String, val b : jet.Int = ...) : jet.Int defined in rendererTest +//private final fun prv(a : jet.String, b : jet.Int = ...) : jet.Int defined in rendererTest //value-parameter val a : jet.String defined in rendererTest.prv //value-parameter val b : jet.Int defined in rendererTest.prv //public final fun jet.Int.ext() : jet.Int defined in rendererTest \ No newline at end of file diff --git a/idea/testData/libraries/decompiled/namespace.kt b/idea/testData/libraries/decompiled/namespace.kt index 100819a0647..7357f1b34c7 100644 --- a/idea/testData/libraries/decompiled/namespace.kt +++ b/idea/testData/libraries/decompiled/namespace.kt @@ -15,12 +15,12 @@ package testData.libraries [public final fun func() : Unit { /* compiled code */ }] -[public final fun func(val a : jet.Int, val b : jet.Int) : Unit { /* compiled code */ }] +[public final fun func(a : jet.Int, b : jet.Int) : Unit { /* compiled code */ }] -[public final fun func(val a : jet.Int, val b : jet.String = /* compiled code */) : Unit { /* compiled code */ }] +[public final fun func(a : jet.Int, b : jet.String = /* compiled code */) : Unit { /* compiled code */ }] -[public final fun func(val str : jet.String) : Unit { /* compiled code */ }] +[public final fun func(str : jet.String) : Unit { /* compiled code */ }] -[public final fun main(val args : jet.Array) : Unit { /* compiled code */ }] +[public final fun main(args : jet.Array) : Unit { /* compiled code */ }] -[public final fun T.filter(val predicate : (T) -> jet.Boolean) : T? { /* compiled code */ }] +[public final fun T.filter(predicate : (T) -> jet.Boolean) : T? { /* compiled code */ }] From 90ac45f3f974f95287da7a57cc662bfa9b7b55db Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 19 Apr 2012 22:53:42 +0400 Subject: [PATCH 074/147] Added extra space after function type arguments list in DescriptorRenderer. Added test. --- .../src/org/jetbrains/jet/resolve/DescriptorRenderer.java | 1 + compiler/testData/renderer/GlobalFunctions.kt | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java index 60c36f8f7fb..fe48060d1bd 100644 --- a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java @@ -388,6 +388,7 @@ public class DescriptorRenderer implements Renderer { } } builder.append(">"); + return true; } return false; } diff --git a/compiler/testData/renderer/GlobalFunctions.kt b/compiler/testData/renderer/GlobalFunctions.kt index 2f834c7fd8d..a8a859da282 100644 --- a/compiler/testData/renderer/GlobalFunctions.kt +++ b/compiler/testData/renderer/GlobalFunctions.kt @@ -10,6 +10,8 @@ private fun prv(a : String, b : Int = 5) = 5 public fun Int.ext() : Int {} +public fun withTypeParam(a : Array) : Int {} + //package rendererTest defined in root package //public final fun pub() : Unit defined in rendererTest //internal final fun int() : jet.String defined in rendererTest @@ -18,4 +20,7 @@ public fun Int.ext() : Int {} //private final fun prv(a : jet.String, b : jet.Int = ...) : jet.Int defined in rendererTest //value-parameter val a : jet.String defined in rendererTest.prv //value-parameter val b : jet.Int defined in rendererTest.prv -//public final fun jet.Int.ext() : jet.Int defined in rendererTest \ No newline at end of file +//public final fun jet.Int.ext() : jet.Int defined in rendererTest +//public final fun withTypeParam(a : jet.Array) : jet.Int defined in rendererTest +// defined in rendererTest.withTypeParam +//value-parameter val a : jet.Array defined in rendererTest.withTypeParam \ No newline at end of file From 9a3af476e543124a17d3add287eff50fe0510029 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 19 Apr 2012 23:36:39 +0400 Subject: [PATCH 075/147] Implemented getDiagnostics() in BindingContext returned by DelegatingBindingTrace. --- .../org/jetbrains/jet/lang/resolve/DelegatingBindingTrace.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DelegatingBindingTrace.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DelegatingBindingTrace.java index f971dcdb619..f7159a905cc 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DelegatingBindingTrace.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DelegatingBindingTrace.java @@ -36,7 +36,7 @@ public class DelegatingBindingTrace implements BindingTrace { private final BindingContext bindingContext = new BindingContext() { @Override public Collection getDiagnostics() { - throw new UnsupportedOperationException(); // TODO + return diagnostics; } @Override @@ -57,6 +57,7 @@ public class DelegatingBindingTrace implements BindingTrace { } @Override + @NotNull public BindingContext getBindingContext() { return bindingContext; } From 60622337c322914a77dcf37b489aec7f5d43d9e6 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Thu, 19 Apr 2012 23:41:52 +0400 Subject: [PATCH 076/147] Implemented stub of highlighting parameters in error tooltip for NONE_APPLICABLE. --- .../plugin/highlighter/IdeErrorMessages.java | 71 ++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index d8cc81dfaa0..66d97803a6a 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -16,15 +16,27 @@ package org.jetbrains.jet.plugin.highlighter; +import com.intellij.psi.PsiElement; +import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.descriptors.CallableDescriptor; import org.jetbrains.jet.lang.descriptors.CallableMemberDescriptor; +import org.jetbrains.jet.lang.descriptors.ValueParameterDescriptor; import org.jetbrains.jet.lang.diagnostics.Diagnostic; +import org.jetbrains.jet.lang.diagnostics.DiagnosticWithParameters1; +import org.jetbrains.jet.lang.diagnostics.Errors; import org.jetbrains.jet.lang.diagnostics.rendering.*; +import org.jetbrains.jet.lang.psi.JetValueArgument; +import org.jetbrains.jet.lang.psi.JetValueArgumentList; +import org.jetbrains.jet.lang.psi.ValueArgument; import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; +import org.jetbrains.jet.lang.resolve.calls.ResolvedCallImpl; +import org.jetbrains.jet.lang.resolve.calls.ResolvedValueArgument; import org.jetbrains.jet.resolve.DescriptorRenderer; import java.util.Collection; +import java.util.Map; import static org.jetbrains.jet.lang.diagnostics.Errors.*; import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.*; @@ -54,6 +66,62 @@ public class IdeErrorMessages { } }; + private static final Renderer>> NONE_APPLICABLE_CALLS = + new Renderer>>() { + @Nullable + private ValueParameterDescriptor findParameterByArgumentExpression( + ResolvedCall call, + JetValueArgument argument) { + for (Map.Entry entry : call.getValueArguments() + .entrySet()) { + for (ValueArgument va : entry.getValue().getArguments()) { + if (va == argument) { + return entry.getKey(); + } + } + } + return null; + } + + @NotNull + @Override + public String render(@NotNull Collection> calls) { + StringBuilder stringBuilder = new StringBuilder(""); + for (ResolvedCall call : calls) { + stringBuilder.append("
  • "); + stringBuilder.append(DescriptorRenderer.HTML.render(call.getResultingDescriptor())); + if (call instanceof ResolvedCallImpl) { + Collection diagnostics = ((ResolvedCallImpl)call).getTrace().getBindingContext().getDiagnostics(); + stringBuilder.append(" | "); + for (Diagnostic diagnostic : diagnostics) { + //stringBuilder.append(DefaultErrorMessages.RENDERER.render(diagnostic)); + PsiElement element = diagnostic.getPsiElement(); + JetValueArgumentList argumentList = PsiTreeUtil.getParentOfType(element, JetValueArgumentList.class, false); + assert argumentList != null; + JetValueArgument argument = PsiTreeUtil.getParentOfType(element, JetValueArgument.class, false); + if (diagnostic.getFactory() == Errors.TOO_MANY_ARGUMENTS) { + stringBuilder.append("LAST )"); + } else if (diagnostic.getFactory() == Errors.NO_VALUE_FOR_PARAMETER) { + ValueParameterDescriptor valueParameterDescriptor = + ((DiagnosticWithParameters1)diagnostic).getA(); + stringBuilder.append("ARGUMENT ").append(valueParameterDescriptor.getName()).append(" "); + } else { + if (argument != null) { + assert argument.getParent() == argumentList; // TODO check that this really can't happen + ValueParameterDescriptor parameter = findParameterByArgumentExpression(call, argument); + if (parameter != null) { + stringBuilder.append("ARGUMENT ").append(parameter.getName()).append(" "); + } + } + } + } + } + stringBuilder.append("
  • "); + } + return stringBuilder.toString(); + } + }; + static { MAP.put(TYPE_MISMATCH, "Type mismatch.
    Required:{0}
    Found:{1}
    ", RENDER_TYPE, RENDER_TYPE); @@ -103,7 +171,8 @@ public class IdeErrorMessages { "Found:{2}", TO_STRING, RENDER_TYPE, RENDER_TYPE); MAP.put(OVERLOAD_RESOLUTION_AMBIGUITY, "Overload resolution ambiguity. All these functions match.
      {0}
    ", HTML_AMBIGUOUS_CALLS); - MAP.put(NONE_APPLICABLE, "None of the following functions can be called with the arguments supplied.
      {0}
    ", HTML_AMBIGUOUS_CALLS); + MAP.put(NONE_APPLICABLE, "None of the following functions can be called with the arguments supplied.
      {0}
    ", + NONE_APPLICABLE_CALLS); MAP.setImmutable(); } From eddc550139306137144e4762bb5d6418b9d002a3 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 20 Apr 2012 13:27:53 +0400 Subject: [PATCH 077/147] Implemented highlighting arguments which don't fit in tooltip. --- .../plugin/highlighter/IdeErrorMessages.java | 95 +++++++++++++------ 1 file changed, 64 insertions(+), 31 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index 66d97803a6a..dc3ce62f1c3 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -22,6 +22,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.descriptors.CallableDescriptor; import org.jetbrains.jet.lang.descriptors.CallableMemberDescriptor; +import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.descriptors.ValueParameterDescriptor; import org.jetbrains.jet.lang.diagnostics.Diagnostic; import org.jetbrains.jet.lang.diagnostics.DiagnosticWithParameters1; @@ -30,13 +31,15 @@ import org.jetbrains.jet.lang.diagnostics.rendering.*; import org.jetbrains.jet.lang.psi.JetValueArgument; import org.jetbrains.jet.lang.psi.JetValueArgumentList; import org.jetbrains.jet.lang.psi.ValueArgument; +import org.jetbrains.jet.lang.resolve.DescriptorUtils; +import org.jetbrains.jet.lang.resolve.FqName; +import org.jetbrains.jet.lang.resolve.FqNameUnsafe; import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; import org.jetbrains.jet.lang.resolve.calls.ResolvedCallImpl; import org.jetbrains.jet.lang.resolve.calls.ResolvedValueArgument; import org.jetbrains.jet.resolve.DescriptorRenderer; -import java.util.Collection; -import java.util.Map; +import java.util.*; import static org.jetbrains.jet.lang.diagnostics.Errors.*; import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.*; @@ -83,39 +86,69 @@ public class IdeErrorMessages { return null; } - @NotNull - @Override - public String render(@NotNull Collection> calls) { - StringBuilder stringBuilder = new StringBuilder(""); - for (ResolvedCall call : calls) { - stringBuilder.append("
  • "); - stringBuilder.append(DescriptorRenderer.HTML.render(call.getResultingDescriptor())); - if (call instanceof ResolvedCallImpl) { - Collection diagnostics = ((ResolvedCallImpl)call).getTrace().getBindingContext().getDiagnostics(); - stringBuilder.append(" | "); - for (Diagnostic diagnostic : diagnostics) { - //stringBuilder.append(DefaultErrorMessages.RENDERER.render(diagnostic)); - PsiElement element = diagnostic.getPsiElement(); - JetValueArgumentList argumentList = PsiTreeUtil.getParentOfType(element, JetValueArgumentList.class, false); - assert argumentList != null; - JetValueArgument argument = PsiTreeUtil.getParentOfType(element, JetValueArgument.class, false); - if (diagnostic.getFactory() == Errors.TOO_MANY_ARGUMENTS) { - stringBuilder.append("LAST )"); - } else if (diagnostic.getFactory() == Errors.NO_VALUE_FOR_PARAMETER) { - ValueParameterDescriptor valueParameterDescriptor = - ((DiagnosticWithParameters1)diagnostic).getA(); - stringBuilder.append("ARGUMENT ").append(valueParameterDescriptor.getName()).append(" "); - } else { - if (argument != null) { - assert argument.getParent() == argumentList; // TODO check that this really can't happen - ValueParameterDescriptor parameter = findParameterByArgumentExpression(call, argument); - if (parameter != null) { - stringBuilder.append("ARGUMENT ").append(parameter.getName()).append(" "); - } + private Set getParametersToHighlight(ResolvedCall call) { + Set parameters = new HashSet(); + if (call instanceof ResolvedCallImpl) { + Collection diagnostics = ((ResolvedCallImpl)call).getTrace().getBindingContext().getDiagnostics(); + for (Diagnostic diagnostic : diagnostics) { + //stringBuilder.append(DefaultErrorMessages.RENDERER.render(diagnostic)); + PsiElement element = diagnostic.getPsiElement(); + JetValueArgumentList argumentList = PsiTreeUtil.getParentOfType(element, JetValueArgumentList.class, false); + assert argumentList != null; + JetValueArgument argument = PsiTreeUtil.getParentOfType(element, JetValueArgument.class, false); + if (diagnostic.getFactory() == Errors.TOO_MANY_ARGUMENTS) { + parameters.add(null); + } else if (diagnostic.getFactory() == Errors.NO_VALUE_FOR_PARAMETER) { + ValueParameterDescriptor parameter = + ((DiagnosticWithParameters1)diagnostic).getA(); + parameters.add(parameter); + } else { + if (argument != null) { + assert argument.getParent() == argumentList; // TODO check that this really can't happen + ValueParameterDescriptor parameter = findParameterByArgumentExpression(call, argument); + if (parameter != null) { + parameters.add(parameter); } } } } + } + return parameters; + } + + @NotNull + @Override + public String render(@NotNull Collection> calls) { + String RED_TEMPLATE = "%s"; + + StringBuilder stringBuilder = new StringBuilder(""); + for (ResolvedCall call : calls) { + stringBuilder.append("
  • "); + CallableDescriptor funDescriptor = call.getResultingDescriptor(); + Set parametersToHighlight = getParametersToHighlight(call); + + stringBuilder.append(funDescriptor.getName()).append("("); + boolean first = true; + DescriptorRenderer htmlRend = DescriptorRenderer.HTML; + for (ValueParameterDescriptor parameter : funDescriptor.getValueParameters()) { + if (!first) { + stringBuilder.append(", "); + } + String paramType = htmlRend.renderType(parameter.getType()); + if (parametersToHighlight.contains(parameter)) { + paramType = String.format(RED_TEMPLATE, paramType); + } + stringBuilder.append(paramType); + + first = false; + } + stringBuilder.append(parametersToHighlight.contains(null) ? String.format(RED_TEMPLATE, ")") : ")"); + stringBuilder.append(" ").append(htmlRend.renderMessage("defined in")).append(" "); + DeclarationDescriptor containingDeclaration = funDescriptor.getContainingDeclaration(); + if (containingDeclaration != null) { + FqNameUnsafe fqName = DescriptorUtils.getFQName(containingDeclaration); + stringBuilder.append(FqName.ROOT.toUnsafe().equals(fqName) ? "root package" : fqName.getFqName()); + } stringBuilder.append("
  • "); } return stringBuilder.toString(); From 1f19c6a0f0eef7d51e5b0ac8e81b8d6bc6449bd9 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 20 Apr 2012 13:29:47 +0400 Subject: [PATCH 078/147] Extracted class NoneApplicableCallsRenderer. --- .../plugin/highlighter/IdeErrorMessages.java | 173 +++++++++--------- 1 file changed, 86 insertions(+), 87 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index dc3ce62f1c3..2cf93c7f94b 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -69,92 +69,6 @@ public class IdeErrorMessages { } }; - private static final Renderer>> NONE_APPLICABLE_CALLS = - new Renderer>>() { - @Nullable - private ValueParameterDescriptor findParameterByArgumentExpression( - ResolvedCall call, - JetValueArgument argument) { - for (Map.Entry entry : call.getValueArguments() - .entrySet()) { - for (ValueArgument va : entry.getValue().getArguments()) { - if (va == argument) { - return entry.getKey(); - } - } - } - return null; - } - - private Set getParametersToHighlight(ResolvedCall call) { - Set parameters = new HashSet(); - if (call instanceof ResolvedCallImpl) { - Collection diagnostics = ((ResolvedCallImpl)call).getTrace().getBindingContext().getDiagnostics(); - for (Diagnostic diagnostic : diagnostics) { - //stringBuilder.append(DefaultErrorMessages.RENDERER.render(diagnostic)); - PsiElement element = diagnostic.getPsiElement(); - JetValueArgumentList argumentList = PsiTreeUtil.getParentOfType(element, JetValueArgumentList.class, false); - assert argumentList != null; - JetValueArgument argument = PsiTreeUtil.getParentOfType(element, JetValueArgument.class, false); - if (diagnostic.getFactory() == Errors.TOO_MANY_ARGUMENTS) { - parameters.add(null); - } else if (diagnostic.getFactory() == Errors.NO_VALUE_FOR_PARAMETER) { - ValueParameterDescriptor parameter = - ((DiagnosticWithParameters1)diagnostic).getA(); - parameters.add(parameter); - } else { - if (argument != null) { - assert argument.getParent() == argumentList; // TODO check that this really can't happen - ValueParameterDescriptor parameter = findParameterByArgumentExpression(call, argument); - if (parameter != null) { - parameters.add(parameter); - } - } - } - } - } - return parameters; - } - - @NotNull - @Override - public String render(@NotNull Collection> calls) { - String RED_TEMPLATE = "%s"; - - StringBuilder stringBuilder = new StringBuilder(""); - for (ResolvedCall call : calls) { - stringBuilder.append("
  • "); - CallableDescriptor funDescriptor = call.getResultingDescriptor(); - Set parametersToHighlight = getParametersToHighlight(call); - - stringBuilder.append(funDescriptor.getName()).append("("); - boolean first = true; - DescriptorRenderer htmlRend = DescriptorRenderer.HTML; - for (ValueParameterDescriptor parameter : funDescriptor.getValueParameters()) { - if (!first) { - stringBuilder.append(", "); - } - String paramType = htmlRend.renderType(parameter.getType()); - if (parametersToHighlight.contains(parameter)) { - paramType = String.format(RED_TEMPLATE, paramType); - } - stringBuilder.append(paramType); - - first = false; - } - stringBuilder.append(parametersToHighlight.contains(null) ? String.format(RED_TEMPLATE, ")") : ")"); - stringBuilder.append(" ").append(htmlRend.renderMessage("defined in")).append(" "); - DeclarationDescriptor containingDeclaration = funDescriptor.getContainingDeclaration(); - if (containingDeclaration != null) { - FqNameUnsafe fqName = DescriptorUtils.getFQName(containingDeclaration); - stringBuilder.append(FqName.ROOT.toUnsafe().equals(fqName) ? "root package" : fqName.getFqName()); - } - stringBuilder.append("
  • "); - } - return stringBuilder.toString(); - } - }; - static { MAP.put(TYPE_MISMATCH, "Type mismatch.
    Required:{0}
    Found:{1}
    ", RENDER_TYPE, RENDER_TYPE); @@ -205,11 +119,96 @@ public class IdeErrorMessages { MAP.put(OVERLOAD_RESOLUTION_AMBIGUITY, "Overload resolution ambiguity. All these functions match.
      {0}
    ", HTML_AMBIGUOUS_CALLS); MAP.put(NONE_APPLICABLE, "None of the following functions can be called with the arguments supplied.
      {0}
    ", - NONE_APPLICABLE_CALLS); + new NoneApplicableCallsRenderer()); MAP.setImmutable(); } private IdeErrorMessages() { } + + private static class NoneApplicableCallsRenderer implements Renderer>> { + @Nullable + private static ValueParameterDescriptor findParameterByArgumentExpression( + ResolvedCall call, + JetValueArgument argument) { + for (Map.Entry entry : call.getValueArguments() + .entrySet()) { + for (ValueArgument va : entry.getValue().getArguments()) { + if (va == argument) { + return entry.getKey(); + } + } + } + return null; + } + + private static Set getParametersToHighlight(ResolvedCall call) { + Set parameters = new HashSet(); + if (call instanceof ResolvedCallImpl) { + Collection diagnostics = ((ResolvedCallImpl)call).getTrace().getBindingContext().getDiagnostics(); + for (Diagnostic diagnostic : diagnostics) { + //stringBuilder.append(DefaultErrorMessages.RENDERER.render(diagnostic)); + PsiElement element = diagnostic.getPsiElement(); + JetValueArgumentList argumentList = PsiTreeUtil.getParentOfType(element, JetValueArgumentList.class, false); + assert argumentList != null; + JetValueArgument argument = PsiTreeUtil.getParentOfType(element, JetValueArgument.class, false); + if (diagnostic.getFactory() == Errors.TOO_MANY_ARGUMENTS) { + parameters.add(null); + } else if (diagnostic.getFactory() == Errors.NO_VALUE_FOR_PARAMETER) { + ValueParameterDescriptor parameter = + ((DiagnosticWithParameters1)diagnostic).getA(); + parameters.add(parameter); + } else { + if (argument != null) { + assert argument.getParent() == argumentList; // TODO check that this really can't happen + ValueParameterDescriptor parameter = findParameterByArgumentExpression(call, argument); + if (parameter != null) { + parameters.add(parameter); + } + } + } + } + } + return parameters; + } + + @NotNull + @Override + public String render(@NotNull Collection> calls) { + String RED_TEMPLATE = "%s"; + + StringBuilder stringBuilder = new StringBuilder(""); + for (ResolvedCall call : calls) { + stringBuilder.append("
  • "); + CallableDescriptor funDescriptor = call.getResultingDescriptor(); + Set parametersToHighlight = getParametersToHighlight(call); + + stringBuilder.append(funDescriptor.getName()).append("("); + boolean first = true; + DescriptorRenderer htmlRend = DescriptorRenderer.HTML; + for (ValueParameterDescriptor parameter : funDescriptor.getValueParameters()) { + if (!first) { + stringBuilder.append(", "); + } + String paramType = htmlRend.renderType(parameter.getType()); + if (parametersToHighlight.contains(parameter)) { + paramType = String.format(RED_TEMPLATE, paramType); + } + stringBuilder.append(paramType); + + first = false; + } + stringBuilder.append(parametersToHighlight.contains(null) ? String.format(RED_TEMPLATE, ")") : ")"); + stringBuilder.append(" ").append(htmlRend.renderMessage("defined in")).append(" "); + DeclarationDescriptor containingDeclaration = funDescriptor.getContainingDeclaration(); + if (containingDeclaration != null) { + FqNameUnsafe fqName = DescriptorUtils.getFQName(containingDeclaration); + stringBuilder.append(FqName.ROOT.toUnsafe().equals(fqName) ? "root package" : fqName.getFqName()); + } + stringBuilder.append("
  • "); + } + return stringBuilder.toString(); + } + } } From 0f0330a4b4fc6f9aa8cb9b62967403417ea1c733 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 20 Apr 2012 18:54:26 +0400 Subject: [PATCH 079/147] Added rendering vararg keywords and valid parameter type in this case. #KT-1840 fixed --- .../jetbrains/jet/resolve/DescriptorRenderer.java | 13 +++++++++---- compiler/testData/renderer/GlobalFunctions.kt | 4 ++-- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java index fe48060d1bd..92ba84da251 100644 --- a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java @@ -252,9 +252,6 @@ public class DescriptorRenderer implements Renderer { @Override public Void visitValueParameterDescriptor(ValueParameterDescriptor descriptor, StringBuilder builder) { builder.append(renderKeyword("value-parameter")).append(" "); - if (descriptor.getVarargElementType() != null) { - builder.append(renderKeyword("vararg")).append(" "); - } return super.visitValueParameterDescriptor(descriptor, builder); } @@ -264,12 +261,20 @@ public class DescriptorRenderer implements Renderer { } protected Void visitVariableDescriptor(VariableDescriptor descriptor, StringBuilder builder, boolean skipValVar) { + JetType type = descriptor.getType(); + if (descriptor instanceof ValueParameterDescriptor) { + JetType varargElementType = ((ValueParameterDescriptor)descriptor).getVarargElementType(); + if (varargElementType != null) { + builder.append(renderKeyword("vararg")).append(" "); + type = varargElementType; + } + } String typeString = renderPropertyPrefixAndComputeTypeString( builder, skipValVar ? null : descriptor.isVar(), Collections.emptyList(), ReceiverDescriptor.NO_RECEIVER, - descriptor.getType()); + type); renderName(descriptor, builder); builder.append(" : ").append(escape(typeString)); return super.visitVariableDescriptor(descriptor, builder); diff --git a/compiler/testData/renderer/GlobalFunctions.kt b/compiler/testData/renderer/GlobalFunctions.kt index a8a859da282..b2226aa8547 100644 --- a/compiler/testData/renderer/GlobalFunctions.kt +++ b/compiler/testData/renderer/GlobalFunctions.kt @@ -15,8 +15,8 @@ public fun withTypeParam(a : Array) : Int {} //package rendererTest defined in root package //public final fun pub() : Unit defined in rendererTest //internal final fun int() : jet.String defined in rendererTest -//internal final fun int2(ints : jet.IntArray) : jet.Int defined in rendererTest -//value-parameter vararg val ints : jet.IntArray defined in rendererTest.int2 +//internal final fun int2(vararg ints : jet.Int) : jet.Int defined in rendererTest +//value-parameter vararg val ints : jet.Int defined in rendererTest.int2 //private final fun prv(a : jet.String, b : jet.Int = ...) : jet.Int defined in rendererTest //value-parameter val a : jet.String defined in rendererTest.prv //value-parameter val b : jet.Int defined in rendererTest.prv From 466e6697270df36bc323a68f5a131268228e522b Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 20 Apr 2012 19:14:54 +0400 Subject: [PATCH 080/147] Added valid rendering varargs and parameters with default values in NONE_APPLICABLE diagnostic. --- .../plugin/highlighter/IdeErrorMessages.java | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index 2cf93c7f94b..4497d018375 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -37,9 +37,13 @@ import org.jetbrains.jet.lang.resolve.FqNameUnsafe; import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; import org.jetbrains.jet.lang.resolve.calls.ResolvedCallImpl; import org.jetbrains.jet.lang.resolve.calls.ResolvedValueArgument; +import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.resolve.DescriptorRenderer; -import java.util.*; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; import static org.jetbrains.jet.lang.diagnostics.Errors.*; import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.*; @@ -191,11 +195,19 @@ public class IdeErrorMessages { if (!first) { stringBuilder.append(", "); } - String paramType = htmlRend.renderType(parameter.getType()); - if (parametersToHighlight.contains(parameter)) { - paramType = String.format(RED_TEMPLATE, paramType); + JetType type = parameter.getType(); + JetType varargElementType = parameter.getVarargElementType(); + if (varargElementType != null) { + type = varargElementType; } - stringBuilder.append(paramType); + String paramString = (varargElementType != null ? "vararg " : "") + htmlRend.renderType(type); + if (parameter.hasDefaultValue()) { + paramString += " = ..."; + } + if (parametersToHighlight.contains(parameter)) { + paramString = String.format(RED_TEMPLATE, paramString); + } + stringBuilder.append(paramString); first = false; } From e4eb48e61ad413b292eac34396f0bad73e65dd02 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 20 Apr 2012 20:43:18 +0400 Subject: [PATCH 081/147] Got rid of saving argument list in NONE_APPLICABLE diagnostic. --- .../jet/plugin/highlighter/IdeErrorMessages.java | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java index 4497d018375..ea0c7300bdb 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/IdeErrorMessages.java @@ -29,7 +29,6 @@ import org.jetbrains.jet.lang.diagnostics.DiagnosticWithParameters1; import org.jetbrains.jet.lang.diagnostics.Errors; import org.jetbrains.jet.lang.diagnostics.rendering.*; import org.jetbrains.jet.lang.psi.JetValueArgument; -import org.jetbrains.jet.lang.psi.JetValueArgumentList; import org.jetbrains.jet.lang.psi.ValueArgument; import org.jetbrains.jet.lang.resolve.DescriptorUtils; import org.jetbrains.jet.lang.resolve.FqName; @@ -136,8 +135,7 @@ public class IdeErrorMessages { private static ValueParameterDescriptor findParameterByArgumentExpression( ResolvedCall call, JetValueArgument argument) { - for (Map.Entry entry : call.getValueArguments() - .entrySet()) { + for (Map.Entry entry : call.getValueArguments().entrySet()) { for (ValueArgument va : entry.getValue().getArguments()) { if (va == argument) { return entry.getKey(); @@ -152,11 +150,6 @@ public class IdeErrorMessages { if (call instanceof ResolvedCallImpl) { Collection diagnostics = ((ResolvedCallImpl)call).getTrace().getBindingContext().getDiagnostics(); for (Diagnostic diagnostic : diagnostics) { - //stringBuilder.append(DefaultErrorMessages.RENDERER.render(diagnostic)); - PsiElement element = diagnostic.getPsiElement(); - JetValueArgumentList argumentList = PsiTreeUtil.getParentOfType(element, JetValueArgumentList.class, false); - assert argumentList != null; - JetValueArgument argument = PsiTreeUtil.getParentOfType(element, JetValueArgument.class, false); if (diagnostic.getFactory() == Errors.TOO_MANY_ARGUMENTS) { parameters.add(null); } else if (diagnostic.getFactory() == Errors.NO_VALUE_FOR_PARAMETER) { @@ -164,8 +157,8 @@ public class IdeErrorMessages { ((DiagnosticWithParameters1)diagnostic).getA(); parameters.add(parameter); } else { + JetValueArgument argument = PsiTreeUtil.getParentOfType(diagnostic.getPsiElement(), JetValueArgument.class, false); if (argument != null) { - assert argument.getParent() == argumentList; // TODO check that this really can't happen ValueParameterDescriptor parameter = findParameterByArgumentExpression(call, argument); if (parameter != null) { parameters.add(parameter); From 289d20229ab4d5e384f59fcd98fe0f264dc2b986 Mon Sep 17 00:00:00 2001 From: Daniel Penkin Date: Fri, 13 Apr 2012 21:21:17 +0400 Subject: [PATCH 082/147] Added String.split(Char) --- libraries/stdlib/src/kotlin/Strings.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libraries/stdlib/src/kotlin/Strings.kt b/libraries/stdlib/src/kotlin/Strings.kt index 81945388444..8afc56cb5fc 100644 --- a/libraries/stdlib/src/kotlin/Strings.kt +++ b/libraries/stdlib/src/kotlin/Strings.kt @@ -60,6 +60,8 @@ public inline fun String.format(format : String, vararg args : Any?) : String = public inline fun String.split(regex : String) : Array = (this as java.lang.String).split(regex) as Array +public inline fun String.split(ch : Char) : Array = (this as java.lang.String).split(java.util.regex.Pattern.quote(ch.toString())) as Array + public inline fun String.substring(beginIndex : Int) : String = (this as java.lang.String).substring(beginIndex).sure() public inline fun String.substring(beginIndex : Int, endIndex : Int) : String = (this as java.lang.String).substring(beginIndex, endIndex).sure() From 1348497188ad686be95cba21e4b5df6f779e1900 Mon Sep 17 00:00:00 2001 From: Daniel Penkin Date: Fri, 13 Apr 2012 21:29:30 +0400 Subject: [PATCH 083/147] Added test for String.split(Char) --- libraries/stdlib/test/StringTest.kt | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/libraries/stdlib/test/StringTest.kt b/libraries/stdlib/test/StringTest.kt index 157a61a2851..2a3923c7673 100644 --- a/libraries/stdlib/test/StringTest.kt +++ b/libraries/stdlib/test/StringTest.kt @@ -52,4 +52,18 @@ class StringTest { assertEquals(3, whitespaceCount) } + test fun testSplitByChar() { + val s = "ab\n[|^$&\\]^cd" + var list = s.split('b'); + assertEquals(2, list.size) + assertEquals("a", list[0]) + assertEquals("\n[|^$&\\]^cd", list[1]) + list = s.split('^') + assertEquals(3, list.size) + assertEquals("cd", list[2]) + list = s.split('.') + assertEquals(1, list.size) + assertEquals(s, list[0]) + } + } From 54368014872d4d39ab1a20643a31a47279175167 Mon Sep 17 00:00:00 2001 From: Daniel Penkin Date: Fri, 13 Apr 2012 22:01:16 +0400 Subject: [PATCH 084/147] Added startsWith(Char) and endsWith(Char) for String --- libraries/stdlib/src/kotlin/Strings.kt | 4 ++++ libraries/stdlib/test/StringTest.kt | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/libraries/stdlib/src/kotlin/Strings.kt b/libraries/stdlib/src/kotlin/Strings.kt index 8afc56cb5fc..cf42a95fd64 100644 --- a/libraries/stdlib/src/kotlin/Strings.kt +++ b/libraries/stdlib/src/kotlin/Strings.kt @@ -70,10 +70,14 @@ public inline fun String.startsWith(prefix: String) : Boolean = (this as java.la public inline fun String.startsWith(prefix: String, toffset: Int) : Boolean = (this as java.lang.String).startsWith(prefix, toffset) +public inline fun String.startsWith(ch: Char) : Boolean = (this as java.lang.String).startsWith(ch.toString()) + public inline fun String.contains(seq: CharSequence) : Boolean = (this as java.lang.String).contains(seq) public inline fun String.endsWith(suffix: String) : Boolean = (this as java.lang.String).endsWith(suffix) +public inline fun String.endsWith(ch: Char) : Boolean = (this as java.lang.String).endsWith(ch.toString()) + inline val String.size : Int get() = length() diff --git a/libraries/stdlib/test/StringTest.kt b/libraries/stdlib/test/StringTest.kt index 2a3923c7673..34bd43da51a 100644 --- a/libraries/stdlib/test/StringTest.kt +++ b/libraries/stdlib/test/StringTest.kt @@ -66,4 +66,16 @@ class StringTest { assertEquals(s, list[0]) } + fun testStartsWithChar() { + assertTrue("abcd".startsWith('a')) + assertFalse("abcd".startsWith('b')) + assertFalse("".startsWith('a')) + } + + fun testEndsWithChar() { + assertTrue("abcd".endsWith('d')) + assertFalse("abcd".endsWith('b')) + assertFalse("".endsWith('a')) + } + } From ebf261e92d779f93eacdeb99c1b91cea26e67b4e Mon Sep 17 00:00:00 2001 From: Daniel Penkin Date: Fri, 20 Apr 2012 21:18:43 +0400 Subject: [PATCH 085/147] Added test annotations --- libraries/stdlib/test/StringTest.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/stdlib/test/StringTest.kt b/libraries/stdlib/test/StringTest.kt index 34bd43da51a..f2db543a24c 100644 --- a/libraries/stdlib/test/StringTest.kt +++ b/libraries/stdlib/test/StringTest.kt @@ -66,13 +66,13 @@ class StringTest { assertEquals(s, list[0]) } - fun testStartsWithChar() { + test fun testStartsWithChar() { assertTrue("abcd".startsWith('a')) assertFalse("abcd".startsWith('b')) assertFalse("".startsWith('a')) } - fun testEndsWithChar() { + test fun testEndsWithChar() { assertTrue("abcd".endsWith('d')) assertFalse("abcd".endsWith('b')) assertFalse("".endsWith('a')) From 092a572143830cf69ad75a1ee0fea2c4b3ecbb8c Mon Sep 17 00:00:00 2001 From: Stepan Koltsov Date: Fri, 20 Apr 2012 21:33:17 +0400 Subject: [PATCH 086/147] do not compile java part of runtime it must be already compiled by Idea --- .../codegen/forTestCompile/ForTestCompileRuntime.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileRuntime.java b/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileRuntime.java index b78a720c22a..34915e32d35 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileRuntime.java +++ b/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileRuntime.java @@ -90,7 +90,15 @@ public class ForTestCompileRuntime { } private static void compileJavaPartOfBuiltins(File destdir) throws IOException { - JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); + if (true) { + FileUtil.copyDir(new File("out/production/runtime"), destdir); + } + else { + doCompileJavaPartOfBuiltins(destdir); + } + } + + private static void doCompileJavaPartOfBuiltins(File destdir) throws IOException {JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ENGLISH, Charset.forName("utf-8")); try { From 994e6fe009d6f0df33a9c8a70f94305f81bd49d3 Mon Sep 17 00:00:00 2001 From: Stepan Koltsov Date: Fri, 20 Apr 2012 21:33:17 +0400 Subject: [PATCH 087/147] di: store everything in fields needed to implement @PreDestroy --- .../jet/di/InjectorForJetTypeMapper.java | 15 ++++- .../jet/di/InjectorForJvmCodegen.java | 15 ++++- .../di/InjectorForJavaSemanticServices.java | 17 ++++-- .../di/InjectorForTopDownAnalyzerForJvm.java | 60 +++++++++++++------ .../jetbrains/jet/di/InjectorForMacros.java | 18 ++++-- .../di/InjectorForTopDownAnalyzerBasic.java | 45 ++++++++++---- .../jetbrains/jet/di/InjectorForTests.java | 9 ++- .../jet/di/DependencyInjectorGenerator.java | 12 ++-- .../di/InjectorForTopDownAnalyzerForJs.java | 45 ++++++++++---- 9 files changed, 167 insertions(+), 69 deletions(-) diff --git a/compiler/backend/src/org/jetbrains/jet/di/InjectorForJetTypeMapper.java b/compiler/backend/src/org/jetbrains/jet/di/InjectorForJetTypeMapper.java index 30a4db600be..91b6fb30cd6 100644 --- a/compiler/backend/src/org/jetbrains/jet/di/InjectorForJetTypeMapper.java +++ b/compiler/backend/src/org/jetbrains/jet/di/InjectorForJetTypeMapper.java @@ -34,17 +34,26 @@ import org.jetbrains.annotations.NotNull; /* This file is generated by org.jetbrains.jet.di.AllInjectorsGenerator. DO NOT EDIT! */ public class InjectorForJetTypeMapper { + private final JetStandardLibrary jetStandardLibrary; + private final BindingContext bindingContext; + private final List listOfJetFile; private JetTypeMapper jetTypeMapper; + private CompilerSpecialMode compilerSpecialMode; + private ClassBuilderMode classBuilderMode; + private ClosureAnnotator closureAnnotator; public InjectorForJetTypeMapper( @NotNull JetStandardLibrary jetStandardLibrary, @NotNull BindingContext bindingContext, @NotNull List listOfJetFile ) { + this.jetStandardLibrary = jetStandardLibrary; + this.bindingContext = bindingContext; + this.listOfJetFile = listOfJetFile; this.jetTypeMapper = new JetTypeMapper(); - CompilerSpecialMode compilerSpecialMode = CompilerSpecialMode.REGULAR; - ClassBuilderMode classBuilderMode = ClassBuilderMode.FULL; - ClosureAnnotator closureAnnotator = new ClosureAnnotator(); + this.compilerSpecialMode = CompilerSpecialMode.REGULAR; + this.classBuilderMode = ClassBuilderMode.FULL; + this.closureAnnotator = new ClosureAnnotator(); this.jetTypeMapper.setBindingContext(bindingContext); this.jetTypeMapper.setClassBuilderMode(classBuilderMode); diff --git a/compiler/backend/src/org/jetbrains/jet/di/InjectorForJvmCodegen.java b/compiler/backend/src/org/jetbrains/jet/di/InjectorForJvmCodegen.java index e54bef57e52..66f37743666 100644 --- a/compiler/backend/src/org/jetbrains/jet/di/InjectorForJvmCodegen.java +++ b/compiler/backend/src/org/jetbrains/jet/di/InjectorForJvmCodegen.java @@ -45,10 +45,17 @@ import org.jetbrains.annotations.NotNull; public class InjectorForJvmCodegen { private final JetStandardLibrary jetStandardLibrary; + private final BindingContext bindingContext; + private final List listOfJetFile; + private final Project project; + private final CompilerSpecialMode compilerSpecialMode; + private final ClassBuilderMode classBuilderMode; private final GenerationState generationState; + private final ClassBuilderFactory classBuilderFactory; private JetTypeMapper jetTypeMapper; private IntrinsicMethods intrinsics; private ClassFileFactory classFileFactory; + private ClosureAnnotator closureAnnotator; public InjectorForJvmCodegen( @NotNull JetStandardLibrary jetStandardLibrary, @@ -61,11 +68,17 @@ public class InjectorForJvmCodegen { @NotNull ClassBuilderFactory classBuilderFactory ) { this.jetStandardLibrary = jetStandardLibrary; + this.bindingContext = bindingContext; + this.listOfJetFile = listOfJetFile; + this.project = project; + this.compilerSpecialMode = compilerSpecialMode; + this.classBuilderMode = classBuilderMode; this.generationState = generationState; + this.classBuilderFactory = classBuilderFactory; this.jetTypeMapper = new JetTypeMapper(); this.intrinsics = new IntrinsicMethods(); this.classFileFactory = new ClassFileFactory(); - ClosureAnnotator closureAnnotator = new ClosureAnnotator(); + this.closureAnnotator = new ClosureAnnotator(); this.jetTypeMapper.setBindingContext(bindingContext); this.jetTypeMapper.setClassBuilderMode(classBuilderMode); diff --git a/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForJavaSemanticServices.java b/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForJavaSemanticServices.java index 7ff65b75d00..75416a327df 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForJavaSemanticServices.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForJavaSemanticServices.java @@ -38,8 +38,14 @@ public class InjectorForJavaSemanticServices { private JavaSemanticServices javaSemanticServices; private JavaDescriptorResolver javaDescriptorResolver; private BindingTrace bindingTrace; + private JavaBridgeConfiguration javaBridgeConfiguration; private PsiClassFinderForJvm psiClassFinderForJvm; + private ModuleDescriptor moduleDescriptor; + private final CompilerDependencies compilerDependencies; + private CompilerSpecialMode compilerSpecialMode; private final Project project; + private JavaTypeTransformer javaTypeTransformer; + private NamespaceFactoryImpl namespaceFactoryImpl; public InjectorForJavaSemanticServices( @NotNull CompilerDependencies compilerDependencies, @@ -48,13 +54,14 @@ public class InjectorForJavaSemanticServices { this.javaSemanticServices = new JavaSemanticServices(); this.javaDescriptorResolver = new JavaDescriptorResolver(); this.bindingTrace = new org.jetbrains.jet.lang.resolve.BindingTraceContext(); - JavaBridgeConfiguration javaBridgeConfiguration = new JavaBridgeConfiguration(); + this.javaBridgeConfiguration = new JavaBridgeConfiguration(); this.psiClassFinderForJvm = new PsiClassFinderForJvm(); - ModuleDescriptor moduleDescriptor = new org.jetbrains.jet.lang.descriptors.ModuleDescriptor(""); - CompilerSpecialMode compilerSpecialMode = compilerDependencies.getCompilerSpecialMode(); + this.moduleDescriptor = new org.jetbrains.jet.lang.descriptors.ModuleDescriptor(""); + this.compilerDependencies = compilerDependencies; + this.compilerSpecialMode = compilerDependencies.getCompilerSpecialMode(); this.project = project; - JavaTypeTransformer javaTypeTransformer = new JavaTypeTransformer(); - NamespaceFactoryImpl namespaceFactoryImpl = new NamespaceFactoryImpl(); + this.javaTypeTransformer = new JavaTypeTransformer(); + this.namespaceFactoryImpl = new NamespaceFactoryImpl(); this.javaSemanticServices.setDescriptorResolver(javaDescriptorResolver); this.javaSemanticServices.setPsiClassFinder(psiClassFinderForJvm); diff --git a/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJvm.java b/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJvm.java index f90be7eefc1..905f3536f98 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJvm.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJvm.java @@ -68,7 +68,28 @@ public class InjectorForTopDownAnalyzerForJvm { private final Project project; private final TopDownAnalysisParameters topDownAnalysisParameters; private final ObservableBindingTrace observableBindingTrace; + private final ModuleDescriptor moduleDescriptor; + private final JetControlFlowDataTraceFactory jetControlFlowDataTraceFactory; + private final CompilerDependencies compilerDependencies; + private CompilerSpecialMode compilerSpecialMode; private JavaBridgeConfiguration javaBridgeConfiguration; + private PsiClassFinderForJvm psiClassFinderForJvm; + private DeclarationResolver declarationResolver; + private AnnotationResolver annotationResolver; + private CallResolver callResolver; + private ExpressionTypingServices expressionTypingServices; + private TypeResolver typeResolver; + private QualifiedExpressionResolver qualifiedExpressionResolver; + private OverloadingConflictResolver overloadingConflictResolver; + private ImportsResolver importsResolver; + private DelegationResolver delegationResolver; + private NamespaceFactoryImpl namespaceFactoryImpl; + private OverloadResolver overloadResolver; + private OverrideResolver overrideResolver; + private TypeHierarchyResolver typeHierarchyResolver; + private JavaSemanticServices javaSemanticServices; + private JavaDescriptorResolver javaDescriptorResolver; + private JavaTypeTransformer javaTypeTransformer; public InjectorForTopDownAnalyzerForJvm( @NotNull Project project, @@ -87,25 +108,28 @@ public class InjectorForTopDownAnalyzerForJvm { this.project = project; this.topDownAnalysisParameters = topDownAnalysisParameters; this.observableBindingTrace = observableBindingTrace; - CompilerSpecialMode compilerSpecialMode = compilerDependencies.getCompilerSpecialMode(); + this.moduleDescriptor = moduleDescriptor; + this.jetControlFlowDataTraceFactory = jetControlFlowDataTraceFactory; + this.compilerDependencies = compilerDependencies; + this.compilerSpecialMode = compilerDependencies.getCompilerSpecialMode(); this.javaBridgeConfiguration = new JavaBridgeConfiguration(); - PsiClassFinderForJvm psiClassFinderForJvm = new PsiClassFinderForJvm(); - DeclarationResolver declarationResolver = new DeclarationResolver(); - AnnotationResolver annotationResolver = new AnnotationResolver(); - CallResolver callResolver = new CallResolver(); - ExpressionTypingServices expressionTypingServices = new ExpressionTypingServices(); - TypeResolver typeResolver = new TypeResolver(); - QualifiedExpressionResolver qualifiedExpressionResolver = new QualifiedExpressionResolver(); - OverloadingConflictResolver overloadingConflictResolver = new OverloadingConflictResolver(); - ImportsResolver importsResolver = new ImportsResolver(); - DelegationResolver delegationResolver = new DelegationResolver(); - NamespaceFactoryImpl namespaceFactoryImpl = new NamespaceFactoryImpl(); - OverloadResolver overloadResolver = new OverloadResolver(); - OverrideResolver overrideResolver = new OverrideResolver(); - TypeHierarchyResolver typeHierarchyResolver = new TypeHierarchyResolver(); - JavaSemanticServices javaSemanticServices = new JavaSemanticServices(); - JavaDescriptorResolver javaDescriptorResolver = new JavaDescriptorResolver(); - JavaTypeTransformer javaTypeTransformer = new JavaTypeTransformer(); + this.psiClassFinderForJvm = new PsiClassFinderForJvm(); + this.declarationResolver = new DeclarationResolver(); + this.annotationResolver = new AnnotationResolver(); + this.callResolver = new CallResolver(); + this.expressionTypingServices = new ExpressionTypingServices(); + this.typeResolver = new TypeResolver(); + this.qualifiedExpressionResolver = new QualifiedExpressionResolver(); + this.overloadingConflictResolver = new OverloadingConflictResolver(); + this.importsResolver = new ImportsResolver(); + this.delegationResolver = new DelegationResolver(); + this.namespaceFactoryImpl = new NamespaceFactoryImpl(); + this.overloadResolver = new OverloadResolver(); + this.overrideResolver = new OverrideResolver(); + this.typeHierarchyResolver = new TypeHierarchyResolver(); + this.javaSemanticServices = new JavaSemanticServices(); + this.javaDescriptorResolver = new JavaDescriptorResolver(); + this.javaTypeTransformer = new JavaTypeTransformer(); this.topDownAnalyzer.setBodyResolver(bodyResolver); this.topDownAnalyzer.setContext(topDownAnalysisContext); diff --git a/compiler/frontend/src/org/jetbrains/jet/di/InjectorForMacros.java b/compiler/frontend/src/org/jetbrains/jet/di/InjectorForMacros.java index ca570d75b93..2b9af7f3106 100644 --- a/compiler/frontend/src/org/jetbrains/jet/di/InjectorForMacros.java +++ b/compiler/frontend/src/org/jetbrains/jet/di/InjectorForMacros.java @@ -33,18 +33,24 @@ public class InjectorForMacros { private ExpressionTypingServices expressionTypingServices; private final Project project; + private CallResolver callResolver; + private DescriptorResolver descriptorResolver; + private AnnotationResolver annotationResolver; + private TypeResolver typeResolver; + private QualifiedExpressionResolver qualifiedExpressionResolver; + private OverloadingConflictResolver overloadingConflictResolver; public InjectorForMacros( @NotNull Project project ) { this.expressionTypingServices = new ExpressionTypingServices(); this.project = project; - CallResolver callResolver = new CallResolver(); - DescriptorResolver descriptorResolver = new DescriptorResolver(); - AnnotationResolver annotationResolver = new AnnotationResolver(); - TypeResolver typeResolver = new TypeResolver(); - QualifiedExpressionResolver qualifiedExpressionResolver = new QualifiedExpressionResolver(); - OverloadingConflictResolver overloadingConflictResolver = new OverloadingConflictResolver(); + this.callResolver = new CallResolver(); + this.descriptorResolver = new DescriptorResolver(); + this.annotationResolver = new AnnotationResolver(); + this.typeResolver = new TypeResolver(); + this.qualifiedExpressionResolver = new QualifiedExpressionResolver(); + this.overloadingConflictResolver = new OverloadingConflictResolver(); this.expressionTypingServices.setCallResolver(callResolver); this.expressionTypingServices.setDescriptorResolver(descriptorResolver); diff --git a/compiler/frontend/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerBasic.java b/compiler/frontend/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerBasic.java index 7c8405cfa5a..68ebbd9692b 100644 --- a/compiler/frontend/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerBasic.java +++ b/compiler/frontend/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerBasic.java @@ -62,6 +62,22 @@ public class InjectorForTopDownAnalyzerBasic { private final Project project; private final TopDownAnalysisParameters topDownAnalysisParameters; private final ObservableBindingTrace observableBindingTrace; + private final ModuleDescriptor moduleDescriptor; + private final JetControlFlowDataTraceFactory jetControlFlowDataTraceFactory; + private final ModuleConfiguration moduleConfiguration; + private DeclarationResolver declarationResolver; + private AnnotationResolver annotationResolver; + private CallResolver callResolver; + private ExpressionTypingServices expressionTypingServices; + private TypeResolver typeResolver; + private QualifiedExpressionResolver qualifiedExpressionResolver; + private OverloadingConflictResolver overloadingConflictResolver; + private ImportsResolver importsResolver; + private DelegationResolver delegationResolver; + private NamespaceFactoryImpl namespaceFactoryImpl; + private OverloadResolver overloadResolver; + private OverrideResolver overrideResolver; + private TypeHierarchyResolver typeHierarchyResolver; public InjectorForTopDownAnalyzerBasic( @NotNull Project project, @@ -80,19 +96,22 @@ public class InjectorForTopDownAnalyzerBasic { this.project = project; this.topDownAnalysisParameters = topDownAnalysisParameters; this.observableBindingTrace = observableBindingTrace; - DeclarationResolver declarationResolver = new DeclarationResolver(); - AnnotationResolver annotationResolver = new AnnotationResolver(); - CallResolver callResolver = new CallResolver(); - ExpressionTypingServices expressionTypingServices = new ExpressionTypingServices(); - TypeResolver typeResolver = new TypeResolver(); - QualifiedExpressionResolver qualifiedExpressionResolver = new QualifiedExpressionResolver(); - OverloadingConflictResolver overloadingConflictResolver = new OverloadingConflictResolver(); - ImportsResolver importsResolver = new ImportsResolver(); - DelegationResolver delegationResolver = new DelegationResolver(); - NamespaceFactoryImpl namespaceFactoryImpl = new NamespaceFactoryImpl(); - OverloadResolver overloadResolver = new OverloadResolver(); - OverrideResolver overrideResolver = new OverrideResolver(); - TypeHierarchyResolver typeHierarchyResolver = new TypeHierarchyResolver(); + this.moduleDescriptor = moduleDescriptor; + this.jetControlFlowDataTraceFactory = jetControlFlowDataTraceFactory; + this.moduleConfiguration = moduleConfiguration; + this.declarationResolver = new DeclarationResolver(); + this.annotationResolver = new AnnotationResolver(); + this.callResolver = new CallResolver(); + this.expressionTypingServices = new ExpressionTypingServices(); + this.typeResolver = new TypeResolver(); + this.qualifiedExpressionResolver = new QualifiedExpressionResolver(); + this.overloadingConflictResolver = new OverloadingConflictResolver(); + this.importsResolver = new ImportsResolver(); + this.delegationResolver = new DelegationResolver(); + this.namespaceFactoryImpl = new NamespaceFactoryImpl(); + this.overloadResolver = new OverloadResolver(); + this.overrideResolver = new OverrideResolver(); + this.typeHierarchyResolver = new TypeHierarchyResolver(); this.topDownAnalyzer.setBodyResolver(bodyResolver); this.topDownAnalyzer.setContext(topDownAnalysisContext); diff --git a/compiler/tests/org/jetbrains/jet/di/InjectorForTests.java b/compiler/tests/org/jetbrains/jet/di/InjectorForTests.java index 82aa49eedde..a8286a6658f 100644 --- a/compiler/tests/org/jetbrains/jet/di/InjectorForTests.java +++ b/compiler/tests/org/jetbrains/jet/di/InjectorForTests.java @@ -38,6 +38,9 @@ public class InjectorForTests { private CallResolver callResolver; private JetStandardLibrary jetStandardLibrary; private final Project project; + private AnnotationResolver annotationResolver; + private QualifiedExpressionResolver qualifiedExpressionResolver; + private OverloadingConflictResolver overloadingConflictResolver; public InjectorForTests( @NotNull Project project @@ -48,9 +51,9 @@ public class InjectorForTests { this.callResolver = new CallResolver(); this.jetStandardLibrary = JetStandardLibrary.getInstance(); this.project = project; - AnnotationResolver annotationResolver = new AnnotationResolver(); - QualifiedExpressionResolver qualifiedExpressionResolver = new QualifiedExpressionResolver(); - OverloadingConflictResolver overloadingConflictResolver = new OverloadingConflictResolver(); + this.annotationResolver = new AnnotationResolver(); + this.qualifiedExpressionResolver = new QualifiedExpressionResolver(); + this.overloadingConflictResolver = new OverloadingConflictResolver(); this.descriptorResolver.setAnnotationResolver(annotationResolver); this.descriptorResolver.setExpressionTypingServices(expressionTypingServices); diff --git a/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java b/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java index ddf120ff89c..f5c8412a1fa 100644 --- a/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java +++ b/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java @@ -233,10 +233,8 @@ public class DependencyInjectorGenerator { private void generateFields(PrintStream out) { for (Field field : fields) { - if (lazy || field.isPublic()) { - String _final = backsParameter.contains(field) ? "final " : ""; - out.println(" private " + _final + field.getType().getSimpleName() + " " + field.getName() + ";"); - } + String _final = backsParameter.contains(field) ? "final " : ""; + out.println(" private " + _final + field.getType().getSimpleName() + " " + field.getName() + ";"); } } @@ -272,10 +270,10 @@ public class DependencyInjectorGenerator { else { // Initialize fields for (Field field : fields) { - if (!backsParameter.contains(field) || field.isPublic()) { - String prefix = field.isPublic() ? "this." : field.getTypeName() + " "; + //if (!backsParameter.contains(field) || field.isPublic()) { + String prefix = "this."; out.println(indent + prefix + field.getName() + " = " + field.getInitialization() + ";"); - } + //} } out.println(); diff --git a/js/js.translator/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJs.java b/js/js.translator/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJs.java index 329d2c0b624..6fc0c64c61c 100644 --- a/js/js.translator/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJs.java +++ b/js/js.translator/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJs.java @@ -62,6 +62,22 @@ public class InjectorForTopDownAnalyzerForJs { private final Project project; private final TopDownAnalysisParameters topDownAnalysisParameters; private final ObservableBindingTrace observableBindingTrace; + private final ModuleDescriptor moduleDescriptor; + private final JetControlFlowDataTraceFactory jetControlFlowDataTraceFactory; + private final ModuleConfiguration moduleConfiguration; + private DeclarationResolver declarationResolver; + private AnnotationResolver annotationResolver; + private CallResolver callResolver; + private ExpressionTypingServices expressionTypingServices; + private TypeResolver typeResolver; + private QualifiedExpressionResolver qualifiedExpressionResolver; + private OverloadingConflictResolver overloadingConflictResolver; + private ImportsResolver importsResolver; + private DelegationResolver delegationResolver; + private NamespaceFactoryImpl namespaceFactoryImpl; + private OverloadResolver overloadResolver; + private OverrideResolver overrideResolver; + private TypeHierarchyResolver typeHierarchyResolver; public InjectorForTopDownAnalyzerForJs( @NotNull Project project, @@ -80,19 +96,22 @@ public class InjectorForTopDownAnalyzerForJs { this.project = project; this.topDownAnalysisParameters = topDownAnalysisParameters; this.observableBindingTrace = observableBindingTrace; - DeclarationResolver declarationResolver = new DeclarationResolver(); - AnnotationResolver annotationResolver = new AnnotationResolver(); - CallResolver callResolver = new CallResolver(); - ExpressionTypingServices expressionTypingServices = new ExpressionTypingServices(); - TypeResolver typeResolver = new TypeResolver(); - QualifiedExpressionResolver qualifiedExpressionResolver = new QualifiedExpressionResolver(); - OverloadingConflictResolver overloadingConflictResolver = new OverloadingConflictResolver(); - ImportsResolver importsResolver = new ImportsResolver(); - DelegationResolver delegationResolver = new DelegationResolver(); - NamespaceFactoryImpl namespaceFactoryImpl = new NamespaceFactoryImpl(); - OverloadResolver overloadResolver = new OverloadResolver(); - OverrideResolver overrideResolver = new OverrideResolver(); - TypeHierarchyResolver typeHierarchyResolver = new TypeHierarchyResolver(); + this.moduleDescriptor = moduleDescriptor; + this.jetControlFlowDataTraceFactory = jetControlFlowDataTraceFactory; + this.moduleConfiguration = moduleConfiguration; + this.declarationResolver = new DeclarationResolver(); + this.annotationResolver = new AnnotationResolver(); + this.callResolver = new CallResolver(); + this.expressionTypingServices = new ExpressionTypingServices(); + this.typeResolver = new TypeResolver(); + this.qualifiedExpressionResolver = new QualifiedExpressionResolver(); + this.overloadingConflictResolver = new OverloadingConflictResolver(); + this.importsResolver = new ImportsResolver(); + this.delegationResolver = new DelegationResolver(); + this.namespaceFactoryImpl = new NamespaceFactoryImpl(); + this.overloadResolver = new OverloadResolver(); + this.overrideResolver = new OverrideResolver(); + this.typeHierarchyResolver = new TypeHierarchyResolver(); this.topDownAnalyzer.setBodyResolver(bodyResolver); this.topDownAnalyzer.setContext(topDownAnalysisContext); From 3b0c9244c9e3fdb3d8d35c9cb3e68e2ee2453463 Mon Sep 17 00:00:00 2001 From: Stepan Koltsov Date: Fri, 20 Apr 2012 21:33:18 +0400 Subject: [PATCH 088/147] di: @PreDestroy I need in my private experiments --- .../jet/codegen/GenerationState.java | 4 +++ .../jet/di/InjectorForJetTypeMapper.java | 5 +++ .../jet/di/InjectorForJvmCodegen.java | 5 +++ .../compiler/KotlinToJVMBytecodeCompiler.java | 29 ++++++++++------- .../di/InjectorForJavaSemanticServices.java | 5 +++ .../di/InjectorForTopDownAnalyzerForJvm.java | 5 +++ .../resolve/java/AnalyzerFacadeForJVM.java | 8 +++-- .../jetbrains/jet/di/InjectorForMacros.java | 5 +++ .../di/InjectorForTopDownAnalyzerBasic.java | 5 +++ .../jetbrains/jet/di/InjectorForTests.java | 5 +++ .../jet/di/DependencyInjectorGenerator.java | 31 ++++++++++++++++++- .../di/InjectorForTopDownAnalyzerForJs.java | 5 +++ 12 files changed, 97 insertions(+), 15 deletions(-) diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java b/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java index 33bb005af93..b536dae92bf 100644 --- a/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java +++ b/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java @@ -170,4 +170,8 @@ public class GenerationState { return answer.toString(); } + + public void destroy() { + injector.destroy(); + } } diff --git a/compiler/backend/src/org/jetbrains/jet/di/InjectorForJetTypeMapper.java b/compiler/backend/src/org/jetbrains/jet/di/InjectorForJetTypeMapper.java index 91b6fb30cd6..0d0ec20975d 100644 --- a/compiler/backend/src/org/jetbrains/jet/di/InjectorForJetTypeMapper.java +++ b/compiler/backend/src/org/jetbrains/jet/di/InjectorForJetTypeMapper.java @@ -30,6 +30,7 @@ import org.jetbrains.jet.lang.resolve.BindingContext; import java.util.List; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.annotations.NotNull; +import javax.annotation.PreDestroy; /* This file is generated by org.jetbrains.jet.di.AllInjectorsGenerator. DO NOT EDIT! */ public class InjectorForJetTypeMapper { @@ -70,6 +71,10 @@ public class InjectorForJetTypeMapper { } + @PreDestroy + public void destroy() { + } + public JetTypeMapper getJetTypeMapper() { return this.jetTypeMapper; } diff --git a/compiler/backend/src/org/jetbrains/jet/di/InjectorForJvmCodegen.java b/compiler/backend/src/org/jetbrains/jet/di/InjectorForJvmCodegen.java index 66f37743666..b5987e16532 100644 --- a/compiler/backend/src/org/jetbrains/jet/di/InjectorForJvmCodegen.java +++ b/compiler/backend/src/org/jetbrains/jet/di/InjectorForJvmCodegen.java @@ -40,6 +40,7 @@ import org.jetbrains.jet.codegen.ClassBuilderMode; import org.jetbrains.jet.codegen.GenerationState; import org.jetbrains.jet.codegen.ClassBuilderFactory; import org.jetbrains.annotations.NotNull; +import javax.annotation.PreDestroy; /* This file is generated by org.jetbrains.jet.di.AllInjectorsGenerator. DO NOT EDIT! */ public class InjectorForJvmCodegen { @@ -103,6 +104,10 @@ public class InjectorForJvmCodegen { } + @PreDestroy + public void destroy() { + } + public JetStandardLibrary getJetStandardLibrary() { return this.jetStandardLibrary; } diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java b/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java index 7e6af64de21..6eb3fd6ef21 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java @@ -165,21 +165,26 @@ public class KotlinToJVMBytecodeCompiler { return false; } - ClassFileFactory factory = generationState.getFactory(); - if (jar != null) { - try { - CompileEnvironmentUtil.writeToJar(factory, new FileOutputStream(jar), mainClass, includeRuntime); - } catch (FileNotFoundException e) { - throw new CompileEnvironmentException("Invalid jar path " + jar, e); + try { + ClassFileFactory factory = generationState.getFactory(); + if (jar != null) { + try { + CompileEnvironmentUtil.writeToJar(factory, new FileOutputStream(jar), mainClass, includeRuntime); + } catch (FileNotFoundException e) { + throw new CompileEnvironmentException("Invalid jar path " + jar, e); + } } + else if (outputDir != null) { + CompileEnvironmentUtil.writeToOutputDirectory(factory, outputDir); + } + else { + throw new CompileEnvironmentException("Output directory or jar file is not specified - no files will be saved to the disk"); + } + return true; } - else if (outputDir != null) { - CompileEnvironmentUtil.writeToOutputDirectory(factory, outputDir); + finally { + generationState.destroy(); } - else { - throw new CompileEnvironmentException("Output directory or jar file is not specified - no files will be saved to the disk"); - } - return true; } public static boolean compileBunchOfSources( diff --git a/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForJavaSemanticServices.java b/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForJavaSemanticServices.java index 75416a327df..a3fe4e74de8 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForJavaSemanticServices.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForJavaSemanticServices.java @@ -31,6 +31,7 @@ import org.jetbrains.jet.lang.resolve.NamespaceFactoryImpl; import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; +import javax.annotation.PreDestroy; /* This file is generated by org.jetbrains.jet.di.AllInjectorsGenerator. DO NOT EDIT! */ public class InjectorForJavaSemanticServices { @@ -94,6 +95,10 @@ public class InjectorForJavaSemanticServices { } + @PreDestroy + public void destroy() { + } + public JavaSemanticServices getJavaSemanticServices() { return this.javaSemanticServices; } diff --git a/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJvm.java b/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJvm.java index 905f3536f98..69366baf299 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJvm.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJvm.java @@ -55,6 +55,7 @@ import org.jetbrains.jet.lang.descriptors.ModuleDescriptor; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; import org.jetbrains.annotations.NotNull; +import javax.annotation.PreDestroy; /* This file is generated by org.jetbrains.jet.di.AllInjectorsGenerator. DO NOT EDIT! */ public class InjectorForTopDownAnalyzerForJvm { @@ -241,6 +242,10 @@ public class InjectorForTopDownAnalyzerForJvm { } + @PreDestroy + public void destroy() { + } + public TopDownAnalyzer getTopDownAnalyzer() { return this.topDownAnalyzer; } diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java index 05fef231d78..97875e8ee8a 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java @@ -95,9 +95,13 @@ public enum AnalyzerFacadeForJVM implements AnalyzerFacade { compilerDependencies); - injector.getTopDownAnalyzer().analyzeFiles(files); + try { + injector.getTopDownAnalyzer().analyzeFiles(files); - return AnalyzeExhaust.success(bindingTraceContext.getBindingContext(), JetStandardLibrary.getInstance()); + return AnalyzeExhaust.success(bindingTraceContext.getBindingContext(), JetStandardLibrary.getInstance()); + } finally { + injector.destroy(); + } } public static AnalyzeExhaust shallowAnalyzeFiles(Collection files, diff --git a/compiler/frontend/src/org/jetbrains/jet/di/InjectorForMacros.java b/compiler/frontend/src/org/jetbrains/jet/di/InjectorForMacros.java index 2b9af7f3106..23020ab2793 100644 --- a/compiler/frontend/src/org/jetbrains/jet/di/InjectorForMacros.java +++ b/compiler/frontend/src/org/jetbrains/jet/di/InjectorForMacros.java @@ -27,6 +27,7 @@ import org.jetbrains.jet.lang.resolve.QualifiedExpressionResolver; import org.jetbrains.jet.lang.resolve.calls.OverloadingConflictResolver; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; +import javax.annotation.PreDestroy; /* This file is generated by org.jetbrains.jet.di.AllInjectorsGenerator. DO NOT EDIT! */ public class InjectorForMacros { @@ -75,6 +76,10 @@ public class InjectorForMacros { } + @PreDestroy + public void destroy() { + } + public ExpressionTypingServices getExpressionTypingServices() { return this.expressionTypingServices; } diff --git a/compiler/frontend/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerBasic.java b/compiler/frontend/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerBasic.java index 68ebbd9692b..569ef4f592c 100644 --- a/compiler/frontend/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerBasic.java +++ b/compiler/frontend/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerBasic.java @@ -49,6 +49,7 @@ import org.jetbrains.jet.lang.descriptors.ModuleDescriptor; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.ModuleConfiguration; import org.jetbrains.annotations.NotNull; +import javax.annotation.PreDestroy; /* This file is generated by org.jetbrains.jet.di.AllInjectorsGenerator. DO NOT EDIT! */ public class InjectorForTopDownAnalyzerBasic { @@ -198,6 +199,10 @@ public class InjectorForTopDownAnalyzerBasic { } + @PreDestroy + public void destroy() { + } + public TopDownAnalyzer getTopDownAnalyzer() { return this.topDownAnalyzer; } diff --git a/compiler/tests/org/jetbrains/jet/di/InjectorForTests.java b/compiler/tests/org/jetbrains/jet/di/InjectorForTests.java index a8286a6658f..165332e7d03 100644 --- a/compiler/tests/org/jetbrains/jet/di/InjectorForTests.java +++ b/compiler/tests/org/jetbrains/jet/di/InjectorForTests.java @@ -28,6 +28,7 @@ import org.jetbrains.jet.lang.resolve.QualifiedExpressionResolver; import org.jetbrains.jet.lang.resolve.calls.OverloadingConflictResolver; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; +import javax.annotation.PreDestroy; /* This file is generated by org.jetbrains.jet.di.AllInjectorsGenerator. DO NOT EDIT! */ public class InjectorForTests { @@ -78,6 +79,10 @@ public class InjectorForTests { } + @PreDestroy + public void destroy() { + } + public DescriptorResolver getDescriptorResolver() { return this.descriptorResolver; } diff --git a/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java b/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java index f5c8412a1fa..0faab5c25f8 100644 --- a/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java +++ b/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java @@ -27,10 +27,12 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; +import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; @@ -106,6 +108,8 @@ public class DependencyInjectorGenerator { out.println(); generateConstructor(injectorClassName, out); out.println(); + generateDestroy(injectorClassName, out); + out.println(); generateGetters(out); // Needed to fix double-checked locking // out.println(); @@ -212,6 +216,7 @@ public class DependencyInjectorGenerator { break; } } + generateImportDirective(out, PreDestroy.class, injectorPackageName); } private void generateImportDirectives(PrintStream out, DiType type, String injectorPackageName) { @@ -305,9 +310,17 @@ public class DependencyInjectorGenerator { } private static List getPostConstructMethods(Class clazz) { + return getInjectSpecialMethods(clazz, PostConstruct.class); + } + + private static List getPreDestroyMethods(Class clazz) { + return getInjectSpecialMethods(clazz, PreDestroy.class); + } + + private static List getInjectSpecialMethods(Class clazz, Class annotationClass) { List r = Lists.newArrayList(); for (Method method : clazz.getMethods()) { - if (method.getAnnotation(PostConstruct.class) != null) { + if (method.getAnnotation(annotationClass) != null) { if (method.getParameterTypes().length != 0) { throw new IllegalStateException("@PostConstruct method must have no arguments: " + method); } @@ -317,6 +330,22 @@ public class DependencyInjectorGenerator { return r; } + private void generateDestroy(@NotNull String injectorClassName, @NotNull PrintStream out) { + out.println(" @PreDestroy"); + out.println(" public void destroy() {"); + for (Field field : fields) { + // TODO: type of field may be different from type of object + List preDestroyMethods = getPreDestroyMethods(field.getType().getClazz()); + for (Method preDestroy : preDestroyMethods) { + out.println(" " + field.getName() + "." + preDestroy.getName() + "();"); + } + if (preDestroyMethods.size() > 0) { + out.println(); + } + } + out.println(" }"); + } + private void generateGetters(PrintStream out) { String indent0 = " "; String indent1 = indent0 + INDENT_STEP; diff --git a/js/js.translator/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJs.java b/js/js.translator/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJs.java index 6fc0c64c61c..2eae6436681 100644 --- a/js/js.translator/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJs.java +++ b/js/js.translator/src/org/jetbrains/jet/di/InjectorForTopDownAnalyzerForJs.java @@ -49,6 +49,7 @@ import org.jetbrains.jet.lang.descriptors.ModuleDescriptor; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.ModuleConfiguration; import org.jetbrains.annotations.NotNull; +import javax.annotation.PreDestroy; /* This file is generated by org.jetbrains.jet.di.AllInjectorsGenerator. DO NOT EDIT! */ public class InjectorForTopDownAnalyzerForJs { @@ -198,6 +199,10 @@ public class InjectorForTopDownAnalyzerForJs { } + @PreDestroy + public void destroy() { + } + public TopDownAnalyzer getTopDownAnalyzer() { return this.topDownAnalyzer; } From 7147998c5c596e828a4bd546bf30393cae7c391c Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 20 Apr 2012 22:02:28 +0400 Subject: [PATCH 089/147] Replaced "namespace header" with "package directive" in parser error. #KT-1799 fixed --- .../frontend/src/org/jetbrains/jet/lang/parsing/JetParsing.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/parsing/JetParsing.java b/compiler/frontend/src/org/jetbrains/jet/lang/parsing/JetParsing.java index b8570e16d4b..9d0da50c551 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/parsing/JetParsing.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/parsing/JetParsing.java @@ -286,7 +286,7 @@ public class JetParsing extends AbstractJetParsing { } if (declType == null) { - errorAndAdvance("Expecting namespace or top level declaration"); + errorAndAdvance("Expecting package directive or top level declaration"); decl.drop(); } else { From e298391645e18c3807fde368e2b0d3f2651f9798 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Fri, 20 Apr 2012 22:16:20 +0400 Subject: [PATCH 090/147] Fixed tests. #KT-1799 fixed --- compiler/testData/psi/FileStart_ERR.txt | 6 +++--- compiler/testData/psi/Imports_ERR.txt | 6 +++--- compiler/testData/psi/NamespaceBlockFirst.txt | 6 +++--- compiler/testData/psi/Properties_ERR.txt | 14 +++++++------- compiler/testData/psi/RootNamespace.txt | 6 +++--- .../psi/greatSyntacticShift/functionTypes.txt | 6 +++--- 6 files changed, 22 insertions(+), 22 deletions(-) diff --git a/compiler/testData/psi/FileStart_ERR.txt b/compiler/testData/psi/FileStart_ERR.txt index 5730db1fdf6..fe469cd014b 100644 --- a/compiler/testData/psi/FileStart_ERR.txt +++ b/compiler/testData/psi/FileStart_ERR.txt @@ -1,9 +1,9 @@ JetFile: FileStart_ERR.jet NAMESPACE_HEADER - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(DIV)('/') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(package)('package') PsiWhiteSpace(' ') MODIFIER_LIST @@ -31,5 +31,5 @@ JetFile: FileStart_ERR.jet USER_TYPE REFERENCE_EXPRESSION PsiElement(IDENTIFIER)('foo') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration \ No newline at end of file diff --git a/compiler/testData/psi/Imports_ERR.txt b/compiler/testData/psi/Imports_ERR.txt index 6f880181140..9406df03bb6 100644 --- a/compiler/testData/psi/Imports_ERR.txt +++ b/compiler/testData/psi/Imports_ERR.txt @@ -31,7 +31,7 @@ JetFile: Imports_ERR.jet REFERENCE_EXPRESSION PsiErrorElement:Expecting qualified name - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(MUL)('*') PsiWhiteSpace('\n') IMPORT_DIRECTIVE @@ -125,7 +125,7 @@ JetFile: Imports_ERR.jet PsiErrorElement:Expecting type name PsiElement(MUL)('*') PsiWhiteSpace(' ') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(as)('as') PsiWhiteSpace(' ') MODIFIER_LIST @@ -158,7 +158,7 @@ JetFile: Imports_ERR.jet PsiErrorElement:Expecting type name PsiElement(MUL)('*') PsiWhiteSpace(' ') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(as)('as') PsiWhiteSpace('\n\n') IMPORT_DIRECTIVE diff --git a/compiler/testData/psi/NamespaceBlockFirst.txt b/compiler/testData/psi/NamespaceBlockFirst.txt index c60803e634b..ee2e8d110aa 100644 --- a/compiler/testData/psi/NamespaceBlockFirst.txt +++ b/compiler/testData/psi/NamespaceBlockFirst.txt @@ -1,7 +1,7 @@ JetFile: NamespaceBlockFirst.jet NAMESPACE_HEADER - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(package)('package') PsiWhiteSpace(' ') MODIFIER_LIST @@ -12,7 +12,7 @@ JetFile: NamespaceBlockFirst.jet REFERENCE_EXPRESSION PsiElement(IDENTIFIER)('foobar') PsiWhiteSpace(' ') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(LBRACE)('{') PsiWhiteSpace('\n ') PROPERTY @@ -39,5 +39,5 @@ JetFile: NamespaceBlockFirst.jet REFERENCE_EXPRESSION PsiElement(IDENTIFIER)('a') PsiWhiteSpace('\n') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(RBRACE)('}') \ No newline at end of file diff --git a/compiler/testData/psi/Properties_ERR.txt b/compiler/testData/psi/Properties_ERR.txt index ac727cd3088..f15af5049e5 100644 --- a/compiler/testData/psi/Properties_ERR.txt +++ b/compiler/testData/psi/Properties_ERR.txt @@ -119,22 +119,22 @@ JetFile: Properties_ERR.jet MODIFIER_LIST PsiElement(public)('public') PsiWhiteSpace(' ') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(LPAR)('(') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(RPAR)(')') PsiWhiteSpace(' ') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(LBRACE)('{') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(RBRACE)('}') PsiWhiteSpace('\n ') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(LPAR)('(') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(RPAR)(')') PsiWhiteSpace(' ') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(EQ)('=') PsiWhiteSpace(' ') PROPERTY diff --git a/compiler/testData/psi/RootNamespace.txt b/compiler/testData/psi/RootNamespace.txt index 70d461713cc..71de1d19f32 100644 --- a/compiler/testData/psi/RootNamespace.txt +++ b/compiler/testData/psi/RootNamespace.txt @@ -16,7 +16,7 @@ JetFile: RootNamespace.jet PsiWhiteSpace('\n\n') TYPE_PARAMETER_LIST - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(package)('package') PsiWhiteSpace(' ') MODIFIER_LIST @@ -31,7 +31,7 @@ JetFile: RootNamespace.jet REFERENCE_EXPRESSION PsiElement(IDENTIFIER)('bar') PsiWhiteSpace(' ') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(LBRACE)('{') PsiWhiteSpace('\n ') FUN @@ -130,5 +130,5 @@ JetFile: RootNamespace.jet PsiWhiteSpace('\n ') PsiElement(RBRACE)('}') PsiWhiteSpace('\n') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(RBRACE)('}') \ No newline at end of file diff --git a/compiler/testData/psi/greatSyntacticShift/functionTypes.txt b/compiler/testData/psi/greatSyntacticShift/functionTypes.txt index fd200c73574..d1da2d361c7 100644 --- a/compiler/testData/psi/greatSyntacticShift/functionTypes.txt +++ b/compiler/testData/psi/greatSyntacticShift/functionTypes.txt @@ -13,7 +13,7 @@ JetFile: functionTypes.jet PsiWhiteSpace('\n') PsiElement(RBRACE)('}') PsiWhiteSpace('\n\n') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(package)('package') PsiWhiteSpace(' ') MODIFIER_LIST @@ -24,7 +24,7 @@ JetFile: functionTypes.jet REFERENCE_EXPRESSION PsiElement(IDENTIFIER)('n') PsiWhiteSpace(' ') - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(LBRACE)('{') PsiWhiteSpace('\n ') CLASS @@ -34,7 +34,7 @@ JetFile: functionTypes.jet PsiWhiteSpace('\n') TYPE_PARAMETER_LIST - PsiErrorElement:Expecting namespace or top level declaration + PsiErrorElement:Expecting package directive or top level declaration PsiElement(RBRACE)('}') PsiWhiteSpace('\n') CLASS From 8c5c9311fbb2cfe91de04a2bea146b8495d2ab74 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Sat, 21 Apr 2012 00:56:04 +0400 Subject: [PATCH 091/147] Added *.template files to resource templates for compiler. --- .idea/compiler.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/.idea/compiler.xml b/.idea/compiler.xml index 3b66d4ce869..8c89653e336 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -17,6 +17,7 @@ + From 32605248c59bc7910d39b53176e558ad9bc0da48 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Sat, 21 Apr 2012 01:09:05 +0400 Subject: [PATCH 092/147] Added intention which adds or removes explicit type specification for property or variable. #KT-1427 fixed --- .../after.kt.template | 3 + .../before.kt.template | 3 + .../description.html | 5 ++ idea/src/META-INF/plugin.xml | 4 + .../jetbrains/jet/plugin/JetBundle.properties | 3 + .../SpecifyTypeExplicitlyAction.java | 88 +++++++++++++++++++ 6 files changed, 106 insertions(+) create mode 100644 idea/resources/intentionDescriptions/SpecifyTypeExplicitlyAction/after.kt.template create mode 100644 idea/resources/intentionDescriptions/SpecifyTypeExplicitlyAction/before.kt.template create mode 100644 idea/resources/intentionDescriptions/SpecifyTypeExplicitlyAction/description.html create mode 100644 idea/src/org/jetbrains/jet/plugin/intentions/SpecifyTypeExplicitlyAction.java diff --git a/idea/resources/intentionDescriptions/SpecifyTypeExplicitlyAction/after.kt.template b/idea/resources/intentionDescriptions/SpecifyTypeExplicitlyAction/after.kt.template new file mode 100644 index 00000000000..d59bae419ce --- /dev/null +++ b/idea/resources/intentionDescriptions/SpecifyTypeExplicitlyAction/after.kt.template @@ -0,0 +1,3 @@ +fun main() { + val a : Array = array(1, 2, 3) +} \ No newline at end of file diff --git a/idea/resources/intentionDescriptions/SpecifyTypeExplicitlyAction/before.kt.template b/idea/resources/intentionDescriptions/SpecifyTypeExplicitlyAction/before.kt.template new file mode 100644 index 00000000000..747b9a65230 --- /dev/null +++ b/idea/resources/intentionDescriptions/SpecifyTypeExplicitlyAction/before.kt.template @@ -0,0 +1,3 @@ +fun main() { + val a = array(1, 2, 3) +} \ No newline at end of file diff --git a/idea/resources/intentionDescriptions/SpecifyTypeExplicitlyAction/description.html b/idea/resources/intentionDescriptions/SpecifyTypeExplicitlyAction/description.html new file mode 100644 index 00000000000..60e767f56aa --- /dev/null +++ b/idea/resources/intentionDescriptions/SpecifyTypeExplicitlyAction/description.html @@ -0,0 +1,5 @@ + + +This intention adds or removes explicit type specification for local values, variables and properties. + + \ No newline at end of file diff --git a/idea/src/META-INF/plugin.xml b/idea/src/META-INF/plugin.xml index ace5239fa46..2abe60e579b 100644 --- a/idea/src/META-INF/plugin.xml +++ b/idea/src/META-INF/plugin.xml @@ -174,6 +174,10 @@ icon="/org/jetbrains/jet/plugin/icons/kotlin13x13.png" /> + + org.jetbrains.jet.plugin.intentions.SpecifyTypeExplicitlyAction + Kotlin + diff --git a/idea/src/org/jetbrains/jet/plugin/JetBundle.properties b/idea/src/org/jetbrains/jet/plugin/JetBundle.properties index cf854a3e94c..d949b7cec59 100644 --- a/idea/src/org/jetbrains/jet/plugin/JetBundle.properties +++ b/idea/src/org/jetbrains/jet/plugin/JetBundle.properties @@ -29,6 +29,9 @@ implement.members=Implement members new.kotlin.file.action=Kotlin File import.fix=Import imports.chooser.title=Imports +specify.type.explicitly.action.family.name=Specify Type Explicitly +specify.type.explicitly.add.action.name=Specify Type Explicitly +specify.type.explicitly.remove.action.name=Remove Explicitly Specified Type livetemplate.description.main=main() function livetemplate.description.soutp=Prints function parameter names and values to System.out diff --git a/idea/src/org/jetbrains/jet/plugin/intentions/SpecifyTypeExplicitlyAction.java b/idea/src/org/jetbrains/jet/plugin/intentions/SpecifyTypeExplicitlyAction.java new file mode 100644 index 00000000000..df30eab6263 --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/intentions/SpecifyTypeExplicitlyAction.java @@ -0,0 +1,88 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.plugin.intentions; + +import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiElement; +import com.intellij.psi.impl.source.tree.LeafPsiElement; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; +import org.jetbrains.jet.lang.descriptors.VariableDescriptor; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.psi.JetProperty; +import org.jetbrains.jet.lang.resolve.BindingContext; +import org.jetbrains.jet.lang.types.ErrorUtils; +import org.jetbrains.jet.lang.types.JetType; +import org.jetbrains.jet.lexer.JetTokens; +import org.jetbrains.jet.plugin.JetBundle; +import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil; +import org.jetbrains.jet.plugin.refactoring.introduceVariable.JetChangePropertyActions; + +/** + * @author Evgeny Gerashchenko + * @since 4/20/12 + */ +public class SpecifyTypeExplicitlyAction extends PsiElementBaseIntentionAction { + private JetType targetType; + + @NotNull + @Override + public String getText() { + return targetType == null ? JetBundle.message("specify.type.explicitly.remove.action.name") : JetBundle.message("specify.type.explicitly.add.action.name"); + } + + @NotNull + @Override + public String getFamilyName() { + return JetBundle.message("specify.type.explicitly.action.family.name"); + } + + @Override + public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) { + JetProperty property = (JetProperty)element.getParent(); + if (targetType == null) { + JetChangePropertyActions.removeTypeAnnotation(project, property); + } else { + JetChangePropertyActions.addTypeAnnotation(project, property, targetType); + } + } + + @Override + public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) { + if (!(element instanceof LeafPsiElement) || ((LeafPsiElement)element).getElementType() != JetTokens.IDENTIFIER + || !(element.getParent() instanceof JetProperty)) { + return false; + } + + JetProperty property = (JetProperty)element.getParent(); + boolean hasTypeSpecified = property.getPropertyTypeRef() != null; + if (hasTypeSpecified) { + targetType = null; + } else { + BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile((JetFile)element.getContainingFile()); + DeclarationDescriptor descriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, property); + assert descriptor instanceof VariableDescriptor; + targetType = ((VariableDescriptor)descriptor).getType(); + if (ErrorUtils.isErrorType(targetType)) { + return false; + } + } + return true; + } +} From 82b4304f0e6f3cb9f9634f8033238047775e69c1 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Sat, 21 Apr 2012 02:39:23 +0400 Subject: [PATCH 093/147] Added auto-importing in JetChangePropertyActions.addTypeAnnotation(). It is used in "specify type explicitly" intention and "introduce variable" refactoring. Corrected auto-importing for cases of nested classes (e.g. Map.Entry). --- .../jetbrains/jet/lang/types/TypeUtils.java | 17 ++++++++++++ .../jet/resolve/DescriptorRenderer.java | 27 +++++++++++++++---- .../jetbrains/jet/plugin/JetPluginUtil.java | 6 ----- .../OverrideImplementMethodsHandler.java | 6 ++--- .../jet/plugin/quickfix/AddReturnTypeFix.java | 2 +- .../plugin/quickfix/ImportInsertHelper.java | 26 +++++++++++++----- .../quickfix/RemovePartsFromPropertyFix.java | 2 +- .../JetChangePropertyActions.java | 6 ++++- 8 files changed, 68 insertions(+), 24 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/TypeUtils.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/TypeUtils.java index 0421553c7a1..f96d11a93ed 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/types/TypeUtils.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/TypeUtils.java @@ -529,6 +529,23 @@ public class TypeUtils { return null; } + private static void addAllClassDescriptors(@NotNull JetType type, @NotNull Set set) { + ClassDescriptor cd = getClassDescriptor(type); + if (cd != null) { + set.add(cd); + } + for (TypeProjection projection : type.getArguments()) { + addAllClassDescriptors(projection.getType(), set); + } + } + + @NotNull + public static List getAllClassDescriptors(@NotNull JetType type) { + Set classDescriptors = new HashSet(); + addAllClassDescriptors(type, classDescriptors); + return new ArrayList(classDescriptors); + } + public static boolean hasUnsubstitutedTypeParameters(JetType type) { if (type.getConstructor().getDeclarationDescriptor() instanceof TypeParameterDescriptor) { return true; diff --git a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java index 92ba84da251..783499a34d0 100644 --- a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java @@ -30,10 +30,7 @@ import org.jetbrains.jet.lang.types.Variance; import org.jetbrains.jet.lang.types.lang.JetStandardClasses; import org.jetbrains.jet.lexer.JetTokens; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; +import java.util.*; /** * @author abreslav @@ -122,6 +119,15 @@ public class DescriptorRenderer implements Renderer { } } + private static List getOuterClassesNames(ClassDescriptor cd) { + ArrayList result = new ArrayList(); + while (cd.getContainingDeclaration() instanceof ClassifierDescriptor) { + result.add(cd.getName()); + cd = (ClassDescriptor)cd.getContainingDeclaration(); + } + return result; + } + private String renderDefaultType(JetType type, boolean shortNamesOnly) { StringBuilder sb = new StringBuilder(); ClassifierDescriptor cd = type.getConstructor().getDeclarationDescriptor(); @@ -132,7 +138,18 @@ public class DescriptorRenderer implements Renderer { typeNameObject = type.getConstructor(); } else { - typeNameObject = shortNamesOnly ? cd.getName() : DescriptorUtils.getFQName(cd); + if (shortNamesOnly) { + // for nested classes qualified name should be used + typeNameObject = cd.getName(); + DeclarationDescriptor parent = cd.getContainingDeclaration(); + while (parent instanceof ClassDescriptor) { + typeNameObject = parent.getName() + "." + typeNameObject; + parent = parent.getContainingDeclaration(); + } + } + else { + typeNameObject = DescriptorUtils.getFQName(cd); + } } sb.append(typeNameObject); diff --git a/idea/src/org/jetbrains/jet/plugin/JetPluginUtil.java b/idea/src/org/jetbrains/jet/plugin/JetPluginUtil.java index 37c647ee4ff..890ea800949 100644 --- a/idea/src/org/jetbrains/jet/plugin/JetPluginUtil.java +++ b/idea/src/org/jetbrains/jet/plugin/JetPluginUtil.java @@ -37,12 +37,6 @@ import java.util.LinkedList; * @author svtk */ public class JetPluginUtil { - @NotNull - public static FqName computeTypeFullName(@NotNull JetType type) { - ClassDescriptor clazz = (ClassDescriptor) type.getConstructor().getDeclarationDescriptor(); - return DescriptorUtils.getFQName(clazz).toSafe(); - } - @NotNull private static LinkedList computeTypeFullNameList(JetType type) { if (type instanceof DeferredType) { diff --git a/idea/src/org/jetbrains/jet/plugin/codeInsight/OverrideImplementMethodsHandler.java b/idea/src/org/jetbrains/jet/plugin/codeInsight/OverrideImplementMethodsHandler.java index 6f8f844d7c6..b82bc360996 100644 --- a/idea/src/org/jetbrains/jet/plugin/codeInsight/OverrideImplementMethodsHandler.java +++ b/idea/src/org/jetbrains/jet/plugin/codeInsight/OverrideImplementMethodsHandler.java @@ -131,7 +131,7 @@ public abstract class OverrideImplementMethodsHandler implements LanguageCodeIns } bodyBuilder.append(descriptor.getName()).append(" : ").append(DescriptorRenderer.COMPACT.renderTypeWithShortNames( descriptor.getType())); - ImportInsertHelper.addImportDirectiveIfNeeded(descriptor.getType(), file); + ImportInsertHelper.addImportDirectivesIfNeeded(descriptor.getType(), file); String initializer = defaultInitializer(descriptor.getType(), JetStandardLibrary.getInstance()); if (initializer != null) { bodyBuilder.append(" = ").append(initializer); @@ -168,7 +168,7 @@ public abstract class OverrideImplementMethodsHandler implements LanguageCodeIns bodyBuilder.append(" : "); bodyBuilder.append(DescriptorRenderer.COMPACT.renderTypeWithShortNames(parameterDescriptor.getType())); - ImportInsertHelper.addImportDirectiveIfNeeded(parameterDescriptor.getType(), file); + ImportInsertHelper.addImportDirectivesIfNeeded(parameterDescriptor.getType(), file); if (!isAbstractFun) { delegationBuilder.append(parameterDescriptor.getName()); @@ -184,7 +184,7 @@ public abstract class OverrideImplementMethodsHandler implements LanguageCodeIns boolean returnsNotUnit = returnType != null && !stdlib.getTuple0Type().equals(returnType); if (returnsNotUnit) { bodyBuilder.append(" : ").append(DescriptorRenderer.COMPACT.renderTypeWithShortNames(returnType)); - ImportInsertHelper.addImportDirectiveIfNeeded(returnType, file); + ImportInsertHelper.addImportDirectivesIfNeeded(returnType, file); } bodyBuilder.append("{").append(returnsNotUnit && !isAbstractFun ? "return " : "").append(delegationBuilder.toString()).append("}"); diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/AddReturnTypeFix.java b/idea/src/org/jetbrains/jet/plugin/quickfix/AddReturnTypeFix.java index 006cb2c3878..6a55bbfd471 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/AddReturnTypeFix.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/AddReturnTypeFix.java @@ -68,7 +68,7 @@ public class AddReturnTypeFix extends JetIntentionAction { assert element instanceof JetFunction; newElement = addFunctionType(project, (JetFunction) element, type); } - ImportInsertHelper.addImportDirectiveIfNeeded(type, (JetFile) file); + ImportInsertHelper.addImportDirectivesIfNeeded(type, (JetFile)file); element.replace(newElement); } diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java b/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java index 42dc1a79121..9dc612eda86 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java @@ -17,22 +17,21 @@ package org.jetbrains.jet.plugin.quickfix; import com.intellij.psi.PsiElement; -import com.intellij.usages.impl.rules.NonCodeUsageGroupingRule; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.DefaultModuleConfiguration; +import org.jetbrains.jet.lang.descriptors.ClassDescriptor; +import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetImportDirective; import org.jetbrains.jet.lang.psi.JetPsiFactory; import org.jetbrains.jet.lang.psi.JetPsiUtil; -import org.jetbrains.jet.lang.resolve.BindingContext; -import org.jetbrains.jet.lang.resolve.BindingContextUtils; -import org.jetbrains.jet.lang.resolve.FqName; -import org.jetbrains.jet.lang.resolve.ImportPath; +import org.jetbrains.jet.lang.resolve.*; import org.jetbrains.jet.lang.resolve.java.JavaBridgeConfiguration; import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; import org.jetbrains.jet.lang.types.ErrorUtils; import org.jetbrains.jet.lang.types.JetType; +import org.jetbrains.jet.lang.types.TypeUtils; import org.jetbrains.jet.plugin.JetPluginUtil; import org.jetbrains.jet.util.QualifiedNamesUtil; @@ -53,7 +52,7 @@ public class ImportInsertHelper { * @param type type to import * @param file file where import directive should be added */ - public static void addImportDirectiveIfNeeded(@NotNull JetType type, @NotNull JetFile file) { + public static void addImportDirectivesIfNeeded(@NotNull JetType type, @NotNull JetFile file) { if (JetPluginUtil.checkTypeIsStandard(type, file.getProject()) || ErrorUtils.isErrorType(type)) { return; } @@ -62,7 +61,9 @@ public class ImportInsertHelper { if (element != null && element.getContainingFile() == file) { //declaration is in the same file, so no import is needed return; } - addImportDirective(JetPluginUtil.computeTypeFullName(type), file); + for (ClassDescriptor clazz : TypeUtils.getAllClassDescriptors(type)) { + addImportDirective(DescriptorUtils.getFQName(getTopLevelClass(clazz)).toSafe(), file); + } } /** @@ -155,4 +156,15 @@ public class ImportInsertHelper { return true; } + + private static ClassDescriptor getTopLevelClass(ClassDescriptor classDescriptor) { + while (true) { + DeclarationDescriptor parent = classDescriptor.getContainingDeclaration(); + if (parent instanceof ClassDescriptor) { + classDescriptor = (ClassDescriptor) parent; + } else { + return classDescriptor; + } + } + } } diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/RemovePartsFromPropertyFix.java b/idea/src/org/jetbrains/jet/plugin/quickfix/RemovePartsFromPropertyFix.java index 886ea3ea8ed..f67c6452cb3 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/RemovePartsFromPropertyFix.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/RemovePartsFromPropertyFix.java @@ -119,7 +119,7 @@ public class RemovePartsFromPropertyFix extends JetIntentionAction } } if (needImport) { - ImportInsertHelper.addImportDirectiveIfNeeded(type, (JetFile) file); + ImportInsertHelper.addImportDirectivesIfNeeded(type, (JetFile)file); } element.replace(newElement); } diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetChangePropertyActions.java b/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetChangePropertyActions.java index 8cd70130ea4..eef765ba774 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetChangePropertyActions.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetChangePropertyActions.java @@ -5,10 +5,13 @@ import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiWhiteSpace; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetProperty; import org.jetbrains.jet.lang.psi.JetPsiFactory; import org.jetbrains.jet.lang.psi.JetTypeReference; import org.jetbrains.jet.lang.types.JetType; +import org.jetbrains.jet.plugin.quickfix.ImportInsertHelper; +import org.jetbrains.jet.resolve.DescriptorRenderer; /** * User: Alefas @@ -35,13 +38,14 @@ public class JetChangePropertyActions { if (anchor == null) return; anchor = anchor.getNextSibling(); if (anchor == null || !(anchor instanceof PsiWhiteSpace)) return; - JetTypeReference typeReference = JetPsiFactory.createType(project, exprType.toString()); + JetTypeReference typeReference = JetPsiFactory.createType(project, DescriptorRenderer.TEXT.renderTypeWithShortNames(exprType)); ASTNode colon = JetPsiFactory.createColonNode(project); ASTNode anchorNode = anchor.getNode().getTreeNext(); property.getNode().addChild(colon, anchorNode); property.getNode().addChild(JetPsiFactory.createWhiteSpace(project).getNode(), anchorNode); property.getNode().addChild(typeReference.getNode(), anchorNode); property.getNode().addChild(JetPsiFactory.createWhiteSpace(project).getNode(), anchorNode); + ImportInsertHelper.addImportDirectivesIfNeeded(exprType, (JetFile)property.getContainingFile()); anchor.delete(); } From be9004aa62d0ae4f0638e9803d7a451422414f2f Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Sat, 21 Apr 2012 02:51:49 +0400 Subject: [PATCH 094/147] Expanded availability of "Specify Type Explicitly" intention. #KT-1849 fixed --- .../jet/plugin/intentions/SpecifyTypeExplicitlyAction.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/intentions/SpecifyTypeExplicitlyAction.java b/idea/src/org/jetbrains/jet/plugin/intentions/SpecifyTypeExplicitlyAction.java index df30eab6263..f10680dddf5 100644 --- a/idea/src/org/jetbrains/jet/plugin/intentions/SpecifyTypeExplicitlyAction.java +++ b/idea/src/org/jetbrains/jet/plugin/intentions/SpecifyTypeExplicitlyAction.java @@ -21,6 +21,7 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.impl.source.tree.LeafPsiElement; +import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.descriptors.VariableDescriptor; @@ -65,8 +66,7 @@ public class SpecifyTypeExplicitlyAction extends PsiElementBaseIntentionAction { @Override public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) { - if (!(element instanceof LeafPsiElement) || ((LeafPsiElement)element).getElementType() != JetTokens.IDENTIFIER - || !(element.getParent() instanceof JetProperty)) { + if (!(element.getParent() instanceof JetProperty) || PsiTreeUtil.isAncestor(((JetProperty)element.getParent()).getInitializer(), element, false)) { return false; } From 7c8937bd2dd9fa5037333ea05375df614e7db002 Mon Sep 17 00:00:00 2001 From: Stepan Koltsov Date: Sat, 21 Apr 2012 18:03:53 +0400 Subject: [PATCH 095/147] JavaDescriptorResolver: negative package cache Time spent in JavaDescriptorResolver.resolveNamespace reduced from 10% to 5% in CompileCompilerDependenciesTest --- .../resolve/java/JavaDescriptorResolver.java | 42 +++++++++++++++++-- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java index 9f8015a8b06..248fca7c8a7 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java @@ -209,11 +209,9 @@ public class JavaDescriptorResolver { final PsiClass psiClass; @Nullable final PsiPackage psiPackage; - @NotNull final FqName fqName; final boolean staticMembers; final boolean kotlin; - @NotNull final ClassOrNamespaceDescriptor classOrNamespaceDescriptor; protected ResolverScopeData(@Nullable PsiClass psiClass, @Nullable PsiPackage psiPackage, @NotNull FqName fqName, boolean staticMembers, @NotNull ClassOrNamespaceDescriptor descriptor) { @@ -237,6 +235,22 @@ public class JavaDescriptorResolver { classOrNamespaceDescriptor = descriptor; } + protected ResolverScopeData(boolean negative) { + if (!negative) { + throw new IllegalStateException(); + } + this.psiClass = null; + this.psiPackage = null; + this.fqName = null; + this.staticMembers = false; + this.kotlin = false; + this.classOrNamespaceDescriptor = null; + } + + public boolean isPositive() { + return this.classOrNamespaceDescriptor != null; + } + @NotNull public PsiElement getPsiPackageOrPsiClass() { if (psiPackage != null) { @@ -262,6 +276,13 @@ public class JavaDescriptorResolver { this.classDescriptor = classDescriptor; } + private ResolverBinaryClassData(boolean negative) { + super(negative); + this.classDescriptor = null; + } + + static final ResolverBinaryClassData NEGATIVE = new ResolverBinaryClassData(true); + List typeParameters; @NotNull @@ -286,6 +307,13 @@ public class JavaDescriptorResolver { this.namespaceDescriptor = namespaceDescriptor; } + private ResolverNamespaceData(boolean negative) { + super(negative); + this.namespaceDescriptor = null; + } + + static final ResolverNamespaceData NEGATIVE = new ResolverNamespaceData(true); + private JavaPackageScope memberScope; @NotNull @@ -374,11 +402,15 @@ public class JavaDescriptorResolver { if (classData == null) { PsiClass psiClass = psiClassFinder.findPsiClass(qualifiedName, PsiClassFinder.RuntimeClassesHandleMode.THROW); if (psiClass == null) { + ResolverBinaryClassData oldValue = classDescriptorCache.put(qualifiedName, ResolverBinaryClassData.NEGATIVE); + if (oldValue != null) { + throw new IllegalStateException("rewrite at " + qualifiedName); + } return null; } classData = createJavaClassDescriptor(psiClass, tasks); } - return classData.getClassDescriptor(); + return classData.classDescriptor; } private ResolverBinaryClassData createJavaClassDescriptor(@NotNull final PsiClass psiClass, List taskList) { @@ -974,6 +1006,10 @@ public class JavaDescriptorResolver { break lookingForPsi; } + ResolverNamespaceData oldValue = namespaceDescriptorCacheByFqn.put(fqName, ResolverNamespaceData.NEGATIVE); + if (oldValue != null) { + throw new IllegalStateException("rewrite at " + fqName); + } return null; } From 75255aebdc7587e73fe9b92cc7c354d820c668a4 Mon Sep 17 00:00:00 2001 From: Stepan Koltsov Date: Sat, 21 Apr 2012 18:03:57 +0400 Subject: [PATCH 096/147] use BufferedOutputStream when building jar it speeds up building (from 3% to 1% in CompileCompilerDependenciesTest) --- .../jet/codegen/forTestCompile/ForTestCompileSomething.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileSomething.java b/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileSomething.java index 174ffe669dc..c6d09a81878 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileSomething.java +++ b/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileSomething.java @@ -23,6 +23,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.JetTestUtils; import org.jetbrains.jet.TimeUtils; +import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -57,7 +58,7 @@ abstract class ForTestCompileSomething { FileOutputStream stdlibJar = new FileOutputStream(jarFile); try { - JarOutputStream jarOutputStream = new JarOutputStream(stdlibJar); + JarOutputStream jarOutputStream = new JarOutputStream(new BufferedOutputStream(stdlibJar)); try { copyToJar(classesDir, jarOutputStream); } From 71ef123dc3f7ba4012aed70ebea463d166e23ed0 Mon Sep 17 00:00:00 2001 From: Sergey Lukjanov Date: Sat, 21 Apr 2012 22:22:55 +0400 Subject: [PATCH 097/147] Array#lastIndex property has been added to stdlib --- libraries/stdlib/src/kotlin/Arrays.kt | 27 +++++++++++++++++++++++++++ libraries/stdlib/test/ArraysTest.kt | 18 ++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/libraries/stdlib/src/kotlin/Arrays.kt b/libraries/stdlib/src/kotlin/Arrays.kt index 74a8cd50b08..15f4e031e92 100644 --- a/libraries/stdlib/src/kotlin/Arrays.kt +++ b/libraries/stdlib/src/kotlin/Arrays.kt @@ -124,3 +124,30 @@ public inline fun Array.isEmpty() : Boolean = this.size == 0 /** Returns the array if its not null or else returns an empty array */ public inline fun Array?.orEmpty() : Array = if (this != null) this else array() + +public inline val BooleanArray.lastIndex : Int + get() = this.size - 1 + +public inline val ByteArray.lastIndex : Int + get() = this.size - 1 + +public inline val ShortArray.lastIndex : Int + get() = this.size - 1 + +public inline val IntArray.lastIndex : Int + get() = this.size - 1 + +public inline val LongArray.lastIndex : Int + get() = this.size - 1 + +public inline val FloatArray.lastIndex : Int + get() = this.size - 1 + +public inline val DoubleArray.lastIndex : Int + get() = this.size - 1 + +public inline val CharArray.lastIndex : Int + get() = this.size - 1 + +public inline val Array.lastIndex : Int + get() = this.size - 1 diff --git a/libraries/stdlib/test/ArraysTest.kt b/libraries/stdlib/test/ArraysTest.kt index 4fe0f3b133b..77620c63610 100644 --- a/libraries/stdlib/test/ArraysTest.kt +++ b/libraries/stdlib/test/ArraysTest.kt @@ -39,4 +39,22 @@ class ArraysTest() : TestCase() { assertFalse(iter.hasNext, "Invalid length (hasNext)") } + fun testEmptyArrayLastIndex() { + val arr1 = IntArray(0) + assertEquals(-1, arr1.lastIndex) + + val arr2 = Array(0, {"$it"}) + assertEquals(-1, arr2.lastIndex) + } + + fun testArrayLastIndex() { + val arr1 = intArray(0, 1, 2, 3, 4) + assertEquals(4, arr1.lastIndex) + assertEquals(4, arr1[arr1.lastIndex]) + + val arr2 = Array(5, {"$it"}) + assertEquals(4, arr2.lastIndex) + assertEquals("4", arr2[arr2.lastIndex]) + } + } From 22d601ffcbacce513c269235ebcb41f63373e66f Mon Sep 17 00:00:00 2001 From: Leonid Shalupov Date: Sun, 22 Apr 2012 22:38:36 +0400 Subject: [PATCH 098/147] integration tests draft --- .idea/modules.xml | 1 + .../compiler-integration-tests.iml | 24 +++ compiler/integration-tests/data/help.gold | 16 ++ .../jetbrains/kotlin/CompilerSmokeTest.java | 26 +++ .../kotlin/KotlinIntegrationTestBase.java | 155 ++++++++++++++++++ 5 files changed, 222 insertions(+) create mode 100644 compiler/integration-tests/compiler-integration-tests.iml create mode 100644 compiler/integration-tests/data/help.gold create mode 100644 compiler/integration-tests/src/org/jetbrains/kotlin/CompilerSmokeTest.java create mode 100644 compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java diff --git a/.idea/modules.xml b/.idea/modules.xml index 94213936f8b..a7a32bf50d1 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -6,6 +6,7 @@ + diff --git a/compiler/integration-tests/compiler-integration-tests.iml b/compiler/integration-tests/compiler-integration-tests.iml new file mode 100644 index 00000000000..b9f5f634fdc --- /dev/null +++ b/compiler/integration-tests/compiler-integration-tests.iml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/compiler/integration-tests/data/help.gold b/compiler/integration-tests/data/help.gold new file mode 100644 index 00000000000..9bb334537b7 --- /dev/null +++ b/compiler/integration-tests/data/help.gold @@ -0,0 +1,16 @@ +OUT Usage: org.jetbrains.jet.cli.CompilerArguments +OUT -output [String] output directory +OUT -jar [String] jar file name +OUT -src [String] source file or directory +OUT -module [String] module to compile +OUT -classpath [String] classpath to use when compiling +OUT -includeRuntime [flag] +OUT -stdlib [String] Path to the stdlib.jar +OUT -jdkHeaders [String] Path to the kotlin-jdk-headers.jar +OUT -help (-h) [flag] +OUT -mode [String] Special compiler modes: stubs or jdkHeaders +OUT -tags [flag] +OUT -verbose [flag] +OUT -version [flag] +ERR exec() finished with INTERNAL_ERROR return code +Return code: 2 diff --git a/compiler/integration-tests/src/org/jetbrains/kotlin/CompilerSmokeTest.java b/compiler/integration-tests/src/org/jetbrains/kotlin/CompilerSmokeTest.java new file mode 100644 index 00000000000..ef858496679 --- /dev/null +++ b/compiler/integration-tests/src/org/jetbrains/kotlin/CompilerSmokeTest.java @@ -0,0 +1,26 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.kotlin; + +import org.junit.Test; + +public class CompilerSmokeTest extends KotlinIntegrationTestBase { + @Test + public void help() throws Exception { + runCompiler("help", "--help"); + } +} diff --git a/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java b/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java new file mode 100644 index 00000000000..a8e793040ea --- /dev/null +++ b/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java @@ -0,0 +1,155 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.kotlin; + +import com.google.common.base.Charsets; +import com.google.common.io.Files; +import com.intellij.execution.ExecutionException; +import com.intellij.execution.configurations.GeneralCommandLine; +import com.intellij.execution.process.OSProcessHandler; +import com.intellij.execution.process.ProcessAdapter; +import com.intellij.execution.process.ProcessEvent; +import com.intellij.execution.process.ProcessOutputTypes; +import com.intellij.openapi.application.PathManager; +import com.intellij.openapi.util.Key; +import com.intellij.openapi.util.SystemInfo; +import com.intellij.util.ArrayUtil; +import org.apache.commons.lang.SystemUtils; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; + +import static com.google.common.base.Charsets.UTF_8; +import static org.junit.Assert.*; + +public abstract class KotlinIntegrationTestBase { + protected void runCompiler(String logName, String... arguments) throws Exception { + Collection javaArgs = new ArrayList(); + javaArgs.add("-jar"); + javaArgs.add(getCompilerJar().getAbsolutePath()); + Collections.addAll(javaArgs, arguments); + + runJava(logName, ArrayUtil.toStringArray(javaArgs)); + } + + protected void runCompiler(StringBuilder executionLog) throws ExecutionException { + final File compilerJar = getCompilerJar(); + assertTrue("no kotlin compiler at " + compilerJar, compilerJar.isFile()); + + GeneralCommandLine commandLine = new GeneralCommandLine(); + commandLine.setExePath(getJavaRuntime().getAbsolutePath()); + commandLine.addParameters("-jar", compilerJar.getAbsolutePath()); + commandLine.addParameters("--help"); + + runProcess(commandLine, executionLog); + } + + protected void runJava(String logName, String... arguments) throws Exception { + GeneralCommandLine commandLine = new GeneralCommandLine(); + commandLine.setExePath(getJavaRuntime().getAbsolutePath()); + commandLine.addParameters(arguments); + + StringBuilder executionLog = new StringBuilder(); + int exitCode = runProcess(commandLine, executionLog); + + if (logName == null) { + assertEquals("Non-zero exit code", 0, exitCode); + } + else { + check(logName, executionLog); + } + } + + protected void check(String baseName, StringBuilder content) throws IOException { + final File tmpFile = new File(getTestDataDirectory(), baseName + ".tmp"); + final File goldFile = new File(getTestDataDirectory(), baseName + ".gold"); + + if (!goldFile.isFile()) { + Files.write(content, tmpFile, Charsets.UTF_8); + fail("No gold file " + goldFile); + } else { + final String goldContent = Files.toString(goldFile, UTF_8); + if (!goldContent.equals(content.toString())) { + Files.write(content, tmpFile, Charsets.UTF_8); + fail("tmp and gold differ, tmp file: " + tmpFile); + } + tmpFile.delete(); + } + } + + protected int runProcess(final GeneralCommandLine commandLine, final StringBuilder executionLog) throws ExecutionException { + OSProcessHandler handler = + new OSProcessHandler(commandLine.createProcess(), commandLine.getCommandLineString(), commandLine.getCharset()); + + final StringBuilder outContent = new StringBuilder(); + final StringBuilder errContent = new StringBuilder(); + + handler.addProcessListener(new ProcessAdapter() { + @Override + public void onTextAvailable(ProcessEvent event, Key outputType) { + if (outputType == ProcessOutputTypes.SYSTEM) { + System.out.print(event.getText()); + } + else if (outputType == ProcessOutputTypes.STDOUT) { + outContent.append("OUT "); + outContent.append(event.getText()); + } + else if (outputType == ProcessOutputTypes.STDERR) { + errContent.append("ERR "); + errContent.append(event.getText()); + } + } + }); + + handler.startNotify(); + handler.waitFor(); + int exitCode = handler.getProcess().exitValue(); + + executionLog.append(outContent); + executionLog.append(errContent); + executionLog.append("Return code: ").append(exitCode).append(SystemUtils.LINE_SEPARATOR); + + return exitCode; + } + + protected static File getJavaRuntime() { + final File javaHome = new File(System.getProperty("java.home")); + final String javaExe = SystemInfo.isWindows ? "java.exe" : "java"; + + final File runtime = new File(javaHome, "bin" + File.separator + javaExe); + assertTrue("no java runtime at " + runtime, runtime.isFile()); + + return runtime; + } + + protected static File getCompilerJar() { + final File file = new File(getKotlinProjectHome(), "dist" + File.separator + "kotlin-compiler.jar"); + assertTrue("no kotlin compiler at " + file, file.isFile()); + return file; + } + + protected static File getTestDataDirectory() { + return new File(getKotlinProjectHome(), "compiler" + File.separator + "integration-tests" + File.separator + "data"); + } + + protected static File getKotlinProjectHome() { + return new File(PathManager.getHomePath()).getParentFile(); + } +} From 40e594668b757c54cbfbc1c27b43df916a37ae79 Mon Sep 17 00:00:00 2001 From: Leonid Shalupov Date: Sun, 22 Apr 2012 22:54:13 +0400 Subject: [PATCH 099/147] integration tests: compile and run hello app --- .../integration-tests/data/hello.compile.gold | 1 + compiler/integration-tests/data/hello.kt | 5 +++ .../integration-tests/data/hello.run.gold | 2 + .../jetbrains/kotlin/CompilerSmokeTest.java | 8 ++++ .../kotlin/KotlinIntegrationTestBase.java | 45 ++++++++++--------- 5 files changed, 41 insertions(+), 20 deletions(-) create mode 100644 compiler/integration-tests/data/hello.compile.gold create mode 100644 compiler/integration-tests/data/hello.kt create mode 100644 compiler/integration-tests/data/hello.run.gold diff --git a/compiler/integration-tests/data/hello.compile.gold b/compiler/integration-tests/data/hello.compile.gold new file mode 100644 index 00000000000..a14ac74940f --- /dev/null +++ b/compiler/integration-tests/data/hello.compile.gold @@ -0,0 +1 @@ +Return code: 0 diff --git a/compiler/integration-tests/data/hello.kt b/compiler/integration-tests/data/hello.kt new file mode 100644 index 00000000000..4c4a4b67c8c --- /dev/null +++ b/compiler/integration-tests/data/hello.kt @@ -0,0 +1,5 @@ +package Hello + +fun main(args : Array) { + System.out?.println("Hello!") +} diff --git a/compiler/integration-tests/data/hello.run.gold b/compiler/integration-tests/data/hello.run.gold new file mode 100644 index 00000000000..fc47ec99014 --- /dev/null +++ b/compiler/integration-tests/data/hello.run.gold @@ -0,0 +1,2 @@ +OUT Hello! +Return code: 0 diff --git a/compiler/integration-tests/src/org/jetbrains/kotlin/CompilerSmokeTest.java b/compiler/integration-tests/src/org/jetbrains/kotlin/CompilerSmokeTest.java index ef858496679..72550b8a5a5 100644 --- a/compiler/integration-tests/src/org/jetbrains/kotlin/CompilerSmokeTest.java +++ b/compiler/integration-tests/src/org/jetbrains/kotlin/CompilerSmokeTest.java @@ -18,9 +18,17 @@ package org.jetbrains.kotlin; import org.junit.Test; +import static junit.framework.Assert.*; + public class CompilerSmokeTest extends KotlinIntegrationTestBase { @Test public void help() throws Exception { runCompiler("help", "--help"); } + + @Test + public void compileAndRunHelloApp() throws Exception { + assertEquals("compilation failed", 0, runCompiler("hello.compile", "-src", "hello.kt", "-jar", "hello.jar")); + runJava("hello.run", "-cp", "hello.jar", "Hello.namespace"); + } } diff --git a/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java b/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java index a8e793040ea..3f6f26c807c 100644 --- a/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java +++ b/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java @@ -27,8 +27,11 @@ import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.SystemInfo; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ArrayUtil; +import com.intellij.util.Function; import org.apache.commons.lang.SystemUtils; +import sun.misc.JarFilter; import java.io.File; import java.io.IOException; @@ -40,29 +43,29 @@ import static com.google.common.base.Charsets.UTF_8; import static org.junit.Assert.*; public abstract class KotlinIntegrationTestBase { - protected void runCompiler(String logName, String... arguments) throws Exception { + protected int runCompiler(String logName, String... arguments) throws Exception { + final File lib = getCompilerLib(); + + final File[] jars = lib.listFiles(new JarFilter()); + final String classpath = StringUtil.join(jars, new Function() { + @Override + public String fun(File file) { + return file.getAbsolutePath(); + } + }, File.pathSeparator); + Collection javaArgs = new ArrayList(); - javaArgs.add("-jar"); - javaArgs.add(getCompilerJar().getAbsolutePath()); + javaArgs.add("-cp"); + javaArgs.add(classpath); + javaArgs.add("org.jetbrains.jet.cli.KotlinCompiler"); Collections.addAll(javaArgs, arguments); - runJava(logName, ArrayUtil.toStringArray(javaArgs)); + return runJava(logName, ArrayUtil.toStringArray(javaArgs)); } - protected void runCompiler(StringBuilder executionLog) throws ExecutionException { - final File compilerJar = getCompilerJar(); - assertTrue("no kotlin compiler at " + compilerJar, compilerJar.isFile()); - - GeneralCommandLine commandLine = new GeneralCommandLine(); - commandLine.setExePath(getJavaRuntime().getAbsolutePath()); - commandLine.addParameters("-jar", compilerJar.getAbsolutePath()); - commandLine.addParameters("--help"); - - runProcess(commandLine, executionLog); - } - - protected void runJava(String logName, String... arguments) throws Exception { + protected int runJava(String logName, String... arguments) throws Exception { GeneralCommandLine commandLine = new GeneralCommandLine(); + commandLine.setWorkDirectory(getTestDataDirectory()); commandLine.setExePath(getJavaRuntime().getAbsolutePath()); commandLine.addParameters(arguments); @@ -75,6 +78,8 @@ public abstract class KotlinIntegrationTestBase { else { check(logName, executionLog); } + + return exitCode; } protected void check(String baseName, StringBuilder content) throws IOException { @@ -139,9 +144,9 @@ public abstract class KotlinIntegrationTestBase { return runtime; } - protected static File getCompilerJar() { - final File file = new File(getKotlinProjectHome(), "dist" + File.separator + "kotlin-compiler.jar"); - assertTrue("no kotlin compiler at " + file, file.isFile()); + protected static File getCompilerLib() { + final File file = new File(getKotlinProjectHome(), "dist" + File.separator + "kotlinc" + File.separator + "lib"); + assertTrue("no kotlin compiler lib at " + file, file.isDirectory()); return file; } From 32a55f786c237b518f259a53772d4584f9c077b8 Mon Sep 17 00:00:00 2001 From: Leonid Shalupov Date: Sun, 22 Apr 2012 23:10:49 +0400 Subject: [PATCH 100/147] integration tests: temp dir, stable test output --- .../jetbrains/kotlin/CompilerSmokeTest.java | 8 +++- .../kotlin/KotlinIntegrationTestBase.java | 46 ++++++++++++++++--- 2 files changed, 45 insertions(+), 9 deletions(-) diff --git a/compiler/integration-tests/src/org/jetbrains/kotlin/CompilerSmokeTest.java b/compiler/integration-tests/src/org/jetbrains/kotlin/CompilerSmokeTest.java index 72550b8a5a5..72d912e47a7 100644 --- a/compiler/integration-tests/src/org/jetbrains/kotlin/CompilerSmokeTest.java +++ b/compiler/integration-tests/src/org/jetbrains/kotlin/CompilerSmokeTest.java @@ -18,6 +18,8 @@ package org.jetbrains.kotlin; import org.junit.Test; +import java.io.File; + import static junit.framework.Assert.*; public class CompilerSmokeTest extends KotlinIntegrationTestBase { @@ -28,7 +30,9 @@ public class CompilerSmokeTest extends KotlinIntegrationTestBase { @Test public void compileAndRunHelloApp() throws Exception { - assertEquals("compilation failed", 0, runCompiler("hello.compile", "-src", "hello.kt", "-jar", "hello.jar")); - runJava("hello.run", "-cp", "hello.jar", "Hello.namespace"); + final String jar = tempDir.getAbsolutePath() + File.separator + "hello.jar"; + + assertEquals("compilation failed", 0, runCompiler("hello.compile", "-src", "hello.kt", "-jar", jar)); + runJava("hello.run", "-cp", jar, "Hello.namespace"); } } diff --git a/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java b/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java index 3f6f26c807c..7407af4cb83 100644 --- a/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java +++ b/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java @@ -30,7 +30,10 @@ import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.Function; -import org.apache.commons.lang.SystemUtils; +import org.junit.Rule; +import org.junit.rules.TestRule; +import org.junit.rules.TestWatcher; +import org.junit.runner.Description; import sun.misc.JarFilter; import java.io.File; @@ -43,6 +46,30 @@ import static com.google.common.base.Charsets.UTF_8; import static org.junit.Assert.*; public abstract class KotlinIntegrationTestBase { + protected File tempDir; + + @Rule + public TestRule watchman = new TestWatcher() { + @Override + protected void starting(Description description) { + tempDir = Files.createTempDir(); + } + + @Override + protected void succeeded(Description description) { + try { + tempDir.delete(); + } catch (Exception e) { + System.out.print("Can't delete temp directory " + tempDir + ": " + e); + } + } + + @Override + protected void failed(Throwable e, Description description) { + System.err.println("Temp directory: " + tempDir); + } + }; + protected int runCompiler(String logName, String... arguments) throws Exception { final File lib = getCompilerLib(); @@ -89,7 +116,8 @@ public abstract class KotlinIntegrationTestBase { if (!goldFile.isFile()) { Files.write(content, tmpFile, Charsets.UTF_8); fail("No gold file " + goldFile); - } else { + } + else { final String goldContent = Files.toString(goldFile, UTF_8); if (!goldContent.equals(content.toString())) { Files.write(content, tmpFile, Charsets.UTF_8); @@ -113,14 +141,18 @@ public abstract class KotlinIntegrationTestBase { System.out.print(event.getText()); } else if (outputType == ProcessOutputTypes.STDOUT) { - outContent.append("OUT "); - outContent.append(event.getText()); + appendToContent(outContent, "OUT ", event.getText()); } else if (outputType == ProcessOutputTypes.STDERR) { - errContent.append("ERR "); - errContent.append(event.getText()); + appendToContent(errContent, "ERR ", event.getText()); } } + + private void appendToContent(StringBuilder content, String prefix, String line) { + content.append(prefix); + content.append(StringUtil.trimTrailing(line)); + content.append("\n"); + } }); handler.startNotify(); @@ -129,7 +161,7 @@ public abstract class KotlinIntegrationTestBase { executionLog.append(outContent); executionLog.append(errContent); - executionLog.append("Return code: ").append(exitCode).append(SystemUtils.LINE_SEPARATOR); + executionLog.append("Return code: ").append(exitCode).append("\n"); return exitCode; } From 789ff0b273832d3208d5847fd02e50424ecca08d Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Mon, 23 Apr 2012 14:16:07 +0400 Subject: [PATCH 101/147] KT-1838 Constructor with a vararg Resolution for properties declared as primary constructor parameters used to ignore the varargs annotation. #KT-1838 Fixed --- .../org/jetbrains/jet/lang/resolve/DescriptorResolver.java | 3 +++ compiler/testData/diagnostics/tests/varargs/kt1838-param.jet | 5 +++++ compiler/testData/diagnostics/tests/varargs/kt1838-val.jet | 5 +++++ 3 files changed, 13 insertions(+) create mode 100644 compiler/testData/diagnostics/tests/varargs/kt1838-param.jet create mode 100644 compiler/testData/diagnostics/tests/varargs/kt1838-val.jet diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java index 8957a3588f3..86710ab25c9 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java @@ -431,6 +431,9 @@ public class DescriptorResolver { // Error is reported by the parser type = ErrorUtils.createErrorType("Annotation is absent"); } + if (parameter.hasModifier(JetTokens.VARARG_KEYWORD)) { + return getVarargParameterType(type); + } return type; } diff --git a/compiler/testData/diagnostics/tests/varargs/kt1838-param.jet b/compiler/testData/diagnostics/tests/varargs/kt1838-param.jet new file mode 100644 index 00000000000..607bbfd1ebb --- /dev/null +++ b/compiler/testData/diagnostics/tests/varargs/kt1838-param.jet @@ -0,0 +1,5 @@ +class A(vararg t : Int) { + { + val t1 : IntArray = t + } +} diff --git a/compiler/testData/diagnostics/tests/varargs/kt1838-val.jet b/compiler/testData/diagnostics/tests/varargs/kt1838-val.jet new file mode 100644 index 00000000000..ae719ee3d42 --- /dev/null +++ b/compiler/testData/diagnostics/tests/varargs/kt1838-val.jet @@ -0,0 +1,5 @@ +class A(vararg val t : Int) { + { + val t1 : IntArray = t + } +} From cde38382c038f349226a020d5f40df26fca7bb2f Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Sun, 22 Apr 2012 18:49:43 +0400 Subject: [PATCH 102/147] Fixed processing function type parameters in override/implement members. #KT-1603 fixed --- .../OverrideImplementMethodsHandler.java | 50 ++++++++++++++++--- .../functionWithTypeParameters.kt | 7 +++ .../functionWithTypeParameters.kt.after | 13 +++++ .../codeInsight/OverrideImplementTest.java | 4 ++ 4 files changed, 66 insertions(+), 8 deletions(-) create mode 100644 idea/testData/codeInsight/overrideImplement/functionWithTypeParameters.kt create mode 100644 idea/testData/codeInsight/overrideImplement/functionWithTypeParameters.kt.after diff --git a/idea/src/org/jetbrains/jet/plugin/codeInsight/OverrideImplementMethodsHandler.java b/idea/src/org/jetbrains/jet/plugin/codeInsight/OverrideImplementMethodsHandler.java index b82bc360996..f010af51727 100644 --- a/idea/src/org/jetbrains/jet/plugin/codeInsight/OverrideImplementMethodsHandler.java +++ b/idea/src/org/jetbrains/jet/plugin/codeInsight/OverrideImplementMethodsHandler.java @@ -24,6 +24,7 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Condition; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; @@ -33,15 +34,13 @@ import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.types.JetType; +import org.jetbrains.jet.lang.types.lang.JetStandardClasses; import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import org.jetbrains.jet.plugin.project.WholeProjectAnalyzerFacade; import org.jetbrains.jet.plugin.quickfix.ImportInsertHelper; import org.jetbrains.jet.resolve.DescriptorRenderer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; +import java.util.*; /** * @author yole @@ -145,7 +144,40 @@ public abstract class OverrideImplementMethodsHandler implements LanguageCodeIns private static JetElement overrideFunction(Project project, JetFile file, SimpleFunctionDescriptor descriptor) { StringBuilder bodyBuilder = new StringBuilder(); bodyBuilder.append(displayableVisibility(descriptor)); - bodyBuilder.append("override fun ").append(descriptor.getName()).append("("); + bodyBuilder.append("override fun "); + + List whereRestrictions = new ArrayList(); + if (!descriptor.getTypeParameters().isEmpty()) { + bodyBuilder.append("<"); + boolean first = true; + for (TypeParameterDescriptor param : descriptor.getTypeParameters()) { + if (!first) { + bodyBuilder.append(", "); + } + + bodyBuilder.append(param.getName()); + Set upperBounds = param.getUpperBounds(); + if (!upperBounds.isEmpty()) { + boolean firstUpperBound = true; + for (JetType upperBound : upperBounds) { + String upperBoundText = " : " + DescriptorRenderer.TEXT.renderTypeWithShortNames(upperBound); + if (upperBound != JetStandardClasses.getDefaultBound()) { + if (firstUpperBound) { + bodyBuilder.append(upperBoundText); + } else { + whereRestrictions.add(param.getName() + upperBoundText); + } + } + ImportInsertHelper.addImportDirectivesIfNeeded(upperBound, file); + firstUpperBound = false; + } + } + + first = false; + } + bodyBuilder.append("> "); + } + bodyBuilder.append(descriptor.getName()).append("("); boolean isAbstractFun = descriptor.getModality() == Modality.ABSTRACT; StringBuilder delegationBuilder = new StringBuilder(); if (isAbstractFun) { @@ -166,7 +198,7 @@ public abstract class OverrideImplementMethodsHandler implements LanguageCodeIns first = false; bodyBuilder.append(parameterDescriptor.getName()); bodyBuilder.append(" : "); - bodyBuilder.append(DescriptorRenderer.COMPACT.renderTypeWithShortNames(parameterDescriptor.getType())); + bodyBuilder.append(DescriptorRenderer.TEXT.renderTypeWithShortNames(parameterDescriptor.getType())); ImportInsertHelper.addImportDirectivesIfNeeded(parameterDescriptor.getType(), file); @@ -183,10 +215,12 @@ public abstract class OverrideImplementMethodsHandler implements LanguageCodeIns boolean returnsNotUnit = returnType != null && !stdlib.getTuple0Type().equals(returnType); if (returnsNotUnit) { - bodyBuilder.append(" : ").append(DescriptorRenderer.COMPACT.renderTypeWithShortNames(returnType)); + bodyBuilder.append(" : ").append(DescriptorRenderer.TEXT.renderTypeWithShortNames(returnType)); ImportInsertHelper.addImportDirectivesIfNeeded(returnType, file); } - + if (!whereRestrictions.isEmpty()) { + bodyBuilder.append("\n").append("where ").append(StringUtil.join(whereRestrictions, ", ")); + } bodyBuilder.append("{").append(returnsNotUnit && !isAbstractFun ? "return " : "").append(delegationBuilder.toString()).append("}"); return JetPsiFactory.createFunction(project, bodyBuilder.toString()); diff --git a/idea/testData/codeInsight/overrideImplement/functionWithTypeParameters.kt b/idea/testData/codeInsight/overrideImplement/functionWithTypeParameters.kt new file mode 100644 index 00000000000..699f1b7034a --- /dev/null +++ b/idea/testData/codeInsight/overrideImplement/functionWithTypeParameters.kt @@ -0,0 +1,7 @@ +trait Trait { + fun > foo() where B : Cloneable, B : Comparable; +} + +class TraitImpl : Trait { + +} \ No newline at end of file diff --git a/idea/testData/codeInsight/overrideImplement/functionWithTypeParameters.kt.after b/idea/testData/codeInsight/overrideImplement/functionWithTypeParameters.kt.after new file mode 100644 index 00000000000..eaf92a65bb1 --- /dev/null +++ b/idea/testData/codeInsight/overrideImplement/functionWithTypeParameters.kt.after @@ -0,0 +1,13 @@ +import java.util.Map + +trait Trait { + fun > foo() where B : Cloneable, B : Comparable; +} + +class TraitImpl : Trait { + + override fun > foo() + where B : Cloneable, B : Comparable { + throw UnsupportedOperationException() + } +} \ No newline at end of file diff --git a/idea/tests/org/jetbrains/jet/plugin/codeInsight/OverrideImplementTest.java b/idea/tests/org/jetbrains/jet/plugin/codeInsight/OverrideImplementTest.java index eb35f51df8f..fadfbc34b22 100644 --- a/idea/tests/org/jetbrains/jet/plugin/codeInsight/OverrideImplementTest.java +++ b/idea/tests/org/jetbrains/jet/plugin/codeInsight/OverrideImplementTest.java @@ -58,6 +58,10 @@ public class OverrideImplementTest extends LightCodeInsightFixtureTestCase { doImplementFileTest(); } + public void testFunctionWithTypeParameters() { + doImplementFileTest(); + } + public void testJavaInterfaceMethod() { doImplementDirectoryTest(); } From d9b04edcf80334dca5e16b195c515fcc97ac44fd Mon Sep 17 00:00:00 2001 From: Nikolay Krasko Date: Mon, 23 Apr 2012 17:58:18 +0400 Subject: [PATCH 103/147] EA-34996 Old assert that is difficult to maintain --- .../resolve/calls/ValueArgumentsToParametersMapper.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/ValueArgumentsToParametersMapper.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/ValueArgumentsToParametersMapper.java index e88d16dd086..6fd1de795c0 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/ValueArgumentsToParametersMapper.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/ValueArgumentsToParametersMapper.java @@ -33,9 +33,7 @@ import java.util.Set; import static org.jetbrains.jet.lang.diagnostics.Errors.*; import static org.jetbrains.jet.lang.resolve.BindingContext.REFERENCE_TARGET; -import static org.jetbrains.jet.lang.resolve.calls.ValueArgumentsToParametersMapper.Status.ERROR; -import static org.jetbrains.jet.lang.resolve.calls.ValueArgumentsToParametersMapper.Status.OK; -import static org.jetbrains.jet.lang.resolve.calls.ValueArgumentsToParametersMapper.Status.WEAK_ERROR; +import static org.jetbrains.jet.lang.resolve.calls.ValueArgumentsToParametersMapper.Status.*; /** * @author abreslav @@ -219,10 +217,6 @@ import static org.jetbrains.jet.lang.resolve.calls.ValueArgumentsToParametersMap status = ERROR; } - if (candidateCall.getThisObject().exists() != candidateCall.getResultingDescriptor().getExpectedThisObject().exists()) { - assert false : "Shouldn't happen because of TaskPrioritizer: " + candidateCall.getCandidateDescriptor(); - } - return status; } From 04143a2563fd907d6b210b218c87da148d9f028e Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Mon, 23 Apr 2012 17:24:04 +0400 Subject: [PATCH 104/147] Moved selectioners to separate package. --- idea/src/META-INF/plugin.xml | 4 ++-- .../{ => editor/wordSelection}/JetCodeBlockSelectioner.java | 2 +- .../wordSelection}/JetStatementGroupSelectioner.java | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) rename idea/src/org/jetbrains/jet/plugin/{ => editor/wordSelection}/JetCodeBlockSelectioner.java (98%) rename idea/src/org/jetbrains/jet/plugin/{ => editor/wordSelection}/JetStatementGroupSelectioner.java (98%) diff --git a/idea/src/META-INF/plugin.xml b/idea/src/META-INF/plugin.xml index 2abe60e579b..7f3404bb41f 100644 --- a/idea/src/META-INF/plugin.xml +++ b/idea/src/META-INF/plugin.xml @@ -133,8 +133,8 @@ - - + + diff --git a/idea/src/org/jetbrains/jet/plugin/JetCodeBlockSelectioner.java b/idea/src/org/jetbrains/jet/plugin/editor/wordSelection/JetCodeBlockSelectioner.java similarity index 98% rename from idea/src/org/jetbrains/jet/plugin/JetCodeBlockSelectioner.java rename to idea/src/org/jetbrains/jet/plugin/editor/wordSelection/JetCodeBlockSelectioner.java index 4165c9a182b..e961a52e7f5 100644 --- a/idea/src/org/jetbrains/jet/plugin/JetCodeBlockSelectioner.java +++ b/idea/src/org/jetbrains/jet/plugin/editor/wordSelection/JetCodeBlockSelectioner.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.jet.plugin; +package org.jetbrains.jet.plugin.editor.wordSelection; import com.intellij.codeInsight.editorActions.wordSelection.BasicSelectioner; import com.intellij.lang.ASTNode; diff --git a/idea/src/org/jetbrains/jet/plugin/JetStatementGroupSelectioner.java b/idea/src/org/jetbrains/jet/plugin/editor/wordSelection/JetStatementGroupSelectioner.java similarity index 98% rename from idea/src/org/jetbrains/jet/plugin/JetStatementGroupSelectioner.java rename to idea/src/org/jetbrains/jet/plugin/editor/wordSelection/JetStatementGroupSelectioner.java index 4d10cf5538e..f98999f0410 100644 --- a/idea/src/org/jetbrains/jet/plugin/JetStatementGroupSelectioner.java +++ b/idea/src/org/jetbrains/jet/plugin/editor/wordSelection/JetStatementGroupSelectioner.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.jetbrains.jet.plugin; +package org.jetbrains.jet.plugin.editor.wordSelection; import com.intellij.codeInsight.editorActions.wordSelection.BasicSelectioner; import com.intellij.openapi.editor.Editor; From 366079a96c490d6161df3a30679894485f011898 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Mon, 23 Apr 2012 17:59:58 +0400 Subject: [PATCH 105/147] Improved word selection for parameters and arguments. #KT-1657 fixed --- idea/src/META-INF/plugin.xml | 1 + .../wordSelection/JetListSelectioner.java | 56 +++++++++++++++++++ .../testData/wordSelection/TypeArguments.1.kt | 3 + idea/testData/wordSelection/TypeArguments.kt | 3 + .../wordSelection/TypeParameters.1.kt | 2 + idea/testData/wordSelection/TypeParameters.kt | 2 + .../wordSelection/ValueArguments.1.kt | 3 + idea/testData/wordSelection/ValueArguments.kt | 3 + .../wordSelection/ValueParameters.1.kt | 2 + .../testData/wordSelection/ValueParameters.kt | 2 + .../jet/plugin/WordSelectionTest.java | 16 ++++++ 11 files changed, 93 insertions(+) create mode 100644 idea/src/org/jetbrains/jet/plugin/editor/wordSelection/JetListSelectioner.java create mode 100644 idea/testData/wordSelection/TypeArguments.1.kt create mode 100644 idea/testData/wordSelection/TypeArguments.kt create mode 100644 idea/testData/wordSelection/TypeParameters.1.kt create mode 100644 idea/testData/wordSelection/TypeParameters.kt create mode 100644 idea/testData/wordSelection/ValueArguments.1.kt create mode 100644 idea/testData/wordSelection/ValueArguments.kt create mode 100644 idea/testData/wordSelection/ValueParameters.1.kt create mode 100644 idea/testData/wordSelection/ValueParameters.kt diff --git a/idea/src/META-INF/plugin.xml b/idea/src/META-INF/plugin.xml index 7f3404bb41f..20edfcd71ec 100644 --- a/idea/src/META-INF/plugin.xml +++ b/idea/src/META-INF/plugin.xml @@ -135,6 +135,7 @@ + diff --git a/idea/src/org/jetbrains/jet/plugin/editor/wordSelection/JetListSelectioner.java b/idea/src/org/jetbrains/jet/plugin/editor/wordSelection/JetListSelectioner.java new file mode 100644 index 00000000000..09ac4a416dd --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/editor/wordSelection/JetListSelectioner.java @@ -0,0 +1,56 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.plugin.editor.wordSelection; + +import com.intellij.codeInsight.editorActions.wordSelection.BasicSelectioner; +import com.intellij.lang.ASTNode; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.PsiElement; +import com.intellij.psi.tree.TokenSet; +import org.jetbrains.jet.lang.psi.JetParameterList; +import org.jetbrains.jet.lang.psi.JetTypeArgumentList; +import org.jetbrains.jet.lang.psi.JetTypeParameterList; +import org.jetbrains.jet.lang.psi.JetValueArgumentList; +import org.jetbrains.jet.lexer.JetTokens; + +import java.util.Arrays; +import java.util.List; + +/** + * @author Evgeny Gerashchenko + * @since 4/23/12 + */ +public class JetListSelectioner extends BasicSelectioner { + @Override + public boolean canSelect(PsiElement e) { + return e instanceof JetParameterList || e instanceof JetValueArgumentList || + e instanceof JetTypeParameterList || e instanceof JetTypeArgumentList; + } + + @Override + public List select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) { + ASTNode node = e.getNode(); + ASTNode startNode = node.findChildByType(TokenSet.create(JetTokens.LPAR, JetTokens.LT)); + ASTNode endNode = node.findChildByType(TokenSet.create(JetTokens.RPAR, JetTokens.GT)); + if (startNode != null && endNode != null) { + return Arrays.asList(new TextRange(startNode.getStartOffset() + 1, endNode.getStartOffset())); + } else { + return Arrays.asList(); + } + } +} diff --git a/idea/testData/wordSelection/TypeArguments.1.kt b/idea/testData/wordSelection/TypeArguments.1.kt new file mode 100644 index 00000000000..c2720afa24f --- /dev/null +++ b/idea/testData/wordSelection/TypeArguments.1.kt @@ -0,0 +1,3 @@ +fun foo() { + foo<Int, B>() +} diff --git a/idea/testData/wordSelection/TypeArguments.kt b/idea/testData/wordSelection/TypeArguments.kt new file mode 100644 index 00000000000..0585d99d48b --- /dev/null +++ b/idea/testData/wordSelection/TypeArguments.kt @@ -0,0 +1,3 @@ +fun foo() { + foo<Int, B>() +} diff --git a/idea/testData/wordSelection/TypeParameters.1.kt b/idea/testData/wordSelection/TypeParameters.1.kt new file mode 100644 index 00000000000..332865cfb5a --- /dev/null +++ b/idea/testData/wordSelection/TypeParameters.1.kt @@ -0,0 +1,2 @@ +fun <A, B> foo() { +} diff --git a/idea/testData/wordSelection/TypeParameters.kt b/idea/testData/wordSelection/TypeParameters.kt new file mode 100644 index 00000000000..d8509f74fdc --- /dev/null +++ b/idea/testData/wordSelection/TypeParameters.kt @@ -0,0 +1,2 @@ +fun B> foo() { +} diff --git a/idea/testData/wordSelection/ValueArguments.1.kt b/idea/testData/wordSelection/ValueArguments.1.kt new file mode 100644 index 00000000000..0078192e4dc --- /dev/null +++ b/idea/testData/wordSelection/ValueArguments.1.kt @@ -0,0 +1,3 @@ +fun foo() { + foo(1, 2) +} diff --git a/idea/testData/wordSelection/ValueArguments.kt b/idea/testData/wordSelection/ValueArguments.kt new file mode 100644 index 00000000000..54dee47384a --- /dev/null +++ b/idea/testData/wordSelection/ValueArguments.kt @@ -0,0 +1,3 @@ +fun foo() { + foo(1, 2) +} diff --git a/idea/testData/wordSelection/ValueParameters.1.kt b/idea/testData/wordSelection/ValueParameters.1.kt new file mode 100644 index 00000000000..df0a9e6bb58 --- /dev/null +++ b/idea/testData/wordSelection/ValueParameters.1.kt @@ -0,0 +1,2 @@ +fun foo(a : Array, b : Int) { +} diff --git a/idea/testData/wordSelection/ValueParameters.kt b/idea/testData/wordSelection/ValueParameters.kt new file mode 100644 index 00000000000..1105f741877 --- /dev/null +++ b/idea/testData/wordSelection/ValueParameters.kt @@ -0,0 +1,2 @@ +fun foo(a : Array, b : Int) { +} diff --git a/idea/tests/org/jetbrains/jet/plugin/WordSelectionTest.java b/idea/tests/org/jetbrains/jet/plugin/WordSelectionTest.java index 21c82df53b1..82c6031392e 100644 --- a/idea/tests/org/jetbrains/jet/plugin/WordSelectionTest.java +++ b/idea/tests/org/jetbrains/jet/plugin/WordSelectionTest.java @@ -35,6 +35,22 @@ public class WordSelectionTest extends LightCodeInsightFixtureTestCase { doTest(6); } + public void testTypeArguments() { + doTest(1); + } + + public void testValueArguments() { + doTest(1); + } + + public void testTypeParameters() { + doTest(1); + } + + public void testValueParameters() { + doTest(1); + } + private void doTest(int howMany) { String testName = getTestName(false); String[] afterFiles = new String[howMany]; From f7d9ecafe4f50e4d2f7ed6bdeeda4e9db4ff52cd Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Mon, 23 Apr 2012 18:04:12 +0400 Subject: [PATCH 106/147] Made overrides/implements mark tooltips more readable. --- .../jet/plugin/highlighter/JetLineMarkerProvider.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/highlighter/JetLineMarkerProvider.java b/idea/src/org/jetbrains/jet/plugin/highlighter/JetLineMarkerProvider.java index aac93f48e64..2767ea51553 100644 --- a/idea/src/org/jetbrains/jet/plugin/highlighter/JetLineMarkerProvider.java +++ b/idea/src/org/jetbrains/jet/plugin/highlighter/JetLineMarkerProvider.java @@ -92,12 +92,12 @@ public class JetLineMarkerProvider implements LineMarkerProvider { builder.append(DescriptorRenderer.HTML.render(descriptor)); int overrideCount = overriddenMembers.size(); if (overrideCount >= 1) { - builder.append(" ").append(implementsOrOverrides).append(" "); + builder.append("\n").append(implementsOrOverrides).append("\n"); builder.append(DescriptorRenderer.HTML.render(overriddenMembers.iterator().next())); } if (overrideCount > 1) { int count = overrideCount - 1; - builder.append(" and ").append(count).append(" other ").append(memberKind); + builder.append("\nand ").append(count).append(" other ").append(memberKind); if (count > 1) { builder.append("s"); } From 993bf650870d5ac691d30e24b7041a52bd092dce Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Mon, 23 Apr 2012 19:17:35 +0400 Subject: [PATCH 107/147] Providing reasonable information about compilation exceptions Self message, cause message and both position in the file under compilation and the executed file position are reported --- .../jet/codegen/CompilationException.java | 48 +++++++------------ 1 file changed, 16 insertions(+), 32 deletions(-) diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/CompilationException.java b/compiler/backend/src/org/jetbrains/jet/codegen/CompilationException.java index 017b499e327..4c7627c8ed6 100644 --- a/compiler/backend/src/org/jetbrains/jet/codegen/CompilationException.java +++ b/compiler/backend/src/org/jetbrains/jet/codegen/CompilationException.java @@ -16,10 +16,10 @@ package org.jetbrains.jet.codegen; -import com.intellij.openapi.editor.Document; -import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils; /** * @author alex.tkachman @@ -27,37 +27,14 @@ import com.intellij.psi.PsiFile; public class CompilationException extends RuntimeException { private PsiElement element; - CompilationException(String message, Throwable cause, PsiElement element) { + CompilationException(@NotNull String message, @Nullable Throwable cause, @NotNull PsiElement element) { super(message, cause); this.element = element; } - public PsiElement getElement() { - return element; - } - @Override public String toString() { - PsiFile psiFile = element.getContainingFile(); - TextRange textRange = element.getTextRange(); - Document document = psiFile.getViewProvider().getDocument(); - int line; - int col; - if (document != null) { - line = document.getLineNumber(textRange.getStartOffset()); - col = textRange.getStartOffset() - document.getLineStartOffset(line) + 1; - } - else { - line = -1; - col = -1; - } - - String s2 = ""; - Throwable cause = getCause(); - if (cause != null) { - s2 = cause.getMessage() != null ? cause.getMessage() : cause.toString(); - } - return "Internal error: (" + (line+1) + "," + col + ") " + s2 + "\n@" + where(); + return getMessage(); } private String where() { @@ -67,13 +44,20 @@ public class CompilationException extends RuntimeException { if (stackTrace != null && stackTrace.length > 0) { return stackTrace[0].getFileName() + ":" + stackTrace[0].getLineNumber(); } - else { - return "unknown"; - } + return "unknown"; } @Override public String getMessage() { - return this.toString(); + StringBuilder message = new StringBuilder("Back-end (JVM) Internal error: ").append(super.getMessage()).append("\n"); + Throwable cause = getCause(); + if (cause != null) { + String causeMessage = cause.getMessage(); + message.append("Cause: ").append(causeMessage == null ? cause.toString() : causeMessage).append("\n"); + } + message.append("File being compiled and position: ").append(DiagnosticUtils.atLocation(element)).append("\n"); + message.append("The root cause was thrown from: ").append(where()); + + return message.toString(); } } From 45d92bebc85bcc1cb414a2aa83989a7d741154f3 Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Mon, 23 Apr 2012 20:25:15 +0400 Subject: [PATCH 108/147] Inner classes are taken out to facilitate testing --- .../compiler/CompilerProcessListener.java | 222 ++++++++++++++++++ .../jet/plugin/compiler/JetCompiler.java | 221 +---------------- .../plugin/compiler/NullProcessHandler.java | 53 +++++ .../plugin/compiler/OutputItemsCollector.java | 24 ++ 4 files changed, 303 insertions(+), 217 deletions(-) create mode 100644 idea/src/org/jetbrains/jet/plugin/compiler/CompilerProcessListener.java create mode 100644 idea/src/org/jetbrains/jet/plugin/compiler/NullProcessHandler.java create mode 100644 idea/src/org/jetbrains/jet/plugin/compiler/OutputItemsCollector.java diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/CompilerProcessListener.java b/idea/src/org/jetbrains/jet/plugin/compiler/CompilerProcessListener.java new file mode 100644 index 00000000000..eff2687c2df --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/compiler/CompilerProcessListener.java @@ -0,0 +1,222 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.plugin.compiler; + +import com.intellij.execution.process.ProcessAdapter; +import com.intellij.execution.process.ProcessEvent; +import com.intellij.execution.process.ProcessOutputTypes; +import com.intellij.openapi.compiler.CompileContext; +import com.intellij.openapi.compiler.CompilerMessageCategory; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.util.Key; +import org.jetbrains.annotations.Nullable; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.intellij.openapi.compiler.CompilerMessageCategory.*; + +/** +* @author abreslav +*/ +public class CompilerProcessListener extends ProcessAdapter { + private static final Logger LOG = Logger.getInstance("#org.jetbrains.jet.plugin.compiler.CompilerProcessListener"); + + private static final Pattern DIAGNOSTIC_PATTERN = Pattern.compile("<(ERROR|WARNING|INFO|EXCEPTION|LOGGING)", Pattern.MULTILINE); + private static final Pattern OPEN_TAG_END_PATTERN = Pattern.compile(">", Pattern.MULTILINE | Pattern.DOTALL); + private static final Pattern ATTRIBUTE_PATTERN = Pattern.compile("\\s*(path|line|column)\\s*=\\s*\"(.*?)\"", Pattern.MULTILINE | Pattern.DOTALL); + private static final Pattern MESSAGE_PATTERN = Pattern.compile("(.*?)", Pattern.MULTILINE | Pattern.DOTALL); + + private enum State { + WAITING, ATTRIBUTES, MESSAGE + } + + private static class CompilerMessage { + private CompilerMessageCategory messageCategory; + private boolean isException; + private @Nullable String url; + private @Nullable Integer line; + private @Nullable Integer column; + private String message; + + public void setMessageCategoryFromString(String tagName) { + if ("ERROR".equals(tagName)) { + messageCategory = ERROR; + } + else if ("EXCEPTION".equals(tagName)) { + messageCategory = ERROR; + isException = true; + } + else if ("WARNING".equals(tagName)) { + messageCategory = WARNING; + } + else if ("LOGGING".equals(tagName)) { + messageCategory = STATISTICS; + } + else { + messageCategory = INFORMATION; + } + } + + public void setAttributeFromStrings(String name, String value) { + if ("path".equals(name)) { + url = "file://" + value.trim(); + } + else if ("line".equals(name)) { + line = safeParseInt(value); + } + else if ("column".equals(name)) { + column = safeParseInt(value); + } + } + + @Nullable + private static Integer safeParseInt(String value) { + try { + return Integer.parseInt(value.trim()); + } + catch (NumberFormatException e) { + return null; + } + } + + public void setMessage(String message) { + this.message = message; + } + + public void reportTo(CompileContext compileContext) { + if (messageCategory == STATISTICS) { + compileContext.getProgressIndicator().setText(message); + } + else { + compileContext.addMessage(messageCategory, message, url == null ? "" : url, line == null ? -1 : line, + column == null + ? -1 + : column); + if (isException) { + LOG.error(message); + } + } + } + } + + private final CompileContext compileContext; + private final OutputItemsCollector collector; + private final StringBuilder output = new StringBuilder(); + private int firstUnprocessedIndex = 0; + private State state = State.WAITING; + private CompilerMessage currentCompilerMessage; + + public CompilerProcessListener(CompileContext compileContext, OutputItemsCollector collector) { + this.compileContext = compileContext; + this.collector = collector; + } + + @Override + public void onTextAvailable(ProcessEvent event, Key outputType) { + String text = event.getText(); + if (outputType == ProcessOutputTypes.STDERR) { + output.append(text); + + // We loop until the state stabilizes + State lastState; + do { + lastState = state; + switch (state) { + case WAITING: { + Matcher matcher = matcher(DIAGNOSTIC_PATTERN); + if (find(matcher)) { + currentCompilerMessage = new CompilerMessage(); + currentCompilerMessage.setMessageCategoryFromString(matcher.group(1)); + state = State.ATTRIBUTES; + } + break; + } + case ATTRIBUTES: { + Matcher matcher = matcher(ATTRIBUTE_PATTERN); + int indexDelta = 0; + while (matcher.find()) { + handleSkippedOutput(output.subSequence(firstUnprocessedIndex + indexDelta, firstUnprocessedIndex + matcher.start())); + currentCompilerMessage.setAttributeFromStrings(matcher.group(1), matcher.group(2)); + indexDelta = matcher.end(); + + } + firstUnprocessedIndex += indexDelta; + + Matcher endMatcher = matcher(OPEN_TAG_END_PATTERN); + if (find(endMatcher)) { + state = State.MESSAGE; + } + break; + } + case MESSAGE: { + Matcher matcher = matcher(MESSAGE_PATTERN); + if (find(matcher)) { + String message = matcher.group(1); + currentCompilerMessage.setMessage(message); + currentCompilerMessage.reportTo(compileContext); + + if (currentCompilerMessage.messageCategory == STATISTICS) { + collector.learn(message); + } + + state = State.WAITING; + } + break; + } + } + } + while (state != lastState); + + } + else { + compileContext.addMessage(INFORMATION, text, "", -1, -1); + } + } + + private boolean find(Matcher matcher) { + boolean result = matcher.find(); + if (result) { + handleSkippedOutput(output.subSequence(firstUnprocessedIndex, firstUnprocessedIndex + matcher.start())); + firstUnprocessedIndex += matcher.end(); + } + return result; + } + + private Matcher matcher(Pattern pattern) { + return pattern.matcher(output.subSequence(firstUnprocessedIndex, output.length())); + } + + @Override + public void processTerminated(ProcessEvent event) { + if (firstUnprocessedIndex < output.length()) { + handleSkippedOutput(output.substring(firstUnprocessedIndex).trim()); + } + int exitCode = event.getExitCode(); + // 0 is normal, 1 is "errors found" - handled by the messages above + if (exitCode != 0 && exitCode != 1) { + compileContext.addMessage(ERROR, "Compiler terminated with exit code: " + exitCode, "", -1, -1); + } + } + + private void handleSkippedOutput(CharSequence substring) { + String message = substring.toString(); + if (!message.trim().isEmpty()) { + compileContext.addMessage(ERROR, message, "", -1, -1); + } + } +} diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java index 6e337505b1e..cc49331ef43 100644 --- a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java +++ b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java @@ -25,7 +25,6 @@ import com.intellij.execution.configurations.SimpleJavaParameters; import com.intellij.execution.process.*; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompileScope; -import com.intellij.openapi.compiler.CompilerMessageCategory; import com.intellij.openapi.compiler.TranslatingCompiler; import com.intellij.openapi.compiler.ex.CompileContextEx; import com.intellij.openapi.diagnostic.Logger; @@ -34,14 +33,12 @@ import com.intellij.openapi.projectRoots.JavaSdkType; import com.intellij.openapi.projectRoots.JdkUtil; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.SimpleJavaSdkType; -import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Chunk; import com.intellij.util.SystemProperties; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.plugin.JetFileType; import org.jetbrains.jet.utils.PathUtil; @@ -53,8 +50,6 @@ import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.Charset; import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import static com.intellij.openapi.compiler.CompilerMessageCategory.*; @@ -138,7 +133,7 @@ public class JetCompiler implements TranslatingCompiler { return; } - OutputItemsCollector collector = new OutputItemsCollector(outputDir.getPath()); + OutputItemsCollectorImpl collector = new OutputItemsCollectorImpl(outputDir.getPath()); if (RUN_OUT_OF_PROCESS) { runOutOfProcess(compileContext, collector, outputDir, kotlinHome, scriptFile); @@ -354,7 +349,7 @@ public class JetCompiler implements TranslatingCompiler { } } - private static class OutputItemsCollector { + public static class OutputItemsCollectorImpl implements OutputItemsCollector { private static final String FOR_SOURCE_PREFIX = "For source: "; private static final String EMITTING_PREFIX = "Emitting: "; private final String outputPath; @@ -362,10 +357,11 @@ public class JetCompiler implements TranslatingCompiler { private List answer = new ArrayList(); private List sources = new ArrayList(); - private OutputItemsCollector(String outputPath) { + public OutputItemsCollectorImpl(String outputPath) { this.outputPath = outputPath; } + @Override public void learn(String message) { message = message.trim(); if (message.startsWith(FOR_SOURCE_PREFIX)) { @@ -402,213 +398,4 @@ public class JetCompiler implements TranslatingCompiler { return path; } - - private static class NullProcessHandler extends ProcessHandler { - public static NullProcessHandler INSTANCE = new NullProcessHandler(); - @Override - protected void destroyProcessImpl() { - throw new UnsupportedOperationException("destroyProcessImpl is not implemented"); - } - - @Override - protected void detachProcessImpl() { - throw new UnsupportedOperationException("detachProcessImpl is not implemented"); // TODO - } - - @Override - public boolean detachIsDefault() { - throw new UnsupportedOperationException("detachIsDefault is not implemented"); - } - - @Override - public OutputStream getProcessInput() { - throw new UnsupportedOperationException("getProcessInput is not implemented"); - } - } - - private static class CompilerProcessListener extends ProcessAdapter { - private static final Pattern DIAGNOSTIC_PATTERN = Pattern.compile("<(ERROR|WARNING|INFO|EXCEPTION|LOGGING)", Pattern.MULTILINE); - private static final Pattern OPEN_TAG_END_PATTERN = Pattern.compile(">", Pattern.MULTILINE | Pattern.DOTALL); - private static final Pattern ATTRIBUTE_PATTERN = Pattern.compile("\\s*(path|line|column)\\s*=\\s*\"(.*?)\"", Pattern.MULTILINE | Pattern.DOTALL); - private static final Pattern MESSAGE_PATTERN = Pattern.compile("(.*?)", Pattern.MULTILINE | Pattern.DOTALL); - - private enum State { - WAITING, ATTRIBUTES, MESSAGE - } - - private static class CompilerMessage { - private CompilerMessageCategory messageCategory; - private boolean isException; - private @Nullable String url; - private @Nullable Integer line; - private @Nullable Integer column; - private String message; - - public void setMessageCategoryFromString(String tagName) { - if ("ERROR".equals(tagName)) { - messageCategory = ERROR; - } - else if ("EXCEPTION".equals(tagName)) { - messageCategory = ERROR; - isException = true; - } - else if ("WARNING".equals(tagName)) { - messageCategory = WARNING; - } - else if ("LOGGING".equals(tagName)) { - messageCategory = STATISTICS; - } - else { - messageCategory = INFORMATION; - } - } - - public void setAttributeFromStrings(String name, String value) { - if ("path".equals(name)) { - url = "file://" + value.trim(); - } - else if ("line".equals(name)) { - line = safeParseInt(value); - } - else if ("column".equals(name)) { - column = safeParseInt(value); - } - } - - @Nullable - private static Integer safeParseInt(String value) { - try { - return Integer.parseInt(value.trim()); - } - catch (NumberFormatException e) { - return null; - } - } - - public void setMessage(String message) { - this.message = message; - } - - public void reportTo(CompileContext compileContext) { - if (messageCategory == STATISTICS) { - compileContext.getProgressIndicator().setText(message); - } - else { - compileContext.addMessage(messageCategory, message, url == null ? "" : url, line == null ? -1 : line, - column == null - ? -1 - : column); - if (isException) { - LOG.error(message); - } - } - } - } - - private final CompileContext compileContext; - private final OutputItemsCollector collector; - private final StringBuilder output = new StringBuilder(); - private int firstUnprocessedIndex = 0; - private State state = State.WAITING; - private CompilerMessage currentCompilerMessage; - - public CompilerProcessListener(CompileContext compileContext, OutputItemsCollector collector) { - this.compileContext = compileContext; - this.collector = collector; - } - - @Override - public void onTextAvailable(ProcessEvent event, Key outputType) { - String text = event.getText(); - if (outputType == ProcessOutputTypes.STDERR) { - output.append(text); - - // We loop until the state stabilizes - State lastState; - do { - lastState = state; - switch (state) { - case WAITING: { - Matcher matcher = matcher(DIAGNOSTIC_PATTERN); - if (find(matcher)) { - currentCompilerMessage = new CompilerMessage(); - currentCompilerMessage.setMessageCategoryFromString(matcher.group(1)); - state = State.ATTRIBUTES; - } - break; - } - case ATTRIBUTES: { - Matcher matcher = matcher(ATTRIBUTE_PATTERN); - int indexDelta = 0; - while (matcher.find()) { - handleSkippedOutput(output.subSequence(firstUnprocessedIndex + indexDelta, firstUnprocessedIndex + matcher.start())); - currentCompilerMessage.setAttributeFromStrings(matcher.group(1), matcher.group(2)); - indexDelta = matcher.end(); - - } - firstUnprocessedIndex += indexDelta; - - Matcher endMatcher = matcher(OPEN_TAG_END_PATTERN); - if (find(endMatcher)) { - state = State.MESSAGE; - } - break; - } - case MESSAGE: { - Matcher matcher = matcher(MESSAGE_PATTERN); - if (find(matcher)) { - String message = matcher.group(1); - currentCompilerMessage.setMessage(message); - currentCompilerMessage.reportTo(compileContext); - - if (currentCompilerMessage.messageCategory == STATISTICS) { - collector.learn(message); - } - - state = State.WAITING; - } - break; - } - } - } - while (state != lastState); - - } - else { - compileContext.addMessage(INFORMATION, text, "", -1, -1); - } - } - - private boolean find(Matcher matcher) { - boolean result = matcher.find(); - if (result) { - handleSkippedOutput(output.subSequence(firstUnprocessedIndex, firstUnprocessedIndex + matcher.start())); - firstUnprocessedIndex += matcher.end(); - } - return result; - } - - private Matcher matcher(Pattern pattern) { - return pattern.matcher(output.subSequence(firstUnprocessedIndex, output.length())); - } - - @Override - public void processTerminated(ProcessEvent event) { - if (firstUnprocessedIndex < output.length()) { - handleSkippedOutput(output.substring(firstUnprocessedIndex).trim()); - } - int exitCode = event.getExitCode(); - // 0 is normal, 1 is "errors found" - handled by the messages above - if (exitCode != 0 && exitCode != 1) { - compileContext.addMessage(ERROR, "Compiler terminated with exit code: " + exitCode, "", -1, -1); - } - } - - private void handleSkippedOutput(CharSequence substring) { - String message = substring.toString(); - if (!message.trim().isEmpty()) { - compileContext.addMessage(ERROR, message, "", -1, -1); - } - } - } } diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/NullProcessHandler.java b/idea/src/org/jetbrains/jet/plugin/compiler/NullProcessHandler.java new file mode 100644 index 00000000000..1e97a38fd4b --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/compiler/NullProcessHandler.java @@ -0,0 +1,53 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.plugin.compiler; + +import com.intellij.execution.process.ProcessHandler; + +import java.io.OutputStream; + +/** + * @author max + * @author abreslav + */ +public class NullProcessHandler extends ProcessHandler { + public static final NullProcessHandler INSTANCE = new NullProcessHandler(); + + private NullProcessHandler() { + + } + + @Override + protected void destroyProcessImpl() { + throw new UnsupportedOperationException("destroyProcessImpl is not implemented"); + } + + @Override + protected void detachProcessImpl() { + throw new UnsupportedOperationException("detachProcessImpl is not implemented"); // TODO + } + + @Override + public boolean detachIsDefault() { + throw new UnsupportedOperationException("detachIsDefault is not implemented"); + } + + @Override + public OutputStream getProcessInput() { + throw new UnsupportedOperationException("getProcessInput is not implemented"); + } +} diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/OutputItemsCollector.java b/idea/src/org/jetbrains/jet/plugin/compiler/OutputItemsCollector.java new file mode 100644 index 00000000000..49bf2881b77 --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/compiler/OutputItemsCollector.java @@ -0,0 +1,24 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.plugin.compiler; + +/** + * @author abreslav + */ +public interface OutputItemsCollector { + void learn(String message); +} From 423920d4c05f5519f1476fe3d412ac760042c308 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Mon, 23 Apr 2012 22:43:52 +0400 Subject: [PATCH 109/147] Renamed FakeJetPsiClassRegressionTest to LibraryNavigationRegressionTest. --- ...nTest.java => LibraryNavigationRegressionTest.java} | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) rename idea/tests/org/jetbrains/jet/plugin/libraries/{FakeJetPsiClassRegressionTest.java => LibraryNavigationRegressionTest.java} (90%) diff --git a/idea/tests/org/jetbrains/jet/plugin/libraries/FakeJetPsiClassRegressionTest.java b/idea/tests/org/jetbrains/jet/plugin/libraries/LibraryNavigationRegressionTest.java similarity index 90% rename from idea/tests/org/jetbrains/jet/plugin/libraries/FakeJetPsiClassRegressionTest.java rename to idea/tests/org/jetbrains/jet/plugin/libraries/LibraryNavigationRegressionTest.java index da7bffa8e57..0f8350ffd24 100644 --- a/idea/tests/org/jetbrains/jet/plugin/libraries/FakeJetPsiClassRegressionTest.java +++ b/idea/tests/org/jetbrains/jet/plugin/libraries/LibraryNavigationRegressionTest.java @@ -25,12 +25,13 @@ import org.jetbrains.jet.plugin.JetLanguage; import org.jetbrains.jet.plugin.JetWithJdkAndRuntimeLightProjectDescriptor; /** - * This is a regression test against KT-1652 - * * @author Evgeny Gerashchenko * @since 3/27/12 */ -public class FakeJetPsiClassRegressionTest extends LightCodeInsightFixtureTestCase { +public class LibraryNavigationRegressionTest extends LightCodeInsightFixtureTestCase { + /** + * Regression test against KT-1652 + */ public void testRefToStdlib() { String text = "fun foo() { println() }"; myFixture.configureByText(JetFileType.INSTANCE, text); @@ -39,6 +40,9 @@ public class FakeJetPsiClassRegressionTest extends LightCodeInsightFixtureTestCa assertSame(JetLanguage.INSTANCE, ref.resolve().getNavigationElement().getLanguage()); } + /** + * Regression test against KT-1652 + */ public void testRefToJdk() { String text = "val x = java.util.HashMap().get(\"\")"; myFixture.configureByText(JetFileType.INSTANCE, text); From 8c2457195e5214fb2b4e3f4be123c1c537956bac Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Mon, 23 Apr 2012 23:08:43 +0400 Subject: [PATCH 110/147] Fixed bug when ctrl+click on ArrayList.add() and other stuff navigated to alt-headers. #KT-1815 fixed --- .../libraries/JetClsNavigationPolicy.java | 9 +++++++++ .../LibraryNavigationRegressionTest.java | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/idea/src/org/jetbrains/jet/plugin/libraries/JetClsNavigationPolicy.java b/idea/src/org/jetbrains/jet/plugin/libraries/JetClsNavigationPolicy.java index a36799df39f..b510306b353 100644 --- a/idea/src/org/jetbrains/jet/plugin/libraries/JetClsNavigationPolicy.java +++ b/idea/src/org/jetbrains/jet/plugin/libraries/JetClsNavigationPolicy.java @@ -34,6 +34,9 @@ public class JetClsNavigationPolicy implements ClsCustomNavigationPolicy { @Override @Nullable public PsiElement getNavigationElement(@NotNull ClsClassImpl clsClass) { + if (clsClass.getUserData(ClsClassImpl.DELEGATE_KEY) != null) { + return null; + } JetClass jetClass = (JetClass) getJetDeclarationByClsElement(clsClass); if (jetClass != null) { JetClass sourceClass = JetSourceNavigationHelper.getSourceClass(jetClass); @@ -47,6 +50,9 @@ public class JetClsNavigationPolicy implements ClsCustomNavigationPolicy { @Override @Nullable public PsiElement getNavigationElement(@NotNull ClsMethodImpl clsMethod) { + if (clsMethod.getParent().getUserData(ClsClassImpl.DELEGATE_KEY) != null) { + return null; + } JetDeclaration jetDeclaration = getJetDeclarationByClsElement(clsMethod); if (jetDeclaration instanceof JetProperty) { JetDeclaration sourceProperty = JetSourceNavigationHelper.getSourceProperty((JetProperty) jetDeclaration); @@ -66,6 +72,9 @@ public class JetClsNavigationPolicy implements ClsCustomNavigationPolicy { @Override @Nullable public PsiElement getNavigationElement(@NotNull ClsFieldImpl clsField) { + if (clsField.getParent().getUserData(ClsClassImpl.DELEGATE_KEY) != null) { + return null; + } return getJetDeclarationByClsElement(clsField); } diff --git a/idea/tests/org/jetbrains/jet/plugin/libraries/LibraryNavigationRegressionTest.java b/idea/tests/org/jetbrains/jet/plugin/libraries/LibraryNavigationRegressionTest.java index 0f8350ffd24..ac5873a882e 100644 --- a/idea/tests/org/jetbrains/jet/plugin/libraries/LibraryNavigationRegressionTest.java +++ b/idea/tests/org/jetbrains/jet/plugin/libraries/LibraryNavigationRegressionTest.java @@ -16,7 +16,11 @@ package org.jetbrains.jet.plugin.libraries; +import com.intellij.psi.JavaPsiFacade; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; +import com.intellij.psi.search.GlobalSearchScope; import com.intellij.testFramework.LightProjectDescriptor; import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; import org.jetbrains.annotations.NotNull; @@ -51,6 +55,20 @@ public class LibraryNavigationRegressionTest extends LightCodeInsightFixtureTest ref.resolve().getNavigationElement(); } + /** + * Regression test against KT-1815 + */ + public void testRefToAltHeaders() { + String text = "fun foo(e : java.util.Map.Entry) { e.getKey(); }"; + myFixture.configureByText(JetFileType.INSTANCE, text); + PsiReference ref = myFixture.getFile().findReferenceAt(text.indexOf("getKey")); + PsiClass expectedClass = + JavaPsiFacade.getInstance(getProject()).findClass("java.util.Map.Entry", GlobalSearchScope.allScope(getProject())); + //noinspection ConstantConditions + PsiElement actualClass = ref.resolve().getNavigationElement().getParent(); + assertSame(expectedClass, actualClass); + } + @NotNull @Override protected LightProjectDescriptor getProjectDescriptor() { From cc7284c67ec9e6f72861b298ac479295fdfa5a38 Mon Sep 17 00:00:00 2001 From: Evgeny Gerashchenko Date: Tue, 24 Apr 2012 17:50:57 +0400 Subject: [PATCH 111/147] Fixed failed assertions on navigating to 'Assertions' class of Kotlin runtime --- .../src/org/jetbrains/jet/resolve/DescriptorRenderer.java | 6 +++++- .../jet/plugin/libraries/JetClsNavigationPolicy.java | 7 ++----- .../jet/plugin/libraries/JetSourceNavigationHelper.java | 4 ++-- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java index 783499a34d0..98283823254 100644 --- a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java @@ -336,7 +336,11 @@ public class DescriptorRenderer implements Renderer { } private void renderVisibility(Visibility visibility, StringBuilder builder) { - builder.append(renderKeyword(visibility.toString())).append(" "); + if ("package".equals(visibility.toString())) { + builder.append("public/*package*/ "); + } else { + builder.append(renderKeyword(visibility.toString())).append(" "); + } } private void renderModality(Modality modality, StringBuilder builder) { diff --git a/idea/src/org/jetbrains/jet/plugin/libraries/JetClsNavigationPolicy.java b/idea/src/org/jetbrains/jet/plugin/libraries/JetClsNavigationPolicy.java index b510306b353..4c1b3181fa7 100644 --- a/idea/src/org/jetbrains/jet/plugin/libraries/JetClsNavigationPolicy.java +++ b/idea/src/org/jetbrains/jet/plugin/libraries/JetClsNavigationPolicy.java @@ -21,10 +21,7 @@ import com.intellij.psi.PsiElement; import com.intellij.psi.impl.compiled.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.lang.psi.JetClass; -import org.jetbrains.jet.lang.psi.JetDeclaration; -import org.jetbrains.jet.lang.psi.JetFunction; -import org.jetbrains.jet.lang.psi.JetProperty; +import org.jetbrains.jet.lang.psi.*; /** * @author Evgeny Gerashchenko @@ -39,7 +36,7 @@ public class JetClsNavigationPolicy implements ClsCustomNavigationPolicy { } JetClass jetClass = (JetClass) getJetDeclarationByClsElement(clsClass); if (jetClass != null) { - JetClass sourceClass = JetSourceNavigationHelper.getSourceClass(jetClass); + JetClassOrObject sourceClass = JetSourceNavigationHelper.getSourceClass(jetClass); if (sourceClass != null) { return sourceClass; } diff --git a/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java b/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java index 9ad91f710d9..ac8b9b55ed2 100644 --- a/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java +++ b/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java @@ -93,7 +93,7 @@ public class JetSourceNavigationHelper { } @Nullable - public static JetClass getSourceClass(@NotNull JetClass decompiledClass) { + public static JetClassOrObject getSourceClass(@NotNull JetClass decompiledClass) { Tuple2 bindingContextAndClassDescriptor = getBindingContextAndClassDescriptor(decompiledClass); if (bindingContextAndClassDescriptor == null) return null; PsiElement declaration = BindingContextUtils.classDescriptorToDeclaration( @@ -101,7 +101,7 @@ public class JetSourceNavigationHelper { if (declaration == null) { throw new IllegalStateException("class not found by " + bindingContextAndClassDescriptor._2); } - return (JetClass) declaration; + return (JetClassOrObject) declaration; } @NotNull From b62f49c9656b2db75e5a6f5d0a6ba21a75315bfe Mon Sep 17 00:00:00 2001 From: Nikolay Krasko Date: Tue, 24 Apr 2012 19:14:28 +0400 Subject: [PATCH 112/147] Some new icons - beta version --- .../jetbrains/jet/plugin/icons/class_kotlin.png | Bin 0 -> 1631 bytes .../org/jetbrains/jet/plugin/icons/kotlin.png | Bin 0 -> 1641 bytes .../org/jetbrains/jet/plugin/icons/kotlin_13.png | Bin 0 -> 1530 bytes .../plugin/icons/kotlin_launch_configuration.png | Bin 0 -> 1556 bytes idea/src/META-INF/plugin.xml | 2 +- .../jet/plugin/JetDescriptorIconProvider.java | 2 +- .../jetbrains/jet/plugin/JetIconProvider.java | 2 +- idea/src/org/jetbrains/jet/plugin/JetIcons.java | 3 +++ .../jet/plugin/actions/NewKotlinFileAction.java | 5 +++-- .../plugin/k2jsrun/K2JSRunConfigurationType.java | 4 ++-- .../jet/plugin/run/JetRunConfigurationType.java | 4 ++-- 11 files changed, 13 insertions(+), 9 deletions(-) create mode 100644 idea/resources/org/jetbrains/jet/plugin/icons/class_kotlin.png create mode 100644 idea/resources/org/jetbrains/jet/plugin/icons/kotlin.png create mode 100644 idea/resources/org/jetbrains/jet/plugin/icons/kotlin_13.png create mode 100644 idea/resources/org/jetbrains/jet/plugin/icons/kotlin_launch_configuration.png diff --git a/idea/resources/org/jetbrains/jet/plugin/icons/class_kotlin.png b/idea/resources/org/jetbrains/jet/plugin/icons/class_kotlin.png new file mode 100644 index 0000000000000000000000000000000000000000..84cfb2aadd53a98c531da986840dfeabeb5c943e GIT binary patch literal 1631 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`k|nMYCBgY=CFO}lsSJ)O`AMk? zp1FzXsX?iUDV2pMQ*9U+n3Xa^B1$5BeXNr6bM+EIYV;~{3xK*A7;Nk-3KEmEQ%e+* zQqwc@Y?a>c-mj#PnPRIHZt82`Ti~3Uk?B!Ylp0*+7m{3+ootz+WN)WnQ(*-(AUCxn zQK2F?C$HG5!d3}vt`(3C64qBz04piUwpD^SD#ABF!8yMuRl!uxKsVXI%uvD1M9IxIyg#@@$ndN=gc>^!3Zj z%k|2Q_413-^$jg8E%gnI^o@*kfhu&1EAvVcD|GXUm0>2hq!uR^WfqiV=I1GZOiWD5 zFD$Tv3bSNU;+l1ennz|zM-B0$V)JVzP|XC=H|jx7ncO3BHWAB;NpiyW)Z+ZoqGVvir744~DzI`cN=+=uFAB-e&w+(vKt_H^esM;Afr4|esh*)icxGNo zet9uiy|1s8XI^nhVqS8pr;Du;&;-5A%oHmlH$x)>Q$t4!S3^@nLsvs5H!~Aw7b8;_ zGgnJPBR3bAUYGpj(%jU%5}4i;gkC3{dO=Acw*Y9fOKMSOS!#+~QGTuh*vnR#xZPrb z(>$o&6x?pH#Hm*w=oo!a#3DsBObD2IKumbD1#;jCKQ#}S+KYh6dWw~v6$1m)WltB! zkcwMNf@3`<2TIg^|9|%F?`<=Ceg@CXu$a5dCpfS@%yAK{ zVVwV(m*K|Te_b1QnjV&3T$xdm_R;Ry*WBO(V&>Q7cN8xw%3tN8^5Ca4gB?phvx2t( zw@Kt~5hJg-d-*bcKXas5r?s3uWf!$9Z{?w+Ae{%ThZuMcO}ruHG&|!?u!`#xk!Q=7 zFIAo2FJBt$=z4bHA0|%42dtS5H;;x^T>8yar*qpuL&;&eHBV%gZbcIV=aQH;H>U^h z*s|r&kCa5tu1ix?1drq~`c!@Sp&7IL4$J4)402x|%}L8n zvp+cY;~&o#=Er(>ypMVud0e#O*QB}8zH{P=Sr7Sa?C%p^z@o49sV#X`)^6W|rJq#` zY|AD{TR+&cSS@*RsL635p1x?=JpHn-KNv+iy$X`H+q*mI_|&y7Ss^>CL+?hii9_38 zG4+(99l7_LXUp;I`IjIU6tJnt%d1Q4tNO!td)YVSZD*9ve^~WeGUM?)rr3KdK4-cT zQr>oCTTHqf^LEe0!$J{mYR`9za7B8p44bSMx`JcxLPn;NGZqth7WBxq{_9`)Va|OH zzsPqtZfpAY$Cl>Z_I^|S{UpydQFrIKb-Ns9u2JF)QcC&r;qt?b-&wNfCsmwz>~*Rv z`_ty`GVA;0`##C-|M5Nk#b!O7e&ucT%d&KNp2b;7#6?UxQ)B%4=%ELj&pdi_Y(=Kg ziJ#Zsui2m3rNp@Tsn6d{p`K4q^_^hL{i}O`;i-nk1bum(tDqv^)78&qol`;+0K$oK ANB{r; literal 0 HcmV?d00001 diff --git a/idea/resources/org/jetbrains/jet/plugin/icons/kotlin.png b/idea/resources/org/jetbrains/jet/plugin/icons/kotlin.png new file mode 100644 index 0000000000000000000000000000000000000000..403a4e89325e11e639da0e780f112536e41d2933 GIT binary patch literal 1641 zcmaJ>c~BE)91WKuBM?Qrs&)y3SS87B3`Z7%h6E&mL3 zBEOjUAYlI}-I?9*nD^fAdb7DQ`L&(Ed_R9VgfPo2IxvQgAmZs%ghE*oEfI$Tay_C$)hMD(Ti=BG zu~=3dEHZ|UQHH`ALeE3Y7@kp2GHe#hZ;6paG)X88#GyJ27jydRFLMA)E9OLdDnTVF zMH8^#jT9QOQ5C7#n4}SDIZONjKO@Wt=usL0jQV8U02{@eVO^Nno3HsCU>HIti8&vW zicy9EQi4JOPaeqCfL;*bCFDUuP$U$200IyK`H+AQdUGKV_Vk892pD-dOf*Ux536NC zBe9s1n3F)$B+Tchrl#^z7xM^8$A?5B5g!!r1p+RE;2P3!8ZmNlgX^e*3^iydjHEFF z2h55{9FancIZUP>OVE>JvbbTSO-#f1Mug-;JkVUyC{U^Vf2dwRhBnY@^i#h7DQt*L zBT>E@H4rJ3h8bMEt2q=2ODPng2`Z8xl1IB3mO#*iA%P$PX@n;a0-`ZoOQafx@k%8u z#|<=sYf!mN%wZIG7^a1V0TNK)BbE3BLP7`%ghUbuk_n|UFV7%ICV*t4Tp6KB(W5v$ z%GG}228_!!TR~4Uk!2`_Z9ug_6rl%(ONO!WbMYBhZ-lEIKNr!sTt1Tw-#plV4SMv7 zagTXBW?SYkW_%Q9+)gpJ&Nr1$XR$2r%4L#Bqv=>dZ0KHO&h^8N!Qrwl$}ds zaoMfKQN^pzu1smWxx=Kmn3(c2rZ0R-b_P~iA8o#h`^vyO&i!QBR1?R?UIvR-e8#qoZcGdLX!R zOYFHBVV}8_^*nl&KB;!a+6=)w9s4LYEl~>&I_9|Jy=MxHzlC2pUzPviV0=aA?7~x} zr4DBwt;Z?VS7^GGY~W<)-(8yBEDaF{#99Ve7X2 zO)FK@ys3Cs_1CX*y=E09cRkCF2uBJVcGR4R!Iqb}?0a`;$QESf>EttuTBRz;GCL~=}}db8eHWUl3bOYY?-2DZ>L~WVFffGH?<^D zp&~aYuh^=>Rtapb6_5=Q)>l#hD=EpgRf0Gw!Z$#{Ilm}X!Bo#cH`&0^~=l4 z^~#O)@{7{-4J|D#^$m>ljf`}GDs+o0^GXscbn}XpVJ5hw7AF^F7L;V>=P7_pOiaoz zEwNPsx)kDt+yc06!V;*iRM zRQ;gT;{4L0WMIUlDTAykuyQU+O)SYT3dzsUfrVl~Mt(_taYlZDf^)E`o}of`W?o8u zc`;bMudkJ7UU5lcUUI6Zi>(sS1ij466f0wA6C-m&3r7oALlZ+oS3^f<3nNQsM^|$v zS2sfgb4!?Bm;B_?+|;}hnBEkGUMHM-K}jLE0BEyIYEfocYKmJ?ey#%8%T}4V-C}{$ zJgD9j+-|YNsaGH97=2L0B1JSz2$*_6On9;da^ML+H4m8Di-5^Gtov6f0|Qf@r;B4q z#Vwypz8)fpGHf5x%hIP91M?G@Wj{lwUcgEaG>F}O^?cYBfdS5$F{GW&- zOYYrdTgQ*((N2py&+L+yTkMv1PeA^l{w4(%>`YCXA+8zwRyn{dZ5ck$_d^%Je# zr4ka6jUPT8Jk{M4-pbjhDdPHhgJ!?|iEuH+y-nv&uQUV-7^)}C+s%sbK8F4@XL3brdlLy zGQ4n1O<)FRlJO}GquJlo4hy{ZP@HViZagpDqA-DZU9F_UGH?Ib<}3TT3a7R$h)VZd zxAUq>yZFQdetWae2%MXj#u)ZqcG7~Hk4aUX2{U9=H8l1{%YV3YGKlq!AD8IuFV`bQ zQ}P(Qy&Wr(md@BF*FIfyd5_za{-`X0PK^nNg}&|DDJyba-^@1t;m6N2Hkc$UE|wDI zZ7)=vfBg8zm&KF24>34Il}+ZkeLP*WbGh{L54Wy0YVJz2ygRS9_UCW&z3i>W+O*!3 z7oKI){n+xSKdoEeG4qvET%_m{52cqS5xcKOEZP45t_71P@7B_(1)rvsEn2z#pW@lD zrcFxX-!7OeaX4e~KGv~r-{VzZ++WDo{O2r^>b<4hJ|Xq#yVs{L%yjxVV@+{WhLdZF zwwLB6CSTFVdQ&MBb@0N08>1ONa4 literal 0 HcmV?d00001 diff --git a/idea/resources/org/jetbrains/jet/plugin/icons/kotlin_launch_configuration.png b/idea/resources/org/jetbrains/jet/plugin/icons/kotlin_launch_configuration.png new file mode 100644 index 0000000000000000000000000000000000000000..ab1407bb717784b8fc88108b38befeed752cac0d GIT binary patch literal 1556 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`k|nMYCBgY=CFO}lsSJ)O`AMk? zp1FzXsX?iUDV2pMQ*9U+n3Xa^B1$5BeXNr6bM+EIYV;~{3xK*A7;Nk-3KEmEQ%e+* zQqwc@Y?a>c-mj#PnPRIHZt82`Ti~3Uk?B!Ylp0*+7m{3+ootz+WN)WnQ(*-(AUCxn zQK2F?C$HG5!d3}vt`(3C64qBz04piUwpD^SD#ABF!8yMuRl!uxKsVXI%uvD1M9IxIyg#@@$ndN=gc>^!3Zj z%k|2Q_413-^$jg8E%gnI^o@*kfhu&1EAvVcD|GXUm0>2hq!uR^WfqiV=I1GZOiWD5 zFD$Tv3bSNU;+l1ennz|zM-B0$V)JVzP|XC=H|jx7ncO3BHWAB;NpiyW)Z+ZoqGVvir744~DzI`cN=+=uFAB-e&w+(vKt_H^esM;Afr4|esh*)icxGNo zet9uiy|1s8XI^nhVqS8pr;Du;&;-5A%oHnAR~KV93l~QVS3^@nLsvs5b7wOr3l{@Z zBNGb?V<$tHUYGpj(%jU%5}4i;gkC3{dO=Acw*Y9fOKMSOS!#+~QGTuh*vnR#xZPrb z(>$o&6x?pH#Hm*w=oo!a#3DsBObD2IKumbD1#;jCKQ#}S+KYh6+F#|T3IhXEho_5U zNX4xslVd%C6J?Ig-~8Fozj%@HS^p*aDs$GIuv1vBV%n>xw1l7I)1qBHD+FG7aqe1u zdJmWKnv|*HKON(xvRHO{1ba*6re;}8FP?3E`=(|3^Eu}vO^iM()#%0DoBjWN?Y!qt z{a38&+IphFwChs8vUrqz?g{ObwLjTdSQP}=o%ZkqPEp|I)#(JDgy|(eu0UygjRjB43e4+fsSP4yl&MN(xMe?}u5e&@y?{GuKf} zHDSH$K{;;5r6K_#!jF`?4W=_rQaZ>f(so~}JDefK^{P&mI9q_@gIkX|eQG`&+IF(Z zd-)rK**yU*5-sJq7E-U59P)E~8k_gzE|1VjAyM818oxID)B5nNTIOl5`p3EyF{SM+ zMSlce+)KVO=VI#|9l%S|FQt#fbAy&>^&&l&J-n&+&GO6e)y_|H&n(Zh)^6(E zQDivx`I0Hk`%AYSX*PCBa!pqvN|0ENSoISka zCzqR$N56}qsY&y~mqB}!vKwPdZzOJg_{&*5t6O5z^iBHzTPyd+&wBgv%icF(ft%0I zGM3j+_ diff --git a/idea/src/org/jetbrains/jet/plugin/JetDescriptorIconProvider.java b/idea/src/org/jetbrains/jet/plugin/JetDescriptorIconProvider.java index 1317a34b943..862eea63b29 100644 --- a/idea/src/org/jetbrains/jet/plugin/JetDescriptorIconProvider.java +++ b/idea/src/org/jetbrains/jet/plugin/JetDescriptorIconProvider.java @@ -92,7 +92,7 @@ public final class JetDescriptorIconProvider { case OBJECT: return JetIcons.OBJECT; case CLASS: - return PlatformIcons.CLASS_ICON; + return JetIcons.CLASS; default: LOG.warn("No icon for descriptor: " + descriptor); return null; diff --git a/idea/src/org/jetbrains/jet/plugin/JetIconProvider.java b/idea/src/org/jetbrains/jet/plugin/JetIconProvider.java index a237db389ea..1449d48d69e 100644 --- a/idea/src/org/jetbrains/jet/plugin/JetIconProvider.java +++ b/idea/src/org/jetbrains/jet/plugin/JetIconProvider.java @@ -73,7 +73,7 @@ public class JetIconProvider extends IconProvider { return JetIcons.TRAIT; } - Icon icon = jetClass.hasModifier(JetTokens.ENUM_KEYWORD) ? PlatformIcons.ENUM_ICON : PlatformIcons.CLASS_ICON; + Icon icon = jetClass.hasModifier(JetTokens.ENUM_KEYWORD) ? PlatformIcons.ENUM_ICON : JetIcons.CLASS; if (jetClass instanceof JetEnumEntry) { JetEnumEntry enumEntry = (JetEnumEntry) jetClass; if (enumEntry.getPrimaryConstructorParameterList() == null) { diff --git a/idea/src/org/jetbrains/jet/plugin/JetIcons.java b/idea/src/org/jetbrains/jet/plugin/JetIcons.java index 8e9969cec3f..9b61eb3e9d6 100644 --- a/idea/src/org/jetbrains/jet/plugin/JetIcons.java +++ b/idea/src/org/jetbrains/jet/plugin/JetIcons.java @@ -26,6 +26,7 @@ import javax.swing.*; public interface JetIcons { Icon SMALL_LOGO = IconLoader.getIcon("/org/jetbrains/jet/plugin/icons/kotlin16x16.png"); + Icon CLASS = IconLoader.getIcon("/org/jetbrains/jet/plugin/icons/class_kotlin.png"); Icon FILE = SMALL_LOGO; // TODO: Add file icon Icon OBJECT = IconLoader.getIcon("/org/jetbrains/jet/plugin/icons/object.png"); Icon TRAIT = IconLoader.getIcon("/org/jetbrains/jet/plugin/icons/trait.png"); @@ -36,4 +37,6 @@ public interface JetIcons { Icon PARAMETER = IconLoader.getIcon("/org/jetbrains/jet/plugin/icons/parameter.png"); Icon FIELD_VAL = IconLoader.getIcon("/org/jetbrains/jet/plugin/icons/field_value.png"); Icon FIELD_VAR = IconLoader.getIcon("/org/jetbrains/jet/plugin/icons/field_variable.png"); + + Icon LAUNCH = IconLoader.getIcon("/org/jetbrains/jet/plugin/icons/kotlin_launch_configuration.png"); } diff --git a/idea/src/org/jetbrains/jet/plugin/actions/NewKotlinFileAction.java b/idea/src/org/jetbrains/jet/plugin/actions/NewKotlinFileAction.java index 1e1321f2836..31e7868df1e 100644 --- a/idea/src/org/jetbrains/jet/plugin/actions/NewKotlinFileAction.java +++ b/idea/src/org/jetbrains/jet/plugin/actions/NewKotlinFileAction.java @@ -23,6 +23,7 @@ import com.intellij.psi.PsiDirectory; import com.intellij.util.PlatformIcons; import org.jetbrains.jet.plugin.JetBundle; import org.jetbrains.jet.plugin.JetFileType; +import org.jetbrains.jet.plugin.JetIcons; /** * @author Nikolay Krasko @@ -37,8 +38,8 @@ public class NewKotlinFileAction extends CreateFileFromTemplateAction { builder .setTitle(JetBundle.message("new.kotlin.file.action")) .addKind("Kotlin file", JetFileType.INSTANCE.getIcon(), "Kotlin File") - .addKind("Class", PlatformIcons.CLASS_ICON, "Kotlin Class") - .addKind("Trait", PlatformIcons.INTERFACE_ICON, "Kotlin Trait") + .addKind("Class", JetIcons.CLASS, "Kotlin Class") + .addKind("Trait", JetIcons.TRAIT, "Kotlin Trait") .addKind("Enum class", PlatformIcons.ENUM_ICON, "Kotlin Enum"); } diff --git a/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfigurationType.java b/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfigurationType.java index f055c3a86ec..21bd928fa72 100644 --- a/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfigurationType.java +++ b/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfigurationType.java @@ -21,7 +21,7 @@ import com.intellij.execution.configurations.ConfigurationTypeBase; import com.intellij.execution.configurations.ConfigurationTypeUtil; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.project.Project; -import org.jetbrains.jet.plugin.JetFileType; +import org.jetbrains.jet.plugin.JetIcons; /** * @author Pavel Talanov @@ -32,7 +32,7 @@ public final class K2JSRunConfigurationType extends ConfigurationTypeBase { } public K2JSRunConfigurationType() { - super("K2JSConfigurationType", "K2JS", "Kotlin to Javascript configuration", JetFileType.INSTANCE.getIcon()); + super("K2JSConfigurationType", "K2JS", "Kotlin to Javascript configuration", JetIcons.LAUNCH); addFactory(new K2JSConfigurationFactory()); } diff --git a/idea/src/org/jetbrains/jet/plugin/run/JetRunConfigurationType.java b/idea/src/org/jetbrains/jet/plugin/run/JetRunConfigurationType.java index e698deed70c..8d08fb898b5 100644 --- a/idea/src/org/jetbrains/jet/plugin/run/JetRunConfigurationType.java +++ b/idea/src/org/jetbrains/jet/plugin/run/JetRunConfigurationType.java @@ -19,7 +19,7 @@ package org.jetbrains.jet.plugin.run; import com.intellij.execution.configurations.*; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.plugin.JetFileType; +import org.jetbrains.jet.plugin.JetIcons; /** * @author yole @@ -30,7 +30,7 @@ public class JetRunConfigurationType extends ConfigurationTypeBase { } public JetRunConfigurationType() { - super("JetRunConfigurationType", "Kotlin", "Kotlin", JetFileType.INSTANCE.getIcon()); + super("JetRunConfigurationType", "Kotlin", "Kotlin", JetIcons.LAUNCH); addFactory(new JetRunConfigurationFactory(this)); } From 419f8c74159f94b79bffa1754a6768ce7795ea57 Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Tue, 24 Apr 2012 20:02:05 +0400 Subject: [PATCH 113/147] Print a root tag in the XML output mode Now, the compiler output in the "-tags" mode is enclosed into ... --- .../org/jetbrains/jet/cli/KotlinCompiler.java | 128 ++++++++++-------- .../compiler/messages/MessageRenderer.java | 22 +++ 2 files changed, 91 insertions(+), 59 deletions(-) diff --git a/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java b/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java index 54a6eef6608..e679e3b7e20 100644 --- a/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java +++ b/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java @@ -77,7 +77,8 @@ public class KotlinCompiler { System.err.println("exec() finished with " + rc + " return code"); System.exit(rc.getCode()); } - } catch (CompileEnvironmentException e) { + } + catch (CompileEnvironmentException e) { System.err.println(e.getMessage()); System.exit(INTERNAL_ERROR.getCode()); } @@ -103,73 +104,82 @@ public class KotlinCompiler { final MessageRenderer messageRenderer = arguments.tags ? MessageRenderer.TAGS : MessageRenderer.PLAIN; - if (arguments.version) { - errStream.println(messageRenderer.render(CompilerMessageSeverity.INFO, "Kotlin Compiler version " + CompilerVersion.VERSION, CompilerMessageLocation.NO_LOCATION)); - } + errStream.print(messageRenderer.renderPreamble()); - CompilerSpecialMode mode = parseCompilerSpecialMode(arguments); - - File jdkHeadersJar; - if (mode.includeJdkHeaders()) { - if (arguments.jdkHeaders != null) { - jdkHeadersJar = new File(arguments.jdkHeaders); - } - else { - jdkHeadersJar = PathUtil.getAltHeadersPath(); - } - } - else { - jdkHeadersJar = null; - } - File runtimeJar; - - if (mode.includeKotlinRuntime()) { - if (arguments.stdlib != null) { - runtimeJar = new File(arguments.stdlib); - } - else { - runtimeJar = PathUtil.getDefaultRuntimePath(); - } - } - else { - runtimeJar = null; - } - - CompilerDependencies dependencies = new CompilerDependencies(mode, jdkHeadersJar, runtimeJar); - PrintingMessageCollector messageCollector = new PrintingMessageCollector(errStream, messageRenderer, arguments.verbose); - Disposable rootDisposable = CompileEnvironmentUtil.createMockDisposable(); - - JetCoreEnvironment environment = new JetCoreEnvironment(rootDisposable, dependencies); - CompileEnvironmentConfiguration configuration = new CompileEnvironmentConfiguration(environment, dependencies, messageCollector); try { - configureEnvironment(configuration, arguments); - - boolean noErrors; - if (arguments.module != null) { - noErrors = KotlinToJVMBytecodeCompiler.compileModuleScript(configuration, - arguments.module, arguments.jar, arguments.outputDir, - arguments.includeRuntime); + if (arguments.version) { + errStream.println(messageRenderer.render(CompilerMessageSeverity.INFO, "Kotlin Compiler version " + CompilerVersion.VERSION, CompilerMessageLocation.NO_LOCATION)); } - else { - // TODO ideally we'd unify to just having a single field that supports multiple files/dirs - if (arguments.getSourceDirs() != null) { - noErrors = KotlinToJVMBytecodeCompiler.compileBunchOfSourceDirectories(configuration, - arguments.getSourceDirs(), arguments.jar, arguments.outputDir, arguments.includeRuntime); + + CompilerSpecialMode mode = parseCompilerSpecialMode(arguments); + + File jdkHeadersJar; + if (mode.includeJdkHeaders()) { + if (arguments.jdkHeaders != null) { + jdkHeadersJar = new File(arguments.jdkHeaders); } else { - noErrors = KotlinToJVMBytecodeCompiler.compileBunchOfSources(configuration, - arguments.src, arguments.jar, arguments.outputDir, arguments.includeRuntime); + jdkHeadersJar = PathUtil.getAltHeadersPath(); } } - return noErrors ? OK : COMPILATION_ERROR; - } - catch (Throwable t) { - errStream.println(messageRenderer.renderException(t)); - return INTERNAL_ERROR; + else { + jdkHeadersJar = null; + } + File runtimeJar; + + if (mode.includeKotlinRuntime()) { + if (arguments.stdlib != null) { + runtimeJar = new File(arguments.stdlib); + } + else { + runtimeJar = PathUtil.getDefaultRuntimePath(); + } + } + else { + runtimeJar = null; + } + + CompilerDependencies dependencies = new CompilerDependencies(mode, jdkHeadersJar, runtimeJar); + PrintingMessageCollector messageCollector = new PrintingMessageCollector(errStream, messageRenderer, arguments.verbose); + Disposable rootDisposable = CompileEnvironmentUtil.createMockDisposable(); + + JetCoreEnvironment environment = new JetCoreEnvironment(rootDisposable, dependencies); + CompileEnvironmentConfiguration configuration = new CompileEnvironmentConfiguration(environment, dependencies, messageCollector); + + configuration.getMessageCollector().report(CompilerMessageSeverity.LOGGING, "Configuring the compilation environment", CompilerMessageLocation.NO_LOCATION); + try { + configureEnvironment(configuration, arguments); + + boolean noErrors; + if (arguments.module != null) { + noErrors = KotlinToJVMBytecodeCompiler.compileModuleScript(configuration, + arguments.module, arguments.jar, arguments.outputDir, + arguments.includeRuntime); + } + else { + // TODO ideally we'd unify to just having a single field that supports multiple files/dirs + if (arguments.getSourceDirs() != null) { + noErrors = KotlinToJVMBytecodeCompiler.compileBunchOfSourceDirectories(configuration, + arguments.getSourceDirs(), arguments.jar, arguments.outputDir, arguments.includeRuntime); + } + else { + noErrors = KotlinToJVMBytecodeCompiler.compileBunchOfSources(configuration, + arguments.src, arguments.jar, arguments.outputDir, arguments.includeRuntime); + } + } + return noErrors ? OK : COMPILATION_ERROR; + } + catch (Throwable t) { + errStream.println(messageRenderer.renderException(t)); + return INTERNAL_ERROR; + } + finally { + Disposer.dispose(rootDisposable); + messageCollector.printToErrStream(); + } } finally { - Disposer.dispose(rootDisposable); - messageCollector.printToErrStream(); + errStream.print(messageRenderer.renderConclusion()); } } diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageRenderer.java b/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageRenderer.java index acf7ec08e21..1324b5f9f47 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageRenderer.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageRenderer.java @@ -27,6 +27,11 @@ import java.io.StringWriter; public interface MessageRenderer { MessageRenderer TAGS = new MessageRenderer() { + @Override + public String renderPreamble() { + return ""; + } + @Override public String render(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location) { StringBuilder out = new StringBuilder(); @@ -48,9 +53,19 @@ public interface MessageRenderer { public String renderException(@NotNull Throwable e) { return render(CompilerMessageSeverity.EXCEPTION, PLAIN.renderException(e), CompilerMessageLocation.NO_LOCATION); } + + @Override + public String renderConclusion() { + return ""; + } }; MessageRenderer PLAIN = new MessageRenderer() { + @Override + public String renderPreamble() { + return ""; + } + @Override public String render(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location) { String path = location.getPath(); @@ -65,8 +80,15 @@ public interface MessageRenderer { e.printStackTrace(new PrintWriter(out)); return out.toString(); } + + @Override + public String renderConclusion() { + return ""; + } }; + String renderPreamble(); String render(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location); String renderException(@NotNull Throwable e); + String renderConclusion(); } From 2693fc1130ad0a9d1f32f68e3d48671078fcf34c Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Tue, 24 Apr 2012 20:05:34 +0400 Subject: [PATCH 114/147] Using a SAX parser for compiler output The previous version of the output processing algorithm was quadratic in the size of a message which manifested in the case of a long stack trace of an internal error. Now we use a SAX parser that processes its input in linear time and notifies the environment as it goes. --- .../jet/plugin/compiler/JetCompiler.java | 165 ++++++++++++++---- 1 file changed, 134 insertions(+), 31 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java index cc49331ef43..ae73873f46c 100644 --- a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java +++ b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java @@ -16,15 +16,18 @@ package org.jetbrains.jet.plugin.compiler; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.intellij.compiler.impl.javaCompiler.ModuleChunk; import com.intellij.compiler.impl.javaCompiler.OutputItemImpl; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.SimpleJavaParameters; -import com.intellij.execution.process.*; +import com.intellij.execution.process.ProcessAdapter; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompileScope; +import com.intellij.openapi.compiler.CompilerMessageCategory; import com.intellij.openapi.compiler.TranslatingCompiler; import com.intellij.openapi.compiler.ex.CompileContextEx; import com.intellij.openapi.diagnostic.Logger; @@ -39,16 +42,22 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Chunk; import com.intellij.util.SystemProperties; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.plugin.JetFileType; import org.jetbrains.jet.utils.PathUtil; +import org.xml.sax.Attributes; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; import java.io.*; import java.lang.ref.SoftReference; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; -import java.nio.charset.Charset; import java.util.*; import static com.intellij.openapi.compiler.CompilerMessageCategory.*; @@ -230,29 +239,32 @@ public class JetCompiler implements TranslatingCompiler { return answer; } - private void runInProcess(CompileContext compileContext, OutputItemsCollector collector, VirtualFile outputDir, File kotlinHome, File scriptFile) { + private void runInProcess(final CompileContext compileContext, OutputItemsCollector collector, VirtualFile outputDir, File kotlinHome, File scriptFile) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream out = new PrintStream(outputStream); - int rc = execInProcess(kotlinHome, outputDir, scriptFile, out, compileContext); - - ProcessAdapter listener = createProcessListener(compileContext, collector); + int exitCode = execInProcess(kotlinHome, outputDir, scriptFile, out, compileContext); BufferedReader reader = new BufferedReader(new StringReader(outputStream.toString())); - while (true) { - try { - String line = reader.readLine(); - if (line == null) break; - listener.onTextAvailable(new ProcessEvent(NullProcessHandler.INSTANCE, line + "\n"), ProcessOutputTypes.STDERR); - } catch (IOException e) { - // Can't be - throw new IllegalStateException(e); - } - } + parseCompilerMessagesFromReader(compileContext, reader); + handleProcessTermination(exitCode, compileContext); + } - ProcessEvent termintationEvent = new ProcessEvent(NullProcessHandler.INSTANCE, rc); - listener.processWillTerminate(termintationEvent, false); - listener.processTerminated(termintationEvent); + private static void parseCompilerMessagesFromReader(CompileContext compileContext, Reader reader) { + try { + SAXParserFactory factory = SAXParserFactory.newInstance(); + SAXParser parser = factory.newSAXParser(); + parser.parse(new InputSource(reader), new CompilerOutputSAXHandler(compileContext)); + } + catch (Throwable e) { + LOG.error(e); + } + } + + private static void handleProcessTermination(int exitCode, CompileContext compileContext) { + if (exitCode != 0 && exitCode != 1) { + compileContext.addMessage(ERROR, "Compiler terminated with exit code: " + exitCode, "", -1, -1); + } } private static int execInProcess(File kotlinHome, VirtualFile outputDir, File scriptFile, PrintStream out, CompileContext context) { @@ -307,7 +319,7 @@ public class JetCompiler implements TranslatingCompiler { return new URLClassLoader(urls, null); } - private static void runOutOfProcess(CompileContext compileContext, OutputItemsCollector collector, VirtualFile outputDir, File kotlinHome, File scriptFile) { + private static void runOutOfProcess(final CompileContext compileContext, OutputItemsCollector collector, VirtualFile outputDir, File kotlinHome, File scriptFile) { final SimpleJavaParameters params = new SimpleJavaParameters(); params.setJdk(new SimpleJavaSdkType().createJdk("tmp", SystemProperties.getJavaHome())); params.setMainClass("org.jetbrains.jet.cli.KotlinCompiler"); @@ -331,19 +343,33 @@ public class JetCompiler implements TranslatingCompiler { compileContext.addMessage(INFORMATION, "Invoking out-of-process compiler with arguments: " + commandLine, "", -1, -1); try { - final OSProcessHandler processHandler = new OSProcessHandler(commandLine.createProcess(), commandLine.getCommandLineString()) { - @Override - public Charset getCharset() { - return commandLine.getCharset(); - } - }; + Process process = commandLine.createProcess(); + final InputStream err = process.getErrorStream(); + final InputStream out = process.getInputStream(); - ProcessAdapter processListener = createProcessListener(compileContext, collector); - processHandler.addProcessListener(processListener); + ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { + @Override + public void run() { + parseCompilerMessagesFromReader(compileContext, new InputStreamReader(out)); + } + }); - processHandler.startNotify(); - processHandler.waitFor(); - } catch (Exception e) { + ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { + @Override + public void run() { + try { + FileUtil.loadBytes(err); + } + catch (IOException e) { + // Don't care + } + } + }); + + process.waitFor(); + handleProcessTermination(process.exitValue(), compileContext); + } + catch (Exception e) { compileContext.addMessage(ERROR, "[Internal Error] " + e.getLocalizedMessage(), "", -1, -1); return; } @@ -398,4 +424,81 @@ public class JetCompiler implements TranslatingCompiler { return path; } + + private static class CompilerOutputSAXHandler extends DefaultHandler { + private static final Map CATEGORIES = ImmutableMap.builder() + .put("error", CompilerMessageCategory.ERROR) + .put("warning", CompilerMessageCategory.WARNING) + .put("logging", CompilerMessageCategory.STATISTICS) + .put("exception", CompilerMessageCategory.ERROR) + .put("info", CompilerMessageCategory.INFORMATION) + .put("messages", CompilerMessageCategory.INFORMATION) // Root XML element + .build(); + + private final CompileContext compileContext; + + private final StringBuilder message = new StringBuilder(); + private Stack tags = new Stack(); + private String path; + private int line; + private int column; + + public CompilerOutputSAXHandler(CompileContext compileContext) { + this.compileContext = compileContext; + } + + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { + tags.push(qName); + + message.setLength(0); + + path = attributes.getValue("path"); + line = safeParseInt(attributes.getValue("line"), -1); + column = safeParseInt(attributes.getValue("column"), -1); + } + + @Override + public void characters(char[] ch, int start, int length) throws SAXException { + if (tags.size() == 1) { + // We're directly inside the root tag: + String message = new String(ch, start, length); + if (!message.trim().isEmpty()) { + compileContext.addMessage(ERROR, "Unhandled compiler output: " + message, null, -1, -1); + } + } + else { + message.append(ch, start, length); + } + } + + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + CompilerMessageCategory category = CATEGORIES.get(qName.toLowerCase()); + if (category == null) { + compileContext.addMessage(ERROR, "Unknown compiler message tag: " + qName, null, -1, -1); + category = INFORMATION; + } + String text = message.toString(); + if (category == STATISTICS) { + compileContext.getProgressIndicator().setText(text); + } + else { + compileContext.addMessage(category, text, path, line, column); + } + tags.pop(); + } + + private static int safeParseInt(@Nullable String value, int defaultValue) { + if (value == null) { + return defaultValue; + } + try { + return Integer.parseInt(value.trim()); + } + catch (NumberFormatException e) { + return defaultValue; + } + } + } } From d1a6c3e7f50f0c5fbb550c7c4e72b4496eff0415 Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Tue, 24 Apr 2012 20:15:42 +0400 Subject: [PATCH 115/147] Unused class removed --- .../plugin/compiler/NullProcessHandler.java | 53 ------------------- 1 file changed, 53 deletions(-) delete mode 100644 idea/src/org/jetbrains/jet/plugin/compiler/NullProcessHandler.java diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/NullProcessHandler.java b/idea/src/org/jetbrains/jet/plugin/compiler/NullProcessHandler.java deleted file mode 100644 index 1e97a38fd4b..00000000000 --- a/idea/src/org/jetbrains/jet/plugin/compiler/NullProcessHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.plugin.compiler; - -import com.intellij.execution.process.ProcessHandler; - -import java.io.OutputStream; - -/** - * @author max - * @author abreslav - */ -public class NullProcessHandler extends ProcessHandler { - public static final NullProcessHandler INSTANCE = new NullProcessHandler(); - - private NullProcessHandler() { - - } - - @Override - protected void destroyProcessImpl() { - throw new UnsupportedOperationException("destroyProcessImpl is not implemented"); - } - - @Override - protected void detachProcessImpl() { - throw new UnsupportedOperationException("detachProcessImpl is not implemented"); // TODO - } - - @Override - public boolean detachIsDefault() { - throw new UnsupportedOperationException("detachIsDefault is not implemented"); - } - - @Override - public OutputStream getProcessInput() { - throw new UnsupportedOperationException("getProcessInput is not implemented"); - } -} From ef90a333ba4bfee122524fc3fa76a7f96fb67bd7 Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Tue, 24 Apr 2012 20:18:30 +0400 Subject: [PATCH 116/147] Prefix paths with the "file://" protocol This is required for error positioning --- idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java index ae73873f46c..d0b9ab3d1fe 100644 --- a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java +++ b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java @@ -453,7 +453,8 @@ public class JetCompiler implements TranslatingCompiler { message.setLength(0); - path = attributes.getValue("path"); + String rawPath = attributes.getValue("path"); + path = rawPath == null ? null : "file://" + rawPath; line = safeParseInt(attributes.getValue("line"), -1); column = safeParseInt(attributes.getValue("column"), -1); } From e6709ab27241ffa58a9528821855a21efb7cb294 Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Tue, 24 Apr 2012 20:43:51 +0400 Subject: [PATCH 117/147] Putting back the support for incremental compilation --- .../jet/plugin/compiler/JetCompiler.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java index d0b9ab3d1fe..856cbe6b94c 100644 --- a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java +++ b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java @@ -246,15 +246,15 @@ public class JetCompiler implements TranslatingCompiler { int exitCode = execInProcess(kotlinHome, outputDir, scriptFile, out, compileContext); BufferedReader reader = new BufferedReader(new StringReader(outputStream.toString())); - parseCompilerMessagesFromReader(compileContext, reader); + parseCompilerMessagesFromReader(compileContext, reader, collector); handleProcessTermination(exitCode, compileContext); } - private static void parseCompilerMessagesFromReader(CompileContext compileContext, Reader reader) { + private static void parseCompilerMessagesFromReader(CompileContext compileContext, Reader reader, OutputItemsCollector collector) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); - parser.parse(new InputSource(reader), new CompilerOutputSAXHandler(compileContext)); + parser.parse(new InputSource(reader), new CompilerOutputSAXHandler(compileContext, collector)); } catch (Throwable e) { LOG.error(e); @@ -319,7 +319,7 @@ public class JetCompiler implements TranslatingCompiler { return new URLClassLoader(urls, null); } - private static void runOutOfProcess(final CompileContext compileContext, OutputItemsCollector collector, VirtualFile outputDir, File kotlinHome, File scriptFile) { + private static void runOutOfProcess(final CompileContext compileContext, final OutputItemsCollector collector, VirtualFile outputDir, File kotlinHome, File scriptFile) { final SimpleJavaParameters params = new SimpleJavaParameters(); params.setJdk(new SimpleJavaSdkType().createJdk("tmp", SystemProperties.getJavaHome())); params.setMainClass("org.jetbrains.jet.cli.KotlinCompiler"); @@ -350,7 +350,7 @@ public class JetCompiler implements TranslatingCompiler { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { @Override public void run() { - parseCompilerMessagesFromReader(compileContext, new InputStreamReader(out)); + parseCompilerMessagesFromReader(compileContext, new InputStreamReader(out), collector); } }); @@ -436,6 +436,7 @@ public class JetCompiler implements TranslatingCompiler { .build(); private final CompileContext compileContext; + private final OutputItemsCollector collector; private final StringBuilder message = new StringBuilder(); private Stack tags = new Stack(); @@ -443,8 +444,9 @@ public class JetCompiler implements TranslatingCompiler { private int line; private int column; - public CompilerOutputSAXHandler(CompileContext compileContext) { + public CompilerOutputSAXHandler(CompileContext compileContext, OutputItemsCollector collector) { this.compileContext = compileContext; + this.collector = collector; } @Override @@ -483,6 +485,8 @@ public class JetCompiler implements TranslatingCompiler { String text = message.toString(); if (category == STATISTICS) { compileContext.getProgressIndicator().setText(text); + collector.learn(text); + System.out.println(text); } else { compileContext.addMessage(category, text, path, line, column); From 8a40f943defbba81544772171b63c9a72e2af3be Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Tue, 24 Apr 2012 20:48:53 +0400 Subject: [PATCH 118/147] Module script loading separated from module compilation --- .../jet/buildtools/core/BytecodeCompiler.java | 4 +-- .../org/jetbrains/jet/cli/KotlinCompiler.java | 8 +++--- .../jet/compiler/CompileEnvironmentUtil.java | 27 ++++++++----------- .../compiler/KotlinToJVMBytecodeCompiler.java | 13 +++------ 4 files changed, 21 insertions(+), 31 deletions(-) diff --git a/build-tools/core/src/org/jetbrains/jet/buildtools/core/BytecodeCompiler.java b/build-tools/core/src/org/jetbrains/jet/buildtools/core/BytecodeCompiler.java index 8617f13f719..0f35310a117 100644 --- a/build-tools/core/src/org/jetbrains/jet/buildtools/core/BytecodeCompiler.java +++ b/build-tools/core/src/org/jetbrains/jet/buildtools/core/BytecodeCompiler.java @@ -128,7 +128,7 @@ public class BytecodeCompiler { /** - * {@code CompileEnvironment#compileModuleScript} wrapper. + * {@code CompileEnvironment#compileModules} wrapper. * * @param module compilation module file * @param jar compilation destination jar @@ -139,7 +139,7 @@ public class BytecodeCompiler { public void moduleToJar ( @NotNull String module, @NotNull String jar, boolean includeRuntime, @Nullable String stdlib, @Nullable String[] classpath ) { try { CompileEnvironmentConfiguration env = env(stdlib, classpath); - boolean success = KotlinToJVMBytecodeCompiler.compileModuleScript(env, module, jar, null, includeRuntime); + boolean success = KotlinToJVMBytecodeCompiler.compileModules(env, module, jar, null, includeRuntime); if ( ! success ) { throw new CompileEnvironmentException( errorMessage( module, false )); } diff --git a/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java b/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java index e679e3b7e20..09b5e719567 100644 --- a/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java +++ b/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java @@ -23,6 +23,7 @@ import com.google.common.collect.Multimap; import com.intellij.openapi.Disposable; import com.intellij.openapi.util.Disposer; import com.sampullara.cli.Args; +import jet.modules.Module; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.compiler.*; import org.jetbrains.jet.compiler.messages.CompilerMessageLocation; @@ -152,9 +153,10 @@ public class KotlinCompiler { boolean noErrors; if (arguments.module != null) { - noErrors = KotlinToJVMBytecodeCompiler.compileModuleScript(configuration, - arguments.module, arguments.jar, arguments.outputDir, - arguments.includeRuntime); + List modules = CompileEnvironmentUtil.loadModuleScript(arguments.module, configuration.getMessageCollector()); + noErrors = KotlinToJVMBytecodeCompiler.compileModules(configuration, modules, + arguments.module, arguments.jar, arguments.outputDir, + arguments.includeRuntime); } else { // TODO ideally we'd unify to just having a single field that supports multiple files/dirs diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentUtil.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentUtil.java index ca803c0549f..26541ca6554 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentUtil.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentUtil.java @@ -78,10 +78,6 @@ public class CompileEnvironmentUtil { return null; } - //public static void ensureRuntime(@NotNull JetCoreEnvironment env) { - // ensureJdkRuntime(env); - //} - public static void ensureKotlinRuntime(JetCoreEnvironment env) { if (JavaPsiFacade.getInstance(env.getProject()).findClass("jet.JetObject", GlobalSearchScope.allScope(env.getProject())) == null) { // TODO: prepend @@ -151,16 +147,7 @@ public class CompileEnvironmentUtil { } } - //private CompileEnvironment copyEnvironment(boolean verbose) { - // CompileEnvironment compileEnvironment = new CompileEnvironment(messageRenderer, verbose, compilerDependencies); - // compileEnvironment.setIgnoreErrors(ignoreErrors); - // compileEnvironment.setErrorStream(errorStream); - // // copy across any compiler plugins - // compileEnvironment.getEnvironment().getCompilerPlugins().addAll(environment.getCompilerPlugins()); - // return compileEnvironment; - //} - // - public static List loadModuleScript(String moduleFile, MessageCollector messageCollector) { + public static List loadModuleScript(String moduleScriptFile, MessageCollector messageCollector) { Disposable disposable = new Disposable() { @Override public void dispose() { @@ -170,7 +157,7 @@ public class CompileEnvironmentUtil { CompilerDependencies dependencies = CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR); JetCoreEnvironment scriptEnvironment = new JetCoreEnvironment(disposable, dependencies); ensureRuntime(scriptEnvironment, dependencies); - scriptEnvironment.addSources(moduleFile); + scriptEnvironment.addSources(moduleScriptFile); GenerationState generationState = KotlinToJVMBytecodeCompiler .analyzeAndGenerate(new CompileEnvironmentConfiguration(scriptEnvironment, dependencies, messageCollector), false); @@ -178,9 +165,17 @@ public class CompileEnvironmentUtil { return null; } - List modules = runDefineModules(dependencies, moduleFile, generationState.getFactory()); + List modules = runDefineModules(dependencies, moduleScriptFile, generationState.getFactory()); Disposer.dispose(disposable); + + if (modules == null) { + throw new CompileEnvironmentException("Module script " + moduleScriptFile + " compilation failed"); + } + + if (modules.isEmpty()) { + throw new CompileEnvironmentException("No modules where defined by " + moduleScriptFile); + } return modules; } diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java b/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java index 324b7740a4e..8244b165dd1 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java @@ -98,22 +98,15 @@ public class KotlinToJVMBytecodeCompiler { return generationState.getFactory(); } - public static boolean compileModuleScript( + public static boolean compileModules( CompileEnvironmentConfiguration configuration, + @NotNull List modules, + @NotNull String moduleScriptFile, @Nullable String jarPath, @Nullable String outputDir, boolean jarRuntime) { - List modules = CompileEnvironmentUtil.loadModuleScript(moduleScriptFile, configuration.getMessageCollector()); - - if (modules == null) { - throw new CompileEnvironmentException("Module script " + moduleScriptFile + " compilation failed"); - } - - if (modules.isEmpty()) { - throw new CompileEnvironmentException("No modules where defined by " + moduleScriptFile); - } final String directory = new File(moduleScriptFile).getParent(); for (Module moduleBuilder : modules) { From 0ab212b240fbee33f277af70a376fc6106b1436b Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Tue, 24 Apr 2012 20:52:48 +0400 Subject: [PATCH 119/147] Module file is not needed when compiling modules --- compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java | 3 ++- .../jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java | 5 ++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java b/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java index 09b5e719567..dec77e75f06 100644 --- a/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java +++ b/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java @@ -154,8 +154,9 @@ public class KotlinCompiler { boolean noErrors; if (arguments.module != null) { List modules = CompileEnvironmentUtil.loadModuleScript(arguments.module, configuration.getMessageCollector()); + File directory = new File(arguments.module).getParentFile(); noErrors = KotlinToJVMBytecodeCompiler.compileModules(configuration, modules, - arguments.module, arguments.jar, arguments.outputDir, + directory, arguments.jar, arguments.outputDir, arguments.includeRuntime); } else { diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java b/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java index 8244b165dd1..da6fbd71787 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java @@ -67,7 +67,7 @@ public class KotlinToJVMBytecodeCompiler { public static ClassFileFactory compileModule( CompileEnvironmentConfiguration configuration, Module moduleBuilder, - String directory + File directory ) { if (moduleBuilder.getSourceFiles().isEmpty()) { throw new CompileEnvironmentException("No source files where defined"); @@ -103,12 +103,11 @@ public class KotlinToJVMBytecodeCompiler { @NotNull List modules, - @NotNull String moduleScriptFile, + @NotNull File directory, @Nullable String jarPath, @Nullable String outputDir, boolean jarRuntime) { - final String directory = new File(moduleScriptFile).getParent(); for (Module moduleBuilder : modules) { // TODO: this should be done only once for the environment if (configuration.getCompilerDependencies().getRuntimeJar() != null) { From deaaf3042b0fd93c52c0d149056e5b9d6ba76a32 Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Tue, 24 Apr 2012 20:58:09 +0400 Subject: [PATCH 120/147] Fixed compilation in build-tools --- build-tools/build-tools.iml | 1 + .../org/jetbrains/jet/buildtools/core/BytecodeCompiler.java | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/build-tools/build-tools.iml b/build-tools/build-tools.iml index d184270053f..d0304c4b431 100644 --- a/build-tools/build-tools.iml +++ b/build-tools/build-tools.iml @@ -10,6 +10,7 @@ + diff --git a/build-tools/core/src/org/jetbrains/jet/buildtools/core/BytecodeCompiler.java b/build-tools/core/src/org/jetbrains/jet/buildtools/core/BytecodeCompiler.java index 0f35310a117..6e886343e5f 100644 --- a/build-tools/core/src/org/jetbrains/jet/buildtools/core/BytecodeCompiler.java +++ b/build-tools/core/src/org/jetbrains/jet/buildtools/core/BytecodeCompiler.java @@ -16,6 +16,7 @@ package org.jetbrains.jet.buildtools.core; +import jet.modules.Module; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.compiler.*; @@ -139,7 +140,9 @@ public class BytecodeCompiler { public void moduleToJar ( @NotNull String module, @NotNull String jar, boolean includeRuntime, @Nullable String stdlib, @Nullable String[] classpath ) { try { CompileEnvironmentConfiguration env = env(stdlib, classpath); - boolean success = KotlinToJVMBytecodeCompiler.compileModules(env, module, jar, null, includeRuntime); + List modules = CompileEnvironmentUtil.loadModuleScript(module, env.getMessageCollector()); + File directory = new File(module).getParentFile(); + boolean success = KotlinToJVMBytecodeCompiler.compileModules(env, modules, directory, jar, null, includeRuntime); if ( ! success ) { throw new CompileEnvironmentException( errorMessage( module, false )); } From d5e103601ba10b23bc8071a5a36e6dfeca615e99 Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Tue, 24 Apr 2012 20:59:55 +0400 Subject: [PATCH 121/147] Debug output removed --- idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java | 1 - 1 file changed, 1 deletion(-) diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java index 856cbe6b94c..3d79c66616d 100644 --- a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java +++ b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java @@ -486,7 +486,6 @@ public class JetCompiler implements TranslatingCompiler { if (category == STATISTICS) { compileContext.getProgressIndicator().setText(text); collector.learn(text); - System.out.println(text); } else { compileContext.addMessage(category, text, path, line, column); From b467edfa0375a75620b1f1d9e7a06b98014a20f6 Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Tue, 24 Apr 2012 21:11:58 +0400 Subject: [PATCH 122/147] Don't compile module scripts in verbose mode --- compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java b/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java index dec77e75f06..32a175995e9 100644 --- a/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java +++ b/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java @@ -153,7 +153,7 @@ public class KotlinCompiler { boolean noErrors; if (arguments.module != null) { - List modules = CompileEnvironmentUtil.loadModuleScript(arguments.module, configuration.getMessageCollector()); + List modules = CompileEnvironmentUtil.loadModuleScript(arguments.module, new PrintingMessageCollector(errStream, messageRenderer, false)); File directory = new File(arguments.module).getParentFile(); noErrors = KotlinToJVMBytecodeCompiler.compileModules(configuration, modules, directory, arguments.jar, arguments.outputDir, From 211fa9dd80d8f7474db94bc40dd2aaa69d9af3ad Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Tue, 24 Apr 2012 21:17:36 +0400 Subject: [PATCH 123/147] Don't treat the root tag as a message tag --- idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java index 3d79c66616d..463835c5084 100644 --- a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java +++ b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java @@ -477,6 +477,10 @@ public class JetCompiler implements TranslatingCompiler { @Override public void endElement(String uri, String localName, String qName) throws SAXException { + if (tags.size() == 1) { + // We're directly inside the root tag: + return; + } CompilerMessageCategory category = CATEGORIES.get(qName.toLowerCase()); if (category == null) { compileContext.addMessage(ERROR, "Unknown compiler message tag: " + qName, null, -1, -1); From 81387c07459ce725795c2e49c1b882e15f3a6c77 Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Tue, 24 Apr 2012 21:21:11 +0400 Subject: [PATCH 124/147] Fixing a regression: Compiler exceptions are now reported to the Exception Analyzer --- .../org/jetbrains/jet/plugin/compiler/JetCompiler.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java index 463835c5084..c9c3d4b972f 100644 --- a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java +++ b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java @@ -481,12 +481,18 @@ public class JetCompiler implements TranslatingCompiler { // We're directly inside the root tag: return; } - CompilerMessageCategory category = CATEGORIES.get(qName.toLowerCase()); + String qNameLowerCase = qName.toLowerCase(); + CompilerMessageCategory category = CATEGORIES.get(qNameLowerCase); if (category == null) { compileContext.addMessage(ERROR, "Unknown compiler message tag: " + qName, null, -1, -1); category = INFORMATION; } String text = message.toString(); + + if ("exception".equals(qNameLowerCase)) { + LOG.error(text); + } + if (category == STATISTICS) { compileContext.getProgressIndicator().setText(text); collector.learn(text); From c686184847be93580fc53beb70bc6e48ba7a844b Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Tue, 24 Apr 2012 21:53:23 +0400 Subject: [PATCH 125/147] KT-1860 Resolve annotations of function parameters #KT-1860 Fixed --- .../jet/lang/resolve/DescriptorResolver.java | 8 ++++---- .../expressions/ClosureExpressionsTypingVisitor.java | 3 ++- .../diagnostics/tests/annotations/kt1860-negative.jet | 9 +++++++++ .../diagnostics/tests/annotations/kt1860-positive.jet | 11 +++++++++++ 4 files changed, 26 insertions(+), 5 deletions(-) create mode 100644 compiler/testData/diagnostics/tests/annotations/kt1860-negative.jet create mode 100644 compiler/testData/diagnostics/tests/annotations/kt1860-positive.jet diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java index 86710ab25c9..5fae6c49bcf 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java @@ -264,7 +264,7 @@ public class DescriptorResolver { type = typeResolver.resolveType(parameterScope, typeReference, trace, true); } - ValueParameterDescriptor valueParameterDescriptor = resolveValueParameterDescriptor(functionDescriptor, valueParameter, i, type, trace); + ValueParameterDescriptor valueParameterDescriptor = resolveValueParameterDescriptor(parameterScope, functionDescriptor, valueParameter, i, type, trace); parameterScope.addVariableDescriptor(valueParameterDescriptor); result.add(valueParameterDescriptor); } @@ -272,7 +272,7 @@ public class DescriptorResolver { } @NotNull - public MutableValueParameterDescriptor resolveValueParameterDescriptor(DeclarationDescriptor declarationDescriptor, JetParameter valueParameter, int index, JetType type, BindingTrace trace) { + public MutableValueParameterDescriptor resolveValueParameterDescriptor(JetScope scope, DeclarationDescriptor declarationDescriptor, JetParameter valueParameter, int index, JetType type, BindingTrace trace) { JetType varargElementType = null; JetType variableType = type; if (valueParameter.hasModifier(JetTokens.VARARG_KEYWORD)) { @@ -282,7 +282,7 @@ public class DescriptorResolver { MutableValueParameterDescriptor valueParameterDescriptor = new ValueParameterDescriptorImpl( declarationDescriptor, index, - annotationResolver.createAnnotationStubs(valueParameter.getModifierList(), trace), + annotationResolver.resolveAnnotations(scope, valueParameter.getModifierList(), trace), JetPsiUtil.safeName(valueParameter.getName()), valueParameter.isMutable(), variableType, @@ -735,7 +735,7 @@ public class DescriptorResolver { } } - MutableValueParameterDescriptor valueParameterDescriptor = resolveValueParameterDescriptor(setterDescriptor, parameter, 0, type, trace); + MutableValueParameterDescriptor valueParameterDescriptor = resolveValueParameterDescriptor(scope, setterDescriptor, parameter, 0, type, trace); setterDescriptor.initialize(valueParameterDescriptor); } else { diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ClosureExpressionsTypingVisitor.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ClosureExpressionsTypingVisitor.java index 8ea9a700549..c0a400931f8 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ClosureExpressionsTypingVisitor.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ClosureExpressionsTypingVisitor.java @@ -195,7 +195,8 @@ public class ClosureExpressionsTypingVisitor extends ExpressionTypingVisitor { type = ErrorUtils.createErrorType("Cannot be inferred"); } } - ValueParameterDescriptor valueParameterDescriptor = context.expressionTypingServices.getDescriptorResolver().resolveValueParameterDescriptor(functionDescriptor, declaredParameter, i, type, context.trace); + ValueParameterDescriptor valueParameterDescriptor = context.expressionTypingServices.getDescriptorResolver().resolveValueParameterDescriptor( + context.scope, functionDescriptor, declaredParameter, i, type, context.trace); valueParameterDescriptors.add(valueParameterDescriptor); } } diff --git a/compiler/testData/diagnostics/tests/annotations/kt1860-negative.jet b/compiler/testData/diagnostics/tests/annotations/kt1860-negative.jet new file mode 100644 index 00000000000..620011f493a --- /dev/null +++ b/compiler/testData/diagnostics/tests/annotations/kt1860-negative.jet @@ -0,0 +1,9 @@ +fun foo(varargs f : Int) {} + +var bar : Int = 1 + set(varargs v) {} + +val x : (Int) -> Int = {([varargs] x : Int) -> x} + +class Hello(varargs args: Any) { +} \ No newline at end of file diff --git a/compiler/testData/diagnostics/tests/annotations/kt1860-positive.jet b/compiler/testData/diagnostics/tests/annotations/kt1860-positive.jet new file mode 100644 index 00000000000..bf00815f64a --- /dev/null +++ b/compiler/testData/diagnostics/tests/annotations/kt1860-positive.jet @@ -0,0 +1,11 @@ +annotation class test {} + +fun foo(test f : Int) {} + +var bar : Int = 1 + set(test v) {} + +val x : (Int) -> Int = {([test] x : Int) -> x} + +class Hello(test args: Any) { +} \ No newline at end of file From ae913f4c0e1ff6746ca669a42cd5b02e6a9a07c7 Mon Sep 17 00:00:00 2001 From: Stepan Koltsov Date: Tue, 24 Apr 2012 22:14:00 +0400 Subject: [PATCH 126/147] replace assert with exception * assert hides errors when code is executed without -ea * it is easier to set up breakpoint --- .../src/org/jetbrains/jet/util/slicedmap/Slices.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/jet/util/slicedmap/Slices.java b/compiler/frontend/src/org/jetbrains/jet/util/slicedmap/Slices.java index b1085c67c9d..e2b4b232146 100644 --- a/compiler/frontend/src/org/jetbrains/jet/util/slicedmap/Slices.java +++ b/compiler/frontend/src/org/jetbrains/jet/util/slicedmap/Slices.java @@ -32,11 +32,12 @@ public class Slices { @Override public boolean processRewrite(WritableSlice slice, K key, V oldValue, V newValue) { - assert (oldValue == null && newValue == null) || (oldValue != null && oldValue.equals(newValue)) - : "Rewrite at slice " + slice + - " key: " + key + - " old value: " + oldValue + '@' + System.identityHashCode(oldValue) + - " new value: " + newValue + '@' + System.identityHashCode(newValue); + if (!((oldValue == null && newValue == null) || (oldValue != null && oldValue.equals(newValue)))) { + throw new IllegalStateException("Rewrite at slice " + slice + + " key: " + key + + " old value: " + oldValue + '@' + System.identityHashCode(oldValue) + + " new value: " + newValue + '@' + System.identityHashCode(newValue)); + } return true; } }; From 0f3aa9e5678f25d7e96f63e5bb8e0aa96a6e6ce7 Mon Sep 17 00:00:00 2001 From: Stepan Koltsov Date: Tue, 24 Apr 2012 22:14:00 +0400 Subject: [PATCH 127/147] remove nop code --- .../jet/lang/resolve/java/JavaDescriptorResolver.java | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java index 248fca7c8a7..adbe0454bb6 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java @@ -76,7 +76,6 @@ import org.jetbrains.jet.lang.psi.JetPsiUtil; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingContextUtils; import org.jetbrains.jet.lang.resolve.BindingTrace; -import org.jetbrains.jet.lang.resolve.BindingTraceContext; import org.jetbrains.jet.lang.resolve.DescriptorUtils; import org.jetbrains.jet.lang.resolve.FqName; import org.jetbrains.jet.lang.resolve.NamespaceFactory; @@ -93,7 +92,6 @@ import org.jetbrains.jet.lang.resolve.constants.NullValue; import org.jetbrains.jet.lang.resolve.constants.ShortValue; import org.jetbrains.jet.lang.resolve.constants.StringValue; import org.jetbrains.jet.lang.resolve.java.kt.JetClassAnnotation; -import org.jetbrains.jet.lang.types.DeferredType; import org.jetbrains.jet.lang.types.ErrorUtils; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.TypeSubstitutor; @@ -105,7 +103,6 @@ import org.jetbrains.jet.rt.signature.JetSignatureAdapter; import org.jetbrains.jet.rt.signature.JetSignatureExceptionsAdapter; import org.jetbrains.jet.rt.signature.JetSignatureReader; import org.jetbrains.jet.rt.signature.JetSignatureVisitor; -import org.jetbrains.jet.util.lazy.LazyValue; import javax.inject.Inject; import java.util.ArrayList; @@ -431,11 +428,7 @@ public class JavaDescriptorResolver { List supertypes = new ArrayList(); - TypeVariableResolver outerTypeVariableByNameResolver = TypeVariableResolvers.classTypeVariableResolver( - (ClassOrNamespaceDescriptor) classData.classDescriptor.getContainingDeclaration(), - "class " + psiClass.getQualifiedName()); - - classData.typeParameters = createUninitializedClassTypeParameters(psiClass, classData, outerTypeVariableByNameResolver); + classData.typeParameters = createUninitializedClassTypeParameters(psiClass, classData); List typeParameters = new ArrayList(); for (TypeParameterDescriptorInitialization typeParameter : classData.typeParameters) { @@ -615,7 +608,7 @@ public class JavaDescriptorResolver { return classData.classDescriptor; } - private List createUninitializedClassTypeParameters(PsiClass psiClass, ResolverBinaryClassData classData, TypeVariableResolver typeVariableResolver) { + private List createUninitializedClassTypeParameters(PsiClass psiClass, ResolverBinaryClassData classData) { JetClassAnnotation jetClassAnnotation = JetClassAnnotation.get(psiClass); if (jetClassAnnotation.signature().length() > 0) { From 4a1c36d7334b5ba512f1fdb158ca9d4c02977cc5 Mon Sep 17 00:00:00 2001 From: Stepan Koltsov Date: Tue, 24 Apr 2012 22:14:01 +0400 Subject: [PATCH 128/147] fix complex case of recursion in JavaDescriptorResolver #KT-1804 --- .../resolve/java/JavaDescriptorResolver.java | 10 ++- .../javaDescriptorResolver/inner.java | 10 +++ .../compiler/JavaDescriptorResolverTest.java | 72 +++++++++++++++++++ 3 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 compiler/testData/javaDescriptorResolver/inner.java create mode 100644 compiler/tests/org/jetbrains/jet/compiler/JavaDescriptorResolverTest.java diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java index adbe0454bb6..556323eed38 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java @@ -410,6 +410,7 @@ public class JavaDescriptorResolver { return classData.classDescriptor; } + @NotNull private ResolverBinaryClassData createJavaClassDescriptor(@NotNull final PsiClass psiClass, List taskList) { FqName fqName = new FqName(psiClass.getQualifiedName()); if (classDescriptorCache.containsKey(fqName)) { @@ -421,7 +422,14 @@ public class JavaDescriptorResolver { String name = psiClass.getName(); ClassKind kind = psiClass.isInterface() ? (psiClass.isAnnotationType() ? ClassKind.ANNOTATION_CLASS : ClassKind.TRAIT) : ClassKind.CLASS; ClassOrNamespaceDescriptor containingDeclaration = resolveParentDescriptor(psiClass); - ResolverBinaryClassData classData = new ResolverBinaryClassData(psiClass, fqName, new MutableClassDescriptorLite(containingDeclaration, kind)); + + // class may be resolved during resolution of parent + ResolverBinaryClassData classData = classDescriptorCache.get(fqName); + if (classData != null) { + return classData; + } + + classData = new ResolverBinaryClassData(psiClass, fqName, new MutableClassDescriptorLite(containingDeclaration, kind)); classDescriptorCache.put(fqName, classData); classData.classDescriptor.setName(name); classData.classDescriptor.setAnnotations(resolveAnnotations(psiClass, taskList)); diff --git a/compiler/testData/javaDescriptorResolver/inner.java b/compiler/testData/javaDescriptorResolver/inner.java new file mode 100644 index 00000000000..cde64b5217a --- /dev/null +++ b/compiler/testData/javaDescriptorResolver/inner.java @@ -0,0 +1,10 @@ + +class A implements B.C { +} + +class B { + B(C c) {} + + interface C { + } +} diff --git a/compiler/tests/org/jetbrains/jet/compiler/JavaDescriptorResolverTest.java b/compiler/tests/org/jetbrains/jet/compiler/JavaDescriptorResolverTest.java new file mode 100644 index 00000000000..746b31b0a2a --- /dev/null +++ b/compiler/tests/org/jetbrains/jet/compiler/JavaDescriptorResolverTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.compiler; + +import org.jetbrains.jet.CompileCompilerDependenciesTest; +import org.jetbrains.jet.JetTestUtils; +import org.jetbrains.jet.di.InjectorForJavaSemanticServices; +import org.jetbrains.jet.lang.descriptors.ClassDescriptor; +import org.jetbrains.jet.lang.resolve.FqName; +import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; +import org.jetbrains.jet.lang.resolve.java.DescriptorSearchRule; +import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; +import org.junit.Assert; + +import javax.tools.*; +import java.io.File; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +/** + * @author Stepan Koltsov + * @see ReadJavaBinaryClassTest + */ +public class JavaDescriptorResolverTest extends TestCaseWithTmpdir { + + // This test can be implemented in ReadJavaBinaryClass test, but it is simpler here + public void testInner() throws Exception { + JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); + + StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ENGLISH, Charset.forName("utf-8")); + try { + File file = new File("compiler/testData/javaDescriptorResolver/inner.java"); + Iterable javaFileObjectsFromFiles = fileManager.getJavaFileObjectsFromFiles(Collections.singleton(file)); + List options = Arrays.asList( + "-d", tmpdir.getPath() + ); + JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, null, options, null, javaFileObjectsFromFiles); + + Assert.assertTrue(task.call()); + } finally { + fileManager.close(); + } + + JetCoreEnvironment jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable, CompilerSpecialMode.JDK_HEADERS); + + jetCoreEnvironment.addToClasspath(tmpdir); + + InjectorForJavaSemanticServices injector = new InjectorForJavaSemanticServices( + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS), jetCoreEnvironment.getProject()); + JavaDescriptorResolver javaDescriptorResolver = injector.getJavaDescriptorResolver(); + ClassDescriptor classDescriptor = javaDescriptorResolver.resolveClass(new FqName("A"), DescriptorSearchRule.ERROR_IF_FOUND_IN_KOTLIN); + Assert.assertNotNull(classDescriptor); + } + +} From 47e096026d6a6f93071bf52e5b340730649e3dae Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Tue, 24 Apr 2012 22:40:36 +0400 Subject: [PATCH 129/147] Escape XML strings in the compiler output --- .../jetbrains/jet/compiler/messages/MessageRenderer.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageRenderer.java b/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageRenderer.java index 1324b5f9f47..eca3c404552 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageRenderer.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageRenderer.java @@ -16,6 +16,7 @@ package org.jetbrains.jet.compiler.messages; +import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NotNull; import java.io.PrintWriter; @@ -37,18 +38,22 @@ public interface MessageRenderer { StringBuilder out = new StringBuilder(); out.append("<").append(severity.toString()); if (location.getPath() != null) { - out.append(" path=\"").append(location.getPath()).append("\""); + out.append(" path=\"").append(e(location.getPath())).append("\""); out.append(" line=\"").append(location.getLine()).append("\""); out.append(" column=\"").append(location.getColumn()).append("\""); } out.append(">\n"); - out.append(message); + out.append(e(message)); out.append("\n"); return out.toString(); } + private String e(String str) { + return StringUtil.escapeXml(str); + } + @Override public String renderException(@NotNull Throwable e) { return render(CompilerMessageSeverity.EXCEPTION, PLAIN.renderException(e), CompilerMessageLocation.NO_LOCATION); From fe9f8a0312d1d2c19b61be93960d675616f5793f Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Wed, 25 Apr 2012 11:26:31 +0400 Subject: [PATCH 130/147] Getting process exit code from waitFor() --- .../jetbrains/jet/plugin/compiler/JetCompiler.java | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java index c9c3d4b972f..b1eed35eb3c 100644 --- a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java +++ b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java @@ -343,14 +343,12 @@ public class JetCompiler implements TranslatingCompiler { compileContext.addMessage(INFORMATION, "Invoking out-of-process compiler with arguments: " + commandLine, "", -1, -1); try { - Process process = commandLine.createProcess(); - final InputStream err = process.getErrorStream(); - final InputStream out = process.getInputStream(); + final Process process = commandLine.createProcess(); ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { @Override public void run() { - parseCompilerMessagesFromReader(compileContext, new InputStreamReader(out), collector); + parseCompilerMessagesFromReader(compileContext, new InputStreamReader(process.getInputStream()), collector); } }); @@ -358,7 +356,7 @@ public class JetCompiler implements TranslatingCompiler { @Override public void run() { try { - FileUtil.loadBytes(err); + FileUtil.loadBytes(process.getErrorStream()); } catch (IOException e) { // Don't care @@ -366,8 +364,8 @@ public class JetCompiler implements TranslatingCompiler { } }); - process.waitFor(); - handleProcessTermination(process.exitValue(), compileContext); + int exitCode = process.waitFor(); + handleProcessTermination(exitCode, compileContext); } catch (Exception e) { compileContext.addMessage(ERROR, "[Internal Error] " + e.getLocalizedMessage(), "", -1, -1); From 890e9f5c43542daf35724a8a3d30f0aba70a6e7c Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Wed, 25 Apr 2012 11:52:30 +0400 Subject: [PATCH 131/147] Providing the same command line for in-process and out-of-process compilation --- .../jetbrains/jet/plugin/compiler/JetCompiler.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java index b1eed35eb3c..bfbce6c8a28 100644 --- a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java +++ b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java @@ -274,7 +274,7 @@ public class JetCompiler implements TranslatingCompiler { Class kompiler = Class.forName(compilerClassName, true, loader); Method exec = kompiler.getDeclaredMethod("exec", PrintStream.class, String[].class); - String[] arguments = { "-module", scriptFile.getAbsolutePath(), "-output", path(outputDir), "-tags", "-verbose", "-version", "-mode", "stdlib" }; + String[] arguments = commandLineArguments(outputDir, scriptFile); context.addMessage(INFORMATION, "Using kotlinHome=" + kotlinHome, "", -1, -1); context.addMessage(INFORMATION, "Invoking in-process compiler " + compilerClassName + " with arguments " + Arrays.asList(arguments), "", -1, -1); @@ -294,6 +294,10 @@ public class JetCompiler implements TranslatingCompiler { } } + private static String[] commandLineArguments(VirtualFile outputDir, File scriptFile) { + return new String[]{ "-module", scriptFile.getAbsolutePath(), "-output", path(outputDir), "-tags", "-verbose", "-version", "-mode", "stdlib" }; + } + private static SoftReference ourClassLoaderRef = new SoftReference(null); private static URLClassLoader getOrCreateClassLoader(File kotlinHome, CompileContext context) { @@ -323,10 +327,10 @@ public class JetCompiler implements TranslatingCompiler { final SimpleJavaParameters params = new SimpleJavaParameters(); params.setJdk(new SimpleJavaSdkType().createJdk("tmp", SystemProperties.getJavaHome())); params.setMainClass("org.jetbrains.jet.cli.KotlinCompiler"); - params.getProgramParametersList().add("-module", scriptFile.getAbsolutePath()); - params.getProgramParametersList().add("-output", path(outputDir)); - params.getProgramParametersList().add("-tags"); - params.getProgramParametersList().add("-verbose"); + + for (String arg : commandLineArguments(outputDir, scriptFile)) { + params.getProgramParametersList().add(arg); + } for (File jar : kompilerClasspath(kotlinHome, compileContext)) { params.getClassPath().add(jar); From 296c16a62337e01324930b818f905790ddabba3a Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Wed, 25 Apr 2012 11:53:17 +0400 Subject: [PATCH 132/147] Remove unused class --- .../compiler/CompilerProcessListener.java | 222 ------------------ .../jet/plugin/compiler/JetCompiler.java | 5 - 2 files changed, 227 deletions(-) delete mode 100644 idea/src/org/jetbrains/jet/plugin/compiler/CompilerProcessListener.java diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/CompilerProcessListener.java b/idea/src/org/jetbrains/jet/plugin/compiler/CompilerProcessListener.java deleted file mode 100644 index eff2687c2df..00000000000 --- a/idea/src/org/jetbrains/jet/plugin/compiler/CompilerProcessListener.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.plugin.compiler; - -import com.intellij.execution.process.ProcessAdapter; -import com.intellij.execution.process.ProcessEvent; -import com.intellij.execution.process.ProcessOutputTypes; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.util.Key; -import org.jetbrains.annotations.Nullable; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.intellij.openapi.compiler.CompilerMessageCategory.*; - -/** -* @author abreslav -*/ -public class CompilerProcessListener extends ProcessAdapter { - private static final Logger LOG = Logger.getInstance("#org.jetbrains.jet.plugin.compiler.CompilerProcessListener"); - - private static final Pattern DIAGNOSTIC_PATTERN = Pattern.compile("<(ERROR|WARNING|INFO|EXCEPTION|LOGGING)", Pattern.MULTILINE); - private static final Pattern OPEN_TAG_END_PATTERN = Pattern.compile(">", Pattern.MULTILINE | Pattern.DOTALL); - private static final Pattern ATTRIBUTE_PATTERN = Pattern.compile("\\s*(path|line|column)\\s*=\\s*\"(.*?)\"", Pattern.MULTILINE | Pattern.DOTALL); - private static final Pattern MESSAGE_PATTERN = Pattern.compile("(.*?)", Pattern.MULTILINE | Pattern.DOTALL); - - private enum State { - WAITING, ATTRIBUTES, MESSAGE - } - - private static class CompilerMessage { - private CompilerMessageCategory messageCategory; - private boolean isException; - private @Nullable String url; - private @Nullable Integer line; - private @Nullable Integer column; - private String message; - - public void setMessageCategoryFromString(String tagName) { - if ("ERROR".equals(tagName)) { - messageCategory = ERROR; - } - else if ("EXCEPTION".equals(tagName)) { - messageCategory = ERROR; - isException = true; - } - else if ("WARNING".equals(tagName)) { - messageCategory = WARNING; - } - else if ("LOGGING".equals(tagName)) { - messageCategory = STATISTICS; - } - else { - messageCategory = INFORMATION; - } - } - - public void setAttributeFromStrings(String name, String value) { - if ("path".equals(name)) { - url = "file://" + value.trim(); - } - else if ("line".equals(name)) { - line = safeParseInt(value); - } - else if ("column".equals(name)) { - column = safeParseInt(value); - } - } - - @Nullable - private static Integer safeParseInt(String value) { - try { - return Integer.parseInt(value.trim()); - } - catch (NumberFormatException e) { - return null; - } - } - - public void setMessage(String message) { - this.message = message; - } - - public void reportTo(CompileContext compileContext) { - if (messageCategory == STATISTICS) { - compileContext.getProgressIndicator().setText(message); - } - else { - compileContext.addMessage(messageCategory, message, url == null ? "" : url, line == null ? -1 : line, - column == null - ? -1 - : column); - if (isException) { - LOG.error(message); - } - } - } - } - - private final CompileContext compileContext; - private final OutputItemsCollector collector; - private final StringBuilder output = new StringBuilder(); - private int firstUnprocessedIndex = 0; - private State state = State.WAITING; - private CompilerMessage currentCompilerMessage; - - public CompilerProcessListener(CompileContext compileContext, OutputItemsCollector collector) { - this.compileContext = compileContext; - this.collector = collector; - } - - @Override - public void onTextAvailable(ProcessEvent event, Key outputType) { - String text = event.getText(); - if (outputType == ProcessOutputTypes.STDERR) { - output.append(text); - - // We loop until the state stabilizes - State lastState; - do { - lastState = state; - switch (state) { - case WAITING: { - Matcher matcher = matcher(DIAGNOSTIC_PATTERN); - if (find(matcher)) { - currentCompilerMessage = new CompilerMessage(); - currentCompilerMessage.setMessageCategoryFromString(matcher.group(1)); - state = State.ATTRIBUTES; - } - break; - } - case ATTRIBUTES: { - Matcher matcher = matcher(ATTRIBUTE_PATTERN); - int indexDelta = 0; - while (matcher.find()) { - handleSkippedOutput(output.subSequence(firstUnprocessedIndex + indexDelta, firstUnprocessedIndex + matcher.start())); - currentCompilerMessage.setAttributeFromStrings(matcher.group(1), matcher.group(2)); - indexDelta = matcher.end(); - - } - firstUnprocessedIndex += indexDelta; - - Matcher endMatcher = matcher(OPEN_TAG_END_PATTERN); - if (find(endMatcher)) { - state = State.MESSAGE; - } - break; - } - case MESSAGE: { - Matcher matcher = matcher(MESSAGE_PATTERN); - if (find(matcher)) { - String message = matcher.group(1); - currentCompilerMessage.setMessage(message); - currentCompilerMessage.reportTo(compileContext); - - if (currentCompilerMessage.messageCategory == STATISTICS) { - collector.learn(message); - } - - state = State.WAITING; - } - break; - } - } - } - while (state != lastState); - - } - else { - compileContext.addMessage(INFORMATION, text, "", -1, -1); - } - } - - private boolean find(Matcher matcher) { - boolean result = matcher.find(); - if (result) { - handleSkippedOutput(output.subSequence(firstUnprocessedIndex, firstUnprocessedIndex + matcher.start())); - firstUnprocessedIndex += matcher.end(); - } - return result; - } - - private Matcher matcher(Pattern pattern) { - return pattern.matcher(output.subSequence(firstUnprocessedIndex, output.length())); - } - - @Override - public void processTerminated(ProcessEvent event) { - if (firstUnprocessedIndex < output.length()) { - handleSkippedOutput(output.substring(firstUnprocessedIndex).trim()); - } - int exitCode = event.getExitCode(); - // 0 is normal, 1 is "errors found" - handled by the messages above - if (exitCode != 0 && exitCode != 1) { - compileContext.addMessage(ERROR, "Compiler terminated with exit code: " + exitCode, "", -1, -1); - } - } - - private void handleSkippedOutput(CharSequence substring) { - String message = substring.toString(); - if (!message.trim().isEmpty()) { - compileContext.addMessage(ERROR, message, "", -1, -1); - } - } -} diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java index bfbce6c8a28..924a69deb27 100644 --- a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java +++ b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java @@ -23,7 +23,6 @@ import com.intellij.compiler.impl.javaCompiler.ModuleChunk; import com.intellij.compiler.impl.javaCompiler.OutputItemImpl; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.SimpleJavaParameters; -import com.intellij.execution.process.ProcessAdapter; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompileScope; @@ -414,10 +413,6 @@ public class JetCompiler implements TranslatingCompiler { } } - private static ProcessAdapter createProcessListener(final CompileContext compileContext, OutputItemsCollector collector) { - return new CompilerProcessListener(compileContext, collector); - } - private static String path(VirtualFile root) { String path = root.getPath(); if (path.endsWith("!/")) { From 3eb6b3d0f5794e3fdd64671f3a505eaa48390fa5 Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Wed, 25 Apr 2012 12:20:27 +0400 Subject: [PATCH 133/147] Formatting --- .../src/org/jetbrains/jet/codegen/ClassBodyCodegen.java | 5 +++-- .../src/org/jetbrains/jet/codegen/NamespaceCodegen.java | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/ClassBodyCodegen.java b/compiler/backend/src/org/jetbrains/jet/codegen/ClassBodyCodegen.java index ea431b29b9b..82415fce97e 100644 --- a/compiler/backend/src/org/jetbrains/jet/codegen/ClassBodyCodegen.java +++ b/compiler/backend/src/org/jetbrains/jet/codegen/ClassBodyCodegen.java @@ -90,9 +90,10 @@ public abstract class ClassBodyCodegen { try { genNamedFunction((JetNamedFunction) declaration, functionCodegen); } - catch(CompilationException e) { + catch (CompilationException e) { throw e; - } catch (RuntimeException e) { + } + catch (RuntimeException e) { throw new RuntimeException("Error generating method " + myClass.getName() + "." + declaration.getName() + " in " + context, e); } } diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/NamespaceCodegen.java b/compiler/backend/src/org/jetbrains/jet/codegen/NamespaceCodegen.java index 2a3338c7510..6478143b709 100644 --- a/compiler/backend/src/org/jetbrains/jet/codegen/NamespaceCodegen.java +++ b/compiler/backend/src/org/jetbrains/jet/codegen/NamespaceCodegen.java @@ -69,7 +69,8 @@ public class NamespaceCodegen { else if (declaration instanceof JetNamedFunction) { try { functionCodegen.gen((JetNamedFunction) declaration); - } catch (CompilationException e) { + } + catch (CompilationException e) { throw e; } catch (Exception e) { From d0bd5cf9c66a9053df7a6a37f0c3227027f4bf7e Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Wed, 25 Apr 2012 12:25:00 +0400 Subject: [PATCH 134/147] Properly positioning compilation exceptions in the IDE --- .../jet/codegen/CompilationErrorHandler.java | 3 ++ .../jet/codegen/CompilationException.java | 14 ++++---- .../org/jetbrains/jet/cli/KotlinCompiler.java | 16 ++++++---- .../jet/compiler/messages/MessageUtil.java | 32 +++++++++++++++++++ .../jet/lang/diagnostics/DiagnosticUtils.java | 9 ++++-- 5 files changed, 60 insertions(+), 14 deletions(-) create mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageUtil.java diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/CompilationErrorHandler.java b/compiler/backend/src/org/jetbrains/jet/codegen/CompilationErrorHandler.java index ccd782a7c12..a3b2acf3846 100644 --- a/compiler/backend/src/org/jetbrains/jet/codegen/CompilationErrorHandler.java +++ b/compiler/backend/src/org/jetbrains/jet/codegen/CompilationErrorHandler.java @@ -24,6 +24,9 @@ public interface CompilationErrorHandler { CompilationErrorHandler THROW_EXCEPTION = new CompilationErrorHandler() { @Override public void reportException(Throwable exception, String fileUrl) { + if (exception instanceof RuntimeException) { + throw (RuntimeException)exception; + } throw new IllegalStateException(exception); } }; diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/CompilationException.java b/compiler/backend/src/org/jetbrains/jet/codegen/CompilationException.java index 4c7627c8ed6..f60a56148b9 100644 --- a/compiler/backend/src/org/jetbrains/jet/codegen/CompilationException.java +++ b/compiler/backend/src/org/jetbrains/jet/codegen/CompilationException.java @@ -23,20 +23,22 @@ import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils; /** * @author alex.tkachman +* @author abreslav */ public class CompilationException extends RuntimeException { - private PsiElement element; + private final PsiElement element; CompilationException(@NotNull String message, @Nullable Throwable cause, @NotNull PsiElement element) { super(message, cause); this.element = element; } - @Override - public String toString() { - return getMessage(); + @NotNull + public PsiElement getElement() { + return element; } - + + private String where() { Throwable cause = getCause(); Throwable throwable = cause != null ? cause : this; @@ -56,7 +58,7 @@ public class CompilationException extends RuntimeException { message.append("Cause: ").append(causeMessage == null ? cause.toString() : causeMessage).append("\n"); } message.append("File being compiled and position: ").append(DiagnosticUtils.atLocation(element)).append("\n"); - message.append("The root cause was thrown from: ").append(where()); + message.append("The root cause was thrown at: ").append(where()); return message.toString(); } diff --git a/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java b/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java index 32a175995e9..bf87036dfb1 100644 --- a/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java +++ b/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java @@ -25,11 +25,9 @@ import com.intellij.openapi.util.Disposer; import com.sampullara.cli.Args; import jet.modules.Module; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.codegen.CompilationException; import org.jetbrains.jet.compiler.*; -import org.jetbrains.jet.compiler.messages.CompilerMessageLocation; -import org.jetbrains.jet.compiler.messages.CompilerMessageSeverity; -import org.jetbrains.jet.compiler.messages.MessageCollector; -import org.jetbrains.jet.compiler.messages.MessageRenderer; +import org.jetbrains.jet.compiler.messages.*; import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.utils.PathUtil; @@ -147,7 +145,8 @@ public class KotlinCompiler { JetCoreEnvironment environment = new JetCoreEnvironment(rootDisposable, dependencies); CompileEnvironmentConfiguration configuration = new CompileEnvironmentConfiguration(environment, dependencies, messageCollector); - configuration.getMessageCollector().report(CompilerMessageSeverity.LOGGING, "Configuring the compilation environment", CompilerMessageLocation.NO_LOCATION); + messageCollector.report(CompilerMessageSeverity.LOGGING, "Configuring the compilation environment", + CompilerMessageLocation.NO_LOCATION); try { configureEnvironment(configuration, arguments); @@ -172,8 +171,13 @@ public class KotlinCompiler { } return noErrors ? OK : COMPILATION_ERROR; } + catch (CompilationException e) { + messageCollector.report(CompilerMessageSeverity.EXCEPTION, MessageRenderer.PLAIN.renderException(e), + MessageUtil.psiElementToMessageLocation(e.getElement())); + return INTERNAL_ERROR; + } catch (Throwable t) { - errStream.println(messageRenderer.renderException(t)); + messageCollector.report(CompilerMessageSeverity.EXCEPTION, MessageRenderer.PLAIN.renderException(t), CompilerMessageLocation.NO_LOCATION); return INTERNAL_ERROR; } finally { diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageUtil.java b/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageUtil.java new file mode 100644 index 00000000000..6ad95bc1e3d --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageUtil.java @@ -0,0 +1,32 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.compiler.messages; + +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils; + +/** + * @author abreslav + */ +public class MessageUtil { + public static CompilerMessageLocation psiElementToMessageLocation(PsiElement element) { + PsiFile file = element.getContainingFile(); + DiagnosticUtils.LineAndColumn lineAndColumn = DiagnosticUtils.getLineAndColumnInPsiFile(file, element.getTextRange()); + return CompilerMessageLocation.create(file.getVirtualFile().getPath(), lineAndColumn.getLine(), lineAndColumn.getColumn()); + } +} diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticUtils.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticUtils.java index 67ab02f1d5f..be456c83593 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticUtils.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/DiagnosticUtils.java @@ -80,11 +80,16 @@ public class DiagnosticUtils { @NotNull public static LineAndColumn getLineAndColumn(@NotNull Diagnostic diagnostic) { PsiFile file = diagnostic.getPsiFile(); - Document document = file.getViewProvider().getDocument(); List textRanges = diagnostic.getTextRanges(); if (textRanges.isEmpty()) return LineAndColumn.NONE; TextRange firstRange = textRanges.iterator().next(); - return offsetToLineAndColumn(document, firstRange.getStartOffset()); + return getLineAndColumnInPsiFile(file, firstRange); + } + + @NotNull + public static LineAndColumn getLineAndColumnInPsiFile(PsiFile file, TextRange range) { + Document document = file.getViewProvider().getDocument(); + return offsetToLineAndColumn(document, range.getStartOffset()); } @NotNull From 0a361f2377c92cece5c873b91f5869ed056c5360 Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Wed, 25 Apr 2012 12:52:45 +0400 Subject: [PATCH 135/147] Make VFS see the newly generated .class files --- idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java index 924a69deb27..bbad5de8885 100644 --- a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java +++ b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java @@ -399,7 +399,9 @@ public class JetCompiler implements TranslatingCompiler { } else if (message.startsWith(EMITTING_PREFIX)) { if (currentSource != null) { - answer.add(new OutputItemImpl(outputPath + "/" + message.substring(EMITTING_PREFIX.length()), currentSource)); + OutputItemImpl item = new OutputItemImpl(outputPath + "/" + message.substring(EMITTING_PREFIX.length()), currentSource); + LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(item.getOutputPath())); + answer.add(item); } } } From 4488a62344e9b7a6c744193e8ca673f7b2fcc739 Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Mon, 9 Apr 2012 18:35:16 +0400 Subject: [PATCH 136/147] Rename K2JS run configuration to "Kotlin (JavaScript)" --- .../jetbrains/jet/plugin/k2jsrun/K2JSRunConfigurationType.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfigurationType.java b/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfigurationType.java index 21bd928fa72..65ccb70f454 100644 --- a/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfigurationType.java +++ b/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfigurationType.java @@ -32,7 +32,7 @@ public final class K2JSRunConfigurationType extends ConfigurationTypeBase { } public K2JSRunConfigurationType() { - super("K2JSConfigurationType", "K2JS", "Kotlin to Javascript configuration", JetIcons.LAUNCH); + super("K2JSConfigurationType", "Kotlin (JavaScript)", "Kotlin to JavaScript configuration", JetIcons.LAUNCH); addFactory(new K2JSConfigurationFactory()); } From b3ffaa89c343b197f09a64f1cebb0736fb8bd507 Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Mon, 9 Apr 2012 20:04:23 +0400 Subject: [PATCH 137/147] Better handling of user provided paths. --- .../k2jsrun/K2JSRunConfigurationEditor.java | 33 +++++++++++++++++++ .../jetbrains/k2js/facade/K2JSTranslator.java | 5 ++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfigurationEditor.java b/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfigurationEditor.java index ebe4e3f1bbf..0a63582a1ac 100644 --- a/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfigurationEditor.java +++ b/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfigurationEditor.java @@ -26,11 +26,18 @@ import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.ui.TextFieldWithBrowseButton; +import com.jgoodies.looks.Fonts; import org.jetbrains.annotations.NotNull; import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; +import java.io.File; import static com.intellij.openapi.util.io.FileUtil.toSystemIndependentName; @@ -88,6 +95,32 @@ public final class K2JSRunConfigurationEditor extends SettingsEditor Date: Tue, 24 Apr 2012 17:28:28 +0400 Subject: [PATCH 138/147] Fix for a problem that caused all files to be analyzed completely in js analyzing facade. --- .../project/JSAnalyzerFacadeForIDEA.java | 2 +- .../k2js/analyze/AnalyzerFacadeForJS.java | 25 ++++++++++--------- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/project/JSAnalyzerFacadeForIDEA.java b/idea/src/org/jetbrains/jet/plugin/project/JSAnalyzerFacadeForIDEA.java index 80976459e39..53a9bf59d2d 100644 --- a/idea/src/org/jetbrains/jet/plugin/project/JSAnalyzerFacadeForIDEA.java +++ b/idea/src/org/jetbrains/jet/plugin/project/JSAnalyzerFacadeForIDEA.java @@ -46,7 +46,7 @@ public enum JSAnalyzerFacadeForIDEA implements AnalyzerFacade { @NotNull Collection files, @NotNull Predicate filesToAnalyzeCompletely, @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory) { - BindingContext context = AnalyzerFacadeForJS.analyzeFiles(files, new IDEAConfig(project)); + BindingContext context = AnalyzerFacadeForJS.analyzeFiles(files, filesToAnalyzeCompletely, new IDEAConfig(project)); return AnalyzeExhaust.success(context, JetStandardLibrary.getInstance()); } } diff --git a/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java b/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java index cb202551495..922995b6095 100644 --- a/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java +++ b/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java @@ -53,26 +53,27 @@ public final class AnalyzerFacadeForJS { @NotNull public static BindingContext analyzeFilesAndCheckErrors(@NotNull List files, - @NotNull Config config) { - BindingContext bindingContext = analyzeFiles(files, config); + @NotNull Config config) { + BindingContext bindingContext = analyzeFiles(files, Predicates.alwaysTrue(), config); checkForErrors(withJsLibAdded(files, config), bindingContext); return bindingContext; } @NotNull public static BindingContext analyzeFiles(@NotNull Collection files, - @NotNull Config config) { + Predicate filesToAnalyzeCompletely, @NotNull Config config) { Project project = config.getProject(); BindingTraceContext bindingTraceContext = new BindingTraceContext(); final ModuleDescriptor owner = new ModuleDescriptor(""); - TopDownAnalysisParameters topDownAnalysisParameters = new TopDownAnalysisParameters( - notLibFiles(config.getLibFiles()), false, false); + Predicate completely = Predicates.and(notLibFiles(config.getLibFiles()), filesToAnalyzeCompletely); + + TopDownAnalysisParameters topDownAnalysisParameters = new TopDownAnalysisParameters(completely, false, false); InjectorForTopDownAnalyzerForJs injector = new InjectorForTopDownAnalyzerForJs( - project, topDownAnalysisParameters, new ObservableBindingTrace(bindingTraceContext), owner, - JetControlFlowDataTraceFactory.EMPTY, JsConfiguration.jsLibConfiguration(project)); + project, topDownAnalysisParameters, new ObservableBindingTrace(bindingTraceContext), owner, + JetControlFlowDataTraceFactory.EMPTY, JsConfiguration.jsLibConfiguration(project)); injector.getTopDownAnalyzer().analyzeFiles(withJsLibAdded(files, config)); return bindingTraceContext.getBindingContext(); @@ -123,11 +124,11 @@ public final class AnalyzerFacadeForJS { final ModuleDescriptor owner = new ModuleDescriptor(""); TopDownAnalysisParameters topDownAnalysisParameters = new TopDownAnalysisParameters( - Predicates.alwaysTrue(), false, false); + Predicates.alwaysTrue(), false, false); InjectorForTopDownAnalyzerForJs injector = new InjectorForTopDownAnalyzerForJs( - project, topDownAnalysisParameters, new ObservableBindingTrace(bindingTraceContext), owner, - JetControlFlowDataTraceFactory.EMPTY, JsConfiguration.jsLibConfiguration(project)); + project, topDownAnalysisParameters, new ObservableBindingTrace(bindingTraceContext), owner, + JetControlFlowDataTraceFactory.EMPTY, JsConfiguration.jsLibConfiguration(project)); injector.getTopDownAnalyzer().analyzeFiles(Collections.singletonList(file)); return bindingTraceContext.getBindingContext(); @@ -156,9 +157,9 @@ public final class AnalyzerFacadeForJS { @Override public void extendNamespaceScope(@NotNull BindingTrace trace, @NotNull NamespaceDescriptor namespaceDescriptor, - @NotNull WritableScope namespaceMemberScope) { + @NotNull WritableScope namespaceMemberScope) { DefaultModuleConfiguration.createStandardConfiguration(project, true) - .extendNamespaceScope(trace, namespaceDescriptor, namespaceMemberScope); + .extendNamespaceScope(trace, namespaceDescriptor, namespaceMemberScope); } } } From 891dd9fc1c4dc1a6b06e7bffe77bfc22046d7818 Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Tue, 24 Apr 2012 20:31:23 +0400 Subject: [PATCH 139/147] extract compiler error reporting functionality from KotlinToJVMBytecodeCompiler --- .../compiler/KotlinToJVMBytecodeCompiler.java | 133 ++++----------- .../messages/AnalyzerWithCompilerReport.java | 154 ++++++++++++++++++ 2 files changed, 182 insertions(+), 105 deletions(-) create mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/messages/AnalyzerWithCompilerReport.java diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java b/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java index da6fbd71787..13945fd5949 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java @@ -19,12 +19,7 @@ package org.jetbrains.jet.compiler; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Ref; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.PsiErrorElement; import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.testFramework.LightVirtualFile; import com.intellij.util.LocalTimeCounter; import jet.modules.Module; @@ -32,17 +27,12 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.codegen.*; +import org.jetbrains.jet.compiler.messages.AnalyzerWithCompilerReport; import org.jetbrains.jet.compiler.messages.CompilerMessageLocation; import org.jetbrains.jet.compiler.messages.CompilerMessageSeverity; -import org.jetbrains.jet.compiler.messages.MessageCollector; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; -import org.jetbrains.jet.lang.descriptors.ClassDescriptor; -import org.jetbrains.jet.lang.diagnostics.*; -import org.jetbrains.jet.lang.diagnostics.rendering.DefaultErrorMessages; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetPsiUtil; -import org.jetbrains.jet.lang.resolve.BindingContext; -import org.jetbrains.jet.lang.resolve.DescriptorUtils; import org.jetbrains.jet.lang.resolve.FqName; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.resolve.java.JvmAbi; @@ -53,7 +43,6 @@ import org.jetbrains.jet.utils.Progress; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; -import java.util.Collection; import java.util.List; /** @@ -61,7 +50,9 @@ import java.util.List; * @author abreslav */ public class KotlinToJVMBytecodeCompiler { - private static final SimpleDiagnosticFactory SYNTAX_ERROR_FACTORY = SimpleDiagnosticFactory.create(Severity.ERROR); + + private KotlinToJVMBytecodeCompiler() { + } @Nullable public static ClassFileFactory compileModule( @@ -111,7 +102,8 @@ public class KotlinToJVMBytecodeCompiler { for (Module moduleBuilder : modules) { // TODO: this should be done only once for the environment if (configuration.getCompilerDependencies().getRuntimeJar() != null) { - CompileEnvironmentUtil.addToClasspath(configuration.getEnvironment(), configuration.getCompilerDependencies().getRuntimeJar()); + CompileEnvironmentUtil + .addToClasspath(configuration.getEnvironment(), configuration.getCompilerDependencies().getRuntimeJar()); } ClassFileFactory moduleFactory = KotlinToJVMBytecodeCompiler.compileModule(configuration, moduleBuilder, directory); if (moduleFactory == null) { @@ -135,7 +127,6 @@ public class KotlinToJVMBytecodeCompiler { private static boolean compileBunchOfSources( CompileEnvironmentConfiguration configuration, - String jar, String outputDir, boolean includeRuntime @@ -161,7 +152,8 @@ public class KotlinToJVMBytecodeCompiler { if (jar != null) { try { CompileEnvironmentUtil.writeToJar(factory, new FileOutputStream(jar), mainClass, includeRuntime); - } catch (FileNotFoundException e) { + } + catch (FileNotFoundException e) { throw new CompileEnvironmentException("Invalid jar path " + jar, e); } } @@ -203,7 +195,8 @@ public class KotlinToJVMBytecodeCompiler { CompileEnvironmentConfiguration configuration, String code) { - configuration.getEnvironment().addSources(new LightVirtualFile("script" + LocalTimeCounter.currentTime() + ".kt", JetLanguage.INSTANCE, code)); + configuration.getEnvironment() + .addSources(new LightVirtualFile("script" + LocalTimeCounter.currentTime() + ".kt", JetLanguage.INSTANCE, code)); GenerationState generationState = analyzeAndGenerate(configuration); if (generationState == null) { @@ -237,51 +230,27 @@ public class KotlinToJVMBytecodeCompiler { @Nullable private static AnalyzeExhaust analyze( final CompileEnvironmentConfiguration configuration, - boolean stubs) { - final Ref hasErrors = new Ref(false); - final MessageCollector messageCollectorWrapper = new MessageCollector() { - @Override - public void report(@NotNull CompilerMessageSeverity severity, - @NotNull String message, - @NotNull CompilerMessageLocation location) { - if (CompilerMessageSeverity.ERRORS.contains(severity)) { - hasErrors.set(true); - } - configuration.getMessageCollector().report(severity, message, location); - } - }; - JetCoreEnvironment environment = configuration.getEnvironment(); - - // Report syntax errors - for (JetFile file : environment.getSourceFiles()) { - file.accept(new PsiRecursiveElementWalkingVisitor() { - @Override - public void visitErrorElement(PsiErrorElement element) { - String description = element.getErrorDescription(); - String message = StringUtil.isEmpty(description) ? "Syntax error" : description; - Diagnostic diagnostic = new SyntaxErrorDiagnostic(element, Severity.ERROR, message); - reportDiagnostic(messageCollectorWrapper, diagnostic); - } - }); - } - - // Analyze and report semantic errors - Predicate filesToAnalyzeCompletely = + final JetCoreEnvironment environment = configuration.getEnvironment(); + AnalyzerWithCompilerReport analyzerWithCompilerReport = new AnalyzerWithCompilerReport(configuration.getMessageCollector()); + final Predicate filesToAnalyzeCompletely = stubs ? Predicates.alwaysFalse() : Predicates.alwaysTrue(); - AnalyzeExhaust exhaust = AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( - environment.getProject(), environment.getSourceFiles(), filesToAnalyzeCompletely, JetControlFlowDataTraceFactory.EMPTY, - configuration.getCompilerDependencies()); + analyzerWithCompilerReport.analyzeAndReport( + new AnalyzerWithCompilerReport.AnalyzerWrapper() { + @NotNull + @Override + public AnalyzeExhaust analyze() { + return AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( + environment.getProject(), environment.getSourceFiles(), filesToAnalyzeCompletely, + JetControlFlowDataTraceFactory.EMPTY, + configuration.getCompilerDependencies()); + } + }, environment.getSourceFiles() + ); - for (Diagnostic diagnostic : exhaust.getBindingContext().getDiagnostics()) { - reportDiagnostic(messageCollectorWrapper, diagnostic); - } - - reportIncompleteHierarchies(messageCollectorWrapper, exhaust); - - return hasErrors.get() ? null : exhaust; + return analyzerWithCompilerReport.hasErrors() ? null : analyzerWithCompilerReport.getAnalyzeExhaust(); } @NotNull @@ -300,7 +269,8 @@ public class KotlinToJVMBytecodeCompiler { } }; GenerationState generationState = new GenerationState(project, ClassBuilderFactories.binaries(stubs), backendProgress, - exhaust, environment.getSourceFiles(), configuration.getCompilerDependencies().getCompilerSpecialMode()); + exhaust, environment.getSourceFiles(), + configuration.getCompilerDependencies().getCompilerSpecialMode()); generationState.compileCorrectFiles(CompilationErrorHandler.THROW_EXCEPTION); List plugins = configuration.getCompilerPlugins(); @@ -312,51 +282,4 @@ public class KotlinToJVMBytecodeCompiler { } return generationState; } - - private static void reportDiagnostic(MessageCollector collector, Diagnostic diagnostic) { - DiagnosticUtils.LineAndColumn lineAndColumn = DiagnosticUtils.getLineAndColumn(diagnostic); - VirtualFile virtualFile = diagnostic.getPsiFile().getVirtualFile(); - String path = virtualFile == null ? null : virtualFile.getPath(); - String render; - if (diagnostic.getFactory() == SYNTAX_ERROR_FACTORY) { - render = ((SyntaxErrorDiagnostic)diagnostic).message; - } - else { - render = DefaultErrorMessages.RENDERER.render(diagnostic); - } - collector.report(convertSeverity(diagnostic.getSeverity()), render, CompilerMessageLocation.create(path, lineAndColumn.getLine(), lineAndColumn.getColumn())); - } - - private static CompilerMessageSeverity convertSeverity(Severity severity) { - switch (severity) { - case INFO: - return CompilerMessageSeverity.INFO; - case ERROR: - return CompilerMessageSeverity.ERROR; - case WARNING: - return CompilerMessageSeverity.WARNING; - } - throw new IllegalStateException("Unknown severity: " + severity); - } - - private static void reportIncompleteHierarchies(MessageCollector collector, AnalyzeExhaust exhaust) { - Collection incompletes = exhaust.getBindingContext().getKeys(BindingContext.INCOMPLETE_HIERARCHY); - if (!incompletes.isEmpty()) { - StringBuilder message = new StringBuilder("The following classes have incomplete hierarchies:\n"); - for (ClassDescriptor incomplete : incompletes) { - String fqName = DescriptorUtils.getFQName(incomplete).getFqName(); - message.append(" ").append(fqName).append("\n"); - } - collector.report(CompilerMessageSeverity.ERROR, message.toString(), CompilerMessageLocation.NO_LOCATION); - } - } - - private static class SyntaxErrorDiagnostic extends SimpleDiagnostic { - private String message; - - private SyntaxErrorDiagnostic(@NotNull PsiErrorElement psiElement, @NotNull Severity severity, String message) { - super(psiElement, SYNTAX_ERROR_FACTORY, severity); - this.message = message; - } - } } diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/messages/AnalyzerWithCompilerReport.java b/compiler/cli/src/org/jetbrains/jet/compiler/messages/AnalyzerWithCompilerReport.java new file mode 100644 index 00000000000..d03a19efd8e --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/compiler/messages/AnalyzerWithCompilerReport.java @@ -0,0 +1,154 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.compiler.messages; + +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.PsiErrorElement; +import com.intellij.psi.PsiRecursiveElementWalkingVisitor; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; +import org.jetbrains.jet.lang.descriptors.ClassDescriptor; +import org.jetbrains.jet.lang.diagnostics.*; +import org.jetbrains.jet.lang.diagnostics.rendering.DefaultErrorMessages; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.BindingContext; +import org.jetbrains.jet.lang.resolve.DescriptorUtils; + +import java.util.Collection; + +/** + * @author Pavel Talanov + */ +public final class AnalyzerWithCompilerReport { + + @NotNull + private static CompilerMessageSeverity convertSeverity(@NotNull Severity severity) { + switch (severity) { + case INFO: + return CompilerMessageSeverity.INFO; + case ERROR: + return CompilerMessageSeverity.ERROR; + case WARNING: + return CompilerMessageSeverity.WARNING; + } + throw new IllegalStateException("Unknown severity: " + severity); + } + + @NotNull + private static final SimpleDiagnosticFactory SYNTAX_ERROR_FACTORY = SimpleDiagnosticFactory.create(Severity.ERROR); + + private boolean hasErrors; + @NotNull + private final MessageCollector messageCollectorWrapper; + @Nullable + private AnalyzeExhaust analyzeExhaust = null; + + public AnalyzerWithCompilerReport(@NotNull final MessageCollector collector) { + messageCollectorWrapper = new MessageCollector() { + @Override + public void report(@NotNull CompilerMessageSeverity severity, + @NotNull String message, + @NotNull CompilerMessageLocation location) { + if (CompilerMessageSeverity.ERRORS.contains(severity)) { + hasErrors = true; + } + collector.report(severity, message, location); + } + }; + } + + private void reportDiagnostic(@NotNull Diagnostic diagnostic) { + DiagnosticUtils.LineAndColumn lineAndColumn = DiagnosticUtils.getLineAndColumn(diagnostic); + VirtualFile virtualFile = diagnostic.getPsiFile().getVirtualFile(); + String path = virtualFile == null ? null : virtualFile.getPath(); + String render; + if (diagnostic.getFactory() == SYNTAX_ERROR_FACTORY) { + render = ((SyntaxErrorDiagnostic)diagnostic).message; + } + else { + render = DefaultErrorMessages.RENDERER.render(diagnostic); + } + messageCollectorWrapper.report(convertSeverity(diagnostic.getSeverity()), render, + CompilerMessageLocation.create(path, lineAndColumn.getLine(), lineAndColumn.getColumn())); + } + + private void reportIncompleteHierarchies() { + assert analyzeExhaust != null; + Collection incompletes = analyzeExhaust.getBindingContext().getKeys(BindingContext.INCOMPLETE_HIERARCHY); + if (!incompletes.isEmpty()) { + StringBuilder message = new StringBuilder("The following classes have incomplete hierarchies:\n"); + for (ClassDescriptor incomplete : incompletes) { + String fqName = DescriptorUtils.getFQName(incomplete).getFqName(); + message.append(" ").append(fqName).append("\n"); + } + messageCollectorWrapper.report(CompilerMessageSeverity.ERROR, message.toString(), CompilerMessageLocation.NO_LOCATION); + } + } + + private void reportDiagnostics() { + assert analyzeExhaust != null; + for (Diagnostic diagnostic : analyzeExhaust.getBindingContext().getDiagnostics()) { + reportDiagnostic(diagnostic); + } + } + + private void reportSyntaxErrors(@NotNull Collection files) { + for (JetFile file : files) { + file.accept(new PsiRecursiveElementWalkingVisitor() { + @Override + public void visitErrorElement(PsiErrorElement element) { + String description = element.getErrorDescription(); + String message = StringUtil.isEmpty(description) ? "Syntax error" : description; + Diagnostic diagnostic = new SyntaxErrorDiagnostic(element, Severity.ERROR, message); + reportDiagnostic(diagnostic); + } + }); + } + } + + @Nullable + public AnalyzeExhaust getAnalyzeExhaust() { + return analyzeExhaust; + } + + public boolean hasErrors() { + return hasErrors; + } + + public void analyzeAndReport(@NotNull AnalyzerWrapper analyzerWrapper, @NotNull Collection files) { + reportSyntaxErrors(files); + analyzeExhaust = analyzerWrapper.analyze(); + reportDiagnostics(); + reportIncompleteHierarchies(); + } + + public interface AnalyzerWrapper { + @NotNull + AnalyzeExhaust analyze(); + } + + public static class SyntaxErrorDiagnostic extends SimpleDiagnostic { + private String message; + + public SyntaxErrorDiagnostic(@NotNull PsiErrorElement psiElement, @NotNull Severity severity, String message) { + super(psiElement, SYNTAX_ERROR_FACTORY, severity); + this.message = message; + } + } +} From 6e3d7cce61c24a4725095b788ee77de1bf8d6b23 Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Wed, 25 Apr 2012 13:45:42 +0400 Subject: [PATCH 140/147] Remove redundant analyzer wrapper. --- .../jet/compiler/KotlinToJVMBytecodeCompiler.java | 13 ++++--------- .../messages/AnalyzerWithCompilerReport.java | 11 ++++------- 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java b/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java index 13945fd5949..6f8798ad661 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java @@ -22,6 +22,7 @@ import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import com.intellij.testFramework.LightVirtualFile; import com.intellij.util.LocalTimeCounter; +import jet.Function0; import jet.modules.Module; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -105,7 +106,7 @@ public class KotlinToJVMBytecodeCompiler { CompileEnvironmentUtil .addToClasspath(configuration.getEnvironment(), configuration.getCompilerDependencies().getRuntimeJar()); } - ClassFileFactory moduleFactory = KotlinToJVMBytecodeCompiler.compileModule(configuration, moduleBuilder, directory); + ClassFileFactory moduleFactory = compileModule(configuration, moduleBuilder, directory); if (moduleFactory == null) { return false; } @@ -193,7 +194,6 @@ public class KotlinToJVMBytecodeCompiler { @Nullable public static ClassLoader compileText( CompileEnvironmentConfiguration configuration, - String code) { configuration.getEnvironment() .addSources(new LightVirtualFile("script" + LocalTimeCounter.currentTime() + ".kt", JetLanguage.INSTANCE, code)); @@ -213,7 +213,6 @@ public class KotlinToJVMBytecodeCompiler { @Nullable public static GenerationState analyzeAndGenerate( CompileEnvironmentConfiguration configuration, - boolean stubs ) { AnalyzeExhaust exhaust = analyze(configuration, stubs); @@ -231,17 +230,15 @@ public class KotlinToJVMBytecodeCompiler { private static AnalyzeExhaust analyze( final CompileEnvironmentConfiguration configuration, boolean stubs) { - - final JetCoreEnvironment environment = configuration.getEnvironment(); AnalyzerWithCompilerReport analyzerWithCompilerReport = new AnalyzerWithCompilerReport(configuration.getMessageCollector()); final Predicate filesToAnalyzeCompletely = stubs ? Predicates.alwaysFalse() : Predicates.alwaysTrue(); analyzerWithCompilerReport.analyzeAndReport( - new AnalyzerWithCompilerReport.AnalyzerWrapper() { + new Function0() { @NotNull @Override - public AnalyzeExhaust analyze() { + public AnalyzeExhaust invoke() { return AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( environment.getProject(), environment.getSourceFiles(), filesToAnalyzeCompletely, JetControlFlowDataTraceFactory.EMPTY, @@ -256,9 +253,7 @@ public class KotlinToJVMBytecodeCompiler { @NotNull private static GenerationState generate( final CompileEnvironmentConfiguration configuration, - AnalyzeExhaust exhaust, - boolean stubs) { JetCoreEnvironment environment = configuration.getEnvironment(); Project project = environment.getProject(); diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/messages/AnalyzerWithCompilerReport.java b/compiler/cli/src/org/jetbrains/jet/compiler/messages/AnalyzerWithCompilerReport.java index d03a19efd8e..0a5d9812340 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/messages/AnalyzerWithCompilerReport.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/messages/AnalyzerWithCompilerReport.java @@ -20,6 +20,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiErrorElement; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; +import jet.Function0; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.analyzer.AnalyzeExhaust; @@ -53,7 +54,7 @@ public final class AnalyzerWithCompilerReport { @NotNull private static final SimpleDiagnosticFactory SYNTAX_ERROR_FACTORY = SimpleDiagnosticFactory.create(Severity.ERROR); - private boolean hasErrors; + private boolean hasErrors = false; @NotNull private final MessageCollector messageCollectorWrapper; @Nullable @@ -131,17 +132,13 @@ public final class AnalyzerWithCompilerReport { return hasErrors; } - public void analyzeAndReport(@NotNull AnalyzerWrapper analyzerWrapper, @NotNull Collection files) { + public void analyzeAndReport(@NotNull Function0 analyzer, @NotNull Collection files) { reportSyntaxErrors(files); - analyzeExhaust = analyzerWrapper.analyze(); + analyzeExhaust = analyzer.invoke(); reportDiagnostics(); reportIncompleteHierarchies(); } - public interface AnalyzerWrapper { - @NotNull - AnalyzeExhaust analyze(); - } public static class SyntaxErrorDiagnostic extends SimpleDiagnostic { private String message; From c083876bf7469652896fb5d9a0ceee7039cafdfc Mon Sep 17 00:00:00 2001 From: Andrey Breslav Date: Wed, 25 Apr 2012 14:55:32 +0400 Subject: [PATCH 141/147] Properly report errors in the IDE when the compiler command line contains errors --- .../jet/plugin/compiler/JetCompiler.java | 51 ++++++++++++++++++- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java index bbad5de8885..3addb898aab 100644 --- a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java +++ b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java @@ -249,14 +249,61 @@ public class JetCompiler implements TranslatingCompiler { handleProcessTermination(exitCode, compileContext); } - private static void parseCompilerMessagesFromReader(CompileContext compileContext, Reader reader, OutputItemsCollector collector) { + private static void parseCompilerMessagesFromReader(CompileContext compileContext, final Reader reader, OutputItemsCollector collector) { + // Sometimes the compiler can't output valid XML + // Example: error in command line arguments passed to the compiler + // having no -tags key (arguments are not parsed), the compiler doesn't know + // if it should put any tags in the output, so it will simply print the usage + // and the SAX parser will break. + // In this case, we want to read everything from this stream + // and report it as an IDE error. + final StringBuilder stringBuilder = new StringBuilder(); + //noinspection IOResourceOpenedButNotSafelyClosed + Reader wrappingReader = new Reader() { + + @Override + public int read(char[] cbuf, int off, int len) throws IOException { + int read = reader.read(cbuf, off, len); + stringBuilder.append(cbuf, off, len); + return read; + } + + @Override + public void close() throws IOException { + // Do nothing: + // If the SAX parser sees a syntax error, it throws an expcetion + // and calls close() on the reader. + // We prevent hte reader from being closed here, and close it later, + // when all the text is read from it + } + }; try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); - parser.parse(new InputSource(reader), new CompilerOutputSAXHandler(compileContext, collector)); + parser.parse(new InputSource(wrappingReader), new CompilerOutputSAXHandler(compileContext, collector)); } catch (Throwable e) { + + // Load all the text into the stringBuilder + try { + // This will not close the reader (see the wrapper above) + FileUtil.loadTextAndClose(wrappingReader); + } + catch (IOException ioException) { + LOG.error(ioException); + } + String message = stringBuilder.toString(); + LOG.error(message); LOG.error(e); + compileContext.addMessage(ERROR, message, null, -1, -1); + } + finally { + try { + reader.close(); + } + catch (IOException e) { + LOG.error(e); + } } } From c9edaa6b4ff2c7180f54f713c33594a6a72c6f84 Mon Sep 17 00:00:00 2001 From: Stepan Koltsov Date: Wed, 25 Apr 2012 18:48:14 +0400 Subject: [PATCH 142/147] do not add annotations.jar to compiler classpath --- compiler/tests/org/jetbrains/jet/JetTestUtils.java | 1 - 1 file changed, 1 deletion(-) diff --git a/compiler/tests/org/jetbrains/jet/JetTestUtils.java b/compiler/tests/org/jetbrains/jet/JetTestUtils.java index fc34073dcec..d0d00c57a97 100644 --- a/compiler/tests/org/jetbrains/jet/JetTestUtils.java +++ b/compiler/tests/org/jetbrains/jet/JetTestUtils.java @@ -174,7 +174,6 @@ public class JetTestUtils { JetCoreEnvironment environment = new JetCoreEnvironment(disposable, CompileCompilerDependenciesTest.compilerDependenciesForTests(compilerSpecialMode)); final File rtJar = new File(JetTestCaseBuilder.getHomeDirectory(), "compiler/testData/mockJDK-1.7/jre/lib/rt.jar"); environment.addToClasspath(rtJar); - environment.addToClasspath(getAnnotationsJar()); return environment; } From 3b43f30824eeb2dbd572cf7bbe4da8cd9a6ea373 Mon Sep 17 00:00:00 2001 From: Stepan Koltsov Date: Wed, 25 Apr 2012 19:36:22 +0400 Subject: [PATCH 143/147] add JDK to CompilerDependencies --- .../org/jetbrains/jet/cli/KotlinCompiler.java | 2 +- .../jet/compiler/CompileEnvironmentUtil.java | 38 ------------------- .../jet/compiler/JetCoreEnvironment.java | 2 + .../resolve/java/CompilerDependencies.java | 38 ++++++++++++++++++- .../jet/CompileCompilerDependenciesTest.java | 3 +- .../org/jetbrains/jet/JetLiteFixture.java | 6 +-- .../tests/org/jetbrains/jet/JetTestUtils.java | 11 +++--- .../jet/checkers/CheckerTestUtilTest.java | 2 +- .../jet/checkers/JetDiagnosticsTest.java | 2 +- .../jet/codegen/CodegenTestCase.java | 2 +- .../jet/codegen/CompileTextTest.java | 2 +- .../jet/codegen/GenerationUtils.java | 2 +- .../jetbrains/jet/codegen/TestlibTest.java | 2 +- .../compiler/JavaDescriptorResolverTest.java | 2 +- .../jet/compiler/ReadJavaBinaryClassTest.java | 4 +- .../compiler/ReadKotlinBinaryClassTest.java | 2 +- ...solveDescriptorsFromExternalLibraries.java | 2 +- .../jet/resolve/DescriptorRendererTest.java | 2 +- .../jet/resolve/ExpectedResolveData.java | 2 +- .../jetbrains/jet/resolve/JetResolveTest.java | 2 +- .../JetDefaultModalityModifiersTest.java | 2 +- .../jet/types/JetTypeCheckerTest.java | 2 +- 22 files changed, 66 insertions(+), 66 deletions(-) diff --git a/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java b/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java index bf87036dfb1..39e831d789f 100644 --- a/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java +++ b/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java @@ -138,7 +138,7 @@ public class KotlinCompiler { runtimeJar = null; } - CompilerDependencies dependencies = new CompilerDependencies(mode, jdkHeadersJar, runtimeJar); + CompilerDependencies dependencies = new CompilerDependencies(mode, CompilerDependencies.findRtJar(), jdkHeadersJar, runtimeJar); PrintingMessageCollector messageCollector = new PrintingMessageCollector(errStream, messageRenderer, arguments.verbose); Disposable rootDisposable = CompileEnvironmentUtil.createMockDisposable(); diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentUtil.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentUtil.java index 26541ca6554..139fcfd72a8 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentUtil.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentUtil.java @@ -93,51 +93,13 @@ public class CompileEnvironmentUtil { } } - public static void ensureJdkRuntime(JetCoreEnvironment env) { - if (JavaPsiFacade.getInstance(env.getProject()).findClass("java.lang.Object", GlobalSearchScope.allScope(env.getProject())) == null) { - // TODO: prepend - env.addToClasspath(findRtJar()); - } - } - - public static File findRtJar() { - String javaHome = System.getProperty("java.home"); - if ("jre".equals(new File(javaHome).getName())) { - javaHome = new File(javaHome).getParent(); - } - - File rtJar = findRtJar(javaHome); - - if (rtJar == null || !rtJar.exists()) { - throw new CompileEnvironmentException("No JDK rt.jar found under " + javaHome); - } - - return rtJar; - } - - private static File findRtJar(String javaHome) { - File rtJar = new File(javaHome, "jre/lib/rt.jar"); - if (rtJar.exists()) { - return rtJar; - } - - File classesJar = new File(new File(javaHome).getParentFile().getAbsolutePath(), "Classes/classes.jar"); - if (classesJar.exists()) { - return classesJar; - } - return null; - } - public static void ensureRuntime(JetCoreEnvironment environment, CompilerDependencies compilerDependencies) { if (compilerDependencies.getCompilerSpecialMode() == CompilerSpecialMode.REGULAR) { - ensureJdkRuntime(environment); ensureKotlinRuntime(environment); } else if (compilerDependencies.getCompilerSpecialMode() == CompilerSpecialMode.JDK_HEADERS) { - ensureJdkRuntime(environment); } else if (compilerDependencies.getCompilerSpecialMode() == CompilerSpecialMode.STDLIB) { - ensureJdkRuntime(environment); } else if (compilerDependencies.getCompilerSpecialMode() == CompilerSpecialMode.BUILTINS) { // nop diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/JetCoreEnvironment.java b/compiler/cli/src/org/jetbrains/jet/compiler/JetCoreEnvironment.java index bd8eb357ccf..648ca6a0f15 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/JetCoreEnvironment.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/JetCoreEnvironment.java @@ -64,6 +64,8 @@ public class JetCoreEnvironment extends JavaCoreEnvironment { CompilerSpecialMode compilerSpecialMode = compilerDependencies.getCompilerSpecialMode(); + addToClasspath(compilerDependencies.getJdkJar()); + if (compilerSpecialMode.includeJdkHeaders()) { for (VirtualFile root : compilerDependencies.getJdkHeaderRoots()) { addLibraryRoot(root); diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/CompilerDependencies.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/CompilerDependencies.java index caea1d27035..05075e34c10 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/CompilerDependencies.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/CompilerDependencies.java @@ -33,12 +33,15 @@ public class CompilerDependencies { @NotNull private final CompilerSpecialMode compilerSpecialMode; @Nullable + private final File jdkJar; + @Nullable private final File jdkHeadersJar; @Nullable private final File runtimeJar; - public CompilerDependencies(@NotNull CompilerSpecialMode compilerSpecialMode, @Nullable File jdkHeadersJar, @Nullable File runtimeJar) { + public CompilerDependencies(@NotNull CompilerSpecialMode compilerSpecialMode, @Nullable File jdkJar, @Nullable File jdkHeadersJar, @Nullable File runtimeJar) { this.compilerSpecialMode = compilerSpecialMode; + this.jdkJar = jdkJar; this.jdkHeadersJar = jdkHeadersJar; this.runtimeJar = runtimeJar; @@ -59,6 +62,11 @@ public class CompilerDependencies { return compilerSpecialMode; } + @Nullable + public File getJdkJar() { + return jdkJar; + } + @Nullable public File getJdkHeadersJar() { return jdkHeadersJar; @@ -93,8 +101,36 @@ public class CompilerDependencies { public static CompilerDependencies compilerDependenciesForProduction(@NotNull CompilerSpecialMode compilerSpecialMode) { return new CompilerDependencies( compilerSpecialMode, + findRtJar(), compilerSpecialMode.includeJdkHeaders() ? PathUtil.getAltHeadersPath() : null, compilerSpecialMode.includeKotlinRuntime() ? PathUtil.getDefaultRuntimePath() : null); } + public static File findRtJar() { + String javaHome = System.getProperty("java.home"); + if ("jre".equals(new File(javaHome).getName())) { + javaHome = new File(javaHome).getParent(); + } + + File rtJar = findRtJar(javaHome); + + if (rtJar == null || !rtJar.exists()) { + throw new IllegalArgumentException("No JDK rt.jar found under " + javaHome); + } + + return rtJar; + } + + private static File findRtJar(String javaHome) { + File rtJar = new File(javaHome, "jre/lib/rt.jar"); + if (rtJar.exists()) { + return rtJar; + } + + File classesJar = new File(new File(javaHome).getParentFile().getAbsolutePath(), "Classes/classes.jar"); + if (classesJar.exists()) { + return classesJar; + } + return null; + } } diff --git a/compiler/tests/org/jetbrains/jet/CompileCompilerDependenciesTest.java b/compiler/tests/org/jetbrains/jet/CompileCompilerDependenciesTest.java index e6178f6d2bd..d024dfd8572 100644 --- a/compiler/tests/org/jetbrains/jet/CompileCompilerDependenciesTest.java +++ b/compiler/tests/org/jetbrains/jet/CompileCompilerDependenciesTest.java @@ -49,9 +49,10 @@ public class CompileCompilerDependenciesTest { * @see CompilerDependencies#compilerDependenciesForProduction(org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode) */ @NotNull - public static CompilerDependencies compilerDependenciesForTests(@NotNull CompilerSpecialMode compilerSpecialMode) { + public static CompilerDependencies compilerDependenciesForTests(@NotNull CompilerSpecialMode compilerSpecialMode, boolean mockJdk) { return new CompilerDependencies( compilerSpecialMode, + mockJdk ? JetTestUtils.findMockJdkRtJar() : CompilerDependencies.findRtJar(), compilerSpecialMode.includeJdkHeaders() ? ForTestCompileJdkHeaders.jdkHeadersForTests() : null, compilerSpecialMode.includeKotlinRuntime() ? ForTestCompileRuntime.runtimeJarForTests() : null); } diff --git a/compiler/tests/org/jetbrains/jet/JetLiteFixture.java b/compiler/tests/org/jetbrains/jet/JetLiteFixture.java index 0591de3e22e..92a04db29c4 100644 --- a/compiler/tests/org/jetbrains/jet/JetLiteFixture.java +++ b/compiler/tests/org/jetbrains/jet/JetLiteFixture.java @@ -30,9 +30,9 @@ import com.intellij.testFramework.LightVirtualFile; import com.intellij.testFramework.TestDataFile; import com.intellij.testFramework.UsefulTestCase; import org.jetbrains.annotations.NonNls; -import org.jetbrains.jet.compiler.CompileEnvironmentUtil; import org.jetbrains.jet.compiler.JetCoreEnvironment; import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.plugin.JetLanguage; @@ -76,9 +76,7 @@ public abstract class JetLiteFixture extends UsefulTestCase { protected void createEnvironmentWithFullJdk() { myEnvironment = new JetCoreEnvironment(getTestRootDisposable(), - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR)); - final File rtJar = CompileEnvironmentUtil.findRtJar(); - myEnvironment.addToClasspath(rtJar); + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, false)); } @Override diff --git a/compiler/tests/org/jetbrains/jet/JetTestUtils.java b/compiler/tests/org/jetbrains/jet/JetTestUtils.java index d0d00c57a97..d340c04c3af 100644 --- a/compiler/tests/org/jetbrains/jet/JetTestUtils.java +++ b/compiler/tests/org/jetbrains/jet/JetTestUtils.java @@ -163,7 +163,7 @@ public class JetTestUtils { public static AnalyzeExhaust analyzeFile(@NotNull JetFile namespace, @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory) { return AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegration(namespace, flowDataTraceFactory, - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR)); + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, true)); } public static JetCoreEnvironment createEnvironmentWithMockJdk(Disposable disposable) { @@ -171,10 +171,11 @@ public class JetTestUtils { } public static JetCoreEnvironment createEnvironmentWithMockJdk(Disposable disposable, @NotNull CompilerSpecialMode compilerSpecialMode) { - JetCoreEnvironment environment = new JetCoreEnvironment(disposable, CompileCompilerDependenciesTest.compilerDependenciesForTests(compilerSpecialMode)); - final File rtJar = new File(JetTestCaseBuilder.getHomeDirectory(), "compiler/testData/mockJDK-1.7/jre/lib/rt.jar"); - environment.addToClasspath(rtJar); - return environment; + return new JetCoreEnvironment(disposable, CompileCompilerDependenciesTest.compilerDependenciesForTests(compilerSpecialMode, true)); + } + + public static File findMockJdkRtJar() { + return new File(JetTestCaseBuilder.getHomeDirectory(), "compiler/testData/mockJDK-1.7/jre/lib/rt.jar"); } public static File getAnnotationsJar() { diff --git a/compiler/tests/org/jetbrains/jet/checkers/CheckerTestUtilTest.java b/compiler/tests/org/jetbrains/jet/checkers/CheckerTestUtilTest.java index 875c4c69bac..1c447845f51 100644 --- a/compiler/tests/org/jetbrains/jet/checkers/CheckerTestUtilTest.java +++ b/compiler/tests/org/jetbrains/jet/checkers/CheckerTestUtilTest.java @@ -101,7 +101,7 @@ public class CheckerTestUtilTest extends JetLiteFixture { public void test(final @NotNull PsiFile psiFile) { BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegration( (JetFile) psiFile, JetControlFlowDataTraceFactory.EMPTY, - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR)) + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, true)) .getBindingContext(); String expectedText = CheckerTestUtil.addDiagnosticMarkersToText(psiFile, CheckerTestUtil.getDiagnosticsIncludingSyntaxErrors(bindingContext, psiFile)).toString(); diff --git a/compiler/tests/org/jetbrains/jet/checkers/JetDiagnosticsTest.java b/compiler/tests/org/jetbrains/jet/checkers/JetDiagnosticsTest.java index a3d1fdb54f8..f1414d9cd17 100644 --- a/compiler/tests/org/jetbrains/jet/checkers/JetDiagnosticsTest.java +++ b/compiler/tests/org/jetbrains/jet/checkers/JetDiagnosticsTest.java @@ -169,7 +169,7 @@ public class JetDiagnosticsTest extends JetLiteFixture { BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( getProject(), jetFiles, Predicates.alwaysTrue(), JetControlFlowDataTraceFactory.EMPTY, - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR)) + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, true)) .getBindingContext(); boolean ok = true; diff --git a/compiler/tests/org/jetbrains/jet/codegen/CodegenTestCase.java b/compiler/tests/org/jetbrains/jet/codegen/CodegenTestCase.java index c9f64026018..e95269f3368 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/CodegenTestCase.java +++ b/compiler/tests/org/jetbrains/jet/codegen/CodegenTestCase.java @@ -127,7 +127,7 @@ public abstract class CodegenTestCase extends JetLiteFixture { private GenerationState generateCommon(ClassBuilderFactory classBuilderFactory) { final AnalyzeExhaust analyzeExhaust = AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegrationAndCheckForErrors( myFile, JetControlFlowDataTraceFactory.EMPTY, - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR)); + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, false)); analyzeExhaust.throwIfError(); GenerationState state = new GenerationState(getProject(), classBuilderFactory, analyzeExhaust, Collections.singletonList(myFile)); state.compileCorrectFiles(CompilationErrorHandler.THROW_EXCEPTION); diff --git a/compiler/tests/org/jetbrains/jet/codegen/CompileTextTest.java b/compiler/tests/org/jetbrains/jet/codegen/CompileTextTest.java index aacc2ca0d65..30743c9dee6 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/CompileTextTest.java +++ b/compiler/tests/org/jetbrains/jet/codegen/CompileTextTest.java @@ -31,7 +31,7 @@ import java.lang.reflect.Method; public class CompileTextTest extends CodegenTestCase { public void testMe() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { String text = "import org.jetbrains.jet.codegen.CompileTextTest; fun x() = CompileTextTest()"; - CompilerDependencies dependencies = CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR); + CompilerDependencies dependencies = CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, false); JetCoreEnvironment environment = new JetCoreEnvironment(CompileEnvironmentUtil.createMockDisposable(), dependencies); CompileEnvironmentConfiguration configuration = new CompileEnvironmentConfiguration(environment, dependencies, MessageCollector.PLAIN_TEXT_TO_SYSTEM_ERR); configuration.getEnvironment().addToClasspathFromClassLoader(getClass().getClassLoader()); diff --git a/compiler/tests/org/jetbrains/jet/codegen/GenerationUtils.java b/compiler/tests/org/jetbrains/jet/codegen/GenerationUtils.java index 63f3b2c796c..6875096cb1c 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/GenerationUtils.java +++ b/compiler/tests/org/jetbrains/jet/codegen/GenerationUtils.java @@ -38,7 +38,7 @@ public class GenerationUtils { public static GenerationState compileFileGetGenerationStateForTest(JetFile psiFile, @NotNull CompilerSpecialMode compilerSpecialMode) { final AnalyzeExhaust analyzeExhaust = AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegrationAndCheckForErrors( psiFile, JetControlFlowDataTraceFactory.EMPTY, - CompileCompilerDependenciesTest.compilerDependenciesForTests(compilerSpecialMode)); + CompileCompilerDependenciesTest.compilerDependenciesForTests(compilerSpecialMode, true)); analyzeExhaust.throwIfError(); GenerationState state = new GenerationState(psiFile.getProject(), ClassBuilderFactories.binaries(false), analyzeExhaust, Collections.singletonList(psiFile)); state.compileCorrectFiles(CompilationErrorHandler.THROW_EXCEPTION); diff --git a/compiler/tests/org/jetbrains/jet/codegen/TestlibTest.java b/compiler/tests/org/jetbrains/jet/codegen/TestlibTest.java index 6ffbe45126b..42fe643ba65 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/TestlibTest.java +++ b/compiler/tests/org/jetbrains/jet/codegen/TestlibTest.java @@ -75,7 +75,7 @@ public class TestlibTest extends CodegenTestCase { private TestSuite doBuildSuite() { try { - CompilerDependencies compilerDependencies = CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR); + CompilerDependencies compilerDependencies = CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, false); File junitJar = new File("libraries/lib/junit-4.9.jar"); if (!junitJar.exists()) { diff --git a/compiler/tests/org/jetbrains/jet/compiler/JavaDescriptorResolverTest.java b/compiler/tests/org/jetbrains/jet/compiler/JavaDescriptorResolverTest.java index 746b31b0a2a..e26bcd05cbc 100644 --- a/compiler/tests/org/jetbrains/jet/compiler/JavaDescriptorResolverTest.java +++ b/compiler/tests/org/jetbrains/jet/compiler/JavaDescriptorResolverTest.java @@ -63,7 +63,7 @@ public class JavaDescriptorResolverTest extends TestCaseWithTmpdir { jetCoreEnvironment.addToClasspath(tmpdir); InjectorForJavaSemanticServices injector = new InjectorForJavaSemanticServices( - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS), jetCoreEnvironment.getProject()); + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS, true), jetCoreEnvironment.getProject()); JavaDescriptorResolver javaDescriptorResolver = injector.getJavaDescriptorResolver(); ClassDescriptor classDescriptor = javaDescriptorResolver.resolveClass(new FqName("A"), DescriptorSearchRule.ERROR_IF_FOUND_IN_KOTLIN); Assert.assertNotNull(classDescriptor); diff --git a/compiler/tests/org/jetbrains/jet/compiler/ReadJavaBinaryClassTest.java b/compiler/tests/org/jetbrains/jet/compiler/ReadJavaBinaryClassTest.java index 251107a40a0..d020a824af8 100644 --- a/compiler/tests/org/jetbrains/jet/compiler/ReadJavaBinaryClassTest.java +++ b/compiler/tests/org/jetbrains/jet/compiler/ReadJavaBinaryClassTest.java @@ -86,7 +86,7 @@ public class ReadJavaBinaryClassTest extends TestCaseWithTmpdir { BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegrationAndCheckForErrors( psiFile, JetControlFlowDataTraceFactory.EMPTY, - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS)) + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS, true)) .getBindingContext(); return bindingContext.get(BindingContext.FQNAME_TO_NAMESPACE_DESCRIPTOR, FqName.topLevel("test")); } @@ -114,7 +114,7 @@ public class ReadJavaBinaryClassTest extends TestCaseWithTmpdir { jetCoreEnvironment.addToClasspath(new File("out/production/runtime")); InjectorForJavaSemanticServices injector = new InjectorForJavaSemanticServices( - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS), jetCoreEnvironment.getProject()); + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS, true), jetCoreEnvironment.getProject()); JavaDescriptorResolver javaDescriptorResolver = injector.getJavaDescriptorResolver(); return javaDescriptorResolver.resolveNamespace(FqName.topLevel("test"), DescriptorSearchRule.ERROR_IF_FOUND_IN_KOTLIN); } diff --git a/compiler/tests/org/jetbrains/jet/compiler/ReadKotlinBinaryClassTest.java b/compiler/tests/org/jetbrains/jet/compiler/ReadKotlinBinaryClassTest.java index cd07037c40b..6eda371a5d7 100644 --- a/compiler/tests/org/jetbrains/jet/compiler/ReadKotlinBinaryClassTest.java +++ b/compiler/tests/org/jetbrains/jet/compiler/ReadKotlinBinaryClassTest.java @@ -90,7 +90,7 @@ public class ReadKotlinBinaryClassTest extends TestCaseWithTmpdir { jetCoreEnvironment.addToClasspath(new File("out/production/runtime")); InjectorForJavaSemanticServices injector = new InjectorForJavaSemanticServices( - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS), jetCoreEnvironment.getProject()); + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS, true), jetCoreEnvironment.getProject()); JavaDescriptorResolver javaDescriptorResolver = injector.getJavaDescriptorResolver(); NamespaceDescriptor namespaceFromClass = javaDescriptorResolver.resolveNamespace(FqName.topLevel("test"), DescriptorSearchRule.ERROR_IF_FOUND_IN_KOTLIN); diff --git a/compiler/tests/org/jetbrains/jet/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java b/compiler/tests/org/jetbrains/jet/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java index a5b9c30a7ba..4a0fc6eb85a 100644 --- a/compiler/tests/org/jetbrains/jet/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java +++ b/compiler/tests/org/jetbrains/jet/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java @@ -59,7 +59,7 @@ public class ResolveDescriptorsFromExternalLibraries { public ResolveDescriptorsFromExternalLibraries() { System.out.println("Getting compiler dependencies"); - compilerDependencies = CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR); + compilerDependencies = CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, true); } private void run() throws Exception { diff --git a/compiler/tests/org/jetbrains/jet/resolve/DescriptorRendererTest.java b/compiler/tests/org/jetbrains/jet/resolve/DescriptorRendererTest.java index 002543d7664..fb299b9a079 100644 --- a/compiler/tests/org/jetbrains/jet/resolve/DescriptorRendererTest.java +++ b/compiler/tests/org/jetbrains/jet/resolve/DescriptorRendererTest.java @@ -72,7 +72,7 @@ public class DescriptorRendererTest extends JetLiteFixture { AnalyzeExhaust analyzeExhaust = AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegration( (JetFile) psiFile, JetControlFlowDataTraceFactory.EMPTY, - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR)); + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, true)); final BindingContext bindingContext = analyzeExhaust.getBindingContext(); final List descriptors = new ArrayList(); psiFile.acceptChildren(new JetVisitorVoid() { diff --git a/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java b/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java index bdca4724f4f..f2d236a2e83 100644 --- a/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java +++ b/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java @@ -143,7 +143,7 @@ public abstract class ExpectedResolveData { AnalyzeExhaust analyzeExhaust = AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(project, files, Predicates.alwaysTrue(), JetControlFlowDataTraceFactory.EMPTY, - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR)); + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, true)); BindingContext bindingContext = analyzeExhaust.getBindingContext(); for (Diagnostic diagnostic : bindingContext.getDiagnostics()) { if (diagnostic.getFactory() instanceof UnresolvedReferenceDiagnosticFactory) { diff --git a/compiler/tests/org/jetbrains/jet/resolve/JetResolveTest.java b/compiler/tests/org/jetbrains/jet/resolve/JetResolveTest.java index 71abc9c1354..6540ba315cd 100644 --- a/compiler/tests/org/jetbrains/jet/resolve/JetResolveTest.java +++ b/compiler/tests/org/jetbrains/jet/resolve/JetResolveTest.java @@ -127,7 +127,7 @@ public class JetResolveTest extends ExtensibleResolveTestCase { private PsiClass findClass(String qualifiedName) { Project project = getProject(); InjectorForJavaSemanticServices injector = new InjectorForJavaSemanticServices( - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR), project); + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, true), project); return injector.getPsiClassFinderForJvm().findPsiClass(new FqName(qualifiedName), PsiClassFinder.RuntimeClassesHandleMode.THROW); } diff --git a/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java b/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java index fd69fc0031e..1a2a064a398 100644 --- a/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java +++ b/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java @@ -67,7 +67,7 @@ public class JetDefaultModalityModifiersTest extends JetLiteFixture { assert aClass instanceof JetClass; AnalyzeExhaust bindingContext = AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegration(file, JetControlFlowDataTraceFactory.EMPTY, - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR)); + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, true)); DeclarationDescriptor classDescriptor = bindingContext.getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, aClass); WritableScopeImpl scope = new WritableScopeImpl(libraryScope, root, RedeclarationHandler.DO_NOTHING); assert classDescriptor instanceof ClassifierDescriptor; diff --git a/compiler/tests/org/jetbrains/jet/types/JetTypeCheckerTest.java b/compiler/tests/org/jetbrains/jet/types/JetTypeCheckerTest.java index 5416440ec5f..400b00ff07d 100644 --- a/compiler/tests/org/jetbrains/jet/types/JetTypeCheckerTest.java +++ b/compiler/tests/org/jetbrains/jet/types/JetTypeCheckerTest.java @@ -587,7 +587,7 @@ public class JetTypeCheckerTest extends JetLiteFixture { WritableScopeImpl writableScope = new WritableScopeImpl(scope, scope.getContainingDeclaration(), RedeclarationHandler.DO_NOTHING); writableScope.importScope(library.getLibraryScope()); InjectorForJavaSemanticServices injector = new InjectorForJavaSemanticServices( - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR), getProject()); + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, true), getProject()); JavaDescriptorResolver javaDescriptorResolver = injector.getJavaDescriptorResolver(); writableScope.importScope(javaDescriptorResolver.resolveNamespace(FqName.ROOT, DescriptorSearchRule.INCLUDE_KOTLIN).getMemberScope()); From b1b9446f13918e2d4f4a8e4a85a9e80bc34b0a51 Mon Sep 17 00:00:00 2001 From: pTalanov Date: Wed, 25 Apr 2012 18:25:31 +0400 Subject: [PATCH 144/147] Fix warnings in K2JSRunConfiguration --- .idea/inspectionProfiles/idea_default.xml | 3 --- .../jetbrains/jet/plugin/k2jsrun/K2JSRunConfiguration.java | 4 ++++ 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.idea/inspectionProfiles/idea_default.xml b/.idea/inspectionProfiles/idea_default.xml index 8014ee92b70..87c20723c79 100644 --- a/.idea/inspectionProfiles/idea_default.xml +++ b/.idea/inspectionProfiles/idea_default.xml @@ -409,9 +409,6 @@ diff --git a/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfiguration.java b/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfiguration.java index 88e0730ee9a..16154253090 100644 --- a/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfiguration.java +++ b/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunConfiguration.java @@ -38,6 +38,7 @@ import org.jetbrains.annotations.NotNull; /** * @author Pavel Talanov */ +@SuppressWarnings("deprecation") public final class K2JSRunConfiguration extends RunConfigurationBase implements RunConfigurationWithSuppressedDefaultRunAction { @@ -78,14 +79,17 @@ public final class K2JSRunConfiguration extends RunConfigurationBase @Override public ExecutionResult execute(Executor executor, @NotNull ProgramRunner runner) throws ExecutionException { return new ExecutionResult() { + @Override public ExecutionConsole getExecutionConsole() { return null; } + @Override public AnAction[] getActions() { return AnAction.EMPTY_ARRAY; } + @Override public ProcessHandler getProcessHandler() { return null; } From d0d5b147f2b05710b0dc79950a6717c056098535 Mon Sep 17 00:00:00 2001 From: pTalanov Date: Wed, 25 Apr 2012 20:19:15 +0400 Subject: [PATCH 145/147] Refactor cli: all the jvm stuff goes under org.jetbrains.jet.cli.jvm, common stuff under org.jetbrains.jet.cli.common --- bin/kotlin | 2 +- .../buildtools/ant/BytecodeCompilerTask.java | 2 +- .../jet/buildtools/core/BytecodeCompiler.java | 7 +- build.xml | 8 +- .../jetbrains/jet/compiler/TipsManager.java | 211 ------- compiler/cli/bin/kotlinc | 2 +- compiler/cli/bin/kotlinc.bat | 2 +- .../jetbrains/jet/cli/CompilerArguments.java | 165 ----- .../jetbrains/jet/cli/CompilerVersion.java | 26 - .../org/jetbrains/jet/cli/KotlinCompiler.java | 313 ---------- .../jet/compiler/CliJetFilesProvider.java | 60 -- .../CompileEnvironmentConfiguration.java | 65 -- .../compiler/CompileEnvironmentException.java | 34 -- .../jet/compiler/CompileEnvironmentUtil.java | 294 --------- .../jet/compiler/CompilerPlugin.java | 25 - .../jet/compiler/CompilerPluginContext.java | 51 -- .../jet/compiler/JetCoreEnvironment.java | 155 ----- .../compiler/KotlinToJVMBytecodeCompiler.java | 280 --------- .../compiler/ModuleExecutionException.java | 34 -- .../messages/AnalyzerWithCompilerReport.java | 151 ----- .../messages/CompilerMessageLocation.java | 57 -- .../messages/CompilerMessageSeverity.java | 32 - .../compiler/messages/MessageCollector.java | 31 - .../compiler/messages/MessageRenderer.java | 99 --- .../jet/compiler/messages/MessageUtil.java | 32 - compiler/integration-tests/data/help.gold | 2 +- .../kotlin/KotlinIntegrationTestBase.java | 2 +- .../org/jetbrains/jet/JetLiteFixture.java | 3 +- .../tests/org/jetbrains/jet/JetTestUtils.java | 2 +- .../jet/codegen/CompileTextTest.java | 10 +- .../jetbrains/jet/codegen/TestlibTest.java | 6 +- .../ForTestCompileBuiltins.java | 7 +- .../ForTestCompileJdkHeaders.java | 7 +- .../forTestCompile/ForTestCompileRuntime.java | 13 +- .../jet/compiler/CompileEnvironmentTest.java | 103 ---- .../CompileJavaAgainstKotlinTest.java | 113 ---- .../CompileKotlinAgainstKotlinTest.java | 133 ---- .../compiler/JavaDescriptorResolverTest.java | 72 --- .../jet/compiler/NamespaceComparator.java | 568 ------------------ .../jet/compiler/ReadJavaBinaryClassTest.java | 132 ---- .../compiler/ReadKotlinBinaryClassTest.java | 110 ---- .../jet/compiler/TestCaseWithTmpdir.java | 37 -- .../jet/compiler/WriteSignatureTest.java | 316 ---------- .../jet/compiler/longTest/LibFromMaven.java | 57 -- ...solveDescriptorsFromExternalLibraries.java | 199 ------ .../jet/plugin/compiler/JetCompiler.java | 19 +- .../plugin/compiler/JetCompilerManager.java | 7 +- .../completion/JetCompletionContributor.java | 2 +- .../completion/JetPackagesContributor.java | 2 +- .../macro/BaseJetVariableMacro.java | 2 +- .../JetFunctionParameterInfoHandler.java | 2 +- .../refactoring/JetNameValidatorImpl.java | 2 +- .../references/JetSimpleNameReference.java | 2 +- .../libraries/AbstractLibrariesTest.java | 9 +- .../k2js/test/TestWithEnvironment.java | 2 +- .../jetbrains/kotlin/maven/doc/KDocMojo.java | 10 +- .../kotlin/doc/JavadocStyleHtmlDoclet.kt | 2 +- .../kotlin/org/jetbrains/kotlin/doc/KDoc.kt | 2 +- .../org/jetbrains/kotlin/doc/KDocCompiler.kt | 18 +- .../doc/highlighter/HtmlCompilerPlugin.kt | 4 +- .../kotlin/doc/model/KModelCompilerPlugin.kt | 4 +- .../test/kotlin/kdoc/HtmlVisitorTest.kt | 8 +- .../kotlin/maven/K2JSCompilerMojo.java | 4 +- .../kotlin/maven/K2JSCompilerPlugin.java | 4 +- .../kotlin/maven/KotlinCompileMojo.java | 4 +- .../kotlin/maven/KotlinCompileMojoBase.java | 26 +- .../kotlin/maven/KotlinTestCompileMojo.java | 4 +- 67 files changed, 113 insertions(+), 4056 deletions(-) delete mode 100644 compiler/backend/src/org/jetbrains/jet/compiler/TipsManager.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/cli/CompilerArguments.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/cli/CompilerVersion.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/CliJetFilesProvider.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentConfiguration.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentException.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentUtil.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/CompilerPlugin.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/CompilerPluginContext.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/JetCoreEnvironment.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/ModuleExecutionException.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/messages/AnalyzerWithCompilerReport.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/messages/CompilerMessageLocation.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/messages/CompilerMessageSeverity.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageCollector.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageRenderer.java delete mode 100644 compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageUtil.java delete mode 100644 compiler/tests/org/jetbrains/jet/compiler/CompileEnvironmentTest.java delete mode 100644 compiler/tests/org/jetbrains/jet/compiler/CompileJavaAgainstKotlinTest.java delete mode 100644 compiler/tests/org/jetbrains/jet/compiler/CompileKotlinAgainstKotlinTest.java delete mode 100644 compiler/tests/org/jetbrains/jet/compiler/JavaDescriptorResolverTest.java delete mode 100644 compiler/tests/org/jetbrains/jet/compiler/NamespaceComparator.java delete mode 100644 compiler/tests/org/jetbrains/jet/compiler/ReadJavaBinaryClassTest.java delete mode 100644 compiler/tests/org/jetbrains/jet/compiler/ReadKotlinBinaryClassTest.java delete mode 100644 compiler/tests/org/jetbrains/jet/compiler/TestCaseWithTmpdir.java delete mode 100644 compiler/tests/org/jetbrains/jet/compiler/WriteSignatureTest.java delete mode 100644 compiler/tests/org/jetbrains/jet/compiler/longTest/LibFromMaven.java delete mode 100644 compiler/tests/org/jetbrains/jet/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java diff --git a/bin/kotlin b/bin/kotlin index e456ffbe73d..5cca3809cde 100755 --- a/bin/kotlin +++ b/bin/kotlin @@ -24,7 +24,7 @@ classpath="$classpath:$root/lib/*:$ideaRoot/lib/*:$ideaRoot/lib/rt/*" exec java $JAVA_OPTS \ -classpath "$classpath" \ - org.jetbrains.jet.cli.KotlinCompiler \ + org.jetbrains.jet.cli.jvm.K2JVMCompiler \ "$@" # vim: set ts=4 sw=4 et: diff --git a/build-tools/ant/src/org/jetbrains/jet/buildtools/ant/BytecodeCompilerTask.java b/build-tools/ant/src/org/jetbrains/jet/buildtools/ant/BytecodeCompilerTask.java index 95c745b429c..7d0099cf964 100644 --- a/build-tools/ant/src/org/jetbrains/jet/buildtools/ant/BytecodeCompilerTask.java +++ b/build-tools/ant/src/org/jetbrains/jet/buildtools/ant/BytecodeCompilerTask.java @@ -21,7 +21,7 @@ import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import org.jetbrains.jet.buildtools.core.BytecodeCompiler; -import org.jetbrains.jet.compiler.CompileEnvironmentException; +import org.jetbrains.jet.cli.jvm.compiler.CompileEnvironmentException; import java.io.File; diff --git a/build-tools/core/src/org/jetbrains/jet/buildtools/core/BytecodeCompiler.java b/build-tools/core/src/org/jetbrains/jet/buildtools/core/BytecodeCompiler.java index 6e886343e5f..d03683a331b 100644 --- a/build-tools/core/src/org/jetbrains/jet/buildtools/core/BytecodeCompiler.java +++ b/build-tools/core/src/org/jetbrains/jet/buildtools/core/BytecodeCompiler.java @@ -19,8 +19,9 @@ package org.jetbrains.jet.buildtools.core; import jet.modules.Module; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.compiler.*; -import org.jetbrains.jet.compiler.messages.MessageCollector; +import org.jetbrains.jet.cli.common.CompilerPlugin; +import org.jetbrains.jet.cli.jvm.compiler.*; +import org.jetbrains.jet.cli.common.messages.MessageCollector; import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; @@ -41,7 +42,7 @@ public class BytecodeCompiler { /** - * Creates new instance of {@link org.jetbrains.jet.compiler.CompileEnvironmentConfiguration} instance using the arguments specified. + * Creates new instance of {@link org.jetbrains.jet.cli.jvm.compiler.CompileEnvironmentConfiguration} instance using the arguments specified. * * @param stdlib path to "kotlin-runtime.jar", only used if not null and not empty * @param classpath compilation classpath, only used if not null and not empty diff --git a/build.xml b/build.xml index f5260c35565..cdee4e237a9 100644 --- a/build.xml +++ b/build.xml @@ -54,7 +54,7 @@ - + @@ -72,7 +72,7 @@ - + @@ -88,7 +88,7 @@ - + @@ -210,7 +210,7 @@ - + diff --git a/compiler/backend/src/org/jetbrains/jet/compiler/TipsManager.java b/compiler/backend/src/org/jetbrains/jet/compiler/TipsManager.java deleted file mode 100644 index 8b6cb8c4a16..00000000000 --- a/compiler/backend/src/org/jetbrains/jet/compiler/TipsManager.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import com.google.common.base.Predicate; -import com.google.common.collect.Collections2; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.lang.descriptors.CallableDescriptor; -import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; -import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor; -import org.jetbrains.jet.lang.psi.JetExpression; -import org.jetbrains.jet.lang.psi.JetImportDirective; -import org.jetbrains.jet.lang.psi.JetNamespaceHeader; -import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; -import org.jetbrains.jet.lang.resolve.BindingContext; -import org.jetbrains.jet.lang.resolve.calls.autocasts.AutoCastServiceImpl; -import org.jetbrains.jet.lang.resolve.calls.autocasts.DataFlowInfo; -import org.jetbrains.jet.lang.resolve.scopes.JetScope; -import org.jetbrains.jet.lang.resolve.scopes.JetScopeUtils; -import org.jetbrains.jet.lang.resolve.scopes.receivers.ExpressionReceiver; -import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverDescriptor; -import org.jetbrains.jet.lang.types.JetType; -import org.jetbrains.jet.lang.types.NamespaceType; -import org.jetbrains.jet.lang.types.expressions.ExpressionTypingUtils; - -import java.util.*; - -/** - * @author Nikolay Krasko, Alefas - */ -public final class TipsManager { - - private TipsManager() { - } - - @NotNull - public static Collection getReferenceVariants(JetSimpleNameExpression expression, BindingContext context) { - JetExpression receiverExpression = expression.getReceiverExpression(); - if (receiverExpression != null) { - // Process as call expression - final JetScope resolutionScope = context.get(BindingContext.RESOLUTION_SCOPE, expression); - final JetType expressionType = context.get(BindingContext.EXPRESSION_TYPE, receiverExpression); - - if (expressionType != null && resolutionScope != null) { - if (!(expressionType instanceof NamespaceType)) { - ExpressionReceiver receiverDescriptor = new ExpressionReceiver(receiverExpression, expressionType); - Set descriptors = new HashSet(); - - DataFlowInfo info = context.get(BindingContext.NON_DEFAULT_EXPRESSION_DATA_FLOW, expression); - if (info == null) { - info = DataFlowInfo.EMPTY; - } - - AutoCastServiceImpl autoCastService = new AutoCastServiceImpl(info, context); - List variantsForExplicitReceiver = autoCastService.getVariantsForReceiver(receiverDescriptor); - - for (ReceiverDescriptor descriptor : variantsForExplicitReceiver) { - descriptors.addAll(includeExternalCallableExtensions( - excludePrivateDescriptors(descriptor.getType().getMemberScope().getAllDescriptors()), - resolutionScope, descriptor)); - } - - return descriptors; - } - - return includeExternalCallableExtensions( - excludePrivateDescriptors(expressionType.getMemberScope().getAllDescriptors()), - resolutionScope, new ExpressionReceiver(receiverExpression, expressionType)); - } - return Collections.emptyList(); - } - else { - return getVariantsNoReceiver(expression, context); - } - } - - public static Collection getVariantsNoReceiver(JetExpression expression, BindingContext context) { - JetScope resolutionScope = context.get(BindingContext.RESOLUTION_SCOPE, expression); - if (resolutionScope != null) { - if (expression.getParent() instanceof JetImportDirective || expression.getParent() instanceof JetNamespaceHeader) { - return excludeNonPackageDescriptors(resolutionScope.getAllDescriptors()); - } - else { - HashSet descriptorsSet = Sets.newHashSet(); - - ArrayList result = new ArrayList(); - resolutionScope.getImplicitReceiversHierarchy(result); - - for (ReceiverDescriptor receiverDescriptor : result) { - JetType receiverType = receiverDescriptor.getType(); - descriptorsSet.addAll(receiverType.getMemberScope().getAllDescriptors()); - } - - descriptorsSet.addAll(resolutionScope.getAllDescriptors()); - return excludeNotCallableExtensions(excludePrivateDescriptors(descriptorsSet), resolutionScope); - } - } - return Collections.emptyList(); - } - - @NotNull - public static Collection getReferenceVariants(JetNamespaceHeader expression, BindingContext context) { - JetScope resolutionScope = context.get(BindingContext.RESOLUTION_SCOPE, expression); - if (resolutionScope != null) { - return excludeNonPackageDescriptors(resolutionScope.getAllDescriptors()); - } - - return Collections.emptyList(); - } - - public static Collection excludePrivateDescriptors( - @NotNull Collection descriptors) { - - return Collections2.filter(descriptors, new Predicate() { - @Override - public boolean apply(@Nullable DeclarationDescriptor descriptor) { - if (descriptor == null) { - return false; - } - - if (descriptor instanceof NamespaceDescriptor) { - NamespaceDescriptor namespaceDescriptor = (NamespaceDescriptor) descriptor; - if (namespaceDescriptor.getName().isEmpty()) { - return false; - } - } - - return true; - } - }); - } - - public static Collection excludeNotCallableExtensions( - @NotNull Collection descriptors, @NotNull final JetScope scope - ) { - final Set descriptorsSet = Sets.newHashSet(descriptors); - - final ArrayList result = new ArrayList(); - scope.getImplicitReceiversHierarchy(result); - - descriptorsSet.removeAll( - Collections2.filter(JetScopeUtils.getAllExtensions(scope), new Predicate() { - @Override - public boolean apply(CallableDescriptor callableDescriptor) { - if (!callableDescriptor.getReceiverParameter().exists()) { - return false; - } - for (ReceiverDescriptor receiverDescriptor : result) { - if (ExpressionTypingUtils.checkIsExtensionCallable(receiverDescriptor, callableDescriptor)) { - return false; - } - } - return true; - } - })); - - return Lists.newArrayList(descriptorsSet); - } - - private static Collection excludeNonPackageDescriptors( - @NotNull Collection descriptors) { - return Collections2.filter(descriptors, new Predicate() { - @Override - public boolean apply(DeclarationDescriptor declarationDescriptor) { - return declarationDescriptor instanceof NamespaceDescriptor; - } - }); - } - - private static Set includeExternalCallableExtensions( - @NotNull Collection descriptors, - @NotNull final JetScope externalScope, - @NotNull final ReceiverDescriptor receiverDescriptor - ) { - // It's impossible to add extension function for namespace - JetType receiverType = receiverDescriptor.getType(); - if (receiverType instanceof NamespaceType) { - return new HashSet(descriptors); - } - - Set descriptorsSet = Sets.newHashSet(descriptors); - - descriptorsSet.addAll( - Collections2.filter(JetScopeUtils.getAllExtensions(externalScope), - new Predicate() { - @Override - public boolean apply(CallableDescriptor callableDescriptor) { - return ExpressionTypingUtils.checkIsExtensionCallable(receiverDescriptor, callableDescriptor); - } - })); - - return descriptorsSet; - } -} diff --git a/compiler/cli/bin/kotlinc b/compiler/cli/bin/kotlinc index 78cde18cb55..22858259c8b 100644 --- a/compiler/cli/bin/kotlinc +++ b/compiler/cli/bin/kotlinc @@ -95,4 +95,4 @@ CPSELECT="-cp " $JAVA_OPTS \ "${java_args[@]}" \ ${CPSELECT}${TOOL_CLASSPATH} \ - org.jetbrains.jet.cli.KotlinCompiler "$@" + org.jetbrains.jet.cli.jvm.K2JVMCompiler "$@" diff --git a/compiler/cli/bin/kotlinc.bat b/compiler/cli/bin/kotlinc.bat index 4fb6990f3b9..803309766f0 100644 --- a/compiler/cli/bin/kotlinc.bat +++ b/compiler/cli/bin/kotlinc.bat @@ -27,7 +27,7 @@ if "%_TOOL_CLASSPATH%"=="" ( for /d %%f in ("%_KOTLIN_HOME%\lib\*") do call :add_cpath "%%f" ) -"%_JAVACMD%" %_JAVA_OPTS% -cp "%_TOOL_CLASSPATH%" org.jetbrains.jet.cli.KotlinCompiler %* +"%_JAVACMD%" %_JAVA_OPTS% -cp "%_TOOL_CLASSPATH%" org.jetbrains.jet.cli.jvm.K2JVMCompiler %* goto end rem ########################################################################## diff --git a/compiler/cli/src/org/jetbrains/jet/cli/CompilerArguments.java b/compiler/cli/src/org/jetbrains/jet/cli/CompilerArguments.java deleted file mode 100644 index ee233809581..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/cli/CompilerArguments.java +++ /dev/null @@ -1,165 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.jet.cli; - -import com.sampullara.cli.Argument; -import org.jetbrains.jet.compiler.CompilerPlugin; - -import java.util.ArrayList; -import java.util.List; - -/** - * Command line arguments for the {@link KotlinCompiler} - */ -public class CompilerArguments { - private List compilerPlugins = new ArrayList(); - - // TODO ideally we'd unify this with 'src' to just having a single field that supports multiple files/dirs - private List sourceDirs; - - public List getSourceDirs() { - return sourceDirs; - } - - public void setSourceDirs(List sourceDirs) { - this.sourceDirs = sourceDirs; - } - - @Argument(value = "output", description = "output directory") - public String outputDir; - - @Argument(value = "jar", description = "jar file name") - public String jar; - - @Argument(value = "src", description = "source file or directory") - public String src; - - @Argument(value = "module", description = "module to compile") - public String module; - - @Argument(value = "classpath", description = "classpath to use when compiling") - public String classpath; - - @Argument(value = "includeRuntime", description = "include Kotlin runtime in to resulting jar") - public boolean includeRuntime; - - @Argument(value = "stdlib", description = "Path to the stdlib.jar") - public String stdlib; - - @Argument(value = "jdkHeaders", description = "Path to the kotlin-jdk-headers.jar") - public String jdkHeaders; - - @Argument(value = "help", alias = "h", description = "show help") - public boolean help; - - @Argument(value = "mode", description = "Special compiler modes: stubs or jdkHeaders") - public String mode; - - @Argument(value = "tags", description = "Demarcate each compilation message (error, warning, etc) with an open and close tag") - public boolean tags; - - @Argument(value = "verbose", description = "Enable verbose logging output") - public boolean verbose; - - @Argument(value = "version", description = "Display compiler version") - public boolean version; - - - public String getClasspath() { - return classpath; - } - - public void setClasspath(String classpath) { - this.classpath = classpath; - } - - public boolean isHelp() { - return help; - } - - public void setHelp(boolean help) { - this.help = help; - } - - public boolean isIncludeRuntime() { - return includeRuntime; - } - - public void setIncludeRuntime(boolean includeRuntime) { - this.includeRuntime = includeRuntime; - } - - public String getJar() { - return jar; - } - - public void setJar(String jar) { - this.jar = jar; - } - - public String getModule() { - return module; - } - - public void setModule(String module) { - this.module = module; - } - - public String getOutputDir() { - return outputDir; - } - - public void setOutputDir(String outputDir) { - this.outputDir = outputDir; - } - - public String getSrc() { - return src; - } - - public void setSrc(String src) { - this.src = src; - } - - public String getStdlib() { - return stdlib; - } - - public void setStdlib(String stdlib) { - this.stdlib = stdlib; - } - - public boolean isTags() { - return tags; - } - - public void setTags(boolean tags) { - this.tags = tags; - } - - public List getCompilerPlugins() { - return compilerPlugins; - } - - /** - * Sets the compiler plugins to be used when working with the {@link KotlinCompiler} - */ - public void setCompilerPlugins(List compilerPlugins) { - this.compilerPlugins = compilerPlugins; - } -} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/CompilerVersion.java b/compiler/cli/src/org/jetbrains/jet/cli/CompilerVersion.java deleted file mode 100644 index 674ba94041d..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/cli/CompilerVersion.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.cli; - -/** - * @author abreslav - */ -public class CompilerVersion { - // The value of this constant is generated by the build script - // DON'T MODIFY IT - public static final String VERSION = "@snapshot@"; -} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java b/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java deleted file mode 100644 index 39e831d789f..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/cli/KotlinCompiler.java +++ /dev/null @@ -1,313 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.cli; - -import com.google.common.base.Splitter; -import com.google.common.collect.Iterables; -import com.google.common.collect.LinkedHashMultimap; -import com.google.common.collect.Multimap; -import com.intellij.openapi.Disposable; -import com.intellij.openapi.util.Disposer; -import com.sampullara.cli.Args; -import jet.modules.Module; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.codegen.CompilationException; -import org.jetbrains.jet.compiler.*; -import org.jetbrains.jet.compiler.messages.*; -import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; -import org.jetbrains.jet.utils.PathUtil; - -import java.io.File; -import java.io.PrintStream; -import java.util.Collection; -import java.util.List; - -import static org.jetbrains.jet.cli.KotlinCompiler.ExitCode.*; - -/** - * @author yole - * @author alex.tkachman - */ -@SuppressWarnings("UseOfSystemOutOrSystemErr") -public class KotlinCompiler { - - public enum ExitCode { - OK(0), - COMPILATION_ERROR(1), - INTERNAL_ERROR(2); - - private final int code; - - private ExitCode(int code) { - this.code = code; - } - - public int getCode() { - return code; - } - } - - public static void main(String... args) { - doMain(new KotlinCompiler(), args); - } - - /** - * Useful main for derived command line tools - */ - public static void doMain(KotlinCompiler compiler, String[] args) { - try { - ExitCode rc = compiler.exec(System.out, args); - if (rc != OK) { - System.err.println("exec() finished with " + rc + " return code"); - System.exit(rc.getCode()); - } - } - catch (CompileEnvironmentException e) { - System.err.println(e.getMessage()); - System.exit(INTERNAL_ERROR.getCode()); - } - } - - public ExitCode exec(PrintStream errStream, String... args) { - CompilerArguments arguments = createArguments(); - if (!parseArguments(errStream, arguments, args)) { - return INTERNAL_ERROR; - } - return exec(errStream, arguments); - } - - /** - * Executes the compiler on the parsed arguments - */ - public ExitCode exec(final PrintStream errStream, CompilerArguments arguments) { - if (arguments.help) { - usage(errStream); - return OK; - } - System.setProperty("java.awt.headless", "true"); - - final MessageRenderer messageRenderer = arguments.tags ? MessageRenderer.TAGS : MessageRenderer.PLAIN; - - errStream.print(messageRenderer.renderPreamble()); - - try { - if (arguments.version) { - errStream.println(messageRenderer.render(CompilerMessageSeverity.INFO, "Kotlin Compiler version " + CompilerVersion.VERSION, CompilerMessageLocation.NO_LOCATION)); - } - - CompilerSpecialMode mode = parseCompilerSpecialMode(arguments); - - File jdkHeadersJar; - if (mode.includeJdkHeaders()) { - if (arguments.jdkHeaders != null) { - jdkHeadersJar = new File(arguments.jdkHeaders); - } - else { - jdkHeadersJar = PathUtil.getAltHeadersPath(); - } - } - else { - jdkHeadersJar = null; - } - File runtimeJar; - - if (mode.includeKotlinRuntime()) { - if (arguments.stdlib != null) { - runtimeJar = new File(arguments.stdlib); - } - else { - runtimeJar = PathUtil.getDefaultRuntimePath(); - } - } - else { - runtimeJar = null; - } - - CompilerDependencies dependencies = new CompilerDependencies(mode, CompilerDependencies.findRtJar(), jdkHeadersJar, runtimeJar); - PrintingMessageCollector messageCollector = new PrintingMessageCollector(errStream, messageRenderer, arguments.verbose); - Disposable rootDisposable = CompileEnvironmentUtil.createMockDisposable(); - - JetCoreEnvironment environment = new JetCoreEnvironment(rootDisposable, dependencies); - CompileEnvironmentConfiguration configuration = new CompileEnvironmentConfiguration(environment, dependencies, messageCollector); - - messageCollector.report(CompilerMessageSeverity.LOGGING, "Configuring the compilation environment", - CompilerMessageLocation.NO_LOCATION); - try { - configureEnvironment(configuration, arguments); - - boolean noErrors; - if (arguments.module != null) { - List modules = CompileEnvironmentUtil.loadModuleScript(arguments.module, new PrintingMessageCollector(errStream, messageRenderer, false)); - File directory = new File(arguments.module).getParentFile(); - noErrors = KotlinToJVMBytecodeCompiler.compileModules(configuration, modules, - directory, arguments.jar, arguments.outputDir, - arguments.includeRuntime); - } - else { - // TODO ideally we'd unify to just having a single field that supports multiple files/dirs - if (arguments.getSourceDirs() != null) { - noErrors = KotlinToJVMBytecodeCompiler.compileBunchOfSourceDirectories(configuration, - arguments.getSourceDirs(), arguments.jar, arguments.outputDir, arguments.includeRuntime); - } - else { - noErrors = KotlinToJVMBytecodeCompiler.compileBunchOfSources(configuration, - arguments.src, arguments.jar, arguments.outputDir, arguments.includeRuntime); - } - } - return noErrors ? OK : COMPILATION_ERROR; - } - catch (CompilationException e) { - messageCollector.report(CompilerMessageSeverity.EXCEPTION, MessageRenderer.PLAIN.renderException(e), - MessageUtil.psiElementToMessageLocation(e.getElement())); - return INTERNAL_ERROR; - } - catch (Throwable t) { - messageCollector.report(CompilerMessageSeverity.EXCEPTION, MessageRenderer.PLAIN.renderException(t), CompilerMessageLocation.NO_LOCATION); - return INTERNAL_ERROR; - } - finally { - Disposer.dispose(rootDisposable); - messageCollector.printToErrStream(); - } - } - finally { - errStream.print(messageRenderer.renderConclusion()); - } - } - - @NotNull - private CompilerSpecialMode parseCompilerSpecialMode(@NotNull CompilerArguments arguments) { - if (arguments.mode == null) { - return CompilerSpecialMode.REGULAR; - } - else { - for (CompilerSpecialMode variant : CompilerSpecialMode.values()) { - if (arguments.mode.equalsIgnoreCase(variant.name().replaceAll("_", ""))) { - return variant; - } - } - } - // TODO: report properly - throw new IllegalArgumentException("unknown compiler mode: " + arguments.mode); - } - - /** - * Returns true if the arguments can be parsed correctly - */ - protected boolean parseArguments(PrintStream errStream, CompilerArguments arguments, String[] args) { - try { - Args.parse(arguments, args); - return true; - } - catch (IllegalArgumentException e) { - usage(errStream); - } - catch (Throwable t) { - // Always use tags - errStream.println(MessageRenderer.TAGS.renderException(t)); - } - return false; - } - - protected void usage(PrintStream target) { - // We should say something like - // Args.usage(target, CompilerArguments.class); - // but currently cli-parser we are using does not support that - // a corresponding patch has been sent to the authors - // For now, we are using this: - - PrintStream oldErr = System.err; - System.setErr(target); - try { - // TODO: use proper argv0 - Args.usage(new CompilerArguments()); - } finally { - System.setErr(oldErr); - } - } - - /** - * Allow derived classes to add additional command line arguments - */ - protected CompilerArguments createArguments() { - return new CompilerArguments(); - } - - /** - * Strategy method to configure the environment, allowing compiler - * based tools to customise their own plugins - */ - protected void configureEnvironment(CompileEnvironmentConfiguration configuration, CompilerArguments arguments) { - // install any compiler plugins - List plugins = arguments.getCompilerPlugins(); - if (plugins != null) { - configuration.getCompilerPlugins().addAll(plugins); - } - - if (configuration.getCompilerDependencies().getRuntimeJar() != null) { - CompileEnvironmentUtil.addToClasspath(configuration.getEnvironment(), configuration.getCompilerDependencies().getRuntimeJar()); - } - - if (arguments.classpath != null) { - final Iterable classpath = Splitter.on(File.pathSeparatorChar).split(arguments.classpath); - CompileEnvironmentUtil.addToClasspath(configuration.getEnvironment(), Iterables.toArray(classpath, String.class)); - } - } - - private static class PrintingMessageCollector implements MessageCollector { - private final boolean verbose; - private final PrintStream errStream; - private final MessageRenderer messageRenderer; - - // File path (nullable) -> error message - private final Multimap groupedMessages = LinkedHashMultimap.create(); - - public PrintingMessageCollector(PrintStream errStream, - MessageRenderer messageRenderer, - boolean verbose) { - this.verbose = verbose; - this.errStream = errStream; - this.messageRenderer = messageRenderer; - } - - @Override - public void report(@NotNull CompilerMessageSeverity severity, - @NotNull String message, - @NotNull CompilerMessageLocation location) { - String text = messageRenderer.render(severity, message, location); - if (severity == CompilerMessageSeverity.LOGGING) { - if (!verbose) { - return; - } - errStream.println(text); - } - groupedMessages.put(location.getPath(), text); - } - - public void printToErrStream() { - if (!groupedMessages.isEmpty()) { - for (String path : groupedMessages.keySet()) { - Collection messageTexts = groupedMessages.get(path); - for (String text : messageTexts) { - errStream.println(text); - } - } - } - } - } -} diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CliJetFilesProvider.java b/compiler/cli/src/org/jetbrains/jet/compiler/CliJetFilesProvider.java deleted file mode 100644 index a5e95ae5696..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CliJetFilesProvider.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * @author max - */ -package org.jetbrains.jet.compiler; - -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.util.Function; -import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.resolve.java.JetFilesProvider; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -public class CliJetFilesProvider extends JetFilesProvider { - private final JetCoreEnvironment environment; - private Function> all_files = new Function>() { - @Override - public Collection fun(JetFile file) { - return environment.getSourceFiles(); - } - - }; - - public CliJetFilesProvider(JetCoreEnvironment environment) { - this.environment = environment; - } - - @Override - public Function> sampleToAllFilesInModule() { - return all_files; - } - - @Override - public List allInScope(GlobalSearchScope scope) { - List answer = new ArrayList(); - for (JetFile file : environment.getSourceFiles()) { - if (scope.contains(file.getVirtualFile())) { - answer.add(file); - } - } - return answer; - } -} diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentConfiguration.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentConfiguration.java deleted file mode 100644 index cf57bee50b2..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentConfiguration.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import com.google.common.collect.Lists; -import com.intellij.openapi.util.Disposer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.compiler.messages.MessageCollector; -import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; - -import java.util.List; - -/** - * @author abreslav - */ -public class CompileEnvironmentConfiguration { - private final JetCoreEnvironment environment; - private final CompilerDependencies compilerDependencies; - private final MessageCollector messageCollector; - - private List compilerPlugins = Lists.newArrayList(); - - /** - * NOTE: It's very important to call dispose for every object of this class or there will be memory leaks. - * @see Disposer - */ - public CompileEnvironmentConfiguration(@NotNull JetCoreEnvironment environment, - @NotNull CompilerDependencies compilerDependencies, @NotNull MessageCollector messageCollector) { - this.messageCollector = messageCollector; - this.compilerDependencies = compilerDependencies; - this.environment = environment; - } - - public JetCoreEnvironment getEnvironment() { - return environment; - } - - @NotNull - public CompilerDependencies getCompilerDependencies() { - return compilerDependencies; - } - - @NotNull - public MessageCollector getMessageCollector() { - return messageCollector; - } - - public List getCompilerPlugins() { - return compilerPlugins; - } -} diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentException.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentException.java deleted file mode 100644 index bf9d8e58c05..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -/** - * @author yole - */ -public class CompileEnvironmentException extends RuntimeException { - public CompileEnvironmentException(String message) { - super(message); - } - - public CompileEnvironmentException(Throwable cause) { - super(cause); - } - - public CompileEnvironmentException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentUtil.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentUtil.java deleted file mode 100644 index 139fcfd72a8..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironmentUtil.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import com.intellij.openapi.Disposable; -import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.psi.JavaPsiFacade; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.util.Processor; -import jet.modules.AllModules; -import jet.modules.Module; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.codegen.ClassFileFactory; -import org.jetbrains.jet.codegen.GeneratedClassLoader; -import org.jetbrains.jet.codegen.GenerationState; -import org.jetbrains.jet.compiler.messages.MessageCollector; -import org.jetbrains.jet.lang.resolve.FqName; -import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; -import org.jetbrains.jet.lang.resolve.java.JvmAbi; -import org.jetbrains.jet.utils.PathUtil; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.lang.reflect.Method; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.List; -import java.util.jar.*; - -/** - * @author abreslav - */ -public class CompileEnvironmentUtil { - public static Disposable createMockDisposable() { - return new Disposable() { - @Override - public void dispose() { - } - }; - } - - @Nullable - public static File getUnpackedRuntimePath() { - URL url = CompileEnvironmentConfiguration.class.getClassLoader().getResource("jet/JetObject.class"); - if (url != null && url.getProtocol().equals("file")) { - return new File(url.getPath()).getParentFile().getParentFile(); - } - return null; - } - - @Nullable - public static File getRuntimeJarPath() { - URL url = CompileEnvironmentConfiguration.class.getClassLoader().getResource("jet/JetObject.class"); - if (url != null && url.getProtocol().equals("jar")) { - String path = url.getPath(); - return new File(path.substring(path.indexOf(":") + 1, path.indexOf("!/"))); - } - return null; - } - - public static void ensureKotlinRuntime(JetCoreEnvironment env) { - if (JavaPsiFacade.getInstance(env.getProject()).findClass("jet.JetObject", GlobalSearchScope.allScope(env.getProject())) == null) { - // TODO: prepend - File kotlin = PathUtil.getDefaultRuntimePath(); - if (kotlin == null || !kotlin.exists()) { - kotlin = getUnpackedRuntimePath(); - if (kotlin == null) kotlin = getRuntimeJarPath(); - } - if (kotlin == null) { - throw new IllegalStateException("kotlin runtime not found"); - } - env.addToClasspath(kotlin); - } - } - - public static void ensureRuntime(JetCoreEnvironment environment, CompilerDependencies compilerDependencies) { - if (compilerDependencies.getCompilerSpecialMode() == CompilerSpecialMode.REGULAR) { - ensureKotlinRuntime(environment); - } - else if (compilerDependencies.getCompilerSpecialMode() == CompilerSpecialMode.JDK_HEADERS) { - } - else if (compilerDependencies.getCompilerSpecialMode() == CompilerSpecialMode.STDLIB) { - } - else if (compilerDependencies.getCompilerSpecialMode() == CompilerSpecialMode.BUILTINS) { - // nop - } - else { - throw new IllegalStateException("unknown mode: " + compilerDependencies.getCompilerSpecialMode()); - } - } - - public static List loadModuleScript(String moduleScriptFile, MessageCollector messageCollector) { - Disposable disposable = new Disposable() { - @Override - public void dispose() { - - } - }; - CompilerDependencies dependencies = CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR); - JetCoreEnvironment scriptEnvironment = new JetCoreEnvironment(disposable, dependencies); - ensureRuntime(scriptEnvironment, dependencies); - scriptEnvironment.addSources(moduleScriptFile); - - GenerationState generationState = KotlinToJVMBytecodeCompiler - .analyzeAndGenerate(new CompileEnvironmentConfiguration(scriptEnvironment, dependencies, messageCollector), false); - if (generationState == null) { - return null; - } - - List modules = runDefineModules(dependencies, moduleScriptFile, generationState.getFactory()); - - Disposer.dispose(disposable); - - if (modules == null) { - throw new CompileEnvironmentException("Module script " + moduleScriptFile + " compilation failed"); - } - - if (modules.isEmpty()) { - throw new CompileEnvironmentException("No modules where defined by " + moduleScriptFile); - } - return modules; - } - - private static List runDefineModules(CompilerDependencies compilerDependencies, String moduleFile, ClassFileFactory factory) { - File stdlibJar = compilerDependencies.getRuntimeJar(); - GeneratedClassLoader loader; - if (stdlibJar != null) { - try { - loader = new GeneratedClassLoader(factory, new URLClassLoader(new URL[]{stdlibJar.toURI().toURL()}, AllModules.class.getClassLoader())); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - } - else { - loader = new GeneratedClassLoader(factory, CompileEnvironmentConfiguration.class.getClassLoader()); - } - try { - Class namespaceClass = loader.loadClass(JvmAbi.PACKAGE_CLASS); - final Method method = namespaceClass.getDeclaredMethod("project"); - if (method == null) { - throw new CompileEnvironmentException("Module script " + moduleFile + " must define project() function"); - } - - method.setAccessible(true); - method.invoke(null); - - ArrayList answer = new ArrayList(AllModules.modules.get()); - AllModules.modules.get().clear(); - return answer; - } - catch (Exception e) { - throw new ModuleExecutionException(e); - } - finally { - loader.dispose(); - } - } - - public static void writeToJar(ClassFileFactory factory, final OutputStream fos, @Nullable FqName mainClass, boolean includeRuntime) { - try { - Manifest manifest = new Manifest(); - final Attributes mainAttributes = manifest.getMainAttributes(); - mainAttributes.putValue("Manifest-Version", "1.0"); - mainAttributes.putValue("Created-By", "JetBrains Kotlin"); - if (mainClass != null) { - mainAttributes.putValue("Main-Class", mainClass.getFqName()); - } - JarOutputStream stream = new JarOutputStream(fos, manifest); - try { - for (String file : factory.files()) { - stream.putNextEntry(new JarEntry(file)); - stream.write(factory.asBytes(file)); - } - if (includeRuntime) { - writeRuntimeToJar(stream); - } - } - finally { - stream.close(); - fos.close(); - } - - } catch (IOException e) { - throw new CompileEnvironmentException("Failed to generate jar file", e); - } - } - - private static void writeRuntimeToJar(final JarOutputStream stream) throws IOException { - final File unpackedRuntimePath = getUnpackedRuntimePath(); - if (unpackedRuntimePath != null) { - FileUtil.processFilesRecursively(unpackedRuntimePath, new Processor() { - @Override - public boolean process(File file) { - if (file.isDirectory()) return true; - final String relativePath = FileUtil.getRelativePath(unpackedRuntimePath, file); - try { - stream.putNextEntry(new JarEntry(FileUtil.toSystemIndependentName(relativePath))); - FileInputStream fis = new FileInputStream(file); - try { - FileUtil.copy(fis, stream); - } - finally { - fis.close(); - } - } - catch (IOException e) { - throw new RuntimeException(e); - } - return true; - } - }); - } - else { - File runtimeJarPath = getRuntimeJarPath(); - if (runtimeJarPath != null) { - JarInputStream jis = new JarInputStream(new FileInputStream(runtimeJarPath)); - try { - while (true) { - JarEntry e = jis.getNextJarEntry(); - if (e == null) { - break; - } - if (FileUtil.getExtension(e.getName()).equals("class")) { - stream.putNextEntry(e); - FileUtil.copy(jis, stream); - } - } - } finally { - jis.close(); - } - } - else { - throw new CompileEnvironmentException("Couldn't find runtime library"); - } - } - } - - public static void writeToOutputDirectory(ClassFileFactory factory, final String outputDir) { - List files = factory.files(); - for (String file : files) { - File target = new File(outputDir, file); - try { - FileUtil.writeToFile(target, factory.asBytes(file)); - } catch (IOException e) { - throw new CompileEnvironmentException(e); - } - } - } - - /** - * Add path specified to the compilation environment. - * @param environment compilation environment to add to - * @param paths paths to add - */ - public static void addToClasspath(JetCoreEnvironment environment, File ... paths) { - for (File path : paths) { - if (!path.exists()) { - throw new CompileEnvironmentException("'" + path + "' does not exist"); - } - environment.addToClasspath(path); - } - } - - /** - * Add path specified to the compilation environment. - * @param environment compilation environment to add to - * @param paths paths to add - */ - public static void addToClasspath(JetCoreEnvironment environment, String ... paths) { - for (String path : paths) { - addToClasspath(environment, new File(path)); - } - } -} diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompilerPlugin.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompilerPlugin.java deleted file mode 100644 index bc2db80c71e..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CompilerPlugin.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -/** - * A simple interface for compiler plugins to run after the compiler has finished such as for things like - * generating documentation or code generation etc - */ -public interface CompilerPlugin { - void processFiles(CompilerPluginContext context); -} diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompilerPluginContext.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompilerPluginContext.java deleted file mode 100644 index 8ce1d7ef805..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CompilerPluginContext.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import com.intellij.openapi.project.Project; -import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.resolve.BindingContext; - -import java.util.List; - -/** - * Represents the context of available state in which a {@link CompilerPlugin} runs such as - * the {@link Project}, the {@link BindingContext} and the underlying {@link JetFile} files. - */ -public class CompilerPluginContext { - private final Project project; - private final BindingContext context; - private final List files; - - public CompilerPluginContext(Project project, BindingContext context, List files) { - this.project = project; - this.context = context; - this.files = files; - } - - public BindingContext getContext() { - return context; - } - - public List getFiles() { - return files; - } - - public Project getProject() { - return project; - } -} diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/JetCoreEnvironment.java b/compiler/cli/src/org/jetbrains/jet/compiler/JetCoreEnvironment.java deleted file mode 100644 index 648ca6a0f15..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/JetCoreEnvironment.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import com.intellij.core.JavaCoreEnvironment; -import com.intellij.lang.java.JavaParserDefinition; -import com.intellij.mock.MockApplication; -import com.intellij.openapi.Disposable; -import com.intellij.openapi.extensions.Extensions; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.PsiElementFinder; -import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiManager; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.asJava.JavaElementFinder; -import org.jetbrains.jet.lang.parsing.JetParserDefinition; -import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; -import org.jetbrains.jet.lang.resolve.java.JetFilesProvider; -import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; -import org.jetbrains.jet.plugin.JetFileType; - -import java.io.File; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.List; - -/** - * @author yole - */ -public class JetCoreEnvironment extends JavaCoreEnvironment { - private final List sourceFiles = new ArrayList(); - - public JetCoreEnvironment(Disposable parentDisposable, @NotNull CompilerDependencies compilerDependencies) { - super(parentDisposable); - registerFileType(JetFileType.INSTANCE, "kt"); - registerFileType(JetFileType.INSTANCE, "kts"); - registerFileType(JetFileType.INSTANCE, "ktm"); - registerFileType(JetFileType.INSTANCE, "jet"); - registerParserDefinition(new JavaParserDefinition()); - registerParserDefinition(new JetParserDefinition()); - - - myProject.registerService(JetFilesProvider.class, new CliJetFilesProvider(this)); - Extensions.getArea(myProject) - .getExtensionPoint(PsiElementFinder.EP_NAME) - .registerExtension(new JavaElementFinder(myProject)); - - CompilerSpecialMode compilerSpecialMode = compilerDependencies.getCompilerSpecialMode(); - - addToClasspath(compilerDependencies.getJdkJar()); - - if (compilerSpecialMode.includeJdkHeaders()) { - for (VirtualFile root : compilerDependencies.getJdkHeaderRoots()) { - addLibraryRoot(root); - } - } - if (compilerSpecialMode.includeKotlinRuntime()) { - for (VirtualFile root : compilerDependencies.getRuntimeRoots()) { - addLibraryRoot(root); - } - } - - JetStandardLibrary.initialize(getProject()); - } - - public MockApplication getApplication() { - return myApplication; - } - - private void addSources(File file) { - if(file.isDirectory()) { - File[] files = file.listFiles(); - if (files != null) { - for (File child : files) { - addSources(child); - } - } - } - else { - VirtualFile fileByPath = getLocalFileSystem().findFileByPath(file.getAbsolutePath()); - if (fileByPath != null) { - PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(fileByPath); - if(psiFile instanceof JetFile) { - sourceFiles.add((JetFile)psiFile); - } - } - } - } - - public void addSources(VirtualFile vFile) { - if (vFile.isDirectory()) { - for (VirtualFile virtualFile : vFile.getChildren()) { - addSources(virtualFile); - } - } - else { - if (vFile.getFileType() == JetFileType.INSTANCE) { - PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(vFile); - if (psiFile instanceof JetFile) { - sourceFiles.add((JetFile)psiFile); - } - } - } - } - - public void addSources(String path) { - if(path == null) - return; - - VirtualFile vFile = getLocalFileSystem().findFileByPath(path); - if (vFile == null) { - throw new CompileEnvironmentException("File/directory not found: " + path); - } - if (!vFile.isDirectory() && vFile.getFileType() != JetFileType.INSTANCE) { - throw new CompileEnvironmentException("Not a Kotlin file: " + path); - } - - addSources(new File(path)); - } - - public List getSourceFiles() { - return sourceFiles; - } - - public void addToClasspathFromClassLoader(ClassLoader loader) { - ClassLoader parent = loader.getParent(); - if(parent != null) - addToClasspathFromClassLoader(parent); - - if(loader instanceof URLClassLoader) { - for (URL url : ((URLClassLoader) loader).getURLs()) { - File file = new File(url.getPath()); - if(file.exists() && (!file.isFile() || file.getPath().endsWith(".jar"))) - addToClasspath(file); - } - } - } -} diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java b/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java deleted file mode 100644 index 6f8798ad661..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/KotlinToJVMBytecodeCompiler.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiFile; -import com.intellij.testFramework.LightVirtualFile; -import com.intellij.util.LocalTimeCounter; -import jet.Function0; -import jet.modules.Module; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.analyzer.AnalyzeExhaust; -import org.jetbrains.jet.codegen.*; -import org.jetbrains.jet.compiler.messages.AnalyzerWithCompilerReport; -import org.jetbrains.jet.compiler.messages.CompilerMessageLocation; -import org.jetbrains.jet.compiler.messages.CompilerMessageSeverity; -import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; -import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.psi.JetPsiUtil; -import org.jetbrains.jet.lang.resolve.FqName; -import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; -import org.jetbrains.jet.lang.resolve.java.JvmAbi; -import org.jetbrains.jet.plugin.JetLanguage; -import org.jetbrains.jet.plugin.JetMainDetector; -import org.jetbrains.jet.utils.Progress; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.util.List; - -/** - * @author yole - * @author abreslav - */ -public class KotlinToJVMBytecodeCompiler { - - private KotlinToJVMBytecodeCompiler() { - } - - @Nullable - public static ClassFileFactory compileModule( - CompileEnvironmentConfiguration configuration, - Module moduleBuilder, - File directory - ) { - if (moduleBuilder.getSourceFiles().isEmpty()) { - throw new CompileEnvironmentException("No source files where defined"); - } - - for (String sourceFile : moduleBuilder.getSourceFiles()) { - File source = new File(sourceFile); - if (!source.isAbsolute()) { - source = new File(directory, sourceFile); - } - - if (!source.exists()) { - throw new CompileEnvironmentException("'" + source + "' does not exist"); - } - - configuration.getEnvironment().addSources(source.getPath()); - } - for (String classpathRoot : moduleBuilder.getClasspathRoots()) { - configuration.getEnvironment().addToClasspath(new File(classpathRoot)); - } - - CompileEnvironmentUtil.ensureRuntime(configuration.getEnvironment(), configuration.getCompilerDependencies()); - - GenerationState generationState = analyzeAndGenerate(configuration); - if (generationState == null) { - return null; - } - return generationState.getFactory(); - } - - public static boolean compileModules( - CompileEnvironmentConfiguration configuration, - - @NotNull List modules, - - @NotNull File directory, - @Nullable String jarPath, - @Nullable String outputDir, - boolean jarRuntime) { - - for (Module moduleBuilder : modules) { - // TODO: this should be done only once for the environment - if (configuration.getCompilerDependencies().getRuntimeJar() != null) { - CompileEnvironmentUtil - .addToClasspath(configuration.getEnvironment(), configuration.getCompilerDependencies().getRuntimeJar()); - } - ClassFileFactory moduleFactory = compileModule(configuration, moduleBuilder, directory); - if (moduleFactory == null) { - return false; - } - if (outputDir != null) { - CompileEnvironmentUtil.writeToOutputDirectory(moduleFactory, outputDir); - } - else { - String path = jarPath != null ? jarPath : new File(directory, moduleBuilder.getModuleName() + ".jar").getPath(); - try { - CompileEnvironmentUtil.writeToJar(moduleFactory, new FileOutputStream(path), null, jarRuntime); - } - catch (FileNotFoundException e) { - throw new CompileEnvironmentException("Invalid jar path " + path, e); - } - } - } - return true; - } - - private static boolean compileBunchOfSources( - CompileEnvironmentConfiguration configuration, - String jar, - String outputDir, - boolean includeRuntime - ) { - FqName mainClass = null; - for (JetFile file : configuration.getEnvironment().getSourceFiles()) { - if (JetMainDetector.hasMain(file.getDeclarations())) { - FqName fqName = JetPsiUtil.getFQName(file); - mainClass = fqName.child(JvmAbi.PACKAGE_CLASS); - break; - } - } - - CompileEnvironmentUtil.ensureRuntime(configuration.getEnvironment(), configuration.getCompilerDependencies()); - - GenerationState generationState = analyzeAndGenerate(configuration); - if (generationState == null) { - return false; - } - - try { - ClassFileFactory factory = generationState.getFactory(); - if (jar != null) { - try { - CompileEnvironmentUtil.writeToJar(factory, new FileOutputStream(jar), mainClass, includeRuntime); - } - catch (FileNotFoundException e) { - throw new CompileEnvironmentException("Invalid jar path " + jar, e); - } - } - else if (outputDir != null) { - CompileEnvironmentUtil.writeToOutputDirectory(factory, outputDir); - } - else { - throw new CompileEnvironmentException("Output directory or jar file is not specified - no files will be saved to the disk"); - } - return true; - } - finally { - generationState.destroy(); - } - } - - public static boolean compileBunchOfSources( - CompileEnvironmentConfiguration configuration, - - String sourceFileOrDir, String jar, String outputDir, boolean includeRuntime) { - configuration.getEnvironment().addSources(sourceFileOrDir); - - return compileBunchOfSources(configuration, jar, outputDir, includeRuntime); - } - - public static boolean compileBunchOfSourceDirectories( - CompileEnvironmentConfiguration configuration, - - List sources, String jar, String outputDir, boolean includeRuntime) { - for (String source : sources) { - configuration.getEnvironment().addSources(source); - } - - return compileBunchOfSources(configuration, jar, outputDir, includeRuntime); - } - - @Nullable - public static ClassLoader compileText( - CompileEnvironmentConfiguration configuration, - String code) { - configuration.getEnvironment() - .addSources(new LightVirtualFile("script" + LocalTimeCounter.currentTime() + ".kt", JetLanguage.INSTANCE, code)); - - GenerationState generationState = analyzeAndGenerate(configuration); - if (generationState == null) { - return null; - } - return new GeneratedClassLoader(generationState.getFactory()); - } - - @Nullable - public static GenerationState analyzeAndGenerate(CompileEnvironmentConfiguration configuration) { - return analyzeAndGenerate(configuration, configuration.getCompilerDependencies().getCompilerSpecialMode().isStubs()); - } - - @Nullable - public static GenerationState analyzeAndGenerate( - CompileEnvironmentConfiguration configuration, - boolean stubs - ) { - AnalyzeExhaust exhaust = analyze(configuration, stubs); - - if (exhaust == null) { - return null; - } - - exhaust.throwIfError(); - - return generate(configuration, exhaust, stubs); - } - - @Nullable - private static AnalyzeExhaust analyze( - final CompileEnvironmentConfiguration configuration, - boolean stubs) { - final JetCoreEnvironment environment = configuration.getEnvironment(); - AnalyzerWithCompilerReport analyzerWithCompilerReport = new AnalyzerWithCompilerReport(configuration.getMessageCollector()); - final Predicate filesToAnalyzeCompletely = - stubs ? Predicates.alwaysFalse() : Predicates.alwaysTrue(); - analyzerWithCompilerReport.analyzeAndReport( - new Function0() { - @NotNull - @Override - public AnalyzeExhaust invoke() { - return AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( - environment.getProject(), environment.getSourceFiles(), filesToAnalyzeCompletely, - JetControlFlowDataTraceFactory.EMPTY, - configuration.getCompilerDependencies()); - } - }, environment.getSourceFiles() - ); - - return analyzerWithCompilerReport.hasErrors() ? null : analyzerWithCompilerReport.getAnalyzeExhaust(); - } - - @NotNull - private static GenerationState generate( - final CompileEnvironmentConfiguration configuration, - AnalyzeExhaust exhaust, - boolean stubs) { - JetCoreEnvironment environment = configuration.getEnvironment(); - Project project = environment.getProject(); - Progress backendProgress = new Progress() { - @Override - public void log(String message) { - configuration.getMessageCollector().report(CompilerMessageSeverity.LOGGING, message, CompilerMessageLocation.NO_LOCATION); - } - }; - GenerationState generationState = new GenerationState(project, ClassBuilderFactories.binaries(stubs), backendProgress, - exhaust, environment.getSourceFiles(), - configuration.getCompilerDependencies().getCompilerSpecialMode()); - generationState.compileCorrectFiles(CompilationErrorHandler.THROW_EXCEPTION); - - List plugins = configuration.getCompilerPlugins(); - if (plugins != null) { - CompilerPluginContext context = new CompilerPluginContext(project, exhaust.getBindingContext(), environment.getSourceFiles()); - for (CompilerPlugin plugin : plugins) { - plugin.processFiles(context); - } - } - return generationState; - } -} diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/ModuleExecutionException.java b/compiler/cli/src/org/jetbrains/jet/compiler/ModuleExecutionException.java deleted file mode 100644 index 67e7a05ea34..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/ModuleExecutionException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -/** - * @author yole - */ -public class ModuleExecutionException extends RuntimeException { - public ModuleExecutionException(String message) { - super(message); - } - - public ModuleExecutionException(Throwable cause) { - super(cause); - } - - public ModuleExecutionException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/messages/AnalyzerWithCompilerReport.java b/compiler/cli/src/org/jetbrains/jet/compiler/messages/AnalyzerWithCompilerReport.java deleted file mode 100644 index 0a5d9812340..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/messages/AnalyzerWithCompilerReport.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler.messages; - -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.PsiErrorElement; -import com.intellij.psi.PsiRecursiveElementWalkingVisitor; -import jet.Function0; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.analyzer.AnalyzeExhaust; -import org.jetbrains.jet.lang.descriptors.ClassDescriptor; -import org.jetbrains.jet.lang.diagnostics.*; -import org.jetbrains.jet.lang.diagnostics.rendering.DefaultErrorMessages; -import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.resolve.BindingContext; -import org.jetbrains.jet.lang.resolve.DescriptorUtils; - -import java.util.Collection; - -/** - * @author Pavel Talanov - */ -public final class AnalyzerWithCompilerReport { - - @NotNull - private static CompilerMessageSeverity convertSeverity(@NotNull Severity severity) { - switch (severity) { - case INFO: - return CompilerMessageSeverity.INFO; - case ERROR: - return CompilerMessageSeverity.ERROR; - case WARNING: - return CompilerMessageSeverity.WARNING; - } - throw new IllegalStateException("Unknown severity: " + severity); - } - - @NotNull - private static final SimpleDiagnosticFactory SYNTAX_ERROR_FACTORY = SimpleDiagnosticFactory.create(Severity.ERROR); - - private boolean hasErrors = false; - @NotNull - private final MessageCollector messageCollectorWrapper; - @Nullable - private AnalyzeExhaust analyzeExhaust = null; - - public AnalyzerWithCompilerReport(@NotNull final MessageCollector collector) { - messageCollectorWrapper = new MessageCollector() { - @Override - public void report(@NotNull CompilerMessageSeverity severity, - @NotNull String message, - @NotNull CompilerMessageLocation location) { - if (CompilerMessageSeverity.ERRORS.contains(severity)) { - hasErrors = true; - } - collector.report(severity, message, location); - } - }; - } - - private void reportDiagnostic(@NotNull Diagnostic diagnostic) { - DiagnosticUtils.LineAndColumn lineAndColumn = DiagnosticUtils.getLineAndColumn(diagnostic); - VirtualFile virtualFile = diagnostic.getPsiFile().getVirtualFile(); - String path = virtualFile == null ? null : virtualFile.getPath(); - String render; - if (diagnostic.getFactory() == SYNTAX_ERROR_FACTORY) { - render = ((SyntaxErrorDiagnostic)diagnostic).message; - } - else { - render = DefaultErrorMessages.RENDERER.render(diagnostic); - } - messageCollectorWrapper.report(convertSeverity(diagnostic.getSeverity()), render, - CompilerMessageLocation.create(path, lineAndColumn.getLine(), lineAndColumn.getColumn())); - } - - private void reportIncompleteHierarchies() { - assert analyzeExhaust != null; - Collection incompletes = analyzeExhaust.getBindingContext().getKeys(BindingContext.INCOMPLETE_HIERARCHY); - if (!incompletes.isEmpty()) { - StringBuilder message = new StringBuilder("The following classes have incomplete hierarchies:\n"); - for (ClassDescriptor incomplete : incompletes) { - String fqName = DescriptorUtils.getFQName(incomplete).getFqName(); - message.append(" ").append(fqName).append("\n"); - } - messageCollectorWrapper.report(CompilerMessageSeverity.ERROR, message.toString(), CompilerMessageLocation.NO_LOCATION); - } - } - - private void reportDiagnostics() { - assert analyzeExhaust != null; - for (Diagnostic diagnostic : analyzeExhaust.getBindingContext().getDiagnostics()) { - reportDiagnostic(diagnostic); - } - } - - private void reportSyntaxErrors(@NotNull Collection files) { - for (JetFile file : files) { - file.accept(new PsiRecursiveElementWalkingVisitor() { - @Override - public void visitErrorElement(PsiErrorElement element) { - String description = element.getErrorDescription(); - String message = StringUtil.isEmpty(description) ? "Syntax error" : description; - Diagnostic diagnostic = new SyntaxErrorDiagnostic(element, Severity.ERROR, message); - reportDiagnostic(diagnostic); - } - }); - } - } - - @Nullable - public AnalyzeExhaust getAnalyzeExhaust() { - return analyzeExhaust; - } - - public boolean hasErrors() { - return hasErrors; - } - - public void analyzeAndReport(@NotNull Function0 analyzer, @NotNull Collection files) { - reportSyntaxErrors(files); - analyzeExhaust = analyzer.invoke(); - reportDiagnostics(); - reportIncompleteHierarchies(); - } - - - public static class SyntaxErrorDiagnostic extends SimpleDiagnostic { - private String message; - - public SyntaxErrorDiagnostic(@NotNull PsiErrorElement psiElement, @NotNull Severity severity, String message) { - super(psiElement, SYNTAX_ERROR_FACTORY, severity); - this.message = message; - } - } -} diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/messages/CompilerMessageLocation.java b/compiler/cli/src/org/jetbrains/jet/compiler/messages/CompilerMessageLocation.java deleted file mode 100644 index f39e6c43a4e..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/messages/CompilerMessageLocation.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler.messages; - -import org.jetbrains.annotations.Nullable; - -/** - * @author abreslav - */ -public class CompilerMessageLocation { - - public static final CompilerMessageLocation NO_LOCATION = new CompilerMessageLocation(null, -1, -1); - - public static CompilerMessageLocation create(@Nullable String path, int line, int column) { - if (path == null) { - return NO_LOCATION; - } - return new CompilerMessageLocation(path, line, column); - } - - private final String path; - private final int line; - private final int column; - - private CompilerMessageLocation(@Nullable String path, int line, int column) { - this.path = path; - this.line = line; - this.column = column; - } - - @Nullable - public String getPath() { - return path; - } - - public int getLine() { - return line; - } - - public int getColumn() { - return column; - } -} diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/messages/CompilerMessageSeverity.java b/compiler/cli/src/org/jetbrains/jet/compiler/messages/CompilerMessageSeverity.java deleted file mode 100644 index 9171be05403..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/messages/CompilerMessageSeverity.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler.messages; - -import java.util.EnumSet; - -/** - * @author abreslav - */ -public enum CompilerMessageSeverity { - INFO, - ERROR, - WARNING, - EXCEPTION, - LOGGING; - - public static final EnumSet ERRORS = EnumSet.of(ERROR, EXCEPTION); -} diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageCollector.java b/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageCollector.java deleted file mode 100644 index 5fb1b0973a0..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageCollector.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler.messages; - -import org.jetbrains.annotations.NotNull; - -public interface MessageCollector { - MessageCollector PLAIN_TEXT_TO_SYSTEM_ERR = new MessageCollector() { - @Override - public void report(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location) { - System.err.println(MessageRenderer.PLAIN.render(severity, message, location)); - } - }; - - void report(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location); -} - diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageRenderer.java b/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageRenderer.java deleted file mode 100644 index eca3c404552..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageRenderer.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler.messages; - -import com.intellij.openapi.util.text.StringUtil; -import org.jetbrains.annotations.NotNull; - -import java.io.PrintWriter; -import java.io.StringWriter; - -/** - * @author abreslav - */ -public interface MessageRenderer { - - MessageRenderer TAGS = new MessageRenderer() { - @Override - public String renderPreamble() { - return ""; - } - - @Override - public String render(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location) { - StringBuilder out = new StringBuilder(); - out.append("<").append(severity.toString()); - if (location.getPath() != null) { - out.append(" path=\"").append(e(location.getPath())).append("\""); - out.append(" line=\"").append(location.getLine()).append("\""); - out.append(" column=\"").append(location.getColumn()).append("\""); - } - out.append(">\n"); - - out.append(e(message)); - - out.append("\n"); - return out.toString(); - } - - private String e(String str) { - return StringUtil.escapeXml(str); - } - - @Override - public String renderException(@NotNull Throwable e) { - return render(CompilerMessageSeverity.EXCEPTION, PLAIN.renderException(e), CompilerMessageLocation.NO_LOCATION); - } - - @Override - public String renderConclusion() { - return ""; - } - }; - - MessageRenderer PLAIN = new MessageRenderer() { - @Override - public String renderPreamble() { - return ""; - } - - @Override - public String render(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location) { - String path = location.getPath(); - String position = path == null ? "" : path + ": (" + (location.getLine() + ", " + location.getColumn()) + ") "; - return severity + ": " + position + message; - } - - @Override - public String renderException(@NotNull Throwable e) { - StringWriter out = new StringWriter(); - //noinspection IOResourceOpenedButNotSafelyClosed - e.printStackTrace(new PrintWriter(out)); - return out.toString(); - } - - @Override - public String renderConclusion() { - return ""; - } - }; - - String renderPreamble(); - String render(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location); - String renderException(@NotNull Throwable e); - String renderConclusion(); -} diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageUtil.java b/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageUtil.java deleted file mode 100644 index 6ad95bc1e3d..00000000000 --- a/compiler/cli/src/org/jetbrains/jet/compiler/messages/MessageUtil.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler.messages; - -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; -import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils; - -/** - * @author abreslav - */ -public class MessageUtil { - public static CompilerMessageLocation psiElementToMessageLocation(PsiElement element) { - PsiFile file = element.getContainingFile(); - DiagnosticUtils.LineAndColumn lineAndColumn = DiagnosticUtils.getLineAndColumnInPsiFile(file, element.getTextRange()); - return CompilerMessageLocation.create(file.getVirtualFile().getPath(), lineAndColumn.getLine(), lineAndColumn.getColumn()); - } -} diff --git a/compiler/integration-tests/data/help.gold b/compiler/integration-tests/data/help.gold index 9bb334537b7..873ad73b72c 100644 --- a/compiler/integration-tests/data/help.gold +++ b/compiler/integration-tests/data/help.gold @@ -1,4 +1,4 @@ -OUT Usage: org.jetbrains.jet.cli.CompilerArguments +OUT Usage: org.jetbrains.jet.cli.jvm.K2JVMCompilerArguments OUT -output [String] output directory OUT -jar [String] jar file name OUT -src [String] source file or directory diff --git a/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java b/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java index 7407af4cb83..8f5ab4b894a 100644 --- a/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java +++ b/compiler/integration-tests/src/org/jetbrains/kotlin/KotlinIntegrationTestBase.java @@ -84,7 +84,7 @@ public abstract class KotlinIntegrationTestBase { Collection javaArgs = new ArrayList(); javaArgs.add("-cp"); javaArgs.add(classpath); - javaArgs.add("org.jetbrains.jet.cli.KotlinCompiler"); + javaArgs.add("org.jetbrains.jet.cli.jvm.K2JVMCompiler"); Collections.addAll(javaArgs, arguments); return runJava(logName, ArrayUtil.toStringArray(javaArgs)); diff --git a/compiler/tests/org/jetbrains/jet/JetLiteFixture.java b/compiler/tests/org/jetbrains/jet/JetLiteFixture.java index 92a04db29c4..2c9d8af4e6d 100644 --- a/compiler/tests/org/jetbrains/jet/JetLiteFixture.java +++ b/compiler/tests/org/jetbrains/jet/JetLiteFixture.java @@ -30,9 +30,8 @@ import com.intellij.testFramework.LightVirtualFile; import com.intellij.testFramework.TestDataFile; import com.intellij.testFramework.UsefulTestCase; import org.jetbrains.annotations.NonNls; -import org.jetbrains.jet.compiler.JetCoreEnvironment; +import org.jetbrains.jet.cli.jvm.compiler.JetCoreEnvironment; import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.plugin.JetLanguage; diff --git a/compiler/tests/org/jetbrains/jet/JetTestUtils.java b/compiler/tests/org/jetbrains/jet/JetTestUtils.java index d340c04c3af..6bb5f8e7728 100644 --- a/compiler/tests/org/jetbrains/jet/JetTestUtils.java +++ b/compiler/tests/org/jetbrains/jet/JetTestUtils.java @@ -24,7 +24,7 @@ import com.intellij.openapi.util.io.FileUtil; import junit.framework.TestCase; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.analyzer.AnalyzeExhaust; -import org.jetbrains.jet.compiler.JetCoreEnvironment; +import org.jetbrains.jet.cli.jvm.compiler.JetCoreEnvironment; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.diagnostics.UnresolvedReferenceDiagnosticFactory; import org.jetbrains.jet.lang.diagnostics.Diagnostic; diff --git a/compiler/tests/org/jetbrains/jet/codegen/CompileTextTest.java b/compiler/tests/org/jetbrains/jet/codegen/CompileTextTest.java index 30743c9dee6..1e60a9fc01f 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/CompileTextTest.java +++ b/compiler/tests/org/jetbrains/jet/codegen/CompileTextTest.java @@ -17,11 +17,11 @@ package org.jetbrains.jet.codegen; import org.jetbrains.jet.CompileCompilerDependenciesTest; -import org.jetbrains.jet.compiler.CompileEnvironmentConfiguration; -import org.jetbrains.jet.compiler.CompileEnvironmentUtil; -import org.jetbrains.jet.compiler.JetCoreEnvironment; -import org.jetbrains.jet.compiler.KotlinToJVMBytecodeCompiler; -import org.jetbrains.jet.compiler.messages.MessageCollector; +import org.jetbrains.jet.cli.jvm.compiler.CompileEnvironmentConfiguration; +import org.jetbrains.jet.cli.jvm.compiler.CompileEnvironmentUtil; +import org.jetbrains.jet.cli.jvm.compiler.JetCoreEnvironment; +import org.jetbrains.jet.cli.jvm.compiler.KotlinToJVMBytecodeCompiler; +import org.jetbrains.jet.cli.common.messages.MessageCollector; import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; diff --git a/compiler/tests/org/jetbrains/jet/codegen/TestlibTest.java b/compiler/tests/org/jetbrains/jet/codegen/TestlibTest.java index 42fe643ba65..fd581894162 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/TestlibTest.java +++ b/compiler/tests/org/jetbrains/jet/codegen/TestlibTest.java @@ -23,9 +23,9 @@ import junit.framework.TestCase; import junit.framework.TestSuite; import org.jetbrains.jet.CompileCompilerDependenciesTest; import org.jetbrains.jet.codegen.forTestCompile.ForTestCompileRuntime; -import org.jetbrains.jet.compiler.CompileEnvironmentConfiguration; -import org.jetbrains.jet.compiler.KotlinToJVMBytecodeCompiler; -import org.jetbrains.jet.compiler.messages.MessageCollector; +import org.jetbrains.jet.cli.jvm.compiler.CompileEnvironmentConfiguration; +import org.jetbrains.jet.cli.jvm.compiler.KotlinToJVMBytecodeCompiler; +import org.jetbrains.jet.cli.common.messages.MessageCollector; import org.jetbrains.jet.lang.descriptors.ClassDescriptor; import org.jetbrains.jet.lang.psi.JetClass; import org.jetbrains.jet.lang.psi.JetDeclaration; diff --git a/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileBuiltins.java b/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileBuiltins.java index 717df3be623..77ce6e88cfa 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileBuiltins.java +++ b/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileBuiltins.java @@ -17,7 +17,8 @@ package org.jetbrains.jet.codegen.forTestCompile; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.cli.KotlinCompiler; +import org.jetbrains.jet.cli.common.ExitCode; +import org.jetbrains.jet.cli.jvm.K2JVMCompiler; import java.io.File; @@ -37,9 +38,9 @@ public class ForTestCompileBuiltins { @Override protected void doCompile(@NotNull File classesDir) throws Exception { - KotlinCompiler.ExitCode exitCode = new KotlinCompiler().exec( + ExitCode exitCode = new K2JVMCompiler().exec( System.err, "-output", classesDir.getPath(), "-src", "./compiler/frontend/src", "-mode", "builtins"); - if (exitCode != KotlinCompiler.ExitCode.OK) { + if (exitCode != ExitCode.OK) { throw new IllegalStateException("jdk headers compilation failed: " + exitCode); } } diff --git a/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileJdkHeaders.java b/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileJdkHeaders.java index b12d967c733..7603af9ee1a 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileJdkHeaders.java +++ b/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileJdkHeaders.java @@ -17,7 +17,8 @@ package org.jetbrains.jet.codegen.forTestCompile; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.cli.KotlinCompiler; +import org.jetbrains.jet.cli.common.ExitCode; +import org.jetbrains.jet.cli.jvm.K2JVMCompiler; import java.io.File; @@ -37,9 +38,9 @@ public class ForTestCompileJdkHeaders { @Override protected void doCompile(@NotNull File classesDir) throws Exception { - KotlinCompiler.ExitCode exitCode = new KotlinCompiler().exec( + ExitCode exitCode = new K2JVMCompiler().exec( System.err, "-output", classesDir.getPath(), "-src", "./jdk-headers/src", "-mode", "jdkHeaders"); - if (exitCode != KotlinCompiler.ExitCode.OK) { + if (exitCode != ExitCode.OK) { throw new IllegalStateException("jdk headers compilation failed: " + exitCode); } } diff --git a/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileRuntime.java b/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileRuntime.java index 34915e32d35..dc8cb3569fe 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileRuntime.java +++ b/compiler/tests/org/jetbrains/jet/codegen/forTestCompile/ForTestCompileRuntime.java @@ -16,12 +16,10 @@ package org.jetbrains.jet.codegen.forTestCompile; -import com.google.common.io.Files; -import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.JetTestUtils; -import org.jetbrains.jet.cli.KotlinCompiler; +import org.jetbrains.jet.cli.common.ExitCode; +import org.jetbrains.jet.cli.jvm.K2JVMCompiler; import org.junit.Assert; import javax.tools.JavaCompiler; @@ -29,12 +27,9 @@ import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.util.*; -import java.util.jar.JarEntry; -import java.util.jar.JarOutputStream; /** * Compile stdlib.jar that can be used in tests @@ -63,12 +58,12 @@ public class ForTestCompileRuntime { } private static void compileStdlib(File destdir) throws IOException { - KotlinCompiler.ExitCode exitCode = new KotlinCompiler().exec(System.err, + ExitCode exitCode = new K2JVMCompiler().exec(System.err, "-output", destdir.getPath(), "-src", "./libraries/stdlib/src", "-mode", "stdlib", "-classpath", "out/production/runtime"); - if (exitCode != KotlinCompiler.ExitCode.OK) { + if (exitCode != ExitCode.OK) { throw new IllegalStateException("stdlib for test compilation failed: " + exitCode); } } diff --git a/compiler/tests/org/jetbrains/jet/compiler/CompileEnvironmentTest.java b/compiler/tests/org/jetbrains/jet/compiler/CompileEnvironmentTest.java deleted file mode 100644 index 15258f3503a..00000000000 --- a/compiler/tests/org/jetbrains/jet/compiler/CompileEnvironmentTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import com.intellij.openapi.util.io.FileUtil; -import junit.framework.TestCase; -import org.jetbrains.jet.cli.KotlinCompiler; -import org.jetbrains.jet.codegen.forTestCompile.ForTestCompileJdkHeaders; -import org.jetbrains.jet.codegen.forTestCompile.ForTestCompileRuntime; -import org.jetbrains.jet.parsing.JetParsingTest; -import org.junit.Assert; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.jar.JarEntry; -import java.util.jar.JarInputStream; - -/** - * @author yole - * @author alex.tkachman - */ -public class CompileEnvironmentTest extends TestCase { - - public void testSmokeWithCompilerJar() throws IOException { - File tempDir = FileUtil.createTempDirectory("compilerTest", "compilerTest"); - - try { - File stdlib = ForTestCompileRuntime.runtimeJarForTests(); - File jdkHeaders = ForTestCompileJdkHeaders.jdkHeadersForTests(); - File resultJar = new File(tempDir, "result.jar"); - KotlinCompiler.ExitCode rv = new KotlinCompiler().exec(System.out, - "-module", JetParsingTest.getTestDataDir() + "/compiler/smoke/Smoke.kts", - "-jar", resultJar.getAbsolutePath(), - "-stdlib", stdlib.getAbsolutePath(), - "-jdkHeaders", jdkHeaders.getAbsolutePath()); - Assert.assertEquals("compilation completed with non-zero code", KotlinCompiler.ExitCode.OK, rv); - FileInputStream fileInputStream = new FileInputStream(resultJar); - try { - JarInputStream is = new JarInputStream(fileInputStream); - try { - final List entries = listEntries(is); - assertTrue(entries.contains("Smoke/namespace.class")); - assertEquals(1, entries.size()); - } - finally { - is.close(); - } - } - finally { - fileInputStream.close(); - } - } - finally { - FileUtil.delete(tempDir); - } - } - - public void testSmokeWithCompilerOutput() throws IOException { - File tempDir = FileUtil.createTempDirectory("compilerTest", "compilerTest"); - try { - File out = new File(tempDir, "out"); - File stdlib = ForTestCompileRuntime.runtimeJarForTests(); - File jdkHeaders = ForTestCompileJdkHeaders.jdkHeadersForTests(); - KotlinCompiler.ExitCode exitCode = new KotlinCompiler() - .exec(System.out, "-src", JetParsingTest.getTestDataDir() + "/compiler/smoke/Smoke.kt", "-output", - out.getAbsolutePath(), "-stdlib", stdlib.getAbsolutePath(), "-jdkHeaders", jdkHeaders.getAbsolutePath()); - Assert.assertEquals(KotlinCompiler.ExitCode.OK, exitCode); - assertEquals(1, out.listFiles().length); - assertEquals(1, out.listFiles()[0].listFiles().length); - } finally { - FileUtil.delete(tempDir); - } - } - - private static List listEntries(JarInputStream is) throws IOException { - List entries = new ArrayList(); - while (true) { - final JarEntry jarEntry = is.getNextJarEntry(); - if (jarEntry == null) { - break; - } - entries.add(jarEntry.getName()); - } - return entries; - } -} diff --git a/compiler/tests/org/jetbrains/jet/compiler/CompileJavaAgainstKotlinTest.java b/compiler/tests/org/jetbrains/jet/compiler/CompileJavaAgainstKotlinTest.java deleted file mode 100644 index 7834b4ead9d..00000000000 --- a/compiler/tests/org/jetbrains/jet/compiler/CompileJavaAgainstKotlinTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.CharsetToolkit; -import com.intellij.psi.PsiFileFactory; -import com.intellij.psi.impl.PsiFileFactoryImpl; -import com.intellij.testFramework.LightVirtualFile; -import junit.framework.Test; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.JetTestCaseBuilder; -import org.jetbrains.jet.JetTestUtils; -import org.jetbrains.jet.codegen.*; -import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; -import org.jetbrains.jet.plugin.JetLanguage; -import org.junit.Assert; - -import javax.tools.JavaCompiler; -import javax.tools.JavaFileObject; -import javax.tools.StandardJavaFileManager; -import javax.tools.ToolProvider; -import java.io.File; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - -/** - * @author Stepan Koltsov - * - * @see WriteSignatureTest - */ -public class CompileJavaAgainstKotlinTest extends TestCaseWithTmpdir { - - private final File ktFile; - private final File javaFile; - private JetCoreEnvironment jetCoreEnvironment; - - public CompileJavaAgainstKotlinTest(File ktFile) { - this.ktFile = ktFile; - Assert.assertTrue(ktFile.getName().endsWith(".kt")); - this.javaFile = new File(ktFile.getPath().replaceFirst("\\.kt", ".java")); - } - - @Override - public String getName() { - return ktFile.getName(); - } - - @Override - protected void runTest() throws Throwable { - jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable); - - - String text = FileUtil.loadFile(ktFile); - - LightVirtualFile virtualFile = new LightVirtualFile(ktFile.getName(), JetLanguage.INSTANCE, text); - virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); - JetFile psiFile = (JetFile) ((PsiFileFactoryImpl) PsiFileFactory.getInstance(jetCoreEnvironment.getProject())).trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false); - - ClassFileFactory classFileFactory = GenerationUtils.compileFileGetClassFileFactoryForTest(psiFile, CompilerSpecialMode.REGULAR); - - CompileEnvironmentUtil.writeToOutputDirectory(classFileFactory, tmpdir.getPath()); - - Disposer.dispose(myTestRootDisposable); - - JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); - - StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ENGLISH, Charset.forName("utf-8")); - try { - Iterable javaFileObjectsFromFiles = fileManager.getJavaFileObjectsFromFiles(Collections.singleton(javaFile)); - List options = Arrays.asList( - "-classpath", tmpdir.getPath() + System.getProperty("path.separator") + "out/production/stdlib", - "-d", tmpdir.getPath() - ); - JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, null, options, null, javaFileObjectsFromFiles); - - Assert.assertTrue(task.call()); - } finally { - fileManager.close(); - } - } - - public static Test suite() { - return JetTestCaseBuilder.suiteForDirectory(JetTestCaseBuilder.getTestDataPathBase(), "/compileJavaAgainstKotlin", true, new JetTestCaseBuilder.NamedTestFactory() { - @NotNull - @Override - public Test createTest(@NotNull String dataPath, @NotNull String name, @NotNull File file) { - return new CompileJavaAgainstKotlinTest(file); - } - }); - - } - -} diff --git a/compiler/tests/org/jetbrains/jet/compiler/CompileKotlinAgainstKotlinTest.java b/compiler/tests/org/jetbrains/jet/compiler/CompileKotlinAgainstKotlinTest.java deleted file mode 100644 index 7eddece3513..00000000000 --- a/compiler/tests/org/jetbrains/jet/compiler/CompileKotlinAgainstKotlinTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.CharsetToolkit; -import com.intellij.psi.PsiFileFactory; -import com.intellij.psi.impl.PsiFileFactoryImpl; -import com.intellij.testFramework.LightVirtualFile; -import junit.framework.Assert; -import junit.framework.Test; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.JetTestCaseBuilder; -import org.jetbrains.jet.JetTestUtils; -import org.jetbrains.jet.codegen.*; -import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; -import org.jetbrains.jet.plugin.JetLanguage; - -import java.io.File; -import java.io.FilenameFilter; -import java.io.IOException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -/** - * @author Stepan Koltsov - */ -public class CompileKotlinAgainstKotlinTest extends TestCaseWithTmpdir { - - private final File ktAFile; - private final File ktBFile; - - public CompileKotlinAgainstKotlinTest(File ktAFile) { - Assert.assertTrue(ktAFile.getName().endsWith("A.kt")); - this.ktAFile = ktAFile; - this.ktBFile = new File(ktAFile.getPath().replaceFirst("A\\.kt$", "B.kt")); - } - - @Override - public String getName() { - return ktAFile.getName(); - } - - private File aDir; - private File bDir; - - @Override - protected void setUp() throws Exception { - super.setUp(); - aDir = new File(tmpdir, "a"); - bDir = new File(tmpdir, "b"); - JetTestUtils.mkdirs(aDir); - JetTestUtils.mkdirs(bDir); - } - - @Override - protected void runTest() throws Throwable { - compileA(); - compileB(); - - URLClassLoader classLoader = new URLClassLoader(new URL[]{ aDir.toURI().toURL(), bDir.toURI().toURL() }); - Class clazz = classLoader.loadClass("bbb.namespace"); - Method main = clazz.getMethod("main", new Class[] { String[].class }); - main.invoke(null, new Object[] { new String[0] }); - } - - private void compileA() throws IOException { - JetCoreEnvironment jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable); - - String text = FileUtil.loadFile(ktAFile); - - LightVirtualFile virtualFile = new LightVirtualFile(ktAFile.getName(), JetLanguage.INSTANCE, text); - virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); - JetFile psiFile = (JetFile) ((PsiFileFactoryImpl) PsiFileFactory.getInstance(jetCoreEnvironment.getProject())).trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false); - - ClassFileFactory classFileFactory = GenerationUtils.compileFileGetClassFileFactoryForTest(psiFile, CompilerSpecialMode.REGULAR); - - CompileEnvironmentUtil.writeToOutputDirectory(classFileFactory, aDir.getPath()); - - Disposer.dispose(myTestRootDisposable); - } - - private void compileB() throws IOException { - JetCoreEnvironment jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable); - - jetCoreEnvironment.addToClasspath(aDir); - - String text = FileUtil.loadFile(ktBFile); - - LightVirtualFile virtualFile = new LightVirtualFile(ktAFile.getName(), JetLanguage.INSTANCE, text); - virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); - JetFile psiFile = (JetFile) ((PsiFileFactoryImpl) PsiFileFactory.getInstance(jetCoreEnvironment.getProject())).trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false); - - ClassFileFactory classFileFactory = GenerationUtils.compileFileGetClassFileFactoryForTest(psiFile, CompilerSpecialMode.REGULAR); - - CompileEnvironmentUtil.writeToOutputDirectory(classFileFactory, bDir.getPath()); - - Disposer.dispose(myTestRootDisposable); - } - - public static Test suite() { - class Filter implements FilenameFilter { - @Override - public boolean accept(File dir, String name) { - return name.endsWith("A.kt"); - } - } - return JetTestCaseBuilder.suiteForDirectory(JetTestCaseBuilder.getTestDataPathBase(), "/compileKotlinAgainstKotlin", true, new Filter(), new JetTestCaseBuilder.NamedTestFactory() { - @NotNull - @Override - public Test createTest(@NotNull String dataPath, @NotNull String name, @NotNull File file) { - return new CompileKotlinAgainstKotlinTest(file); - } - }); - } -} diff --git a/compiler/tests/org/jetbrains/jet/compiler/JavaDescriptorResolverTest.java b/compiler/tests/org/jetbrains/jet/compiler/JavaDescriptorResolverTest.java deleted file mode 100644 index e26bcd05cbc..00000000000 --- a/compiler/tests/org/jetbrains/jet/compiler/JavaDescriptorResolverTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import org.jetbrains.jet.CompileCompilerDependenciesTest; -import org.jetbrains.jet.JetTestUtils; -import org.jetbrains.jet.di.InjectorForJavaSemanticServices; -import org.jetbrains.jet.lang.descriptors.ClassDescriptor; -import org.jetbrains.jet.lang.resolve.FqName; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; -import org.jetbrains.jet.lang.resolve.java.DescriptorSearchRule; -import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; -import org.junit.Assert; - -import javax.tools.*; -import java.io.File; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - -/** - * @author Stepan Koltsov - * @see ReadJavaBinaryClassTest - */ -public class JavaDescriptorResolverTest extends TestCaseWithTmpdir { - - // This test can be implemented in ReadJavaBinaryClass test, but it is simpler here - public void testInner() throws Exception { - JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); - - StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ENGLISH, Charset.forName("utf-8")); - try { - File file = new File("compiler/testData/javaDescriptorResolver/inner.java"); - Iterable javaFileObjectsFromFiles = fileManager.getJavaFileObjectsFromFiles(Collections.singleton(file)); - List options = Arrays.asList( - "-d", tmpdir.getPath() - ); - JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, null, options, null, javaFileObjectsFromFiles); - - Assert.assertTrue(task.call()); - } finally { - fileManager.close(); - } - - JetCoreEnvironment jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable, CompilerSpecialMode.JDK_HEADERS); - - jetCoreEnvironment.addToClasspath(tmpdir); - - InjectorForJavaSemanticServices injector = new InjectorForJavaSemanticServices( - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS, true), jetCoreEnvironment.getProject()); - JavaDescriptorResolver javaDescriptorResolver = injector.getJavaDescriptorResolver(); - ClassDescriptor classDescriptor = javaDescriptorResolver.resolveClass(new FqName("A"), DescriptorSearchRule.ERROR_IF_FOUND_IN_KOTLIN); - Assert.assertNotNull(classDescriptor); - } - -} diff --git a/compiler/tests/org/jetbrains/jet/compiler/NamespaceComparator.java b/compiler/tests/org/jetbrains/jet/compiler/NamespaceComparator.java deleted file mode 100644 index e7e235e091b..00000000000 --- a/compiler/tests/org/jetbrains/jet/compiler/NamespaceComparator.java +++ /dev/null @@ -1,568 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import com.google.common.io.Files; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.codegen.PropertyCodegen; -import org.jetbrains.jet.lang.descriptors.*; -import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor; -import org.jetbrains.jet.lang.resolve.DescriptorUtils; -import org.jetbrains.jet.lang.resolve.scopes.JetScope; -import org.jetbrains.jet.lang.resolve.scopes.receivers.ExtensionReceiver; -import org.jetbrains.jet.lang.types.JetType; -import org.jetbrains.jet.lang.types.TypeProjection; -import org.jetbrains.jet.lang.types.Variance; -import org.junit.Assert; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Method; -import java.nio.charset.Charset; -import java.util.*; - -/** - * @author Stepan Koltsov - */ -class NamespaceComparator { - - private final boolean includeObject; - - private NamespaceComparator(boolean includeObject) { - this.includeObject = includeObject; - } - - public static void compareNamespaces(@NotNull NamespaceDescriptor nsa, @NotNull NamespaceDescriptor nsb, boolean includeObject, - @NotNull File txtFile) { - String serialized = new NamespaceComparator(includeObject).doCompareNamespaces(nsa, nsb); - try { - for (;;) { - String expected = Files.toString(txtFile, Charset.forName("utf-8")).replace("\r\n", "\n"); - - if (expected.contains("kick me")) { - // for developer - System.err.println("generating " + txtFile); - Files.write(serialized, txtFile, Charset.forName("utf-8")); - continue; - } - - // compare with hardcopy: make sure nothing is lost in output - Assert.assertEquals(expected, serialized); - break; - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private String doCompareNamespaces(@NotNull NamespaceDescriptor nsa, @NotNull NamespaceDescriptor nsb) { - StringBuilder sb = new StringBuilder(); - Assert.assertEquals(nsa.getName(), nsb.getName()); - - sb.append("namespace " + nsa.getName() + "\n\n"); - - Assert.assertTrue(!nsa.getMemberScope().getAllDescriptors().isEmpty()); - - Set classifierNames = new HashSet(); - Set propertyNames = new HashSet(); - Set functionNames = new HashSet(); - - for (DeclarationDescriptor ad : nsa.getMemberScope().getAllDescriptors()) { - if (ad instanceof ClassifierDescriptor) { - classifierNames.add(ad.getName()); - } - else if (ad instanceof PropertyDescriptor) { - propertyNames.add(ad.getName()); - } - else if (ad instanceof FunctionDescriptor) { - functionNames.add(ad.getName()); - } - else { - throw new AssertionError("unknown member: " + ad); - } - } - - for (String name : classifierNames) { - ClassifierDescriptor ca = nsa.getMemberScope().getClassifier(name); - ClassifierDescriptor cb = nsb.getMemberScope().getClassifier(name); - Assert.assertTrue(ca != null); - Assert.assertTrue(cb != null); - compareClassifiers(ca, cb, sb); - } - - for (String name : propertyNames) { - Set pa = nsa.getMemberScope().getProperties(name); - Set pb = nsb.getMemberScope().getProperties(name); - compareDeclarationSets(pa, pb, sb); - - Assert.assertTrue(nsb.getMemberScope().getFunctions(PropertyCodegen.getterName(name)).isEmpty()); - Assert.assertTrue(nsb.getMemberScope().getFunctions(PropertyCodegen.setterName(name)).isEmpty()); - } - - for (String name : functionNames) { - Set fa = nsa.getMemberScope().getFunctions(name); - Set fb = nsb.getMemberScope().getFunctions(name); - compareDeclarationSets(fa, fb, sb); - } - - return sb.toString(); - } - - private static void compareDeclarationSets(Set a, Set b, - @NotNull StringBuilder sb) { - String at = serializedDeclarationSets(a); - String bt = serializedDeclarationSets(b); - Assert.assertEquals(at, bt); - sb.append(at); - } - - private static String serializedDeclarationSets(Collection ds) { - List strings = new ArrayList(); - for (DeclarationDescriptor d : ds) { - StringBuilder sb = new StringBuilder(); - new Serializer(sb).serialize(d); - strings.add(sb.toString()); - } - - Collections.sort(strings, new MemberComparator()); - - StringBuilder r = new StringBuilder(); - for (String string : strings) { - r.append(string); - r.append("\n"); - } - return r.toString(); - } - - /** - * This comparator only affects test output, you can drop it if you don't want to understand it. - */ - private static class MemberComparator implements Comparator { - - @NotNull - private String normalize(String s) { - return s.replaceFirst( - "^ *(private|final|abstract|open|override|fun|val|var|/\\*.*?\\*/|((?!)<.*?>)| )*", - "") - + s; - } - - @Override - public int compare(@NotNull String a, @NotNull String b) { - return normalize(a).compareTo(normalize(b)); - } - } - - private void compareClassifiers(@NotNull ClassifierDescriptor a, @NotNull ClassifierDescriptor b, @NotNull StringBuilder sb) { - StringBuilder sba = new StringBuilder(); - StringBuilder sbb = new StringBuilder(); - - new FullContentSerialier(sba).serialize((ClassDescriptor) a); - new FullContentSerialier(sbb).serialize((ClassDescriptor) b); - - String as = sba.toString(); - String bs = sbb.toString(); - - Assert.assertEquals(as, bs); - sb.append(as); - } - - - - private static class Serializer { - - protected final StringBuilder sb; - - public Serializer(StringBuilder sb) { - this.sb = sb; - } - - public void serialize(ClassKind kind) { - switch (kind) { - case CLASS: - sb.append("class"); - break; - case TRAIT: - sb.append("trait"); - break; - case OBJECT: - sb.append("object"); - break; - case ANNOTATION_CLASS: - sb.append("annotation class"); - break; - default: - throw new IllegalStateException("unknown class kind: " + kind); - } - } - - - private static Object invoke(Method method, Object thiz, Object... args) { - try { - return method.invoke(thiz, args); - } catch (Exception e) { - throw new RuntimeException("failed to invoke " + method + ": " + e, e); - } - } - - - public void serialize(FunctionDescriptor fun) { - serialize(fun.getModality()); - sb.append(" "); - - if (!fun.getAnnotations().isEmpty()) { - new Serializer(sb).serializeSeparated(fun.getAnnotations(), " "); - sb.append(" "); - } - - if (!fun.getOverriddenDescriptors().isEmpty()) { - sb.append("override /*" + fun.getOverriddenDescriptors().size() + "*/ "); - } - - if (fun instanceof ConstructorDescriptor) { - sb.append("/*constructor*/ "); - } - sb.append("fun "); - if (!fun.getTypeParameters().isEmpty()) { - sb.append("<"); - new Serializer(sb).serializeCommaSeparated(fun.getTypeParameters()); - sb.append(">"); - } - - if (fun.getReceiverParameter().exists()) { - new TypeSerializer(sb).serialize(fun.getReceiverParameter()); - sb.append("."); - } - - sb.append(fun.getName()); - sb.append("("); - new TypeSerializer(sb).serializeCommaSeparated(fun.getValueParameters()); - sb.append("): "); - new TypeSerializer(sb).serialize(fun.getReturnType()); - } - - public void serialize(ExtensionReceiver extensionReceiver) { - serialize(extensionReceiver.getType()); - } - - public void serialize(PropertyDescriptor prop) { - serialize(prop.getModality()); - sb.append(" "); - - if (!prop.getAnnotations().isEmpty()) { - new Serializer(sb).serializeSeparated(prop.getAnnotations(), " "); - sb.append(" "); - } - - if (prop.isVar()) { - sb.append("var "); - } - else { - sb.append("val "); - } - if (!prop.getTypeParameters().isEmpty()) { - sb.append(" <"); - new Serializer(sb).serializeCommaSeparated(prop.getTypeParameters()); - sb.append("> "); - } - if (prop.getReceiverParameter().exists()) { - new TypeSerializer(sb).serialize(prop.getReceiverParameter().getType()); - sb.append("."); - } - sb.append(prop.getName()); - sb.append(": "); - new TypeSerializer(sb).serialize(prop.getType()); - } - - public void serialize(ValueParameterDescriptor valueParameter) { - sb.append("/*"); - sb.append(valueParameter.getIndex()); - sb.append("*/ "); - if (valueParameter.getVarargElementType() != null) { - sb.append("vararg "); - } - sb.append(valueParameter.getName()); - sb.append(": "); - if (valueParameter.getVarargElementType() != null) { - new TypeSerializer(sb).serialize(valueParameter.getVarargElementType()); - } - else { - new TypeSerializer(sb).serialize(valueParameter.getType()); - } - if (valueParameter.hasDefaultValue()) { - sb.append(" = ?"); - } - } - - public void serialize(Variance variance) { - if (variance == Variance.INVARIANT) { - - } - else { - sb.append(variance); - sb.append(' '); - } - } - - public void serialize(Modality modality) { - sb.append(modality.name().toLowerCase()); - } - - public void serialize(AnnotationDescriptor annotation) { - new TypeSerializer(sb).serialize(annotation.getType()); - sb.append("("); - serializeCommaSeparated(annotation.getValueArguments()); - sb.append(")"); - } - - public void serializeCommaSeparated(List list) { - serializeSeparated(list, ", "); - } - - public void serializeSeparated(List list, String sep) { - boolean first = true; - for (Object o : list) { - if (!first) { - sb.append(sep); - } - serialize(o); - first = false; - } - } - - private Method getMethodToSerialize(Object o) { - if (o == null) { - throw new IllegalStateException("won't serialize null"); - } - - // TODO: cache - for (Method method : this.getClass().getMethods()) { - if (!method.getName().equals("serialize")) { - continue; - } - if (method.getParameterTypes().length != 1) { - continue; - } - if (method.getParameterTypes()[0].equals(Object.class)) { - continue; - } - if (method.getParameterTypes()[0].isInstance(o)) { - method.setAccessible(true); - return method; - } - } - throw new IllegalStateException("don't know how to serialize " + o + " (of " + o.getClass() + ")"); - } - - public void serialize(Object o) { - Method method = getMethodToSerialize(o); - invoke(method, this, o); - } - - public void serialize(String s) { - sb.append(s); - } - - public void serialize(ClassDescriptor clazz) { - sb.append(DescriptorUtils.getFQName(clazz)); - } - - public void serialize(NamespaceDescriptor ns) { - sb.append(DescriptorUtils.getFQName(ns)); - } - - public void serialize(TypeParameterDescriptor param) { - sb.append("/*"); - sb.append(param.getIndex()); - if (param.isReified()) { - sb.append(",r"); - } - sb.append("*/ "); - serialize(param.getVariance()); - sb.append(param.getName()); - if (!param.getUpperBounds().isEmpty()) { - sb.append(" : "); - List list = new ArrayList(); - for (JetType upper : param.getUpperBounds()) { - StringBuilder sb = new StringBuilder(); - new TypeSerializer(sb).serialize(upper); - list.add(sb.toString()); - } - Collections.sort(list); - serializeSeparated(list, " & "); // TODO: use where - } - // TODO: lower bounds - } - - } - - private static class TypeSerializer extends Serializer { - - public TypeSerializer(StringBuilder sb) { - super(sb); - } - - @Override - public void serialize(TypeParameterDescriptor param) { - sb.append(param.getName()); - } - - public void serialize(@NotNull JetType type) { - serialize(type.getConstructor().getDeclarationDescriptor()); - if (!type.getArguments().isEmpty()) { - sb.append("<"); - boolean first = true; - for (TypeProjection proj : type.getArguments()) { - if (!first) { - sb.append(", "); - } - serialize(proj.getProjectionKind()); - serialize(proj.getType()); - first = false; - } - sb.append(">"); - } - if (type.isNullable()) { - sb.append("?"); - } - } - - } - - private static boolean isRootNs(DeclarationDescriptor ns) { - return ns instanceof NamespaceDescriptor && ns.getContainingDeclaration() instanceof ModuleDescriptor; - } - - private static class NamespacePrefixSerializer extends Serializer { - - public NamespacePrefixSerializer(StringBuilder sb) { - super(sb); - } - - @Override - public void serialize(NamespaceDescriptor ns) { - super.serialize(ns); - if (isRootNs(ns)) { - return; - } - sb.append("."); - } - - @Override - public void serialize(ClassDescriptor clazz) { - super.serialize(clazz); - sb.append("."); - } - } - - private class FullContentSerialier extends Serializer { - private FullContentSerialier(StringBuilder sb) { - super(sb); - } - - public void serialize(ClassDescriptor klass) { - - if (!klass.getAnnotations().isEmpty()) { - new Serializer(sb).serializeSeparated(klass.getAnnotations(), " "); - sb.append(" "); - } - serialize(klass.getModality()); - sb.append(" "); - - serialize(klass.getKind()); - sb.append(" "); - - new Serializer(sb).serialize(klass); - - if (!klass.getTypeConstructor().getParameters().isEmpty()) { - sb.append("<"); - serializeCommaSeparated(klass.getTypeConstructor().getParameters()); - sb.append(">"); - } - - if (!klass.getTypeConstructor().getSupertypes().isEmpty()) { - sb.append(" : "); - new TypeSerializer(sb).serializeCommaSeparated(new ArrayList(klass.getTypeConstructor().getSupertypes())); - } - - sb.append(" {\n"); - - List typeArguments = new ArrayList(); - for (TypeParameterDescriptor param : klass.getTypeConstructor().getParameters()) { - typeArguments.add(new TypeProjection(Variance.INVARIANT, param.getDefaultType())); - } - - List memberStrings = new ArrayList(); - - for (ConstructorDescriptor constructor : klass.getConstructors()) { - StringBuilder constructorSb = new StringBuilder(); - new Serializer(constructorSb).serialize(constructor); - memberStrings.add(constructorSb.toString()); - } - - JetScope memberScope = klass.getMemberScope(typeArguments); - for (DeclarationDescriptor member : memberScope.getAllDescriptors()) { - if (!includeObject) { - if (member.getName().matches("equals|hashCode|finalize|wait|notify(All)?|toString|clone|getClass")) { - continue; - } - } - StringBuilder memberSb = new StringBuilder(); - new FullContentSerialier(memberSb).serialize(member); - memberStrings.add(memberSb.toString()); - } - - Collections.sort(memberStrings, new MemberComparator()); - - for (String memberString : memberStrings) { - sb.append(indent(memberString)); - } - - if (klass.getClassObjectDescriptor() != null) { - StringBuilder sbForClassObject = new StringBuilder(); - new FullContentSerialier(sbForClassObject).serialize(klass.getClassObjectDescriptor()); - sb.append(indent(sbForClassObject.toString())); - } - - sb.append("}\n"); - } - } - - - private static String indent(String string) { - try { - StringBuilder r = new StringBuilder(); - BufferedReader reader = new BufferedReader(new StringReader(string)); - for (;;) { - String line = reader.readLine(); - if (line == null) { - break; - } - r.append(" "); - r.append(line); - r.append("\n"); - } - return r.toString(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - -} diff --git a/compiler/tests/org/jetbrains/jet/compiler/ReadJavaBinaryClassTest.java b/compiler/tests/org/jetbrains/jet/compiler/ReadJavaBinaryClassTest.java deleted file mode 100644 index d020a824af8..00000000000 --- a/compiler/tests/org/jetbrains/jet/compiler/ReadJavaBinaryClassTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.CharsetToolkit; -import com.intellij.psi.PsiFileFactory; -import com.intellij.psi.impl.PsiFileFactoryImpl; -import com.intellij.testFramework.LightVirtualFile; -import junit.framework.Test; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.CompileCompilerDependenciesTest; -import org.jetbrains.jet.JetTestCaseBuilder; -import org.jetbrains.jet.JetTestUtils; -import org.jetbrains.jet.di.InjectorForJavaSemanticServices; -import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; -import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor; -import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.resolve.BindingContext; -import org.jetbrains.jet.lang.resolve.FqName; -import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; -import org.jetbrains.jet.lang.resolve.java.DescriptorSearchRule; -import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; -import org.jetbrains.jet.plugin.JetLanguage; -import org.junit.Assert; - -import javax.tools.JavaCompiler; -import javax.tools.JavaFileObject; -import javax.tools.StandardJavaFileManager; -import javax.tools.ToolProvider; -import java.io.File; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - -/** - * @author Stepan Koltsov - */ -public class ReadJavaBinaryClassTest extends TestCaseWithTmpdir { - - private final File ktFile; - private final File javaFile; - private final File txtFile; - - public ReadJavaBinaryClassTest(File ktFile) { - this.ktFile = ktFile; - Assert.assertTrue(ktFile.getName().endsWith(".kt")); - this.javaFile = new File(ktFile.getPath().replaceFirst("\\.kt$", ".java")); - this.txtFile = new File(ktFile.getPath().replaceFirst("\\.kt$", ".txt")); - setName(javaFile.getName()); - } - - - @Override - public void runTest() throws Exception { - NamespaceDescriptor nsa = compileKotlin(); - NamespaceDescriptor nsb = compileJava(); - NamespaceComparator.compareNamespaces(nsa, nsb, false, txtFile); - } - - private NamespaceDescriptor compileKotlin() throws Exception { - JetCoreEnvironment jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable, CompilerSpecialMode.JDK_HEADERS); - - String text = FileUtil.loadFile(ktFile); - - LightVirtualFile virtualFile = new LightVirtualFile(ktFile.getName(), JetLanguage.INSTANCE, text); - virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); - JetFile psiFile = (JetFile) ((PsiFileFactoryImpl) PsiFileFactory.getInstance(jetCoreEnvironment.getProject())).trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false); - - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegrationAndCheckForErrors( - psiFile, JetControlFlowDataTraceFactory.EMPTY, - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS, true)) - .getBindingContext(); - return bindingContext.get(BindingContext.FQNAME_TO_NAMESPACE_DESCRIPTOR, FqName.topLevel("test")); - } - - private NamespaceDescriptor compileJava() throws Exception { - JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); - - StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ENGLISH, Charset.forName("utf-8")); - try { - Iterable javaFileObjectsFromFiles = fileManager.getJavaFileObjectsFromFiles(Collections.singleton(javaFile)); - List options = Arrays.asList( - "-classpath", "out/production/runtime" + File.pathSeparator + JetTestUtils.getAnnotationsJar().getPath(), - "-d", tmpdir.getPath() - ); - JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, null, options, null, javaFileObjectsFromFiles); - - Assert.assertTrue(task.call()); - } finally { - fileManager.close(); - } - - JetCoreEnvironment jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable, CompilerSpecialMode.JDK_HEADERS); - - jetCoreEnvironment.addToClasspath(tmpdir); - jetCoreEnvironment.addToClasspath(new File("out/production/runtime")); - - InjectorForJavaSemanticServices injector = new InjectorForJavaSemanticServices( - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS, true), jetCoreEnvironment.getProject()); - JavaDescriptorResolver javaDescriptorResolver = injector.getJavaDescriptorResolver(); - return javaDescriptorResolver.resolveNamespace(FqName.topLevel("test"), DescriptorSearchRule.ERROR_IF_FOUND_IN_KOTLIN); - } - - public static Test suite() { - return JetTestCaseBuilder.suiteForDirectory(JetTestCaseBuilder.getTestDataPathBase(), "/readJavaBinaryClass", true, new JetTestCaseBuilder.NamedTestFactory() { - @NotNull - @Override - public Test createTest(@NotNull String dataPath, @NotNull String name, @NotNull File file) { - return new ReadJavaBinaryClassTest(file); - } - }); - } - -} diff --git a/compiler/tests/org/jetbrains/jet/compiler/ReadKotlinBinaryClassTest.java b/compiler/tests/org/jetbrains/jet/compiler/ReadKotlinBinaryClassTest.java deleted file mode 100644 index 6eda371a5d7..00000000000 --- a/compiler/tests/org/jetbrains/jet/compiler/ReadKotlinBinaryClassTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.CharsetToolkit; -import com.intellij.psi.PsiFileFactory; -import com.intellij.psi.impl.PsiFileFactoryImpl; -import com.intellij.testFramework.LightVirtualFile; -import junit.framework.Assert; -import junit.framework.Test; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.CompileCompilerDependenciesTest; -import org.jetbrains.jet.JetTestCaseBuilder; -import org.jetbrains.jet.JetTestUtils; -import org.jetbrains.jet.codegen.ClassFileFactory; -import org.jetbrains.jet.codegen.GenerationState; -import org.jetbrains.jet.codegen.GenerationUtils; -import org.jetbrains.jet.di.InjectorForJavaSemanticServices; -import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor; -import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.resolve.BindingContext; -import org.jetbrains.jet.lang.resolve.FqName; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; -import org.jetbrains.jet.lang.resolve.java.DescriptorSearchRule; -import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; -import org.jetbrains.jet.plugin.JetLanguage; - -import java.io.File; - -/** - * Compile Kotlin and then parse model from .class files. - * - * @author Stepan Koltsov - */ -public class ReadKotlinBinaryClassTest extends TestCaseWithTmpdir { - - private JetCoreEnvironment jetCoreEnvironment; - - private final File testFile; - private final File txtFile; - - public ReadKotlinBinaryClassTest(@NotNull File testFile) { - this.testFile = testFile; - this.txtFile = new File(testFile.getPath().replaceFirst("\\.kt$", ".txt")); - setName(testFile.getName()); - } - - @Override - public void runTest() throws Exception { - jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable, CompilerSpecialMode.JDK_HEADERS); - - String text = FileUtil.loadFile(testFile); - - LightVirtualFile virtualFile = new LightVirtualFile(testFile.getName(), JetLanguage.INSTANCE, text); - virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); - JetFile psiFile = (JetFile) ((PsiFileFactoryImpl) PsiFileFactory.getInstance(jetCoreEnvironment.getProject())).trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false); - - GenerationState state = GenerationUtils.compileFileGetGenerationStateForTest(psiFile, CompilerSpecialMode.JDK_HEADERS); - - ClassFileFactory classFileFactory = state.getFactory(); - - CompileEnvironmentUtil.writeToOutputDirectory(classFileFactory, tmpdir.getPath()); - - NamespaceDescriptor namespaceFromSource = state.getBindingContext().get(BindingContext.FILE_TO_NAMESPACE, psiFile); - - Assert.assertEquals("test", namespaceFromSource.getName()); - - Disposer.dispose(myTestRootDisposable); - - - jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable, CompilerSpecialMode.JDK_HEADERS); - - jetCoreEnvironment.addToClasspath(tmpdir); - jetCoreEnvironment.addToClasspath(new File("out/production/runtime")); - - InjectorForJavaSemanticServices injector = new InjectorForJavaSemanticServices( - CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS, true), jetCoreEnvironment.getProject()); - JavaDescriptorResolver javaDescriptorResolver = injector.getJavaDescriptorResolver(); - NamespaceDescriptor namespaceFromClass = javaDescriptorResolver.resolveNamespace(FqName.topLevel("test"), DescriptorSearchRule.ERROR_IF_FOUND_IN_KOTLIN); - - NamespaceComparator.compareNamespaces(namespaceFromSource, namespaceFromClass, false, txtFile); - } - - public static Test suite() { - return JetTestCaseBuilder.suiteForDirectory(JetTestCaseBuilder.getTestDataPathBase(), "/readKotlinBinaryClass", true, new JetTestCaseBuilder.NamedTestFactory() { - @NotNull - @Override - public Test createTest(@NotNull String dataPath, @NotNull String name, @NotNull File file) { - return new ReadKotlinBinaryClassTest(file); - } - }); - } - -} diff --git a/compiler/tests/org/jetbrains/jet/compiler/TestCaseWithTmpdir.java b/compiler/tests/org/jetbrains/jet/compiler/TestCaseWithTmpdir.java deleted file mode 100644 index f00189b4298..00000000000 --- a/compiler/tests/org/jetbrains/jet/compiler/TestCaseWithTmpdir.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import com.intellij.testFramework.UsefulTestCase; -import org.jetbrains.jet.JetTestUtils; - -import java.io.File; - -/** - * @author Stepan Koltsov - */ -public abstract class TestCaseWithTmpdir extends UsefulTestCase { - - protected File tmpdir; - - @Override - protected void setUp() throws Exception { - super.setUp(); - tmpdir = JetTestUtils.tmpDirForTest(this); - } - -} diff --git a/compiler/tests/org/jetbrains/jet/compiler/WriteSignatureTest.java b/compiler/tests/org/jetbrains/jet/compiler/WriteSignatureTest.java deleted file mode 100644 index f09a6fa3a0f..00000000000 --- a/compiler/tests/org/jetbrains/jet/compiler/WriteSignatureTest.java +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler; - -import com.google.common.io.Closeables; -import com.google.common.io.Files; -import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.CharsetToolkit; -import com.intellij.psi.PsiFileFactory; -import com.intellij.psi.impl.PsiFileFactoryImpl; -import com.intellij.testFramework.LightVirtualFile; -import junit.framework.Test; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.JetTestCaseBuilder; -import org.jetbrains.jet.JetTestUtils; -import org.jetbrains.jet.codegen.*; -import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; -import org.jetbrains.jet.lang.resolve.java.JvmStdlibNames; -import org.jetbrains.jet.plugin.JetLanguage; -import org.junit.Assert; -import org.objectweb.asm.AnnotationVisitor; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.commons.EmptyVisitor; -import org.objectweb.asm.commons.Method; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Test correctness of written JVM signature - * - * @author Stepan Koltsov - * - * @see CompileJavaAgainstKotlinTest - */ -public class WriteSignatureTest extends TestCaseWithTmpdir { - - private final File ktFile; - private JetCoreEnvironment jetCoreEnvironment; - - public WriteSignatureTest(File ktFile) { - this.ktFile = ktFile; - } - - @Override - public String getName() { - return ktFile.getName(); - } - - @Override - protected void runTest() throws Throwable { - jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable); - - - String text = FileUtil.loadFile(ktFile); - - LightVirtualFile virtualFile = new LightVirtualFile(ktFile.getName(), JetLanguage.INSTANCE, text); - virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); - JetFile psiFile = (JetFile) ((PsiFileFactoryImpl) PsiFileFactory.getInstance(jetCoreEnvironment.getProject())).trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false); - - ClassFileFactory classFileFactory = GenerationUtils.compileFileGetClassFileFactoryForTest(psiFile, CompilerSpecialMode.REGULAR); - - CompileEnvironmentUtil.writeToOutputDirectory(classFileFactory, tmpdir.getPath()); - - Disposer.dispose(myTestRootDisposable); - - final Expectation expectation = parseExpectations(); - - ActualSignature actualSignature = readSignature(expectation.className, expectation.methodName); - - String template = - "jvm signature: %s\n" + - "generic signature: %s\n" + - "kotlin signature: %s\n" + - ""; - - String expected = String.format(template, expectation.jvmSignature, expectation.genericSignature, expectation.kotlinSignature); - String actual = String.format(template, actualSignature.jvmSignature, actualSignature.genericSignature, actualSignature.kotlinSignature); - - Assert.assertEquals(expected, actual); - } - - private static class ActualSignature { - private final String jvmSignature; - private final String genericSignature; - private final String kotlinSignature; - - private ActualSignature(@NotNull String jvmSignature, @Nullable String genericSignature, @Nullable String kotlinSignature) { - this.jvmSignature = jvmSignature; - this.genericSignature = genericSignature; - this.kotlinSignature = kotlinSignature; - } - } - - @NotNull - private ActualSignature readSignature(String className, final String methodName) throws Exception { - // ugly unreadable code begin - FileInputStream classInputStream = new FileInputStream(tmpdir + "/" + className.replace('.', '/') + ".class"); - try { - class Visitor extends EmptyVisitor { - ActualSignature readSignature; - - @Override - public MethodVisitor visitMethod(int access, String name, final String desc, final String signature, String[] exceptions) { - if (name.equals(methodName)) { - - final int parameterCount = new Method(name, desc).getArgumentTypes().length; - - return new EmptyVisitor() { - String typeParameters = ""; - String returnType; - String[] parameterTypes = new String[parameterCount]; - - @Override - public AnnotationVisitor visitAnnotation(String desc, boolean visible) { - if (desc.equals(JvmStdlibNames.JET_METHOD.getDescriptor())) { - return new EmptyVisitor() { - @Override - public void visit(String name, Object value) { - if (name.equals(JvmStdlibNames.JET_METHOD_TYPE_PARAMETERS_FIELD)) { - typeParameters = (String) value; - } - else if (name.equals(JvmStdlibNames.JET_METHOD_RETURN_TYPE_FIELD)) { - returnType = (String) value; - } - } - - @Override - public AnnotationVisitor visitAnnotation(String desc, boolean visible) { - return new EmptyVisitor(); - } - - @Override - public AnnotationVisitor visitArray(String name) { - return new EmptyVisitor(); - } - }; - } - else { - return new EmptyVisitor(); - } - } - - @Override - public AnnotationVisitor visitParameterAnnotation(final int parameter, String desc, boolean visible) { - if (desc.equals(JvmStdlibNames.JET_VALUE_PARAMETER.getDescriptor())) { - return new EmptyVisitor() { - @Override - public void visit(String name, Object value) { - if (name.equals(JvmStdlibNames.JET_VALUE_PARAMETER_TYPE_FIELD)) { - parameterTypes[parameter] = (String) value; - } - } - - @Override - public AnnotationVisitor visitAnnotation(String desc, boolean visible) { - return new EmptyVisitor(); - } - - @Override - public AnnotationVisitor visitArray(String name) { - return new EmptyVisitor(); - } - }; - } - else { - return new EmptyVisitor(); - } - } - - @Override - public AnnotationVisitor visitAnnotationDefault() { - return new EmptyVisitor(); - } - - @Nullable - private String makeKotlinSignature() { - boolean allNulls = true; - - StringBuilder sb = new StringBuilder(); - sb.append(typeParameters); - if (typeParameters != null && typeParameters.length() > 0) { - allNulls = false; - } - sb.append("("); - for (String parameterType : parameterTypes) { - sb.append(parameterType); - if (parameterType != null) { - allNulls = false; - } - } - sb.append(")"); - sb.append(returnType); - if (returnType != null) { - allNulls = false; - } - if (allNulls) { - return null; - } - else { - return sb.toString(); - } - } - - @Override - public void visitEnd() { - Assert.assertNull(readSignature); - readSignature = new ActualSignature(desc, signature, makeKotlinSignature()); - } - }; - } - return super.visitMethod(access, name, desc, signature, exceptions); - } - } - - Visitor visitor = new Visitor(); - - new ClassReader(classInputStream).accept(visitor, - ClassReader.SKIP_CODE|ClassReader.SKIP_DEBUG|ClassReader.SKIP_FRAMES); - - Assert.assertNotNull("method not found: " + className + "::" + methodName, visitor.readSignature); - - return visitor.readSignature; - } finally { - Closeables.closeQuietly(classInputStream); - } - // ugly unreadable code end - } - - private static class Expectation { - private final String className; - private final String methodName; - private final String jvmSignature; - private final String genericSignature; - private final String kotlinSignature; - - private Expectation(@NotNull String className, @NotNull String methodName, - @NotNull String jvmSignature, @Nullable String genericSignature, @Nullable String kotlinSignature) { - this.className = className; - this.methodName = methodName; - this.jvmSignature = jvmSignature; - this.genericSignature = genericSignature; - this.kotlinSignature = kotlinSignature; - } - } - - @NotNull - private static final Pattern methodPattern = Pattern.compile("^// method: *(.*)::(.*?) *(//.*)?"); - private static final Pattern jvmSignaturePattern = Pattern.compile("^// jvm signature: *(.+?) *(//.*)?"); - private static final Pattern genericSignaturePattern = Pattern.compile("^// generic signature: *(.+?) *(//.*)?"); - private static final Pattern kotlinSignaturePattern = Pattern.compile("^// kotlin signature: *(.+?) *(//.*)?"); - private Expectation parseExpectations() throws IOException { - List lines = Files.readLines(ktFile, Charset.forName("utf-8")); - for (int i = 0; i < lines.size() - 3; ++i) { - Matcher methodMatcher = methodPattern.matcher(lines.get(i)); - if (methodMatcher.matches()) { - Matcher jvmSignatureMatcher = jvmSignaturePattern.matcher(lines.get(i + 1)); - Matcher genericSignatureMatcher = genericSignaturePattern.matcher(lines.get(i + 2)); - Matcher kotlinSignatureMatcher = kotlinSignaturePattern.matcher(lines.get(i + 3)); - if (!jvmSignatureMatcher.matches() || !genericSignatureMatcher.matches() || !kotlinSignatureMatcher.matches()) { - throw new AssertionError("'method:' must be followed ... bla bla ... use the source luke"); - } - - String className = methodMatcher.group(1); - String methodName = methodMatcher.group(2); - - String jvmSignature = jvmSignatureMatcher.group(1); - String genericSignature = genericSignatureMatcher.group(1); - String kotlinSignature = kotlinSignatureMatcher.group(1); - if (genericSignature.equals("null")) { - genericSignature = null; - } - if (kotlinSignature.equals("null")) { - kotlinSignature = null; - } - return new Expectation(className, methodName, jvmSignature, genericSignature, kotlinSignature); - } - } - throw new AssertionError("test instructions not found in " + ktFile); - } - - public static Test suite() { - return JetTestCaseBuilder.suiteForDirectory(JetTestCaseBuilder.getTestDataPathBase(), "/writeSignature", true, new JetTestCaseBuilder.NamedTestFactory() { - @NotNull - @Override - public Test createTest(@NotNull String dataPath, @NotNull String name, @NotNull File file) { - return new WriteSignatureTest(file); - } - }); - - } - -} diff --git a/compiler/tests/org/jetbrains/jet/compiler/longTest/LibFromMaven.java b/compiler/tests/org/jetbrains/jet/compiler/longTest/LibFromMaven.java deleted file mode 100644 index f16c660f1da..00000000000 --- a/compiler/tests/org/jetbrains/jet/compiler/longTest/LibFromMaven.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler.longTest; - -import org.jetbrains.annotations.NotNull; - -/** - * @author Stepan Koltsov - */ -public class LibFromMaven { - @NotNull - private final String org; - @NotNull - private final String module; - @NotNull - private final String rev; - - public LibFromMaven(@NotNull String org, @NotNull String module, @NotNull String rev) { - this.org = org; - this.module = module; - this.rev = rev; - } - - @NotNull - public String getOrg() { - return org; - } - - @NotNull - public String getModule() { - return module; - } - - @NotNull - public String getRev() { - return rev; - } - - @Override - public String toString() { - return org + "/" + module + "/" + rev; - } -} diff --git a/compiler/tests/org/jetbrains/jet/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java b/compiler/tests/org/jetbrains/jet/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java deleted file mode 100644 index 4a0fc6eb85a..00000000000 --- a/compiler/tests/org/jetbrains/jet/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright 2010-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.compiler.longTest; - -import com.google.common.io.ByteStreams; -import com.intellij.openapi.Disposable; -import com.intellij.openapi.util.Disposer; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.params.HttpMethodParams; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.CompileCompilerDependenciesTest; -import org.jetbrains.jet.JetTestUtils; -import org.jetbrains.jet.TimeUtils; -import org.jetbrains.jet.compiler.JetCoreEnvironment; -import org.jetbrains.jet.di.InjectorForJavaSemanticServices; -import org.jetbrains.jet.lang.descriptors.ClassDescriptor; -import org.jetbrains.jet.lang.resolve.FqName; -import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; -import org.jetbrains.jet.lang.resolve.java.DescriptorSearchRule; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -/** - * @author Stepan Koltsov - */ -public class ResolveDescriptorsFromExternalLibraries { - - @NotNull - private final CompilerDependencies compilerDependencies; - - - public static void main(String[] args) throws Exception { - new ResolveDescriptorsFromExternalLibraries().run(); - System.out.println("$"); - } - - - public ResolveDescriptorsFromExternalLibraries() { - System.out.println("Getting compiler dependencies"); - compilerDependencies = CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, true); - } - - private void run() throws Exception { - testLibrary("com.google.guava", "guava", "12.0-rc2"); - testLibrary("org.springframework", "spring-core", "3.1.1.RELEASE"); - } - - private void testLibrary(@NotNull String org, @NotNull String module, @NotNull String rev) throws Exception { - LibFromMaven lib = new LibFromMaven(org, module, rev); - File jar = getLibrary(lib); - System.out.println("Testing library " + lib + "..."); - System.out.println("Using file " + jar); - - long start = System.currentTimeMillis(); - - Disposable junk = new Disposable() { - @Override - public void dispose() { } - }; - - JetCoreEnvironment jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(junk); - jetCoreEnvironment.addToClasspath(jar); - - - InjectorForJavaSemanticServices injector = new InjectorForJavaSemanticServices(compilerDependencies, jetCoreEnvironment.getProject()); - - FileInputStream is = new FileInputStream(jar); - try { - ZipInputStream zip = new ZipInputStream(is); - for (;;) { - ZipEntry entry = zip.getNextEntry(); - if (entry == null) { - break; - } - String entryName = entry.getName(); - if (!entryName.endsWith(".class")) { - continue; - } - if (entryName.matches("(.*/|)package-info\\.class")) { - continue; - } - if (entryName.contains("$")) { - continue; - } - String className = entryName.substring(0, entryName.length() - ".class".length()).replace("/", "."); - ClassDescriptor clazz = injector.getJavaDescriptorResolver().resolveClass(new FqName(className), DescriptorSearchRule.ERROR_IF_FOUND_IN_KOTLIN); - if (clazz == null) { - throw new IllegalStateException("class not found by name " + className + " in " + lib); - } - clazz.getDefaultType().getMemberScope().getAllDescriptors(); - } - - } finally { - try { - is.close(); - } - catch (Throwable e) {} - - Disposer.dispose(junk); - } - - System.out.println("Testing library " + lib + " done in " + TimeUtils.millisecondsToSecondsString(System.currentTimeMillis() - start) + "s"); - } - - @NotNull - private File getLibrary(@NotNull LibFromMaven lib) throws Exception { - File userHome = new File(System.getProperty("user.home")); - String fileName = lib.getModule() + "-" + lib.getRev() + ".jar"; - - File dir = new File(userHome, ".kotlin-project/resolve-libraries/" + lib.getOrg() + "/" + lib.getModule()); - - File file = new File(dir, fileName); - if (file.exists()) { - return file; - } - - JetTestUtils.mkdirs(dir); - - File tmp = new File(dir, fileName + "~"); - - String uri = url(lib); - GetMethod method = new GetMethod(uri); - - FileOutputStream os = null; - - System.out.println("Downloading library " + lib + " to " + file); - - MultiThreadedHttpConnectionManager connectionManager = null; - try { - connectionManager = new MultiThreadedHttpConnectionManager(); - HttpClient httpClient = new HttpClient(connectionManager); - os = new FileOutputStream(tmp); - String userAgent = ResolveDescriptorsFromExternalLibraries.class.getName() + "/commons-httpclient"; - method.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent); - int code = httpClient.executeMethod(method); - if (code != 200) { - throw new RuntimeException("failed to execute GET " + uri + ", code is " + code); - } - InputStream responseBodyAsStream = method.getResponseBodyAsStream(); - if (responseBodyAsStream == null) { - throw new RuntimeException("method is executed fine, but response is null"); - } - ByteStreams.copy(responseBodyAsStream, os); - os.close(); - if (!tmp.renameTo(file)) { - throw new RuntimeException("failed to rename file: " + tmp + " to " + file); - } - return file; - } - finally { - if (method != null) { - try { - method.releaseConnection(); - } - catch (Throwable e) {} - } - if (connectionManager != null) { - try { - connectionManager.shutdown(); - } - catch (Throwable e) {} - } - if (os != null) { - try { - os.close(); - } - catch (Throwable e) {} - } - tmp.delete(); - } - } - - private static String url(LibFromMaven lib) { - return "http://repo1.maven.org/maven2/" + lib.getOrg().replace(".", "/") + "/" + lib.getModule() + "/" + lib.getRev() - + "/" + lib.getModule() + "-" + lib.getRev() + ".jar"; - } -} diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java index 3addb898aab..b6336e54af4 100644 --- a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java +++ b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompiler.java @@ -31,6 +31,7 @@ import com.intellij.openapi.compiler.TranslatingCompiler; import com.intellij.openapi.compiler.ex.CompileContextEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; +import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdkType; import com.intellij.openapi.projectRoots.JdkUtil; import com.intellij.openapi.projectRoots.Sdk; @@ -43,6 +44,7 @@ import com.intellij.util.SystemProperties; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.plugin.JetFileType; +import org.jetbrains.jet.plugin.project.JsModuleDetector; import org.jetbrains.jet.utils.PathUtil; import org.xml.sax.Attributes; import org.xml.sax.InputSource; @@ -71,7 +73,14 @@ public class JetCompiler implements TranslatingCompiler { @Override public boolean isCompilableFile(VirtualFile virtualFile, CompileContext compileContext) { - return virtualFile.getFileType() instanceof JetFileType; + if (!(virtualFile.getFileType() instanceof JetFileType)) { + return false; + } + Project project = compileContext.getProject(); + if (project == null || JsModuleDetector.isJsProject(project)) { + return false; + } + return true; } @NotNull @@ -316,7 +325,7 @@ public class JetCompiler implements TranslatingCompiler { private static int execInProcess(File kotlinHome, VirtualFile outputDir, File scriptFile, PrintStream out, CompileContext context) { URLClassLoader loader = getOrCreateClassLoader(kotlinHome, context); try { - String compilerClassName = "org.jetbrains.jet.cli.KotlinCompiler"; + String compilerClassName = "org.jetbrains.jet.cli.jvm.K2JVMCompiler"; Class kompiler = Class.forName(compilerClassName, true, loader); Method exec = kompiler.getDeclaredMethod("exec", PrintStream.class, String[].class); @@ -326,9 +335,9 @@ public class JetCompiler implements TranslatingCompiler { context.addMessage(INFORMATION, "Invoking in-process compiler " + compilerClassName + " with arguments " + Arrays.asList(arguments), "", -1, -1); Object rc = exec.invoke(kompiler.newInstance(), out, arguments); - // exec() returns a KotlinCompiler.ExitCode object, that class is not accessible here, + // exec() returns a K2JVMCompiler.ExitCode object, that class is not accessible here, // so we take it's contents through reflection - if ("org.jetbrains.jet.cli.KotlinCompiler.ExitCode".equals(rc.getClass().getCanonicalName())) { + if ("org.jetbrains.jet.cli.jvm.K2JVMCompiler.ExitCode".equals(rc.getClass().getCanonicalName())) { return (Integer) rc.getClass().getMethod("getCode").invoke(rc); } else { @@ -372,7 +381,7 @@ public class JetCompiler implements TranslatingCompiler { private static void runOutOfProcess(final CompileContext compileContext, final OutputItemsCollector collector, VirtualFile outputDir, File kotlinHome, File scriptFile) { final SimpleJavaParameters params = new SimpleJavaParameters(); params.setJdk(new SimpleJavaSdkType().createJdk("tmp", SystemProperties.getJavaHome())); - params.setMainClass("org.jetbrains.jet.cli.KotlinCompiler"); + params.setMainClass("org.jetbrains.jet.cli.jvm.K2JVMCompiler"); for (String arg : commandLineArguments(outputDir, scriptFile)) { params.getProgramParametersList().add(arg); diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompilerManager.java b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompilerManager.java index d08b047218a..71fd5b79333 100644 --- a/idea/src/org/jetbrains/jet/plugin/compiler/JetCompilerManager.java +++ b/idea/src/org/jetbrains/jet/plugin/compiler/JetCompilerManager.java @@ -31,8 +31,11 @@ import java.util.Collections; public class JetCompilerManager implements ProjectComponent { public JetCompilerManager(CompilerManager manager) { manager.addTranslatingCompiler(new JetCompiler(), - Collections.singleton(JetFileType.INSTANCE), - Collections.singleton(StdFileTypes.CLASS)); + Collections.singleton(JetFileType.INSTANCE), + Collections.singleton(StdFileTypes.CLASS)); + manager.addTranslatingCompiler(new K2JSCompiler(), + Collections.singleton(JetFileType.INSTANCE), + Collections.singleton(StdFileTypes.JS)); manager.addCompilableFileType(JetFileType.INSTANCE); } diff --git a/idea/src/org/jetbrains/jet/plugin/completion/JetCompletionContributor.java b/idea/src/org/jetbrains/jet/plugin/completion/JetCompletionContributor.java index 1c4907a2247..a57ba5fcb71 100644 --- a/idea/src/org/jetbrains/jet/plugin/completion/JetCompletionContributor.java +++ b/idea/src/org/jetbrains/jet/plugin/completion/JetCompletionContributor.java @@ -31,7 +31,7 @@ import com.intellij.util.Consumer; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.compiler.TipsManager; +import org.jetbrains.jet.cli.jvm.compiler.TipsManager; import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; diff --git a/idea/src/org/jetbrains/jet/plugin/completion/JetPackagesContributor.java b/idea/src/org/jetbrains/jet/plugin/completion/JetPackagesContributor.java index 4fbf325a7ae..955a72f1568 100644 --- a/idea/src/org/jetbrains/jet/plugin/completion/JetPackagesContributor.java +++ b/idea/src/org/jetbrains/jet/plugin/completion/JetPackagesContributor.java @@ -24,7 +24,7 @@ import com.intellij.psi.PsiReference; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.compiler.TipsManager; +import org.jetbrains.jet.cli.jvm.compiler.TipsManager; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetNamespaceHeader; import org.jetbrains.jet.lang.resolve.BindingContext; diff --git a/idea/src/org/jetbrains/jet/plugin/liveTemplates/macro/BaseJetVariableMacro.java b/idea/src/org/jetbrains/jet/plugin/liveTemplates/macro/BaseJetVariableMacro.java index 944840d744a..e0dfb2073ac 100644 --- a/idea/src/org/jetbrains/jet/plugin/liveTemplates/macro/BaseJetVariableMacro.java +++ b/idea/src/org/jetbrains/jet/plugin/liveTemplates/macro/BaseJetVariableMacro.java @@ -29,7 +29,7 @@ import com.intellij.psi.PsiFile; import com.intellij.psi.PsiNamedElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.compiler.TipsManager; +import org.jetbrains.jet.cli.jvm.compiler.TipsManager; import org.jetbrains.jet.di.InjectorForMacros; import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.descriptors.VariableDescriptor; diff --git a/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java b/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java index ab61b98afc4..0d85c588bd9 100644 --- a/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java +++ b/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java @@ -26,7 +26,7 @@ import com.intellij.psi.PsiReference; import com.intellij.psi.tree.IElementType; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.compiler.TipsManager; +import org.jetbrains.jet.cli.jvm.compiler.TipsManager; import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameValidatorImpl.java b/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameValidatorImpl.java index 79306959dda..efb8d885e06 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameValidatorImpl.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameValidatorImpl.java @@ -20,7 +20,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.compiler.TipsManager; +import org.jetbrains.jet.cli.jvm.compiler.TipsManager; import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.psi.JetExpression; import org.jetbrains.jet.lang.psi.JetFile; diff --git a/idea/src/org/jetbrains/jet/plugin/references/JetSimpleNameReference.java b/idea/src/org/jetbrains/jet/plugin/references/JetSimpleNameReference.java index 0b583f8684e..6be592e32e9 100644 --- a/idea/src/org/jetbrains/jet/plugin/references/JetSimpleNameReference.java +++ b/idea/src/org/jetbrains/jet/plugin/references/JetSimpleNameReference.java @@ -20,7 +20,7 @@ import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.compiler.TipsManager; +import org.jetbrains.jet.cli.jvm.compiler.TipsManager; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetPsiFactory; import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; diff --git a/idea/tests/org/jetbrains/jet/plugin/libraries/AbstractLibrariesTest.java b/idea/tests/org/jetbrains/jet/plugin/libraries/AbstractLibrariesTest.java index 4b225a785ef..86ebd521d91 100644 --- a/idea/tests/org/jetbrains/jet/plugin/libraries/AbstractLibrariesTest.java +++ b/idea/tests/org/jetbrains/jet/plugin/libraries/AbstractLibrariesTest.java @@ -28,7 +28,8 @@ import com.intellij.openapi.vfs.VirtualFileVisitor; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.testFramework.PlatformTestCase; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.cli.KotlinCompiler; +import org.jetbrains.jet.cli.common.ExitCode; +import org.jetbrains.jet.cli.jvm.K2JVMCompiler; import org.jetbrains.jet.plugin.PluginTestCaseBase; import java.io.File; @@ -61,9 +62,9 @@ public abstract class AbstractLibrariesTest extends PlatformTestCase { }); librarySourceDir = LocalFileSystem.getInstance().findFileByPath(TEST_DATA_PATH + "/library"); assertNotNull(librarySourceDir); - KotlinCompiler.ExitCode compilerExec = - new KotlinCompiler().exec(System.out, "-src", librarySourceDir.getPath(), "-output", libraryIoDir.getAbsolutePath()); - assertEquals(KotlinCompiler.ExitCode.OK, compilerExec); + ExitCode compilerExec = + new K2JVMCompiler().exec(System.out, "-src", librarySourceDir.getPath(), "-output", libraryIoDir.getAbsolutePath()); + assertEquals(ExitCode.OK, compilerExec); libraryDir = LocalFileSystem.getInstance().findFileByIoFile(libraryIoDir); assertNotNull(libraryDir); diff --git a/js/js.tests/test/org/jetbrains/k2js/test/TestWithEnvironment.java b/js/js.tests/test/org/jetbrains/k2js/test/TestWithEnvironment.java index 27b72a70e82..17c0f30cc5a 100644 --- a/js/js.tests/test/org/jetbrains/k2js/test/TestWithEnvironment.java +++ b/js/js.tests/test/org/jetbrains/k2js/test/TestWithEnvironment.java @@ -21,7 +21,7 @@ import com.intellij.testFramework.UsefulTestCase; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.JetTestUtils; -import org.jetbrains.jet.compiler.JetCoreEnvironment; +import org.jetbrains.jet.cli.jvm.compiler.JetCoreEnvironment; /** * @author Pavel Talanov diff --git a/libraries/tools/kdoc-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/doc/KDocMojo.java b/libraries/tools/kdoc-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/doc/KDocMojo.java index 83c99535bef..d2dea0a4266 100644 --- a/libraries/tools/kdoc-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/doc/KDocMojo.java +++ b/libraries/tools/kdoc-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/doc/KDocMojo.java @@ -17,8 +17,8 @@ package org.jetbrains.kotlin.maven.doc; import org.apache.maven.plugin.MojoExecutionException; -import org.jetbrains.jet.cli.CompilerArguments; -import org.jetbrains.jet.cli.KotlinCompiler; +import org.jetbrains.jet.cli.jvm.K2JVMCompilerArguments; +import org.jetbrains.jet.cli.jvm.K2JVMCompiler; import org.jetbrains.kotlin.doc.KDocArguments; import org.jetbrains.kotlin.doc.KDocCompiler; import org.jetbrains.kotlin.doc.KDocConfig; @@ -164,17 +164,17 @@ public class KDocMojo extends KotlinCompileMojoBase { private Map packageSummaryText; @Override - protected KotlinCompiler createCompiler() { + protected K2JVMCompiler createCompiler() { return new KDocCompiler(); } @Override - protected CompilerArguments createCompilerArguments() { + protected K2JVMCompilerArguments createCompilerArguments() { return new KDocArguments(); } @Override - protected void configureCompilerArguments(CompilerArguments arguments) throws MojoExecutionException { + protected void configureCompilerArguments(K2JVMCompilerArguments arguments) throws MojoExecutionException { configureBaseCompilerArguments(getLog(), arguments, docModule, sources, classpath, output); if (arguments instanceof KDocArguments) { diff --git a/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/JavadocStyleHtmlDoclet.kt b/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/JavadocStyleHtmlDoclet.kt index 847452d3c28..ad2e696fc1b 100644 --- a/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/JavadocStyleHtmlDoclet.kt +++ b/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/JavadocStyleHtmlDoclet.kt @@ -15,7 +15,7 @@ import java.util.* import com.intellij.psi.PsiElement import org.jetbrains.jet.lang.resolve.BindingContext import org.jetbrains.jet.lang.resolve.BindingContext.* -import org.jetbrains.jet.compiler.CompilerPlugin +import org.jetbrains.jet.cli.common.CompilerPlugin import org.jetbrains.jet.lang.psi.JetFile import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor import org.jetbrains.jet.lexer.JetTokens diff --git a/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/KDoc.kt b/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/KDoc.kt index b4496becf97..afdd10c5f1a 100644 --- a/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/KDoc.kt +++ b/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/KDoc.kt @@ -15,7 +15,7 @@ import java.util.Collection import com.intellij.psi.PsiElement import org.jetbrains.jet.lang.resolve.BindingContext import org.jetbrains.jet.lang.resolve.BindingContext.* -import org.jetbrains.jet.compiler.CompilerPlugin +import org.jetbrains.jet.cli.common.CompilerPlugin import org.jetbrains.jet.lang.psi.JetFile import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor import org.jetbrains.jet.lexer.JetTokens diff --git a/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/KDocCompiler.kt b/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/KDocCompiler.kt index a4256f29f55..2bdb2416de5 100644 --- a/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/KDocCompiler.kt +++ b/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/KDocCompiler.kt @@ -2,25 +2,25 @@ package org.jetbrains.kotlin.doc import java.io.File import java.io.PrintStream -import org.jetbrains.jet.cli.CompilerArguments -import org.jetbrains.jet.cli.KotlinCompiler -import org.jetbrains.jet.compiler.CompileEnvironmentConfiguration +import org.jetbrains.jet.cli.jvm.K2JVMCompilerArguments +import org.jetbrains.jet.cli.jvm.K2JVMCompiler +import org.jetbrains.jet.cli.jvm.compiler.CompileEnvironmentConfiguration import org.jetbrains.kotlin.doc.highlighter.HtmlCompilerPlugin /** * Main for running the KDocCompiler */ fun main(args: Array): Unit { - KotlinCompiler.doMain(KDocCompiler(), args); + K2JVMCompiler.doMain(KDocCompiler(), args); } /** - * A version of the [[KotlinCompiler]] which includes the [[KDoc]] compiler plugin and allows + * A version of the [[K2JVMCompiler]] which includes the [[KDoc]] compiler plugin and allows * command line validation or for the configuration to be provided via [[KDocArguments]] */ -class KDocCompiler() : KotlinCompiler() { +class KDocCompiler() : K2JVMCompiler() { - protected override fun configureEnvironment(configuration : CompileEnvironmentConfiguration?, arguments : CompilerArguments?) { + protected override fun configureEnvironment(configuration : CompileEnvironmentConfiguration?, arguments : K2JVMCompilerArguments?) { super.configureEnvironment(configuration, arguments) val coreEnvironment = configuration?.getEnvironment() if (coreEnvironment != null) { @@ -38,7 +38,7 @@ class KDocCompiler() : KotlinCompiler() { } } - protected override fun createArguments() : CompilerArguments? { + protected override fun createArguments() : K2JVMCompilerArguments? { return KDocArguments() } @@ -47,7 +47,7 @@ class KDocCompiler() : KotlinCompiler() { } } -class KDocArguments() : CompilerArguments() { +class KDocArguments() : K2JVMCompilerArguments() { public var docConfig: KDocConfig = KDocConfig() diff --git a/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/highlighter/HtmlCompilerPlugin.kt b/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/highlighter/HtmlCompilerPlugin.kt index b9dc146e952..188b375b6b9 100644 --- a/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/highlighter/HtmlCompilerPlugin.kt +++ b/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/highlighter/HtmlCompilerPlugin.kt @@ -1,7 +1,7 @@ package org.jetbrains.kotlin.doc.highlighter -import org.jetbrains.jet.compiler.CompilerPlugin -import org.jetbrains.jet.compiler.CompilerPluginContext +import org.jetbrains.jet.cli.common.CompilerPlugin +import org.jetbrains.jet.cli.common.CompilerPluginContext /** */ diff --git a/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/model/KModelCompilerPlugin.kt b/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/model/KModelCompilerPlugin.kt index 26aa13b2462..47852604562 100644 --- a/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/model/KModelCompilerPlugin.kt +++ b/libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/model/KModelCompilerPlugin.kt @@ -1,7 +1,7 @@ package org.jetbrains.kotlin.doc.model -import org.jetbrains.jet.compiler.CompilerPlugin -import org.jetbrains.jet.compiler.CompilerPluginContext +import org.jetbrains.jet.cli.common.CompilerPlugin +import org.jetbrains.jet.cli.common.CompilerPluginContext import org.jetbrains.kotlin.doc.KDocConfig /** Base class for any compiler plugin which needs to process a KModel */ diff --git a/libraries/tools/kdoc/src/test/kotlin/test/kotlin/kdoc/HtmlVisitorTest.kt b/libraries/tools/kdoc/src/test/kotlin/test/kotlin/kdoc/HtmlVisitorTest.kt index 2c9a8977659..7b873d58922 100644 --- a/libraries/tools/kdoc/src/test/kotlin/test/kotlin/kdoc/HtmlVisitorTest.kt +++ b/libraries/tools/kdoc/src/test/kotlin/test/kotlin/kdoc/HtmlVisitorTest.kt @@ -2,8 +2,8 @@ package test.kotlin.kdoc import java.io.File import kotlin.test.assertTrue -import org.jetbrains.jet.cli.CompilerArguments -import org.jetbrains.jet.cli.KotlinCompiler +import org.jetbrains.jet.cli.jvm.K2JVMCompilerArguments +import org.jetbrains.jet.cli.jvm.K2JVMCompiler import org.jetbrains.kotlin.doc.highlighter.HtmlCompilerPlugin import org.junit.Test @@ -20,12 +20,12 @@ class HtmlVisitorTest { val outDir = File(dir, "target/htmldocs") println("Generating source HTML to $outDir") - val args = CompilerArguments() + val args = K2JVMCompilerArguments() args.setSrc(srcDir.toString()) args.setOutputDir(File(dir, "target/classes-htmldocs").toString()) args.getCompilerPlugins()?.add(HtmlCompilerPlugin()) - val compiler = KotlinCompiler() + val compiler = K2JVMCompiler() compiler.exec(System.out, args) } } \ No newline at end of file diff --git a/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/K2JSCompilerMojo.java b/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/K2JSCompilerMojo.java index 9cfb8dfb3cf..769a12ea9ba 100644 --- a/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/K2JSCompilerMojo.java +++ b/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/K2JSCompilerMojo.java @@ -17,7 +17,7 @@ package org.jetbrains.kotlin.maven; import org.apache.maven.plugin.MojoExecutionException; -import org.jetbrains.jet.cli.CompilerArguments; +import org.jetbrains.jet.cli.jvm.K2JVMCompilerArguments; /** * Converts Kotlin to JavaScript code @@ -36,7 +36,7 @@ public class K2JSCompilerMojo extends KotlinCompileMojo { private String outFile; @Override - protected void configureCompilerArguments(CompilerArguments arguments) throws MojoExecutionException { + protected void configureCompilerArguments(K2JVMCompilerArguments arguments) throws MojoExecutionException { super.configureCompilerArguments(arguments); K2JSCompilerPlugin plugin = new K2JSCompilerPlugin(); diff --git a/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/K2JSCompilerPlugin.java b/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/K2JSCompilerPlugin.java index 25962fe74ff..18eeafe73ce 100644 --- a/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/K2JSCompilerPlugin.java +++ b/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/K2JSCompilerPlugin.java @@ -19,8 +19,8 @@ package org.jetbrains.kotlin.maven; import com.google.common.io.Files; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.compiler.CompilerPlugin; -import org.jetbrains.jet.compiler.CompilerPluginContext; +import org.jetbrains.jet.cli.common.CompilerPlugin; +import org.jetbrains.jet.cli.common.CompilerPluginContext; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.k2js.config.Config; diff --git a/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/KotlinCompileMojo.java b/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/KotlinCompileMojo.java index cf87d2b4d6c..2e2edbb5868 100644 --- a/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/KotlinCompileMojo.java +++ b/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/KotlinCompileMojo.java @@ -17,7 +17,7 @@ package org.jetbrains.kotlin.maven; import org.apache.maven.plugin.MojoExecutionException; -import org.jetbrains.jet.cli.CompilerArguments; +import org.jetbrains.jet.cli.jvm.K2JVMCompilerArguments; /** * Compiles kotlin sources @@ -29,7 +29,7 @@ import org.jetbrains.jet.cli.CompilerArguments; */ public class KotlinCompileMojo extends KotlinCompileMojoBase { @Override - protected void configureCompilerArguments(CompilerArguments arguments) throws MojoExecutionException { + protected void configureCompilerArguments(K2JVMCompilerArguments arguments) throws MojoExecutionException { configureBaseCompilerArguments(getLog(), arguments, module, sources, classpath, output); } } diff --git a/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/KotlinCompileMojoBase.java b/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/KotlinCompileMojoBase.java index ee10c5baf34..95db5cd5dfc 100644 --- a/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/KotlinCompileMojoBase.java +++ b/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/KotlinCompileMojoBase.java @@ -23,8 +23,10 @@ import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; -import org.jetbrains.jet.cli.CompilerArguments; -import org.jetbrains.jet.cli.KotlinCompiler; +import org.jetbrains.jet.cli.jvm.K2JVMCompilerArguments; +import org.jetbrains.jet.cli.jvm.K2JVMCompiler; +import org.jetbrains.jet.cli.common.ExitCode.*; +import org.jetbrains.jet.cli.common.ExitCode; import java.io.File; import java.io.IOException; @@ -104,15 +106,15 @@ public abstract class KotlinCompileMojoBase extends AbstractMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { - final CompilerArguments arguments = createCompilerArguments(); + final K2JVMCompilerArguments arguments = createCompilerArguments(); configureCompilerArguments(arguments); - final KotlinCompiler compiler = createCompiler(); + final K2JVMCompiler compiler = createCompiler(); printCompilerArgumentsIfDebugEnabled(arguments, compiler); - final KotlinCompiler.ExitCode exitCode = compiler.exec(System.err, arguments); + final ExitCode exitCode = compiler.exec(System.err, arguments); switch (exitCode) { case COMPILATION_ERROR: @@ -123,7 +125,7 @@ public abstract class KotlinCompileMojoBase extends AbstractMojo { } } - private void printCompilerArgumentsIfDebugEnabled(CompilerArguments arguments, KotlinCompiler compiler) { + private void printCompilerArgumentsIfDebugEnabled(K2JVMCompilerArguments arguments, K2JVMCompiler compiler) { if (getLog().isDebugEnabled()) { getLog().debug("Invoking compiler " + compiler + " with arguments:"); try { @@ -142,24 +144,24 @@ public abstract class KotlinCompileMojoBase extends AbstractMojo { } } - protected KotlinCompiler createCompiler() { - return new KotlinCompiler(); + protected K2JVMCompiler createCompiler() { + return new K2JVMCompiler(); } /** * Derived classes can create custom compiler argument implementations * such as for KDoc */ - protected CompilerArguments createCompilerArguments() { - return new CompilerArguments(); + protected K2JVMCompilerArguments createCompilerArguments() { + return new K2JVMCompilerArguments(); } /** * Derived classes can register custom plugins or configurations */ - protected abstract void configureCompilerArguments(CompilerArguments arguments) throws MojoExecutionException; + protected abstract void configureCompilerArguments(K2JVMCompilerArguments arguments) throws MojoExecutionException; - protected void configureBaseCompilerArguments(Log log, CompilerArguments arguments, String module, + protected void configureBaseCompilerArguments(Log log, K2JVMCompilerArguments arguments, String module, List sources, List classpath, String output) throws MojoExecutionException { // don't include runtime, it should be in maven dependencies arguments.mode = "stdlib"; diff --git a/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/KotlinTestCompileMojo.java b/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/KotlinTestCompileMojo.java index afaccba1cba..03a00389bf3 100644 --- a/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/KotlinTestCompileMojo.java +++ b/libraries/tools/kotlin-maven-plugin/src/main/java/org/jetbrains/kotlin/maven/KotlinTestCompileMojo.java @@ -18,7 +18,7 @@ package org.jetbrains.kotlin.maven; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; -import org.jetbrains.jet.cli.CompilerArguments; +import org.jetbrains.jet.cli.jvm.K2JVMCompilerArguments; /** * Compiles Kotlin test sources @@ -47,7 +47,7 @@ public class KotlinTestCompileMojo extends KotlinCompileMojoBase { } @Override - protected void configureCompilerArguments(CompilerArguments arguments) throws MojoExecutionException { + protected void configureCompilerArguments(K2JVMCompilerArguments arguments) throws MojoExecutionException { configureBaseCompilerArguments( getLog(), arguments, testModule, testSources, testClasspath, testOutput); From 9f92b0b5d7c0b034050464410868cd8705128704 Mon Sep 17 00:00:00 2001 From: pTalanov Date: Wed, 25 Apr 2012 20:08:55 +0400 Subject: [PATCH 146/147] Refactor cli: all the jvm stuff goes under org.jetbrains.jet.cli.jvm, common stuff under org.jetbrains.jet.cli.common --- .../jet/cli/jvm/compiler/TipsManager.java | 211 +++++++ .../jet/cli/common/CompilerPlugin.java | 25 + .../jet/cli/common/CompilerPluginContext.java | 51 ++ .../jetbrains/jet/cli/common/ExitCode.java | 36 ++ .../messages/AnalyzerWithCompilerReport.java | 151 +++++ .../messages/CompilerMessageLocation.java | 57 ++ .../messages/CompilerMessageSeverity.java | 32 + .../cli/common/messages/MessageCollector.java | 31 + .../cli/common/messages/MessageRenderer.java | 99 +++ .../jet/cli/common/messages/MessageUtil.java | 32 + .../messages/PrintingMessageCollector.java | 73 +++ .../jetbrains/jet/cli/js/K2JSCompiler.java | 27 + .../jet/cli/js/K2JSCompilerArguments.java | 24 + .../jetbrains/jet/cli/jvm/K2JVMCompiler.java | 255 ++++++++ .../jet/cli/jvm/K2JVMCompilerArguments.java | 165 +++++ .../jet/cli/jvm/K2JVMCompilerVersion.java | 26 + .../cli/jvm/compiler/CliJetFilesProvider.java | 60 ++ .../CompileEnvironmentConfiguration.java | 66 ++ .../compiler/CompileEnvironmentException.java | 34 ++ .../jvm/compiler/CompileEnvironmentUtil.java | 340 +++++++++++ .../cli/jvm/compiler/JetCoreEnvironment.java | 155 +++++ .../compiler/KotlinToJVMBytecodeCompiler.java | 282 +++++++++ .../compiler/ModuleExecutionException.java | 34 ++ .../jvm/compiler/CompileEnvironmentTest.java | 104 ++++ .../CompileJavaAgainstKotlinTest.java | 113 ++++ .../CompileKotlinAgainstKotlinTest.java | 133 ++++ .../compiler/JavaDescriptorResolverTest.java | 72 +++ .../cli/jvm/compiler/NamespaceComparator.java | 568 ++++++++++++++++++ .../jvm/compiler/ReadJavaBinaryClassTest.java | 132 ++++ .../compiler/ReadKotlinBinaryClassTest.java | 110 ++++ .../cli/jvm/compiler/TestCaseWithTmpdir.java | 37 ++ .../cli/jvm/compiler/WriteSignatureTest.java | 316 ++++++++++ .../jvm/compiler/longTest/LibFromMaven.java | 57 ++ ...solveDescriptorsFromExternalLibraries.java | 199 ++++++ .../jet/plugin/compiler/K2JSCompiler.java | 64 ++ 35 files changed, 4171 insertions(+) create mode 100644 compiler/backend/src/org/jetbrains/jet/cli/jvm/compiler/TipsManager.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/common/CompilerPlugin.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/common/CompilerPluginContext.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/common/ExitCode.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/common/messages/AnalyzerWithCompilerReport.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/common/messages/CompilerMessageLocation.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/common/messages/CompilerMessageSeverity.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/common/messages/MessageCollector.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/common/messages/MessageRenderer.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/common/messages/MessageUtil.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/common/messages/PrintingMessageCollector.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompiler.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompilerArguments.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/jvm/K2JVMCompiler.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/jvm/K2JVMCompilerArguments.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/jvm/K2JVMCompilerVersion.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CliJetFilesProvider.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentConfiguration.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentException.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentUtil.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/JetCoreEnvironment.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/KotlinToJVMBytecodeCompiler.java create mode 100644 compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/ModuleExecutionException.java create mode 100644 compiler/tests/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentTest.java create mode 100644 compiler/tests/org/jetbrains/jet/cli/jvm/compiler/CompileJavaAgainstKotlinTest.java create mode 100644 compiler/tests/org/jetbrains/jet/cli/jvm/compiler/CompileKotlinAgainstKotlinTest.java create mode 100644 compiler/tests/org/jetbrains/jet/cli/jvm/compiler/JavaDescriptorResolverTest.java create mode 100644 compiler/tests/org/jetbrains/jet/cli/jvm/compiler/NamespaceComparator.java create mode 100644 compiler/tests/org/jetbrains/jet/cli/jvm/compiler/ReadJavaBinaryClassTest.java create mode 100644 compiler/tests/org/jetbrains/jet/cli/jvm/compiler/ReadKotlinBinaryClassTest.java create mode 100644 compiler/tests/org/jetbrains/jet/cli/jvm/compiler/TestCaseWithTmpdir.java create mode 100644 compiler/tests/org/jetbrains/jet/cli/jvm/compiler/WriteSignatureTest.java create mode 100644 compiler/tests/org/jetbrains/jet/cli/jvm/compiler/longTest/LibFromMaven.java create mode 100644 compiler/tests/org/jetbrains/jet/cli/jvm/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java create mode 100644 idea/src/org/jetbrains/jet/plugin/compiler/K2JSCompiler.java diff --git a/compiler/backend/src/org/jetbrains/jet/cli/jvm/compiler/TipsManager.java b/compiler/backend/src/org/jetbrains/jet/cli/jvm/compiler/TipsManager.java new file mode 100644 index 00000000000..3e7972e5e28 --- /dev/null +++ b/compiler/backend/src/org/jetbrains/jet/cli/jvm/compiler/TipsManager.java @@ -0,0 +1,211 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.lang.descriptors.CallableDescriptor; +import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; +import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor; +import org.jetbrains.jet.lang.psi.JetExpression; +import org.jetbrains.jet.lang.psi.JetImportDirective; +import org.jetbrains.jet.lang.psi.JetNamespaceHeader; +import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; +import org.jetbrains.jet.lang.resolve.BindingContext; +import org.jetbrains.jet.lang.resolve.calls.autocasts.AutoCastServiceImpl; +import org.jetbrains.jet.lang.resolve.calls.autocasts.DataFlowInfo; +import org.jetbrains.jet.lang.resolve.scopes.JetScope; +import org.jetbrains.jet.lang.resolve.scopes.JetScopeUtils; +import org.jetbrains.jet.lang.resolve.scopes.receivers.ExpressionReceiver; +import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverDescriptor; +import org.jetbrains.jet.lang.types.JetType; +import org.jetbrains.jet.lang.types.NamespaceType; +import org.jetbrains.jet.lang.types.expressions.ExpressionTypingUtils; + +import java.util.*; + +/** + * @author Nikolay Krasko, Alefas + */ +public final class TipsManager { + + private TipsManager() { + } + + @NotNull + public static Collection getReferenceVariants(JetSimpleNameExpression expression, BindingContext context) { + JetExpression receiverExpression = expression.getReceiverExpression(); + if (receiverExpression != null) { + // Process as call expression + final JetScope resolutionScope = context.get(BindingContext.RESOLUTION_SCOPE, expression); + final JetType expressionType = context.get(BindingContext.EXPRESSION_TYPE, receiverExpression); + + if (expressionType != null && resolutionScope != null) { + if (!(expressionType instanceof NamespaceType)) { + ExpressionReceiver receiverDescriptor = new ExpressionReceiver(receiverExpression, expressionType); + Set descriptors = new HashSet(); + + DataFlowInfo info = context.get(BindingContext.NON_DEFAULT_EXPRESSION_DATA_FLOW, expression); + if (info == null) { + info = DataFlowInfo.EMPTY; + } + + AutoCastServiceImpl autoCastService = new AutoCastServiceImpl(info, context); + List variantsForExplicitReceiver = autoCastService.getVariantsForReceiver(receiverDescriptor); + + for (ReceiverDescriptor descriptor : variantsForExplicitReceiver) { + descriptors.addAll(includeExternalCallableExtensions( + excludePrivateDescriptors(descriptor.getType().getMemberScope().getAllDescriptors()), + resolutionScope, descriptor)); + } + + return descriptors; + } + + return includeExternalCallableExtensions( + excludePrivateDescriptors(expressionType.getMemberScope().getAllDescriptors()), + resolutionScope, new ExpressionReceiver(receiverExpression, expressionType)); + } + return Collections.emptyList(); + } + else { + return getVariantsNoReceiver(expression, context); + } + } + + public static Collection getVariantsNoReceiver(JetExpression expression, BindingContext context) { + JetScope resolutionScope = context.get(BindingContext.RESOLUTION_SCOPE, expression); + if (resolutionScope != null) { + if (expression.getParent() instanceof JetImportDirective || expression.getParent() instanceof JetNamespaceHeader) { + return excludeNonPackageDescriptors(resolutionScope.getAllDescriptors()); + } + else { + HashSet descriptorsSet = Sets.newHashSet(); + + ArrayList result = new ArrayList(); + resolutionScope.getImplicitReceiversHierarchy(result); + + for (ReceiverDescriptor receiverDescriptor : result) { + JetType receiverType = receiverDescriptor.getType(); + descriptorsSet.addAll(receiverType.getMemberScope().getAllDescriptors()); + } + + descriptorsSet.addAll(resolutionScope.getAllDescriptors()); + return excludeNotCallableExtensions(excludePrivateDescriptors(descriptorsSet), resolutionScope); + } + } + return Collections.emptyList(); + } + + @NotNull + public static Collection getReferenceVariants(JetNamespaceHeader expression, BindingContext context) { + JetScope resolutionScope = context.get(BindingContext.RESOLUTION_SCOPE, expression); + if (resolutionScope != null) { + return excludeNonPackageDescriptors(resolutionScope.getAllDescriptors()); + } + + return Collections.emptyList(); + } + + public static Collection excludePrivateDescriptors( + @NotNull Collection descriptors) { + + return Collections2.filter(descriptors, new Predicate() { + @Override + public boolean apply(@Nullable DeclarationDescriptor descriptor) { + if (descriptor == null) { + return false; + } + + if (descriptor instanceof NamespaceDescriptor) { + NamespaceDescriptor namespaceDescriptor = (NamespaceDescriptor) descriptor; + if (namespaceDescriptor.getName().isEmpty()) { + return false; + } + } + + return true; + } + }); + } + + public static Collection excludeNotCallableExtensions( + @NotNull Collection descriptors, @NotNull final JetScope scope + ) { + final Set descriptorsSet = Sets.newHashSet(descriptors); + + final ArrayList result = new ArrayList(); + scope.getImplicitReceiversHierarchy(result); + + descriptorsSet.removeAll( + Collections2.filter(JetScopeUtils.getAllExtensions(scope), new Predicate() { + @Override + public boolean apply(CallableDescriptor callableDescriptor) { + if (!callableDescriptor.getReceiverParameter().exists()) { + return false; + } + for (ReceiverDescriptor receiverDescriptor : result) { + if (ExpressionTypingUtils.checkIsExtensionCallable(receiverDescriptor, callableDescriptor)) { + return false; + } + } + return true; + } + })); + + return Lists.newArrayList(descriptorsSet); + } + + private static Collection excludeNonPackageDescriptors( + @NotNull Collection descriptors) { + return Collections2.filter(descriptors, new Predicate() { + @Override + public boolean apply(DeclarationDescriptor declarationDescriptor) { + return declarationDescriptor instanceof NamespaceDescriptor; + } + }); + } + + private static Set includeExternalCallableExtensions( + @NotNull Collection descriptors, + @NotNull final JetScope externalScope, + @NotNull final ReceiverDescriptor receiverDescriptor + ) { + // It's impossible to add extension function for namespace + JetType receiverType = receiverDescriptor.getType(); + if (receiverType instanceof NamespaceType) { + return new HashSet(descriptors); + } + + Set descriptorsSet = Sets.newHashSet(descriptors); + + descriptorsSet.addAll( + Collections2.filter(JetScopeUtils.getAllExtensions(externalScope), + new Predicate() { + @Override + public boolean apply(CallableDescriptor callableDescriptor) { + return ExpressionTypingUtils.checkIsExtensionCallable(receiverDescriptor, callableDescriptor); + } + })); + + return descriptorsSet; + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/common/CompilerPlugin.java b/compiler/cli/src/org/jetbrains/jet/cli/common/CompilerPlugin.java new file mode 100644 index 00000000000..8587929d80c --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/common/CompilerPlugin.java @@ -0,0 +1,25 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.common; + +/** + * A simple interface for compiler plugins to run after the compiler has finished such as for things like + * generating documentation or code generation etc + */ +public interface CompilerPlugin { + void processFiles(CompilerPluginContext context); +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/common/CompilerPluginContext.java b/compiler/cli/src/org/jetbrains/jet/cli/common/CompilerPluginContext.java new file mode 100644 index 00000000000..7716e3130ed --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/common/CompilerPluginContext.java @@ -0,0 +1,51 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.common; + +import com.intellij.openapi.project.Project; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.BindingContext; + +import java.util.List; + +/** + * Represents the context of available state in which a {@link CompilerPlugin} runs such as + * the {@link Project}, the {@link BindingContext} and the underlying {@link JetFile} files. + */ +public class CompilerPluginContext { + private final Project project; + private final BindingContext context; + private final List files; + + public CompilerPluginContext(Project project, BindingContext context, List files) { + this.project = project; + this.context = context; + this.files = files; + } + + public BindingContext getContext() { + return context; + } + + public List getFiles() { + return files; + } + + public Project getProject() { + return project; + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/common/ExitCode.java b/compiler/cli/src/org/jetbrains/jet/cli/common/ExitCode.java new file mode 100644 index 00000000000..db3c954d0db --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/common/ExitCode.java @@ -0,0 +1,36 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.common; + +/** +* @author Pavel Talanov +*/ +public enum ExitCode { + OK(0), + COMPILATION_ERROR(1), + INTERNAL_ERROR(2); + + private final int code; + + ExitCode(int code) { + this.code = code; + } + + public int getCode() { + return code; + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/common/messages/AnalyzerWithCompilerReport.java b/compiler/cli/src/org/jetbrains/jet/cli/common/messages/AnalyzerWithCompilerReport.java new file mode 100644 index 00000000000..24c2f1b1175 --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/common/messages/AnalyzerWithCompilerReport.java @@ -0,0 +1,151 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.common.messages; + +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.PsiErrorElement; +import com.intellij.psi.PsiRecursiveElementWalkingVisitor; +import jet.Function0; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; +import org.jetbrains.jet.lang.descriptors.ClassDescriptor; +import org.jetbrains.jet.lang.diagnostics.*; +import org.jetbrains.jet.lang.diagnostics.rendering.DefaultErrorMessages; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.BindingContext; +import org.jetbrains.jet.lang.resolve.DescriptorUtils; + +import java.util.Collection; + +/** + * @author Pavel Talanov + */ +public final class AnalyzerWithCompilerReport { + + @NotNull + private static CompilerMessageSeverity convertSeverity(@NotNull Severity severity) { + switch (severity) { + case INFO: + return CompilerMessageSeverity.INFO; + case ERROR: + return CompilerMessageSeverity.ERROR; + case WARNING: + return CompilerMessageSeverity.WARNING; + } + throw new IllegalStateException("Unknown severity: " + severity); + } + + @NotNull + private static final SimpleDiagnosticFactory SYNTAX_ERROR_FACTORY = SimpleDiagnosticFactory.create(Severity.ERROR); + + private boolean hasErrors = false; + @NotNull + private final MessageCollector messageCollectorWrapper; + @Nullable + private AnalyzeExhaust analyzeExhaust = null; + + public AnalyzerWithCompilerReport(@NotNull final MessageCollector collector) { + messageCollectorWrapper = new MessageCollector() { + @Override + public void report(@NotNull CompilerMessageSeverity severity, + @NotNull String message, + @NotNull CompilerMessageLocation location) { + if (CompilerMessageSeverity.ERRORS.contains(severity)) { + hasErrors = true; + } + collector.report(severity, message, location); + } + }; + } + + private void reportDiagnostic(@NotNull Diagnostic diagnostic) { + DiagnosticUtils.LineAndColumn lineAndColumn = DiagnosticUtils.getLineAndColumn(diagnostic); + VirtualFile virtualFile = diagnostic.getPsiFile().getVirtualFile(); + String path = virtualFile == null ? null : virtualFile.getPath(); + String render; + if (diagnostic.getFactory() == SYNTAX_ERROR_FACTORY) { + render = ((SyntaxErrorDiagnostic)diagnostic).message; + } + else { + render = DefaultErrorMessages.RENDERER.render(diagnostic); + } + messageCollectorWrapper.report(convertSeverity(diagnostic.getSeverity()), render, + CompilerMessageLocation.create(path, lineAndColumn.getLine(), lineAndColumn.getColumn())); + } + + private void reportIncompleteHierarchies() { + assert analyzeExhaust != null; + Collection incompletes = analyzeExhaust.getBindingContext().getKeys(BindingContext.INCOMPLETE_HIERARCHY); + if (!incompletes.isEmpty()) { + StringBuilder message = new StringBuilder("The following classes have incomplete hierarchies:\n"); + for (ClassDescriptor incomplete : incompletes) { + String fqName = DescriptorUtils.getFQName(incomplete).getFqName(); + message.append(" ").append(fqName).append("\n"); + } + messageCollectorWrapper.report(CompilerMessageSeverity.ERROR, message.toString(), CompilerMessageLocation.NO_LOCATION); + } + } + + private void reportDiagnostics() { + assert analyzeExhaust != null; + for (Diagnostic diagnostic : analyzeExhaust.getBindingContext().getDiagnostics()) { + reportDiagnostic(diagnostic); + } + } + + private void reportSyntaxErrors(@NotNull Collection files) { + for (JetFile file : files) { + file.accept(new PsiRecursiveElementWalkingVisitor() { + @Override + public void visitErrorElement(PsiErrorElement element) { + String description = element.getErrorDescription(); + String message = StringUtil.isEmpty(description) ? "Syntax error" : description; + Diagnostic diagnostic = new SyntaxErrorDiagnostic(element, Severity.ERROR, message); + reportDiagnostic(diagnostic); + } + }); + } + } + + @Nullable + public AnalyzeExhaust getAnalyzeExhaust() { + return analyzeExhaust; + } + + public boolean hasErrors() { + return hasErrors; + } + + public void analyzeAndReport(@NotNull Function0 analyzer, @NotNull Collection files) { + reportSyntaxErrors(files); + analyzeExhaust = analyzer.invoke(); + reportDiagnostics(); + reportIncompleteHierarchies(); + } + + + public static class SyntaxErrorDiagnostic extends SimpleDiagnostic { + private String message; + + public SyntaxErrorDiagnostic(@NotNull PsiErrorElement psiElement, @NotNull Severity severity, String message) { + super(psiElement, SYNTAX_ERROR_FACTORY, severity); + this.message = message; + } + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/common/messages/CompilerMessageLocation.java b/compiler/cli/src/org/jetbrains/jet/cli/common/messages/CompilerMessageLocation.java new file mode 100644 index 00000000000..247656bc88b --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/common/messages/CompilerMessageLocation.java @@ -0,0 +1,57 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.common.messages; + +import org.jetbrains.annotations.Nullable; + +/** + * @author abreslav + */ +public class CompilerMessageLocation { + + public static final CompilerMessageLocation NO_LOCATION = new CompilerMessageLocation(null, -1, -1); + + public static CompilerMessageLocation create(@Nullable String path, int line, int column) { + if (path == null) { + return NO_LOCATION; + } + return new CompilerMessageLocation(path, line, column); + } + + private final String path; + private final int line; + private final int column; + + private CompilerMessageLocation(@Nullable String path, int line, int column) { + this.path = path; + this.line = line; + this.column = column; + } + + @Nullable + public String getPath() { + return path; + } + + public int getLine() { + return line; + } + + public int getColumn() { + return column; + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/common/messages/CompilerMessageSeverity.java b/compiler/cli/src/org/jetbrains/jet/cli/common/messages/CompilerMessageSeverity.java new file mode 100644 index 00000000000..2608639a9f6 --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/common/messages/CompilerMessageSeverity.java @@ -0,0 +1,32 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.common.messages; + +import java.util.EnumSet; + +/** + * @author abreslav + */ +public enum CompilerMessageSeverity { + INFO, + ERROR, + WARNING, + EXCEPTION, + LOGGING; + + public static final EnumSet ERRORS = EnumSet.of(ERROR, EXCEPTION); +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/common/messages/MessageCollector.java b/compiler/cli/src/org/jetbrains/jet/cli/common/messages/MessageCollector.java new file mode 100644 index 00000000000..44b2697262b --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/common/messages/MessageCollector.java @@ -0,0 +1,31 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.common.messages; + +import org.jetbrains.annotations.NotNull; + +public interface MessageCollector { + MessageCollector PLAIN_TEXT_TO_SYSTEM_ERR = new MessageCollector() { + @Override + public void report(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location) { + System.err.println(MessageRenderer.PLAIN.render(severity, message, location)); + } + }; + + void report(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location); +} + diff --git a/compiler/cli/src/org/jetbrains/jet/cli/common/messages/MessageRenderer.java b/compiler/cli/src/org/jetbrains/jet/cli/common/messages/MessageRenderer.java new file mode 100644 index 00000000000..15eb3824455 --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/common/messages/MessageRenderer.java @@ -0,0 +1,99 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.common.messages; + +import com.intellij.openapi.util.text.StringUtil; +import org.jetbrains.annotations.NotNull; + +import java.io.PrintWriter; +import java.io.StringWriter; + +/** + * @author abreslav + */ +public interface MessageRenderer { + + MessageRenderer TAGS = new MessageRenderer() { + @Override + public String renderPreamble() { + return ""; + } + + @Override + public String render(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location) { + StringBuilder out = new StringBuilder(); + out.append("<").append(severity.toString()); + if (location.getPath() != null) { + out.append(" path=\"").append(e(location.getPath())).append("\""); + out.append(" line=\"").append(location.getLine()).append("\""); + out.append(" column=\"").append(location.getColumn()).append("\""); + } + out.append(">\n"); + + out.append(e(message)); + + out.append("\n"); + return out.toString(); + } + + private String e(String str) { + return StringUtil.escapeXml(str); + } + + @Override + public String renderException(@NotNull Throwable e) { + return render(CompilerMessageSeverity.EXCEPTION, PLAIN.renderException(e), CompilerMessageLocation.NO_LOCATION); + } + + @Override + public String renderConclusion() { + return ""; + } + }; + + MessageRenderer PLAIN = new MessageRenderer() { + @Override + public String renderPreamble() { + return ""; + } + + @Override + public String render(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location) { + String path = location.getPath(); + String position = path == null ? "" : path + ": (" + (location.getLine() + ", " + location.getColumn()) + ") "; + return severity + ": " + position + message; + } + + @Override + public String renderException(@NotNull Throwable e) { + StringWriter out = new StringWriter(); + //noinspection IOResourceOpenedButNotSafelyClosed + e.printStackTrace(new PrintWriter(out)); + return out.toString(); + } + + @Override + public String renderConclusion() { + return ""; + } + }; + + String renderPreamble(); + String render(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location); + String renderException(@NotNull Throwable e); + String renderConclusion(); +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/common/messages/MessageUtil.java b/compiler/cli/src/org/jetbrains/jet/cli/common/messages/MessageUtil.java new file mode 100644 index 00000000000..9e3775e3ef4 --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/common/messages/MessageUtil.java @@ -0,0 +1,32 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.common.messages; + +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils; + +/** + * @author abreslav + */ +public class MessageUtil { + public static CompilerMessageLocation psiElementToMessageLocation(PsiElement element) { + PsiFile file = element.getContainingFile(); + DiagnosticUtils.LineAndColumn lineAndColumn = DiagnosticUtils.getLineAndColumnInPsiFile(file, element.getTextRange()); + return CompilerMessageLocation.create(file.getVirtualFile().getPath(), lineAndColumn.getLine(), lineAndColumn.getColumn()); + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/common/messages/PrintingMessageCollector.java b/compiler/cli/src/org/jetbrains/jet/cli/common/messages/PrintingMessageCollector.java new file mode 100644 index 00000000000..9f9e8b0120d --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/common/messages/PrintingMessageCollector.java @@ -0,0 +1,73 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.common.messages; + +import com.google.common.collect.LinkedHashMultimap; +import com.google.common.collect.Multimap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.cli.common.messages.CompilerMessageLocation; +import org.jetbrains.jet.cli.common.messages.CompilerMessageSeverity; +import org.jetbrains.jet.cli.common.messages.MessageCollector; +import org.jetbrains.jet.cli.common.messages.MessageRenderer; + +import java.io.PrintStream; +import java.util.Collection; + +/** + * @author Pavel Talanov + */ +public class PrintingMessageCollector implements MessageCollector { + private final boolean verbose; + private final PrintStream errStream; + private final MessageRenderer messageRenderer; + + // File path (nullable) -> error message + private final Multimap groupedMessages = LinkedHashMultimap.create(); + + public PrintingMessageCollector(PrintStream errStream, + MessageRenderer messageRenderer, + boolean verbose) { + this.verbose = verbose; + this.errStream = errStream; + this.messageRenderer = messageRenderer; + } + + @Override + public void report(@NotNull CompilerMessageSeverity severity, + @NotNull String message, + @NotNull CompilerMessageLocation location) { + String text = messageRenderer.render(severity, message, location); + if (severity == CompilerMessageSeverity.LOGGING) { + if (!verbose) { + return; + } + errStream.println(text); + } + groupedMessages.put(location.getPath(), text); + } + + public void printToErrStream() { + if (!groupedMessages.isEmpty()) { + for (String path : groupedMessages.keySet()) { + Collection messageTexts = groupedMessages.get(path); + for (String text : messageTexts) { + errStream.println(text); + } + } + } + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompiler.java b/compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompiler.java new file mode 100644 index 00000000000..63d8e8fb778 --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompiler.java @@ -0,0 +1,27 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.js; + +/** + * @author Pavel Talanov + */ +public final class K2JSCompiler { + + public static void main(String... args) { + //TODO + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompilerArguments.java b/compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompilerArguments.java new file mode 100644 index 00000000000..46522696f05 --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompilerArguments.java @@ -0,0 +1,24 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.js; + +/** + * @author Pavel Talanov + */ +//TODO +public class K2JSCompilerArguments { +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/jvm/K2JVMCompiler.java b/compiler/cli/src/org/jetbrains/jet/cli/jvm/K2JVMCompiler.java new file mode 100644 index 00000000000..007253e25e5 --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/jvm/K2JVMCompiler.java @@ -0,0 +1,255 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm; + +import com.google.common.base.Splitter; +import com.google.common.collect.Iterables; +import com.intellij.openapi.Disposable; +import com.intellij.openapi.util.Disposer; +import com.sampullara.cli.Args; +import jet.modules.Module; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.cli.common.CompilerPlugin; +import org.jetbrains.jet.cli.common.ExitCode; +import org.jetbrains.jet.cli.common.messages.PrintingMessageCollector; +import org.jetbrains.jet.codegen.CompilationException; +import org.jetbrains.jet.cli.jvm.compiler.*; +import org.jetbrains.jet.cli.common.messages.*; +import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; +import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; +import org.jetbrains.jet.utils.PathUtil; + +import java.io.File; +import java.io.PrintStream; +import java.util.List; + +import static org.jetbrains.jet.cli.common.ExitCode.*; + +/** + * @author yole + * @author alex.tkachman + */ +@SuppressWarnings("UseOfSystemOutOrSystemErr") +public class K2JVMCompiler { + + public static void main(String... args) { + doMain(new K2JVMCompiler(), args); + } + + /** + * Useful main for derived command line tools + */ + public static void doMain(K2JVMCompiler compiler, String[] args) { + try { + ExitCode rc = compiler.exec(System.out, args); + if (rc != OK) { + System.err.println("exec() finished with " + rc + " return code"); + System.exit(rc.getCode()); + } + } + catch (CompileEnvironmentException e) { + System.err.println(e.getMessage()); + System.exit(INTERNAL_ERROR.getCode()); + } + } + + public ExitCode exec(PrintStream errStream, String... args) { + K2JVMCompilerArguments arguments = createArguments(); + if (!parseArguments(errStream, arguments, args)) { + return INTERNAL_ERROR; + } + return exec(errStream, arguments); + } + + /** + * Executes the compiler on the parsed arguments + */ + public ExitCode exec(final PrintStream errStream, K2JVMCompilerArguments arguments) { + if (arguments.help) { + usage(errStream); + return OK; + } + System.setProperty("java.awt.headless", "true"); + + final MessageRenderer messageRenderer = arguments.tags ? MessageRenderer.TAGS : MessageRenderer.PLAIN; + + errStream.print(messageRenderer.renderPreamble()); + + try { + if (arguments.version) { + errStream.println(messageRenderer.render(CompilerMessageSeverity.INFO, "Kotlin Compiler version " + K2JVMCompilerVersion.VERSION, CompilerMessageLocation.NO_LOCATION)); + } + + CompilerSpecialMode mode = parseCompilerSpecialMode(arguments); + + File jdkHeadersJar; + if (mode.includeJdkHeaders()) { + if (arguments.jdkHeaders != null) { + jdkHeadersJar = new File(arguments.jdkHeaders); + } + else { + jdkHeadersJar = PathUtil.getAltHeadersPath(); + } + } + else { + jdkHeadersJar = null; + } + File runtimeJar; + + if (mode.includeKotlinRuntime()) { + if (arguments.stdlib != null) { + runtimeJar = new File(arguments.stdlib); + } + else { + runtimeJar = PathUtil.getDefaultRuntimePath(); + } + } + else { + runtimeJar = null; + } + + CompilerDependencies dependencies = new CompilerDependencies(mode, CompilerDependencies.findRtJar(), jdkHeadersJar, runtimeJar); + PrintingMessageCollector messageCollector = new PrintingMessageCollector(errStream, messageRenderer, arguments.verbose); + Disposable rootDisposable = CompileEnvironmentUtil.createMockDisposable(); + + JetCoreEnvironment environment = new JetCoreEnvironment(rootDisposable, dependencies); + CompileEnvironmentConfiguration configuration = new CompileEnvironmentConfiguration(environment, dependencies, messageCollector); + + messageCollector.report(CompilerMessageSeverity.LOGGING, "Configuring the compilation environment", + CompilerMessageLocation.NO_LOCATION); + try { + configureEnvironment(configuration, arguments); + + boolean noErrors; + if (arguments.module != null) { + List modules = CompileEnvironmentUtil.loadModuleScript(arguments.module, new PrintingMessageCollector(errStream, messageRenderer, false)); + File directory = new File(arguments.module).getParentFile(); + noErrors = KotlinToJVMBytecodeCompiler.compileModules(configuration, modules, + directory, arguments.jar, arguments.outputDir, + arguments.includeRuntime); + } + else { + // TODO ideally we'd unify to just having a single field that supports multiple files/dirs + if (arguments.getSourceDirs() != null) { + noErrors = KotlinToJVMBytecodeCompiler.compileBunchOfSourceDirectories(configuration, + arguments.getSourceDirs(), arguments.jar, arguments.outputDir, arguments.includeRuntime); + } + else { + noErrors = KotlinToJVMBytecodeCompiler.compileBunchOfSources(configuration, + arguments.src, arguments.jar, arguments.outputDir, arguments.includeRuntime); + } + } + return noErrors ? OK : COMPILATION_ERROR; + } + catch (CompilationException e) { + messageCollector.report(CompilerMessageSeverity.EXCEPTION, MessageRenderer.PLAIN.renderException(e), + MessageUtil.psiElementToMessageLocation(e.getElement())); + return INTERNAL_ERROR; + } + catch (Throwable t) { + messageCollector.report(CompilerMessageSeverity.EXCEPTION, MessageRenderer.PLAIN.renderException(t), CompilerMessageLocation.NO_LOCATION); + return INTERNAL_ERROR; + } + finally { + Disposer.dispose(rootDisposable); + messageCollector.printToErrStream(); + } + } + finally { + errStream.print(messageRenderer.renderConclusion()); + } + } + + @NotNull + private CompilerSpecialMode parseCompilerSpecialMode(@NotNull K2JVMCompilerArguments arguments) { + if (arguments.mode == null) { + return CompilerSpecialMode.REGULAR; + } + else { + for (CompilerSpecialMode variant : CompilerSpecialMode.values()) { + if (arguments.mode.equalsIgnoreCase(variant.name().replaceAll("_", ""))) { + return variant; + } + } + } + // TODO: report properly + throw new IllegalArgumentException("unknown compiler mode: " + arguments.mode); + } + + /** + * Returns true if the arguments can be parsed correctly + */ + protected boolean parseArguments(PrintStream errStream, K2JVMCompilerArguments arguments, String[] args) { + try { + Args.parse(arguments, args); + return true; + } + catch (IllegalArgumentException e) { + usage(errStream); + } + catch (Throwable t) { + // Always use tags + errStream.println(MessageRenderer.TAGS.renderException(t)); + } + return false; + } + + protected void usage(PrintStream target) { + // We should say something like + // Args.usage(target, K2JVMCompilerArguments.class); + // but currently cli-parser we are using does not support that + // a corresponding patch has been sent to the authors + // For now, we are using this: + + PrintStream oldErr = System.err; + System.setErr(target); + try { + // TODO: use proper argv0 + Args.usage(new K2JVMCompilerArguments()); + } finally { + System.setErr(oldErr); + } + } + + /** + * Allow derived classes to add additional command line arguments + */ + protected K2JVMCompilerArguments createArguments() { + return new K2JVMCompilerArguments(); + } + + /** + * Strategy method to configure the environment, allowing compiler + * based tools to customise their own plugins + */ + protected void configureEnvironment(CompileEnvironmentConfiguration configuration, K2JVMCompilerArguments arguments) { + // install any compiler plugins + List plugins = arguments.getCompilerPlugins(); + if (plugins != null) { + configuration.getCompilerPlugins().addAll(plugins); + } + + if (configuration.getCompilerDependencies().getRuntimeJar() != null) { + CompileEnvironmentUtil.addToClasspath(configuration.getEnvironment(), configuration.getCompilerDependencies().getRuntimeJar()); + } + + if (arguments.classpath != null) { + final Iterable classpath = Splitter.on(File.pathSeparatorChar).split(arguments.classpath); + CompileEnvironmentUtil.addToClasspath(configuration.getEnvironment(), Iterables.toArray(classpath, String.class)); + } + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/jvm/K2JVMCompilerArguments.java b/compiler/cli/src/org/jetbrains/jet/cli/jvm/K2JVMCompilerArguments.java new file mode 100644 index 00000000000..bed558b5f08 --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/jvm/K2JVMCompilerArguments.java @@ -0,0 +1,165 @@ +/** + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.jet.cli.jvm; + +import com.sampullara.cli.Argument; +import org.jetbrains.jet.cli.common.CompilerPlugin; + +import java.util.ArrayList; +import java.util.List; + +/** + * Command line arguments for the {@link K2JVMCompiler} + */ +public class K2JVMCompilerArguments { + private List compilerPlugins = new ArrayList(); + + // TODO ideally we'd unify this with 'src' to just having a single field that supports multiple files/dirs + private List sourceDirs; + + public List getSourceDirs() { + return sourceDirs; + } + + public void setSourceDirs(List sourceDirs) { + this.sourceDirs = sourceDirs; + } + + @Argument(value = "output", description = "output directory") + public String outputDir; + + @Argument(value = "jar", description = "jar file name") + public String jar; + + @Argument(value = "src", description = "source file or directory") + public String src; + + @Argument(value = "module", description = "module to compile") + public String module; + + @Argument(value = "classpath", description = "classpath to use when compiling") + public String classpath; + + @Argument(value = "includeRuntime", description = "include Kotlin runtime in to resulting jar") + public boolean includeRuntime; + + @Argument(value = "stdlib", description = "Path to the stdlib.jar") + public String stdlib; + + @Argument(value = "jdkHeaders", description = "Path to the kotlin-jdk-headers.jar") + public String jdkHeaders; + + @Argument(value = "help", alias = "h", description = "show help") + public boolean help; + + @Argument(value = "mode", description = "Special compiler modes: stubs or jdkHeaders") + public String mode; + + @Argument(value = "tags", description = "Demarcate each compilation message (error, warning, etc) with an open and close tag") + public boolean tags; + + @Argument(value = "verbose", description = "Enable verbose logging output") + public boolean verbose; + + @Argument(value = "version", description = "Display compiler version") + public boolean version; + + + public String getClasspath() { + return classpath; + } + + public void setClasspath(String classpath) { + this.classpath = classpath; + } + + public boolean isHelp() { + return help; + } + + public void setHelp(boolean help) { + this.help = help; + } + + public boolean isIncludeRuntime() { + return includeRuntime; + } + + public void setIncludeRuntime(boolean includeRuntime) { + this.includeRuntime = includeRuntime; + } + + public String getJar() { + return jar; + } + + public void setJar(String jar) { + this.jar = jar; + } + + public String getModule() { + return module; + } + + public void setModule(String module) { + this.module = module; + } + + public String getOutputDir() { + return outputDir; + } + + public void setOutputDir(String outputDir) { + this.outputDir = outputDir; + } + + public String getSrc() { + return src; + } + + public void setSrc(String src) { + this.src = src; + } + + public String getStdlib() { + return stdlib; + } + + public void setStdlib(String stdlib) { + this.stdlib = stdlib; + } + + public boolean isTags() { + return tags; + } + + public void setTags(boolean tags) { + this.tags = tags; + } + + public List getCompilerPlugins() { + return compilerPlugins; + } + + /** + * Sets the compiler plugins to be used when working with the {@link K2JVMCompiler} + */ + public void setCompilerPlugins(List compilerPlugins) { + this.compilerPlugins = compilerPlugins; + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/jvm/K2JVMCompilerVersion.java b/compiler/cli/src/org/jetbrains/jet/cli/jvm/K2JVMCompilerVersion.java new file mode 100644 index 00000000000..460d5c89493 --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/jvm/K2JVMCompilerVersion.java @@ -0,0 +1,26 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm; + +/** + * @author abreslav + */ +public class K2JVMCompilerVersion { + // The value of this constant is generated by the build script + // DON'T MODIFY IT + public static final String VERSION = "@snapshot@"; +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CliJetFilesProvider.java b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CliJetFilesProvider.java new file mode 100644 index 00000000000..fa66c13bcaa --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CliJetFilesProvider.java @@ -0,0 +1,60 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * @author max + */ +package org.jetbrains.jet.cli.jvm.compiler; + +import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.util.Function; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.java.JetFilesProvider; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class CliJetFilesProvider extends JetFilesProvider { + private final JetCoreEnvironment environment; + private Function> all_files = new Function>() { + @Override + public Collection fun(JetFile file) { + return environment.getSourceFiles(); + } + + }; + + public CliJetFilesProvider(JetCoreEnvironment environment) { + this.environment = environment; + } + + @Override + public Function> sampleToAllFilesInModule() { + return all_files; + } + + @Override + public List allInScope(GlobalSearchScope scope) { + List answer = new ArrayList(); + for (JetFile file : environment.getSourceFiles()) { + if (scope.contains(file.getVirtualFile())) { + answer.add(file); + } + } + return answer; + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentConfiguration.java b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentConfiguration.java new file mode 100644 index 00000000000..e95f3ba7186 --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentConfiguration.java @@ -0,0 +1,66 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +import com.google.common.collect.Lists; +import com.intellij.openapi.util.Disposer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.cli.common.CompilerPlugin; +import org.jetbrains.jet.cli.common.messages.MessageCollector; +import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; + +import java.util.List; + +/** + * @author abreslav + */ +public class CompileEnvironmentConfiguration { + private final JetCoreEnvironment environment; + private final CompilerDependencies compilerDependencies; + private final MessageCollector messageCollector; + + private List compilerPlugins = Lists.newArrayList(); + + /** + * NOTE: It's very important to call dispose for every object of this class or there will be memory leaks. + * @see Disposer + */ + public CompileEnvironmentConfiguration(@NotNull JetCoreEnvironment environment, + @NotNull CompilerDependencies compilerDependencies, @NotNull MessageCollector messageCollector) { + this.messageCollector = messageCollector; + this.compilerDependencies = compilerDependencies; + this.environment = environment; + } + + public JetCoreEnvironment getEnvironment() { + return environment; + } + + @NotNull + public CompilerDependencies getCompilerDependencies() { + return compilerDependencies; + } + + @NotNull + public MessageCollector getMessageCollector() { + return messageCollector; + } + + public List getCompilerPlugins() { + return compilerPlugins; + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentException.java b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentException.java new file mode 100644 index 00000000000..92ef9b972d7 --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentException.java @@ -0,0 +1,34 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +/** + * @author yole + */ +public class CompileEnvironmentException extends RuntimeException { + public CompileEnvironmentException(String message) { + super(message); + } + + public CompileEnvironmentException(Throwable cause) { + super(cause); + } + + public CompileEnvironmentException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentUtil.java b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentUtil.java new file mode 100644 index 00000000000..344fa99cd59 --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentUtil.java @@ -0,0 +1,340 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +import com.intellij.openapi.Disposable; +import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.psi.JavaPsiFacade; +import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.util.Processor; +import jet.modules.AllModules; +import jet.modules.Module; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.cli.common.messages.MessageCollector; +import org.jetbrains.jet.codegen.ClassFileFactory; +import org.jetbrains.jet.codegen.GeneratedClassLoader; +import org.jetbrains.jet.codegen.GenerationState; +import org.jetbrains.jet.lang.resolve.FqName; +import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; +import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; +import org.jetbrains.jet.lang.resolve.java.JvmAbi; +import org.jetbrains.jet.utils.PathUtil; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.List; +import java.util.jar.*; + +/** + * @author abreslav + */ +public class CompileEnvironmentUtil { + public static Disposable createMockDisposable() { + return new Disposable() { + @Override + public void dispose() { + } + }; + } + + @Nullable + public static File getUnpackedRuntimePath() { + URL url = CompileEnvironmentConfiguration.class.getClassLoader().getResource("jet/JetObject.class"); + if (url != null && url.getProtocol().equals("file")) { + return new File(url.getPath()).getParentFile().getParentFile(); + } + return null; + } + + @Nullable + public static File getRuntimeJarPath() { + URL url = CompileEnvironmentConfiguration.class.getClassLoader().getResource("jet/JetObject.class"); + if (url != null && url.getProtocol().equals("jar")) { + String path = url.getPath(); + return new File(path.substring(path.indexOf(":") + 1, path.indexOf("!/"))); + } + return null; + } + + public static void ensureKotlinRuntime(JetCoreEnvironment env) { + if (JavaPsiFacade.getInstance(env.getProject()).findClass("jet.JetObject", GlobalSearchScope.allScope(env.getProject())) == null) { + // TODO: prepend + File kotlin = PathUtil.getDefaultRuntimePath(); + if (kotlin == null || !kotlin.exists()) { + kotlin = getUnpackedRuntimePath(); + if (kotlin == null) kotlin = getRuntimeJarPath(); + } + if (kotlin == null) { + throw new IllegalStateException("kotlin runtime not found"); + } + env.addToClasspath(kotlin); + } + } + + + public static void ensureJdkRuntime(JetCoreEnvironment env) { + if (JavaPsiFacade.getInstance(env.getProject()).findClass("java.lang.Object", GlobalSearchScope.allScope(env.getProject())) == + null) { + // TODO: prepend + env.addToClasspath(findRtJar()); + } + } + + public static File findRtJar() { + String javaHome = System.getProperty("java.home"); + if ("jre".equals(new File(javaHome).getName())) { + javaHome = new File(javaHome).getParent(); + } + + File rtJar = findRtJar(javaHome); + + if (rtJar == null || !rtJar.exists()) { + throw new CompileEnvironmentException("No JDK rt.jar found under " + javaHome); + } + + return rtJar; + } + + private static File findRtJar(String javaHome) { + File rtJar = new File(javaHome, "jre/lib/rt.jar"); + if (rtJar.exists()) { + return rtJar; + } + + File classesJar = new File(new File(javaHome).getParentFile().getAbsolutePath(), "Classes/classes.jar"); + if (classesJar.exists()) { + return classesJar; + } + return null; + } + + public static void ensureRuntime(JetCoreEnvironment environment, CompilerDependencies compilerDependencies) { + if (compilerDependencies.getCompilerSpecialMode() == CompilerSpecialMode.REGULAR) { + ensureJdkRuntime(environment); + ensureKotlinRuntime(environment); + } + else if (compilerDependencies.getCompilerSpecialMode() == CompilerSpecialMode.JDK_HEADERS) { + ensureJdkRuntime(environment); + } + else if (compilerDependencies.getCompilerSpecialMode() == CompilerSpecialMode.STDLIB) { + ensureJdkRuntime(environment); + } + else if (compilerDependencies.getCompilerSpecialMode() == CompilerSpecialMode.BUILTINS) { + // nop + } + else { + throw new IllegalStateException("unknown mode: " + compilerDependencies.getCompilerSpecialMode()); + } + } + + public static List loadModuleScript(String moduleScriptFile, MessageCollector messageCollector) { + Disposable disposable = new Disposable() { + @Override + public void dispose() { + + } + }; + CompilerDependencies dependencies = CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR); + JetCoreEnvironment scriptEnvironment = new JetCoreEnvironment(disposable, dependencies); + ensureRuntime(scriptEnvironment, dependencies); + scriptEnvironment.addSources(moduleScriptFile); + + GenerationState generationState = KotlinToJVMBytecodeCompiler + .analyzeAndGenerate(new CompileEnvironmentConfiguration(scriptEnvironment, dependencies, messageCollector), false); + if (generationState == null) { + return null; + } + + List modules = runDefineModules(dependencies, moduleScriptFile, generationState.getFactory()); + + Disposer.dispose(disposable); + + if (modules == null) { + throw new CompileEnvironmentException("Module script " + moduleScriptFile + " compilation failed"); + } + + if (modules.isEmpty()) { + throw new CompileEnvironmentException("No modules where defined by " + moduleScriptFile); + } + return modules; + } + + private static List runDefineModules(CompilerDependencies compilerDependencies, String moduleFile, ClassFileFactory factory) { + File stdlibJar = compilerDependencies.getRuntimeJar(); + GeneratedClassLoader loader; + if (stdlibJar != null) { + try { + loader = new GeneratedClassLoader(factory, new URLClassLoader(new URL[]{stdlibJar.toURI().toURL()}, + AllModules.class.getClassLoader())); + } + catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + else { + loader = new GeneratedClassLoader(factory, CompileEnvironmentConfiguration.class.getClassLoader()); + } + try { + Class namespaceClass = loader.loadClass(JvmAbi.PACKAGE_CLASS); + final Method method = namespaceClass.getDeclaredMethod("project"); + if (method == null) { + throw new CompileEnvironmentException("Module script " + moduleFile + " must define project() function"); + } + + method.setAccessible(true); + method.invoke(null); + + ArrayList answer = new ArrayList(AllModules.modules.get()); + AllModules.modules.get().clear(); + return answer; + } + catch (Exception e) { + throw new ModuleExecutionException(e); + } + finally { + loader.dispose(); + } + } + + public static void writeToJar(ClassFileFactory factory, final OutputStream fos, @Nullable FqName mainClass, boolean includeRuntime) { + try { + Manifest manifest = new Manifest(); + final Attributes mainAttributes = manifest.getMainAttributes(); + mainAttributes.putValue("Manifest-Version", "1.0"); + mainAttributes.putValue("Created-By", "JetBrains Kotlin"); + if (mainClass != null) { + mainAttributes.putValue("Main-Class", mainClass.getFqName()); + } + JarOutputStream stream = new JarOutputStream(fos, manifest); + try { + for (String file : factory.files()) { + stream.putNextEntry(new JarEntry(file)); + stream.write(factory.asBytes(file)); + } + if (includeRuntime) { + writeRuntimeToJar(stream); + } + } + finally { + stream.close(); + fos.close(); + } + } + catch (IOException e) { + throw new CompileEnvironmentException("Failed to generate jar file", e); + } + } + + private static void writeRuntimeToJar(final JarOutputStream stream) throws IOException { + final File unpackedRuntimePath = getUnpackedRuntimePath(); + if (unpackedRuntimePath != null) { + FileUtil.processFilesRecursively(unpackedRuntimePath, new Processor() { + @Override + public boolean process(File file) { + if (file.isDirectory()) return true; + final String relativePath = FileUtil.getRelativePath(unpackedRuntimePath, file); + try { + stream.putNextEntry(new JarEntry(FileUtil.toSystemIndependentName(relativePath))); + FileInputStream fis = new FileInputStream(file); + try { + FileUtil.copy(fis, stream); + } + finally { + fis.close(); + } + } + catch (IOException e) { + throw new RuntimeException(e); + } + return true; + } + }); + } + else { + File runtimeJarPath = getRuntimeJarPath(); + if (runtimeJarPath != null) { + JarInputStream jis = new JarInputStream(new FileInputStream(runtimeJarPath)); + try { + while (true) { + JarEntry e = jis.getNextJarEntry(); + if (e == null) { + break; + } + if (FileUtil.getExtension(e.getName()).equals("class")) { + stream.putNextEntry(e); + FileUtil.copy(jis, stream); + } + } + } + finally { + jis.close(); + } + } + else { + throw new CompileEnvironmentException("Couldn't find runtime library"); + } + } + } + + public static void writeToOutputDirectory(ClassFileFactory factory, final String outputDir) { + List files = factory.files(); + for (String file : files) { + File target = new File(outputDir, file); + try { + FileUtil.writeToFile(target, factory.asBytes(file)); + } + catch (IOException e) { + throw new CompileEnvironmentException(e); + } + } + } + + /** + * Add path specified to the compilation environment. + * + * @param environment compilation environment to add to + * @param paths paths to add + */ + public static void addToClasspath(JetCoreEnvironment environment, File... paths) { + for (File path : paths) { + if (!path.exists()) { + throw new CompileEnvironmentException("'" + path + "' does not exist"); + } + environment.addToClasspath(path); + } + } + + /** + * Add path specified to the compilation environment. + * + * @param environment compilation environment to add to + * @param paths paths to add + */ + public static void addToClasspath(JetCoreEnvironment environment, String... paths) { + for (String path : paths) { + addToClasspath(environment, new File(path)); + } + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/JetCoreEnvironment.java b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/JetCoreEnvironment.java new file mode 100644 index 00000000000..14e5111f06b --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/JetCoreEnvironment.java @@ -0,0 +1,155 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +import com.intellij.core.JavaCoreEnvironment; +import com.intellij.lang.java.JavaParserDefinition; +import com.intellij.mock.MockApplication; +import com.intellij.openapi.Disposable; +import com.intellij.openapi.extensions.Extensions; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.PsiElementFinder; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiManager; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.asJava.JavaElementFinder; +import org.jetbrains.jet.lang.parsing.JetParserDefinition; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; +import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; +import org.jetbrains.jet.lang.resolve.java.JetFilesProvider; +import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; +import org.jetbrains.jet.plugin.JetFileType; + +import java.io.File; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.List; + +/** + * @author yole + */ +public class JetCoreEnvironment extends JavaCoreEnvironment { + private final List sourceFiles = new ArrayList(); + + public JetCoreEnvironment(Disposable parentDisposable, @NotNull CompilerDependencies compilerDependencies) { + super(parentDisposable); + registerFileType(JetFileType.INSTANCE, "kt"); + registerFileType(JetFileType.INSTANCE, "kts"); + registerFileType(JetFileType.INSTANCE, "ktm"); + registerFileType(JetFileType.INSTANCE, "jet"); + registerParserDefinition(new JavaParserDefinition()); + registerParserDefinition(new JetParserDefinition()); + + + myProject.registerService(JetFilesProvider.class, new CliJetFilesProvider(this)); + Extensions.getArea(myProject) + .getExtensionPoint(PsiElementFinder.EP_NAME) + .registerExtension(new JavaElementFinder(myProject)); + + CompilerSpecialMode compilerSpecialMode = compilerDependencies.getCompilerSpecialMode(); + + addToClasspath(compilerDependencies.getJdkJar()); + + if (compilerSpecialMode.includeJdkHeaders()) { + for (VirtualFile root : compilerDependencies.getJdkHeaderRoots()) { + addLibraryRoot(root); + } + } + if (compilerSpecialMode.includeKotlinRuntime()) { + for (VirtualFile root : compilerDependencies.getRuntimeRoots()) { + addLibraryRoot(root); + } + } + + JetStandardLibrary.initialize(getProject()); + } + + public MockApplication getApplication() { + return myApplication; + } + + private void addSources(File file) { + if(file.isDirectory()) { + File[] files = file.listFiles(); + if (files != null) { + for (File child : files) { + addSources(child); + } + } + } + else { + VirtualFile fileByPath = getLocalFileSystem().findFileByPath(file.getAbsolutePath()); + if (fileByPath != null) { + PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(fileByPath); + if(psiFile instanceof JetFile) { + sourceFiles.add((JetFile)psiFile); + } + } + } + } + + public void addSources(VirtualFile vFile) { + if (vFile.isDirectory()) { + for (VirtualFile virtualFile : vFile.getChildren()) { + addSources(virtualFile); + } + } + else { + if (vFile.getFileType() == JetFileType.INSTANCE) { + PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(vFile); + if (psiFile instanceof JetFile) { + sourceFiles.add((JetFile)psiFile); + } + } + } + } + + public void addSources(String path) { + if(path == null) + return; + + VirtualFile vFile = getLocalFileSystem().findFileByPath(path); + if (vFile == null) { + throw new CompileEnvironmentException("File/directory not found: " + path); + } + if (!vFile.isDirectory() && vFile.getFileType() != JetFileType.INSTANCE) { + throw new CompileEnvironmentException("Not a Kotlin file: " + path); + } + + addSources(new File(path)); + } + + public List getSourceFiles() { + return sourceFiles; + } + + public void addToClasspathFromClassLoader(ClassLoader loader) { + ClassLoader parent = loader.getParent(); + if(parent != null) + addToClasspathFromClassLoader(parent); + + if(loader instanceof URLClassLoader) { + for (URL url : ((URLClassLoader) loader).getURLs()) { + File file = new File(url.getPath()); + if(file.exists() && (!file.isFile() || file.getPath().endsWith(".jar"))) + addToClasspath(file); + } + } + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/KotlinToJVMBytecodeCompiler.java b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/KotlinToJVMBytecodeCompiler.java new file mode 100644 index 00000000000..af98cf42dc6 --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/KotlinToJVMBytecodeCompiler.java @@ -0,0 +1,282 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiFile; +import com.intellij.testFramework.LightVirtualFile; +import com.intellij.util.LocalTimeCounter; +import jet.Function0; +import jet.modules.Module; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; +import org.jetbrains.jet.cli.common.CompilerPlugin; +import org.jetbrains.jet.cli.common.CompilerPluginContext; +import org.jetbrains.jet.codegen.*; +import org.jetbrains.jet.cli.common.messages.AnalyzerWithCompilerReport; +import org.jetbrains.jet.cli.common.messages.CompilerMessageLocation; +import org.jetbrains.jet.cli.common.messages.CompilerMessageSeverity; +import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.psi.JetPsiUtil; +import org.jetbrains.jet.lang.resolve.FqName; +import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; +import org.jetbrains.jet.lang.resolve.java.JvmAbi; +import org.jetbrains.jet.plugin.JetLanguage; +import org.jetbrains.jet.plugin.JetMainDetector; +import org.jetbrains.jet.utils.Progress; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.util.List; + +/** + * @author yole + * @author abreslav + */ +public class KotlinToJVMBytecodeCompiler { + + private KotlinToJVMBytecodeCompiler() { + } + + @Nullable + public static ClassFileFactory compileModule( + CompileEnvironmentConfiguration configuration, + Module moduleBuilder, + File directory + ) { + if (moduleBuilder.getSourceFiles().isEmpty()) { + throw new CompileEnvironmentException("No source files where defined"); + } + + for (String sourceFile : moduleBuilder.getSourceFiles()) { + File source = new File(sourceFile); + if (!source.isAbsolute()) { + source = new File(directory, sourceFile); + } + + if (!source.exists()) { + throw new CompileEnvironmentException("'" + source + "' does not exist"); + } + + configuration.getEnvironment().addSources(source.getPath()); + } + for (String classpathRoot : moduleBuilder.getClasspathRoots()) { + configuration.getEnvironment().addToClasspath(new File(classpathRoot)); + } + + CompileEnvironmentUtil.ensureRuntime(configuration.getEnvironment(), configuration.getCompilerDependencies()); + + GenerationState generationState = analyzeAndGenerate(configuration); + if (generationState == null) { + return null; + } + return generationState.getFactory(); + } + + public static boolean compileModules( + CompileEnvironmentConfiguration configuration, + + @NotNull List modules, + + @NotNull File directory, + @Nullable String jarPath, + @Nullable String outputDir, + boolean jarRuntime) { + + for (Module moduleBuilder : modules) { + // TODO: this should be done only once for the environment + if (configuration.getCompilerDependencies().getRuntimeJar() != null) { + CompileEnvironmentUtil + .addToClasspath(configuration.getEnvironment(), configuration.getCompilerDependencies().getRuntimeJar()); + } + ClassFileFactory moduleFactory = compileModule(configuration, moduleBuilder, directory); + if (moduleFactory == null) { + return false; + } + if (outputDir != null) { + CompileEnvironmentUtil.writeToOutputDirectory(moduleFactory, outputDir); + } + else { + String path = jarPath != null ? jarPath : new File(directory, moduleBuilder.getModuleName() + ".jar").getPath(); + try { + CompileEnvironmentUtil.writeToJar(moduleFactory, new FileOutputStream(path), null, jarRuntime); + } + catch (FileNotFoundException e) { + throw new CompileEnvironmentException("Invalid jar path " + path, e); + } + } + } + return true; + } + + private static boolean compileBunchOfSources( + CompileEnvironmentConfiguration configuration, + String jar, + String outputDir, + boolean includeRuntime + ) { + FqName mainClass = null; + for (JetFile file : configuration.getEnvironment().getSourceFiles()) { + if (JetMainDetector.hasMain(file.getDeclarations())) { + FqName fqName = JetPsiUtil.getFQName(file); + mainClass = fqName.child(JvmAbi.PACKAGE_CLASS); + break; + } + } + + CompileEnvironmentUtil.ensureRuntime(configuration.getEnvironment(), configuration.getCompilerDependencies()); + + GenerationState generationState = analyzeAndGenerate(configuration); + if (generationState == null) { + return false; + } + + try { + ClassFileFactory factory = generationState.getFactory(); + if (jar != null) { + try { + CompileEnvironmentUtil.writeToJar(factory, new FileOutputStream(jar), mainClass, includeRuntime); + } + catch (FileNotFoundException e) { + throw new CompileEnvironmentException("Invalid jar path " + jar, e); + } + } + else if (outputDir != null) { + CompileEnvironmentUtil.writeToOutputDirectory(factory, outputDir); + } + else { + throw new CompileEnvironmentException("Output directory or jar file is not specified - no files will be saved to the disk"); + } + return true; + } + finally { + generationState.destroy(); + } + } + + public static boolean compileBunchOfSources( + CompileEnvironmentConfiguration configuration, + + String sourceFileOrDir, String jar, String outputDir, boolean includeRuntime) { + configuration.getEnvironment().addSources(sourceFileOrDir); + + return compileBunchOfSources(configuration, jar, outputDir, includeRuntime); + } + + public static boolean compileBunchOfSourceDirectories( + CompileEnvironmentConfiguration configuration, + + List sources, String jar, String outputDir, boolean includeRuntime) { + for (String source : sources) { + configuration.getEnvironment().addSources(source); + } + + return compileBunchOfSources(configuration, jar, outputDir, includeRuntime); + } + + @Nullable + public static ClassLoader compileText( + CompileEnvironmentConfiguration configuration, + String code) { + configuration.getEnvironment() + .addSources(new LightVirtualFile("script" + LocalTimeCounter.currentTime() + ".kt", JetLanguage.INSTANCE, code)); + + GenerationState generationState = analyzeAndGenerate(configuration); + if (generationState == null) { + return null; + } + return new GeneratedClassLoader(generationState.getFactory()); + } + + @Nullable + public static GenerationState analyzeAndGenerate(CompileEnvironmentConfiguration configuration) { + return analyzeAndGenerate(configuration, configuration.getCompilerDependencies().getCompilerSpecialMode().isStubs()); + } + + @Nullable + public static GenerationState analyzeAndGenerate( + CompileEnvironmentConfiguration configuration, + boolean stubs + ) { + AnalyzeExhaust exhaust = analyze(configuration, stubs); + + if (exhaust == null) { + return null; + } + + exhaust.throwIfError(); + + return generate(configuration, exhaust, stubs); + } + + @Nullable + private static AnalyzeExhaust analyze( + final CompileEnvironmentConfiguration configuration, + boolean stubs) { + final JetCoreEnvironment environment = configuration.getEnvironment(); + AnalyzerWithCompilerReport analyzerWithCompilerReport = new AnalyzerWithCompilerReport(configuration.getMessageCollector()); + final Predicate filesToAnalyzeCompletely = + stubs ? Predicates.alwaysFalse() : Predicates.alwaysTrue(); + analyzerWithCompilerReport.analyzeAndReport( + new Function0() { + @NotNull + @Override + public AnalyzeExhaust invoke() { + return AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( + environment.getProject(), environment.getSourceFiles(), filesToAnalyzeCompletely, + JetControlFlowDataTraceFactory.EMPTY, + configuration.getCompilerDependencies()); + } + }, environment.getSourceFiles() + ); + + return analyzerWithCompilerReport.hasErrors() ? null : analyzerWithCompilerReport.getAnalyzeExhaust(); + } + + @NotNull + private static GenerationState generate( + final CompileEnvironmentConfiguration configuration, + AnalyzeExhaust exhaust, + boolean stubs) { + JetCoreEnvironment environment = configuration.getEnvironment(); + Project project = environment.getProject(); + Progress backendProgress = new Progress() { + @Override + public void log(String message) { + configuration.getMessageCollector().report(CompilerMessageSeverity.LOGGING, message, CompilerMessageLocation.NO_LOCATION); + } + }; + GenerationState generationState = new GenerationState(project, ClassBuilderFactories.binaries(stubs), backendProgress, + exhaust, environment.getSourceFiles(), + configuration.getCompilerDependencies().getCompilerSpecialMode()); + generationState.compileCorrectFiles(CompilationErrorHandler.THROW_EXCEPTION); + + List plugins = configuration.getCompilerPlugins(); + if (plugins != null) { + CompilerPluginContext context = new CompilerPluginContext(project, exhaust.getBindingContext(), environment.getSourceFiles()); + for (CompilerPlugin plugin : plugins) { + plugin.processFiles(context); + } + } + return generationState; + } +} diff --git a/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/ModuleExecutionException.java b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/ModuleExecutionException.java new file mode 100644 index 00000000000..e20d73888fd --- /dev/null +++ b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/ModuleExecutionException.java @@ -0,0 +1,34 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +/** + * @author yole + */ +public class ModuleExecutionException extends RuntimeException { + public ModuleExecutionException(String message) { + super(message); + } + + public ModuleExecutionException(Throwable cause) { + super(cause); + } + + public ModuleExecutionException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentTest.java b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentTest.java new file mode 100644 index 00000000000..57ddba262e0 --- /dev/null +++ b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/CompileEnvironmentTest.java @@ -0,0 +1,104 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +import com.intellij.openapi.util.io.FileUtil; +import junit.framework.TestCase; +import org.jetbrains.jet.cli.common.ExitCode; +import org.jetbrains.jet.cli.jvm.K2JVMCompiler; +import org.jetbrains.jet.codegen.forTestCompile.ForTestCompileJdkHeaders; +import org.jetbrains.jet.codegen.forTestCompile.ForTestCompileRuntime; +import org.jetbrains.jet.parsing.JetParsingTest; +import org.junit.Assert; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; + +/** + * @author yole + * @author alex.tkachman + */ +public class CompileEnvironmentTest extends TestCase { + + public void testSmokeWithCompilerJar() throws IOException { + File tempDir = FileUtil.createTempDirectory("compilerTest", "compilerTest"); + + try { + File stdlib = ForTestCompileRuntime.runtimeJarForTests(); + File jdkHeaders = ForTestCompileJdkHeaders.jdkHeadersForTests(); + File resultJar = new File(tempDir, "result.jar"); + ExitCode rv = new K2JVMCompiler().exec(System.out, + "-module", JetParsingTest.getTestDataDir() + "/compiler/smoke/Smoke.kts", + "-jar", resultJar.getAbsolutePath(), + "-stdlib", stdlib.getAbsolutePath(), + "-jdkHeaders", jdkHeaders.getAbsolutePath()); + Assert.assertEquals("compilation completed with non-zero code", ExitCode.OK, rv); + FileInputStream fileInputStream = new FileInputStream(resultJar); + try { + JarInputStream is = new JarInputStream(fileInputStream); + try { + final List entries = listEntries(is); + assertTrue(entries.contains("Smoke/namespace.class")); + assertEquals(1, entries.size()); + } + finally { + is.close(); + } + } + finally { + fileInputStream.close(); + } + } + finally { + FileUtil.delete(tempDir); + } + } + + public void testSmokeWithCompilerOutput() throws IOException { + File tempDir = FileUtil.createTempDirectory("compilerTest", "compilerTest"); + try { + File out = new File(tempDir, "out"); + File stdlib = ForTestCompileRuntime.runtimeJarForTests(); + File jdkHeaders = ForTestCompileJdkHeaders.jdkHeadersForTests(); + ExitCode exitCode = new K2JVMCompiler() + .exec(System.out, "-src", JetParsingTest.getTestDataDir() + "/compiler/smoke/Smoke.kt", "-output", + out.getAbsolutePath(), "-stdlib", stdlib.getAbsolutePath(), "-jdkHeaders", jdkHeaders.getAbsolutePath()); + Assert.assertEquals(ExitCode.OK, exitCode); + assertEquals(1, out.listFiles().length); + assertEquals(1, out.listFiles()[0].listFiles().length); + } finally { + FileUtil.delete(tempDir); + } + } + + private static List listEntries(JarInputStream is) throws IOException { + List entries = new ArrayList(); + while (true) { + final JarEntry jarEntry = is.getNextJarEntry(); + if (jarEntry == null) { + break; + } + entries.add(jarEntry.getName()); + } + return entries; + } +} diff --git a/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/CompileJavaAgainstKotlinTest.java b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/CompileJavaAgainstKotlinTest.java new file mode 100644 index 00000000000..6f995fb3ff5 --- /dev/null +++ b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/CompileJavaAgainstKotlinTest.java @@ -0,0 +1,113 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.vfs.CharsetToolkit; +import com.intellij.psi.PsiFileFactory; +import com.intellij.psi.impl.PsiFileFactoryImpl; +import com.intellij.testFramework.LightVirtualFile; +import junit.framework.Test; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.JetTestCaseBuilder; +import org.jetbrains.jet.JetTestUtils; +import org.jetbrains.jet.codegen.*; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; +import org.jetbrains.jet.plugin.JetLanguage; +import org.junit.Assert; + +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.ToolProvider; +import java.io.File; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +/** + * @author Stepan Koltsov + * + * @see WriteSignatureTest + */ +public class CompileJavaAgainstKotlinTest extends TestCaseWithTmpdir { + + private final File ktFile; + private final File javaFile; + private JetCoreEnvironment jetCoreEnvironment; + + public CompileJavaAgainstKotlinTest(File ktFile) { + this.ktFile = ktFile; + Assert.assertTrue(ktFile.getName().endsWith(".kt")); + this.javaFile = new File(ktFile.getPath().replaceFirst("\\.kt", ".java")); + } + + @Override + public String getName() { + return ktFile.getName(); + } + + @Override + protected void runTest() throws Throwable { + jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable); + + + String text = FileUtil.loadFile(ktFile); + + LightVirtualFile virtualFile = new LightVirtualFile(ktFile.getName(), JetLanguage.INSTANCE, text); + virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); + JetFile psiFile = (JetFile) ((PsiFileFactoryImpl) PsiFileFactory.getInstance(jetCoreEnvironment.getProject())).trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false); + + ClassFileFactory classFileFactory = GenerationUtils.compileFileGetClassFileFactoryForTest(psiFile, CompilerSpecialMode.REGULAR); + + CompileEnvironmentUtil.writeToOutputDirectory(classFileFactory, tmpdir.getPath()); + + Disposer.dispose(myTestRootDisposable); + + JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); + + StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ENGLISH, Charset.forName("utf-8")); + try { + Iterable javaFileObjectsFromFiles = fileManager.getJavaFileObjectsFromFiles(Collections.singleton(javaFile)); + List options = Arrays.asList( + "-classpath", tmpdir.getPath() + System.getProperty("path.separator") + "out/production/stdlib", + "-d", tmpdir.getPath() + ); + JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, null, options, null, javaFileObjectsFromFiles); + + Assert.assertTrue(task.call()); + } finally { + fileManager.close(); + } + } + + public static Test suite() { + return JetTestCaseBuilder.suiteForDirectory(JetTestCaseBuilder.getTestDataPathBase(), "/compileJavaAgainstKotlin", true, new JetTestCaseBuilder.NamedTestFactory() { + @NotNull + @Override + public Test createTest(@NotNull String dataPath, @NotNull String name, @NotNull File file) { + return new CompileJavaAgainstKotlinTest(file); + } + }); + + } + +} diff --git a/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/CompileKotlinAgainstKotlinTest.java b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/CompileKotlinAgainstKotlinTest.java new file mode 100644 index 00000000000..d4fca06a78f --- /dev/null +++ b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/CompileKotlinAgainstKotlinTest.java @@ -0,0 +1,133 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.vfs.CharsetToolkit; +import com.intellij.psi.PsiFileFactory; +import com.intellij.psi.impl.PsiFileFactoryImpl; +import com.intellij.testFramework.LightVirtualFile; +import junit.framework.Assert; +import junit.framework.Test; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.JetTestCaseBuilder; +import org.jetbrains.jet.JetTestUtils; +import org.jetbrains.jet.codegen.*; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; +import org.jetbrains.jet.plugin.JetLanguage; + +import java.io.File; +import java.io.FilenameFilter; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; + +/** + * @author Stepan Koltsov + */ +public class CompileKotlinAgainstKotlinTest extends TestCaseWithTmpdir { + + private final File ktAFile; + private final File ktBFile; + + public CompileKotlinAgainstKotlinTest(File ktAFile) { + Assert.assertTrue(ktAFile.getName().endsWith("A.kt")); + this.ktAFile = ktAFile; + this.ktBFile = new File(ktAFile.getPath().replaceFirst("A\\.kt$", "B.kt")); + } + + @Override + public String getName() { + return ktAFile.getName(); + } + + private File aDir; + private File bDir; + + @Override + protected void setUp() throws Exception { + super.setUp(); + aDir = new File(tmpdir, "a"); + bDir = new File(tmpdir, "b"); + JetTestUtils.mkdirs(aDir); + JetTestUtils.mkdirs(bDir); + } + + @Override + protected void runTest() throws Throwable { + compileA(); + compileB(); + + URLClassLoader classLoader = new URLClassLoader(new URL[]{ aDir.toURI().toURL(), bDir.toURI().toURL() }); + Class clazz = classLoader.loadClass("bbb.namespace"); + Method main = clazz.getMethod("main", new Class[] { String[].class }); + main.invoke(null, new Object[] { new String[0] }); + } + + private void compileA() throws IOException { + JetCoreEnvironment jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable); + + String text = FileUtil.loadFile(ktAFile); + + LightVirtualFile virtualFile = new LightVirtualFile(ktAFile.getName(), JetLanguage.INSTANCE, text); + virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); + JetFile psiFile = (JetFile) ((PsiFileFactoryImpl) PsiFileFactory.getInstance(jetCoreEnvironment.getProject())).trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false); + + ClassFileFactory classFileFactory = GenerationUtils.compileFileGetClassFileFactoryForTest(psiFile, CompilerSpecialMode.REGULAR); + + CompileEnvironmentUtil.writeToOutputDirectory(classFileFactory, aDir.getPath()); + + Disposer.dispose(myTestRootDisposable); + } + + private void compileB() throws IOException { + JetCoreEnvironment jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable); + + jetCoreEnvironment.addToClasspath(aDir); + + String text = FileUtil.loadFile(ktBFile); + + LightVirtualFile virtualFile = new LightVirtualFile(ktAFile.getName(), JetLanguage.INSTANCE, text); + virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); + JetFile psiFile = (JetFile) ((PsiFileFactoryImpl) PsiFileFactory.getInstance(jetCoreEnvironment.getProject())).trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false); + + ClassFileFactory classFileFactory = GenerationUtils.compileFileGetClassFileFactoryForTest(psiFile, CompilerSpecialMode.REGULAR); + + CompileEnvironmentUtil.writeToOutputDirectory(classFileFactory, bDir.getPath()); + + Disposer.dispose(myTestRootDisposable); + } + + public static Test suite() { + class Filter implements FilenameFilter { + @Override + public boolean accept(File dir, String name) { + return name.endsWith("A.kt"); + } + } + return JetTestCaseBuilder.suiteForDirectory(JetTestCaseBuilder.getTestDataPathBase(), "/compileKotlinAgainstKotlin", true, new Filter(), new JetTestCaseBuilder.NamedTestFactory() { + @NotNull + @Override + public Test createTest(@NotNull String dataPath, @NotNull String name, @NotNull File file) { + return new CompileKotlinAgainstKotlinTest(file); + } + }); + } +} diff --git a/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/JavaDescriptorResolverTest.java b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/JavaDescriptorResolverTest.java new file mode 100644 index 00000000000..d2f9e3ffc2d --- /dev/null +++ b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/JavaDescriptorResolverTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +import org.jetbrains.jet.CompileCompilerDependenciesTest; +import org.jetbrains.jet.JetTestUtils; +import org.jetbrains.jet.di.InjectorForJavaSemanticServices; +import org.jetbrains.jet.lang.descriptors.ClassDescriptor; +import org.jetbrains.jet.lang.resolve.FqName; +import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; +import org.jetbrains.jet.lang.resolve.java.DescriptorSearchRule; +import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; +import org.junit.Assert; + +import javax.tools.*; +import java.io.File; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +/** + * @author Stepan Koltsov + * @see ReadJavaBinaryClassTest + */ +public class JavaDescriptorResolverTest extends TestCaseWithTmpdir { + + // This test can be implemented in ReadJavaBinaryClass test, but it is simpler here + public void testInner() throws Exception { + JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); + + StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ENGLISH, Charset.forName("utf-8")); + try { + File file = new File("compiler/testData/javaDescriptorResolver/inner.java"); + Iterable javaFileObjectsFromFiles = fileManager.getJavaFileObjectsFromFiles(Collections.singleton(file)); + List options = Arrays.asList( + "-d", tmpdir.getPath() + ); + JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, null, options, null, javaFileObjectsFromFiles); + + Assert.assertTrue(task.call()); + } finally { + fileManager.close(); + } + + JetCoreEnvironment jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable, CompilerSpecialMode.JDK_HEADERS); + + jetCoreEnvironment.addToClasspath(tmpdir); + + InjectorForJavaSemanticServices injector = new InjectorForJavaSemanticServices( + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS, true), jetCoreEnvironment.getProject()); + JavaDescriptorResolver javaDescriptorResolver = injector.getJavaDescriptorResolver(); + ClassDescriptor classDescriptor = javaDescriptorResolver.resolveClass(new FqName("A"), DescriptorSearchRule.ERROR_IF_FOUND_IN_KOTLIN); + Assert.assertNotNull(classDescriptor); + } + +} diff --git a/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/NamespaceComparator.java b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/NamespaceComparator.java new file mode 100644 index 00000000000..e7be1728e58 --- /dev/null +++ b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/NamespaceComparator.java @@ -0,0 +1,568 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +import com.google.common.io.Files; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.codegen.PropertyCodegen; +import org.jetbrains.jet.lang.descriptors.*; +import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor; +import org.jetbrains.jet.lang.resolve.DescriptorUtils; +import org.jetbrains.jet.lang.resolve.scopes.JetScope; +import org.jetbrains.jet.lang.resolve.scopes.receivers.ExtensionReceiver; +import org.jetbrains.jet.lang.types.JetType; +import org.jetbrains.jet.lang.types.TypeProjection; +import org.jetbrains.jet.lang.types.Variance; +import org.junit.Assert; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Method; +import java.nio.charset.Charset; +import java.util.*; + +/** + * @author Stepan Koltsov + */ +class NamespaceComparator { + + private final boolean includeObject; + + private NamespaceComparator(boolean includeObject) { + this.includeObject = includeObject; + } + + public static void compareNamespaces(@NotNull NamespaceDescriptor nsa, @NotNull NamespaceDescriptor nsb, boolean includeObject, + @NotNull File txtFile) { + String serialized = new NamespaceComparator(includeObject).doCompareNamespaces(nsa, nsb); + try { + for (;;) { + String expected = Files.toString(txtFile, Charset.forName("utf-8")).replace("\r\n", "\n"); + + if (expected.contains("kick me")) { + // for developer + System.err.println("generating " + txtFile); + Files.write(serialized, txtFile, Charset.forName("utf-8")); + continue; + } + + // compare with hardcopy: make sure nothing is lost in output + Assert.assertEquals(expected, serialized); + break; + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private String doCompareNamespaces(@NotNull NamespaceDescriptor nsa, @NotNull NamespaceDescriptor nsb) { + StringBuilder sb = new StringBuilder(); + Assert.assertEquals(nsa.getName(), nsb.getName()); + + sb.append("namespace " + nsa.getName() + "\n\n"); + + Assert.assertTrue(!nsa.getMemberScope().getAllDescriptors().isEmpty()); + + Set classifierNames = new HashSet(); + Set propertyNames = new HashSet(); + Set functionNames = new HashSet(); + + for (DeclarationDescriptor ad : nsa.getMemberScope().getAllDescriptors()) { + if (ad instanceof ClassifierDescriptor) { + classifierNames.add(ad.getName()); + } + else if (ad instanceof PropertyDescriptor) { + propertyNames.add(ad.getName()); + } + else if (ad instanceof FunctionDescriptor) { + functionNames.add(ad.getName()); + } + else { + throw new AssertionError("unknown member: " + ad); + } + } + + for (String name : classifierNames) { + ClassifierDescriptor ca = nsa.getMemberScope().getClassifier(name); + ClassifierDescriptor cb = nsb.getMemberScope().getClassifier(name); + Assert.assertTrue(ca != null); + Assert.assertTrue(cb != null); + compareClassifiers(ca, cb, sb); + } + + for (String name : propertyNames) { + Set pa = nsa.getMemberScope().getProperties(name); + Set pb = nsb.getMemberScope().getProperties(name); + compareDeclarationSets(pa, pb, sb); + + Assert.assertTrue(nsb.getMemberScope().getFunctions(PropertyCodegen.getterName(name)).isEmpty()); + Assert.assertTrue(nsb.getMemberScope().getFunctions(PropertyCodegen.setterName(name)).isEmpty()); + } + + for (String name : functionNames) { + Set fa = nsa.getMemberScope().getFunctions(name); + Set fb = nsb.getMemberScope().getFunctions(name); + compareDeclarationSets(fa, fb, sb); + } + + return sb.toString(); + } + + private static void compareDeclarationSets(Set a, Set b, + @NotNull StringBuilder sb) { + String at = serializedDeclarationSets(a); + String bt = serializedDeclarationSets(b); + Assert.assertEquals(at, bt); + sb.append(at); + } + + private static String serializedDeclarationSets(Collection ds) { + List strings = new ArrayList(); + for (DeclarationDescriptor d : ds) { + StringBuilder sb = new StringBuilder(); + new Serializer(sb).serialize(d); + strings.add(sb.toString()); + } + + Collections.sort(strings, new MemberComparator()); + + StringBuilder r = new StringBuilder(); + for (String string : strings) { + r.append(string); + r.append("\n"); + } + return r.toString(); + } + + /** + * This comparator only affects test output, you can drop it if you don't want to understand it. + */ + private static class MemberComparator implements Comparator { + + @NotNull + private String normalize(String s) { + return s.replaceFirst( + "^ *(private|final|abstract|open|override|fun|val|var|/\\*.*?\\*/|((?!)<.*?>)| )*", + "") + + s; + } + + @Override + public int compare(@NotNull String a, @NotNull String b) { + return normalize(a).compareTo(normalize(b)); + } + } + + private void compareClassifiers(@NotNull ClassifierDescriptor a, @NotNull ClassifierDescriptor b, @NotNull StringBuilder sb) { + StringBuilder sba = new StringBuilder(); + StringBuilder sbb = new StringBuilder(); + + new FullContentSerialier(sba).serialize((ClassDescriptor) a); + new FullContentSerialier(sbb).serialize((ClassDescriptor) b); + + String as = sba.toString(); + String bs = sbb.toString(); + + Assert.assertEquals(as, bs); + sb.append(as); + } + + + + private static class Serializer { + + protected final StringBuilder sb; + + public Serializer(StringBuilder sb) { + this.sb = sb; + } + + public void serialize(ClassKind kind) { + switch (kind) { + case CLASS: + sb.append("class"); + break; + case TRAIT: + sb.append("trait"); + break; + case OBJECT: + sb.append("object"); + break; + case ANNOTATION_CLASS: + sb.append("annotation class"); + break; + default: + throw new IllegalStateException("unknown class kind: " + kind); + } + } + + + private static Object invoke(Method method, Object thiz, Object... args) { + try { + return method.invoke(thiz, args); + } catch (Exception e) { + throw new RuntimeException("failed to invoke " + method + ": " + e, e); + } + } + + + public void serialize(FunctionDescriptor fun) { + serialize(fun.getModality()); + sb.append(" "); + + if (!fun.getAnnotations().isEmpty()) { + new Serializer(sb).serializeSeparated(fun.getAnnotations(), " "); + sb.append(" "); + } + + if (!fun.getOverriddenDescriptors().isEmpty()) { + sb.append("override /*" + fun.getOverriddenDescriptors().size() + "*/ "); + } + + if (fun instanceof ConstructorDescriptor) { + sb.append("/*constructor*/ "); + } + sb.append("fun "); + if (!fun.getTypeParameters().isEmpty()) { + sb.append("<"); + new Serializer(sb).serializeCommaSeparated(fun.getTypeParameters()); + sb.append(">"); + } + + if (fun.getReceiverParameter().exists()) { + new TypeSerializer(sb).serialize(fun.getReceiverParameter()); + sb.append("."); + } + + sb.append(fun.getName()); + sb.append("("); + new TypeSerializer(sb).serializeCommaSeparated(fun.getValueParameters()); + sb.append("): "); + new TypeSerializer(sb).serialize(fun.getReturnType()); + } + + public void serialize(ExtensionReceiver extensionReceiver) { + serialize(extensionReceiver.getType()); + } + + public void serialize(PropertyDescriptor prop) { + serialize(prop.getModality()); + sb.append(" "); + + if (!prop.getAnnotations().isEmpty()) { + new Serializer(sb).serializeSeparated(prop.getAnnotations(), " "); + sb.append(" "); + } + + if (prop.isVar()) { + sb.append("var "); + } + else { + sb.append("val "); + } + if (!prop.getTypeParameters().isEmpty()) { + sb.append(" <"); + new Serializer(sb).serializeCommaSeparated(prop.getTypeParameters()); + sb.append("> "); + } + if (prop.getReceiverParameter().exists()) { + new TypeSerializer(sb).serialize(prop.getReceiverParameter().getType()); + sb.append("."); + } + sb.append(prop.getName()); + sb.append(": "); + new TypeSerializer(sb).serialize(prop.getType()); + } + + public void serialize(ValueParameterDescriptor valueParameter) { + sb.append("/*"); + sb.append(valueParameter.getIndex()); + sb.append("*/ "); + if (valueParameter.getVarargElementType() != null) { + sb.append("vararg "); + } + sb.append(valueParameter.getName()); + sb.append(": "); + if (valueParameter.getVarargElementType() != null) { + new TypeSerializer(sb).serialize(valueParameter.getVarargElementType()); + } + else { + new TypeSerializer(sb).serialize(valueParameter.getType()); + } + if (valueParameter.hasDefaultValue()) { + sb.append(" = ?"); + } + } + + public void serialize(Variance variance) { + if (variance == Variance.INVARIANT) { + + } + else { + sb.append(variance); + sb.append(' '); + } + } + + public void serialize(Modality modality) { + sb.append(modality.name().toLowerCase()); + } + + public void serialize(AnnotationDescriptor annotation) { + new TypeSerializer(sb).serialize(annotation.getType()); + sb.append("("); + serializeCommaSeparated(annotation.getValueArguments()); + sb.append(")"); + } + + public void serializeCommaSeparated(List list) { + serializeSeparated(list, ", "); + } + + public void serializeSeparated(List list, String sep) { + boolean first = true; + for (Object o : list) { + if (!first) { + sb.append(sep); + } + serialize(o); + first = false; + } + } + + private Method getMethodToSerialize(Object o) { + if (o == null) { + throw new IllegalStateException("won't serialize null"); + } + + // TODO: cache + for (Method method : this.getClass().getMethods()) { + if (!method.getName().equals("serialize")) { + continue; + } + if (method.getParameterTypes().length != 1) { + continue; + } + if (method.getParameterTypes()[0].equals(Object.class)) { + continue; + } + if (method.getParameterTypes()[0].isInstance(o)) { + method.setAccessible(true); + return method; + } + } + throw new IllegalStateException("don't know how to serialize " + o + " (of " + o.getClass() + ")"); + } + + public void serialize(Object o) { + Method method = getMethodToSerialize(o); + invoke(method, this, o); + } + + public void serialize(String s) { + sb.append(s); + } + + public void serialize(ClassDescriptor clazz) { + sb.append(DescriptorUtils.getFQName(clazz)); + } + + public void serialize(NamespaceDescriptor ns) { + sb.append(DescriptorUtils.getFQName(ns)); + } + + public void serialize(TypeParameterDescriptor param) { + sb.append("/*"); + sb.append(param.getIndex()); + if (param.isReified()) { + sb.append(",r"); + } + sb.append("*/ "); + serialize(param.getVariance()); + sb.append(param.getName()); + if (!param.getUpperBounds().isEmpty()) { + sb.append(" : "); + List list = new ArrayList(); + for (JetType upper : param.getUpperBounds()) { + StringBuilder sb = new StringBuilder(); + new TypeSerializer(sb).serialize(upper); + list.add(sb.toString()); + } + Collections.sort(list); + serializeSeparated(list, " & "); // TODO: use where + } + // TODO: lower bounds + } + + } + + private static class TypeSerializer extends Serializer { + + public TypeSerializer(StringBuilder sb) { + super(sb); + } + + @Override + public void serialize(TypeParameterDescriptor param) { + sb.append(param.getName()); + } + + public void serialize(@NotNull JetType type) { + serialize(type.getConstructor().getDeclarationDescriptor()); + if (!type.getArguments().isEmpty()) { + sb.append("<"); + boolean first = true; + for (TypeProjection proj : type.getArguments()) { + if (!first) { + sb.append(", "); + } + serialize(proj.getProjectionKind()); + serialize(proj.getType()); + first = false; + } + sb.append(">"); + } + if (type.isNullable()) { + sb.append("?"); + } + } + + } + + private static boolean isRootNs(DeclarationDescriptor ns) { + return ns instanceof NamespaceDescriptor && ns.getContainingDeclaration() instanceof ModuleDescriptor; + } + + private static class NamespacePrefixSerializer extends Serializer { + + public NamespacePrefixSerializer(StringBuilder sb) { + super(sb); + } + + @Override + public void serialize(NamespaceDescriptor ns) { + super.serialize(ns); + if (isRootNs(ns)) { + return; + } + sb.append("."); + } + + @Override + public void serialize(ClassDescriptor clazz) { + super.serialize(clazz); + sb.append("."); + } + } + + private class FullContentSerialier extends Serializer { + private FullContentSerialier(StringBuilder sb) { + super(sb); + } + + public void serialize(ClassDescriptor klass) { + + if (!klass.getAnnotations().isEmpty()) { + new Serializer(sb).serializeSeparated(klass.getAnnotations(), " "); + sb.append(" "); + } + serialize(klass.getModality()); + sb.append(" "); + + serialize(klass.getKind()); + sb.append(" "); + + new Serializer(sb).serialize(klass); + + if (!klass.getTypeConstructor().getParameters().isEmpty()) { + sb.append("<"); + serializeCommaSeparated(klass.getTypeConstructor().getParameters()); + sb.append(">"); + } + + if (!klass.getTypeConstructor().getSupertypes().isEmpty()) { + sb.append(" : "); + new TypeSerializer(sb).serializeCommaSeparated(new ArrayList(klass.getTypeConstructor().getSupertypes())); + } + + sb.append(" {\n"); + + List typeArguments = new ArrayList(); + for (TypeParameterDescriptor param : klass.getTypeConstructor().getParameters()) { + typeArguments.add(new TypeProjection(Variance.INVARIANT, param.getDefaultType())); + } + + List memberStrings = new ArrayList(); + + for (ConstructorDescriptor constructor : klass.getConstructors()) { + StringBuilder constructorSb = new StringBuilder(); + new Serializer(constructorSb).serialize(constructor); + memberStrings.add(constructorSb.toString()); + } + + JetScope memberScope = klass.getMemberScope(typeArguments); + for (DeclarationDescriptor member : memberScope.getAllDescriptors()) { + if (!includeObject) { + if (member.getName().matches("equals|hashCode|finalize|wait|notify(All)?|toString|clone|getClass")) { + continue; + } + } + StringBuilder memberSb = new StringBuilder(); + new FullContentSerialier(memberSb).serialize(member); + memberStrings.add(memberSb.toString()); + } + + Collections.sort(memberStrings, new MemberComparator()); + + for (String memberString : memberStrings) { + sb.append(indent(memberString)); + } + + if (klass.getClassObjectDescriptor() != null) { + StringBuilder sbForClassObject = new StringBuilder(); + new FullContentSerialier(sbForClassObject).serialize(klass.getClassObjectDescriptor()); + sb.append(indent(sbForClassObject.toString())); + } + + sb.append("}\n"); + } + } + + + private static String indent(String string) { + try { + StringBuilder r = new StringBuilder(); + BufferedReader reader = new BufferedReader(new StringReader(string)); + for (;;) { + String line = reader.readLine(); + if (line == null) { + break; + } + r.append(" "); + r.append(line); + r.append("\n"); + } + return r.toString(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + +} diff --git a/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/ReadJavaBinaryClassTest.java b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/ReadJavaBinaryClassTest.java new file mode 100644 index 00000000000..7e76f3be6dd --- /dev/null +++ b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/ReadJavaBinaryClassTest.java @@ -0,0 +1,132 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.vfs.CharsetToolkit; +import com.intellij.psi.PsiFileFactory; +import com.intellij.psi.impl.PsiFileFactoryImpl; +import com.intellij.testFramework.LightVirtualFile; +import junit.framework.Test; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.CompileCompilerDependenciesTest; +import org.jetbrains.jet.JetTestCaseBuilder; +import org.jetbrains.jet.JetTestUtils; +import org.jetbrains.jet.di.InjectorForJavaSemanticServices; +import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; +import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.BindingContext; +import org.jetbrains.jet.lang.resolve.FqName; +import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; +import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; +import org.jetbrains.jet.lang.resolve.java.DescriptorSearchRule; +import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; +import org.jetbrains.jet.plugin.JetLanguage; +import org.junit.Assert; + +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.ToolProvider; +import java.io.File; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +/** + * @author Stepan Koltsov + */ +public class ReadJavaBinaryClassTest extends TestCaseWithTmpdir { + + private final File ktFile; + private final File javaFile; + private final File txtFile; + + public ReadJavaBinaryClassTest(File ktFile) { + this.ktFile = ktFile; + Assert.assertTrue(ktFile.getName().endsWith(".kt")); + this.javaFile = new File(ktFile.getPath().replaceFirst("\\.kt$", ".java")); + this.txtFile = new File(ktFile.getPath().replaceFirst("\\.kt$", ".txt")); + setName(javaFile.getName()); + } + + + @Override + public void runTest() throws Exception { + NamespaceDescriptor nsa = compileKotlin(); + NamespaceDescriptor nsb = compileJava(); + NamespaceComparator.compareNamespaces(nsa, nsb, false, txtFile); + } + + private NamespaceDescriptor compileKotlin() throws Exception { + JetCoreEnvironment jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable, CompilerSpecialMode.JDK_HEADERS); + + String text = FileUtil.loadFile(ktFile); + + LightVirtualFile virtualFile = new LightVirtualFile(ktFile.getName(), JetLanguage.INSTANCE, text); + virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); + JetFile psiFile = (JetFile) ((PsiFileFactoryImpl) PsiFileFactory.getInstance(jetCoreEnvironment.getProject())).trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false); + + BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegrationAndCheckForErrors( + psiFile, JetControlFlowDataTraceFactory.EMPTY, + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS, true)) + .getBindingContext(); + return bindingContext.get(BindingContext.FQNAME_TO_NAMESPACE_DESCRIPTOR, FqName.topLevel("test")); + } + + private NamespaceDescriptor compileJava() throws Exception { + JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); + + StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ENGLISH, Charset.forName("utf-8")); + try { + Iterable javaFileObjectsFromFiles = fileManager.getJavaFileObjectsFromFiles(Collections.singleton(javaFile)); + List options = Arrays.asList( + "-classpath", "out/production/runtime" + File.pathSeparator + JetTestUtils.getAnnotationsJar().getPath(), + "-d", tmpdir.getPath() + ); + JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, null, options, null, javaFileObjectsFromFiles); + + Assert.assertTrue(task.call()); + } finally { + fileManager.close(); + } + + JetCoreEnvironment jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable, CompilerSpecialMode.JDK_HEADERS); + + jetCoreEnvironment.addToClasspath(tmpdir); + jetCoreEnvironment.addToClasspath(new File("out/production/runtime")); + + InjectorForJavaSemanticServices injector = new InjectorForJavaSemanticServices( + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS, true), jetCoreEnvironment.getProject()); + JavaDescriptorResolver javaDescriptorResolver = injector.getJavaDescriptorResolver(); + return javaDescriptorResolver.resolveNamespace(FqName.topLevel("test"), DescriptorSearchRule.ERROR_IF_FOUND_IN_KOTLIN); + } + + public static Test suite() { + return JetTestCaseBuilder.suiteForDirectory(JetTestCaseBuilder.getTestDataPathBase(), "/readJavaBinaryClass", true, new JetTestCaseBuilder.NamedTestFactory() { + @NotNull + @Override + public Test createTest(@NotNull String dataPath, @NotNull String name, @NotNull File file) { + return new ReadJavaBinaryClassTest(file); + } + }); + } + +} diff --git a/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/ReadKotlinBinaryClassTest.java b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/ReadKotlinBinaryClassTest.java new file mode 100644 index 00000000000..a15d70efffc --- /dev/null +++ b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/ReadKotlinBinaryClassTest.java @@ -0,0 +1,110 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.vfs.CharsetToolkit; +import com.intellij.psi.PsiFileFactory; +import com.intellij.psi.impl.PsiFileFactoryImpl; +import com.intellij.testFramework.LightVirtualFile; +import junit.framework.Assert; +import junit.framework.Test; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.CompileCompilerDependenciesTest; +import org.jetbrains.jet.JetTestCaseBuilder; +import org.jetbrains.jet.JetTestUtils; +import org.jetbrains.jet.codegen.ClassFileFactory; +import org.jetbrains.jet.codegen.GenerationState; +import org.jetbrains.jet.codegen.GenerationUtils; +import org.jetbrains.jet.di.InjectorForJavaSemanticServices; +import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.BindingContext; +import org.jetbrains.jet.lang.resolve.FqName; +import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; +import org.jetbrains.jet.lang.resolve.java.DescriptorSearchRule; +import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; +import org.jetbrains.jet.plugin.JetLanguage; + +import java.io.File; + +/** + * Compile Kotlin and then parse model from .class files. + * + * @author Stepan Koltsov + */ +public class ReadKotlinBinaryClassTest extends TestCaseWithTmpdir { + + private JetCoreEnvironment jetCoreEnvironment; + + private final File testFile; + private final File txtFile; + + public ReadKotlinBinaryClassTest(@NotNull File testFile) { + this.testFile = testFile; + this.txtFile = new File(testFile.getPath().replaceFirst("\\.kt$", ".txt")); + setName(testFile.getName()); + } + + @Override + public void runTest() throws Exception { + jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable, CompilerSpecialMode.JDK_HEADERS); + + String text = FileUtil.loadFile(testFile); + + LightVirtualFile virtualFile = new LightVirtualFile(testFile.getName(), JetLanguage.INSTANCE, text); + virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); + JetFile psiFile = (JetFile) ((PsiFileFactoryImpl) PsiFileFactory.getInstance(jetCoreEnvironment.getProject())).trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false); + + GenerationState state = GenerationUtils.compileFileGetGenerationStateForTest(psiFile, CompilerSpecialMode.JDK_HEADERS); + + ClassFileFactory classFileFactory = state.getFactory(); + + CompileEnvironmentUtil.writeToOutputDirectory(classFileFactory, tmpdir.getPath()); + + NamespaceDescriptor namespaceFromSource = state.getBindingContext().get(BindingContext.FILE_TO_NAMESPACE, psiFile); + + Assert.assertEquals("test", namespaceFromSource.getName()); + + Disposer.dispose(myTestRootDisposable); + + + jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable, CompilerSpecialMode.JDK_HEADERS); + + jetCoreEnvironment.addToClasspath(tmpdir); + jetCoreEnvironment.addToClasspath(new File("out/production/runtime")); + + InjectorForJavaSemanticServices injector = new InjectorForJavaSemanticServices( + CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.JDK_HEADERS, true), jetCoreEnvironment.getProject()); + JavaDescriptorResolver javaDescriptorResolver = injector.getJavaDescriptorResolver(); + NamespaceDescriptor namespaceFromClass = javaDescriptorResolver.resolveNamespace(FqName.topLevel("test"), DescriptorSearchRule.ERROR_IF_FOUND_IN_KOTLIN); + + NamespaceComparator.compareNamespaces(namespaceFromSource, namespaceFromClass, false, txtFile); + } + + public static Test suite() { + return JetTestCaseBuilder.suiteForDirectory(JetTestCaseBuilder.getTestDataPathBase(), "/readKotlinBinaryClass", true, new JetTestCaseBuilder.NamedTestFactory() { + @NotNull + @Override + public Test createTest(@NotNull String dataPath, @NotNull String name, @NotNull File file) { + return new ReadKotlinBinaryClassTest(file); + } + }); + } + +} diff --git a/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/TestCaseWithTmpdir.java b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/TestCaseWithTmpdir.java new file mode 100644 index 00000000000..c3b7635b3a1 --- /dev/null +++ b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/TestCaseWithTmpdir.java @@ -0,0 +1,37 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +import com.intellij.testFramework.UsefulTestCase; +import org.jetbrains.jet.JetTestUtils; + +import java.io.File; + +/** + * @author Stepan Koltsov + */ +public abstract class TestCaseWithTmpdir extends UsefulTestCase { + + protected File tmpdir; + + @Override + protected void setUp() throws Exception { + super.setUp(); + tmpdir = JetTestUtils.tmpDirForTest(this); + } + +} diff --git a/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/WriteSignatureTest.java b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/WriteSignatureTest.java new file mode 100644 index 00000000000..9ffdf0eb2c1 --- /dev/null +++ b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/WriteSignatureTest.java @@ -0,0 +1,316 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler; + +import com.google.common.io.Closeables; +import com.google.common.io.Files; +import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.vfs.CharsetToolkit; +import com.intellij.psi.PsiFileFactory; +import com.intellij.psi.impl.PsiFileFactoryImpl; +import com.intellij.testFramework.LightVirtualFile; +import junit.framework.Test; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.JetTestCaseBuilder; +import org.jetbrains.jet.JetTestUtils; +import org.jetbrains.jet.codegen.*; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; +import org.jetbrains.jet.lang.resolve.java.JvmStdlibNames; +import org.jetbrains.jet.plugin.JetLanguage; +import org.junit.Assert; +import org.objectweb.asm.AnnotationVisitor; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.commons.EmptyVisitor; +import org.objectweb.asm.commons.Method; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Test correctness of written JVM signature + * + * @author Stepan Koltsov + * + * @see CompileJavaAgainstKotlinTest + */ +public class WriteSignatureTest extends TestCaseWithTmpdir { + + private final File ktFile; + private JetCoreEnvironment jetCoreEnvironment; + + public WriteSignatureTest(File ktFile) { + this.ktFile = ktFile; + } + + @Override + public String getName() { + return ktFile.getName(); + } + + @Override + protected void runTest() throws Throwable { + jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(myTestRootDisposable); + + + String text = FileUtil.loadFile(ktFile); + + LightVirtualFile virtualFile = new LightVirtualFile(ktFile.getName(), JetLanguage.INSTANCE, text); + virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); + JetFile psiFile = (JetFile) ((PsiFileFactoryImpl) PsiFileFactory.getInstance(jetCoreEnvironment.getProject())).trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false); + + ClassFileFactory classFileFactory = GenerationUtils.compileFileGetClassFileFactoryForTest(psiFile, CompilerSpecialMode.REGULAR); + + CompileEnvironmentUtil.writeToOutputDirectory(classFileFactory, tmpdir.getPath()); + + Disposer.dispose(myTestRootDisposable); + + final Expectation expectation = parseExpectations(); + + ActualSignature actualSignature = readSignature(expectation.className, expectation.methodName); + + String template = + "jvm signature: %s\n" + + "generic signature: %s\n" + + "kotlin signature: %s\n" + + ""; + + String expected = String.format(template, expectation.jvmSignature, expectation.genericSignature, expectation.kotlinSignature); + String actual = String.format(template, actualSignature.jvmSignature, actualSignature.genericSignature, actualSignature.kotlinSignature); + + Assert.assertEquals(expected, actual); + } + + private static class ActualSignature { + private final String jvmSignature; + private final String genericSignature; + private final String kotlinSignature; + + private ActualSignature(@NotNull String jvmSignature, @Nullable String genericSignature, @Nullable String kotlinSignature) { + this.jvmSignature = jvmSignature; + this.genericSignature = genericSignature; + this.kotlinSignature = kotlinSignature; + } + } + + @NotNull + private ActualSignature readSignature(String className, final String methodName) throws Exception { + // ugly unreadable code begin + FileInputStream classInputStream = new FileInputStream(tmpdir + "/" + className.replace('.', '/') + ".class"); + try { + class Visitor extends EmptyVisitor { + ActualSignature readSignature; + + @Override + public MethodVisitor visitMethod(int access, String name, final String desc, final String signature, String[] exceptions) { + if (name.equals(methodName)) { + + final int parameterCount = new Method(name, desc).getArgumentTypes().length; + + return new EmptyVisitor() { + String typeParameters = ""; + String returnType; + String[] parameterTypes = new String[parameterCount]; + + @Override + public AnnotationVisitor visitAnnotation(String desc, boolean visible) { + if (desc.equals(JvmStdlibNames.JET_METHOD.getDescriptor())) { + return new EmptyVisitor() { + @Override + public void visit(String name, Object value) { + if (name.equals(JvmStdlibNames.JET_METHOD_TYPE_PARAMETERS_FIELD)) { + typeParameters = (String) value; + } + else if (name.equals(JvmStdlibNames.JET_METHOD_RETURN_TYPE_FIELD)) { + returnType = (String) value; + } + } + + @Override + public AnnotationVisitor visitAnnotation(String desc, boolean visible) { + return new EmptyVisitor(); + } + + @Override + public AnnotationVisitor visitArray(String name) { + return new EmptyVisitor(); + } + }; + } + else { + return new EmptyVisitor(); + } + } + + @Override + public AnnotationVisitor visitParameterAnnotation(final int parameter, String desc, boolean visible) { + if (desc.equals(JvmStdlibNames.JET_VALUE_PARAMETER.getDescriptor())) { + return new EmptyVisitor() { + @Override + public void visit(String name, Object value) { + if (name.equals(JvmStdlibNames.JET_VALUE_PARAMETER_TYPE_FIELD)) { + parameterTypes[parameter] = (String) value; + } + } + + @Override + public AnnotationVisitor visitAnnotation(String desc, boolean visible) { + return new EmptyVisitor(); + } + + @Override + public AnnotationVisitor visitArray(String name) { + return new EmptyVisitor(); + } + }; + } + else { + return new EmptyVisitor(); + } + } + + @Override + public AnnotationVisitor visitAnnotationDefault() { + return new EmptyVisitor(); + } + + @Nullable + private String makeKotlinSignature() { + boolean allNulls = true; + + StringBuilder sb = new StringBuilder(); + sb.append(typeParameters); + if (typeParameters != null && typeParameters.length() > 0) { + allNulls = false; + } + sb.append("("); + for (String parameterType : parameterTypes) { + sb.append(parameterType); + if (parameterType != null) { + allNulls = false; + } + } + sb.append(")"); + sb.append(returnType); + if (returnType != null) { + allNulls = false; + } + if (allNulls) { + return null; + } + else { + return sb.toString(); + } + } + + @Override + public void visitEnd() { + Assert.assertNull(readSignature); + readSignature = new ActualSignature(desc, signature, makeKotlinSignature()); + } + }; + } + return super.visitMethod(access, name, desc, signature, exceptions); + } + } + + Visitor visitor = new Visitor(); + + new ClassReader(classInputStream).accept(visitor, + ClassReader.SKIP_CODE|ClassReader.SKIP_DEBUG|ClassReader.SKIP_FRAMES); + + Assert.assertNotNull("method not found: " + className + "::" + methodName, visitor.readSignature); + + return visitor.readSignature; + } finally { + Closeables.closeQuietly(classInputStream); + } + // ugly unreadable code end + } + + private static class Expectation { + private final String className; + private final String methodName; + private final String jvmSignature; + private final String genericSignature; + private final String kotlinSignature; + + private Expectation(@NotNull String className, @NotNull String methodName, + @NotNull String jvmSignature, @Nullable String genericSignature, @Nullable String kotlinSignature) { + this.className = className; + this.methodName = methodName; + this.jvmSignature = jvmSignature; + this.genericSignature = genericSignature; + this.kotlinSignature = kotlinSignature; + } + } + + @NotNull + private static final Pattern methodPattern = Pattern.compile("^// method: *(.*)::(.*?) *(//.*)?"); + private static final Pattern jvmSignaturePattern = Pattern.compile("^// jvm signature: *(.+?) *(//.*)?"); + private static final Pattern genericSignaturePattern = Pattern.compile("^// generic signature: *(.+?) *(//.*)?"); + private static final Pattern kotlinSignaturePattern = Pattern.compile("^// kotlin signature: *(.+?) *(//.*)?"); + private Expectation parseExpectations() throws IOException { + List lines = Files.readLines(ktFile, Charset.forName("utf-8")); + for (int i = 0; i < lines.size() - 3; ++i) { + Matcher methodMatcher = methodPattern.matcher(lines.get(i)); + if (methodMatcher.matches()) { + Matcher jvmSignatureMatcher = jvmSignaturePattern.matcher(lines.get(i + 1)); + Matcher genericSignatureMatcher = genericSignaturePattern.matcher(lines.get(i + 2)); + Matcher kotlinSignatureMatcher = kotlinSignaturePattern.matcher(lines.get(i + 3)); + if (!jvmSignatureMatcher.matches() || !genericSignatureMatcher.matches() || !kotlinSignatureMatcher.matches()) { + throw new AssertionError("'method:' must be followed ... bla bla ... use the source luke"); + } + + String className = methodMatcher.group(1); + String methodName = methodMatcher.group(2); + + String jvmSignature = jvmSignatureMatcher.group(1); + String genericSignature = genericSignatureMatcher.group(1); + String kotlinSignature = kotlinSignatureMatcher.group(1); + if (genericSignature.equals("null")) { + genericSignature = null; + } + if (kotlinSignature.equals("null")) { + kotlinSignature = null; + } + return new Expectation(className, methodName, jvmSignature, genericSignature, kotlinSignature); + } + } + throw new AssertionError("test instructions not found in " + ktFile); + } + + public static Test suite() { + return JetTestCaseBuilder.suiteForDirectory(JetTestCaseBuilder.getTestDataPathBase(), "/writeSignature", true, new JetTestCaseBuilder.NamedTestFactory() { + @NotNull + @Override + public Test createTest(@NotNull String dataPath, @NotNull String name, @NotNull File file) { + return new WriteSignatureTest(file); + } + }); + + } + +} diff --git a/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/longTest/LibFromMaven.java b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/longTest/LibFromMaven.java new file mode 100644 index 00000000000..d39b3ca3f80 --- /dev/null +++ b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/longTest/LibFromMaven.java @@ -0,0 +1,57 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler.longTest; + +import org.jetbrains.annotations.NotNull; + +/** + * @author Stepan Koltsov + */ +public class LibFromMaven { + @NotNull + private final String org; + @NotNull + private final String module; + @NotNull + private final String rev; + + public LibFromMaven(@NotNull String org, @NotNull String module, @NotNull String rev) { + this.org = org; + this.module = module; + this.rev = rev; + } + + @NotNull + public String getOrg() { + return org; + } + + @NotNull + public String getModule() { + return module; + } + + @NotNull + public String getRev() { + return rev; + } + + @Override + public String toString() { + return org + "/" + module + "/" + rev; + } +} diff --git a/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java new file mode 100644 index 00000000000..2351d449223 --- /dev/null +++ b/compiler/tests/org/jetbrains/jet/cli/jvm/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java @@ -0,0 +1,199 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.cli.jvm.compiler.longTest; + +import com.google.common.io.ByteStreams; +import com.intellij.openapi.Disposable; +import com.intellij.openapi.util.Disposer; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.params.HttpMethodParams; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.CompileCompilerDependenciesTest; +import org.jetbrains.jet.JetTestUtils; +import org.jetbrains.jet.TimeUtils; +import org.jetbrains.jet.cli.jvm.compiler.JetCoreEnvironment; +import org.jetbrains.jet.di.InjectorForJavaSemanticServices; +import org.jetbrains.jet.lang.descriptors.ClassDescriptor; +import org.jetbrains.jet.lang.resolve.FqName; +import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; +import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; +import org.jetbrains.jet.lang.resolve.java.DescriptorSearchRule; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +/** + * @author Stepan Koltsov + */ +public class ResolveDescriptorsFromExternalLibraries { + + @NotNull + private final CompilerDependencies compilerDependencies; + + + public static void main(String[] args) throws Exception { + new ResolveDescriptorsFromExternalLibraries().run(); + System.out.println("$"); + } + + + public ResolveDescriptorsFromExternalLibraries() { + System.out.println("Getting compiler dependencies"); + compilerDependencies = CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR, true); + } + + private void run() throws Exception { + testLibrary("com.google.guava", "guava", "12.0-rc2"); + testLibrary("org.springframework", "spring-core", "3.1.1.RELEASE"); + } + + private void testLibrary(@NotNull String org, @NotNull String module, @NotNull String rev) throws Exception { + LibFromMaven lib = new LibFromMaven(org, module, rev); + File jar = getLibrary(lib); + System.out.println("Testing library " + lib + "..."); + System.out.println("Using file " + jar); + + long start = System.currentTimeMillis(); + + Disposable junk = new Disposable() { + @Override + public void dispose() { } + }; + + JetCoreEnvironment jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdk(junk); + jetCoreEnvironment.addToClasspath(jar); + + + InjectorForJavaSemanticServices injector = new InjectorForJavaSemanticServices(compilerDependencies, jetCoreEnvironment.getProject()); + + FileInputStream is = new FileInputStream(jar); + try { + ZipInputStream zip = new ZipInputStream(is); + for (;;) { + ZipEntry entry = zip.getNextEntry(); + if (entry == null) { + break; + } + String entryName = entry.getName(); + if (!entryName.endsWith(".class")) { + continue; + } + if (entryName.matches("(.*/|)package-info\\.class")) { + continue; + } + if (entryName.contains("$")) { + continue; + } + String className = entryName.substring(0, entryName.length() - ".class".length()).replace("/", "."); + ClassDescriptor clazz = injector.getJavaDescriptorResolver().resolveClass(new FqName(className), DescriptorSearchRule.ERROR_IF_FOUND_IN_KOTLIN); + if (clazz == null) { + throw new IllegalStateException("class not found by name " + className + " in " + lib); + } + clazz.getDefaultType().getMemberScope().getAllDescriptors(); + } + + } finally { + try { + is.close(); + } + catch (Throwable e) {} + + Disposer.dispose(junk); + } + + System.out.println("Testing library " + lib + " done in " + TimeUtils.millisecondsToSecondsString(System.currentTimeMillis() - start) + "s"); + } + + @NotNull + private File getLibrary(@NotNull LibFromMaven lib) throws Exception { + File userHome = new File(System.getProperty("user.home")); + String fileName = lib.getModule() + "-" + lib.getRev() + ".jar"; + + File dir = new File(userHome, ".kotlin-project/resolve-libraries/" + lib.getOrg() + "/" + lib.getModule()); + + File file = new File(dir, fileName); + if (file.exists()) { + return file; + } + + JetTestUtils.mkdirs(dir); + + File tmp = new File(dir, fileName + "~"); + + String uri = url(lib); + GetMethod method = new GetMethod(uri); + + FileOutputStream os = null; + + System.out.println("Downloading library " + lib + " to " + file); + + MultiThreadedHttpConnectionManager connectionManager = null; + try { + connectionManager = new MultiThreadedHttpConnectionManager(); + HttpClient httpClient = new HttpClient(connectionManager); + os = new FileOutputStream(tmp); + String userAgent = ResolveDescriptorsFromExternalLibraries.class.getName() + "/commons-httpclient"; + method.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent); + int code = httpClient.executeMethod(method); + if (code != 200) { + throw new RuntimeException("failed to execute GET " + uri + ", code is " + code); + } + InputStream responseBodyAsStream = method.getResponseBodyAsStream(); + if (responseBodyAsStream == null) { + throw new RuntimeException("method is executed fine, but response is null"); + } + ByteStreams.copy(responseBodyAsStream, os); + os.close(); + if (!tmp.renameTo(file)) { + throw new RuntimeException("failed to rename file: " + tmp + " to " + file); + } + return file; + } + finally { + if (method != null) { + try { + method.releaseConnection(); + } + catch (Throwable e) {} + } + if (connectionManager != null) { + try { + connectionManager.shutdown(); + } + catch (Throwable e) {} + } + if (os != null) { + try { + os.close(); + } + catch (Throwable e) {} + } + tmp.delete(); + } + } + + private static String url(LibFromMaven lib) { + return "http://repo1.maven.org/maven2/" + lib.getOrg().replace(".", "/") + "/" + lib.getModule() + "/" + lib.getRev() + + "/" + lib.getModule() + "-" + lib.getRev() + ".jar"; + } +} diff --git a/idea/src/org/jetbrains/jet/plugin/compiler/K2JSCompiler.java b/idea/src/org/jetbrains/jet/plugin/compiler/K2JSCompiler.java new file mode 100644 index 00000000000..ca8f5e0bb58 --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/compiler/K2JSCompiler.java @@ -0,0 +1,64 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.plugin.compiler; + +import com.intellij.openapi.compiler.CompileContext; +import com.intellij.openapi.compiler.CompileScope; +import com.intellij.openapi.compiler.CompilerMessageCategory; +import com.intellij.openapi.compiler.TranslatingCompiler; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.Chunk; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.plugin.JetFileType; +import org.jetbrains.jet.plugin.project.JsModuleDetector; + +/** + * @author Pavel Talanov + */ +public final class K2JSCompiler implements TranslatingCompiler { + + @Override + public boolean isCompilableFile(VirtualFile file, CompileContext context) { + if (!(file.getFileType() instanceof JetFileType)) { + return false; + } + Project project = context.getProject(); + if (project == null) { + return false; + } + return JsModuleDetector.isJsProject(project); + } + + @Override + public void compile(final CompileContext context, Chunk moduleChunk, final VirtualFile[] files, OutputSink sink) { + context.addMessage(CompilerMessageCategory.INFORMATION, "Some useful code will be there", null, -1, -1); + //TODO: + } + + @NotNull + @Override + public String getDescription() { + return "Kotlin to JavaScript compiler"; + } + + @Override + public boolean validateConfiguration(CompileScope scope) { + return true; + } +} From 272bac357d05898bf567112c4fa3ab2370dbf1c7 Mon Sep 17 00:00:00 2001 From: pTalanov Date: Wed, 25 Apr 2012 21:02:45 +0400 Subject: [PATCH 147/147] Fix for teamcity build. --- TeamCityBuild.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TeamCityBuild.xml b/TeamCityBuild.xml index f9ab064f01b..a37cd929ec5 100644 --- a/TeamCityBuild.xml +++ b/TeamCityBuild.xml @@ -10,7 +10,7 @@ - +