diff --git a/RegExpSupport/src/org/intellij/lang/regexp/RegExpBraceMatcher.java b/RegExpSupport/src/org/intellij/lang/regexp/RegExpBraceMatcher.java index e51b63fa22ff..387c548c4d21 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/RegExpBraceMatcher.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/RegExpBraceMatcher.java @@ -28,6 +28,7 @@ public class RegExpBraceMatcher implements PairedBraceMatcher { new BracePair(RegExpTT.SET_OPTIONS, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.NON_CAPT_GROUP, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.POS_LOOKAHEAD, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.NEG_LOOKAHEAD, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.POS_LOOKBEHIND, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.NEG_LOOKBEHIND, RegExpTT.GROUP_END, true), + new BracePair(RegExpTT.PYTHON_NAMED_GROUP, RegExpTT.GROUP_END, true), new BracePair(RegExpTT.CLASS_BEGIN, RegExpTT.CLASS_END, false), new BracePair(RegExpTT.LBRACE, RegExpTT.RBRACE, false), new BracePair(RegExpTT.QUOTE_BEGIN, RegExpTT.QUOTE_END, false),}; } diff --git a/RegExpSupport/src/org/intellij/lang/regexp/RegExpLanguageHost.java b/RegExpSupport/src/org/intellij/lang/regexp/RegExpLanguageHost.java index f1d344564c22..a3251e6d1127 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/RegExpLanguageHost.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/RegExpLanguageHost.java @@ -22,4 +22,5 @@ public interface RegExpLanguageHost { boolean characterNeedsEscaping(char c); boolean supportsPerl5EmbeddedComments(); boolean supportsPossessiveQuantifiers(); + boolean supportsPythonNamedGroups(); } diff --git a/RegExpSupport/src/org/intellij/lang/regexp/RegExpTT.java b/RegExpSupport/src/org/intellij/lang/regexp/RegExpTT.java index 59eafbca65d7..54f03f7bf886 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/RegExpTT.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/RegExpTT.java @@ -97,6 +97,9 @@ public interface RegExpTT { IElementType OPTIONS_ON = new RegExpElementType("OPTIONS_ON"); IElementType OPTIONS_OFF = new RegExpElementType("OPTIONS_OFF"); + // (?P... + IElementType PYTHON_NAMED_GROUP = new RegExpElementType("PYTHON_NAMED_GROUP"); + TokenSet KEYWORDS = TokenSet.create(DOT, STAR, QUEST, PLUS); TokenSet CHARACTERS = TokenSet.create(CHARACTER, @@ -123,7 +126,8 @@ public interface RegExpTT { POS_LOOKAHEAD, NEG_LOOKAHEAD, POS_LOOKBEHIND, - NEG_LOOKBEHIND); + NEG_LOOKBEHIND, + PYTHON_NAMED_GROUP); TokenSet BOUNDARIES = TokenSet.create(BOUNDARY, CARET, DOLLAR); } diff --git a/RegExpSupport/src/org/intellij/lang/regexp/_RegExLexer.java b/RegExpSupport/src/org/intellij/lang/regexp/_RegExLexer.java index 8de1c26644c5..a4126fd94117 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/_RegExLexer.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/_RegExLexer.java @@ -1,21 +1,20 @@ -/* The following code was generated by JFlex 1.4.1 on 18.12.09 20:27 */ +/* The following code was generated by JFlex 1.4.3 on 21.02.10 20:59 */ /* It's an automatically generated code. Do not modify it. */ package org.intellij.lang.regexp; import com.intellij.lexer.FlexLexer; -import com.intellij.psi.StringEscapesTokenTypes; import com.intellij.psi.tree.IElementType; - import java.util.LinkedList; +import com.intellij.psi.StringEscapesTokenTypes; // IDEADEV-11055 @SuppressWarnings({ "ALL", "SameParameterValue", "WeakerAccess", "SameReturnValue", "RedundantThrows", "UnusedDeclaration", "UnusedDeclaration" }) /** * This class is a scanner generated by - * JFlex 1.4.1 - * on 18.12.09 20:27 from the specification file + * JFlex 1.4.3 + * on 21.02.10 20:59 from the specification file * C:/JetBrains/IDEA/tools/lexer/../../community/RegExpSupport/src/org/intellij/lang/regexp/regexp-lexer.flex */ class _RegExLexer implements FlexLexer { @@ -23,86 +22,96 @@ class _RegExLexer implements FlexLexer { private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ - public static final int CLASS1 = 3; - public static final int PROP = 5; - public static final int EMBRACED = 2; - public static final int QUOTED = 1; + public static final int CLASS1 = 6; + public static final int PROP = 10; + public static final int EMBRACED = 4; + public static final int QUOTED = 2; public static final int YYINITIAL = 0; - public static final int COMMENT = 7; - public static final int OPTIONS = 6; - public static final int CLASS2 = 4; + public static final int COMMENT = 14; + public static final int OPTIONS = 12; + public static final int CLASS2 = 8; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7 + }; /** * Translates characters to character classes */ private static final String ZZ_CMAP_PACKED = - "\10\0\2\51\1\13\1\0\1\51\1\60\22\0\1\44\1\55\1\0"+ - "\1\57\1\15\1\0\1\50\1\0\1\4\1\5\1\17\1\20\1\47"+ - "\1\42\1\3\1\0\1\2\7\41\2\1\1\52\1\0\1\56\1\54"+ - "\1\53\1\16\1\0\1\24\1\24\1\30\1\27\1\36\1\34\1\25"+ - "\1\43\1\32\6\43\1\33\1\35\1\43\1\26\3\43\1\26\1\26"+ - "\1\43\1\25\1\10\1\12\1\11\1\14\1\45\1\0\1\23\1\24"+ - "\1\31\1\27\1\23\1\23\2\43\1\32\4\43\1\22\1\43\1\33"+ - "\1\43\1\22\1\26\1\22\1\40\1\43\1\26\1\37\1\43\1\25"+ - "\1\6\1\21\1\7\54\0\1\43\12\0\1\43\4\0\1\43\5\0"+ - "\27\43\1\0\37\43\1\0\u013f\43\31\0\162\43\4\0\14\43\16\0"+ - "\5\43\11\0\1\43\213\0\1\43\13\0\1\43\1\0\3\43\1\0"+ - "\1\43\1\0\24\43\1\0\54\43\1\0\46\43\1\0\5\43\4\0"+ - "\202\43\10\0\105\43\1\0\46\43\2\0\2\43\6\0\20\43\41\0"+ - "\46\43\2\0\1\43\7\0\47\43\110\0\33\43\5\0\3\43\56\0"+ - "\32\43\5\0\13\43\25\0\12\46\4\0\2\43\1\0\143\43\1\0"+ - "\1\43\17\0\2\43\7\0\2\43\12\46\3\43\2\0\1\43\20\0"+ - "\1\43\1\0\36\43\35\0\3\43\60\0\46\43\13\0\1\43\u0152\0"+ - "\66\43\3\0\1\43\22\0\1\43\7\0\12\43\4\0\12\46\25\0"+ - "\10\43\2\0\2\43\2\0\26\43\1\0\7\43\1\0\1\43\3\0"+ - "\4\43\3\0\1\43\36\0\2\43\1\0\3\43\4\0\12\46\2\43"+ - "\23\0\6\43\4\0\2\43\2\0\26\43\1\0\7\43\1\0\2\43"+ - "\1\0\2\43\1\0\2\43\37\0\4\43\1\0\1\43\7\0\12\46"+ - "\2\0\3\43\20\0\11\43\1\0\3\43\1\0\26\43\1\0\7\43"+ - "\1\0\2\43\1\0\5\43\3\0\1\43\22\0\1\43\17\0\2\43"+ - "\4\0\12\46\25\0\10\43\2\0\2\43\2\0\26\43\1\0\7\43"+ - "\1\0\2\43\1\0\5\43\3\0\1\43\36\0\2\43\1\0\3\43"+ - "\4\0\12\46\1\0\1\43\21\0\1\43\1\0\6\43\3\0\3\43"+ - "\1\0\4\43\3\0\2\43\1\0\1\43\1\0\2\43\3\0\2\43"+ - "\3\0\3\43\3\0\10\43\1\0\3\43\55\0\11\46\25\0\10\43"+ - "\1\0\3\43\1\0\27\43\1\0\12\43\1\0\5\43\46\0\2\43"+ - "\4\0\12\46\25\0\10\43\1\0\3\43\1\0\27\43\1\0\12\43"+ - "\1\0\5\43\3\0\1\43\40\0\1\43\1\0\2\43\4\0\12\46"+ - "\25\0\10\43\1\0\3\43\1\0\27\43\1\0\20\43\46\0\2\43"+ - "\4\0\12\46\25\0\22\43\3\0\30\43\1\0\11\43\1\0\1\43"+ - "\2\0\7\43\72\0\60\43\1\0\2\43\14\0\7\43\11\0\12\46"+ - "\47\0\2\43\1\0\1\43\2\0\2\43\1\0\1\43\2\0\1\43"+ - "\6\0\4\43\1\0\7\43\1\0\3\43\1\0\1\43\1\0\1\43"+ - "\2\0\2\43\1\0\4\43\1\0\2\43\11\0\1\43\2\0\5\43"+ - "\1\0\1\43\11\0\12\46\2\0\2\43\42\0\1\43\37\0\12\46"+ - "\26\0\10\43\1\0\42\43\35\0\4\43\164\0\42\43\1\0\5\43"+ - "\1\0\2\43\25\0\12\46\6\0\6\43\112\0\46\43\12\0\51\43"+ - "\7\0\132\43\5\0\104\43\5\0\122\43\6\0\7\43\1\0\77\43"+ - "\1\0\1\43\1\0\4\43\2\0\7\43\1\0\1\43\1\0\4\43"+ - "\2\0\47\43\1\0\1\43\1\0\4\43\2\0\37\43\1\0\1\43"+ - "\1\0\4\43\2\0\7\43\1\0\1\43\1\0\4\43\2\0\7\43"+ - "\1\0\7\43\1\0\27\43\1\0\37\43\1\0\1\43\1\0\4\43"+ - "\2\0\7\43\1\0\47\43\1\0\23\43\16\0\11\46\56\0\125\43"+ - "\14\0\u026c\43\2\0\10\43\12\0\32\43\5\0\113\43\25\0\15\43"+ - "\1\0\4\43\16\0\22\43\16\0\22\43\16\0\15\43\1\0\3\43"+ - "\17\0\64\43\43\0\1\43\4\0\1\43\3\0\12\46\46\0\12\46"+ - "\6\0\130\43\10\0\51\43\127\0\35\43\51\0\12\46\36\43\2\0"+ - "\5\43\u038b\0\154\43\224\0\234\43\4\0\132\43\6\0\26\43\2\0"+ - "\6\43\2\0\46\43\2\0\6\43\2\0\10\43\1\0\1\43\1\0"+ - "\1\43\1\0\1\43\1\0\37\43\2\0\65\43\1\0\7\43\1\0"+ - "\1\43\3\0\3\43\1\0\7\43\3\0\4\43\2\0\6\43\4\0"+ - "\15\43\5\0\3\43\1\0\7\43\164\0\1\43\15\0\1\43\202\0"+ - "\1\43\4\0\1\43\2\0\12\43\1\0\1\43\3\0\5\43\6\0"+ - "\1\43\1\0\1\43\1\0\1\43\1\0\4\43\1\0\3\43\1\0"+ - "\7\43\3\0\3\43\5\0\5\43\u0ebb\0\2\43\52\0\5\43\5\0"+ - "\2\43\4\0\126\43\6\0\3\43\1\0\132\43\1\0\4\43\5\0"+ - "\50\43\4\0\136\43\21\0\30\43\70\0\20\43\u0200\0\u19b6\43\112\0"+ - "\u51a6\43\132\0\u048d\43\u0773\0\u2ba4\43\u215c\0\u012e\43\2\0\73\43\225\0"+ - "\7\43\14\0\5\43\5\0\1\43\1\0\12\43\1\0\15\43\1\0"+ - "\5\43\1\0\1\43\1\0\2\43\1\0\2\43\1\0\154\43\41\0"+ - "\u016b\43\22\0\100\43\2\0\66\43\50\0\14\43\164\0\5\43\1\0"+ - "\207\43\23\0\12\46\7\0\32\43\6\0\32\43\13\0\131\43\3\0"+ - "\6\43\2\0\6\43\2\0\6\43\2\0\3\43\43\0"; + "\10\0\2\52\1\13\1\0\1\52\1\61\22\0\1\45\1\56\1\0"+ + "\1\60\1\15\1\0\1\51\1\0\1\4\1\5\1\17\1\20\1\50"+ + "\1\43\1\3\1\0\1\2\7\42\2\1\1\53\1\0\1\57\1\55"+ + "\1\54\1\16\1\0\1\24\1\24\1\30\1\27\1\37\1\35\1\25"+ + "\1\44\1\32\6\44\1\34\1\36\1\44\1\26\3\44\1\26\1\26"+ + "\1\44\1\25\1\10\1\12\1\11\1\14\1\46\1\0\1\23\1\24"+ + "\1\31\1\27\1\23\1\23\2\44\1\32\4\44\1\22\1\44\1\33"+ + "\1\44\1\22\1\26\1\22\1\41\1\44\1\26\1\40\1\44\1\25"+ + "\1\6\1\21\1\7\54\0\1\44\12\0\1\44\4\0\1\44\5\0"+ + "\27\44\1\0\37\44\1\0\u013f\44\31\0\162\44\4\0\14\44\16\0"+ + "\5\44\11\0\1\44\213\0\1\44\13\0\1\44\1\0\3\44\1\0"+ + "\1\44\1\0\24\44\1\0\54\44\1\0\46\44\1\0\5\44\4\0"+ + "\202\44\10\0\105\44\1\0\46\44\2\0\2\44\6\0\20\44\41\0"+ + "\46\44\2\0\1\44\7\0\47\44\110\0\33\44\5\0\3\44\56\0"+ + "\32\44\5\0\13\44\25\0\12\47\4\0\2\44\1\0\143\44\1\0"+ + "\1\44\17\0\2\44\7\0\2\44\12\47\3\44\2\0\1\44\20\0"+ + "\1\44\1\0\36\44\35\0\3\44\60\0\46\44\13\0\1\44\u0152\0"+ + "\66\44\3\0\1\44\22\0\1\44\7\0\12\44\4\0\12\47\25\0"+ + "\10\44\2\0\2\44\2\0\26\44\1\0\7\44\1\0\1\44\3\0"+ + "\4\44\3\0\1\44\36\0\2\44\1\0\3\44\4\0\12\47\2\44"+ + "\23\0\6\44\4\0\2\44\2\0\26\44\1\0\7\44\1\0\2\44"+ + "\1\0\2\44\1\0\2\44\37\0\4\44\1\0\1\44\7\0\12\47"+ + "\2\0\3\44\20\0\11\44\1\0\3\44\1\0\26\44\1\0\7\44"+ + "\1\0\2\44\1\0\5\44\3\0\1\44\22\0\1\44\17\0\2\44"+ + "\4\0\12\47\25\0\10\44\2\0\2\44\2\0\26\44\1\0\7\44"+ + "\1\0\2\44\1\0\5\44\3\0\1\44\36\0\2\44\1\0\3\44"+ + "\4\0\12\47\1\0\1\44\21\0\1\44\1\0\6\44\3\0\3\44"+ + "\1\0\4\44\3\0\2\44\1\0\1\44\1\0\2\44\3\0\2\44"+ + "\3\0\3\44\3\0\10\44\1\0\3\44\55\0\11\47\25\0\10\44"+ + "\1\0\3\44\1\0\27\44\1\0\12\44\1\0\5\44\46\0\2\44"+ + "\4\0\12\47\25\0\10\44\1\0\3\44\1\0\27\44\1\0\12\44"+ + "\1\0\5\44\3\0\1\44\40\0\1\44\1\0\2\44\4\0\12\47"+ + "\25\0\10\44\1\0\3\44\1\0\27\44\1\0\20\44\46\0\2\44"+ + "\4\0\12\47\25\0\22\44\3\0\30\44\1\0\11\44\1\0\1\44"+ + "\2\0\7\44\72\0\60\44\1\0\2\44\14\0\7\44\11\0\12\47"+ + "\47\0\2\44\1\0\1\44\2\0\2\44\1\0\1\44\2\0\1\44"+ + "\6\0\4\44\1\0\7\44\1\0\3\44\1\0\1\44\1\0\1\44"+ + "\2\0\2\44\1\0\4\44\1\0\2\44\11\0\1\44\2\0\5\44"+ + "\1\0\1\44\11\0\12\47\2\0\2\44\42\0\1\44\37\0\12\47"+ + "\26\0\10\44\1\0\42\44\35\0\4\44\164\0\42\44\1\0\5\44"+ + "\1\0\2\44\25\0\12\47\6\0\6\44\112\0\46\44\12\0\51\44"+ + "\7\0\132\44\5\0\104\44\5\0\122\44\6\0\7\44\1\0\77\44"+ + "\1\0\1\44\1\0\4\44\2\0\7\44\1\0\1\44\1\0\4\44"+ + "\2\0\47\44\1\0\1\44\1\0\4\44\2\0\37\44\1\0\1\44"+ + "\1\0\4\44\2\0\7\44\1\0\1\44\1\0\4\44\2\0\7\44"+ + "\1\0\7\44\1\0\27\44\1\0\37\44\1\0\1\44\1\0\4\44"+ + "\2\0\7\44\1\0\47\44\1\0\23\44\16\0\11\47\56\0\125\44"+ + "\14\0\u026c\44\2\0\10\44\12\0\32\44\5\0\113\44\25\0\15\44"+ + "\1\0\4\44\16\0\22\44\16\0\22\44\16\0\15\44\1\0\3\44"+ + "\17\0\64\44\43\0\1\44\4\0\1\44\3\0\12\47\46\0\12\47"+ + "\6\0\130\44\10\0\51\44\127\0\35\44\51\0\12\47\36\44\2\0"+ + "\5\44\u038b\0\154\44\224\0\234\44\4\0\132\44\6\0\26\44\2\0"+ + "\6\44\2\0\46\44\2\0\6\44\2\0\10\44\1\0\1\44\1\0"+ + "\1\44\1\0\1\44\1\0\37\44\2\0\65\44\1\0\7\44\1\0"+ + "\1\44\3\0\3\44\1\0\7\44\3\0\4\44\2\0\6\44\4\0"+ + "\15\44\5\0\3\44\1\0\7\44\164\0\1\44\15\0\1\44\202\0"+ + "\1\44\4\0\1\44\2\0\12\44\1\0\1\44\3\0\5\44\6\0"+ + "\1\44\1\0\1\44\1\0\1\44\1\0\4\44\1\0\3\44\1\0"+ + "\7\44\3\0\3\44\5\0\5\44\u0ebb\0\2\44\52\0\5\44\5\0"+ + "\2\44\4\0\126\44\6\0\3\44\1\0\132\44\1\0\4\44\5\0"+ + "\50\44\4\0\136\44\21\0\30\44\70\0\20\44\u0200\0\u19b6\44\112\0"+ + "\u51a6\44\132\0\u048d\44\u0773\0\u2ba4\44\u215c\0\u012e\44\2\0\73\44\225\0"+ + "\7\44\14\0\5\44\5\0\1\44\1\0\12\44\1\0\15\44\1\0"+ + "\5\44\1\0\1\44\1\0\2\44\1\0\2\44\1\0\154\44\41\0"+ + "\u016b\44\22\0\100\44\2\0\66\44\50\0\14\44\164\0\5\44\1\0"+ + "\207\44\23\0\12\47\7\0\32\44\6\0\32\44\13\0\131\44\3\0"+ + "\6\44\2\0\6\44\2\0\6\44\2\0\3\44\43\0"; /** * Translates characters to character classes @@ -122,12 +131,12 @@ class _RegExLexer implements FlexLexer { "\1\36\1\35\1\37\1\40\1\1\1\41\1\42\1\2"+ "\1\43\1\44\1\45\1\46\1\47\1\50\1\51\1\52"+ "\1\53\1\54\2\55\1\56\1\11\1\57\1\60\1\61"+ - "\1\62\1\63\1\64\1\65\1\66\2\0\1\67\1\70"+ - "\2\60\2\61\1\71\1\72\1\0\1\67\1\60\1\73"+ - "\2\61\1\74\1\67\3\61\1\75"; + "\1\62\1\63\1\0\1\64\1\65\1\66\2\0\1\67"+ + "\1\70\2\60\2\61\1\0\1\71\1\72\1\0\1\67"+ + "\1\60\1\73\2\61\1\74\1\75\1\67\3\61\1\76"; private static int [] zzUnpackAction() { - int [] result = new int[89]; + int [] result = new int[92]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; @@ -152,21 +161,21 @@ class _RegExLexer implements FlexLexer { private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = - "\0\0\0\61\0\142\0\223\0\304\0\365\0\u0126\0\u0157"+ - "\0\u0188\0\u0188\0\u01b9\0\u0188\0\u0188\0\u01ea\0\u021b\0\u0188"+ - "\0\u0188\0\u0188\0\u0188\0\u0188\0\u0188\0\u0188\0\u0188\0\u0188"+ - "\0\u0188\0\u024c\0\u0188\0\u027d\0\u0188\0\u02ae\0\u0188\0\u0188"+ - "\0\u0188\0\u0188\0\u0188\0\u02df\0\u0188\0\u0188\0\u01ea\0\u0188"+ - "\0\u0188\0\u0310\0\u0341\0\u0188\0\u0188\0\u0372\0\u0188\0\u0188"+ - "\0\u03a3\0\u03d4\0\u0188\0\u0188\0\u0188\0\u0188\0\u0188\0\u0188"+ - "\0\u0405\0\u0188\0\u0188\0\u0188\0\u0436\0\u0467\0\u0188\0\u0188"+ - "\0\u0188\0\u0188\0\u0188\0\u0498\0\u04c9\0\u04fa\0\u0188\0\u052b"+ - "\0\u055c\0\u058d\0\u05be\0\u0188\0\u0188\0\u05ef\0\u0620\0\u0188"+ - "\0\u0188\0\u0651\0\u0682\0\u0188\0\u0188\0\u06b3\0\u06e4\0\u0188"+ - "\0\u0188"; + "\0\0\0\62\0\144\0\226\0\310\0\372\0\u012c\0\u015e"+ + "\0\u0190\0\u0190\0\u01c2\0\u0190\0\u0190\0\u01f4\0\u0226\0\u0190"+ + "\0\u0190\0\u0190\0\u0190\0\u0190\0\u0190\0\u0190\0\u0190\0\u0190"+ + "\0\u0190\0\u0258\0\u0190\0\u028a\0\u0190\0\u02bc\0\u0190\0\u0190"+ + "\0\u0190\0\u0190\0\u0190\0\u02ee\0\u0190\0\u0190\0\u01f4\0\u0190"+ + "\0\u0190\0\u0320\0\u0352\0\u0190\0\u0190\0\u0384\0\u0190\0\u0190"+ + "\0\u03b6\0\u03e8\0\u0190\0\u0190\0\u0190\0\u0190\0\u0190\0\u0190"+ + "\0\u041a\0\u0190\0\u0190\0\u0190\0\u044c\0\u047e\0\u0190\0\u0190"+ + "\0\u04b0\0\u0190\0\u0190\0\u0190\0\u04e2\0\u0514\0\u0546\0\u0190"+ + "\0\u0578\0\u05aa\0\u05dc\0\u060e\0\u0640\0\u0190\0\u0190\0\u0672"+ + "\0\u06a4\0\u0190\0\u0190\0\u06d6\0\u0708\0\u0190\0\u0190\0\u0190"+ + "\0\u073a\0\u076c\0\u0190\0\u0190"; private static int [] zzUnpackRowMap() { - int [] result = new int[89]; + int [] result = new int[92]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; @@ -191,40 +200,41 @@ class _RegExLexer implements FlexLexer { private static final String ZZ_TRANS_PACKED_0 = "\3\11\1\12\1\13\1\14\1\15\1\11\1\16\1\11"+ "\1\17\1\20\1\21\1\22\1\23\1\24\1\25\1\26"+ - "\20\11\1\27\1\11\1\30\4\11\1\20\5\11\1\31"+ - "\1\20\12\11\1\32\1\0\45\11\1\33\2\34\4\33"+ - "\1\35\12\33\17\36\1\34\1\33\1\36\2\33\1\34"+ - "\1\37\11\33\11\40\1\41\1\40\1\0\45\40\6\11"+ - "\1\15\1\11\1\16\1\42\1\17\1\43\1\21\25\11"+ + "\21\11\1\27\1\11\1\30\4\11\1\20\5\11\1\31"+ + "\1\20\12\11\1\32\1\0\46\11\1\33\2\34\4\33"+ + "\1\35\12\33\20\36\1\34\1\33\1\36\2\33\1\34"+ + "\1\37\11\33\11\40\1\41\1\40\1\0\46\40\6\11"+ + "\1\15\1\11\1\16\1\42\1\17\1\43\1\21\26\11"+ "\1\27\5\11\1\44\1\43\6\11\1\43\6\45\1\46"+ - "\1\45\1\47\1\45\1\17\46\45\5\50\1\51\14\50"+ - "\17\52\1\50\1\53\1\52\6\50\1\54\6\50\13\10"+ - "\1\55\44\10\1\55\77\0\1\56\53\0\1\57\47\0"+ + "\1\45\1\47\1\45\1\17\47\45\5\50\1\51\14\50"+ + "\20\52\1\50\1\53\1\52\6\50\1\54\6\50\13\10"+ + "\1\55\45\10\1\55\100\0\1\56\54\0\1\57\50\0"+ "\1\60\1\61\1\62\4\63\1\60\1\63\1\60\1\63"+ "\1\64\6\63\2\65\2\66\2\67\1\70\1\71\1\70"+ - "\1\72\1\73\1\74\1\73\1\75\1\76\1\61\1\63"+ - "\1\73\1\64\4\60\1\64\6\60\1\64\36\0\1\77"+ - "\23\0\2\34\36\0\1\34\4\0\1\34\13\0\2\36"+ - "\17\0\20\36\1\0\1\36\1\0\2\36\62\0\1\100"+ - "\32\0\17\52\2\0\1\52\37\0\17\53\2\0\1\53"+ - "\67\0\2\101\1\102\1\103\1\104\1\105\2\0\2\61"+ - "\36\0\1\61\21\0\1\106\36\0\1\106\17\0\61\107"+ - "\1\110\2\111\20\110\2\111\2\110\3\111\2\110\1\111"+ - "\1\110\1\111\2\110\1\111\17\110\1\112\2\113\20\112"+ - "\2\113\2\112\3\113\2\112\1\113\1\112\1\113\2\112"+ - "\1\113\17\112\54\0\1\114\1\115\3\0\5\116\1\0"+ - "\53\116\2\0\1\117\36\0\1\117\17\0\62\120\2\121"+ - "\20\120\2\121\2\120\3\121\2\120\1\121\1\120\1\121"+ - "\2\120\1\121\17\120\62\122\2\123\20\122\2\123\2\122"+ - "\3\123\2\122\1\123\1\122\1\123\2\122\1\123\17\122"+ - "\5\116\1\124\53\116\2\0\1\125\36\0\1\125\17\0"+ - "\62\126\2\127\20\126\2\127\2\126\3\127\2\126\1\127"+ - "\1\126\1\127\2\126\1\127\17\126\62\130\2\131\20\130"+ - "\2\131\2\130\3\131\2\130\1\131\1\130\1\131\2\130"+ - "\1\131\17\130"; + "\2\72\1\73\1\74\1\73\1\75\1\76\1\61\1\63"+ + "\1\73\1\64\4\60\1\64\6\60\1\64\37\0\1\77"+ + "\23\0\2\34\37\0\1\34\4\0\1\34\13\0\2\36"+ + "\17\0\21\36\1\0\1\36\1\0\2\36\63\0\1\100"+ + "\32\0\20\52\2\0\1\52\37\0\20\53\2\0\1\53"+ + "\51\0\1\101\16\0\2\102\1\103\1\104\1\105\1\106"+ + "\2\0\2\61\37\0\1\61\21\0\1\107\37\0\1\107"+ + "\17\0\62\110\1\111\2\112\20\111\2\112\2\111\3\112"+ + "\3\111\1\112\1\111\1\112\2\111\1\112\17\111\1\113"+ + "\2\114\20\113\2\114\2\113\3\114\3\113\1\114\1\113"+ + "\1\114\2\113\1\114\17\113\57\0\1\115\57\0\1\116"+ + "\1\117\3\0\5\120\1\0\54\120\2\0\1\121\37\0"+ + "\1\121\17\0\63\122\2\123\20\122\2\123\2\122\3\123"+ + "\3\122\1\123\1\122\1\123\2\122\1\123\17\122\63\124"+ + "\2\125\20\124\2\125\2\124\3\125\3\124\1\125\1\124"+ + "\1\125\2\124\1\125\17\124\22\0\20\115\2\0\1\115"+ + "\7\0\1\126\5\0\5\120\1\127\54\120\2\0\1\130"+ + "\37\0\1\130\17\0\63\131\2\132\20\131\2\132\2\131"+ + "\3\132\3\131\1\132\1\131\1\132\2\131\1\132\17\131"+ + "\63\133\2\134\20\133\2\134\2\133\3\134\3\133\1\134"+ + "\1\133\1\134\2\133\1\134\17\133"; private static int [] zzUnpackTrans() { - int [] result = new int[1813]; + int [] result = new int[1950]; int offset = 0; offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; @@ -265,15 +275,15 @@ class _RegExLexer implements FlexLexer { private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = - "\6\0\2\1\2\11\1\1\2\11\1\3\1\1\12\11"+ - "\1\1\1\11\1\1\1\11\1\1\5\11\1\1\2\11"+ - "\1\3\2\11\2\1\2\11\1\1\1\15\1\11\2\1"+ - "\6\11\1\1\3\11\2\1\5\11\2\0\1\1\1\11"+ - "\4\1\2\11\1\0\1\1\2\11\2\1\2\11\2\1"+ - "\2\11"; + "\6\0\2\1\2\11\1\1\2\11\2\1\12\11\1\1"+ + "\1\11\1\1\1\11\1\1\5\11\1\1\2\11\1\1"+ + "\2\11\2\1\2\11\1\1\2\11\2\1\6\11\1\1"+ + "\3\11\2\1\2\11\1\0\3\11\2\0\1\1\1\11"+ + "\4\1\1\0\2\11\1\0\1\1\2\11\2\1\3\11"+ + "\2\1\2\11"; private static int [] zzUnpackAttribute() { - int [] result = new int[89]; + int [] result = new int[92]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; @@ -570,8 +580,6 @@ class _RegExLexer implements FlexLexer { int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; - int zzPushbackPosL = zzPushbackPos = -1; - boolean zzWasPushback; while (true) { zzMarkedPosL = zzMarkedPos; @@ -580,9 +588,8 @@ class _RegExLexer implements FlexLexer { zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; - zzState = zzLexicalState; + zzState = ZZ_LEXSTATE[zzLexicalState]; - zzWasPushback = false; zzForAction: { while (true) { @@ -597,14 +604,12 @@ class _RegExLexer implements FlexLexer { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; - zzPushbackPos = zzPushbackPosL; boolean eof = zzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; - zzPushbackPosL = zzPushbackPos; if (eof) { zzInput = YYEOF; break zzForAction; @@ -618,11 +623,7 @@ class _RegExLexer implements FlexLexer { zzState = zzNext; int zzAttributes = zzAttrL[zzState]; - if ( (zzAttributes & 2) == 2 ) - zzPushbackPosL = zzCurrentPosL; - if ( (zzAttributes & 1) == 1 ) { - zzWasPushback = (zzAttributes & 4) == 4; zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; @@ -633,246 +634,250 @@ class _RegExLexer implements FlexLexer { // store back cached position zzMarkedPos = zzMarkedPosL; - if (zzWasPushback) - zzMarkedPos = zzPushbackPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 7: { if (yystate() != CLASS2) yypushstate(EMBRACED); return RegExpTT.LBRACE; } - case 62: break; + case 63: break; case 6: { return RegExpTT.GROUP_END; } - case 63: break; + case 64: break; case 36: + // lookahead expression with fixed base length + zzMarkedPos = zzStartRead + 1; { yypushstate(CLASS1); return RegExpTT.CLASS_BEGIN; } - case 64: break; + case 65: break; case 14: { return RegExpTT.STAR; } - case 65: break; + case 66: break; case 40: { return RegExpTT.ESC_CHARACTER; } - case 66: break; + case 67: break; case 28: { return commentMode ? com.intellij.psi.TokenType.WHITE_SPACE : RegExpTT.ESC_CHARACTER; } - case 67: break; + case 68: break; case 41: { return commentMode ? RegExpTT.CHARACTER : RegExpTT.REDUNDANT_ESCAPE; } - case 68: break; + case 69: break; case 37: { return RegExpTT.REDUNDANT_ESCAPE; } - case 69: break; + case 70: break; case 24: { return RegExpTT.COMMA; } - case 70: break; + case 71: break; case 57: { return RegExpTT.POS_LOOKBEHIND; } - case 71: break; + case 72: break; case 39: { return RegExpTT.BAD_OCT_VALUE; } - case 72: break; + case 73: break; case 10: { return commentMode ? com.intellij.psi.TokenType.WHITE_SPACE : RegExpTT.CTRL_CHARACTER; } - case 73: break; + case 74: break; case 30: { yypopstate(); yypushstate(EMBRACED); return RegExpTT.LBRACE; } - case 74: break; + case 75: break; case 49: { return StringEscapesTokenTypes.INVALID_UNICODE_ESCAPE_TOKEN; } - case 75: break; + case 76: break; case 58: { return RegExpTT.NEG_LOOKBEHIND; } - case 76: break; - case 61: + case 77: break; + case 62: { return RegExpTT.UNICODE_CHAR; } - case 77: break; + case 78: break; case 56: { if (xmlSchemaMode) { yypushback(1); return RegExpTT.CHAR_CLASS; } else return RegExpTT.CTRL; } - case 78: break; + case 79: break; case 35: { yybegin(OPTIONS); return RegExpTT.SET_OPTIONS; } - case 79: break; + case 80: break; case 12: { return RegExpTT.DOLLAR; } - case 80: break; + case 81: break; case 50: { yypopstate(); return RegExpTT.QUOTE_END; } - case 81: break; + case 82: break; case 53: { return RegExpTT.POS_LOOKAHEAD; } - case 82: break; + case 83: break; case 22: { yypopstate(); return RegExpTT.RBRACE; } - case 83: break; + case 84: break; case 3: { return RegExpTT.CHARACTER; } - case 84: break; + case 85: break; case 54: { return RegExpTT.NEG_LOOKAHEAD; } - case 85: break; + case 86: break; case 42: { return RegExpTT.ESC_CTRL_CHARACTER; } - case 86: break; + case 87: break; case 23: { return RegExpTT.NAME; } - case 87: break; + case 88: break; case 51: { return RegExpTT.ANDAND; } - case 88: break; + case 89: break; case 13: { return RegExpTT.QUEST; } - case 89: break; + case 90: break; case 44: { return RegExpTT.CHAR_CLASS; } - case 90: break; + case 91: break; case 17: { return RegExpTT.MINUS; } - case 91: break; - case 60: + case 92: break; + case 61: { return RegExpTT.COMMENT; } - case 92: break; + case 93: break; case 38: { return yystate() != CLASS2 ? RegExpTT.BACKREF : RegExpTT.ESC_CHARACTER; } - case 93: break; + case 94: break; case 16: { return RegExpTT.UNION; } - case 94: break; + case 95: break; + case 60: + { return RegExpTT.PYTHON_NAMED_GROUP; + } + case 96: break; case 45: { if (xmlSchemaMode) return RegExpTT.CHAR_CLASS; else return StringEscapesTokenTypes.INVALID_CHARACTER_ESCAPE_TOKEN; } - case 95: break; + case 97: break; case 55: { return RegExpTT.OCT_CHAR; } - case 96: break; + case 98: break; case 4: { return RegExpTT.DOT; } - case 97: break; + case 99: break; case 32: { yybegin(YYINITIAL); return RegExpTT.GROUP_END; } - case 98: break; + case 100: break; case 21: { return RegExpTT.NUMBER; } - case 99: break; + case 101: break; case 46: { yypushstate(PROP); return RegExpTT.PROPERTY; } - case 100: break; + case 102: break; case 18: { return commentMode ? com.intellij.psi.TokenType.WHITE_SPACE : RegExpTT.CHARACTER; } - case 101: break; + case 103: break; case 33: { handleOptions(); return RegExpTT.OPTIONS_OFF; } - case 102: break; + case 104: break; case 34: { yybegin(YYINITIAL); return RegExpTT.COLON; } - case 103: break; + case 105: break; case 25: { assert false : yytext(); } - case 104: break; + case 106: break; case 27: { yypopstate(); return RegExpTT.CLASS_END; } - case 105: break; + case 107: break; case 11: { return RegExpTT.CARET; } - case 106: break; + case 108: break; case 1: { handleOptions(); return RegExpTT.OPTIONS_ON; } - case 107: break; + case 109: break; case 29: { yypopstate(); yypushback(1); } - case 108: break; + case 110: break; case 43: { return yystate() != CLASS2 ? RegExpTT.BOUNDARY : RegExpTT.ESC_CHARACTER; } - case 109: break; + case 111: break; case 19: { if (commentMode) { yypushstate(COMMENT); return RegExpTT.COMMENT; } else return RegExpTT.CHARACTER; } - case 110: break; + case 112: break; case 59: { return RegExpTT.HEX_CHAR; } - case 111: break; + case 113: break; case 5: { return RegExpTT.GROUP_BEGIN; } - case 112: break; + case 114: break; case 8: { yypushstate(CLASS2); return RegExpTT.CLASS_BEGIN; } - case 113: break; + case 115: break; case 52: { return RegExpTT.NON_CAPT_GROUP; } - case 114: break; + case 116: break; case 9: { return StringEscapesTokenTypes.INVALID_CHARACTER_ESCAPE_TOKEN; } - case 115: break; + case 117: break; case 48: { return RegExpTT.BAD_HEX_VALUE; } - case 116: break; + case 118: break; case 2: { yypopstate(); return RegExpTT.COMMENT; } - case 117: break; + case 119: break; case 47: { yypushstate(QUOTED); return RegExpTT.QUOTE_BEGIN; } - case 118: break; + case 120: break; case 26: { yybegin(CLASS2); return RegExpTT.CHARACTER; } - case 119: break; + case 121: break; case 15: { return RegExpTT.PLUS; } - case 120: break; + case 122: break; case 20: { if (allowDanglingMetacharacters) { yypopstate(); yypushback(1); @@ -880,11 +885,11 @@ class _RegExLexer implements FlexLexer { return RegExpTT.BAD_CHARACTER; } } - case 121: break; + case 123: break; case 31: { yybegin(YYINITIAL); return RegExpTT.BAD_CHARACTER; } - case 122: break; + case 124: break; default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; diff --git a/RegExpSupport/src/org/intellij/lang/regexp/psi/RegExpGroup.java b/RegExpSupport/src/org/intellij/lang/regexp/psi/RegExpGroup.java index 7770f6ad4376..db6e81c0eae5 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/psi/RegExpGroup.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/psi/RegExpGroup.java @@ -22,4 +22,6 @@ public interface RegExpGroup extends RegExpAtom { @Nullable RegExpPattern getPattern(); + + boolean isPythonNamedGroup(); } diff --git a/RegExpSupport/src/org/intellij/lang/regexp/psi/impl/RegExpGroupImpl.java b/RegExpSupport/src/org/intellij/lang/regexp/psi/impl/RegExpGroupImpl.java index 9b8fa67ece98..976fb2ba8fef 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/psi/impl/RegExpGroupImpl.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/psi/impl/RegExpGroupImpl.java @@ -41,4 +41,8 @@ public class RegExpGroupImpl extends RegExpElementImpl implements RegExpGroup { final ASTNode node = getNode().findChildByType(RegExpElementTypes.PATTERN); return node != null ? (RegExpPattern)node.getPsi() : null; } + + public boolean isPythonNamedGroup() { + return getNode().findChildByType(RegExpTT.PYTHON_NAMED_GROUP) != null; + } } diff --git a/RegExpSupport/src/org/intellij/lang/regexp/regexp-lexer.flex b/RegExpSupport/src/org/intellij/lang/regexp/regexp-lexer.flex index 621fc89cf6e6..2b0455a747eb 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/regexp-lexer.flex +++ b/RegExpSupport/src/org/intellij/lang/regexp/regexp-lexer.flex @@ -205,6 +205,7 @@ HEX_CHAR=[0-9a-fA-F] "(?<=" { return RegExpTT.POS_LOOKBEHIND; } "(?" { return RegExpTT.PYTHON_NAMED_GROUP; } "(?" { yybegin(OPTIONS); return RegExpTT.SET_OPTIONS; } } diff --git a/RegExpSupport/src/org/intellij/lang/regexp/validation/RegExpAnnotator.java b/RegExpSupport/src/org/intellij/lang/regexp/validation/RegExpAnnotator.java index 52307d1cd58d..21e50a871722 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/validation/RegExpAnnotator.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/validation/RegExpAnnotator.java @@ -30,12 +30,13 @@ import org.intellij.lang.regexp.RegExpLanguageHost; import org.intellij.lang.regexp.RegExpTT; import org.intellij.lang.regexp.psi.*; import org.intellij.lang.regexp.psi.impl.RegExpPropertyImpl; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class RegExpAnnotator extends RegExpElementVisitor implements Annotator { private AnnotationHolder myHolder; - public void annotate(PsiElement psiElement, AnnotationHolder holder) { + public void annotate(@NotNull PsiElement psiElement, @NotNull AnnotationHolder holder) { assert myHolder == null : "unsupported concurrent annotator invocation"; try { myHolder = holder; @@ -159,6 +160,12 @@ public final class RegExpAnnotator extends RegExpElementVisitor implements Annot } } } + if (group.isPythonNamedGroup()) { + RegExpLanguageHost host = findRegExpHost(group); + if (host == null || !host.supportsPythonNamedGroups()) { + myHolder.createErrorAnnotation(group, "This named group syntax is not supported"); + } + } } @Override diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberInfoExternalizer.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberInfoExternalizer.java index ffaa5d227fcd..a807bd59f126 100644 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberInfoExternalizer.java +++ b/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberInfoExternalizer.java @@ -57,7 +57,7 @@ public class MemberInfoExternalizer { else if (tag == FIELD_INFO_TAG) { return new FieldInfo(in); } - LOG.assertTrue(false, "Unknown member info"); + LOG.error("Unknown member info"); return null; } @@ -69,7 +69,7 @@ public class MemberInfoExternalizer { else if (tag == MEMBER_REFERENCE_INFO_TAG) { return new MemberReferenceInfo(in); } - LOG.assertTrue(false, "Unknown declaration info tag: " + tag); + LOG.error("Unknown declaration info tag: " + tag); return null; } @@ -108,7 +108,7 @@ public class MemberInfoExternalizer { else if (tag == ENUM_CONSTANT_VALUE_TAG) { return new EnumConstantValue(in); } - LOG.assertTrue(false, "Unknown constant value type " + tag); + LOG.error("Unknown constant value type " + tag); return null; } @@ -120,7 +120,7 @@ public class MemberInfoExternalizer { out.writeByte(FIELD_INFO_TAG); } else { - LOG.assertTrue(false, "Unknown member info"); + LOG.error("Unknown member info"); } info.save(out); } diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/MethodInfo.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/MethodInfo.java index 1aa0cda20e28..c18d9ae801d7 100644 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/MethodInfo.java +++ b/java/compiler/impl/src/com/intellij/compiler/classParsing/MethodInfo.java @@ -161,7 +161,7 @@ public class MethodInfo extends MemberInfo { String descriptor = symbolTable.getSymbol(getDescriptor()); int endIndex = descriptor.indexOf(')'); if (endIndex <= 0) { - LOG.assertTrue(false, "Corrupted method descriptor: "+descriptor); + LOG.error("Corrupted method descriptor: " + descriptor); } myParameterDescriptors = parseParameterDescriptors(descriptor.substring(1, endIndex)); } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/OneProjectItemCompileScope.java b/java/compiler/impl/src/com/intellij/compiler/impl/OneProjectItemCompileScope.java index c815ecde5e45..d85b28af44e8 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/OneProjectItemCompileScope.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/OneProjectItemCompileScope.java @@ -71,7 +71,7 @@ public class OneProjectItemCompileScope extends UserDataHolderBase implements Co public Module[] getAffectedModules() { final Module module = ModuleUtil.findModuleForFile(myFile, myProject); if (module == null) { - LOG.assertTrue(false, "Module is null for file " + myFile.getPresentableUrl()); + LOG.error("Module is null for file " + myFile.getPresentableUrl()); return Module.EMPTY_ARRAY; } return new Module[] {module}; diff --git a/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java b/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java index 1514175abc88..e2ce0fa640d7 100644 --- a/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java +++ b/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java @@ -47,7 +47,7 @@ public class CacheUtils { String descriptor = symbolTable.getSymbol(methodDeclarationId.getDescriptor()); int endIndex = descriptor.indexOf(')'); if (endIndex <= 0) { - LOG.assertTrue(false, "Corrupted method descriptor: "+descriptor); + LOG.error("Corrupted method descriptor: " + descriptor); } return parseSignature(descriptor.substring(1, endIndex)); } diff --git a/java/compiler/impl/src/com/intellij/compiler/make/Dependency.java b/java/compiler/impl/src/com/intellij/compiler/make/Dependency.java index 3eb5aed1eeb0..cf50003bc0e4 100644 --- a/java/compiler/impl/src/com/intellij/compiler/make/Dependency.java +++ b/java/compiler/impl/src/com/intellij/compiler/make/Dependency.java @@ -97,7 +97,7 @@ public class Dependency { String descriptorStr = symbolTable.getSymbol(descriptor); int endIndex = descriptorStr.indexOf(')'); if (endIndex <= 0) { - LOG.assertTrue(false, "Corrupted method descriptor: "+ descriptorStr); + LOG.error("Corrupted method descriptor: " + descriptorStr); } myParameterDescriptors = parseParameterDescriptors(descriptorStr.substring(1, endIndex)); } diff --git a/java/compiler/impl/src/com/intellij/compiler/make/DependencyCacheNavigator.java b/java/compiler/impl/src/com/intellij/compiler/make/DependencyCacheNavigator.java index 29c595abf304..a93caa2aeb54 100644 --- a/java/compiler/impl/src/com/intellij/compiler/make/DependencyCacheNavigator.java +++ b/java/compiler/impl/src/com/intellij/compiler/make/DependencyCacheNavigator.java @@ -39,7 +39,7 @@ public class DependencyCacheNavigator { int superQName = myCache.getSuperQualifiedName(classQName); if (classQName == superQName) { - LOG.assertTrue(false, "Superclass qualified name is the same as class' name: " + classQName); + LOG.error("Superclass qualified name is the same as class' name: " + classQName); return; } @@ -70,7 +70,7 @@ public class DependencyCacheNavigator { public void walkSubClasses(int fromClassQName, ClassInfoProcessor processor) throws CacheCorruptedException { for (int subQName : myCache.getSubclasses(fromClassQName)) { if (fromClassQName == subQName) { - LOG.assertTrue(false, "Subclass qualified name is the same as class' name: " + fromClassQName); + LOG.error("Subclass qualified name is the same as class' name: " + fromClassQName); return; } if (subQName != Cache.UNKNOWN) { diff --git a/java/compiler/impl/src/com/intellij/compiler/CompilerSettingsFactory.java b/java/compiler/openapi/src/com/intellij/compiler/CompilerSettingsFactory.java similarity index 100% rename from java/compiler/impl/src/com/intellij/compiler/CompilerSettingsFactory.java rename to java/compiler/openapi/src/com/intellij/compiler/CompilerSettingsFactory.java diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java index c05df216afbf..e9cd41bdbc0f 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java @@ -245,7 +245,7 @@ public abstract class DebugProcessImpl implements DebugProcess { @SuppressWarnings({"HardCodedStringLiteral"}) protected void commitVM(VirtualMachine vm) { if (!isInInitialState()) { - LOG.assertTrue(false, "State is invalid " + myState.get()); + LOG.error("State is invalid " + myState.get()); } DebuggerManagerThreadImpl.assertIsManagerThread(); myPositionManager = createPositionManager(); diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/JVMNameUtil.java b/java/debugger/impl/src/com/intellij/debugger/engine/JVMNameUtil.java index f5e40da93aea..6faffeba0813 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/JVMNameUtil.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/JVMNameUtil.java @@ -95,7 +95,7 @@ public class JVMNameUtil { buffer.append(getPrimitiveSignature(psiType.getCanonicalText())); } else { - LOG.assertTrue(false, "unknown type " + type.getCanonicalText()); + LOG.error("unknown type " + type.getCanonicalText()); } } diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java index 8b8813ebe377..1c0134e06326 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java @@ -215,12 +215,12 @@ public class PositionManagerImpl implements PositionManager { if(PsiUtil.isLocalOrAnonymousClass(psiClass)) { final PsiClass parentNonLocal = JVMNameUtil.getTopLevelParentClass(psiClass); if(parentNonLocal == null) { - LOG.assertTrue(false, "Local or anonymous class has no non-local parent"); + LOG.error("Local or anonymous class has no non-local parent"); return Collections.emptyList(); } final String parentClassName = JVMNameUtil.getNonAnonymousClassName(parentNonLocal); if(parentClassName == null) { - LOG.assertTrue(false, "The name of a parent of a local (anonymous) class is null"); + LOG.error("The name of a parent of a local (anonymous) class is null"); return Collections.emptyList(); } final List outers = myDebugProcess.getVirtualMachineProxy().classesByName(parentClassName); diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java index aa5128b9bbab..2d7baf56ee96 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java @@ -102,7 +102,7 @@ public abstract class SuspendContextImpl implements SuspendContext { private void assertNotResumed() { if (myIsResumed) { if (myDebugProcess.isAttached()) { - LOG.assertTrue(false, "Cannot access SuspendContext. SuspendContext is resumed."); + LOG.error("Cannot access SuspendContext. SuspendContext is resumed."); } } } diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerImpl.java index 6acf537430c9..6d5c2b3ae382 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerImpl.java @@ -120,7 +120,7 @@ public class SuspendManagerImpl implements SuspendManager { if (thread != null) { // check that thread is suspended at the moment try { if (!thread.isSuspended()) { - LOG.assertTrue(false, "Context thread must be suspended"); + LOG.error("Context thread must be suspended"); } } catch (ObjectCollectedException ignored) {} diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/CodeFragmentEvaluator.java b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/CodeFragmentEvaluator.java index 5fb1e8b2823a..6572d44e2570 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/CodeFragmentEvaluator.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/CodeFragmentEvaluator.java @@ -86,7 +86,7 @@ public class CodeFragmentEvaluator extends BlockStatementEvaluator{ return vm.mirrorOf((String)value); } else { - LOG.assertTrue(false, "unknown default initializer type " + value.getClass().getName()); + LOG.error("unknown default initializer type " + value.getClass().getName()); return null; } } diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java index 3b7cec8c4d87..ae6252e4407f 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java @@ -1026,13 +1026,13 @@ public class EvaluatorBuilderImpl implements EvaluatorBuilder { final PsiType castType = expression.getCastType().getType(); final PsiType operandType = operandExpr.getType(); - if (!TypeConversionUtil.areTypesConvertible(operandType, castType)) { + if (castType != null && operandType != null && !TypeConversionUtil.areTypesConvertible(operandType, castType)) { throw new EvaluateRuntimeException( new EvaluateException(JavaErrorMessages.message("inconvertible.type.cast", HighlightUtil.formatType(operandType), HighlightUtil.formatType(castType))) ); } - final boolean shouldPerformBoxingConversion = TypeConversionUtil.boxingConversionApplicable(castType, operandType); + final boolean shouldPerformBoxingConversion = castType != null && operandType != null && TypeConversionUtil.boxingConversionApplicable(castType, operandType); final boolean castingToPrimitive = castType instanceof PsiPrimitiveType; if (shouldPerformBoxingConversion && castingToPrimitive) { operandEvaluator = new UnBoxingEvaluator(operandEvaluator); diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/requests/MethodReturnValueWatcher.java b/java/debugger/impl/src/com/intellij/debugger/engine/requests/MethodReturnValueWatcher.java index 561ab0c2a240..16fc43ce1639 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/requests/MethodReturnValueWatcher.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/requests/MethodReturnValueWatcher.java @@ -17,6 +17,7 @@ package com.intellij.debugger.engine.requests; import com.intellij.debugger.settings.DebuggerSettings; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.util.ArrayUtil; import com.sun.jdi.Method; import com.sun.jdi.ObjectCollectedException; import com.sun.jdi.Value; @@ -56,7 +57,7 @@ public class MethodReturnValueWatcher { try { if (myReturnValueMethod == null) { //noinspection HardCodedStringLiteral - myReturnValueMethod = MethodExitEvent.class.getDeclaredMethod("returnValue", new Class[0]); + myReturnValueMethod = MethodExitEvent.class.getDeclaredMethod("returnValue", ArrayUtil.EMPTY_CLASS_ARRAY); } myLastMethodReturnValue = (Value)myReturnValueMethod.invoke(event); } diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java b/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java index b041959ed403..6848a3f3450b 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java @@ -129,7 +129,7 @@ public abstract class InvokeThread { } if(getCurrentRequest() != current) { - LOG.assertTrue(false, "Expected " + current + " instead of " + getCurrentRequest()); + LOG.error("Expected " + current + " instead of " + getCurrentRequest()); } processEvent(myEvents.get()); diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java index 9de989d1eeb6..afa09b72b124 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java @@ -18,6 +18,7 @@ import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.DebuggerManagerEx; import com.intellij.openapi.project.Project; import com.intellij.ui.*; +import com.intellij.util.ArrayUtil; import com.intellij.util.Icons; import com.intellij.util.containers.Convertor; import com.intellij.util.ui.tree.TreeUtil; @@ -42,7 +43,7 @@ public class BreakpointTree extends CheckboxTree { private boolean myGroupByClasses = true; private boolean myFlattenPackages = true; - private final NodeAppender[] myAppenders = new NodeAppender[] { + private final NodeAppender[] myAppenders = { new BreakpointToMethodAppender(), new BreakpointToClassAppender(), new BreakpointToPackageAppender(), @@ -186,12 +187,13 @@ public class BreakpointTree extends CheckboxTree { public BreakpointDescriptor(Breakpoint breakpoint) { myBreakpoint = breakpoint; } - public @NotNull Breakpoint getBreakpoint() { + @NotNull + public Breakpoint getBreakpoint() { return myBreakpoint; } protected Icon getDisplayIcon() { - return (myBreakpoint instanceof BreakpointWithHighlighter)? + return myBreakpoint instanceof BreakpointWithHighlighter ? myBreakpoint.ENABLED? ((BreakpointWithHighlighter)myBreakpoint).getSetIcon() : ((BreakpointWithHighlighter)myBreakpoint).getDisabledIcon() : myBreakpoint.getIcon(); } @@ -224,7 +226,7 @@ public class BreakpointTree extends CheckboxTree { private static final class MethodDescriptor extends TreeDescriptor { private final String myClassName; private final String myMethodName; - private final @NotNull String myPackageName; + @NotNull private final String myPackageName; public MethodDescriptor(String methodName, String className, @NotNull String packageName) { myClassName = className; @@ -232,7 +234,8 @@ public class BreakpointTree extends CheckboxTree { myPackageName = packageName; } - public @NotNull String getPackageName() { + @NotNull + public String getPackageName() { return myPackageName; } @@ -267,26 +270,27 @@ public class BreakpointTree extends CheckboxTree { } public int hashCode() { - int result; - result = myClassName.hashCode(); + int result = myClassName.hashCode(); result = 29 * result + myMethodName.hashCode(); return result; } } private static final class ClassDescriptor extends TreeDescriptor { - private final @NotNull String myClassName; - private final @NotNull String myPackageName; + @NotNull private final String myClassName; + @NotNull private final String myPackageName; public ClassDescriptor(@NotNull String className, @NotNull String packageName) { myClassName = className; myPackageName = packageName.length() == 0? DEFAULT_PACKAGE_NAME : packageName; } + @NotNull public String getPackageName() { return myPackageName; } + @NotNull public String getClassName() { return myClassName; } @@ -383,7 +387,7 @@ public class BreakpointTree extends CheckboxTree { myBreakpointManager = DebuggerManagerEx.getInstanceEx(project).getBreakpointManager(); myNodeUpdateListener = new BreakpointManagerListener() { public void breakpointsChanged() { - BreakpointTree.this.repaint(); + repaint(); } }; myBreakpointManager.addBreakpointManagerListener(myNodeUpdateListener); @@ -554,7 +558,8 @@ public class BreakpointTree extends CheckboxTree { } } - private @NotNull CheckedTreeNode createNode(final TreeDescriptor descriptor) { + @NotNull + private CheckedTreeNode createNode(final TreeDescriptor descriptor) { final CheckedTreeNode node = new CheckedTreeNode(descriptor); myDescriptorToNodeMap.put(descriptor, node); return node; @@ -615,7 +620,7 @@ public class BreakpointTree extends CheckboxTree { } } - private static abstract class NodeAppender { + private abstract static class NodeAppender { public abstract CheckedTreeNode append(CheckedTreeNode node); } @@ -676,10 +681,10 @@ public class BreakpointTree extends CheckboxTree { final Breakpoint breakpoint = ((BreakpointDescriptor)descriptor).getBreakpoint(); final String packageName; if (breakpoint instanceof ExceptionBreakpoint) { - packageName = ((ExceptionBreakpoint)breakpoint).getPackageName(); + packageName = breakpoint.getPackageName(); } else if (breakpoint instanceof BreakpointWithHighlighter) { - packageName = ((BreakpointWithHighlighter)breakpoint).getPackageName(); + packageName = breakpoint.getPackageName(); } else { packageName = null; @@ -768,7 +773,6 @@ public class BreakpointTree extends CheckboxTree { private static class TreeStateSnapshot { private final Object[] myExpandedUserObjects; private final Object[] mySelectedUserObjects; - private static final Object[][] EMPTY = new Object[0][]; public TreeStateSnapshot(BreakpointTree tree) { final List expandedPaths = TreeUtil.collectExpandedPaths(tree); @@ -776,9 +780,9 @@ public class BreakpointTree extends CheckboxTree { mySelectedUserObjects =getUserObjects(tree.getSelectionPaths()); } - private Object[] getUserObjects(final TreePath[] treePaths) { + private static Object[] getUserObjects(final TreePath[] treePaths) { if (treePaths == null) { - return EMPTY; + return ArrayUtil.EMPTY_OBJECT_ARRAY; } Object[] userObjects = new Object[treePaths.length]; int index = 0; @@ -790,18 +794,18 @@ public class BreakpointTree extends CheckboxTree { public void restore(BreakpointTree tree) { final List pathsToExpand = getPaths(tree, myExpandedUserObjects); - if (pathsToExpand.size() > 0) { + if (!pathsToExpand.isEmpty()) { TreeUtil.restoreExpandedPaths(tree, pathsToExpand); } final List pathsToSelect = getPaths(tree, mySelectedUserObjects); - if (pathsToSelect.size() > 0) { + if (!pathsToSelect.isEmpty()) { tree.getSelectionModel().clearSelection(); tree.setSelectionPaths(pathsToSelect.toArray(new TreePath[pathsToSelect.size()])); } } - private List getPaths(BreakpointTree tree, final Object[] userObjects) { + private static List getPaths(BreakpointTree tree, final Object[] userObjects) { final List paths = new ArrayList(userObjects.length); for (Object descriptor : userObjects) { final CheckedTreeNode node = tree.myDescriptorToNodeMap.get(descriptor); diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeExpression.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeExpression.java index bb89a974ac0e..f744512122e8 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeExpression.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeExpression.java @@ -266,7 +266,7 @@ public class DebuggerTreeNodeExpression { return ((ValueDescriptorImpl)node.getDescriptor()).getTreeEvaluation(node, context); } else { - LOG.assertTrue(false, node.getDescriptor() != null ? node.getDescriptor().getClass().getName() : "null"); + LOG.error(node.getDescriptor() != null ? node.getDescriptor().getClass().getName() : "null"); return null; } } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/NodeDescriptorFactoryImpl.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/NodeDescriptorFactoryImpl.java index 575f1260d37e..9596b397b222 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/NodeDescriptorFactoryImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/NodeDescriptorFactoryImpl.java @@ -138,7 +138,7 @@ public class NodeDescriptorFactoryImpl implements NodeDescriptorFactory { final DescriptorData descriptorData; if (objRef == null ) { if (!field.isStatic()) { - LOG.assertTrue(false, "Object reference is null for non-static field: " + field); + LOG.error("Object reference is null for non-static field: " + field); } descriptorData = new StaticFieldData(field); } diff --git a/java/execution/impl/src/com/intellij/compiler/options/CompileStepBeforeRun.java b/java/execution/impl/src/com/intellij/compiler/options/CompileStepBeforeRun.java index d165861a020c..88c56e8ca770 100644 --- a/java/execution/impl/src/com/intellij/compiler/options/CompileStepBeforeRun.java +++ b/java/execution/impl/src/com/intellij/compiler/options/CompileStepBeforeRun.java @@ -102,10 +102,8 @@ public class CompileStepBeforeRun extends BeforeRunTaskProvider 0) { for (Module module : modules) { if (module == null) { - LOG.assertTrue( - false, - "RunConfiguration should not return null modules. Configuration=" + runConfiguration.getName() + "; class=" + runConfiguration.getClass().getName() - ); + LOG.error("RunConfiguration should not return null modules. Configuration=" + runConfiguration.getName() + "; class=" + + runConfiguration.getClass().getName()); } } scope = compilerManager.createModulesCompileScope(modules, true); diff --git a/java/execution/impl/src/com/intellij/execution/junit2/SegmentedInputStream.java b/java/execution/impl/src/com/intellij/execution/junit2/SegmentedInputStream.java index d15336716a52..4ebdbebc72ce 100644 --- a/java/execution/impl/src/com/intellij/execution/junit2/SegmentedInputStream.java +++ b/java/execution/impl/src/com/intellij/execution/junit2/SegmentedInputStream.java @@ -19,6 +19,7 @@ import com.intellij.rt.execution.junit.segments.Packet; import com.intellij.rt.execution.junit.segments.PacketProcessor; import com.intellij.rt.execution.junit.segments.SegmentedStream; import com.intellij.util.StringBuilderSpinAllocator; +import com.intellij.util.containers.HashMap; import java.io.BufferedReader; import java.io.IOException; @@ -108,7 +109,9 @@ public class SegmentedInputStream extends InputStream { } public int available() throws IOException { - + + final HashMap map = new HashMap(); + map.keySet(); while (mySourceStream.ready()) { while(myStartupPassed < SegmentedStream.STARTUP_MESSAGE.length()) { @@ -131,8 +134,8 @@ public class SegmentedInputStream extends InputStream { final Integer packetRead = readControlSequence(); if (packetRead != null) { // push back quoted slash - mySourceStream.pushBack(b); mySourceStream.pushBack(packetRead); + mySourceStream.pushBack(b); return 1; } } diff --git a/java/execution/impl/src/com/intellij/execution/junit2/configuration/CommonJavaParameters.java b/java/execution/impl/src/com/intellij/execution/junit2/configuration/CommonJavaParameters.java index 8d411dbd9bd9..f32438d59ee4 100644 --- a/java/execution/impl/src/com/intellij/execution/junit2/configuration/CommonJavaParameters.java +++ b/java/execution/impl/src/com/intellij/execution/junit2/configuration/CommonJavaParameters.java @@ -32,6 +32,7 @@ import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.RawCommandLineEditor; +import com.intellij.util.ArrayUtil; import javax.swing.*; import java.awt.*; @@ -152,7 +153,7 @@ public class CommonJavaParameters extends JPanel { final List macros = new ArrayList(PathMacros.getInstance().getUserMacroNames()); macros.add("MODULE_DIR"); - final JList list = new JList(macros.toArray(new String[macros.size()])); + final JList list = new JList(ArrayUtil.toStringArray(macros)); final JBPopup popup = JBPopupFactory.getInstance().createListPopupBuilder(list).setItemChoosenCallback(new Runnable() { public void run() { final Object value = list.getSelectedValue(); diff --git a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/versions/LibrariesConfigurationManager.java b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/versions/LibrariesConfigurationManager.java index 633c4201b7d2..babd5cfb94ab 100644 --- a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/versions/LibrariesConfigurationManager.java +++ b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/versions/LibrariesConfigurationManager.java @@ -112,7 +112,7 @@ public class LibrariesConfigurationManager implements Disposable { } private static String[] getSplitted(@Nullable final String s) { - if (StringUtil.isEmptyOrSpaces(s)) return new String[0]; + if (StringUtil.isEmptyOrSpaces(s)) return ArrayUtil.EMPTY_STRING_ARRAY; return ArrayUtil.toStringArray(StringUtil.split(s, STRING_DELIMITER)); } diff --git a/java/idea-ui/src/com/intellij/ide/actions/OpenProjectAction.java b/java/idea-ui/src/com/intellij/ide/actions/OpenProjectAction.java index 27c8ef04662d..3058583092d1 100644 --- a/java/idea-ui/src/com/intellij/ide/actions/OpenProjectAction.java +++ b/java/idea-ui/src/com/intellij/ide/actions/OpenProjectAction.java @@ -24,6 +24,7 @@ import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; +import com.intellij.openapi.fileChooser.ex.FileChooserDialogImpl; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.SystemInfo; @@ -63,6 +64,7 @@ public class OpenProjectAction extends AnAction implements DumbAware { } } + descriptor.putUserData(FileChooserDialogImpl.PREFER_LAST_OVER_TO_SELECT, Boolean.TRUE); final VirtualFile[] files = FileChooser.chooseFiles(project, descriptor, userHomeDir); if (files.length == 0 || files[0] == null) return; diff --git a/java/idea-ui/src/com/intellij/ide/impl/NewProjectUtil.java b/java/idea-ui/src/com/intellij/ide/impl/NewProjectUtil.java index 5888e31fc19f..da9e84693775 100644 --- a/java/idea-ui/src/com/intellij/ide/impl/NewProjectUtil.java +++ b/java/idea-ui/src/com/intellij/ide/impl/NewProjectUtil.java @@ -34,7 +34,6 @@ import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.CompilerProjectExtension; import com.intellij.openapi.roots.LanguageLevelProjectExtension; -import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.roots.ex.ProjectRootManagerEx; import com.intellij.openapi.roots.ui.configuration.ModulesConfigurator; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; @@ -132,11 +131,13 @@ public class NewProjectUtil { // ensure the dialog is shown after all startup activities are done SwingUtilities.invokeLater(new Runnable() { public void run() { + if (newProject.isDisposed()) return; if (need2OpenProjectStructure) { ModulesConfigurator.showDialog(newProject, null, null, true); } ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { + if (newProject.isDisposed()) return; final ToolWindow toolWindow = ToolWindowManager.getInstance(newProject).getToolWindow(ToolWindowId.PROJECT_VIEW); if (toolWindow != null) { toolWindow.activate(null); diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ClasspathPanel.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ClasspathPanel.java index 3e57d38f4728..9d04aa700dbd 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ClasspathPanel.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ClasspathPanel.java @@ -18,8 +18,6 @@ package com.intellij.openapi.roots.ui.configuration; import com.intellij.ide.DataManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.module.Module; @@ -530,7 +528,7 @@ public class ClasspathPanel extends JPanel { } } } - LOG.assertTrue(false, "Unknown library " + item); + LOG.error("Unknown library " + item); return null; } @@ -549,7 +547,7 @@ public class ClasspathPanel extends JPanel { } } } - LOG.assertTrue(false, "Unknown library " + item); + LOG.error("Unknown library " + item); return null; } @@ -886,7 +884,7 @@ public class ClasspathPanel extends JPanel { if (columnIndex == ITEM_COLUMN) { return item; } - LOG.assertTrue(false, "Incorrect column index: " + columnIndex); + LOG.error("Incorrect column index: " + columnIndex); return null; } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/LibraryChooserElement.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/LibraryChooserElement.java index 54386314ffa9..99c2c8efebd6 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/LibraryChooserElement.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/LibraryChooserElement.java @@ -56,7 +56,7 @@ public class LibraryChooserElement { myLibrary = library; myOrderEntry = orderEntry; if (myLibrary == null && myOrderEntry == null) { - LOG.assertTrue(false, "Both library and order entry are null"); + LOG.error("Both library and order entry are null"); myName = ProjectBundle.message("module.libraries.unknown.item"); } else { diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTreeComponent.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTreeComponent.java index 3b7c3a3ad4d9..db8f14791cb1 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTreeComponent.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTreeComponent.java @@ -44,6 +44,7 @@ import com.intellij.ui.treeStructure.SimpleNode; import com.intellij.ui.treeStructure.SimpleTreeBuilder; import com.intellij.ui.treeStructure.SimpleTreeStructure; import com.intellij.ui.treeStructure.WeightBasedComparator; +import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NonNls; @@ -288,7 +289,7 @@ public class LayoutTreeComponent implements DnDTarget, Disposable { myBuilder.addSubtreeToUpdate(treeNode, new Runnable() { public void run() { List> nodes = myTree.findNodes(toSelect); - myBuilder.select(nodes.toArray(new Object[nodes.size()]), null); + myBuilder.select(ArrayUtil.toObjectArray(nodes), null); } }); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/nodes/PackagingElementNode.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/nodes/PackagingElementNode.java index 349016a15a2e..7e1e8e653623 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/nodes/PackagingElementNode.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/nodes/PackagingElementNode.java @@ -27,6 +27,7 @@ import com.intellij.packaging.elements.PackagingElement; import com.intellij.packaging.ui.ArtifactEditorContext; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.treeStructure.SimpleNode; +import com.intellij.util.ArrayUtil; import com.intellij.util.SmartList; import com.intellij.util.StringBuilderSpinAllocator; import org.jetbrains.annotations.NotNull; @@ -81,7 +82,7 @@ public class PackagingElementNode> extends Artifac @Override public Object[] getEqualityObjects() { - return myPackagingElements.toArray(new Object[myPackagingElements.size()]); + return ArrayUtil.toObjectArray(myPackagingElements); } @Override diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java index 6c6c209a4d78..d6d33237a64a 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java @@ -222,12 +222,11 @@ public class JavaCompletionContributor extends CompletionContributor { final Object[] variants = reference.getVariants(); if (variants == null) { - LOG.assertTrue(false, "Reference=" + reference); + LOG.error("Reference=" + reference); } for (Object completion : variants) { if (completion == null) { - LOG.assertTrue(false, "Position=" + insertedElement + "\n;Reference=" + reference + "\n;variants=" + Arrays.toString( - variants)); + LOG.error("Position=" + insertedElement + "\n;Reference=" + reference + "\n;variants=" + Arrays.toString(variants)); } if (completion instanceof LookupElement) { result.addElement((LookupElement)completion); diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/CopyPasteReferenceProcessor.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/CopyPasteReferenceProcessor.java index dabe31bccb74..3f70ed37a9e4 100644 --- a/java/java-impl/src/com/intellij/codeInsight/editorActions/CopyPasteReferenceProcessor.java +++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/CopyPasteReferenceProcessor.java @@ -26,6 +26,7 @@ import com.intellij.openapi.project.DumbService; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.*; +import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.Nullable; @@ -238,7 +239,7 @@ public class CopyPasteReferenceProcessor implements CopyPastePostProcessor { } if (array.isEmpty()) return; - Object[] selectedObjects = array.toArray(new Object[array.size()]); + Object[] selectedObjects = ArrayUtil.toObjectArray(array); Arrays.sort( selectedObjects, new Comparator() { diff --git a/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java b/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java index bdea5103dccd..a2455da108b2 100644 --- a/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java +++ b/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java @@ -516,15 +516,8 @@ public class JavaFoldingBuilder extends FoldingBuilderEx implements DumbAware { final String baseClassName = quick ? anonymousClass.getBaseClassReference().getReferenceName() : anonymousClass.getBaseClassType().resolve().getName(); if (lastLineEnd >= seq.length() || firstLineStart >= seq.length() || firstLineStart < 0) { - LOG.assertTrue(false, "llE=" + - lastLineEnd + - "; fLS=" + - firstLineStart + - "; len=" + - seq.length() + - "rE=" + - rangeEnd + - "; class=" + baseClassName); + LOG.error("llE=" + lastLineEnd + "; fLS=" + firstLineStart + "; len=" + seq.length() + "rE=" + rangeEnd + "; class=" + + baseClassName); } final String params = StringUtil.join(method.getParameterList().getParameters(), new Function() { diff --git a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java index 19aa7cc0fd60..c7211eb840e5 100644 --- a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java @@ -117,7 +117,7 @@ public class HighlightSuppressedWarningsHandler extends HighlightUsagesHandlerBa final GlobalInspectionContextImpl context = managerEx.createNewGlobalContext(false); tool.initialize(context); ((RefManagerImpl)context.getRefManager()).inspectionReadActionStarted(); - pass.doInspectInBatch(managerEx, new InspectionProfileEntry[]{tool}, false); + pass.doInspectInBatch(managerEx, Collections.singletonList(tool), false); for (HighlightInfo info : pass.getInfos()) { final PsiElement element = CollectHighlightsUtil.findCommonParent(myFile, info.startOffset, info.endOffset); if (element != null) { diff --git a/java/java-impl/src/com/intellij/codeInsight/hint/JavaImplementationTextSelectioner.java b/java/java-impl/src/com/intellij/codeInsight/hint/JavaImplementationTextSelectioner.java index 8e5800d295c6..8028a96d4a08 100644 --- a/java/java-impl/src/com/intellij/codeInsight/hint/JavaImplementationTextSelectioner.java +++ b/java/java-impl/src/com/intellij/codeInsight/hint/JavaImplementationTextSelectioner.java @@ -46,7 +46,7 @@ public class JavaImplementationTextSelectioner implements ImplementationTextSele return element.getTextRange().getStartOffset(); } else { - LOG.assertTrue(false, "Element should not be null: " + parent.getText()); + LOG.error("Element should not be null: " + parent.getText()); return parent.getTextRange().getStartOffset(); } } diff --git a/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java b/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java index 7615b0fac4d8..7d58c2f12c12 100644 --- a/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java +++ b/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java @@ -236,9 +236,9 @@ public class JavaDocInfoGenerator { if (file instanceof PsiJavaFile) { String packageName = ((PsiJavaFile)file).getPackageName(); if (packageName.length() > 0) { - buffer.append(""); + buffer.append(""); buffer.append(packageName); - buffer.append(""); + buffer.append(""); //buffer.append("
"); } } @@ -359,8 +359,19 @@ public class JavaDocInfoGenerator { return null; } + @Nullable private static PsiDocComment getDocComment(final PsiDocCommentOwner docOwner) { - return ((PsiDocCommentOwner)docOwner.getNavigationElement()).getDocComment(); + PsiDocComment comment = ((PsiDocCommentOwner)docOwner.getNavigationElement()).getDocComment(); + if (comment == null) { //check for non-normalized fields + final PsiModifierList modifierList = docOwner.getModifierList(); + if (modifierList != null) { + final PsiElement parent = modifierList.getParent(); + if (parent instanceof PsiDocCommentOwner) { + return ((PsiDocCommentOwner)parent.getNavigationElement()).getDocComment(); + } + } + } + return comment; } private void generateFieldJavaDoc(@NonNls StringBuilder buffer, PsiField field) { @@ -370,10 +381,10 @@ public class JavaDocInfoGenerator { if (parentClass != null) { String qName = parentClass.getQualifiedName(); if (qName != null) { - buffer.append(""); + buffer.append(""); //buffer.append(qName); generateLink(buffer, qName, qName, field, false); - buffer.append(""); + buffer.append(""); //buffer.append("
"); } } @@ -550,7 +561,7 @@ public class JavaDocInfoGenerator { } buffer.append(")"); } - buffer.append("\n"); + buffer.append(" "); } } } @@ -599,10 +610,10 @@ public class JavaDocInfoGenerator { if (parentClass != null) { String qName = parentClass.getQualifiedName(); if (qName != null) { - buffer.append(""); + buffer.append(""); generateLink(buffer, qName, qName, method, false); //buffer.append(qName); - buffer.append(""); + buffer.append(""); //buffer.append("
"); } } diff --git a/java/java-impl/src/com/intellij/codeInsight/lookup/LookupItemUtil.java b/java/java-impl/src/com/intellij/codeInsight/lookup/LookupItemUtil.java index 4e53c23a2c6d..aca3dff1c9d9 100644 --- a/java/java-impl/src/com/intellij/codeInsight/lookup/LookupItemUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/lookup/LookupItemUtil.java @@ -137,7 +137,7 @@ public class LookupItemUtil{ } if (s == null) { - LOG.assertTrue(false, "Null string for object: " + object + " of class " + (object != null ?object.getClass():null)); + LOG.error("Null string for object: " + object + " of class " + (object != null ? object.getClass() : null)); } if (object instanceof LookupValueWithTail) { item.setAttribute(LookupItem.TAIL_TEXT_ATTR, " " + ((LookupValueWithTail)object).getTailText()); diff --git a/java/java-impl/src/com/intellij/ide/JavaFileIconPatcher.java b/java/java-impl/src/com/intellij/ide/JavaFileIconPatcher.java index a70de4d0e132..4552c0cd67c2 100644 --- a/java/java-impl/src/com/intellij/ide/JavaFileIconPatcher.java +++ b/java/java-impl/src/com/intellij/ide/JavaFileIconPatcher.java @@ -63,14 +63,14 @@ public class JavaFileIconPatcher implements FileIconPatcher { // prefer icon of the class named after file final String fileName = file.getNameWithoutExtension(); for (PsiClass aClass : classes) { - if (!(aClass instanceof SyntheticElement) && Comparing.strEqual(aClass.getName(), fileName)) { + if (aClass instanceof SyntheticElement) { + return baseIcon; + } + if (Comparing.strEqual(aClass.getName(), fileName)) { return aClass.getIcon(flags); } } - final PsiClass lastClass = classes[classes.length - 1]; - if (!(lastClass instanceof SyntheticElement)) { - return lastClass.getIcon(flags); - } + return classes[classes.length - 1].getIcon(flags); } } return baseIcon; diff --git a/java/java-impl/src/com/intellij/ide/actions/CreateClassAction.java b/java/java-impl/src/com/intellij/ide/actions/CreateClassAction.java index 6b658f8d1a32..7b5bd8d35b4f 100644 --- a/java/java-impl/src/com/intellij/ide/actions/CreateClassAction.java +++ b/java/java-impl/src/com/intellij/ide/actions/CreateClassAction.java @@ -36,7 +36,7 @@ import org.jetbrains.annotations.NotNull; */ public class CreateClassAction extends CreateTemplateInPackageAction { public CreateClassAction() { - super(IdeBundle.message("action.create.new.class"), IdeBundle.message("action.create.new.class"), Icons.CLASS_ICON); + super(IdeBundle.message("action.create.new.class"), IdeBundle.message("action.create.new.class"), Icons.CLASS_ICON, true); } @NotNull diff --git a/java/java-impl/src/com/intellij/ide/actions/CreateTemplateInPackageAction.java b/java/java-impl/src/com/intellij/ide/actions/CreateTemplateInPackageAction.java index 463509a7bcbe..5defec828c81 100644 --- a/java/java-impl/src/com/intellij/ide/actions/CreateTemplateInPackageAction.java +++ b/java/java-impl/src/com/intellij/ide/actions/CreateTemplateInPackageAction.java @@ -34,8 +34,11 @@ import javax.swing.*; * @author peter */ public abstract class CreateTemplateInPackageAction extends AnAction { - protected CreateTemplateInPackageAction(String text, String description, Icon icon) { + private final boolean myinSourceOnly; + + protected CreateTemplateInPackageAction(String text, String description, Icon icon, boolean inSourceOnly) { super(text, description, icon); + myinSourceOnly = inSourceOnly; } public final void actionPerformed(final AnActionEvent e) { @@ -93,6 +96,10 @@ public abstract class CreateTemplateInPackageAction extend return false; } + if (!myinSourceOnly) { + return true; + } + ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (PsiDirectory dir : view.getDirectories()) { if (projectFileIndex.isInSourceContent(dir.getVirtualFile()) && JavaDirectoryService.getInstance().getPackage(dir) != null) { diff --git a/java/java-impl/src/com/intellij/ide/scopeView/ClassesScopeTreeStructureExpander.java b/java/java-impl/src/com/intellij/ide/scopeView/ClassesScopeTreeStructureExpander.java index eedc196bdc71..a08337dbe6e5 100644 --- a/java/java-impl/src/com/intellij/ide/scopeView/ClassesScopeTreeStructureExpander.java +++ b/java/java-impl/src/com/intellij/ide/scopeView/ClassesScopeTreeStructureExpander.java @@ -129,12 +129,12 @@ public class ClassesScopeTreeStructureExpander implements ScopeTreeStructureExpa final TreeNode childNode = node.getChildAt(i); if (childNode instanceof ClassNode) { final ClassNode classNode = (ClassNode)childNode; - final PsiElement psiElement = classNode.getPsiElement(); - if (psiElement != null && psiElement.isValid()) { + final PsiFile containingFile = classNode.getContainingFile(); + if (containingFile != null && containingFile.isValid()) { if (fileNodes == null) { fileNodes = new HashSet(); } - fileNodes.add(new FileNode(psiElement.getContainingFile(), true)); + fileNodes.add(new FileNode(containingFile, true)); } node.remove(classNode); } diff --git a/java/java-impl/src/com/intellij/ide/util/gotoByName/DefaultSymbolNavigationContributor.java b/java/java-impl/src/com/intellij/ide/util/gotoByName/DefaultSymbolNavigationContributor.java index fb5a995ba555..beba42382ee0 100644 --- a/java/java-impl/src/com/intellij/ide/util/gotoByName/DefaultSymbolNavigationContributor.java +++ b/java/java-impl/src/com/intellij/ide/util/gotoByName/DefaultSymbolNavigationContributor.java @@ -136,7 +136,7 @@ public class DefaultSymbolNavigationContributor implements ChooseByNameContribut return 3; } else{ - LOG.error(element.toString()); + LOG.error(element); return 0; } } diff --git a/java/java-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java b/java/java-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java index 3a1c401507ee..3d1cb7f68d1e 100644 --- a/java/java-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java @@ -77,7 +77,6 @@ public class JavaPsiFacadeImpl extends JavaPsiFacadeEx implements Disposable { private final ConcurrentMap myPackageCache = new ConcurrentHashMap(); private final Project myProject; private final JavaFileManager myFileManager; - private final ProgressManager myProgressManager; private final PackagePrefixIndex myPackagePrefixIndex; @@ -114,7 +113,6 @@ public class JavaPsiFacadeImpl extends JavaPsiFacadeEx implements Disposable { } myFileManager = new JavaFileManagerImpl(psiManager, projectRootManagerEx, psiManager.getFileManager(), bus); - myProgressManager = ProgressManager.getInstance(); final PsiModificationTrackerImpl modificationTracker = (PsiModificationTrackerImpl) psiManager.getModificationTracker(); psiManager.addTreeChangePreprocessor(new JavaCodeBlockModificationListener(modificationTracker)); @@ -308,13 +306,15 @@ public class JavaPsiFacadeImpl extends JavaPsiFacadeEx implements Disposable { } public PsiClass[] getClasses(PsiPackageImpl psiPackage, GlobalSearchScope scope) { - List result = new ArrayList(); + List result = null; for (PsiElementFinder finder : myElementFinders) { PsiClass[] classes = finder.getClasses(psiPackage, scope); + if (classes.length == 0) continue; + if (result == null) result = new ArrayList(); result.addAll(Arrays.asList(classes)); } - return result.toArray(new PsiClass[result.size()]); + return result == null ? PsiClass.EMPTY_ARRAY : result.toArray(new PsiClass[result.size()]); } public PsiPackage[] getSubPackages(PsiPackageImpl psiPackage, GlobalSearchScope scope) { @@ -414,13 +414,21 @@ public class JavaPsiFacadeImpl extends JavaPsiFacadeEx implements Disposable { @NotNull public PsiClass[] getClasses(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) { - List list = new ArrayList(); + List list = null; final PsiDirectory[] dirs = psiPackage.getDirectories(scope); + String packageName = psiPackage.getQualifiedName(); for (PsiDirectory dir : dirs) { PsiClass[] classes = JavaDirectoryService.getInstance().getClasses(dir); - list.addAll(Arrays.asList(classes)); + if (classes.length == 0) continue; + if (list == null) list = new ArrayList(); + for (PsiClass aClass : classes) { + // class file can be located in wrong place inside file system + if (Comparing.strEqual(((PsiClassOwner)aClass.getContainingFile()).getPackageName(), packageName)) { + list.add(aClass); + } + } } - return list.toArray(new PsiClass[list.size()]); + return list == null ? PsiClass.EMPTY_ARRAY : list.toArray(new PsiClass[list.size()]); } } diff --git a/java/java-impl/src/com/intellij/psi/impl/compiled/ClassFileStubBuilder.java b/java/java-impl/src/com/intellij/psi/impl/compiled/ClassFileStubBuilder.java index 1f455afe852a..bba38dd08fd2 100644 --- a/java/java-impl/src/com/intellij/psi/impl/compiled/ClassFileStubBuilder.java +++ b/java/java-impl/src/com/intellij/psi/impl/compiled/ClassFileStubBuilder.java @@ -28,11 +28,21 @@ import com.intellij.util.cls.ClsFormatException; public class ClassFileStubBuilder implements BinaryFileStubBuilder { public boolean acceptsFile(final VirtualFile file) { - return !isInner(file.getNameWithoutExtension()); + return !isInner(file.getNameWithoutExtension(), new ParentDirectory(file)); } - private static boolean isInner(final String name) { - return name.indexOf('$') >= 0; + static boolean isInner(final String name, final Directory directory) { + return isInner(name, 0, directory); + } + + private static boolean isInner(final String name, final int from, final Directory directory) { + final int index = name.indexOf('$', from); + return index == -1 ? false + : containsPart(directory, name, index) ? true : isInner(name, index + 1, directory); + } + + private static boolean containsPart(Directory directory, String name, int endIndex) { + return endIndex > 0 && directory.contains(name.substring(0, endIndex)); } public StubElement buildStubTree(final VirtualFile file, final byte[] content, final Project project) { @@ -47,4 +57,24 @@ public class ClassFileStubBuilder implements BinaryFileStubBuilder { public int getStubVersion() { return JavaFileElementType.STUB_VERSION; } + + + interface Directory { + boolean contains(String name); + } + + private static class ParentDirectory implements Directory { + private final VirtualFile myDirectory; + private final String myExtension; + + private ParentDirectory(final VirtualFile file) { + myDirectory = file.getParent(); + myExtension = file.getExtension(); + } + + public boolean contains(final String name) { + final String fullName = myExtension == null ? name : name + "." + myExtension; + return myDirectory == null ? false : myDirectory.findChild(fullName) != null; + } + } } \ No newline at end of file diff --git a/java/java-impl/src/com/intellij/psi/impl/compiled/ClsParsingUtil.java b/java/java-impl/src/com/intellij/psi/impl/compiled/ClsParsingUtil.java index d0efe8a5b65c..b9a9a07350a5 100644 --- a/java/java-impl/src/com/intellij/psi/impl/compiled/ClsParsingUtil.java +++ b/java/java-impl/src/com/intellij/psi/impl/compiled/ClsParsingUtil.java @@ -63,7 +63,7 @@ public class ClsParsingUtil { return new ClsLiteralExpressionImpl(parent, exprText, expr.getType(), value); //it seems ok to make literal expression with non-literal text } } - LOG.error(expr.toString()); + LOG.error(expr); return null; } } diff --git a/java/java-impl/src/com/intellij/psi/impl/file/JavaDirectoryServiceImpl.java b/java/java-impl/src/com/intellij/psi/impl/file/JavaDirectoryServiceImpl.java index 129c20e3be7c..9ad79c328ef7 100644 --- a/java/java-impl/src/com/intellij/psi/impl/file/JavaDirectoryServiceImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/file/JavaDirectoryServiceImpl.java @@ -42,6 +42,7 @@ import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import java.util.Properties; public class JavaDirectoryServiceImpl extends JavaDirectoryService { @@ -58,13 +59,16 @@ public class JavaDirectoryServiceImpl extends JavaDirectoryService { public PsiClass[] getClasses(@NotNull PsiDirectory dir) { LOG.assertTrue(dir.isValid()); - ArrayList classes = new ArrayList(); + List classes = null; for (PsiFile file : dir.getFiles()) { if (file instanceof PsiClassOwner) { - classes.addAll(Arrays.asList(((PsiClassOwner)file).getClasses())); + PsiClass[] psiClasses = ((PsiClassOwner)file).getClasses(); + if (psiClasses.length == 0) continue; + if (classes == null) classes = new ArrayList(); + classes.addAll(Arrays.asList(psiClasses)); } } - return classes.toArray(new PsiClass[classes.size()]); + return classes == null ? PsiClass.EMPTY_ARRAY : classes.toArray(new PsiClass[classes.size()]); } @NotNull diff --git a/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImpl.java b/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImpl.java index 98d9004078d4..a94be32fc589 100644 --- a/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImpl.java @@ -116,14 +116,15 @@ public class PsiPackageImpl extends PsiElementBase implements PsiPackage { @NotNull public PsiDirectory[] getDirectories(@NotNull GlobalSearchScope scope) { - final List result = new ArrayList(); + List result = null; final Collection directories = getAllDirectories(); for (final PsiDirectory directory : directories) { if (scope.contains(directory.getVirtualFile())) { + if (result == null) result = new ArrayList(); result.add(directory); } } - return result.toArray(new PsiDirectory[result.size()]); + return result == null ? PsiDirectory.EMPTY_ARRAY : result.toArray(new PsiDirectory[result.size()]); } public RowIcon getElementIcon(final int elementFlags) { diff --git a/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedElementsSearcher.java b/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedElementsSearcher.java index 5621622de856..f5f32578f121 100644 --- a/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedElementsSearcher.java +++ b/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedElementsSearcher.java @@ -79,7 +79,7 @@ public class AnnotatedElementsSearcher implements QueryExecutor myVarToConstValueMap2; private static final Object NULL = Key.create("NULL"); - private static final PsiType NULL_TYPE = new PsiEllipsisType(PsiType.NULL){ + public static final PsiType NULL_TYPE = new PsiEllipsisType(PsiType.NULL){ public boolean isValid() { return true; } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/JavaChangeUtilSupport.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/JavaChangeUtilSupport.java index 1bc212c954c8..14b44609ccc5 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/JavaChangeUtilSupport.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/JavaChangeUtilSupport.java @@ -436,7 +436,7 @@ public class JavaChangeUtilSupport implements TreeGenerator, TreeCopyHandler { } } else { - LOG.assertTrue(false, "Wrong element type: " + original.getElementType()); + LOG.error("Wrong element type: " + original.getElementType()); } } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java index f067d7eb25e0..a4603ae44544 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java @@ -150,6 +150,7 @@ public class JavaConcatenationInjectorManager implements ProjectComponent, Modif } private static final Key> INJECTED_PSI_IN_CONCATENATION = Key.create("INJECTED_PSI_IN_CONCATENATION"); + private final Concatenation2InjectorAdapter myConcatenation2InjectorAdapter = new Concatenation2InjectorAdapter(); private class Concatenation2InjectorAdapter implements MultiHostInjector { public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) { if (myConcatenationInjectors.isEmpty()) return; @@ -206,9 +207,8 @@ public class JavaConcatenationInjectorManager implements ProjectComponent, Modif } } else { - MultiHostInjector adapter = new Concatenation2InjectorAdapter(); - if (myRegisteredConcatenationAdapter.compareAndSet(null, adapter)) { - myInjectedLanguageManager.registerMultiHostInjector(adapter); + if (myRegisteredConcatenationAdapter.compareAndSet(null, myConcatenation2InjectorAdapter)) { + myInjectedLanguageManager.registerMultiHostInjector(myConcatenation2InjectorAdapter); } } } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiBinaryExpressionImpl.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiBinaryExpressionImpl.java index 47aa5a836ccc..5576c1811d36 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiBinaryExpressionImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiBinaryExpressionImpl.java @@ -61,6 +61,11 @@ public class PsiBinaryExpressionImpl extends ExpressionPsiElement implements Psi PsiExpression lOperand = param.getLOperand(); PsiExpression rOperand = param.getROperand(); if (rOperand == null) return null; + PsiType rType = rOperand.getType(); + IElementType sign = param.getOperationSign().getNode().getElementType(); + // optimization: if we can calculate type based on right type only + PsiType type = calcTypeForBinaryExpression(null, rType, sign, false); + if (type != JavaResolveCache.NULL_TYPE) return type; if (lOperand instanceof PsiBinaryExpressionImpl && !JavaResolveCache.getInstance(param.getProject()).isTypeCached(lOperand)) { // cache all intermediate expression types from bottom up @@ -80,9 +85,8 @@ public class PsiBinaryExpressionImpl extends ExpressionPsiElement implements Psi } }); } - PsiType rType = rOperand.getType(); PsiType lType = lOperand.getType(); - return calcTypeForBinaryExpression(lType, rType, param.getOperationSign().getNode().getElementType()); + return calcTypeForBinaryExpression(lType, rType, sign, true); } private static final Function MY_TYPE_EVALUATOR = new Function() { @@ -144,13 +148,14 @@ public class PsiBinaryExpressionImpl extends ExpressionPsiElement implements Psi } @Nullable - public static PsiType calcTypeForBinaryExpression(PsiType lType, PsiType rType, IElementType sign) { + public static PsiType calcTypeForBinaryExpression(PsiType lType, PsiType rType, IElementType sign, boolean accessLType) { if (sign == JavaTokenType.PLUS) { // evaluate right argument first, since '+-/*%' is left associative and left operand tends to be bigger if (rType == null) return null; if (rType.equalsToText("java.lang.String")) { return rType; } + if (!accessLType) return JavaResolveCache.NULL_TYPE; if (lType == null) return null; if (lType.equalsToText("java.lang.String")) { return lType; @@ -158,10 +163,13 @@ public class PsiBinaryExpressionImpl extends ExpressionPsiElement implements Psi return TypeConversionUtil.unboxAndBalanceTypes(lType, rType); } if (sign == JavaTokenType.MINUS || sign == JavaTokenType.ASTERISK || sign == JavaTokenType.DIV || sign == JavaTokenType.PERC) { - if (lType == null && rType == null) return null; + if (rType == null) return null; + if (!accessLType) return JavaResolveCache.NULL_TYPE; + if (lType == null) return null; return TypeConversionUtil.unboxAndBalanceTypes(lType, rType); } if (sign == JavaTokenType.LTLT || sign == JavaTokenType.GTGT || sign == JavaTokenType.GTGTGT) { + if (!accessLType) return JavaResolveCache.NULL_TYPE; if (PsiType.BYTE.equals(lType) || PsiType.CHAR.equals(lType) || PsiType.SHORT.equals(lType)) { return PsiType.INT; } @@ -178,11 +186,15 @@ public class PsiBinaryExpressionImpl extends ExpressionPsiElement implements Psi return PsiType.BOOLEAN; } if (sign == JavaTokenType.OR || sign == JavaTokenType.XOR || sign == JavaTokenType.AND) { - if (lType instanceof PsiClassType) lType = PsiPrimitiveType.getUnboxedType(lType); if (rType instanceof PsiClassType) rType = PsiPrimitiveType.getUnboxedType(rType); - if (lType == null && rType == null) return null; - if (PsiType.BOOLEAN.equals(lType) || PsiType.BOOLEAN.equals(rType)) return PsiType.BOOLEAN; + if (lType instanceof PsiClassType) lType = PsiPrimitiveType.getUnboxedType(lType); + + if (rType == null) return null; + if (PsiType.BOOLEAN.equals(rType)) return PsiType.BOOLEAN; + if (!accessLType) return JavaResolveCache.NULL_TYPE; + if (lType == null) return null; + if (PsiType.BOOLEAN.equals(lType)) return PsiType.BOOLEAN; if (PsiType.LONG.equals(lType) || PsiType.LONG.equals(rType)) return PsiType.LONG; return PsiType.INT; } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiInlineDocTagImpl.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiInlineDocTagImpl.java index 6a1e158eaa42..613b52678ffd 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiInlineDocTagImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiInlineDocTagImpl.java @@ -39,14 +39,8 @@ import org.jetbrains.annotations.NotNull; public class PsiInlineDocTagImpl extends CompositePsiElement implements PsiInlineDocTag, Constants { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.PsiInlineDocTagImpl"); - private static final TokenSet VALUE_BIT_SET = TokenSet.create(new IElementType[]{ - JAVA_CODE_REFERENCE, - DOC_TAG_VALUE_TOKEN, - DOC_METHOD_OR_FIELD_REF, - DOC_COMMENT_DATA, - DOC_INLINE_TAG, - DOC_REFERENCE_HOLDER - }); + private static final TokenSet VALUE_BIT_SET = TokenSet.create(JAVA_CODE_REFERENCE, DOC_TAG_VALUE_TOKEN, DOC_METHOD_OR_FIELD_REF, + DOC_COMMENT_DATA, DOC_INLINE_TAG, DOC_REFERENCE_HOLDER, WHITE_SPACE, DOC_COMMENT_BAD_CHARACTER); public PsiInlineDocTagImpl() { super(DOC_INLINE_TAG); diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java index 8cb2b20f6a6f..deea549bc0d1 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java @@ -284,7 +284,7 @@ public class PsiReferenceExpressionImpl extends ExpressionPsiElement implements public JavaResolveResult[] multiResolve(boolean incompleteCode) { final PsiManagerEx manager = getManager(); if (manager == null) { - LOG.assertTrue(false, "getManager() == null!"); + LOG.error("getManager() == null!"); return null; } ResolveResult[] results = manager.getResolveCache().resolveWithCaching(this, OurGenericsResolver.INSTANCE, true, incompleteCode); @@ -619,7 +619,7 @@ public class PsiReferenceExpressionImpl extends ExpressionPsiElement implements if (nameChild == null) { final TreeElement dot = (TreeElement)findChildByRole(ChildRole.DOT); if (dot == null) { - LOG.assertTrue(false, this); + LOG.error(toString()); } return new TextRange(dot.getStartOffsetInParent() + dot.getTextLength(), getTextLength()); } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/ReplaceExpressionUtil.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/ReplaceExpressionUtil.java index b18e8b8f0e1a..f016798a5f6b 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/ReplaceExpressionUtil.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/ReplaceExpressionUtil.java @@ -154,7 +154,7 @@ public class ReplaceExpressionUtil implements Constants { return 14; } else { - LOG.assertTrue(false, "Unknown element type:"+i); + LOG.error("Unknown element type:" + i); return -1; } } diff --git a/java/java-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java b/java/java-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java index bae8d6c2d350..22c5be988e64 100644 --- a/java/java-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java +++ b/java/java-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java @@ -233,7 +233,7 @@ public class PsiScopesUtil { } } else{ - LOG.assertTrue(false, "Unknown name element " + referenceNameElement + " in reference " + ref.getText() + "(" + ref + ")"); + LOG.error("Unknown name element " + referenceNameElement + " in reference " + ref.getText() + "(" + ref + ")"); } } else if (referenceNameElement instanceof PsiIdentifier){ @@ -243,7 +243,7 @@ public class PsiScopesUtil { resolveAndWalk(processor, ref, null); } else{ - LOG.assertTrue(false, "Unknown name element " + referenceNameElement + " in reference " + ref.getText() + "(" + ref + ")"); + LOG.error("Unknown name element " + referenceNameElement + " in reference " + ref.getText() + "(" + ref + ")"); } } else{ diff --git a/java/java-impl/src/com/intellij/refactoring/IntroduceHandlerBase.java b/java/java-impl/src/com/intellij/refactoring/IntroduceHandlerBase.java index 3216086a31ca..bccfa30c379f 100644 --- a/java/java-impl/src/com/intellij/refactoring/IntroduceHandlerBase.java +++ b/java/java-impl/src/com/intellij/refactoring/IntroduceHandlerBase.java @@ -54,7 +54,7 @@ public abstract class IntroduceHandlerBase { invokeImpl(project, (PsiLocalVariable)tempExpr, editor); } else { - LOG.assertTrue(false, "elements[0] should be PsiExpression or PsiLocalVariable"); + LOG.error("elements[0] should be PsiExpression or PsiLocalVariable"); } } diff --git a/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDialog.java b/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDialog.java index 6e8f0acb09b1..510c5e1892c4 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDialog.java @@ -238,7 +238,7 @@ public class ChangeSignatureDialog extends RefactoringDialog { final PsiElementFactory factory = JavaPsiFacade.getInstance(myMethod.getProject()).getElementFactory(); final PsiTypeElement typeElement = myMethod.getReturnTypeElement(); if (typeElement == null) { - LOG.assertTrue(false, myMethod.getClass().getName()); + LOG.error(myMethod.getClass().getName()); return panel; } myReturnTypeCodeFragment = factory.createTypeCodeFragment(typeElement.getText(), myMethod.getParameterList(), true, true); diff --git a/java/java-impl/src/com/intellij/refactoring/changeSignature/MethodCallUsageInfo.java b/java/java-impl/src/com/intellij/refactoring/changeSignature/MethodCallUsageInfo.java index eacc2e9fbc59..616ec7f5c32e 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeSignature/MethodCallUsageInfo.java +++ b/java/java-impl/src/com/intellij/refactoring/changeSignature/MethodCallUsageInfo.java @@ -52,7 +52,7 @@ public class MethodCallUsageInfo extends UsageInfo { else if (parent instanceof PsiAnonymousClass) { return ((PsiNewExpression)parent.getParent()).resolveConstructor(); } - LOG.assertTrue(false, "Unknown reference"); + LOG.error("Unknown reference"); return null; } diff --git a/java/java-impl/src/com/intellij/refactoring/extractMethod/ControlFlowWrapper.java b/java/java-impl/src/com/intellij/refactoring/extractMethod/ControlFlowWrapper.java index ffe10f406a71..23bd6406fdf5 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractMethod/ControlFlowWrapper.java +++ b/java/java-impl/src/com/intellij/refactoring/extractMethod/ControlFlowWrapper.java @@ -281,7 +281,7 @@ public class ControlFlowWrapper { if (myFlowStart <= startOffset && endOffset <= myFlowEnd) continue; } else { - LOG.assertTrue(false, exitStatement); + LOG.error(String.valueOf(exitStatement)); continue; } diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java index a78a315e7017..104332c1c3e8 100644 --- a/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java @@ -81,7 +81,9 @@ public class InlineParameterHandler extends JavaInlineActionHandler { final PsiCallExpression methodCall = (PsiCallExpression)parent; occurrences.add(psiReference); containingFiles.add(element.getContainingFile()); - PsiExpression argument = methodCall.getArgumentList().getExpressions()[index]; + final PsiExpression[] expressions = methodCall.getArgumentList().getExpressions(); + if (expressions.length <= index) return false; + PsiExpression argument = expressions[index]; if (!refInitializer.isNull()) { return argument != null && PsiEquivalenceUtil.areElementsEquivalent(refInitializer.get(), argument) diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java index a5aae5d453b6..4aa0f8d94492 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java @@ -59,6 +59,7 @@ import com.intellij.refactoring.util.EnumConstantsUtil; import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.refactoring.util.occurences.OccurenceManager; import com.intellij.util.IncorrectOperationException; +import com.intellij.util.VisibilityUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -194,21 +195,7 @@ public abstract class BaseExpressionToFieldHandler extends IntroduceHandlerBase ChangeContextUtil.encodeContextInfo(initializer, true); PsiField field = settings.isIntroduceEnumConstant() ? EnumConstantsUtil.createEnumConstant(destClass, fieldName, initializer) : createField(fieldName, type, initializer, initializerPlace == InitializationPlace.IN_FIELD_DECLARATION && initializer != null); - if (!settings.isIntroduceEnumConstant()) { - PsiUtil.setModifierProperty(field, settings.getFieldVisibility(), true); - if (settings.isDeclareFinal()) { - PsiUtil.setModifierProperty(field, PsiModifier.FINAL, true); - } - if (settings.isDeclareStatic()) { - PsiUtil.setModifierProperty(field, PsiModifier.STATIC, true); - } - if (settings.isAnnotateAsNonNls()) { - PsiAnnotation annotation = JavaPsiFacade.getInstance(myParentClass.getProject()).getElementFactory() - .createAnnotationFromText("@" + AnnotationUtil.NON_NLS, myParentClass); - field.getModifierList().addAfter(annotation, null); - JavaCodeStyleManager.getInstance(myParentClass.getProject()).shortenClassReferences(field.getModifierList()); - } - } + PsiElement finalAnchorElement = null; if (destClass == myParentClass) { for (finalAnchorElement = anchorElement; @@ -230,6 +217,7 @@ public abstract class BaseExpressionToFieldHandler extends IntroduceHandlerBase else { field = (PsiField)destClass.add(field); } + setModifiers(field, settings, settings.isDeclareStatic(), occurrences); PsiStatement assignStatement = null; PsiElement anchorElementHere = null; if (initializerPlace == InitializationPlace.IN_CURRENT_METHOD && initializer != null || @@ -326,6 +314,26 @@ public abstract class BaseExpressionToFieldHandler extends IntroduceHandlerBase return true; } + public static void setModifiers(PsiField field, Settings settings, final boolean declareStatic, PsiExpression[] occurrences) { + if (!settings.isIntroduceEnumConstant()) { + VisibilityUtil.fixVisibility(occurrences, field, settings.getFieldVisibility()); + if (declareStatic) { + PsiUtil.setModifierProperty(field, PsiModifier.STATIC, true); + } + if (settings.isDeclareFinal()) { + PsiUtil.setModifierProperty(field, PsiModifier.FINAL, true); + } + if (settings.isAnnotateAsNonNls()) { + PsiAnnotation annotation = JavaPsiFacade.getInstance(field.getProject()).getElementFactory() + .createAnnotationFromText("@" + AnnotationUtil.NON_NLS, field); + final PsiModifierList modifierList = field.getModifierList(); + LOG.assertTrue(modifierList != null); + modifierList.addAfter(annotation, null); + } + } + JavaCodeStyleManager.getInstance(field.getProject()).shortenClassReferences(field); + } + private static PsiElement getPhysicalElement(final PsiExpression selectedExpr) { PsiElement element = selectedExpr.getUserData(ElementToWorkOn.PARENT); if (element == null) element = selectedExpr; diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.form b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.form index be37bbaa3235..08c65852f116 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.form +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.form @@ -79,52 +79,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -152,6 +106,14 @@ + + + + + + + + diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.java b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.java index 4bc51108528b..8fb93fb70d7e 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.java @@ -46,6 +46,7 @@ import com.intellij.ui.RecentsManager; import com.intellij.ui.ReferenceEditorComboWithBrowseButton; import com.intellij.ui.StateRestoringCheckBox; import com.intellij.util.IncorrectOperationException; +import com.intellij.util.ui.UIUtil; import gnu.trove.THashSet; import org.jetbrains.annotations.NonNls; @@ -77,11 +78,6 @@ class IntroduceConstantDialog extends DialogWrapper { private NameSuggestionsField myNameField; private JCheckBox myCbReplaceAll; - private JRadioButton myRbPrivate; - private JRadioButton myRbProtected; - private JRadioButton myRbpackageLocal; - private JRadioButton myRbPublic; - private TypeSelector myTypeSelector; private StateRestoringCheckBox myCbDeleteVariable; private final JavaCodeStyleManager myCodeStyleManager; @@ -95,6 +91,8 @@ class IntroduceConstantDialog extends DialogWrapper { private JLabel myNameSuggestionLabel; private JLabel myTargetClassNameLabel; private JCheckBox myCbNonNls; + private JPanel myVisibilityPanel; + private VisibilityPanel myVPanel; private final JCheckBox myIntroduceEnumConstantCb = new JCheckBox(RefactoringBundle.message("introduce.constant.enum.cb"), true); IntroduceConstantDialog(Project project, @@ -119,20 +117,11 @@ class IntroduceConstantDialog extends DialogWrapper { setTitle(IntroduceConstantHandler.REFACTORING_NAME); myCodeStyleManager = JavaCodeStyleManager.getInstance(myProject); + myVPanel = new VisibilityPanel(false, true); + myVisibilityPanel.add(myVPanel, BorderLayout.CENTER); init(); - final String ourLastVisibility = JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY; - if (PsiModifier.PUBLIC.equals(ourLastVisibility)) { - myRbPublic.setSelected(true); - } else if (PsiModifier.PROTECTED.equals(ourLastVisibility)) { - myRbProtected.setSelected(true); - } else if (PsiModifier.PACKAGE_LOCAL.equals(ourLastVisibility)) { - myRbpackageLocal.setSelected(true); - } else if (PsiModifier.PRIVATE.equals(ourLastVisibility)) { - myRbPrivate.setSelected(true); - } else { - myRbPrivate.setSelected(true); - } + myVPanel.setVisibility(JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY); myIntroduceEnumConstantCb.setEnabled(EnumConstantsUtil.isSuitableForEnumConstant(getSelectedType(), myTargetClass)); updateVisibilityPanel(); } @@ -155,20 +144,7 @@ class IntroduceConstantDialog extends DialogWrapper { @Modifier public String getFieldVisibility() { - if (myRbPublic.isSelected()) { - return PsiModifier.PUBLIC; - } - if (myRbpackageLocal.isSelected()) { - return PsiModifier.PACKAGE_LOCAL; - } - if (myRbProtected.isSelected()) { - return PsiModifier.PROTECTED; - } - if (myRbPrivate.isSelected()) { - return PsiModifier.PRIVATE; - } - LOG.assertTrue(false); - return null; + return myVPanel.getVisibility(); } public boolean isReplaceAllOccurrences() { @@ -301,11 +277,6 @@ class IntroduceConstantDialog extends DialogWrapper { updateTypeSelector(); - ButtonGroup bg = new ButtonGroup(); - bg.add(myRbPrivate); - bg.add(myRbpackageLocal); - bg.add(myRbProtected); - bg.add(myRbPublic); enableEnumDependant(introduceEnumConstant()); return myPanel; } @@ -319,11 +290,7 @@ class IntroduceConstantDialog extends DialogWrapper { private void enableEnumDependant(boolean enable) { if (enable) { - myRbPrivate.setEnabled(false); - myRbProtected.setEnabled(false); - myRbpackageLocal.setEnabled(false); - myRbPublic.setEnabled(true); - myRbPublic.setSelected(true); + myVPanel.disableAllButPublic(); } else { updateVisibilityPanel(); } @@ -361,19 +328,11 @@ class IntroduceConstantDialog extends DialogWrapper { } private void updateVisibilityPanel() { - if (myTargetClass == null) return; - if (myTargetClass.isInterface()) { - myRbPrivate.setEnabled(false); - myRbProtected.setEnabled(false); - myRbpackageLocal.setEnabled(false); - myRbPublic.setEnabled(true); - myRbPublic.setSelected(true); + if (myTargetClass != null && myTargetClass.isInterface()) { + myVPanel.disableAllButPublic(); } else { - myRbPrivate.setEnabled(true); - myRbProtected.setEnabled(true); - myRbpackageLocal.setEnabled(true); - myRbPublic.setEnabled(true); + UIUtil.setEnabled(myVisibilityPanel, true, true); // exclude all modifiers not visible from all occurences final Set visible = new THashSet(); visible.add(PsiModifier.PRIVATE); @@ -397,10 +356,12 @@ class IntroduceConstantDialog extends DialogWrapper { } } } - if (visible.contains(PsiModifier.PUBLIC)) myRbPublic.setSelected(true); - if (visible.contains(PsiModifier.PACKAGE_LOCAL)) myRbpackageLocal.setSelected(true); - if (visible.contains(PsiModifier.PROTECTED)) myRbProtected.setSelected(true); - if (visible.contains(PsiModifier.PRIVATE)) myRbPrivate.setSelected(true); + if (!visible.contains(getFieldVisibility())) { + if (visible.contains(PsiModifier.PUBLIC)) myVPanel.setVisibility(PsiModifier.PUBLIC); + if (visible.contains(PsiModifier.PACKAGE_LOCAL)) myVPanel.setVisibility(PsiModifier.PACKAGE_LOCAL); + if (visible.contains(PsiModifier.PROTECTED)) myVPanel.setVisibility(PsiModifier.PROTECTED); + if (visible.contains(PsiModifier.PRIVATE)) myVPanel.setVisibility(PsiModifier.PRIVATE); + } } } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java index 9055a91074c5..7764cd42a55b 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java @@ -15,7 +15,6 @@ */ package com.intellij.refactoring.introduceField; -import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInsight.CodeInsightUtil; import com.intellij.codeInsight.TestUtil; import com.intellij.openapi.application.ApplicationManager; @@ -25,15 +24,11 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; -import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.psi.util.PsiUtil; import com.intellij.refactoring.HelpID; import com.intellij.refactoring.RefactoringBundle; -import static com.intellij.refactoring.introduceField.BaseExpressionToFieldHandler.InitializationPlace.IN_CONSTRUCTOR; -import static com.intellij.refactoring.introduceField.BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION; import com.intellij.refactoring.ui.TypeSelectorManagerImpl; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.refactoring.util.EnumConstantsUtil; @@ -41,6 +36,9 @@ import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NonNls; +import static com.intellij.refactoring.introduceField.BaseExpressionToFieldHandler.InitializationPlace.IN_CONSTRUCTOR; +import static com.intellij.refactoring.introduceField.BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION; + public class LocalToFieldHandler { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.introduceField.LocalToFieldHandler"); @@ -125,9 +123,7 @@ public class LocalToFieldHandler { final boolean isStatic = tempIsStatic; - PsiExpression[] occurences = CodeInsightUtil.findReferenceExpressions(RefactoringUtil.getVariableScope(local), - local - ); + final PsiExpression[] occurences = CodeInsightUtil.findReferenceExpressions(RefactoringUtil.getVariableScope(local), local); if (editor != null) { RefactoringUtil.highlightAllOccurences(myProject, occurences, editor); } @@ -138,7 +134,6 @@ public class LocalToFieldHandler { final String variableName = local.getName(); final String fieldName = settings.getFieldName(); final BaseExpressionToFieldHandler.InitializationPlace initializerPlace = settings.getInitializerPlace(); - final boolean declareFinal = settings.isDeclareFinal(); @Modifier final String fieldVisibility = settings.getFieldVisibility(); final PsiClass destinationClass = settings.getDestinationClass(); boolean rebindNeeded = false; @@ -146,7 +141,6 @@ public class LocalToFieldHandler { aClass = destinationClass; rebindNeeded = true; } - final boolean annotateAsNonNls = settings.isAnnotateAsNonNls(); final PsiClass aaClass = aClass; final boolean rebindNeeded1 = rebindNeeded; @@ -165,22 +159,8 @@ public class LocalToFieldHandler { final PsiMethod enclosingConstructor = BaseExpressionToFieldHandler.getEnclosingConstructor(aaClass, local); PsiField field = settings.isIntroduceEnumConstant() ? EnumConstantsUtil.createEnumConstant(aaClass, local, fieldName) : createField(local, fieldName, initializerPlace == IN_FIELD_DECLARATION); - if (!settings.isIntroduceEnumConstant()) { - if (isStatic) { - PsiUtil.setModifierProperty(field, PsiModifier.STATIC, true); - } - if (declareFinal) { - PsiUtil.setModifierProperty(field, PsiModifier.FINAL, true); - } - if (annotateAsNonNls) { - PsiAnnotation annotation = JavaPsiFacade.getInstance(local.getProject()).getElementFactory().createAnnotationFromText("@" + AnnotationUtil.NON_NLS, field); - field.getModifierList().addAfter(annotation, null); - } - PsiUtil.setModifierProperty(field, fieldVisibility, true); - } - field = (PsiField)aaClass.add(field); - JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(field); + BaseExpressionToFieldHandler.setModifiers(field, settings, isStatic, occurences); local.normalizeDeclaration(); PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement)local.getParent(); diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java index 94b79585d4de..0ae7342287fd 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java @@ -511,7 +511,7 @@ public class IntroduceParameterProcessor extends BaseRefactoringProcessor implem removeParametersFromCall(argList); } else { - LOG.error(element.getParent().toString()); + LOG.error(element.getParent()); } } diff --git a/java/java-impl/src/com/intellij/refactoring/rename/JavaNameSuggestionProvider.java b/java/java-impl/src/com/intellij/refactoring/rename/JavaNameSuggestionProvider.java index 8b8414794e19..23a2b12cc3bc 100644 --- a/java/java-impl/src/com/intellij/refactoring/rename/JavaNameSuggestionProvider.java +++ b/java/java-impl/src/com/intellij/refactoring/rename/JavaNameSuggestionProvider.java @@ -165,7 +165,7 @@ public class JavaNameSuggestionProvider implements NameSuggestionProvider { result.add(suggestProperlyCasedName(prefix, NameUtil.splitNameIntoWords(name))); } result.add(suggestProperlyCasedName(prefix, NameUtil.splitNameIntoWords(name.toLowerCase()))); - return result.toArray(new String[result.size()]); + return ArrayUtil.toStringArray(result); } } diff --git a/java/java-impl/src/com/intellij/refactoring/rename/naming/PsiNamedElementAutomaticRenamer.java b/java/java-impl/src/com/intellij/refactoring/rename/naming/PsiNamedElementAutomaticRenamer.java index dd0e4c62973d..b5c4e74566c4 100644 --- a/java/java-impl/src/com/intellij/refactoring/rename/naming/PsiNamedElementAutomaticRenamer.java +++ b/java/java-impl/src/com/intellij/refactoring/rename/naming/PsiNamedElementAutomaticRenamer.java @@ -45,13 +45,8 @@ public abstract class PsiNamedElementAutomaticRenamer String canonicalName = nameToCanonicalName(elementName, element); final String newCanonicalName = suggester.suggestName(canonicalName); if (newCanonicalName.length() == 0) { - LOG.assertTrue(false, - "oldName = " + getOldName() + - ", newName = " + getNewName() + - ", name = " + elementName + - ", canonicalName = " + canonicalName + - ", newCanonicalName = " + newCanonicalName - ); + LOG.error("oldName = " + getOldName() + ", newName = " + getNewName() + ", name = " + elementName + ", canonicalName = " + + canonicalName + ", newCanonicalName = " + newCanonicalName); } return canonicalNameToName(newCanonicalName, element); } diff --git a/java/java-impl/src/com/intellij/refactoring/ui/VisibilityPanel.java b/java/java-impl/src/com/intellij/refactoring/ui/VisibilityPanel.java index 558b82a17566..95b0e3d384b8 100644 --- a/java/java-impl/src/com/intellij/refactoring/ui/VisibilityPanel.java +++ b/java/java-impl/src/com/intellij/refactoring/ui/VisibilityPanel.java @@ -144,6 +144,20 @@ public class VisibilityPanel extends JPanel { } } + public void disableAllButPublic() { + myRbPrivate.setEnabled(false); + myRbProtected.setEnabled(false); + myRbPackageLocal.setEnabled(false); + if (myRbEscalate != null) { + myRbEscalate.setEnabled(false); + } + if (myRbAsIs != null) { + myRbAsIs.setEnabled(false); + } + myRbPublic.setEnabled(true); + myRbPublic.setSelected(true); + } + public static interface StateChanged extends EventListener { void visibilityChanged(); } diff --git a/java/java-impl/src/com/intellij/refactoring/util/classRefs/ClassInstanceScanner.java b/java/java-impl/src/com/intellij/refactoring/util/classRefs/ClassInstanceScanner.java index 99f8f33fcfaf..cc72b6682993 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/classRefs/ClassInstanceScanner.java +++ b/java/java-impl/src/com/intellij/refactoring/util/classRefs/ClassInstanceScanner.java @@ -186,7 +186,7 @@ public class ClassInstanceScanner extends DelegatingClassReferenceVisitor { visitor.visitReadUsage(expression, null, referencedElement); } else { - LOG.assertTrue(false, "Unknown variation of class instance usage"); + LOG.error("Unknown variation of class instance usage"); } } diff --git a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueDialog.java b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueDialog.java index fe6aeb62e04a..fab67d602497 100644 --- a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueDialog.java @@ -22,6 +22,7 @@ import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.TypeConversionUtil; @@ -226,6 +227,16 @@ class WrapReturnValueDialog extends RefactoringDialog { UIUtil.setEnabled(myExistingClassPanel, useExistingClassButton.isSelected(), true); UIUtil.setEnabled(myNewClassPanel, createNewClassButton.isSelected(), true); UIUtil.setEnabled(myCreateInnerPanel, myCreateInnerClassButton.isSelected(), true); + final IdeFocusManager focusManager = IdeFocusManager.getInstance(myProject); + if (useExistingClassButton.isSelected()) { + focusManager.requestFocus(existingClassField, true); + } + else if (myCreateInnerClassButton.isSelected()) { + focusManager.requestFocus(myInnerClassNameTextField, true); + } + else { + focusManager.requestFocus(classNameField, true); + } validateButtons(); } diff --git a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueForm.form b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueForm.form index a3c4342ea222..e185665d4071 100644 --- a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueForm.form +++ b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueForm.form @@ -96,6 +96,7 @@ + diff --git a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueProcessor.java b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueProcessor.java index aabf2ac3eed0..564e16cc7adf 100644 --- a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueProcessor.java @@ -164,21 +164,22 @@ public class WrapReturnValueProcessor extends FixableUsagesRefactoringProcessor } else { boolean foundConstructor = false; - final PsiCodeBlock methodBody = method.getBody(); - assert methodBody != null; final Set returnTypes = new HashSet(); returnTypes.add(method.getReturnType()); - methodBody.accept(new JavaRecursiveElementWalkingVisitor() { - @Override - public void visitReturnStatement(final PsiReturnStatement statement) { - super.visitReturnStatement(statement); - if (PsiTreeUtil.getParentOfType(statement, PsiMethod.class) != method) return; - final PsiExpression returnValue = statement.getReturnValue(); - if (returnValue != null) { - returnTypes.add(returnValue.getType()); + final PsiCodeBlock methodBody = method.getBody(); + if (methodBody != null) { + methodBody.accept(new JavaRecursiveElementWalkingVisitor() { + @Override + public void visitReturnStatement(final PsiReturnStatement statement) { + super.visitReturnStatement(statement); + if (PsiTreeUtil.getParentOfType(statement, PsiMethod.class) != method) return; + final PsiExpression returnValue = statement.getReturnValue(); + if (returnValue != null) { + returnTypes.add(returnValue.getType()); + } } - } - }); + }); + } final PsiMethod[] constructors = existingClass.getConstructors(); constr: for (PsiMethod constructor : constructors) { diff --git a/java/java-impl/src/com/intellij/slicer/CanItBeNullAction.java b/java/java-impl/src/com/intellij/slicer/CanItBeNullAction.java index 4dddb17afc00..8ab184d66e97 100644 --- a/java/java-impl/src/com/intellij/slicer/CanItBeNullAction.java +++ b/java/java-impl/src/com/intellij/slicer/CanItBeNullAction.java @@ -54,7 +54,7 @@ public class CanItBeNullAction extends AnAction { else { type = null; } - return type instanceof PsiClassType; + return type instanceof PsiClassType || type instanceof PsiArrayType; } @Override diff --git a/java/java-tests/testData/refactoring/introduceParameterObject/copyJavadoc/before/Test.java b/java/java-tests/testData/refactoring/introduceParameterObject/copyJavadoc/before/Test.java index 124187af21df..f9260f0d7dc6 100644 --- a/java/java-tests/testData/refactoring/introduceParameterObject/copyJavadoc/before/Test.java +++ b/java/java-tests/testData/refactoring/introduceParameterObject/copyJavadoc/before/Test.java @@ -8,4 +8,4 @@ class Test { } void bar(String s){} -} \ No newline at end of file +} diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/compiled/ClassFileStubBuilderTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/compiled/ClassFileStubBuilderTest.java new file mode 100644 index 000000000000..b5e9fa54880f --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/psi/impl/compiled/ClassFileStubBuilderTest.java @@ -0,0 +1,143 @@ +package com.intellij.psi.impl.compiled; + +import junit.framework.TestCase; + +import java.util.*; + +/** + * Pavel.Fatin, 18.02.2010 + */ +public class ClassFileStubBuilderTest extends TestCase { + public void testOneFile() { + assertTopLevel(""); + assertTopLevel("$"); + assertTopLevel("$$"); + assertTopLevel("$$$"); + assertTopLevel("Foo"); + assertTopLevel("Foo$"); + assertTopLevel("$Foo"); + assertTopLevel("$Foo$"); + assertTopLevel("Foo$Bar"); + assertTopLevel("$Foo$Bar"); + assertTopLevel("Foo$Bar$"); + assertTopLevel("$Foo$Bar$"); + assertTopLevel("$$Foo$$Bar$$"); + } + + public void testWrongCase() { + assertTopLevel("Foo$Bar", "foo"); + assertTopLevel("foo$Bar", "Foo"); + } + + public void testShortName() { + assertTopLevel("A"); + + assertInner("Foo$B", "Foo"); + assertInner("A$Foo", "A"); + assertInner("A$B", "A"); + + assertTopLevel("A$B", "A$"); + assertTopLevel("A$B", "$B"); + assertTopLevel("A$B", "B"); + assertTopLevel("A$B", "$"); + } + + public void testShortNames() { + assertInner("A$B$C", "A"); + assertInner("A$B$C", "A$B"); + assertInner("A$B$C", "A", "A$B"); + + assertTopLevel("A$B$C", "A$"); + assertTopLevel("A$B$C", "A$B$"); + } + + public void testEmptyFileName() { + assertTopLevel("$Foo", ""); + } + + public void testNoInnerName() { + //assertTopLevel("Foo$", "Foo"); + //assertTopLevel("Foo$$", "Foo$"); + // an exception to the rule (to hide Scala "objects") + assertInner("Foo$", "Foo"); + assertInner("Foo$$", "Foo$"); + } + + public void testDollarsInName() { + assertInner("$Foo$Bar", "$Foo"); + assertInner("Foo$$Bar", "Foo"); + assertInner("Foo$$Bar", "Foo"); + assertInner("$Foo$$Bar", "$Foo"); + assertInner("$Foo$$Bar", "$Foo$"); + } + + public void testInner() { + assertInner("Foo$Bar", "Foo"); + assertInner("Foo$bar", "Foo"); + assertInner("foo$Bar", "foo"); + assertInner("foo$bar", "foo"); + } + + public void testInnerAndNoise() { + assertInner("Foo$Bar", "Foo", "Foo$", "$Bar", "Bar"); + } + + public void testTopLevel() { + assertTopLevel("Foo$Bar"); + assertTopLevel("Foo$Bar", "Foo$"); + assertTopLevel("Foo$Bar", "$Bar"); + assertTopLevel("Foo$Bar", "Bar"); + assertTopLevel("Foo$Bar", "Foo$", "$Bar", "Bar"); + } + + public void testInners() { + assertInner("Foo$Bar$Moo", "Foo"); + assertInner("Foo$Bar$Moo", "Foo$Bar"); + assertInner("Foo$Bar$Moo", "Foo", "Foo$Bar"); + } + + public void testInnersAndNoise() { + assertInner("Foo$Bar$Moo", "Foo", "$Bar", "Bar", "$Moo", "Moo", "Bar$Moo", "$Bar$Moo"); + assertInner("Foo$Bar$Moo", "Foo$Bar", "$Bar", "Bar", "$Moo", "Moo", "Bar$Moo", "$Bar$Moo"); + assertInner("Foo$Bar$Moo", "Foo", "Foo$Bar", "$Bar", "Bar", "$Moo", "Moo", "Bar$Moo", "$Bar$Moo"); + } + + public void testTopLevels() { + assertTopLevel("Foo$Bar$Moo"); + assertTopLevel("Foo$Bar$Moo", "$Bar"); + assertTopLevel("Foo$Bar$Moo", "Bar"); + assertTopLevel("Foo$Bar$Moo", "$Moo"); + assertTopLevel("Foo$Bar$Moo", "Moo"); + assertTopLevel("Foo$Bar$Moo", "Bar$Moo"); + assertTopLevel("Foo$Bar$Moo", "$Bar$Moo"); + assertTopLevel("Foo$Bar$Moo", "$Bar", "Bar", "$Moo", "Moo", "Bar$Moo", "$Bar$Moo"); + } + + private static void assertInner(String name, String... files) { + assertTrue("Class " + name + " must be identified as inner", isInner(name, files)); + } + + private static void assertTopLevel(String name, String... files) { + assertFalse("Class " + name + " must be identified as top-level", isInner(name, files)); + } + + private static boolean isInner(String name, String... files) { + Set all = new HashSet(); + all.addAll(Arrays.asList(files)); + all.add(name); + return ClassFileStubBuilder.isInner(name, new DirectoryMock(all)); + } + + + private static class DirectoryMock implements ClassFileStubBuilder.Directory { + private Set myFiles; + + private DirectoryMock(Set files) { + myFiles = files; + } + + public boolean contains(String name) { + return myFiles.contains(name); + } + } +} \ No newline at end of file diff --git a/java/openapi/src/com/intellij/psi/util/TypeConversionUtil.java b/java/openapi/src/com/intellij/psi/util/TypeConversionUtil.java index deeacf849071..1647efb410fe 100644 --- a/java/openapi/src/com/intellij/psi/util/TypeConversionUtil.java +++ b/java/openapi/src/com/intellij/psi/util/TypeConversionUtil.java @@ -685,7 +685,7 @@ public class TypeConversionUtil { IS_ASSIGNABLE_BIT_SET[rightTypeIndex][leftTypeIndex]; } if (!(right instanceof PsiClassType)) { - LOG.error(right.toString()); + LOG.error(right); } if (left instanceof PsiPrimitiveType) { return isUnboxable((PsiPrimitiveType)left, (PsiClassType)right); diff --git a/java/openapi/src/com/intellij/util/VisibilityUtil.java b/java/openapi/src/com/intellij/util/VisibilityUtil.java index a5505ac27d88..773717d07a02 100644 --- a/java/openapi/src/com/intellij/util/VisibilityUtil.java +++ b/java/openapi/src/com/intellij/util/VisibilityUtil.java @@ -143,4 +143,16 @@ public class VisibilityUtil { modifierList.setModifierProperty(PsiModifier.PROTECTED, false); modifierList.setModifierProperty(newVisibility, true); } + + public static void fixVisibility(PsiExpression[] expressions, PsiMember member, String newVisibility) { + if (newVisibility == null) return; + if (ESCALATE_VISIBILITY.equals(newVisibility)) { + for (PsiExpression element : expressions) { + escalateVisibility(member, element); + } + } + else { + setVisibility(member.getModifierList(), newVisibility); + } + } } diff --git a/platform/lang-api/src/com/intellij/codeInsight/daemon/LineMarkerProviders.java b/platform/lang-api/src/com/intellij/codeInsight/daemon/LineMarkerProviders.java index 1e6734d10156..05974940c789 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/daemon/LineMarkerProviders.java +++ b/platform/lang-api/src/com/intellij/codeInsight/daemon/LineMarkerProviders.java @@ -17,14 +17,16 @@ package com.intellij.codeInsight.daemon; import com.intellij.lang.LanguageExtension; +import org.jetbrains.annotations.NonNls; /** * @author yole */ public class LineMarkerProviders extends LanguageExtension { public static LineMarkerProviders INSTANCE = new LineMarkerProviders(); + @NonNls public static final String EP_NAME = "com.intellij.codeInsight.lineMarkerProvider"; private LineMarkerProviders() { - super("com.intellij.codeInsight.lineMarkerProvider"); + super(EP_NAME); } } diff --git a/platform/lang-api/src/com/intellij/codeInsight/generation/MemberChooserObjectBase.java b/platform/lang-api/src/com/intellij/codeInsight/generation/MemberChooserObjectBase.java index b35af75a8eee..9a4c2dd9c769 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/generation/MemberChooserObjectBase.java +++ b/platform/lang-api/src/com/intellij/codeInsight/generation/MemberChooserObjectBase.java @@ -38,7 +38,7 @@ public class MemberChooserObjectBase implements MemberChooserObject { } public void renderTreeNode(SimpleColoredComponent component, JTree tree) { - component.append(myText, getTextAttributes(tree)); + component.append(getText(), getTextAttributes(tree)); component.setIcon(myIcon); } diff --git a/platform/lang-api/src/com/intellij/execution/runners/ProgramRunnerUtil.java b/platform/lang-api/src/com/intellij/execution/runners/ProgramRunnerUtil.java index 2fe12089b83a..1362af5b7213 100644 --- a/platform/lang-api/src/com/intellij/execution/runners/ProgramRunnerUtil.java +++ b/platform/lang-api/src/com/intellij/execution/runners/ProgramRunnerUtil.java @@ -44,7 +44,7 @@ public class ProgramRunnerUtil { String message = ExecutionBundle.message("error.running.configuration.with.error.error.message", runProfile != null? runProfile.getName() : "Run profile", e.getMessage()); if (ApplicationManager.getApplication().isUnitTestMode()) { - LOG.assertTrue(false, message); + LOG.error(message); } else { if (message.contains("87") && e instanceof ProcessNotCreatedException) { diff --git a/platform/lang-api/src/com/intellij/lang/folding/LanguageFolding.java b/platform/lang-api/src/com/intellij/lang/folding/LanguageFolding.java index e369efd4a074..232118cf37a4 100644 --- a/platform/lang-api/src/com/intellij/lang/folding/LanguageFolding.java +++ b/platform/lang-api/src/com/intellij/lang/folding/LanguageFolding.java @@ -73,7 +73,7 @@ public class LanguageFolding extends LanguageExtension { return ((FoldingBuilderEx)builder).buildFoldRegions(root, document, quick); } final ASTNode astNode = root.getNode(); - if (astNode == null) { + if (astNode == null || builder == null) { return FoldingDescriptor.EMPTY; } diff --git a/platform/lang-api/src/com/intellij/psi/PsiFileSystemItem.java b/platform/lang-api/src/com/intellij/psi/PsiFileSystemItem.java index 209579b894cc..a10628d91bc3 100644 --- a/platform/lang-api/src/com/intellij/psi/PsiFileSystemItem.java +++ b/platform/lang-api/src/com/intellij/psi/PsiFileSystemItem.java @@ -15,7 +15,6 @@ */ package com.intellij.psi; -import com.intellij.navigation.NavigationItem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.search.PsiElementProcessor; import org.jetbrains.annotations.NonNls; @@ -27,7 +26,7 @@ import org.jetbrains.annotations.Nullable; * * @author ven */ -public interface PsiFileSystemItem extends PsiCheckedRenameElement, NavigationItem { +public interface PsiFileSystemItem extends PsiCheckedRenameElement, NavigatablePsiElement { boolean isDirectory(); @Nullable diff --git a/platform/lang-impl/src/com/intellij/codeInsight/CodeInsightSettings.java b/platform/lang-impl/src/com/intellij/codeInsight/CodeInsightSettings.java index 1debf36b3241..cc8f0c81fab0 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/CodeInsightSettings.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/CodeInsightSettings.java @@ -22,6 +22,7 @@ import com.intellij.openapi.util.DefaultJDOMExternalizer; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.util.ArrayUtil; import com.intellij.util.xmlb.annotations.AbstractCollection; import com.intellij.util.xmlb.annotations.Property; import org.jdom.Element; @@ -127,13 +128,11 @@ public class CodeInsightSettings implements PersistentStateComponent, C public boolean OPTIMIZE_IMPORTS_ON_THE_FLY = false; public boolean ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = false; - @Property(surroundWithTag = false) - @AbstractCollection( + @Property(surroundWithTag = false) @AbstractCollection( surroundWithTag = false, elementTag = "EXCLUDED_PACKAGE", - elementValueAttribute = "NAME" - ) - public String[] EXCLUDED_PACKAGES = new String[0]; + elementValueAttribute = "NAME") + public String[] EXCLUDED_PACKAGES = ArrayUtil.EMPTY_STRING_ARRAY; public void loadState(final Element state) { try { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java index 0892b7696ce9..efd1e6381a12 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java @@ -396,7 +396,7 @@ public class CodeCompletionHandlerBase implements CodeInsightActionHandler { if (fileCopy == null) { PsiElement elementAfterCommit = findElementAt(hostFile, hostStartOffset); if (wasInjected) { - LOG.assertTrue(false, "No injected fragmnent found at offset " + hostStartOffset + " in the patched file copy, found: " + elementAfterCommit); + LOG.error("No injected fragmnent found at offset " + hostStartOffset + " in the patched file copy, found: " + elementAfterCommit); } fileCopy = elementAfterCommit == null ? oldFileCopy : elementAfterCommit.getContainingFile(); } @@ -420,11 +420,8 @@ public class CodeCompletionHandlerBase implements CodeInsightActionHandler { final String allDoc = hostFile.getViewProvider().getDocument().getText(); String docText = allDoc.substring(Math.max(0, context.getStartOffset() - 10), Math.min(allDoc.length(), context.getStartOffset() + 10)); - LOG.assertTrue(false, "offset " + newContext.getStartOffset() + " at:\n" + - "text=\"" + injectedFile.getText() + "\"\n" + - "instance=" + injectedFile + "\n" + - "patcher=" + patcher + "\n" + - "docText=" + docText); + LOG.error("offset " + newContext.getStartOffset() + " at:\n" + "text=\"" + injectedFile.getText() + "\"\n" + "instance=" + + injectedFile + "\n" + "patcher=" + patcher + "\n" + "docText=" + docText); } EditorFactory.getInstance().releaseEditor(editor); return Pair.create(newContext, element); @@ -433,7 +430,7 @@ public class CodeCompletionHandlerBase implements CodeInsightActionHandler { } PsiElement element = findElementAt(fileCopy, context.getStartOffset()); if (element == null) { - LOG.assertTrue(false, "offset " + context.getStartOffset() + " at:\ntext=\"" + fileCopy.getText() + "\"\ninstance=" + fileCopy); + LOG.error("offset " + context.getStartOffset() + " at:\ntext=\"" + fileCopy.getText() + "\"\ninstance=" + fileCopy); } return Pair.create(context, element); } @@ -463,7 +460,7 @@ public class CodeCompletionHandlerBase implements CodeInsightActionHandler { Project project = context.project; Editor editor = context.editor; if (!ApplicationManager.getApplication().isUnitTestMode() && context.editor.getComponent().getRootPane() == null) { - LOG.assertTrue(false, "null root pane"); + LOG.error("null root pane"); } for (final CompletionContributor contributor : CompletionContributor.forParameters(parameters)) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionData.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionData.java index 7f234341b844..58257600360f 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionData.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionData.java @@ -248,7 +248,7 @@ public class CompletionData { s = ((PresentableLookupValue)object).getPresentation(); } else { - LOG.assertTrue(false, "Null string for object: " + object + " of class " + (object != null ?object.getClass():null)); + LOG.error("Null string for object: " + object + " of class " + (object != null ? object.getClass() : null)); } LookupItem item = new LookupItem(object, s); @@ -311,7 +311,7 @@ public class CompletionData { for (Object completion : completions) { if (completion == null) { - LOG.assertTrue(false, "Position=" + position + "\n;Reference=" + reference + "\n;variants=" + Arrays.toString(completions)); + LOG.error("Position=" + position + "\n;Reference=" + reference + "\n;variants=" + Arrays.toString(completions)); } if (completion instanceof PsiElement) { final PsiElement psiElement = (PsiElement)completion; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IdentifierHighlighterPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IdentifierHighlighterPass.java index dbf760b25923..07e50a9763a4 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IdentifierHighlighterPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IdentifierHighlighterPass.java @@ -31,9 +31,11 @@ import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; +import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; +import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.util.Processor; @@ -78,13 +80,26 @@ public class IdentifierHighlighterPass extends TextEditorHighlightingPass { return; } - final PsiElement myTarget = TargetElementUtilBase.getInstance().findTargetElement(myEditor, TargetElementUtilBase.ELEMENT_NAME_ACCEPTED | TargetElementUtilBase.REFERENCED_ELEMENT_ACCEPTED, myCaretOffset); + int flags = TargetElementUtilBase.ELEMENT_NAME_ACCEPTED | TargetElementUtilBase.REFERENCED_ELEMENT_ACCEPTED; + PsiElement myTarget = TargetElementUtilBase.getInstance().findTargetElement(myEditor, flags, myCaretOffset); + + if (myTarget == null) { + if (!PsiDocumentManager.getInstance(myProject).isUncommited(myEditor.getDocument())) { + // when document is committed, try to check injected stuff - it's fast + Editor injectedEditor = InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(myEditor, myFile, myCaretOffset); + if (injectedEditor != null) { + myTarget = TargetElementUtilBase.getInstance().findTargetElement(injectedEditor, flags, injectedEditor.getCaretModel().getOffset()); + } + } + } + if (myTarget != null) { final ReadWriteAccessDetector detector = ReadWriteAccessDetector.findDetector(myTarget); + final PsiElement finalMyTarget = myTarget; ReferencesSearch.search(myTarget, new LocalSearchScope(myFile)).forEach(new Processor() { public boolean process(final PsiReference psiReference) { final TextRange textRange = HighlightUsagesHandler.getRangeToHighlight(psiReference); - if (detector == null || detector.getReferenceAccess(myTarget, psiReference) == ReadWriteAccessDetector.Access.Read) { + if (detector == null || detector.getReferenceAccess(finalMyTarget, psiReference) == ReadWriteAccessDetector.Access.Read) { myReadAccessRanges.add(textRange); } else { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java index c74efd2d06b1..f789c6ce3407 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java @@ -118,12 +118,12 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass inspect(tools, iManager, true, true); } - public void doInspectInBatch(final InspectionManagerEx iManager, InspectionProfileEntry[] toolWrappers, boolean ignoreSuppressed) { + public void doInspectInBatch(final InspectionManagerEx iManager, List toolWrappers, boolean ignoreSuppressed) { myDescriptors = new ArrayList(); myLevels = new ArrayList(); myTools = new ArrayList(); - Map tool2Wrapper = new THashMap(toolWrappers.length); + Map tool2Wrapper = new THashMap(toolWrappers.size()); for (InspectionProfileEntry toolWrapper : toolWrappers) { tool2Wrapper.put(((LocalInspectionToolWrapper)toolWrapper).getTool(), (LocalInspectionToolWrapper)toolWrapper); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java index bd47348f1e2c..8445802578f9 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java @@ -131,7 +131,7 @@ public class DocumentationComponent extends JPanel implements Disposable { myText = ""; myEditorPane.setEditable(false); myEditorPane.setBackground(HintUtil.INFORMATION_COLOR); - + myEditorPane.setEditorKit(UIUtil.getHTMLEditorKit()); myScrollPane = new JScrollPane(myEditorPane); myScrollPane.setBorder(null); @@ -269,7 +269,7 @@ public class DocumentationComponent extends JPanel implements Disposable { myForwardStack.clear(); } updateControlState(); - setData(element, text, !clean); + setData(element, text, clearHistory); if (clean) { myIsEmpty = false; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/BackspaceHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/BackspaceHandler.java index 0714bdc304b7..9a7b1b063652 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/BackspaceHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/BackspaceHandler.java @@ -90,14 +90,13 @@ public class BackspaceHandler extends EditorWriteActionHandler { myOriginalHandler.execute(editor, dataContext); - if (offset >= editor.getDocument().getTextLength()) return true; - for(BackspaceHandlerDelegate delegate: delegates) { if (delegate.charDeleted(c, file, editor)) { return true; } } + if (offset >= editor.getDocument().getTextLength()) return true; chars = editor.getDocument().getCharsSequence(); if (c == '(' || c == '[' || c == '{'){ diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java index a667dd956f43..8f1cd78588a9 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java @@ -181,7 +181,7 @@ public class DocumentFoldingInfo implements JDOMExternalizable, CodeFoldingState PsiElement restoredElement = FoldingPolicy.restoreBySignature(psiElement.getContainingFile(), signature); if (!psiElement.equals(restoredElement)){ restoredElement = FoldingPolicy.restoreBySignature(psiElement.getContainingFile(), signature); - LOG.assertTrue(false, "element:" + psiElement + ", signature:" + signature + ", file:" + psiElement.getContainingFile()); + LOG.error("element:" + psiElement + ", signature:" + signature + ", file:" + psiElement.getContainingFile()); } Element e = new Element(ELEMENT_TAG); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java index f691ed92aac2..1c1ddc61914e 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java @@ -424,7 +424,8 @@ public class LookupImpl extends LightweightHint implements Lookup, Disposable { Dimension dim = getComponent().getPreferredSize(); int lookupStart = getLookupStart(); if (lookupStart < 0) { - LOG.assertTrue(false, lookupStart + "; minprefix=" + myMinPrefixLength + "; offset=" + myEditor.getCaretModel().getOffset() + "; element=" + getPsiElement()); + LOG.error(lookupStart + "; minprefix=" + myMinPrefixLength + "; offset=" + myEditor.getCaretModel().getOffset() + "; element=" + + getPsiElement()); } LogicalPosition pos = myEditor.offsetToLogicalPosition(lookupStart); @@ -434,7 +435,7 @@ public class LookupImpl extends LightweightHint implements Lookup, Disposable { JComponent internalComponent = myEditor.getContentComponent(); final JRootPane rootPane = editorComponent.getRootPane(); if (rootPane == null) { - LOG.assertTrue(false, myArranger); + LOG.error(myArranger); } JLayeredPane layeredPane = rootPane.getLayeredPane(); Point layeredPanePoint=SwingUtilities.convertPoint(internalComponent,location, layeredPane); @@ -921,7 +922,7 @@ public class LookupImpl extends LightweightHint implements Lookup, Disposable { if (isVisible() && !ApplicationManager.getApplication().isUnitTestMode()) { if (myEditor.getComponent().getRootPane() == null) { - LOG.assertTrue(false, "Null root pane"); + LOG.error("Null root pane"); } Point point = calculatePosition(); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java index 02bd1aafc627..75a4f28b976d 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java @@ -347,8 +347,9 @@ public class CtrlMouseHandler extends AbstractProjectComponent { return new InfoSingle (ref, resolvedElement); } } - targetElement = GotoDeclarationAction.findTargetElement(myProject, editor, offset); - } else if ( browseMode == BrowseMode.Implementation ) { + targetElement = GotoDeclarationAction.findTargetElementNoVS(myProject, editor, offset); + } + else if ( browseMode == BrowseMode.Implementation ) { final PsiElement element = TargetElementUtilBase.getInstance().findTargetElement(editor, ImplementationSearcher.getFlags(), offset); PsiElement[] targetElements = new ImplementationSearcher() { @NotNull diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java index a18141721b90..4978f3180d57 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java @@ -155,6 +155,11 @@ public class GotoDeclarationAction extends BaseCodeInsightAction implements Code return null; } + return findTargetElementNoVS(project, editor, offset); + } + + @Nullable + public static PsiElement findTargetElementNoVS(Project project, Editor editor, int offset) { PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null) { return null; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/CustomLiveTemplate.java b/platform/lang-impl/src/com/intellij/codeInsight/template/CustomLiveTemplate.java index 74912fddebad..959aa06fa19a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/CustomLiveTemplate.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/CustomLiveTemplate.java @@ -26,7 +26,8 @@ import org.jetbrains.annotations.Nullable; public interface CustomLiveTemplate { ExtensionPointName EP_NAME = ExtensionPointName.create("com.intellij.customLiveTemplate"); - boolean isApplicable(@NotNull String key, @NotNull CustomTemplateCallback callback); + @Nullable + String computeTemplateKey(@NotNull CustomTemplateCallback callback); - void execute(@NotNull String key, @NotNull CustomTemplateCallback callback, @Nullable TemplateInvokationListener listener); + void execute(String key, @NotNull CustomTemplateCallback callback, @Nullable TemplateInvokationListener listener); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/CustomTemplateCallback.java b/platform/lang-impl/src/com/intellij/codeInsight/template/CustomTemplateCallback.java index dc75c79e4ae0..08906aebd5af 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/CustomTemplateCallback.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/CustomTemplateCallback.java @@ -20,6 +20,7 @@ import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateSettings; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleManager; @@ -40,15 +41,16 @@ public class CustomTemplateCallback { private final Editor myEditor; private final PsiFile myFile; private int myStartOffset; - private int myStartLength; private Project myProject; + private RangeMarker myGlobalMarker; - private final Map myCheckpoints = new HashMap(); + //private final Map myCheckpoints = new HashMap(); + private final Map myCheckpoints = new HashMap(); - private static class MyCheckpoint { - int myFixedLength = -1; - int myFixedOffset; - } + /*private static class MyCheckpoint { + int myFixedLength = null; + RangeMarker myFixedOffset; + }*/ public CustomTemplateCallback(Editor editor, PsiFile file) { myEditor = editor; @@ -59,7 +61,9 @@ public class CustomTemplateCallback { public void fixInitialEditorState() { myStartOffset = myEditor.getCaretModel().getOffset(); - myStartLength = myEditor.getDocument().getCharsSequence().length(); + myGlobalMarker = myEditor.getDocument().createRangeMarker(myStartOffset, myStartOffset); + myGlobalMarker.setGreedyToLeft(true); + myGlobalMarker.setGreedyToRight(true); } public boolean isLiveTemplateApplicable(@NotNull String key) { @@ -128,11 +132,11 @@ public class CustomTemplateCallback { myTemplateManager.startTemplate(myEditor, template, false, predefinedVarValues, new TemplateEditingAdapter() { @Override public void templateFinished(Template template, boolean brokenOff) { - final int lengthAfter = myEditor.getDocument().getCharsSequence().length(); final CodeStyleManager style = CodeStyleManager.getInstance(myProject); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { - style.reformatText(myFile, myStartOffset, myStartOffset + lengthAfter - myStartLength); + //style.reformatText(myFile, myStartOffset, myStartOffset + lengthAfter - myStartLength); + style.reformatText(myFile, myGlobalMarker.getStartOffset(), myGlobalMarker.getEndOffset()); } }); if (brokenOff) return; @@ -150,10 +154,11 @@ public class CustomTemplateCallback { } public void fixStartOfTemplate(@NotNull Object key) { - MyCheckpoint checkpoint = new MyCheckpoint(); - checkpoint.myFixedOffset = myEditor.getCaretModel().getOffset(); - checkpoint.myFixedLength = myEditor.getDocument().getTextLength(); - myCheckpoints.put(key, checkpoint); + int offset = myEditor.getCaretModel().getOffset(); + RangeMarker marker = myEditor.getDocument().createRangeMarker(offset, offset); + marker.setGreedyToLeft(true); + marker.setGreedyToRight(true); + myCheckpoints.put(key, marker); } public void gotoEndOfTemplate(@NotNull Object key) { @@ -161,20 +166,19 @@ public class CustomTemplateCallback { } public int getEndOfTemplate(@NotNull Object key) { - MyCheckpoint checkpoint = myCheckpoints.get(key); - if (checkpoint == null) { + RangeMarker marker = myCheckpoints.get(key); + if (marker == null) { throw new IllegalArgumentException(); } - int length = myEditor.getDocument().getTextLength(); - return checkpoint.myFixedOffset + length - checkpoint.myFixedLength; + return marker.getEndOffset(); } public int getStartOfTemplate(@NotNull Object key) { - MyCheckpoint checkpoint = myCheckpoints.get(key); - if (checkpoint == null) { + RangeMarker marker = myCheckpoints.get(key); + if (marker == null) { throw new IllegalArgumentException(); } - return checkpoint.myFixedOffset; + return marker.getStartOffset(); } private static List getMatchingTemplates(@NotNull String templateKey) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java index 0f661293de45..6bfda59e3a57 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java @@ -220,47 +220,19 @@ public class TemplateManagerImpl extends TemplateManager implements ProjectCompo } } - private static String getCurrentLineBeforeCaret(@NotNull Editor editor) { - CaretModel caretModel = editor.getCaretModel(); - int line = caretModel.getLogicalPosition().line; - int lineStart = editor.getDocument().getLineStartOffset(line); - int offset = caretModel.getOffset(); - String s = editor.getDocument().getCharsSequence().subSequence(lineStart, offset).toString(); - int index = 0; - while (index < s.length() && Character.isWhitespace(s.charAt(index))) { - index++; - } - return index < s.length() ? s.substring(index) : s; - } - - @NotNull - private static String normalize(@NotNull String key) { - int lastWhitespaceIndex = -1; - for (int i = 0; i < key.length(); i++) { - if (Character.isWhitespace(key.charAt(i))) { - lastWhitespaceIndex = i; - } - } - if (lastWhitespaceIndex >= 0 && lastWhitespaceIndex < key.length() - 1) { - return key.substring(lastWhitespaceIndex + 1); - } - return key; - } - public boolean startTemplate(final Editor editor, char shortcutChar, final PairProcessor processor) { PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, myProject); if (file == null) return false; TemplateSettings templateSettings = TemplateSettings.getInstance(); if (shortcutChar == templateSettings.getDefaultShortcutChar()) { for (final CustomLiveTemplate customLiveTemplate : CustomLiveTemplate.EP_NAME.getExtensions()) { - final String currentLineBeforeCaret = normalize(getCurrentLineBeforeCaret(editor)); final CustomTemplateCallback callback = new CustomTemplateCallback(editor, file); - if (customLiveTemplate.isApplicable(currentLineBeforeCaret, callback)) { - int offset = editor.getCaretModel().getOffset(); - final int startOffset = offset - currentLineBeforeCaret.length(); - editor.getDocument().deleteString(startOffset, offset); + String key = customLiveTemplate.computeTemplateKey(callback); + if (key != null) { + int offset = callback.getEditor().getCaretModel().getOffset(); + callback.getEditor().getDocument().deleteString(offset - key.length(), offset); callback.fixInitialEditorState(); - customLiveTemplate.execute(currentLineBeforeCaret, callback, null); + customLiveTemplate.execute(key, callback, null); return true; } } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/GlobalInspectionUtil.java b/platform/lang-impl/src/com/intellij/codeInspection/GlobalInspectionUtil.java index b5b0a077e8ed..43c7e51950cf 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/GlobalInspectionUtil.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/GlobalInspectionUtil.java @@ -56,4 +56,18 @@ public class GlobalInspectionUtil { descriptor ); } + + public static void createProblem(PsiElement elt, String message, ProblemHighlightType problemHighlightType, TextRange range, + InspectionManager manager, ProblemDescriptionsProcessor problemDescriptionsProcessor, + GlobalInspectionContext globalContext, LocalQuickFix fix) { + ProblemDescriptor descriptor = manager.createProblemDescriptor( + elt, + range, + createInspectionMessage(message), + problemHighlightType, false, fix); + problemDescriptionsProcessor.addProblemElement( + retrieveRefElement(elt, globalContext), + descriptor + ); + } } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java index 3e3dd8df1e65..4e3256258f1a 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java @@ -420,7 +420,7 @@ public class GlobalInspectionContextImpl implements GlobalInspectionContext { public void run() { LOG.info("Code inspection finished"); - final InspectionResultsView view = new InspectionResultsView(myProject, getCurrentProfile(), + InspectionResultsView view = new InspectionResultsView(myProject, getCurrentProfile(), scope, GlobalInspectionContextImpl.this, new InspectionRVContentProviderImpl(myProject)); if (!view.update() && !getUIOptions().SHOW_ONLY_DIFF) { @@ -469,11 +469,11 @@ public class GlobalInspectionContextImpl implements GlobalInspectionContext { } private void runTools(final List needRepeatSearchRequest, final AnalysisScope scope, final InspectionManager manager) { - final List usedTools = new ArrayList(); + final List globalTools = new ArrayList(); final List localTools = new ArrayList(); - initializeTools(usedTools, localTools); + initializeTools(globalTools, localTools); ((RefManagerImpl)getRefManager()).initializeAnnotators(); - for (Tools tools : usedTools) { + for (Tools tools : globalTools) { for (ScopeToolState state : tools.getTools()) { final InspectionTool tool = (InspectionTool)state.getTool(); try { @@ -510,14 +510,13 @@ public class GlobalInspectionContextImpl implements GlobalInspectionContext { scope.accept(new PsiRecursiveElementVisitor() { @Override public void visitFile(PsiFile file) { - final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null) { incrementJobDoneAmount(LOCAL_ANALYSIS, ProjectUtil.calcRelativeToProjectPath(virtualFile, myProject)); } final FileViewProvider viewProvider = psiManager.findViewProvider(virtualFile); - final com.intellij.openapi.editor.Document document = viewProvider != null ? viewProvider.getDocument() : null; + final com.intellij.openapi.editor.Document document = viewProvider == null ? null : viewProvider.getDocument(); if (document == null || virtualFile.getFileType().isBinary()) return; //do not inspect binary files final LocalInspectionsPass pass = new LocalInspectionsPass(file, document, 0, file.getTextLength()); try { @@ -528,7 +527,7 @@ public class GlobalInspectionContextImpl implements GlobalInspectionContext { lTools.add(enabledTool); } } - pass.doInspectInBatch((InspectionManagerEx)manager, lTools.toArray(new InspectionProfileEntry[lTools.size()]), true); + pass.doInspectInBatch((InspectionManagerEx)manager, lTools, true); } catch (ProcessCanceledException e) { throw e; @@ -540,7 +539,7 @@ public class GlobalInspectionContextImpl implements GlobalInspectionContext { }); } - public void initializeTools(List tools, List localTools) { + public void initializeTools(List globalTools, List localTools) { myJobDescriptors = new ArrayList(); final InspectionProfileImpl profile = new InspectionProfileImpl((InspectionProfileImpl)getCurrentProfile()); final List usedTools = profile.getAllEnabledInspectionTools(); @@ -553,7 +552,7 @@ public class GlobalInspectionContextImpl implements GlobalInspectionContext { appendJobDescriptor(LOCAL_ANALYSIS); } else { - tools.add(currentTools); + globalTools.add(currentTools); JobDescriptor[] jobDescriptors = tool.getJobDescriptors(); for (JobDescriptor jobDescriptor : jobDescriptors) { appendJobDescriptor(jobDescriptor); @@ -565,7 +564,7 @@ public class GlobalInspectionContextImpl implements GlobalInspectionContext { } } for (GlobalInspectionContextExtension extension : myExtensions.values()) { - extension.performPreRunActivities(tools, localTools, this); + extension.performPreRunActivities(globalTools, localTools, this); } } diff --git a/platform/lang-impl/src/com/intellij/execution/ui/layout/actions/MoveToTabAction.java b/platform/lang-impl/src/com/intellij/execution/ui/layout/actions/MoveToTabAction.java index f99a1942e756..bf20c5280fe9 100644 --- a/platform/lang-impl/src/com/intellij/execution/ui/layout/actions/MoveToTabAction.java +++ b/platform/lang-impl/src/com/intellij/execution/ui/layout/actions/MoveToTabAction.java @@ -35,6 +35,12 @@ public class MoveToTabAction extends BaseViewAction { } Grid grid = context.findGridFor(content[0]); + if (grid == null) { + setEnabled(e, false); + return; + } + + Tab tab = context.getTabFor(grid); if (ViewContext.TAB_TOOLBAR_PLACE.equals(e.getPlace())) { diff --git a/platform/lang-impl/src/com/intellij/extapi/psi/PsiElementBase.java b/platform/lang-impl/src/com/intellij/extapi/psi/PsiElementBase.java index b8d550e237db..51b3594a0fda 100644 --- a/platform/lang-impl/src/com/intellij/extapi/psi/PsiElementBase.java +++ b/platform/lang-impl/src/com/intellij/extapi/psi/PsiElementBase.java @@ -243,7 +243,7 @@ public abstract class PsiElementBase extends ElementBase implements NavigatableP protected T findNotNullChildByClass(Class aClass) { final T child = findChildByClass(aClass); if (child == null) { - LOG.assertTrue(false, getText() + "\n parent=" + getParent().getText()); + LOG.error(getText() + "\n parent=" + getParent().getText()); } return child; } diff --git a/platform/lang-impl/src/com/intellij/find/actions/ShowUsagesAction.java b/platform/lang-impl/src/com/intellij/find/actions/ShowUsagesAction.java index 69d744506b30..a286f77354af 100644 --- a/platform/lang-impl/src/com/intellij/find/actions/ShowUsagesAction.java +++ b/platform/lang-impl/src/com/intellij/find/actions/ShowUsagesAction.java @@ -59,6 +59,7 @@ import com.intellij.usages.impl.NullUsage; import com.intellij.usages.impl.UsageNode; import com.intellij.usages.impl.UsageViewImpl; import com.intellij.usages.rules.UsageFilteringRuleProvider; +import com.intellij.util.ArrayUtil; import com.intellij.util.Icons; import com.intellij.util.Processor; import com.intellij.util.messages.MessageBusConnection; @@ -364,7 +365,7 @@ public class ShowUsagesAction extends AnAction { } protected Object[] getAllElements() { - return data.toArray(new Object[data.size()]); + return ArrayUtil.toObjectArray(data); } protected String getElementText(Object element) { diff --git a/platform/lang-impl/src/com/intellij/formatting/InitialInfoBuilder.java b/platform/lang-impl/src/com/intellij/formatting/InitialInfoBuilder.java index a95646da5554..7f99f4858127 100644 --- a/platform/lang-impl/src/com/intellij/formatting/InitialInfoBuilder.java +++ b/platform/lang-impl/src/com/intellij/formatting/InitialInfoBuilder.java @@ -315,6 +315,6 @@ class InitialInfoBuilder { buffer.append('\n'); } - LOG.error(buffer.toString()); + LOG.error(buffer); } } diff --git a/platform/lang-impl/src/com/intellij/formatting/templateLanguages/BlockUtil.java b/platform/lang-impl/src/com/intellij/formatting/templateLanguages/BlockUtil.java index 3b9f8d0bf555..1a67ea08ae70 100644 --- a/platform/lang-impl/src/com/intellij/formatting/templateLanguages/BlockUtil.java +++ b/platform/lang-impl/src/com/intellij/formatting/templateLanguages/BlockUtil.java @@ -184,16 +184,24 @@ class BlockUtil { final List children = new ArrayList(5); final TextRange range = block.getTextRange(); int childStartOffset = range.getStartOffset(); + TemplateLanguageBlock lastTLBlock = null; for (TemplateLanguageBlock tlBlock : subBlocks) { final TextRange tlTextRange = tlBlock.getTextRange(); if (tlTextRange.getStartOffset() > childStartOffset) { - children.add(new DataLanguageBlockFragmentWrapper(block, new TextRange(childStartOffset, tlTextRange.getStartOffset()))); + TextRange dataBlockTextRange = new TextRange(childStartOffset, tlTextRange.getStartOffset()); + if (tlBlock.isRequiredRange(dataBlockTextRange)) { + children.add(new DataLanguageBlockFragmentWrapper(block, dataBlockTextRange)); + } } children.add(tlBlock); + lastTLBlock = tlBlock; childStartOffset = tlTextRange.getEndOffset(); } if (range.getEndOffset() > childStartOffset) { - children.add(new DataLanguageBlockFragmentWrapper(block, new TextRange(childStartOffset, range.getEndOffset()))); + TextRange dataBlockTextRange = new TextRange(childStartOffset, range.getEndOffset()); + if (lastTLBlock == null || lastTLBlock.isRequiredRange(dataBlockTextRange) ) { + children.add(new DataLanguageBlockFragmentWrapper(block, dataBlockTextRange)); + } } return children; } diff --git a/platform/lang-impl/src/com/intellij/formatting/templateLanguages/TemplateLanguageBlock.java b/platform/lang-impl/src/com/intellij/formatting/templateLanguages/TemplateLanguageBlock.java index af5a734cf4fe..9970f478b51e 100644 --- a/platform/lang-impl/src/com/intellij/formatting/templateLanguages/TemplateLanguageBlock.java +++ b/platform/lang-impl/src/com/intellij/formatting/templateLanguages/TemplateLanguageBlock.java @@ -17,6 +17,7 @@ package com.intellij.formatting.templateLanguages; import com.intellij.formatting.*; import com.intellij.lang.ASTNode; +import com.intellij.openapi.util.TextRange; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.formatter.FormatterUtil; import com.intellij.psi.formatter.common.AbstractBlock; @@ -119,5 +120,14 @@ public abstract class TemplateLanguageBlock extends AbstractBlock implements Blo public void setParent(BlockWithParent newParent) { myParent = newParent; } + + /** + * Checks if DataLanguageBlockFragmentWrapper must be created for the given text range. + * @param range The range to check. + * @return True by default. + */ + public boolean isRequiredRange(TextRange range) { + return true; + } } diff --git a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeStructure.java b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeStructure.java index 191f66396613..6a9a22165cef 100644 --- a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeStructure.java +++ b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeStructure.java @@ -100,7 +100,7 @@ public class FavoritesTreeStructure extends ProjectTreeStructure { if (result.isEmpty()) { result.add(getEmptyScreen()); } - return result.toArray(new Object[result.size()]); + return ArrayUtil.toObjectArray(result); } catch (Exception e) { } diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java index 6010b0e857bc..e3dc85211919 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java @@ -461,7 +461,7 @@ public final class ProjectViewImpl extends ProjectView implements PersistentStat else { String presentable = pane.getPresentableSubIdName(subId); if (index == -1) { - setText(pane.getTitle() + ": " + presentable); + setText(presentable); setIcon(pane.getIcon()); } else { diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/ProjectViewDirectoryHelper.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/ProjectViewDirectoryHelper.java index adf7c33ace82..e2341a1be15a 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/ProjectViewDirectoryHelper.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/ProjectViewDirectoryHelper.java @@ -223,7 +223,7 @@ public class ProjectViewDirectoryHelper { } } else { - LOG.assertTrue(false, "Either PsiFile or PsiDirectory expected as a child of " + child.getParent() + ", but was " + child); + LOG.error("Either PsiFile or PsiDirectory expected as a child of " + child.getParent() + ", but was " + child); } } } diff --git a/platform/lang-impl/src/com/intellij/openapi/module/impl/scopes/LibraryRuntimeClasspathScope.java b/platform/lang-impl/src/com/intellij/openapi/module/impl/scopes/LibraryRuntimeClasspathScope.java index a749b352e4a4..3f8d0c76c902 100644 --- a/platform/lang-impl/src/com/intellij/openapi/module/impl/scopes/LibraryRuntimeClasspathScope.java +++ b/platform/lang-impl/src/com/intellij/openapi/module/impl/scopes/LibraryRuntimeClasspathScope.java @@ -52,9 +52,9 @@ public class LibraryRuntimeClasspathScope extends GlobalSearchScope { public boolean equals(Object object) { if (object == this) return true; - if (object.getClass() != LibraryRuntimeClasspathScope.class) return false; + if (object == null || object.getClass() != LibraryRuntimeClasspathScope.class) return false; - final LibraryRuntimeClasspathScope that = ((LibraryRuntimeClasspathScope)object); + final LibraryRuntimeClasspathScope that = (LibraryRuntimeClasspathScope)object; return that.myModules.equals(myModules); } diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/impl/ContentEntryImpl.java b/platform/lang-impl/src/com/intellij/openapi/roots/impl/ContentEntryImpl.java index eccbbbf3ce53..f7260d85a6c6 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/impl/ContentEntryImpl.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/impl/ContentEntryImpl.java @@ -218,7 +218,7 @@ public class ContentEntryImpl extends RootModelComponentBase implements ContentE final String rootUrl = getUrl(); try { if (!FileUtil.isAncestor(new File(rootUrl), new File(url), false)) { - LOG.assertTrue(false, "The file " + url + " is not under content entry root " + rootUrl); + LOG.error("The file " + url + " is not under content entry root " + rootUrl); } } catch (IOException e) { diff --git a/platform/lang-impl/src/com/intellij/pom/references/PomReferenceServiceImpl.java b/platform/lang-impl/src/com/intellij/pom/references/PomReferenceServiceImpl.java index 2c4088c9e48e..9c7be766862b 100644 --- a/platform/lang-impl/src/com/intellij/pom/references/PomReferenceServiceImpl.java +++ b/platform/lang-impl/src/com/intellij/pom/references/PomReferenceServiceImpl.java @@ -127,7 +127,7 @@ public class PomReferenceServiceImpl extends PomReferenceService { @SuppressWarnings({"unchecked"}) final PomReferenceProvider provider = trinity.getFirst(); for (PomReference reference : provider.getReferencesByElement(context, trinity.getSecond())) { if (reference == null) { - LOG.error(context.toString()); + LOG.error(context); } if (offsetMatches(offset, reference)) { result.add(reference); diff --git a/platform/lang-impl/src/com/intellij/psi/formatter/FormattingDocumentModelImpl.java b/platform/lang-impl/src/com/intellij/psi/formatter/FormattingDocumentModelImpl.java index 9276f2b051f4..84d0cf06351e 100644 --- a/platform/lang-impl/src/com/intellij/psi/formatter/FormattingDocumentModelImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/formatter/FormattingDocumentModelImpl.java @@ -42,10 +42,11 @@ public class FormattingDocumentModelImpl implements FormattingDocumentModel{ Document document = getDocumentToBeUsedFor(file); if (document != null) { if (PsiDocumentManager.getInstance(file.getProject()).isUncommited(document)) { - LOG.assertTrue(false, "Document is uncommited"); + LOG.error("Document is uncommited"); } if (!document.getText().equals(file.getText())) { - LOG.assertTrue(false, "Document and psi file texts should be equal : \nDocument text:\n" + document.getText() + "\nFile text:\n" + file.getText()); + LOG.error( + "Document and psi file texts should be equal : \nDocument text:\n" + document.getText() + "\nFile text:\n" + file.getText()); } return new FormattingDocumentModelImpl(document, file); } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/SharedPsiElementImplUtil.java b/platform/lang-impl/src/com/intellij/psi/impl/SharedPsiElementImplUtil.java index da6835d54a42..abf7f58357fa 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/SharedPsiElementImplUtil.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/SharedPsiElementImplUtil.java @@ -65,7 +65,7 @@ public class SharedPsiElementImplUtil { private static void addReferences(int offset, PsiElement element, final Collection outReferences) { for (final PsiReference reference : element.getReferences()) { if (reference == null) { - LOG.error(element.toString()); + LOG.error(element); } final TextRange range = reference.getRangeInElement(); if (range.getStartOffset() <= offset && offset <= range.getEndOffset()) { diff --git a/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/IndexCacheManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/IndexCacheManagerImpl.java index c2f9254dad6d..9585b99a6bee 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/IndexCacheManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/IndexCacheManagerImpl.java @@ -20,6 +20,7 @@ import com.intellij.ide.caches.CacheUpdater; import com.intellij.injected.editor.VirtualFileWindow; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; @@ -78,6 +79,23 @@ public class IndexCacheManagerImpl implements CacheManager{ } public boolean processFilesWithWord(@NotNull final Processor psiFileProcessor, @NotNull final String word, final short occurrenceMask, @NotNull final GlobalSearchScope scope, final boolean caseSensitively) { + final Set vFiles = new THashSet(); + final GlobalSearchScope projectScope = GlobalSearchScope.allScope(myProject); + ApplicationManager.getApplication().runReadAction(new Runnable() { + public void run() { + FileBasedIndex.getInstance().processValues(IdIndex.NAME, new IdIndexEntry(word, caseSensitively), null, new FileBasedIndex.ValueProcessor() { + public boolean process(final VirtualFile file, final Integer value) { + ProgressManager.checkCanceled(); + final int mask = value.intValue(); + if ((mask & occurrenceMask) != 0) { + vFiles.add(file); + } + return true; + } + }, projectScope); + } + }); + final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); final Processor virtualFileProcessor = new Processor() { @@ -97,29 +115,14 @@ public class IndexCacheManagerImpl implements CacheManager{ } }; - final Set vFiles = new THashSet(); - final GlobalSearchScope projectScope = GlobalSearchScope.allScope(myProject); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - FileBasedIndex.getInstance().processValues(IdIndex.NAME, new IdIndexEntry(word, caseSensitively), null, new FileBasedIndex.ValueProcessor() { - public boolean process(final VirtualFile file, final Integer value) { - final int mask = value.intValue(); - if ((mask & occurrenceMask) != 0) { - vFiles.add(file); - } - return true; - } - }, projectScope); - } - }); // IMPORTANT!!! // Since implementation of virtualFileProcessor.process() may call indices dierctly or indirectly, // we cannot call it inside FileBasedIndex.processValues() method // If we do, deadlocks are possible (IDEADEV-42137). So first we obtain files with the word specified, // and then process them not holding indices' read lock. - for (VirtualFile vFile : vFiles) { + ProgressManager.checkCanceled(); if (!virtualFileProcessor.process(vFile)) { return false; } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java index 9153e01dc4d1..b7dd5cc7ddbf 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java @@ -312,7 +312,7 @@ public class FileManagerImpl implements FileManager { ApplicationManager.getApplication().assertReadAccessAllowed(); if (!vFile.isValid()) { - LOG.assertTrue(false, "Invalid file: " + vFile); + LOG.error("Invalid file: " + vFile); return null; } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java index fe97f81cca29..d8fd4fa99440 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java @@ -103,7 +103,7 @@ public class PsiSearchHelperImpl implements PsiSearchHelper { return todoPattern; } } - LOG.assertTrue(false, "Could not find matching TODO pattern for index pattern " + pattern.getPatternString()); + LOG.error("Could not find matching TODO pattern for index pattern " + pattern.getPatternString()); return null; } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SelfElementInfo.java b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SelfElementInfo.java index ae9784c0063d..d72a009ef33a 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SelfElementInfo.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SelfElementInfo.java @@ -21,7 +21,11 @@ import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; +import com.intellij.psi.PsiDocumentManager; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiManager; +import org.jetbrains.annotations.NotNull; /** * User: cdr @@ -111,7 +115,7 @@ class SelfElementInfo implements SmartPointerElementInfo { return null; } - public static PsiFile restoreFile(PsiFile file, Project project) { + public static PsiFile restoreFile(PsiFile file,@NotNull Project project) { if (file == null) return null; if (file.isValid()) return file; VirtualFile virtualFile = file.getVirtualFile(); @@ -120,7 +124,7 @@ class SelfElementInfo implements SmartPointerElementInfo { if (vParent == null || !vParent.isDirectory()) return null; String name = file.getName(); VirtualFile child = vParent.findChild(name); - if (child == null) return null; + if (child == null || !child.isValid()) return null; file = PsiManager.getInstance(project).findFile(child); if (file == null || !file.isValid()) return null; return file; diff --git a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerManagerImpl.java index ce5583246b2d..3e1a0f9da35d 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerManagerImpl.java @@ -126,7 +126,7 @@ public class SmartPointerManagerImpl extends SmartPointerManager { @NotNull public SmartPsiElementPointer createSmartPsiElementPointer(E element) { if (!element.isValid()) { - LOG.assertTrue(false, "Invalid element:" + element); + LOG.error("Invalid element:" + element); } PsiFile file = element.getContainingFile(); diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java index 987edc4db892..155c9951d2c8 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java @@ -149,10 +149,10 @@ public class CodeStyleManagerImpl extends CodeStyleManager { final PsiElement start = findElementInTreeWithFormatterEnabled(file, startOffset); final PsiElement end = findElementInTreeWithFormatterEnabled(file, endOffset); if (start != null && !start.isValid()) { - LOG.assertTrue(false, "start=" + start + "; file=" + file); + LOG.error("start=" + start + "; file=" + file); } if (end != null && !end.isValid()) { - LOG.assertTrue(false, "end=" + start + "; end=" + file); + LOG.error("end=" + start + "; end=" + file); } boolean formatFromStart = startOffset == 0; diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java b/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java index 93342a6f8877..2a21662b0a99 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java @@ -266,7 +266,7 @@ public class FileReferenceSet { private PsiFile getContainingFile() { PsiFile file = myElement.getContainingFile(); if (file == null) { - LOG.assertTrue(false, "Invalid element: " + myElement); + LOG.error("Invalid element: " + myElement); } return file.getOriginalFile(); diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/SharedImplUtil.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/SharedImplUtil.java index cc2113e6182d..f99a11945d1d 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/SharedImplUtil.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/SharedImplUtil.java @@ -85,7 +85,7 @@ public class SharedImplUtil { if (tree instanceof FileElement) return ((FileElement)tree).getCharTable(); tree = tree.getTreeParent(); } - LOG.assertTrue(false, "Invalid root element"); + LOG.error("Invalid root element"); return null; } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageManagerImpl.java index 6dbea2e861e1..a03d3c5e03b8 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageManagerImpl.java @@ -65,7 +65,7 @@ public class InjectedLanguageManagerImpl extends InjectedLanguageManager { myProject = project; myDumbService = dumbService; - final ExtensionPoint multiPoint = Extensions.getArea(project).getExtensionPoint(MULTIHOST_INJECTOR_EP_NAME); + final ExtensionPoint multiPoint = Extensions.getArea(project).getExtensionPoint(MultiHostInjector.MULTIHOST_INJECTOR_EP_NAME); multiPoint.addExtensionPointListener(new ExtensionPointListener() { public void extensionAdded(MultiHostInjector injector, @Nullable PluginDescriptor pluginDescriptor) { registerMultiHostInjector(injector); diff --git a/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateDataElementType.java b/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateDataElementType.java index 1e9b71dbcc3a..cb243e0c26b0 100644 --- a/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateDataElementType.java +++ b/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateDataElementType.java @@ -156,11 +156,11 @@ public class TemplateDataElementType extends IFileElementType implements ITempla final CharSequence buffer = lexer.getBufferSequence(); final int tokenStart = lexer.getTokenStart(); if (tokenStart < 0 || tokenStart > buffer.length()) { - LOG.assertTrue(false, "Invalid start: " + tokenStart + "; " + lexer); + LOG.error("Invalid start: " + tokenStart + "; " + lexer); } final int tokenEnd = lexer.getTokenEnd(); if (tokenEnd < 0 || tokenEnd > buffer.length()) { - LOG.assertTrue(false, "Invalid end: " + tokenEnd + "; " + lexer); + LOG.error("Invalid end: " + tokenEnd + "; " + lexer); } return new OuterLanguageElementImpl(outerElementType, table.intern(buffer, tokenStart, tokenEnd)); diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameHandlerRegistry.java b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameHandlerRegistry.java index 9d3994f7bcad..65a64ab876c1 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameHandlerRegistry.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameHandlerRegistry.java @@ -26,6 +26,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.lang.TitledHandler; import com.intellij.refactoring.util.RadioUpDownListener; +import com.intellij.util.ArrayUtil; import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.Nullable; @@ -80,7 +81,7 @@ public class RenameHandlerRegistry { } if (availableHandlers.size() == 1) return availableHandlers.values().iterator().next(); if (availableHandlers.size() > 1) { - final String[] strings = availableHandlers.keySet().toArray(new String[availableHandlers.keySet().size()]); + final String[] strings = ArrayUtil.toStringArray(availableHandlers.keySet()); final HandlersChooser chooser = new HandlersChooser(PlatformDataKeys.PROJECT.getData(dataContext), strings); chooser.show(); if (chooser.isOK()) { diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameViewDescriptor.java b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameViewDescriptor.java index 73766302979a..734d4a2ba264 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameViewDescriptor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameViewDescriptor.java @@ -63,8 +63,9 @@ class RenameViewDescriptor implements UsageViewDescriptor{ } - myProcessedElementsHeader = StringUtil.join(processedElementsHeaders.toArray(ArrayUtil.EMPTY_STRING_ARRAY),", "); - myCodeReferencesText = RefactoringBundle.message("references.in.code.to.0", StringUtil.join(codeReferences.toArray(ArrayUtil.EMPTY_STRING_ARRAY), ", ")); + myProcessedElementsHeader = StringUtil.join(ArrayUtil.toStringArray(processedElementsHeaders), ", "); + myCodeReferencesText = RefactoringBundle.message("references.in.code.to.0", StringUtil.join(ArrayUtil.toStringArray(codeReferences), + ", ")); } @NotNull diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/naming/AutomaticRenamer.java b/platform/lang-impl/src/com/intellij/refactoring/rename/naming/AutomaticRenamer.java index 7f1519cd2e7e..655afe2866c6 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/naming/AutomaticRenamer.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/naming/AutomaticRenamer.java @@ -99,13 +99,8 @@ public abstract class AutomaticRenamer { String canonicalName = nameToCanonicalName(name, element); final String newCanonicalName = suggester.suggestName(canonicalName); if (newCanonicalName.length() == 0) { - LOG.assertTrue(false, - "oldClassName = " + oldClassName + - ", newClassName = " + newClassName + - ", name = " + name + - ", canonicalName = " + canonicalName + - ", newCanonicalName = " + newCanonicalName - ); + LOG.error("oldClassName = " + oldClassName + ", newClassName = " + newClassName + ", name = " + name + ", canonicalName = " + + canonicalName + ", newCanonicalName = " + newCanonicalName); } String newName = canonicalNameToName(newCanonicalName, element); if (!newName.equals(name)) { diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/naming/NameSuggester.java b/platform/lang-impl/src/com/intellij/refactoring/rename/naming/NameSuggester.java index 0abd6dd647e2..591c57481614 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/naming/NameSuggester.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/naming/NameSuggester.java @@ -184,8 +184,8 @@ public class NameSuggester { final int propertyWordFirst = matches.get(first); if (first >= myOldClassName.length || last >= myOldClassName.length) { - LOG.assertTrue(false, "old class name = " + myOldClassNameAsGiven + ", new class name = " + myNewClassNameAsGiven + - ", propertyWords = " + Arrays.asList(propertyWords).toString()); + LOG.error("old class name = " + myOldClassNameAsGiven + ", new class name = " + myNewClassNameAsGiven + ", propertyWords = " + + Arrays.asList(propertyWords).toString()); } final String replacement = suggestReplacement(propertyWords[propertyWordFirst], newString); diff --git a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java index 224831a0bf30..621c60cdf5ff 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java @@ -321,7 +321,7 @@ public class FileBasedIndex implements ApplicationComponent { for (int attempt = 0; attempt < 2; attempt++) { try { final MapIndexStorage storage = new MapIndexStorage(IndexInfrastructure.getStorageFile(name), extension.getKeyDescriptor(), extension.getValueExternalizer(), extension.getCacheSize()); - final IndexStorage memStorage = new MemoryIndexStorage(storage); + final MemoryIndexStorage memStorage = new MemoryIndexStorage(storage); final UpdatableIndex index = createIndex(name, extension, memStorage); myIndices.put(name, new Pair, InputFilter>(index, new IndexableFilesFilter(extension.getInputFilter()))); myUnsavedDataIndexingSemaphores.put(name, new Semaphore()); @@ -382,7 +382,7 @@ public class FileBasedIndex implements ApplicationComponent { return new File(PathManager.getIndexRoot(), "work_in_progress"); } - private UpdatableIndex createIndex(final ID indexId, final FileBasedIndexExtension extension, final IndexStorage storage) throws IOException { + private UpdatableIndex createIndex(final ID indexId, final FileBasedIndexExtension extension, final MemoryIndexStorage storage) throws IOException { final MapReduceIndex index; if (extension instanceof CustomImplementationFileBasedIndexExtension) { final UpdatableIndex custom = @@ -400,7 +400,7 @@ public class FileBasedIndex implements ApplicationComponent { index.setInputIdToDataKeysIndex(new Factory>>() { public PersistentHashMap> create() { try { - return createIdToDataKeysIndex(indexId, keyDescriptor); + return createIdToDataKeysIndex(indexId, keyDescriptor, storage); } catch (IOException e) { throw new RuntimeException(e); @@ -411,9 +411,14 @@ public class FileBasedIndex implements ApplicationComponent { return index; } - private static PersistentHashMap> createIdToDataKeysIndex(ID indexId, final KeyDescriptor keyDescriptor) throws IOException { + private static PersistentHashMap> createIdToDataKeysIndex(ID indexId, + final KeyDescriptor keyDescriptor, + MemoryIndexStorage storage) throws IOException { final File indexStorageFile = IndexInfrastructure.getInputIndexStorageFile(indexId); - return new PersistentHashMap>(indexStorageFile, new EnumeratorIntegerDescriptor(), new DataExternalizer>() { + final Ref isBufferingMode = new Ref(false); + final Map> tempMap = new com.intellij.util.containers.HashMap>(); + + final DataExternalizer> dataExternalizer = new DataExternalizer>() { public void save(DataOutput out, Collection value) throws IOException { DataInputOutputUtil.writeINT(out, value.size()); for (K key : value) { @@ -429,7 +434,63 @@ public class FileBasedIndex implements ApplicationComponent { } return list; } + }; + + // Important! Update IdToDataKeysIndex depending on the sate of "buffering" flag from the MemoryStorage. + // If buffering is on, all changes should be done in memory (similar to the way it is done in memory storage). + // Otherwise data in IdToDataKeysIndex will not be in sync with the 'main' data in the index on disk and index updates will be based on the + // wrong sets of keys for the given file. This will lead to unpretictable results in main index because it will not be + // cleared properly before updating (removed data will still be present on disk). See IDEA-52223 for illustration of possible effects. + + final PersistentHashMap> map = new PersistentHashMap>( + indexStorageFile, new EnumeratorIntegerDescriptor(), dataExternalizer + ) { + + @Override + public synchronized Collection get(Integer integer) throws IOException { + if (isBufferingMode.get()) { + final Collection collection = tempMap.get(integer); + if (collection != null) { + return collection; + } + } + return super.get(integer); + } + + @Override + public synchronized void put(Integer integer, Collection ks) throws IOException { + if (isBufferingMode.get()) { + tempMap.put(integer, ks == null? Collections.emptySet() : ks); + } + else { + super.put(integer, ks); + } + } + + @Override + public synchronized void remove(Integer integer) throws IOException { + if (isBufferingMode.get()) { + tempMap.put(integer, Collections.emptySet()); + } + else { + super.remove(integer); + } + } + }; + + storage.addBufferingStateListsner(new MemoryIndexStorage.BufferingStateListener() { + public void bufferingStateChanged(boolean newState) { + synchronized (map) { + isBufferingMode.set(newState); + } + } + public void memoryStorageCleared() { + synchronized (map) { + tempMap.clear(); + } + } }); + return map; } @NonNls diff --git a/platform/lvcs-impl/lvcs-impl.iml b/platform/lvcs-impl/lvcs-impl.iml index 5d3d67900b2a..4976107b6041 100644 --- a/platform/lvcs-impl/lvcs-impl.iml +++ b/platform/lvcs-impl/lvcs-impl.iml @@ -12,9 +12,12 @@ - + + + + diff --git a/platform/lvcs-impl/src/com/intellij/history/deprecated/DeprecatedLVCS.java b/platform/lvcs-impl/src/com/intellij/history/deprecated/DeprecatedLVCS.java index f92595b2c567..19a2ccbab3ef 100644 --- a/platform/lvcs-impl/src/com/intellij/history/deprecated/DeprecatedLVCS.java +++ b/platform/lvcs-impl/src/com/intellij/history/deprecated/DeprecatedLVCS.java @@ -23,6 +23,7 @@ import com.intellij.history.LocalHistory; import com.intellij.history.LocalHistoryAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -62,7 +63,7 @@ public class DeprecatedLVCS extends LocalVcs implements ProjectComponent { } public String[] getRootPaths() { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } @Nullable diff --git a/platform/platform-api/src/com/intellij/execution/process/ProcessHandler.java b/platform/platform-api/src/com/intellij/execution/process/ProcessHandler.java index 9c8e83fffee4..e7cb96652371 100644 --- a/platform/platform-api/src/com/intellij/execution/process/ProcessHandler.java +++ b/platform/platform-api/src/com/intellij/execution/process/ProcessHandler.java @@ -58,7 +58,7 @@ public abstract class ProcessHandler extends UserDataHolderBase { myEventMulticaster.startNotified(new ProcessEvent(this)); } else { - LOG.assertTrue(false, "startNotify called already"); + LOG.error("startNotify called already"); } } diff --git a/platform/platform-api/src/com/intellij/ide/plugins/PluginManager.java b/platform/platform-api/src/com/intellij/ide/plugins/PluginManager.java index 4ba1aef918a9..ea08b49757b8 100644 --- a/platform/platform-api/src/com/intellij/ide/plugins/PluginManager.java +++ b/platform/platform-api/src/com/intellij/ide/plugins/PluginManager.java @@ -470,7 +470,7 @@ public class PluginManager { final ClassLoader loader = pluginDescriptor.getPluginClassLoader(); if (loader == null) { - getLogger().assertTrue(false, "Plugin class loader should be initialized for plugin " + id); + getLogger().error("Plugin class loader should be initialized for plugin " + id); } classLoaders.add(loader); } diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java index 354b9c02af71..fa6777ff4a20 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java @@ -406,6 +406,7 @@ public class AbstractTreeBuilder implements Disposable { @NotNull public final Set getSelectedElements() { + if (isDisposed()) return Collections.emptySet(); return getUi().getSelectedElements(); } diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java index c5fc44a8afd1..fa6bdbcfd73b 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java @@ -268,6 +268,25 @@ public class AbstractTreeUi { } } + private ActionCallback invokeLaterIfNeeded(@NotNull final Runnable runnable) { + final ActionCallback result = new ActionCallback(); + + Runnable actual = new Runnable() { + public void run() { + runnable.run(); + result.setDone(); + } + }; + + if (isPassthroughMode() || (!isEdt() && !isTreeShowing())) { + actual.run(); + } else { + UIUtil.invokeLaterIfNeeded(actual); + } + + return result; + } + public void activate(boolean byShowing) { cancelCurrentCleanupTask(); @@ -1896,13 +1915,17 @@ public class AbstractTreeUi { final Runnable finalizeRunnable = new Runnable() { public void run() { - removeLoading(node, true); - removeFromLoadedInBackground(elementFromDescriptor.get()); - removeFromLoadedInBackground(oldElementFromDescriptor); + invokeLaterIfNeeded(new Runnable() { + public void run() { + removeLoading(node, true); + removeFromLoadedInBackground(elementFromDescriptor.get()); + removeFromLoadedInBackground(oldElementFromDescriptor); - if (nodeToProcessActions[0] != null) { - processNodeActionsIfReady(nodeToProcessActions[0]); - } + if (nodeToProcessActions[0] != null) { + processNodeActionsIfReady(nodeToProcessActions[0]); + } + } + }); } }; @@ -2062,7 +2085,7 @@ public class AbstractTreeUi { List secondary = secondaryNodeAction != null ? secondaryNodeAction.get(element) : null; for (NodeAction each : actions) { if (secondary != null && secondary.contains(each)) { - secondary.remove(each); + secondary.remove(each); } each.onReady(node); } @@ -2266,7 +2289,7 @@ public class AbstractTreeUi { NodeDescriptor parentDescriptor = getDescriptorFrom(parentNode); if (parentDescriptor != null) { parentDescriptor.setChildrenSortingStamp(-1); - } + } } if (index == null) { @@ -2867,7 +2890,7 @@ public class AbstractTreeUi { final Runnable onDone, final boolean addToSelection, boolean scroll) { - _select(elements, onDone, addToSelection, true, false, scroll, false, true, true); + _select(elements, onDone, addToSelection, true, false, scroll, false, true, true); } void _select(final Object[] elements, @@ -3647,6 +3670,8 @@ public class AbstractTreeUi { if (myRequestedExpand != null && !myRequestedExpand.equals(path)) return; + //myRequestedExpand = null; + final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); if (!myUnbuiltNodes.contains(node)) { @@ -3791,7 +3816,7 @@ public class AbstractTreeUi { private Map myChanges = new HashMap(); LoadedChildren(Object[] elements) { - myElements = Arrays.asList(elements != null ? elements : new Object[0]); + myElements = Arrays.asList(elements != null ? elements : ArrayUtil.EMPTY_OBJECT_ARRAY); } void putDescriptor(Object element, NodeDescriptor descriptor, boolean isChanged) { @@ -3924,7 +3949,7 @@ public class AbstractTreeUi { } } - + public void setPassthroughMode(boolean passthrough) { myPassthroughMode = passthrough; AbstractTreeUpdater updater = getUpdater(); @@ -3967,5 +3992,5 @@ public class AbstractTreeUi { } }); } - + } diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/TreeBuilderUtil.java b/platform/platform-api/src/com/intellij/ide/util/treeView/TreeBuilderUtil.java index 89624b54605a..9493ea3539c9 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/TreeBuilderUtil.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/TreeBuilderUtil.java @@ -53,7 +53,7 @@ public class TreeBuilderUtil { final Object userObject = childNode.getUserObject(); if (tree.isPathSelected(path)) { if (!(userObject instanceof NodeDescriptor)) { - LOG.assertTrue(false, "Node: " + childNode + "; userObject: " + userObject + " of class " + userObject.getClass()); + LOG.error("Node: " + childNode + "; userObject: " + userObject + " of class " + userObject.getClass()); } selectionPaths.add(storeElementsOnly ? ((NodeDescriptor)userObject).getElement() : path); } diff --git a/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardEx.java b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardEx.java new file mode 100644 index 000000000000..b78a4b65304f --- /dev/null +++ b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardEx.java @@ -0,0 +1,148 @@ +/* + * Copyright 2000-2010 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 com.intellij.ide.wizard; + +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.Messages; +import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.wm.IdeFocusManager; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AbstractWizardEx extends AbstractWizard { + + private final String myTitle; + private final Map myStepId2Index = new HashMap(); + private final Map myIndex2Step = new HashMap(); + + public AbstractWizardEx(String title, @Nullable Project project, List steps) { + super(title, project); + myTitle = title; + + int index = 0; + for (AbstractWizardStepEx step : steps) { + myStepId2Index.put(step.getStepId(), index); + myIndex2Step.put(index, step); + addStep(step); + + step.addStepListener(new AbstractWizardStepEx.Listener() { + public void stateChanged() { + updateButtons(); + } + + public void doNextAction() { + if (getNextButton().isEnabled()) { + AbstractWizardEx.this.doNextAction(); + } + } + }); + index++; + } + + init(); + } + + protected void doPreviousAction() { + // Commit data of current step + final AbstractWizardStepEx currentStep = mySteps.get(myCurrentStep); + try { + currentStep._commitPrev(); + } + catch (final CommitStepCancelledException e) { + return; + } + catch (CommitStepException e) { + Messages.showErrorDialog(getContentPane(), e.getMessage()); + return; + } + + myCurrentStep = getPreviousStep(myCurrentStep); + updateStep(); + } + + protected void doNextAction() { + // Commit data of current step + final AbstractWizardStepEx currentStep = mySteps.get(myCurrentStep); + try { + currentStep._commit(false); + } + catch (final CommitStepCancelledException e) { + return; + } + catch (CommitStepException e) { + Messages.showErrorDialog(getContentPane(), e.getMessage()); + return; + } + + myCurrentStep = getNextStep(myCurrentStep); + updateStep(); + } + + protected int getNextStep(final int step) { + AbstractWizardStepEx stepObject = myIndex2Step.get(step); + Object nextStepId = stepObject.getNextStepId(); + return myStepId2Index.get(nextStepId); + } + + protected int getPreviousStep(final int step) { + AbstractWizardStepEx stepObject = myIndex2Step.get(step); + Object previousStepId = stepObject.getPreviousStepId(); + return myStepId2Index.get(previousStepId); + } + + protected String getHelpID() { + return null; + } + + protected void updateStep() { + super.updateStep(); + updateButtons(); + final AbstractWizardStepEx step = getCurrentStepObject(); + setTitle(myTitle + ": " + step.getTitle()); + final JComponent toFocus = step.getPreferredFocusedComponent(); + if (toFocus != null) { + IdeFocusManager.findInstanceByComponent(getWindow()).requestFocus(toFocus, true); + } + } + + private void updateButtons() { + getNextButton().setEnabled(getCurrentStepObject().isComplete() && getCurrentStepObject().getNextStepId() != null); + getPreviousButton().setEnabled(getCurrentStepObject().getPreviousStepId() != null); + getFinishButton().setEnabled(canFinish()); + } + + protected boolean canFinish() { + for (AbstractWizardStepEx step : mySteps) { + if (!step.isComplete()) { + return false; + } + } + return true; + } + + @Override + protected void dispose() { + super.dispose(); + for (AbstractWizardStepEx step : mySteps) { + Disposer.dispose(step); + } + } +} diff --git a/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java new file mode 100644 index 000000000000..8950b53a95e7 --- /dev/null +++ b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java @@ -0,0 +1,99 @@ +/* + * Copyright 2000-2010 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 com.intellij.ide.wizard; + +import com.intellij.openapi.Disposable; +import com.intellij.util.EventDispatcher; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; +import java.awt.*; + +public abstract class AbstractWizardStepEx implements Step, Disposable { + + protected enum CommitType { + Prev, Next, Finish + } + + private String myTitle; + + interface Listener extends StepListener { + void doNextAction(); + } + + private final EventDispatcher myEventDispatcher = EventDispatcher.create(Listener.class); + + public AbstractWizardStepEx(final String title) { + myTitle = title; + } + + public void _init() { + } + + public final void _commitPrev() throws CommitStepException { + commit(CommitType.Prev); + } + + public final void _commit(boolean finishChosen) throws CommitStepException { + commit(finishChosen ? CommitType.Finish : CommitType.Next); + } + + public void addStepListener(Listener listener) { + myEventDispatcher.addListener(listener); + } + + protected void setTitle(final String title) { + myTitle = title; + } + + protected void fireStateChanged() { + myEventDispatcher.getMulticaster().stateChanged(); + } + + protected void fireGoNext() { + myEventDispatcher.getMulticaster().doNextAction(); + } + + public Icon getIcon() { + return null; + } + + @NotNull + public abstract Object getStepId(); + + @Nullable + public abstract Object getNextStepId(); + + @Nullable + public abstract Object getPreviousStepId(); + + public abstract boolean isComplete(); + + protected abstract void commit(CommitType commitType) throws CommitStepException; + + public String getTitle() { + return myTitle; + } + + public void dispose() { + } + + @Nullable + public abstract JComponent getPreferredFocusedComponent(); + +} diff --git a/platform/platform-api/src/com/intellij/ide/wizard/CommitStepCancelledException.java b/platform/platform-api/src/com/intellij/ide/wizard/CommitStepCancelledException.java new file mode 100644 index 000000000000..7135a75eabb1 --- /dev/null +++ b/platform/platform-api/src/com/intellij/ide/wizard/CommitStepCancelledException.java @@ -0,0 +1,25 @@ +/* + * Copyright 2000-2010 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 com.intellij.ide.wizard; + +import com.intellij.ide.wizard.CommitStepException; + +public class CommitStepCancelledException extends CommitStepException { + public CommitStepCancelledException() { + super("User cancelled"); + } +} diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionPlaces.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionPlaces.java index 9be902f8afd7..0ec1b550cae2 100644 --- a/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionPlaces.java +++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionPlaces.java @@ -95,6 +95,8 @@ public abstract class ActionPlaces { public static final String CHANGES_VIEW_TOOLBAR = "ChangesViewToolbar"; public static final String CHANGES_VIEW_POPUP = "ChangesViewPopup"; + public static final String REMOTE_HOST_VIEW_POPUP = "RemoteHostPopup"; + public static final String REMOTE_HOST_DIALOG_POPUP = "RemoteHostDialogPopup"; private static final String[] ourToolbarPlaces = new String[]{PROJECT_VIEW_TOOLBAR, TESTTREE_VIEW_TOOLBAR, MAIN_TOOLBAR, ANT_EXPLORER_TOOLBAR, ANT_MESSAGES_TOOLBAR, COMPILER_MESSAGES_TOOLBAR, TODO_VIEW_TOOLBAR, STRUCTURE_VIEW_TOOLBAR, USAGE_VIEW_TOOLBAR, @@ -110,7 +112,7 @@ public abstract class ActionPlaces { METHOD_HIERARCHY_VIEW_POPUP, CALL_HIERARCHY_VIEW_POPUP, J2EE_ATTRIBUTES_VIEW_POPUP, J2EE_VIEW_POPUP, USAGE_VIEW_POPUP, STRUCTURE_VIEW_POPUP, TODO_VIEW_POPUP, COMPILER_MESSAGES_POPUP, ANT_MESSAGES_POPUP, ANT_EXPLORER_POPUP, UPDATE_POPUP, FILEVIEW_POPUP, CHECKOUT_POPUP, LVCS_DIRECTORY_HISTORY_POPUP, GUI_DESIGNER_EDITOR_POPUP, GUI_DESIGNER_COMPONENT_TREE_POPUP, GUI_DESIGNER_PROPERTY_INSPECTOR_POPUP, - CREATE_EJB_POPUP, CHANGES_VIEW_POPUP, + CREATE_EJB_POPUP, CHANGES_VIEW_POPUP, REMOTE_HOST_VIEW_POPUP, REMOTE_HOST_DIALOG_POPUP, }; public static boolean isPopupPlace(@NotNull String place) { diff --git a/platform/platform-api/src/com/intellij/openapi/fileTypes/MockFileTypeManager.java b/platform/platform-api/src/com/intellij/openapi/fileTypes/MockFileTypeManager.java index 080b51c8fd5e..5605c68d3d0f 100644 --- a/platform/platform-api/src/com/intellij/openapi/fileTypes/MockFileTypeManager.java +++ b/platform/platform-api/src/com/intellij/openapi/fileTypes/MockFileTypeManager.java @@ -20,6 +20,7 @@ package com.intellij.openapi.fileTypes; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -64,7 +65,7 @@ class MockFileTypeManager extends FileTypeManager { @NotNull @Override public String[] getAssociatedExtensions(@NotNull FileType type) { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } @NotNull diff --git a/platform/platform-api/src/com/intellij/openapi/roots/ui/util/CompositeAppearance.java b/platform/platform-api/src/com/intellij/openapi/roots/ui/util/CompositeAppearance.java index eb9b280b865e..1f9112f016de 100644 --- a/platform/platform-api/src/com/intellij/openapi/roots/ui/util/CompositeAppearance.java +++ b/platform/platform-api/src/com/intellij/openapi/roots/ui/util/CompositeAppearance.java @@ -68,7 +68,7 @@ public class CompositeAppearance implements ModifiableCellAppearance { for (Iterator iterator = mySections.iterator(); iterator.hasNext();) { TextSection textSection = iterator.next(); if (textSection == null) { - LOG.assertTrue(false, "index: " + index + " size: " + mySections.size()); + LOG.error("index: " + index + " size: " + mySections.size()); iterator.remove(); } } diff --git a/platform/platform-api/src/com/intellij/ui/ListUtil.java b/platform/platform-api/src/com/intellij/ui/ListUtil.java index dc3c86baac34..66a380463143 100644 --- a/platform/platform-api/src/com/intellij/ui/ListUtil.java +++ b/platform/platform-api/src/com/intellij/ui/ListUtil.java @@ -268,7 +268,7 @@ public class ListUtil { if (model instanceof FilteringListModel) return FILTERED_MODEL; if (model == null) LOG.assertTrue(false); - else LOG.assertTrue(false, "Unknown model class: " + model.getClass().getName()); + else LOG.error("Unknown model class: " + model.getClass().getName()); return null; } diff --git a/platform/platform-api/src/com/intellij/ui/table/BaseTableView.java b/platform/platform-api/src/com/intellij/ui/table/BaseTableView.java index 59a0643d45ee..f58b24c6e381 100644 --- a/platform/platform-api/src/com/intellij/ui/table/BaseTableView.java +++ b/platform/platform-api/src/com/intellij/ui/table/BaseTableView.java @@ -101,8 +101,7 @@ public abstract class BaseTableView extends Table { final int modelIndex = column.getModelIndex(); storage.put(orderPropertyName(i), String.valueOf(modelIndex)); if (storedColumns[modelIndex]) { - LOG.assertTrue(false, - "columnCount: " + columnCount + " current: " + i + " modelINdex: " + modelIndex); + LOG.error("columnCount: " + columnCount + " current: " + i + " modelINdex: " + modelIndex); } storedColumns[modelIndex] = true; } @@ -160,7 +159,7 @@ public abstract class BaseTableView extends Table { for (int i = 0; i < model.getColumnCount(); i++) if (model.getColumn(i).getModelIndex() == index) return i; - LOG.assertTrue(false, "Total: " + model.getColumnCount() + " index: "+ index); + LOG.error("Total: " + model.getColumnCount() + " index: " + index); return index; } } diff --git a/platform/platform-impl/platform-impl.iml b/platform/platform-impl/platform-impl.iml index 3f163f7e753d..dd72340ad855 100644 --- a/platform/platform-impl/platform-impl.iml +++ b/platform/platform-impl/platform-impl.iml @@ -23,7 +23,8 @@ - + + diff --git a/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java b/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java index 4ad3015d48fe..6f66e323ef01 100644 --- a/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java +++ b/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java @@ -234,7 +234,7 @@ public class IdeEventQueue extends EventQueue { synchronized (myLock) { final boolean wasRemoved = myIdleListeners.remove(runnable); if (!wasRemoved) { - LOG.assertTrue(false, "unknown runnable: " + runnable); + LOG.error("unknown runnable: " + runnable); } final MyFireIdleRequest request = myListener2Request.remove(runnable); LOG.assertTrue(request != null); @@ -260,7 +260,7 @@ public class IdeEventQueue extends EventQueue { synchronized (myLock) { final boolean wasRemoved = myActivityListeners.remove(runnable); if (!wasRemoved) { - LOG.assertTrue(false, "unknown runnable: " + runnable); + LOG.error("unknown runnable: " + runnable); } } } diff --git a/platform/platform-impl/src/com/intellij/ide/ToolkitBugsProcessor.java b/platform/platform-impl/src/com/intellij/ide/ToolkitBugsProcessor.java index 660ac475114b..b7de602e4ab3 100644 --- a/platform/platform-impl/src/com/intellij/ide/ToolkitBugsProcessor.java +++ b/platform/platform-impl/src/com/intellij/ide/ToolkitBugsProcessor.java @@ -114,6 +114,21 @@ public class ToolkitBugsProcessor { } } + static class Sun_6785663 extends Handler { + Sun_6785663() { + super("Numbus L&F problem -- update style"); + } + + @Override + boolean process(Throwable e, StackTraceElement[] stack) { + if (e instanceof ClassCastException && stack.length > 1) { + return stack[0].getClassName().equals("javax.swing.plaf.synth.SynthButtonUI") + && stack[0].getMethodName().equals("updateStyle"); + } + return false; + } + } + static class Apple_ExceptionOnChangingMonitors extends Handler { @Override diff --git a/platform/platform-impl/src/com/intellij/ide/actions/ShowFilePathAction.java b/platform/platform-impl/src/com/intellij/ide/actions/ShowFilePathAction.java index a29a74d0d65f..6f030082eeb8 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/ShowFilePathAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/ShowFilePathAction.java @@ -32,6 +32,7 @@ import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.awt.RelativePoint; +import com.intellij.util.ArrayUtil; import com.intellij.util.ui.EmptyIcon; import org.jetbrains.annotations.NotNull; @@ -174,7 +175,7 @@ public class ShowFilePathAction extends AnAction { try { File parent = ioFile.getParentFile(); if (parent != null) { - Runtime.getRuntime().exec(cmd + " " + path, new String[0], parent); + Runtime.getRuntime().exec(cmd + " " + path, ArrayUtil.EMPTY_STRING_ARRAY, parent); } else { Runtime.getRuntime().exec(cmd + " " + path); } diff --git a/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java b/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java index 1e56ad0dc092..d2ec4fb49caa 100644 --- a/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java +++ b/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java @@ -21,9 +21,11 @@ import com.intellij.ide.errorTreeView.impl.ErrorTreeViewConfiguration; import com.intellij.ide.errorTreeView.impl.ErrorViewTextExporter; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.ide.CopyPasteManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.IconLoader; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.Navigatable; import com.intellij.ui.AutoScrollToSourceHandler; @@ -42,11 +44,12 @@ import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import java.awt.*; +import java.awt.datatransfer.StringSelection; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.List; -public class NewErrorTreeViewPanel extends JPanel implements DataProvider, OccurenceNavigator, MutableErrorTreeView { +public class NewErrorTreeViewPanel extends JPanel implements DataProvider, OccurenceNavigator, MutableErrorTreeView, CopyProvider { protected static final Logger LOG = Logger.getInstance("#com.intellij.ide.errorTreeView.NewErrorTreeViewPanel"); private String myProgressText = ""; private final boolean myCreateExitAction; @@ -158,10 +161,29 @@ public class NewErrorTreeViewPanel extends JPanel implements DataProvider, Occur Disposer.dispose(myBuilder); } + public void performCopy(DataContext dataContext) { + final ErrorTreeNodeDescriptor descriptor = getSelectedNodeDescriptor(); + if (descriptor != null) { + final String[] lines = descriptor.getElement().getText(); + CopyPasteManager.getInstance().setContents(new StringSelection(StringUtil.join(lines, "\n"))); + } + } + + public boolean isCopyEnabled(DataContext dataContext) { + return getSelectedNodeDescriptor() != null; + } + + public boolean isCopyVisible(DataContext dataContext) { + return true; + } + public Object getData(String dataId) { + if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) { + return this; + } if (PlatformDataKeys.NAVIGATABLE.is(dataId)) { final NavigatableMessageElement selectedMessageElement = getSelectedMessageElement(); - return selectedMessageElement != null? selectedMessageElement.getNavigatable() : null; + return selectedMessageElement != null ? selectedMessageElement.getNavigatable() : null; } else if (PlatformDataKeys.HELP_ID.is(dataId)) { return myHelpId; @@ -174,7 +196,7 @@ public class NewErrorTreeViewPanel extends JPanel implements DataProvider, Occur } else if (CURRENT_EXCEPTION_DATA_KEY.is(dataId)) { NavigatableMessageElement selectedMessageElement = getSelectedMessageElement(); - return selectedMessageElement != null? selectedMessageElement.getData() : null; + return selectedMessageElement != null ? selectedMessageElement.getData() : null; } return null; } @@ -289,6 +311,7 @@ public class NewErrorTreeViewPanel extends JPanel implements DataProvider, Occur if (getData(PlatformDataKeys.NAVIGATABLE.getName()) != null) { group.add(ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_SOURCE)); } + group.add(ActionManager.getInstance().getAction(IdeActions.ACTION_COPY)); addExtraPopupMenuActions(group); ActionPopupMenu menu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.COMPILER_MESSAGES_POPUP, group); diff --git a/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java b/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java index 775f44ab6b83..649f6708c328 100644 --- a/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java @@ -290,8 +290,8 @@ public class DataManagerImpl extends DataManager implements ApplicationComponent myEventCount + "; current event count = " + currentEventCount ); */ - LOG.assertTrue(false, "cannot share data context between Swing events; initial event count = " + myEventCount + - "; current event count = " + currentEventCount); + LOG.error("cannot share data context between Swing events; initial event count = " + myEventCount + "; current event count = " + + currentEventCount); } Component _component = myRef.get(); diff --git a/platform/platform-impl/src/com/intellij/ide/impl/DataValidator.java b/platform/platform-impl/src/com/intellij/ide/impl/DataValidator.java index a2e4e3f4062f..c2b0462573ab 100644 --- a/platform/platform-impl/src/com/intellij/ide/impl/DataValidator.java +++ b/platform/platform-impl/src/com/intellij/ide/impl/DataValidator.java @@ -85,8 +85,8 @@ public abstract class DataValidator { public T[] findInvalid(final String dataId, T[] array, final Object dataSource) { for (T element : array) { if (element == null) { - LOG.assertTrue(false, "Data isn't valid. " + dataId + "=null Provided by: " + dataSource.getClass().getName() + - " (" + dataSource.toString() + ")"); + LOG.error( + "Data isn't valid. " + dataId + "=null Provided by: " + dataSource.getClass().getName() + " (" + dataSource.toString() + ")"); } T invalid = myElementValidator.findInvalid(dataId, element, dataSource); if (invalid != null) { diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java index 520db075c1ad..77aefc9eb471 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java @@ -839,7 +839,7 @@ public final class ActionManagerImpl extends ActionManagerEx implements Applicat private static void assertActionIsGroupOrStub(final AnAction action) { if (!(action instanceof ActionGroup || action instanceof ActionStub)) { - LOG.assertTrue(false, "Action : "+action + "; class: "+action.getClass()); + LOG.error("Action : " + action + "; class: " + action.getClass()); } } @@ -1145,10 +1145,7 @@ public final class ActionManagerImpl extends ActionManagerEx implements Applicat } public void removeTimerListener(TimerListener listener){ - final boolean removed = myTimerListeners.remove(listener); - if (!removed) { - LOG.assertTrue(false, "Unknown listener " + listener); - } + myTimerListeners.remove(listener); } public void actionPerformed(ActionEvent e) { @@ -1163,10 +1160,16 @@ public final class ActionManagerImpl extends ActionManagerEx implements Applicat return; } - TimerListener[] listeners = myTimerListeners.toArray(new TimerListener[myTimerListeners.size()]); - for (TimerListener listener : listeners) { - runListenerAction(listener); - } + final TimerListener[] listeners = myTimerListeners.toArray(new TimerListener[myTimerListeners.size()]); + IdeFocusManager.getInstance(null).doWhenFocusSettlesDown(new Runnable() { + public void run() { + for (TimerListener listener : listeners) { + if (myTimerListeners.contains(listener)) { + runListenerAction(listener); + } + } + } + }); } private void runListenerAction(final TimerListener listener) { diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java index 0f444fb37a8b..6c537cb7bcba 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java @@ -99,7 +99,7 @@ public class Utils{ AnAction child = children[i]; if (child == null) { String groupId = ActionManager.getInstance().getId(group); - LOG.assertTrue(false, "action is null: i=" + i + " group=" + group + " group id=" + groupId); + LOG.error("action is null: i=" + i + " group=" + group + " group id=" + groupId); continue; } diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/ComponentStoreImpl.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/ComponentStoreImpl.java index f40da2a5825b..341d3d3caf24 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/ComponentStoreImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/ComponentStoreImpl.java @@ -348,7 +348,7 @@ abstract class ComponentStoreImpl implements IComponentStore { private static String getComponentName(@NotNull final PersistentStateComponent persistentStateComponent) { final State stateSpec = getStateSpec(persistentStateComponent); if (stateSpec == null) { - LOG.assertTrue(false, "Null state spec for " + persistentStateComponent); + LOG.error("Null state spec for " + persistentStateComponent); } return stateSpec.name(); } diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java index 30f4261ec00a..cfda7c873e1b 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java @@ -27,6 +27,7 @@ import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.ArrayUtil; import com.intellij.util.containers.MultiMap; import com.intellij.util.io.fs.IFile; import org.jdom.Document; @@ -363,7 +364,7 @@ public abstract class StateStorageManagerImpl implements StateStorageManager, Di } public String[] listSubFiles(final String fileSpec) { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } public boolean isEnabled() { diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/MergeList.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/MergeList.java index 24a24125fd66..eae0f578e829 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/MergeList.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/MergeList.java @@ -90,7 +90,7 @@ public class MergeList implements ChangeList.Parent, UserDataHolder { rightChanges.add(SimpleChange.fromRanges(ranges[1], new TextRange(rightTextLength, rightTextLength), mergeList.myChanges[1])); leftChanges.add(SimpleChange.fromRanges(ranges[1], new TextRange(leftTextLength, leftTextLength), mergeList.myChanges[0])); } else { - LOG.assertTrue(false, "Left Text: " + leftText + "\n" + "Right Text: " + rightText + "\nBase Text: " + baseText); + LOG.error("Left Text: " + leftText + "\n" + "Right Text: " + rightText + "\nBase Text: " + baseText); } } else { rightChanges.add(SimpleChange.fromRanges(ranges[1], ranges[2], mergeList.myChanges[1])); @@ -98,7 +98,7 @@ public class MergeList implements ChangeList.Parent, UserDataHolder { } else if (ranges[2] == null) { if (ranges[0] == null) { - LOG.assertTrue(false, "Left Text: " + leftText + "\n" + "Right Text: " + rightText + "\nBase Text: " + baseText); + LOG.error("Left Text: " + leftText + "\n" + "Right Text: " + rightText + "\nBase Text: " + baseText); } leftChanges.add(SimpleChange.fromRanges(ranges[1], ranges[0], mergeList.myChanges[0])); } diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/processing/PreferWholeLines.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/processing/PreferWholeLines.java index edcac10b3e3b..2a6a01c10414 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/processing/PreferWholeLines.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/processing/PreferWholeLines.java @@ -30,8 +30,7 @@ class PreferWholeLines implements DiffCorrection { DiffFragment nextFragment = fragments[i + 1]; FragmentSide side = FragmentSide.chooseSide(fragment); if (nextFragment.isOneSide()) { - LOG.assertTrue(false, - "<" + side.getText(fragment) + "> <" + side.getOtherText(nextFragment) + ">"); + LOG.error("<" + side.getText(fragment) + "> <" + side.getOtherText(nextFragment) + ">"); } if (StringUtil.startsWithChar(side.getText(fragment), '\n') && StringUtil.startsWithChar(side.getText(nextFragment), '\n') && diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java index f0b00ade31cd..143acf9b0642 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java @@ -2041,7 +2041,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi if (fontType == Font.ITALIC) return myItalicFontMetrics; if (fontType == Font.BOLD + Font.ITALIC) return myBoldItalicFontMetrics; - LOG.assertTrue(false, "Unknown font type: " + fontType); + LOG.error("Unknown font type: " + fontType); return myPlainFontMetrics; } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java index 991663561e71..1c216b9ae3ba 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java @@ -60,6 +60,8 @@ import java.util.List; import java.util.Map; public class FileChooserDialogImpl extends DialogWrapper implements FileChooserDialog, FileLookup { + public static final DataKey PREFER_LAST_OVER_TO_SELECT = DataKey.create("PREFER_LAST_OVER_TO_SELECT"); + private final FileChooserDescriptor myChooserDescriptor; protected FileSystemTreeImpl myFileSystemTree; @@ -106,7 +108,8 @@ public class FileChooserDialogImpl extends DialogWrapper implements FileChooserD selectFile = project.getBaseDir(); } } else { - selectFile = (toSelect == null) ? ourLastFile : toSelect; + selectFile = (toSelect == null) ? ourLastFile : (ourLastFile == null ? toSelect : myChooserDescriptor.getUserData( + PREFER_LAST_OVER_TO_SELECT.getName()) == null ? toSelect : ourLastFile); } final VirtualFile file = selectFile; diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java index 4c034522dac0..619ae78e7d40 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java @@ -125,7 +125,7 @@ public final class EditorHistoryManager extends AbstractProjectComponent impleme final FileEditor[] editors = editorsWithProviders.getFirst(); final FileEditorProvider[] oldProviders = editorsWithProviders.getSecond(); if (editors.length <= 0) { - LOG.assertTrue(false, "No editors for file " + file.getPresentableUrl()); + LOG.error("No editors for file " + file.getPresentableUrl()); } final FileEditor selectedEditor = editorManager.getSelectedEditor(file); LOG.assertTrue(selectedEditor != null); diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java index 0953b839cf6d..3041414f2323 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java @@ -148,7 +148,7 @@ public final class EditorsSplitters extends JPanel { return res; } else { - LOG.assertTrue(false, comp != null ? comp.getClass().getName() : null); + LOG.error(comp != null ? comp.getClass().getName() : null); return null; } } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java index 8d9b4420803a..5e254c62d420 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java @@ -54,7 +54,7 @@ import java.util.regex.Pattern; */ public class FileTypeManagerImpl extends FileTypeManagerEx implements NamedJDOMExternalizable, ExportableApplicationComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl"); - private static final int VERSION = 6; + private static final int VERSION = 7; private final Set myDefaultTypes = new THashSet(); private final ArrayList mySpecialFileTypes = new ArrayList(); @@ -521,9 +521,13 @@ public class FileTypeManagerImpl extends FileTypeManagerEx implements NamedJDOME if (savedVersion < 5) { addIgnore("*.hprof"); } - if (savedVersion < VERSION) { + if (savedVersion < 6) { addIgnore("_svn"); } + + if (savedVersion < VERSION) { + addIgnore(".hg"); + } } private void readGlobalMappings(final Element e) { diff --git a/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java b/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java index bfd46bad00cc..b2b1c86543bc 100644 --- a/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java @@ -308,7 +308,7 @@ public class DumbServiceImpl extends DumbService { final IndexUpdateRunnable nextUpdateRunnable = myUpdatesQueue.pullFirst(); // run next action under already existing progress indicator if (!myActionQueue.offer(new Ref(nextUpdateRunnable.myAction))) { - LOG.assertTrue(false, "Action queue rejected next updateRunnable!"); + LOG.error("Action queue rejected next updateRunnable!"); nextUpdateRunnable.run(); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java index 7b79cd58ffe3..66d976010ac4 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java @@ -15,6 +15,8 @@ */ package com.intellij.openapi.vfs.impl.win32; +import com.intellij.util.ArrayUtil; + import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; @@ -40,7 +42,7 @@ public class Win32Kernel { FileInfo[] fileInfos = myKernel.listChildren(absolutePath.replace('/', '\\') + "\\*.*"); if (fileInfos == null) { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } ArrayList names = new ArrayList(fileInfos.length); for (int i = 0, fileInfosLength = fileInfos.length; i < fileInfosLength; i++) { @@ -56,7 +58,7 @@ public class Win32Kernel { names.add(info.name); } - return names.toArray(new String[names.size()]); + return ArrayUtil.toStringArray(names); } public boolean exists(String path) { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java index c5f0c2ad7402..85acb08387d0 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java @@ -37,6 +37,7 @@ import com.intellij.openapi.wm.WindowManagerListener; import com.intellij.openapi.wm.ex.StatusBarEx; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.util.Alarm; +import com.intellij.util.ArrayUtil; import com.intellij.util.EventDispatcher; import com.intellij.util.ui.UIUtil; import com.sun.jna.examples.WindowUtils; @@ -446,8 +447,8 @@ public final class WindowManagerImpl extends WindowManagerEx implements Applicat frame.setProject(project); } else { - frame = new IdeFrameImpl((ApplicationInfoEx)ApplicationInfo.getInstance(), ActionManager.getInstance(), UISettings.getInstance(), DataManager.getInstance(), - KeymapManager.getInstance(), ApplicationManager.getApplication(), new String[0]); + frame = new IdeFrameImpl((ApplicationInfoEx)ApplicationInfo.getInstance(), ActionManager.getInstance(), UISettings.getInstance(), + DataManager.getInstance(), KeymapManager.getInstance(), ApplicationManager.getApplication(), ArrayUtil.EMPTY_STRING_ARRAY); if (myFrameBounds != null) { frame.setBounds(myFrameBounds); } diff --git a/platform/platform-impl/src/com/intellij/platform/NewDirectoryProjectDialog.java b/platform/platform-impl/src/com/intellij/platform/NewDirectoryProjectDialog.java index da3416d95878..64eb4d849083 100644 --- a/platform/platform-impl/src/com/intellij/platform/NewDirectoryProjectDialog.java +++ b/platform/platform-impl/src/com/intellij/platform/NewDirectoryProjectDialog.java @@ -110,7 +110,7 @@ public class NewDirectoryProjectDialog extends DialogWrapper { } } - private static String getBaseDir() { + public static String getBaseDir() { final String lastProjectLocation = GeneralSettings.getInstance().getLastProjectLocation(); if (lastProjectLocation != null) { return lastProjectLocation.replace('/', File.separatorChar); diff --git a/platform/platform-impl/src/com/intellij/ui/EditorComboBox.java b/platform/platform-impl/src/com/intellij/ui/EditorComboBox.java index 1d701013e79c..5b320c544bed 100644 --- a/platform/platform-impl/src/com/intellij/ui/EditorComboBox.java +++ b/platform/platform-impl/src/com/intellij/ui/EditorComboBox.java @@ -29,6 +29,7 @@ import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.TextComponentAccessor; +import com.intellij.util.ArrayUtil; import javax.swing.*; import java.awt.*; @@ -199,7 +200,7 @@ public class EditorComboBox extends JComboBox implements DocumentListener { objects.add(itemAt); } } - setModel(new DefaultComboBoxModel(objects.toArray(new Object[objects.size()]))); + setModel(new DefaultComboBoxModel(ArrayUtil.toObjectArray(objects))); } private class MyEditor implements ComboBoxEditor { diff --git a/platform/platform-impl/src/com/intellij/util/PendingEventDispatcher.java b/platform/platform-impl/src/com/intellij/util/PendingEventDispatcher.java index adffad01cf50..e70784de9bdb 100644 --- a/platform/platform-impl/src/com/intellij/util/PendingEventDispatcher.java +++ b/platform/platform-impl/src/com/intellij/util/PendingEventDispatcher.java @@ -171,8 +171,7 @@ public class PendingEventDispatcher { private void dispatch(Method method, Object[] args) { assertDispatchThread(); if(myCurrentDispatchMethod != null) { - LOG.assertTrue(false, - "Event cannot be raised when dispatching another event is in progress. Dispatching " + myCurrentDispatchMethod.getName()); + LOG.error("Event cannot be raised when dispatching another event is in progress. Dispatching " + myCurrentDispatchMethod.getName()); } method.setAccessible(true); diff --git a/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java b/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java index ef11b2a03cf7..483e421ef8e2 100644 --- a/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java +++ b/platform/platform-impl/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java @@ -1,6 +1,7 @@ package com.intellij.ide.util.treeView; import com.intellij.openapi.progress.ProcessCanceledException; +import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; import com.intellij.util.Time; @@ -1341,6 +1342,35 @@ public class TreeUiTest extends AbstractTreeBuilderTest { }); } + public void testStickyLoadingNodeIssue() throws Exception { + buildStructure(myRoot); + + final boolean[] done = new boolean[] {false}; + getBuilder().select(new NodeElement("jetbrains"), new Runnable() { + public void run() { + getBuilder().expand(new NodeElement("fabrique"), new Runnable() { + public void run() { + done[0] = true; + } + }); + } + }); + + waitBuilderToCome(new Condition() { + public boolean value(Object o) { + return done[0]; + } + }); + + assertTree("-/\n" + + " +com\n" + + " -[jetbrains]\n" + + " -fabrique\n" + + " ide\n" + + " +org\n" + + " +xunit\n"); + } + public void testReleaseBuilderDuringGetChildren() throws Exception { assertReleaseDuringBuilding("getChildren", "fabrique", new Runnable() { public void run() { @@ -1463,6 +1493,10 @@ public class TreeUiTest extends AbstractTreeBuilderTest { //todo } + @Override + public void testStickyLoadingNodeIssue() throws Exception { + super.testStickyLoadingNodeIssue(); + } } public static TestSuite suite() { diff --git a/platform/platform-impl/testSrc/com/intellij/openapi/execution/ParametersListTest.java b/platform/platform-impl/testSrc/com/intellij/openapi/execution/ParametersListTest.java index 3dc85de6c6c4..d792a353759e 100644 --- a/platform/platform-impl/testSrc/com/intellij/openapi/execution/ParametersListTest.java +++ b/platform/platform-impl/testSrc/com/intellij/openapi/execution/ParametersListTest.java @@ -38,7 +38,7 @@ public class ParametersListTest extends TestCase { private void checkTokenizer(String parmsString, String[] expected) { ParametersList params = new ParametersList(); params.addParametersString(parmsString); - String[] strings = params.getList().toArray(ArrayUtil.EMPTY_STRING_ARRAY); + String[] strings = ArrayUtil.toStringArray(params.getList()); CHECK.compareAll(expected, strings); } } diff --git a/platform/platform-resources-en/src/messages/XmlBundle.properties b/platform/platform-resources-en/src/messages/XmlBundle.properties index da7f5bcc334a..eb375b8b92f5 100644 --- a/platform/platform-resources-en/src/messages/XmlBundle.properties +++ b/platform/platform-resources-en/src/messages/XmlBundle.properties @@ -159,6 +159,9 @@ browser.path.not.specified=Please, set the path to the browser at Settings / Web browser.path.not.specified.title=Browser Path Was Not Specified browser.error=Browser Error web.editor.configuration.title=Web +action.OpenInBrowser.text=Open in _Browser +action.open.file.in.browser.description=Open a selected file in browser + xml.split.tag.intention.action=Split current tag tag.name.completion.hint=Press {0} to view tags from other namespaces diff --git a/platform/platform-resources/src/META-INF/XmlPlugin.xml b/platform/platform-resources/src/META-INF/XmlPlugin.xml index 4142e22f93c1..f05c4d4b8309 100644 --- a/platform/platform-resources/src/META-INF/XmlPlugin.xml +++ b/platform/platform-resources/src/META-INF/XmlPlugin.xml @@ -304,11 +304,17 @@ - + + + + + + diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/TestSuiteStack.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/TestSuiteStack.java index 7887db9c3c7c..9033ed9ea731 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/TestSuiteStack.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/TestSuiteStack.java @@ -55,13 +55,16 @@ public class TestSuiteStack { @NotNull public SMTestProxy popSuite(final String suiteName) throws EmptyStackException { if (myStack.isEmpty()) { - LOG.assertTrue(false, "Pop error: Test runner tried to close test suite which has been already closed or wasn't started at all. Unexpected suite name [" + suiteName + "]"); + LOG.error( + "Pop error: Test runner tried to close test suite which has been already closed or wasn't started at all. Unexpected suite name [" + + suiteName + "]"); return null; } final SMTestProxy currentSuite = myStack.pop(); if (!suiteName.equals(currentSuite.getName())) { - LOG.assertTrue(false, "Pop error: Unexpected closing suite. Expected [" + suiteName + "] but [" + currentSuite.getName() + "] was found. Rest of stack: " + getSuitePathPresentation()); + LOG.error("Pop error: Unexpected closing suite. Expected [" + suiteName + "] but [" + currentSuite.getName() + + "] was found. Rest of stack: " + getSuitePathPresentation()); return null; } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsTableModel.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsTableModel.java index 274dcba28801..dfd0ba5b6685 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsTableModel.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsTableModel.java @@ -136,7 +136,7 @@ public class StatisticsTableModel extends ListTableModel { public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) { // Setting value is prevented! - LOG.assertTrue(false, "value: " + aValue + " row: " + rowIndex + " column: " + columnIndex); + LOG.error("value: " + aValue + " row: " + rowIndex + " column: " + columnIndex); } @Nullable diff --git a/platform/testFramework/src/com/intellij/TestAll.java b/platform/testFramework/src/com/intellij/TestAll.java index 400b30f5c7e6..9ebb97e8d49f 100644 --- a/platform/testFramework/src/com/intellij/TestAll.java +++ b/platform/testFramework/src/com/intellij/TestAll.java @@ -31,6 +31,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl; import com.intellij.testFramework.*; +import com.intellij.util.ArrayUtil; import junit.framework.*; import java.io.File; @@ -296,8 +297,8 @@ public class TestAll implements Test { if ((testCaseClass.getModifiers() & Modifier.PUBLIC) == 0) return null; try { - Method suiteMethod = testCaseClass.getMethod("suite", new Class[0]); - return (Test)suiteMethod.invoke(null, new Class[0]); + Method suiteMethod = testCaseClass.getMethod("suite", ArrayUtil.EMPTY_CLASS_ARRAY); + return (Test)suiteMethod.invoke(null, ArrayUtil.EMPTY_CLASS_ARRAY); } catch (NoSuchMethodException e) { if (TestRunnerUtil.isJUnit4TestClass(testCaseClass)) { diff --git a/platform/testFramework/src/com/intellij/mock/MockLocalFileSystem.java b/platform/testFramework/src/com/intellij/mock/MockLocalFileSystem.java index 2e47322919f8..38917d86fd50 100644 --- a/platform/testFramework/src/com/intellij/mock/MockLocalFileSystem.java +++ b/platform/testFramework/src/com/intellij/mock/MockLocalFileSystem.java @@ -185,7 +185,7 @@ public class MockLocalFileSystem extends LocalFileSystem { } public String[] list(final VirtualFile file) { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } public VirtualFile[] listFiles(final VirtualFile file) { diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java index e0c0b24009cf..800f286f6b6f 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java @@ -29,6 +29,7 @@ import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Alarm; +import com.intellij.util.ArrayUtil; import com.intellij.util.SystemProperties; import com.intellij.util.ui.UIUtil; import junit.framework.Assert; @@ -230,7 +231,7 @@ public class PlatformTestUtil { if (comparator != null) { ArrayList list = new ArrayList(Arrays.asList(children)); Collections.sort(list, comparator); - children = list.toArray(new Object[list.size()]); + children = ArrayUtil.toObjectArray(list); } for (Object child : children) { currentLine = doPrint(buffer, currentLevel + 1, child, structure, comparator, maxRowCount, currentLine, paddingChar); diff --git a/platform/usageView/src/com/intellij/usages/UsageInfo2UsageAdapter.java b/platform/usageView/src/com/intellij/usages/UsageInfo2UsageAdapter.java index 06ce759a280f..7d10f844cf4b 100644 --- a/platform/usageView/src/com/intellij/usages/UsageInfo2UsageAdapter.java +++ b/platform/usageView/src/com/intellij/usages/UsageInfo2UsageAdapter.java @@ -84,8 +84,7 @@ public class UsageInfo2UsageAdapter implements UsageInModule, UsageInLibrary, Us myLineNumber = getLineNumber(document, startOffset); if (endOffset > document.getTextLength()) { - LOG.assertTrue(false, - "Invalid usage info, psiElement:" + element + " end offset: " + endOffset + " psiFile: " + psiFile.getName()); + LOG.error("Invalid usage info, psiElement:" + element + " end offset: " + endOffset + " psiFile: " + psiFile.getName()); } myRangeMarkers.add(document.createRangeMarker(startOffset, endOffset)); diff --git a/platform/util/src/com/intellij/openapi/diagnostic/Logger.java b/platform/util/src/com/intellij/openapi/diagnostic/Logger.java index 4ed1375bb24a..e86bbe89e9f6 100644 --- a/platform/util/src/com/intellij/openapi/diagnostic/Logger.java +++ b/platform/util/src/com/intellij/openapi/diagnostic/Logger.java @@ -47,6 +47,9 @@ public abstract class Logger { public void error(@NonNls String message) { error(message, new Throwable(), ArrayUtil.EMPTY_STRING_ARRAY); } + public void error(Object message) { + error(String.valueOf(message)); + } public void error(@NonNls String message, @NonNls String... details) { error(message, new Throwable(), details); diff --git a/platform/util/src/com/intellij/openapi/diff/impl/highlighting/Util.java b/platform/util/src/com/intellij/openapi/diff/impl/highlighting/Util.java index d0e72eff5b23..1356eb6d20af 100644 --- a/platform/util/src/com/intellij/openapi/diff/impl/highlighting/Util.java +++ b/platform/util/src/com/intellij/openapi/diff/impl/highlighting/Util.java @@ -72,7 +72,7 @@ public class Util { String[] lines1 = splitByLines(fragment.getText1()); String[] lines2 = splitByLines(fragment.getText2()); if (lines1 != null && lines2 != null && lines1.length != lines2.length) { - LOG.assertTrue(false, "1:<" + fragment.getText1() + "> 2:<" + fragment.getText2() + ">"); + LOG.error("1:<" + fragment.getText1() + "> 2:<" + fragment.getText2() + ">"); } int length = lines1 == null ? lines2.length : lines1.length; DiffFragment[] lines = new DiffFragment[length]; diff --git a/platform/util/src/com/intellij/openapi/util/IconLoader.java b/platform/util/src/com/intellij/openapi/util/IconLoader.java index ded2a4dc6776..5ce17117a722 100644 --- a/platform/util/src/com/intellij/openapi/util/IconLoader.java +++ b/platform/util/src/com/intellij/openapi/util/IconLoader.java @@ -170,7 +170,7 @@ public final class IconLoader { Icon disabledIcon = ourIcon2DisabledIcon.get(icon); if (disabledIcon == null) { if (!ImageLoader.isGoodSize(icon)) { - LOG.error(icon.toString()); // # 22481 + LOG.error(icon); // # 22481 return EMPTY_ICON; } final BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); diff --git a/platform/util/src/com/intellij/openapi/util/JDOMExternalizer.java b/platform/util/src/com/intellij/openapi/util/JDOMExternalizer.java index d6ebe99e9253..72dc236f0935 100644 --- a/platform/util/src/com/intellij/openapi/util/JDOMExternalizer.java +++ b/platform/util/src/com/intellij/openapi/util/JDOMExternalizer.java @@ -16,6 +16,7 @@ package com.intellij.openapi.util; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.util.ArrayUtil; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; @@ -73,7 +74,7 @@ public class JDOMExternalizer { else { mapRoot = root; } - final String[] names = map.keySet().toArray(new String[0]); + final String[] names = ArrayUtil.toStringArray(map.keySet()); Arrays.sort(names); for (String name : names) { @NonNls final Element element = new Element(entryName); diff --git a/platform/util/src/com/intellij/openapi/util/text/StringUtil.java b/platform/util/src/com/intellij/openapi/util/text/StringUtil.java index 0fe7ac86fa17..4ed80c6f3cd4 100644 --- a/platform/util/src/com/intellij/openapi/util/text/StringUtil.java +++ b/platform/util/src/com/intellij/openapi/util/text/StringUtil.java @@ -581,20 +581,29 @@ public class StringUtil { return suggestion + "s"; } - @NotNull public static String capitalizeWords(@NotNull String text, boolean allWords) { - StringTokenizer tokenizer = new StringTokenizer(text); - String out = ""; - String delim = ""; + @NotNull public static String capitalizeWords(@NotNull String text, + boolean allWords) { + return capitalizeWords(text, " \t\n\r\f", allWords, false); + } + + @NotNull public static String capitalizeWords(@NotNull String text, + @NotNull String tokenizerDelim, + boolean allWords, + boolean leaveOriginalDelims) { + final StringTokenizer tokenizer = new StringTokenizer(text, tokenizerDelim, leaveOriginalDelims); + final StringBuilder out = new StringBuilder(); boolean toCapitalize = true; while (tokenizer.hasMoreTokens()) { - String word = tokenizer.nextToken(); - out += delim + (toCapitalize ? capitalize(word) : word); - delim = " "; + final String word = tokenizer.nextToken(); + if (!leaveOriginalDelims && out.length() > 0) { + out.append(' '); + } + out.append(toCapitalize ? capitalize(word) : word); if (!allWords) { toCapitalize = false; } } - return out; + return out.toString(); } public static String decapitalize(String s) { diff --git a/platform/util/src/com/intellij/util/ArrayUtil.java b/platform/util/src/com/intellij/util/ArrayUtil.java index 8c8f973b1206..879d4539fffc 100644 --- a/platform/util/src/com/intellij/util/ArrayUtil.java +++ b/platform/util/src/com/intellij/util/ArrayUtil.java @@ -34,14 +34,15 @@ public class ArrayUtil { public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; public static final int [] EMPTY_INT_ARRAY = new int[0]; public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0]; - public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; - public static final String[] EMPTY_STRING_ARRAY = new String[0]; - public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; + @SuppressWarnings({"SSBasedInspection"}) public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; + @SuppressWarnings({"SSBasedInspection"}) public static final String[] EMPTY_STRING_ARRAY = new String[0]; + @SuppressWarnings({"SSBasedInspection"}) public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; public static final long[] EMPTY_LONG_ARRAY = new long[0]; public static final Collection[] EMPTY_COLLECTION_ARRAY = new Collection[0]; public static final CharSequence EMPTY_CHAR_SEQUENCE = new CharArrayCharSequence(EMPTY_CHAR_ARRAY); - public static byte[] realloc (final byte [] array, final int newSize) { + @NotNull + public static byte[] realloc (@NotNull byte [] array, final int newSize) { if (newSize == 0) { return EMPTY_BYTE_ARRAY; } @@ -56,7 +57,8 @@ public class ArrayUtil { return result; } - public static int[] realloc (final int [] array, final int newSize) { + @NotNull + public static int[] realloc (@NotNull int [] array, final int newSize) { if (newSize == 0) { return EMPTY_INT_ARRAY; } @@ -71,13 +73,15 @@ public class ArrayUtil { return result; } - public static int[] append(int[] array, int value) { + @NotNull + public static int[] append(@NotNull int[] array, int value) { array = realloc(array, array.length + 1); array[array.length - 1] = value; return array; } - public static char[] realloc (final char[] array, final int newSize) { + @NotNull + public static char[] realloc (@NotNull char[] array, final int newSize) { if (newSize == 0) { return EMPTY_CHAR_ARRAY; } @@ -117,7 +121,8 @@ public class ArrayUtil { return collection.toArray(new String[collection.size()]); } - public static T[] mergeArrays(T[] a1, T[] a2, Class aClass) { + @NotNull + public static T[] mergeArrays(@NotNull T[] a1, @NotNull T[] a2, @NotNull Class aClass) { if (a1.length == 0) { return a2; } @@ -156,10 +161,12 @@ public class ArrayUtil { * @param src array to which the element should be appended. * @param element object to be appended to the end of src array. */ + @NotNull public static T[] append(@NotNull final T[] src,final T element){ return append(src, element, (Class)src.getClass().getComponentType()); } + @NotNull public static T[] append(@NotNull T[] src, final T element, @NotNull Class componentType) { int length=src.length; T[] result=(T[])Array.newInstance(componentType, length+ 1); diff --git a/platform/util/src/com/intellij/util/ReflectionUtil.java b/platform/util/src/com/intellij/util/ReflectionUtil.java index 394f67ac39f5..0bff817da623 100644 --- a/platform/util/src/com/intellij/util/ReflectionUtil.java +++ b/platform/util/src/com/intellij/util/ReflectionUtil.java @@ -65,10 +65,8 @@ public class ReflectionUtil { final TypeVariable typeVariable = (TypeVariable)resolved; index = ArrayUtil.find(ReflectionCache.getTypeParameters(anInterface), typeVariable); if (index < 0) { - LOG.assertTrue(false, "Cannot resolve type variable:\n" + - "typeVariable = " + typeVariable + "\n" + - "genericDeclaration = " + declarationToString(typeVariable.getGenericDeclaration()) + "\n" + - "searching in " + declarationToString(anInterface)); + LOG.error("Cannot resolve type variable:\n" + "typeVariable = " + typeVariable + "\n" + "genericDeclaration = " + + declarationToString(typeVariable.getGenericDeclaration()) + "\n" + "searching in " + declarationToString(anInterface)); } final Type type = i < genericInterfaces.length ? genericInterfaces[i] : aClass.getGenericSuperclass(); if (type instanceof Class) { diff --git a/platform/util/src/com/intellij/util/containers/VariableWidthIntArray.java b/platform/util/src/com/intellij/util/containers/VariableWidthIntArray.java index ef5cc676d492..f82ca19646ec 100644 --- a/platform/util/src/com/intellij/util/containers/VariableWidthIntArray.java +++ b/platform/util/src/com/intellij/util/containers/VariableWidthIntArray.java @@ -82,13 +82,13 @@ public final class VariableWidthIntArray implements Cloneable { case SHORT: return shortArray[index]; case BYTE: return byteArray[index]; } - LOG.assertTrue( false, "No array allocated" ); + LOG.error("No array allocated"); return 0; } public void put( int index, int value ) { if( value < minValue || value > maxValue ) { - LOG.assertTrue( false, "Value out of domain" ); + LOG.error("Value out of domain"); } switch( arrayType ) { @@ -97,7 +97,7 @@ public final class VariableWidthIntArray implements Cloneable { case BYTE: byteArray[index] = (byte)value; return; } - LOG.assertTrue( false, "No array allocated" ); + LOG.error("No array allocated"); } public Object clone() throws CloneNotSupportedException { @@ -118,7 +118,8 @@ public final class VariableWidthIntArray implements Cloneable { case INT: System.arraycopy( intArray, from, intArray, to, count ); break; case SHORT: System.arraycopy( shortArray, from, shortArray, to, count ); break; case BYTE: System.arraycopy( byteArray, from, byteArray, to, count ); break; - default: LOG.assertTrue( false, "Invalid array type" ); + default: + LOG.error("Invalid array type"); } } diff --git a/platform/util/src/com/intellij/util/xmlb/OptionTagBinding.java b/platform/util/src/com/intellij/util/xmlb/OptionTagBinding.java index 2a7c8e6b9f78..e076e3632735 100644 --- a/platform/util/src/com/intellij/util/xmlb/OptionTagBinding.java +++ b/platform/util/src/com/intellij/util/xmlb/OptionTagBinding.java @@ -18,6 +18,7 @@ package com.intellij.util.xmlb; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.JDOMUtil; +import com.intellij.util.ArrayUtil; import org.jdom.Attribute; import org.jdom.Content; import org.jdom.Element; @@ -87,7 +88,7 @@ class OptionTagBinding implements Binding { } if (children.size() > 0) { - Object value = myBinding.deserialize(accessor.read(o), children.toArray(new Object[children.size()])); + Object value = myBinding.deserialize(accessor.read(o), ArrayUtil.toObjectArray(children)); accessor.write(o, value); } else { diff --git a/platform/vcs-impl/src/com/intellij/ide/actions/StartUseVcsDialog.java b/platform/vcs-impl/src/com/intellij/ide/actions/StartUseVcsDialog.java index 61b699d9281f..7b67aef3f0f5 100644 --- a/platform/vcs-impl/src/com/intellij/ide/actions/StartUseVcsDialog.java +++ b/platform/vcs-impl/src/com/intellij/ide/actions/StartUseVcsDialog.java @@ -19,6 +19,7 @@ import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.MultiLineLabelUI; import com.intellij.openapi.vcs.VcsBundle; +import com.intellij.util.ArrayUtil; import com.intellij.util.ui.UIUtil; import javax.swing.*; @@ -113,7 +114,7 @@ public class StartUseVcsDialog extends DialogWrapper { keys.add(""); keys.addAll(displayNames); Collections.sort(keys); - return keys.toArray(new Object[keys.size()]); + return ArrayUtil.toObjectArray(keys); } private static class VcsCombo extends JComboBox { diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsGroupsWrapper.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsGroupsWrapper.java index 7cbd28e6314f..acdee8ce2017 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsGroupsWrapper.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsGroupsWrapper.java @@ -44,9 +44,8 @@ public class VcsGroupsWrapper extends DefaultActionGroup { 0)); for (AnAction child : children) { if (!(child instanceof StandardVcsGroup)) { - LOG.assertTrue(false, - "Any version control group should extends com.intellij.openapi.vcs.actions.StandardVcsGroup class. Groupd class: " + - child.getClass().getName() + ", group ID: " + ActionManager.getInstance().getId(child)); + LOG.error("Any version control group should extends com.intellij.openapi.vcs.actions.StandardVcsGroup class. Groupd class: " + + child.getClass().getName() + ", group ID: " + ActionManager.getInstance().getId(child)); } else { validChildren.add(child); diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java index 44c0946f3b13..f476453ee4b3 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java @@ -390,7 +390,7 @@ public class LineStatusTracker { myRanges.addAll(rangesAfterChange); if (myHighlighterCount != myRanges.size()) { - LOG.assertTrue(false, "Highlighters: " + myHighlighterCount + ", ranges: " + myRanges.size()); + LOG.error("Highlighters: " + myHighlighterCount + ", ranges: " + myRanges.size()); } myRanges = mergeRanges(myRanges); @@ -401,7 +401,7 @@ public class LineStatusTracker { } if (myHighlighterCount != myRanges.size()) { - LOG.assertTrue(false, "Highlighters: " + myHighlighterCount + ", ranges: " + myRanges.size()); + LOG.error("Highlighters: " + myHighlighterCount + ", ranges: " + myRanges.size()); } } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/Range.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/Range.java index 2e341af96700..eba9acb089a3 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/Range.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/Range.java @@ -53,7 +53,7 @@ public class Range { if ((change.deleted > 0) && (change.inserted > 0)) return MODIFIED; if ((change.deleted > 0)) return DELETED; if ((change.inserted > 0)) return INSERTED; - LOG.assertTrue(false, "Unknown change type"); + LOG.error("Unknown change type"); return 0; } diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcess.java b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcess.java index 1899ebac774f..f8cf0f91916c 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcess.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcess.java @@ -27,12 +27,22 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** + * Extends this class to provide debugging capabilities for custom language/framework. + * + * In order to start debugger by 'Debug' action for a specific run configuration implement {@link com.intellij.execution.runners.ProgramRunner} + * and call {@link XDebuggerManager#startSession} from {@link com.intellij.execution.runners.ProgramRunner#execute} method + * + * Otherwise use method {@link XDebuggerManager#startSessionAndShowTab} to start new debugging session + * * @author nik */ public abstract class XDebugProcess { private final XDebugSession mySession; private ProcessHandler myProcessHandler; + /** + * @param session pass session parameter of {@link XDebugProcessStarter#start} method to this constructor + */ protected XDebugProcess(@NotNull XDebugSession session) { mySession = session; } @@ -64,27 +74,31 @@ public abstract class XDebugProcess { } /** - * Interrupt debugging process and call {@link XDebugSession#positionReached(com.intellij.xdebugger.frame.XSuspendContext)} - * when next line in current method/function is reached + * Interrupt debugging process and call {@link XDebugSession#positionReached} + * when next line in current method/function is reached. + * Do not call this method directly. Use {@link XDebugSession#pause()} instead */ public void startPausing() { } /** - * Resume execution and call {@link XDebugSession#positionReached(com.intellij.xdebugger.frame.XSuspendContext)} - * when next line in current method/function is reached + * Resume execution and call {@link XDebugSession#positionReached} + * when next line in current method/function is reached. + * Do not call this method directly. Use {@link XDebugSession#stepOver} instead */ public abstract void startStepOver(); /** - * Resume execution and call {@link XDebugSession#positionReached(com.intellij.xdebugger.frame.XSuspendContext)} - * when next line is reached + * Resume execution and call {@link XDebugSession#positionReached} + * when next line is reached. + * Do not call this method directly. Use {@link XDebugSession#stepInto} instead */ public abstract void startStepInto(); /** - * Resume execution and call {@link XDebugSession#positionReached(com.intellij.xdebugger.frame.XSuspendContext)} - * after returning from current method/function + * Resume execution and call {@link XDebugSession#positionReached} + * after returning from current method/function. + * Do not call this method directly. Use {@link XDebugSession#stepOut} instead */ public abstract void startStepOut(); @@ -98,18 +112,21 @@ public abstract class XDebugProcess { } /** - * Stop debugging and dispose resources + * Stop debugging and dispose resources. + * Do not call this method directly. Use {@link XDebugSession#stop} instead */ public abstract void stop(); /** - * Resume execution + * Resume execution. + * Do not call this method directly. Use {@link XDebugSession#resume} instead */ public abstract void resume(); /** * Resume execution and call {@link XDebugSession#positionReached(com.intellij.xdebugger.frame.XSuspendContext)} - * when position is reached + * when position is reached. + * Do not call this method directly. Use {@link XDebugSession#runToPosition} instead * @param position position in source code */ public abstract void runToPosition(@NotNull XSourcePosition position); diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcessStarter.java b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcessStarter.java index 54405346eab2..d37afc05b5dd 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcessStarter.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcessStarter.java @@ -18,10 +18,18 @@ package com.intellij.xdebugger; import org.jetbrains.annotations.NotNull; /** + * Factory class for {@link XDebugProcess} implementation. Used by {@link XDebuggerManager} to start a new debugging session + * * @author nik */ public abstract class XDebugProcessStarter { + /** + * Create a new instance of {@link XDebugProcess} implementation. Note that session isn't initialized when this method is + * called so in order to perform code depending on session parameter override {@link XDebugProcess#sessionInitialized} method + * @param session session to be passed to {@link XDebugProcess#XDebugProcess} constructor + * @return new {@link XDebugProcess} instance + */ @NotNull public abstract XDebugProcess start(@NotNull XDebugSession session); diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugSession.java b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugSession.java index 11ad6fb38e77..4a24013a7074 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugSession.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugSession.java @@ -31,6 +31,10 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; /** + * Instances of this class are created by the debugging subsystem when {@link XDebuggerManager#startSession} or + * {@link XDebuggerManager#startSessionAndShowTab} method is called. It isn't supposed to be implemented by a plugin. + * + * Instance of this class can be obtained from {@link XDebugProcess#getSession()} method and used to control debugging process * @author nik */ public interface XDebugSession extends AbstractDebuggerSession { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebuggerManager.java b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebuggerManager.java index 5b0ac76e7bf8..0682a127e83e 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebuggerManager.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebuggerManager.java @@ -48,13 +48,21 @@ public abstract class XDebuggerManager { @Nullable public abstract XDebugSession getCurrentSession(); + /** + * Start a new debugging session. Use this method only if debugging is started by using standard 'Debug' action i.e. this methods is called + * from {@link com.intellij.execution.runners.ProgramRunner#execute} method. Otherwise use {@link #startSessionAndShowTab} method + */ @NotNull public abstract XDebugSession startSession(@NotNull final ProgramRunner runner, @NotNull ExecutionEnvironment env, @Nullable RunContentDescriptor contentToReuse, @NotNull XDebugProcessStarter processStarter); + /** + * Start a new debugging session and open 'Debug' tool window + * @param sessionName title of 'Debug' tool window + */ @NotNull public abstract XDebugSession startSessionAndShowTab(@NotNull String sessionName, @Nullable RunContentDescriptor contentToReuse, - @NotNull XDebugProcessStarter starter); + @NotNull XDebugProcessStarter starter); } diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/XSourcePosition.java b/platform/xdebugger-api/src/com/intellij/xdebugger/XSourcePosition.java index 445f06b1ce6b..0f4930d96270 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/XSourcePosition.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/XSourcePosition.java @@ -22,8 +22,8 @@ import com.intellij.pom.Navigatable; import org.jetbrains.annotations.NotNull; /** - * Represents position in a source file. Use {@link XDebuggerUtil#createPosition(com.intellij.openapi.vfs.VirtualFile, int)} to create - * instances of this interface. + * Represents position in a source file. Use {@link XDebuggerUtil#createPosition} and {@link XDebuggerUtil#createPositionByOffset} to + * create instances of this interface. * @author nik */ public interface XSourcePosition { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpoint.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpoint.java index 368a225818f1..c52e87e10579 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpoint.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpoint.java @@ -23,6 +23,11 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** + * Represents a breakpoint. This interface isn't supposed to be implemented by a plugin. In order to support breakpoint provide + * {@link XBreakpointType} or {@link XLineBreakpointType} implementation + * + * @see XLineBreakpoint + * @see XBreakpointManager * @author nik */ public interface XBreakpoint

extends UserDataHolder { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointManager.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointManager.java index c936e5ae74a3..116e6bf01ce3 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointManager.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointManager.java @@ -24,6 +24,8 @@ import org.jetbrains.annotations.Nullable; import java.util.Collection; /** + * Use {@link com.intellij.xdebugger.XDebuggerManager#getBreakpointManager()} to obtain instance of this service + * * @author nik */ public interface XBreakpointManager { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java index 120f30efb805..cdcc335c128f 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java @@ -40,6 +40,9 @@ import java.util.Comparator; *   <xdebugger.breakpointType implementation="qualified-class-name"/>
* </extensions> * + * Use this class only for breakpoints like an exception breakpoints in Java. If a breakpoint will be put on some line in a file use + * {@link XLineBreakpointType} instead + * * @author nik */ public abstract class XBreakpointType, P extends XBreakpointProperties> { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpoint.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpoint.java index 456f419433bc..cdd45d58b2b1 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpoint.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpoint.java @@ -19,6 +19,9 @@ package com.intellij.xdebugger.breakpoints; import org.jetbrains.annotations.NotNull; /** + * Represent a breakpoint which is set on some line in a file. This interface isn't supposed to be implemented by a plugin. In order to + * support breakpoint provide {@link XLineBreakpointType} implementation + * * @author nik */ public interface XLineBreakpoint

extends XBreakpoint

{ diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpointType.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpointType.java index 6baa0227f003..3c5232c51973 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpointType.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpointType.java @@ -34,6 +34,15 @@ import java.util.List; import java.util.Collections; /** + * Implement this class to support new type of line breakpoints. An implementation should be registered in a plugin.xml: + *

+ * <extensions defaultExtensionNs="com.intellij">
+ *   <xdebugger.breakpointType implementation="qualified-class-name"/>
+ * </extensions> + * + * In order to support actual setting breakpoints in a debugging process create a {@link XBreakpointHandler} implementation and return it + * from {@link com.intellij.xdebugger.XDebugProcess#getBreakpointHandlers()} method + * * @author nik */ public abstract class XLineBreakpointType

extends XBreakpointType,P> { @@ -42,16 +51,23 @@ public abstract class XLineBreakpointType

exten } /** - * @deprecated implement {@link XLineBreakpointType#canPutAt(com.intellij.openapi.vfs.VirtualFile, int, com.intellij.openapi.project.Project)} instead + * @deprecated implement {@link #canPutAt(com.intellij.openapi.vfs.VirtualFile, int, com.intellij.openapi.project.Project)} instead */ public boolean canPutAt(@NotNull VirtualFile file, int line) { return false; } + /** + * Return true if breakpoint can be put on line in file + */ public boolean canPutAt(@NotNull VirtualFile file, int line, @NotNull Project project) { return canPutAt(file, line); } + /** + * return non-null value if a breakpoint should have specific properties besides containing file and line. These properties will be stored in + * {@link XBreakpoint} instance and can be obtained by using {@link XBreakpoint#getProperties()} method + */ public abstract P createBreakpointProperties(@NotNull VirtualFile file, int line); public String getDisplayText(final XLineBreakpoint

breakpoint) { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/evaluation/XDebuggerEvaluator.java b/platform/xdebugger-api/src/com/intellij/xdebugger/evaluation/XDebuggerEvaluator.java index 3e5857bbce46..e17f3b6c2e3e 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/evaluation/XDebuggerEvaluator.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/evaluation/XDebuggerEvaluator.java @@ -69,7 +69,7 @@ public abstract class XDebuggerEvaluator { } /** - * @deprecated override {@link XDebuggerEvaluator#evaluate(String, XEvaluationCallback, com.intellij.xdebugger.XSourcePosition)} instead + * @deprecated override {@link #evaluate(String, XEvaluationCallback, com.intellij.xdebugger.XSourcePosition)} instead */ @Deprecated public void evaluate(@NotNull String expression, XEvaluationCallback callback) { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XCompositeNode.java b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XCompositeNode.java index 49828556d02a..badc500ae727 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XCompositeNode.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XCompositeNode.java @@ -21,6 +21,10 @@ import org.jetbrains.annotations.NotNull; import java.util.List; /** + * Represents a node with children in a debugger tree. This interface isn't supposed to be implemented by a plugin. + * + * @see XValueContainer + * * @author nik */ public interface XCompositeNode extends Obsolescent { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XExecutionStack.java b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XExecutionStack.java index b3b6f3f18549..4188ee1fb88d 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XExecutionStack.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XExecutionStack.java @@ -24,6 +24,9 @@ import javax.swing.*; import java.util.List; /** + * Represents a stack of executions frames usually corresponding to a thread. It is shown in 'Frames' panel of + * 'Debug' tool window + * * @author nik */ public abstract class XExecutionStack { @@ -58,7 +61,8 @@ public abstract class XExecutionStack { public abstract XStackFrame getTopFrame(); /** - * Start computing stack frames top-down starting from firstFrameIndex + * Start computing stack frames top-down starting from firstFrameIndex. This method is called from the Event Dispatch Thread + * so it should return quickly * @param firstFrameIndex frame index to start from (1 corresponds to the frame just under the top frame) * @param container callback */ diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XStackFrame.java b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XStackFrame.java index 2a369dffa31f..82b97af99f7c 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XStackFrame.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XStackFrame.java @@ -25,11 +25,16 @@ import com.intellij.xdebugger.ui.DebuggerIcons; import org.jetbrains.annotations.Nullable; /** + * Represents a frame of execution stack. The selected frame is shown in 'Variables' panel of 'Debug' tool window. + * Override {@link XValueContainer#computeChildren} to show local variable, parameters, fields available in the frame + * * @author nik */ public abstract class XStackFrame extends XValueContainer { /** + * If stack frame is not changed after step expanded nodes and selection will be restored in 'Variables' tree. A stack frame is assumed + * unchanged if this method return equal non-null values before and after step * @return an object which will be used to determine if stack frame changed after step */ @Nullable diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XSuspendContext.java b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XSuspendContext.java index 008f112ed875..4406ea69276a 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XSuspendContext.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XSuspendContext.java @@ -18,10 +18,16 @@ package com.intellij.xdebugger.frame; import org.jetbrains.annotations.Nullable; /** + * Represents a suspended state of a debug process + * * @author nik */ public abstract class XSuspendContext { + /** + * Returned execution stack will be selected by default in 'Frames' panel of 'Debug' tool window. Also it will be used to obtain current + * stack frame to perform 'Evaluate' action, for example + */ @Nullable public XExecutionStack getActiveExecutionStack() { return null; diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValue.java b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValue.java index 7b8ce4d87e60..74b7221a7bdb 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValue.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValue.java @@ -19,6 +19,9 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** + * Represents a value in debugger tree. + * Override {@link XValueContainer#computeChildren} if value has a properties which should be shown as child nodes + * * @author nik */ public abstract class XValue extends XValueContainer { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueModifier.java b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueModifier.java index 6a1f8829755c..e4f90b8fa1a6 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueModifier.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueModifier.java @@ -24,7 +24,7 @@ import org.jetbrains.annotations.Nullable; public abstract class XValueModifier { /** - * Start modification of the value. + * Start modification of the value. Note that this methods is called from the Event Dispatch Thread so it should return quickly * @param expression new value * @param callback used to notify that value has been successfully modified or an error occurs */ diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueNode.java b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueNode.java index e957ded9a771..66394a03892a 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueNode.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/frame/XValueNode.java @@ -23,6 +23,10 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; /** + * Represents a node in debugger tree. This interface isn't supposed to be implemented by a plugin. + * + * @see XValue + * * @author nik */ public interface XValueNode extends Obsolescent { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/package.html b/platform/xdebugger-api/src/com/intellij/xdebugger/package.html new file mode 100644 index 000000000000..558808105d34 --- /dev/null +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/package.html @@ -0,0 +1,27 @@ + + + + +

API for integration with debuggers of custom languages/frameworks

+ + {@link com.intellij.xdebugger.XDebugProcess} is the main class which need to be extended to support debugging
+ + Implement {@link com.intellij.xdebugger.breakpoints.XLineBreakpointType} to support new type of breakpoints
+ + Use {@link com.intellij.xdebugger.settings.XDebuggerSettings} to provide settings + + diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebugSessionTab.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebugSessionTab.java index 4a2be06fd5d3..23129e1810c3 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebugSessionTab.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebugSessionTab.java @@ -40,6 +40,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.registry.Registry; import com.intellij.ui.content.Content; import com.intellij.ui.content.tabs.PinToolwindowTabAction; +import com.intellij.util.ArrayUtil; import com.intellij.xdebugger.XDebugProcess; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XDebuggerBundle; @@ -132,7 +133,7 @@ public class XDebugSessionTab extends DebuggerLogConsoleManagerBase { public XDebugSessionData saveData() { final List watchExpressions = myWatchesView.getWatchExpressions(); - return new XDebugSessionData(watchExpressions.toArray(new String[watchExpressions.size()])); + return new XDebugSessionData(ArrayUtil.toStringArray(watchExpressions)); } public ExecutionConsole getConsole() { diff --git a/plugins/IdeaTestAssistant/src/com/intellij/testAssistant/TestDataNavigationHandler.java b/plugins/IdeaTestAssistant/src/com/intellij/testAssistant/TestDataNavigationHandler.java index 0856f6cd98f3..8682806dc338 100644 --- a/plugins/IdeaTestAssistant/src/com/intellij/testAssistant/TestDataNavigationHandler.java +++ b/plugins/IdeaTestAssistant/src/com/intellij/testAssistant/TestDataNavigationHandler.java @@ -99,7 +99,7 @@ public class TestDataNavigationHandler implements GutterIconNavigationHandler<<< HTML + + "<HTML>" + + + + "SELECT " + + <<< JS diff --git a/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser2.java b/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser2.java index 492a79a05618..6b2b629dde2b 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser2.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser2.java @@ -45,7 +45,7 @@ final class OutputParser2 extends OutputParser implements PacketProcessor, Input SegmentReader reader = new SegmentReader(packet); int index = reader.readInt(); if (myLastPacketIndex + 1 < index) { - LOG.assertTrue(false, "last: " + myLastPacketIndex + " current: " + index); + LOG.error("last: " + myLastPacketIndex + " current: " + index); } if (myLastPacketIndex + 1 > index) return; myLastPacketIndex++; diff --git a/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorerTreeStructure.java b/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorerTreeStructure.java index bcfbce834253..5049c3356a37 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorerTreeStructure.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorerTreeStructure.java @@ -64,7 +64,7 @@ final class AntExplorerTreeStructure extends AbstractTreeStructure { else if (element instanceof AntBuildTarget) { return new AntTargetNodeDescriptor(myProject, parentDescriptor, (AntBuildTargetBase)element); } - LOG.assertTrue(false, "Unknown element for this tree structure " + element); + LOG.error("Unknown element for this tree structure " + element); return null; } diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/AddFileOrDirectoryAction.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/AddFileOrDirectoryAction.java index 827878244f3e..727dd4574bd5 100644 --- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/AddFileOrDirectoryAction.java +++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/AddFileOrDirectoryAction.java @@ -104,7 +104,7 @@ public class AddFileOrDirectoryAction extends ActionOnSelectedElement { Collection roots = new CreateTreeOnFileList(filesToAdd, project, includeAllRoots).getRoots(); if (roots.size() == 0) { - LOG.assertTrue(false, filesToAdd); + LOG.error(filesToAdd); } if (showDialog){ diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/IgnoreFileAction.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/IgnoreFileAction.java index a16592798c9c..aeef0caf2a9b 100644 --- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/IgnoreFileAction.java +++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/IgnoreFileAction.java @@ -113,9 +113,7 @@ public class IgnoreFileAction extends AnAction { VirtualFile cvsIgnoreFile = CvsVfsUtil.refreshAndfFindChild(parent, CvsUtil.CVS_IGNORE_FILE); if (cvsIgnoreFile == null) { String path = parent.getPath() + "/" + CvsUtil.CVS_IGNORE_FILE; - LOG.assertTrue(false, - String.valueOf(CvsVfsUtil.findFileByPath(path)) + " " + parent.getPath() + " " + - new File(VfsUtil.virtualToIoFile(parent), CvsUtil.CVS_IGNORE_FILE).isFile()); + LOG.error(String.valueOf(CvsVfsUtil.findFileByPath(path)) + " " + parent.getPath() + " " + new File(VfsUtil.virtualToIoFile(parent), CvsUtil.CVS_IGNORE_FILE).isFile()); return; } diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/config/CvsApplicationLevelConfiguration.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/config/CvsApplicationLevelConfiguration.java index cdb94979508b..b807b713baaf 100644 --- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/config/CvsApplicationLevelConfiguration.java +++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/config/CvsApplicationLevelConfiguration.java @@ -147,7 +147,7 @@ public class CvsApplicationLevelConfiguration implements ApplicationComponent, J return result; } catch (Exception ex) { - LOG.assertTrue(false, "userHome = " + userHome + ", presenation = " + presentation); + LOG.error("userHome = " + userHome + ", presenation = " + presentation); return ""; } } diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/cvsAdd/AddFileOperation.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/cvsAdd/AddFileOperation.java index 62fe1b7dec69..dbea13021049 100644 --- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/cvsAdd/AddFileOperation.java +++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/cvsAdd/AddFileOperation.java @@ -45,7 +45,7 @@ public class AddFileOperation extends CvsOperationOnFiles { List fileObjects = command.getFileObjects().getFileObjects(); for (final AbstractFileObject fileObject: fileObjects) { if (fileObject.getParent() == null) { - LOG.assertTrue(false, "Local Root: " + getLocalRootFor(root) + ", Files: " + myFiles); + LOG.error("Local Root: " + getLocalRootFor(root) + ", Files: " + myFiles); } } } diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/javacvsSpecificImpls/AdminWriterOnCache.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/javacvsSpecificImpls/AdminWriterOnCache.java index 32400daadd5b..b77014a99714 100644 --- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/javacvsSpecificImpls/AdminWriterOnCache.java +++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/javacvsSpecificImpls/AdminWriterOnCache.java @@ -118,7 +118,7 @@ public class AdminWriterOnCache implements IAdminWriter { } public void pruneDirectory(DirectoryObject directoryObject, ICvsFileSystem cvsFileSystem) { - LOG.assertTrue(false, "Cannot be called"); + LOG.error("Cannot be called"); } public void editFile(FileObject fileObject, diff --git a/plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/command/Watch.java b/plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/command/Watch.java index 1a8a9b95a971..7b00d9db35a7 100644 --- a/plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/command/Watch.java +++ b/plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/command/Watch.java @@ -12,6 +12,7 @@ */ package org.netbeans.lib.cvsclient.command; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.netbeans.lib.cvsclient.JavaCvsSrcBundle; @@ -39,7 +40,7 @@ public final class Watch { new String[]{"tedit", "tunedit", "tcommit"}); // NOI18N public static final Watch NONE = new Watch(JavaCvsSrcBundle.message("watch.name.none"), "", // NOI18N - new String[0]); + ArrayUtil.EMPTY_STRING_ARRAY); // Static ================================================================= diff --git a/plugins/git4idea/src/git4idea/changes/GitChangeUtils.java b/plugins/git4idea/src/git4idea/changes/GitChangeUtils.java index 58cf81abe202..318c34e7f81d 100644 --- a/plugins/git4idea/src/git4idea/changes/GitChangeUtils.java +++ b/plugins/git4idea/src/git4idea/changes/GitChangeUtils.java @@ -25,6 +25,7 @@ import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList; import com.intellij.openapi.vcs.versionBrowser.CommittedChangeListImpl; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.ArrayUtil; import git4idea.GitContentRevision; import git4idea.GitRevisionNumber; import git4idea.GitUtil; @@ -293,7 +294,7 @@ public class GitChangeUtils { final Date commitDate = GitUtil.parseTimestamp(s.line()); final String revisionNumber = s.line(); final String parentsLine = s.line(); - final String[] parents = parentsLine.length() == 0 ? new String[0] : parentsLine.split(" "); + final String[] parents = parentsLine.length() == 0 ? ArrayUtil.EMPTY_STRING_ARRAY : parentsLine.split(" "); String authorName = s.line(); String committerName = s.line(); committerName = GitUtil.adjustAuthorName(authorName, committerName); diff --git a/plugins/git4idea/src/org/jetbrains/git4idea/ssh/SSHMain.java b/plugins/git4idea/src/org/jetbrains/git4idea/ssh/SSHMain.java index e4c948ae2cd1..8eb04a347743 100644 --- a/plugins/git4idea/src/org/jetbrains/git4idea/ssh/SSHMain.java +++ b/plugins/git4idea/src/org/jetbrains/git4idea/ssh/SSHMain.java @@ -16,6 +16,7 @@ package org.jetbrains.git4idea.ssh; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.util.ArrayUtil; import com.trilead.ssh2.*; import com.trilead.ssh2.crypto.PEMDecoder; import git4idea.i18n.GitBundle; @@ -439,7 +440,7 @@ public class SSHMain { database.addHostkeys(knownHostFile); } final List algorithms = myHost.getHostKeyAlgorithms(); - c.setServerHostKeyAlgorithms(algorithms.toArray(new String[algorithms.size()])); + c.setServerHostKeyAlgorithms(ArrayUtil.toStringArray(algorithms)); } /** @@ -501,7 +502,7 @@ public class SSHMain { final String[] prompt, final boolean[] echo) throws Exception { if (numPrompts == 0) { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } myPromptCount++; Vector vPrompts = new Vector(prompt.length); @@ -519,7 +520,7 @@ public class SSHMain { return rc; } else { - return result.toArray(new String[result.size()]); + return ArrayUtil.toStringArray(result); } } } diff --git a/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerWrapper.java b/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerWrapper.java index d9e22c303402..821950cb45d3 100644 --- a/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerWrapper.java +++ b/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerWrapper.java @@ -28,6 +28,8 @@ import org.codehaus.groovy.tools.GroovyClass; import java.io.File; import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; import java.util.*; @@ -154,7 +156,10 @@ public class GroovyCompilerWrapper { } else if (forStubs) { addMessageWithoutLocation(collector, "Groovyc stub generation failed: " + exception.getMessage(), false); } else { - addMessageWithoutLocation(collector, exception.getMessage(), true); + final StringWriter writer = new StringWriter(); + //noinspection IOResourceOpenedButNotSafelyClosed + exception.printStackTrace(new PrintWriter(writer)); + addMessageWithoutLocation(collector, writer.toString(), true); } } diff --git a/plugins/groovy/src/META-INF/plugin.xml b/plugins/groovy/src/META-INF/plugin.xml index 765a0b694494..3b5a010b90e2 100644 --- a/plugins/groovy/src/META-INF/plugin.xml +++ b/plugins/groovy/src/META-INF/plugin.xml @@ -70,7 +70,6 @@ - @@ -136,6 +135,7 @@ + @@ -483,6 +483,9 @@ org.jetbrains.plugins.groovy.codeInspection.local.GroovyUnusedImportsPassFactory + org.jetbrains.plugins.groovy.annotator.intentions.dynamic.DynamicManager org.jetbrains.plugins.groovy.annotator.intentions.dynamic.DynamicManagerImpl diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties b/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties index 0f09fa2689c0..5477076735a1 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties @@ -125,7 +125,7 @@ case.expected='case' or 'default' expected block.expression.expected=Block expression expected wrong.string=Wrong string literal path.selector.expected=Property selector expected -duplicate.modifier=Duplicate modifier +duplicate.modifier=Duplicate modifier ''{0}'' param.expected=Parameter expected for.clause.expected=clause expected at.expected='@' expected @@ -174,6 +174,9 @@ unused.import.statement=Unused import statement static.declaration.in.inner.class=Inner classes cannot have static declarations constructors.are.not.allowed.in.anonymous.class=Constructors are not allowed in anonymous class no.such.property=Property ''{0}'' does not exist +change.modifier=Make ''{0}'' {1} +change.modifier.not=Make ''{0}'' not {1} +change.modifier.family.name=Change modifiers # {0} - colspan, {1} - method name, {2} - class name, {3} - formal myParameters row, {4} - arguments row argument.mismatch.html.tooltip=\ @@ -204,7 +207,8 @@ intarface.cannot.have.modifier.final=interface cannot have modifier 'final' script.cannot.have.modifier.abstract=script cannot have modifier 'abstract' script.cannot.have.modifier.native=script cannot have modifier 'native' interface.must.have.no.static.method=interface must have no static method -not.abstract.class.cannot.have.abstract.method=not abstract class cannot have abstract method +only.abstract.class.can.have.abstract.method=only abstract class can have abstract method +anonymous.class.cannot.have.abstract.method=anonymous class cannot have abstract method illegal.combination.of.modifiers.volatile.and.final=illegal combination of modifiers 'volatile' and 'final' variable.cannot.be.native=variable cannot have modifier 'native' variable.cannot.be.abstract=variable cannot have modifier 'abstract' @@ -302,3 +306,4 @@ copy.groovy.files.to.output=Copy Groovy files to output as &resources in.expected='in' expected not.allowed.modifier.in.forin=Modifier ''{0}'' is not allowed here property.name.expected=Property name expected +add.method.body=Add method body diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewGroovyClassAction.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewGroovyClassAction.java index e78f50b08ce4..17ad85067580 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewGroovyClassAction.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewGroovyClassAction.java @@ -35,7 +35,7 @@ import org.jetbrains.plugins.groovy.util.LibrariesUtil; public class NewGroovyClassAction extends CreateTemplateInPackageAction implements DumbAware { public NewGroovyClassAction() { - super(GroovyBundle.message("newclass.menu.action.text"), GroovyBundle.message("newclass.menu.action.description"), GroovyIcons.CLASS); + super(GroovyBundle.message("newclass.menu.action.text"), GroovyBundle.message("newclass.menu.action.description"), GroovyIcons.CLASS, true); } @NotNull diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewScriptAction.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewScriptAction.java index eb7a8affa576..a8831400bd91 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewScriptAction.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewScriptAction.java @@ -38,7 +38,7 @@ public class NewScriptAction extends CreateTemplateInPackageAction i private static final String GROOVY_DSL_SCRIPT_TMPL = "GroovyDslScript.gdsl"; public NewScriptAction() { - super(GroovyBundle.message("newscript.menu.action.text"), GroovyBundle.message("newscript.menu.action.description"), GroovyIcons.GROOVY_ICON_16x16); + super(GroovyBundle.message("newscript.menu.action.text"), GroovyBundle.message("newscript.menu.action.description"), GroovyIcons.GROOVY_ICON_16x16, false); } @NotNull diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java index 35707bf19cdf..c681e3cbeaea 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java @@ -16,12 +16,15 @@ package org.jetbrains.plugins.groovy.annotator; +import com.intellij.codeInsight.daemon.impl.quickfix.AddMethodBodyFix; +import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.lang.ASTNode; import com.intellij.lang.annotation.Annotation; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; @@ -29,6 +32,9 @@ import com.intellij.psi.*; import com.intellij.psi.infos.CandidateInfo; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.util.ArrayUtil; +import com.intellij.util.IncorrectOperationException; +import gnu.trove.THashSet; import gnu.trove.TObjectHashingStrategy; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -152,11 +158,15 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { } if (!resolveResult.isAccessible()) { String message = GroovyBundle.message("cannot.access", referenceExpression.getReferenceName()); - myHolder.createWarningAnnotation(referenceExpression.getReferenceNameElement(), message); + final Annotation annotation = myHolder.createWarningAnnotation(referenceExpression.getReferenceNameElement(), message); + if (resolved instanceof PsiMember) { + registerAccessFix(annotation, referenceExpression, ((PsiMember)resolved)); + } } if (!resolveResult.isStaticsOK() && resolved instanceof PsiModifierListOwner) { if (!((PsiModifierListOwner)resolved).hasModifierProperty(GrModifier.STATIC)) { - myHolder.createWarningAnnotation(referenceExpression, GroovyBundle.message("cannot.reference.nonstatic", referenceExpression.getReferenceName())); + myHolder.createWarningAnnotation(referenceExpression, + GroovyBundle.message("cannot.reference.nonstatic", referenceExpression.getReferenceName())); } } } @@ -207,6 +217,39 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { } } + private static void registerAccessFix(Annotation annotation, GrReferenceExpression place, PsiMember refElement) { + if (refElement instanceof PsiCompiledElement) return; + PsiModifierList modifierList = refElement.getModifierList(); + if (modifierList == null) return; + + try { + Project project = refElement.getProject(); + JavaPsiFacade facade = JavaPsiFacade.getInstance(project); + PsiModifierList modifierListCopy = facade.getElementFactory().createFieldFromText("int a;", null).getModifierList(); + modifierListCopy.setModifierProperty(PsiModifier.STATIC, modifierList.hasModifierProperty(PsiModifier.STATIC)); + @Modifier String minModifier = PsiModifier.PROTECTED; + if (refElement.hasModifierProperty(PsiModifier.PROTECTED)) { + minModifier = PsiModifier.PUBLIC; + } + String[] modifiers = {PsiModifier.PROTECTED, PsiModifier.PUBLIC,}; + PsiClass accessObjectClass = PsiTreeUtil.getParentOfType(place, PsiClass.class, false); + if (accessObjectClass == null) { + accessObjectClass = ((GroovyFile)place.getContainingFile()).getScriptClass(); + } + for (int i = ArrayUtil.indexOf(modifiers, minModifier); i < modifiers.length; i++) { + String modifier = modifiers[i]; + modifierListCopy.setModifierProperty(modifier, true); + if (facade.getResolveHelper().isAccessible(refElement, modifierListCopy, place, accessObjectClass, null)) { + IntentionAction fix = new GrModifierFix(refElement, refElement.getModifierList(), modifier, true, true); + annotation.registerFix(fix); + } + } + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + } + private static void registerStaticImportFix(GrReferenceExpression referenceExpression, Annotation annotation) { final String referenceName = referenceExpression.getReferenceName(); //noinspection ConstantConditions @@ -242,18 +285,25 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { PsiElement typeDef = parent.getParent(); if (typeDef != null && typeDef instanceof GrTypeDefinition) { PsiModifierList modifiersList = variableDeclaration.getModifierList(); - checkAccessModifiers(myHolder, modifiersList); + final GrMember member = variableDeclaration.getMembers()[0]; + checkAccessModifiers(myHolder, modifiersList, member); + checkDuplicateModifiers(myHolder, variableDeclaration.getModifierList(), member); if (modifiersList.hasExplicitModifier(GrModifier.VOLATILE) && modifiersList.hasExplicitModifier(GrModifier.FINAL)) { - myHolder.createErrorAnnotation(modifiersList, GroovyBundle.message("illegal.combination.of.modifiers.volatile.and.final")); + final Annotation annotation = + myHolder.createErrorAnnotation(modifiersList, GroovyBundle.message("illegal.combination.of.modifiers.volatile.and.final")); + annotation.registerFix(new GrModifierFix(member, modifiersList, GrModifier.VOLATILE, true, false)); + annotation.registerFix(new GrModifierFix(member, modifiersList, GrModifier.FINAL, true, false)); } if (modifiersList.hasExplicitModifier(GrModifier.NATIVE)) { - myHolder.createErrorAnnotation(modifiersList, GroovyBundle.message("variable.cannot.be.native")); + final Annotation annotation = myHolder.createErrorAnnotation(modifiersList, GroovyBundle.message("variable.cannot.be.native")); + annotation.registerFix(new GrModifierFix(member, modifiersList, GrModifier.NATIVE, true, false)); } if (modifiersList.hasExplicitModifier(GrModifier.ABSTRACT)) { - myHolder.createErrorAnnotation(modifiersList, GroovyBundle.message("variable.cannot.be.abstract")); + final Annotation annotation = myHolder.createErrorAnnotation(modifiersList, GroovyBundle.message("variable.cannot.be.abstract")); + annotation.registerFix(new GrModifierFix(member, modifiersList, GrModifier.ABSTRACT, true, false)); } } } @@ -601,7 +651,8 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { if (classMember.hasModifierProperty(GrModifier.STATIC)) { final PsiElement modifier = findModifierStatic(classMember); if (modifier != null) { - holder.createErrorAnnotation(modifier, GroovyBundle.message("cannot.have.static.declarations")); + final Annotation annotation = holder.createErrorAnnotation(modifier, GroovyBundle.message("cannot.have.static.declarations")); + annotation.registerFix(new GrModifierFix(classMember, classMember.getModifierList(), GrModifier.STATIC, true, false)); } } } @@ -679,20 +730,41 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { } } + private static void registerAbstractMethodFix(Annotation annotation, GrMethod method, boolean makeClassAbstract) { + if (method.getBlock() == null) { + annotation.registerFix(new AddMethodBodyFix(method)); + } + else { + annotation.registerFix(new GrModifierFix(method, method.getModifierList(), GrModifier.ABSTRACT, false, false)); + } + if (makeClassAbstract) { + final PsiClass containingClass = method.getContainingClass(); + LOG.assertTrue(containingClass != null); + final GrModifierList list = (GrModifierList)containingClass.getModifierList(); + LOG.assertTrue(list != null); + annotation.registerFix(new GrModifierFix(containingClass, list, GrModifier.ABSTRACT, false, true)); + } + } + private static void checkMethodDefinitionModifiers(AnnotationHolder holder, GrMethod method) { - final PsiModifierList modifiersList = method.getModifierList(); - checkAccessModifiers(holder, modifiersList); + final GrModifierList modifiersList = method.getModifierList(); + checkAccessModifiers(holder, modifiersList, method); + checkDuplicateModifiers(holder, modifiersList, method); //script methods boolean isMethodAbstract = modifiersList.hasExplicitModifier(GrModifier.ABSTRACT); final boolean isMethodStatic = modifiersList.hasExplicitModifier(GrModifier.STATIC); if (method.getParent() instanceof GroovyFileBase) { if (isMethodAbstract) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("script.cannot.have.modifier.abstract")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("script.cannot.have.modifier.abstract")); + registerAbstractMethodFix(annotation, method, false); } if (modifiersList.hasExplicitModifier(GrModifier.NATIVE)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("script.cannot.have.modifier.native")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("script.cannot.have.modifier.native")); + annotation.registerFix(new GrModifierFix(method, modifiersList, GrModifier.NATIVE, false, false)); } } else //type definition methods @@ -702,11 +774,15 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { //interface if (containingTypeDef.isInterface()) { if (isMethodStatic) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("interface.must.have.no.static.method")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("interface.must.have.no.static.method")); + annotation.registerFix(new GrModifierFix(method, modifiersList, GrModifier.STATIC, true, false)); } if (modifiersList.hasExplicitModifier(GrModifier.PRIVATE)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("interface.must.have.no.private.method")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("interface.must.have.no.private.method")); + annotation.registerFix(new GrModifierFix(method, modifiersList, GrModifier.PRIVATE, true, false)); } } @@ -721,14 +797,18 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { else if (containingTypeDef.isAnonymous()) { //anonymous class if (isMethodStatic) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("static.declaration.in.inner.class")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("static.declaration.in.inner.class")); + annotation.registerFix(new GrModifierFix(method, modifiersList, GrModifier.STATIC, false, false)); } if (method.isConstructor()) { holder.createErrorAnnotation(method.getNameIdentifierGroovy(), GroovyBundle.message("constructors.are.not.allowed.in.anonymous.class")); } if (isMethodAbstract) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("not.abstract.class.cannot.have.abstract.method")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("anonymous.class.cannot.have.abstract.method")); + registerAbstractMethodFix(annotation, method, false); } } else { @@ -738,13 +818,18 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { if (!typeDefModifiersList.hasExplicitModifier(GrModifier.ABSTRACT)) { if (isMethodAbstract) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("not.abstract.class.cannot.have.abstract.method")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("only.abstract.class.can.have.abstract.method")); + registerAbstractMethodFix(annotation, method, true); } } if (!isMethodAbstract) { if (method.getBlock() == null) { - holder.createErrorAnnotation(method.getNameIdentifierGroovy(), GroovyBundle.message("not.abstract.method.should.have.body")); + final Annotation annotation = holder + .createErrorAnnotation(method.getNameIdentifierGroovy(), GroovyBundle.message("not.abstract.method.should.have.body")); + annotation.registerFix(new AddMethodBodyFix(method)); + } } if (isMethodStatic) { @@ -755,12 +840,13 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { } private static void checkTypeDefinitionModifiers(AnnotationHolder holder, GrTypeDefinition typeDefinition) { - PsiModifierList modifiersList = typeDefinition.getModifierList(); + GrModifierList modifiersList = typeDefinition.getModifierList(); if (modifiersList == null) return; /**** class ****/ - checkAccessModifiers(holder, modifiersList); + checkAccessModifiers(holder, modifiersList, typeDefinition); + checkDuplicateModifiers(holder, modifiersList, typeDefinition); PsiClassType[] extendsListTypes = typeDefinition.getExtendsListTypes(); @@ -771,48 +857,75 @@ public class GroovyAnnotator extends GroovyElementVisitor implements Annotator { PsiModifierList modifierList = psiClass.getModifierList(); if (modifierList != null) { if (modifierList.hasExplicitModifier(GrModifier.FINAL)) { - holder.createErrorAnnotation(typeDefinition.getNameIdentifierGroovy(), GroovyBundle.message("final.class.cannot.be.extended")); + final Annotation annotation = holder + .createErrorAnnotation(typeDefinition.getNameIdentifierGroovy(), GroovyBundle.message("final.class.cannot.be.extended")); + annotation.registerFix(new GrModifierFix(typeDefinition, modifiersList, GrModifier.FINAL, false, false)); } } } } if (modifiersList.hasExplicitModifier(GrModifier.ABSTRACT) && modifiersList.hasExplicitModifier(GrModifier.FINAL)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("illegal.combination.of.modifiers.abstract.and.final")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("illegal.combination.of.modifiers.abstract.and.final")); + annotation.registerFix(new GrModifierFix(typeDefinition, modifiersList, GrModifier.FINAL, false, false)); + annotation.registerFix(new GrModifierFix(typeDefinition, modifiersList, GrModifier.ABSTRACT, false, false)); + } if (modifiersList.hasExplicitModifier(GrModifier.TRANSIENT)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("modifier.transient.not.allowed.here")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("modifier.transient.not.allowed.here")); + annotation.registerFix(new GrModifierFix(typeDefinition, modifiersList, GrModifier.TRANSIENT, false, false)); } if (modifiersList.hasExplicitModifier(GrModifier.VOLATILE)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("modifier.volatile.not.allowed.here")); + final Annotation annotation = holder.createErrorAnnotation(modifiersList, GroovyBundle.message("modifier.volatile.not.allowed.here")); + annotation.registerFix(new GrModifierFix(typeDefinition, modifiersList, GrModifier.VOLATILE, false, false)); } /**** interface ****/ if (typeDefinition.isInterface()) { if (modifiersList.hasExplicitModifier(GrModifier.FINAL)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("intarface.cannot.have.modifier.final")); - } - - if (modifiersList.hasExplicitModifier(GrModifier.VOLATILE)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("modifier.volatile.not.allowed.here")); - } - - if (modifiersList.hasExplicitModifier(GrModifier.TRANSIENT)) { - holder.createErrorAnnotation(modifiersList, GroovyBundle.message("modifier.transient.not.allowed.here")); + final Annotation annotation = + holder.createErrorAnnotation(modifiersList, GroovyBundle.message("intarface.cannot.have.modifier.final")); + annotation.registerFix(new GrModifierFix(typeDefinition, modifiersList, GrModifier.FINAL, false, false)); } } checkStaticDeclarationsInInnerClass(typeDefinition, holder); } - private static void checkAccessModifiers(AnnotationHolder holder, @NotNull PsiModifierList modifierList) { + private static void checkDuplicateModifiers(AnnotationHolder holder, @NotNull GrModifierList list, PsiMember member) { + final PsiElement[] modifiers = list.getModifiers(); + Set set = new THashSet(modifiers.length); + for (PsiElement modifier : modifiers) { + String name = modifier.getText(); + if (set.contains(name)) { + final Annotation annotation = holder.createErrorAnnotation(list, GroovyBundle.message("duplicate.modifier", name)); + annotation.registerFix(new GrModifierFix(member, list, name, false, false)); + } + else { + set.add(name); + } + } + } + + private static void checkAccessModifiers(AnnotationHolder holder, @NotNull PsiModifierList modifierList, PsiMember member) { boolean hasPrivate = modifierList.hasExplicitModifier(GrModifier.PRIVATE); boolean hasPublic = modifierList.hasExplicitModifier(GrModifier.PUBLIC); boolean hasProtected = modifierList.hasExplicitModifier(GrModifier.PROTECTED); if (hasPrivate && hasPublic || hasPrivate && hasProtected || hasPublic && hasProtected) { - holder.createErrorAnnotation(modifierList, GroovyBundle.message("illegal.combination.of.modifiers")); + final Annotation annotation = holder.createErrorAnnotation(modifierList, GroovyBundle.message("illegal.combination.of.modifiers")); + if (hasPrivate) { + annotation.registerFix(new GrModifierFix(member, modifierList, GrModifier.PRIVATE, false, false)); + } + if (hasProtected) { + annotation.registerFix(new GrModifierFix(member, modifierList, GrModifier.PROTECTED, false, false)); + } + if (hasPublic) { + annotation.registerFix(new GrModifierFix(member, modifierList, GrModifier.PUBLIC, false, false)); + } } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateFieldFromUsageFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateFieldFromUsageFix.java index 5c06006dbaab..808c25838b2d 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateFieldFromUsageFix.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateFieldFromUsageFix.java @@ -25,7 +25,7 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.GroovyBundle; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrMemberOwner; -import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesUtil; +import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider; import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint; import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; @@ -62,7 +62,7 @@ public class CreateFieldFromUsageFix extends CreateFieldFix { } protected TypeConstraint[] calculateTypeConstrains() { - return GroovyExpectedTypesUtil.calculateTypeConstraints(myRefExpression); + return GroovyExpectedTypesProvider.calculateTypeConstraints(myRefExpression); } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateLocalVariableFromUsageFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateLocalVariableFromUsageFix.java index c54b2b8ca5db..1e5255a701e8 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateLocalVariableFromUsageFix.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateLocalVariableFromUsageFix.java @@ -39,7 +39,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaratio import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement; import org.jetbrains.plugins.groovy.lang.psi.api.util.GrVariableDeclarationOwner; -import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesUtil; +import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider; import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint; /** @@ -85,7 +85,7 @@ public class CreateLocalVariableFromUsageFix implements IntentionAction { int offset = myRefExpression.getTextRange().getStartOffset(); GrStatement anchor = findAnchor(file, offset); - TypeConstraint[] constraints = GroovyExpectedTypesUtil.calculateTypeConstraints(myRefExpression); + TypeConstraint[] constraints = GroovyExpectedTypesProvider.calculateTypeConstraints(myRefExpression); if (anchor.equals(myRefExpression)) { decl = myRefExpression.replaceWithStatement(decl); } else { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateMethodFromUsageFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateMethodFromUsageFix.java index 41f44fb1ba79..c14efd35f9e5 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateMethodFromUsageFix.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateMethodFromUsageFix.java @@ -33,7 +33,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrRefere import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrMemberOwner; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; -import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesUtil; +import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider; import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SupertypeConstraint; import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; @@ -83,7 +83,7 @@ public class CreateMethodFromUsageFix implements IntentionAction { methodBuffer.append(") {\n}"); GrMethod method = GroovyPsiElementFactory.getInstance(project).createMethodFromText(methodBuffer.toString()); GrMemberOwner owner = myTargetClass; - TypeConstraint[] constraints = GroovyExpectedTypesUtil.calculateTypeConstraints((GrExpression) myRefExpression.getParent()); + TypeConstraint[] constraints = GroovyExpectedTypesProvider.calculateTypeConstraints((GrExpression) myRefExpression.getParent()); PsiElement parent = myTargetClass instanceof GrTypeDefinition ? ((GrTypeDefinition)myTargetClass).getBody() : ((GroovyScriptClass) myTargetClass).getContainingFile(); if (PsiTreeUtil.isAncestor(parent, myRefExpression, false)) { PsiElement prevParent = PsiTreeUtil.findPrevParent(parent, myRefExpression); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrModifierFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrModifierFix.java new file mode 100644 index 000000000000..057f39f991ca --- /dev/null +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrModifierFix.java @@ -0,0 +1,96 @@ +/* + * Copyright 2000-2010 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.plugins.groovy.annotator.intentions; + +import com.intellij.codeInsight.intention.IntentionAction; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiMember; +import com.intellij.psi.PsiModifierList; +import com.intellij.util.IncorrectOperationException; +import com.intellij.util.VisibilityUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.plugins.groovy.GroovyBundle; + +/** + * @author Maxim.Medvedev + */ +public class GrModifierFix implements IntentionAction { + @NotNull private final PsiMember myMember; + private final String myModifier; + private final boolean myShowContainingClass; + private final PsiModifierList myModifierList; + private final boolean myDoSet; + + public GrModifierFix(@NotNull PsiMember member, + @NotNull PsiModifierList modifierList, + String modifier, + boolean showContainingClass, + boolean doSet) { + myMember = member; + myModifier = modifier; + myShowContainingClass = showContainingClass; + myModifierList = modifierList; + myDoSet = doSet; + } + + @NotNull + public String getText() { + String name; + if (myShowContainingClass) { + final PsiClass containingClass = myMember.getContainingClass(); + String containingClassName; + if (containingClass != null) { + containingClassName = containingClass.getName() + "."; + } + else { + containingClassName = ""; + } + + name = containingClassName + myMember.getName(); + } + else { + name = myMember.getName(); + } + String modifierText = VisibilityUtil.toPresentableText(myModifier); + + if (myDoSet) { + return GroovyBundle.message("change.modifier", name, modifierText); + } + else { + return GroovyBundle.message("change.modifier.not", name, modifierText); + } + } + + @NotNull + public String getFamilyName() { + return GroovyBundle.message("change.modifier.family.name"); + } + + public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { + return myModifierList != null && myModifierList.isValid(); + } + + public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { + myModifierList.setModifierProperty(myModifier, myDoSet); + } + + public boolean startInWriteAction() { + return true; + } +} diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/QuickfixUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/QuickfixUtil.java index cc819fbe7266..22f927512eaa 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/QuickfixUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/QuickfixUtil.java @@ -156,7 +156,7 @@ public class QuickfixUtil { public static String[] getArgumentsTypes(List listOfPairs) { final List result = new ArrayList(); - if (listOfPairs == null) return new String[0]; + if (listOfPairs == null) return ArrayUtil.EMPTY_STRING_ARRAY; for (MyPair listOfPair : listOfPairs) { String type = PsiTypesUtil.unboxIfPossible(listOfPair.second); result.add(type); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicMethodDialog.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicMethodDialog.java index 1275eda5cd64..0054c8f3f08c 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicMethodDialog.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicMethodDialog.java @@ -26,7 +26,7 @@ import org.jetbrains.plugins.groovy.annotator.intentions.dynamic.MyPair; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; -import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesUtil; +import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider; import javax.swing.*; import javax.swing.event.CellEditorListener; @@ -46,7 +46,7 @@ public class DynamicMethodDialog extends DynamicDialog { private final GrReferenceExpression myReferenceExpression; public DynamicMethodDialog(GrReferenceExpression referenceExpression) { - super(referenceExpression, QuickfixUtil.createSettings(referenceExpression), GroovyExpectedTypesUtil.calculateTypeConstraints((GrExpression)referenceExpression.getParent())); + super(referenceExpression, QuickfixUtil.createSettings(referenceExpression), GroovyExpectedTypesProvider.calculateTypeConstraints((GrExpression)referenceExpression.getParent())); myReferenceExpression = referenceExpression; assert getSettings().isMethod(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicPropertyDialog.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicPropertyDialog.java index 3bd0191d323d..98c3dd49e7de 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicPropertyDialog.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicPropertyDialog.java @@ -20,7 +20,7 @@ import org.jetbrains.plugins.groovy.GroovyBundle; import org.jetbrains.plugins.groovy.annotator.intentions.QuickfixUtil; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; -import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesUtil; +import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider; import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SupertypeConstraint; /** @@ -32,7 +32,7 @@ public class DynamicPropertyDialog extends DynamicDialog { private final GrArgumentLabel myLabel; public DynamicPropertyDialog(GrReferenceExpression referenceExpression) { - super(referenceExpression, QuickfixUtil.createSettings(referenceExpression), GroovyExpectedTypesUtil.calculateTypeConstraints(referenceExpression)); + super(referenceExpression, QuickfixUtil.createSettings(referenceExpression), GroovyExpectedTypesProvider.calculateTypeConstraints(referenceExpression)); myReferenceExpression = referenceExpression; myLabel = null; setTitle(GroovyBundle.message("add.dynamic.property", referenceExpression.getReferenceName())); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java index b18f4507c08f..b4c1067d7981 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java @@ -16,6 +16,7 @@ package org.jetbrains.plugins.groovy.compiler; +import com.intellij.compiler.CompilerConfiguration; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompileScope; @@ -27,19 +28,26 @@ import com.intellij.openapi.projectRoots.JavaSdkType; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ContentIterator; import com.intellij.openapi.roots.ModuleRootManager; +import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.roots.ui.configuration.ClasspathEditor; import com.intellij.openapi.roots.ui.configuration.ModulesConfigurator; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiElementVisitor; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiManager; +import com.intellij.psi.search.FilenameIndex; +import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.containers.FactoryMap; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.GroovyBundle; import org.jetbrains.plugins.groovy.GroovyFileType; import org.jetbrains.plugins.groovy.GroovyFileTypeLoader; +import org.jetbrains.plugins.groovy.GroovyIcons; import org.jetbrains.plugins.groovy.config.GroovyConfigUtils; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; @@ -55,6 +63,7 @@ import java.util.*; public class GroovyCompiler extends GroovyCompilerBase { private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.compiler.GroovyCompiler"); + private static final String AST_TRANSFORM_FILE_NAME = "org.codehaus.groovy.transform.ASTTransformation"; public GroovyCompiler(Project project) { super(project); @@ -167,6 +176,10 @@ public class GroovyCompiler extends GroovyCompilerBase { LOG.error(e); //prevent our PSI errors from failing the entire compilation } + catch (AssertionError e) { + LOG.error(e); + //prevent our PSI errors from failing the entire compilation + } } element.acceptChildren(this); @@ -231,7 +244,33 @@ public class GroovyCompiler extends GroovyCompilerBase { return false; } + final GroovyCompilerConfiguration configuration = GroovyCompilerConfiguration.getInstance(myProject); + if (!configuration.transformsOk && needTransformCopying(compileScope)) { + final int result = Messages.showYesNoDialog(myProject, + "You seem to have global Groovy AST transformations defined in your project,\n" + + "but they won't be applied to your code because they are not marked as compiler resources.\n" + + "Do you want to add them to compiler resource list?\n" + + "(you can do it yourself later in Settings | Compiler | Resource patterns)", "AST Transformations found", + GroovyIcons.GROOVY_ICON_32x32); + if (result == 0) { + CompilerConfiguration.getInstance(myProject).addResourceFilePattern(AST_TRANSFORM_FILE_NAME); + } else { + configuration.transformsOk = true; + } + } + return true; } + private boolean needTransformCopying(CompileScope compileScope) { + final CompilerConfiguration configuration = CompilerConfiguration.getInstance(myProject); + final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); + for (VirtualFile file : FilenameIndex.getVirtualFilesByName(myProject, AST_TRANSFORM_FILE_NAME, GlobalSearchScope.projectScope(myProject))) { + if (compileScope.belongs(file.getUrl()) && index.isInSource(file) && !configuration.isResourceFile(file)) { + return true; + } + } + return false; + } + } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerConfiguration.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerConfiguration.java index dfc2534355c8..6690eb562468 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerConfiguration.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerConfiguration.java @@ -37,12 +37,14 @@ import org.jdom.Element; public class GroovyCompilerConfiguration implements PersistentStateComponent, Disposable { private String myHeapSize = "400"; private boolean myUseGroovycStubs = false; + public boolean transformsOk = false; private final ExcludedEntriesConfiguration myExcludeFromStubGeneration = new ExcludedEntriesConfiguration(); public MyStateBean getState() { final MyStateBean bean = new MyStateBean(); bean.heapSize = myHeapSize; bean.useGroovycStubs = myUseGroovycStubs; + bean.transformsOk = transformsOk; myExcludeFromStubGeneration.writeExternal(bean.excludes); return bean; } @@ -58,6 +60,7 @@ public class GroovyCompilerConfiguration implements PersistentStateComponent groovyModules = new HashSet(); + + public GroovyLibraryListener(Project project) { + super(project); + } + + @Override + public void projectOpened() { + final MessageBusConnection connection = myProject.getMessageBus().connect(myProject); + connection.subscribe(ProjectTopics.PROJECT_ROOTS, this); + + final Module[] modules = ModuleManager.getInstance(myProject).getModules(); + for (Module module : modules) { + if (module.isDisposed()) continue; + if (LibrariesUtil.hasGroovySdk(module)) { + groovyModules.add(module); + } + } + } + + public void beforeRootsChange(ModuleRootEvent event) { + } + + public void rootsChanged(ModuleRootEvent event) { + final Module[] modules = ModuleManager.getInstance(myProject).getModules(); + for (Module module : modules) { + if (module.isDisposed()) continue; + final Library[] libraries = GroovyConfigUtils.getInstance().getSDKLibrariesByModule(module); + if ((libraries.length > 0 && !groovyModules.contains(module))) { + final Application app = ApplicationManager.getApplication(); + if (app.isRestartCapable()) { + if (Messages.showYesNoDialog(myProject, "You have added Groovy SDK library '" + + libraries[0].getName() + + "' to module '" + + module.getName() + + "'. To add Groovy support " + + ApplicationNamesInfo.getInstance().getFullProductName() + + " must be restarted. Would you like to add Groovy support and restart now?", + "Add Groovy support", Messages.getInformationIcon()) == 0) { + FSRecords.invalidateCaches(); + app.restart(); + } + } + else { + Messages.showMessageDialog(myProject, "You have added Groovy SDK library '" + + libraries[0].getName() + + "' to module '" + + module.getName() + + "'. To add Groovy support you need to restart " + + ApplicationNamesInfo.getInstance().getFullProductName() + + ".", "Add Groovy support", Messages.getInformationIcon()); + } + } + else if ((libraries.length == 0 && groovyModules.contains(module))) { + groovyModules.remove(module); + } + } + } +} diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java index d20e6053370e..3735eeaac2a6 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java @@ -56,32 +56,15 @@ import java.util.Random; */ public class GroovyCodeFragmentFactory implements CodeFragmentFactory { private static final String EVAL_NAME = "_JETGROOVY_EVAL_"; - - private static String createProperty(String text, String imports) { - String classText = "\"" + - imports + - "class DUMMY { " + - "public groovy.lang.Closure " + - EVAL_NAME + " = {" + text + "}}\""; - - return "final java.lang.ClassLoader parentLoader = clazz.getClassLoader();\n" + - " final groovy.lang.GroovyClassLoader loader = new groovy.lang.GroovyClassLoader(parentLoader);\n" + - " final java.lang.Class c = loader.parseClass(" + - classText + - ", \"DUMMY.groovy\");\n" + - " int i;\n" + - " java.lang.reflect.Field[] fields = c.getFields();\n" + - " for (int j = 0; j < fields.length; j++) if (fields[j].getName().equals(\"_JETGROOVY_EVAL_\")) {i = j; break;}\n" + - " final java.lang.reflect.Field field = fields[i];\n" + - " final java.lang.Object closure = field.get(c.newInstance());\n"; - } + private static final String IMPORTS = "___$$IMPORTS$$___"; + private static final String TEXT = "___$$TEXT$$___"; private static String unwrapVals(List vals) { - return "java.lang.Object[] vals = new java.lang.Object[]{" + StringUtil.join(vals, ",") + "};\n" + - "java.lang.Object[] resVals = new java.lang.Object[" + vals.size() + "];\n" + - "for (int iii =0; iii, GroovyFile> pair = externalParameters(text, context); GroovyFile toEval = pair.second; final Map parameters = pair.first; @@ -103,76 +85,66 @@ public class GroovyCodeFragmentFactory implements CodeFragmentFactory { text = toEval.getText(); + final String groovyText = StringUtil.join(names, ", ") + "->" + stripImports(text, toEval); PsiClass contextClass = PsiUtil.getContextClass(context); boolean isStatic = isStaticContext(context); StringBuffer javaText = new StringBuffer(); - javaText.append("groovy.lang.MetaClass mc;\n"); - javaText.append("java.lang.Class clazz;\n"); + javaText.append("groovy.lang.MetaClass |mc;\n"); + javaText.append("java.lang.Class |clazz;\n"); if (!isStatic) { - javaText.append("clazz = ((java.lang.Object)this).getClass();\n"); - javaText.append("mc = ((groovy.lang.GroovyObject)this).getMetaClass();\n"); + javaText.append("|clazz = ((java.lang.Object)this).getClass();\n"); + javaText.append("|mc = ((groovy.lang.GroovyObject)this).getMetaClass();\n"); } else { - javaText.append("clazz = java.lang.Class.forName(\"").append(contextClass.getQualifiedName()).append("\");\n"); - javaText.append("mc = groovy.lang.GroovySystem.getMetaClassRegistry().getMetaClass(clazz);\n"); + assert contextClass != null; + javaText.append("|clazz = java.lang.Class.forName(\"").append(contextClass.getQualifiedName()).append("\");\n"); + javaText.append("|mc = groovy.lang.GroovySystem.getMetaClassRegistry().getMetaClass(|clazz);\n"); } - javaText.append(createProperty(StringUtil.join(names, ", ") + "->" + stripImports(text, toEval), imports)); + javaText.append("final java.lang.ClassLoader |parentLoader = |clazz.getClassLoader();\n" + + " final groovy.lang.GroovyClassLoader |loader = new groovy.lang.GroovyClassLoader(|parentLoader);\n" + + " final java.lang.Class |c = |loader.parseClass("); + javaText.append("\"" + IMPORTS + "class DUMMY { " + + "public groovy.lang.Closure " + + EVAL_NAME + " = {" + TEXT + "}}\""); + javaText.append(", \"DUMMY.groovy\");\n" + + " int |i;\n" + + " java.lang.reflect.Field[] |fields = |c.getFields();\n" + + " for (int |j = 0; |j < |fields.length; |j++) if (|fields[|j].getName().equals(\"_JETGROOVY_EVAL_\")) {|i = |j; break;}\n" + + " final java.lang.reflect.Field |field = |fields[|i];\n" + + " final java.lang.Object |closure = |field.get(|c.newInstance());\n"); - javaText.append("groovy.lang.ExpandoMetaClass emc = new groovy.lang.ExpandoMetaClass(clazz);\n"); + javaText.append("groovy.lang.ExpandoMetaClass |emc = new groovy.lang.ExpandoMetaClass(|clazz);\n"); if (!isStatic) { - javaText.append("emc.setProperty(\"").append(EVAL_NAME).append("\", closure);\n"); - javaText.append("((groovy.lang.GroovyObject)this).setMetaClass(emc);\n"); + javaText.append("|emc.setProperty(\"").append(EVAL_NAME).append("\", |closure);\n"); + javaText.append("((groovy.lang.GroovyObject)this).setMetaClass(|emc);\n"); } else { - javaText.append("((groovy.lang.GroovyObject)emc.getProperty(\"static\")).setProperty(\"").append(EVAL_NAME).append("\", closure);\n"); - javaText.append("groovy.lang.GroovySystem.getMetaClassRegistry().setMetaClass(clazz, emc);\n"); + javaText.append("((groovy.lang.GroovyObject)|emc.getProperty(\"static\")).setProperty(\"").append(EVAL_NAME).append("\", |closure);\n"); + javaText.append("groovy.lang.GroovySystem.getMetaClassRegistry().setMetaClass(|clazz, |emc);\n"); } - javaText.append("emc.initialize();\n"); + javaText.append("|emc.initialize();\n"); javaText.append(unwrapVals(values)); if (!isStatic) { - javaText.append("java.lang.Object res = ((groovy.lang.MetaClassImpl)emc).invokeMethod(this, \"").append(EVAL_NAME).append("\", "). - append("resVals").append(");\n"); - javaText.append("((groovy.lang.GroovyObject)this).setMetaClass(mc);"); //try/finally is not supported + javaText.append("java.lang.Object |res = ((groovy.lang.MetaClassImpl)|emc).invokeMethod(this, \"").append(EVAL_NAME).append("\", |resVals);\n"); + javaText.append("((groovy.lang.GroovyObject)this).setMetaClass(|mc);"); //try/finally is not supported } else { - javaText.append("java.lang.Object res = ((groovy.lang.MetaClassImpl)emc).invokeStaticMethod(clazz, \"").append(EVAL_NAME) - .append("\", "). - append("resVals").append(");\n"); - javaText.append("groovy.lang.GroovySystem.getMetaClassRegistry().setMetaClass(clazz, mc);\n"); + javaText.append("java.lang.Object |res = ((groovy.lang.MetaClassImpl)|emc).invokeStaticMethod(|clazz, \"").append(EVAL_NAME).append("\", |resVals);\n"); + javaText.append("groovy.lang.GroovySystem.getMetaClassRegistry().setMetaClass(|clazz, |mc);\n"); } - javaText.append("res"); + javaText.append("|res"); final PsiElementFactory factory = JavaPsiFacade.getInstance(toEval.getProject()).getElementFactory(); - JavaCodeFragment result = factory.createCodeBlockCodeFragment(javaText.toString(), null, true); - hideInternalJavaVariables(factory, result); + + final String hiddenJavaVars = StringUtil.replace(javaText.toString(), "|", "_$$_$$$_$$$$$$$$$_" + new Random().nextInt(42)); + final String finalText = StringUtil.replace(StringUtil.replace(hiddenJavaVars, TEXT, groovyText), IMPORTS, imports); + JavaCodeFragment result = factory.createCodeBlockCodeFragment(finalText, null, true); if (contextClass != null) { result.setThisType(factory.createType(contextClass)); } return result; } - private static void hideInternalJavaVariables(final PsiElementFactory factory, JavaCodeFragment result) { - final String varPrefix = "_$$_$$$_$$$$$$$$$_" + new Random().nextInt(42); - result.accept(new PsiRecursiveElementWalkingVisitor() { - @Override - public void visitElement(PsiElement element) { - if (element instanceof PsiReferenceExpression && ((PsiReferenceExpression)element).resolve() instanceof PsiLocalVariable) { - element.replace(factory.createExpressionFromText(varPrefix + element.getText(), element)); - } - super.visitElement(element); - } - }); - result.accept(new PsiRecursiveElementWalkingVisitor() { - @Override - public void visitElement(PsiElement element) { - if (element instanceof PsiLocalVariable) { - ((PsiLocalVariable)element).setName(varPrefix + ((PsiLocalVariable)element).getName()); - } - super.visitElement(element); - } - }); - } - public static Pair, GroovyFile> externalParameters(String text, @NotNull final PsiElement context) { final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(context.getProject()); final GroovyFile toEval = factory.createGroovyFile(text, false, context); @@ -211,6 +183,13 @@ public class GroovyCodeFragmentFactory implements CodeFragmentFactory { } parameters.put(name, value); } + + if (resolved instanceof PsiClass) { + String qName = ((PsiClass)resolved).getQualifiedName(); + if (qName != null && qName.contains(".") && !referenceExpression.isQualified()) { + replaceWithReference(referenceExpression, qName); + } + } } @Override diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/parameterToEntry/ConvertParameterToMapEntryIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/parameterToEntry/ConvertParameterToMapEntryIntention.java index 5b0b9e650105..4952796b0223 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/parameterToEntry/ConvertParameterToMapEntryIntention.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/parameterToEntry/ConvertParameterToMapEntryIntention.java @@ -42,7 +42,6 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle; import org.jetbrains.plugins.groovy.intentions.base.Intention; import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate; -import static org.jetbrains.plugins.groovy.intentions.style.parameterToEntry.ConvertParameterToMapEntryIntention.FIRST_PARAMETER_KIND.*; import org.jetbrains.plugins.groovy.lang.psi.GrNamedElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; @@ -64,6 +63,8 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; +import static org.jetbrains.plugins.groovy.intentions.style.parameterToEntry.ConvertParameterToMapEntryIntention.FIRST_PARAMETER_KIND.*; + /** * @author ilyas */ @@ -424,7 +425,7 @@ public class ConvertParameterToMapEntryIntention extends Intention { CodeStyleManager.getInstance(owner.getProject()).reformat(owner); } - private static boolean reportConflicts(final MultiMap conflicts, final Project project) { + private static boolean reportConflicts(final MultiMap conflicts, final Project project) { if (conflicts.size() == 0) return true; ConflictsDialog conflictsDialog = new ConflictsDialog(project, conflicts); conflictsDialog.show(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java index 82e13abd4ce8..3c413437c04e 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java @@ -16,9 +16,7 @@ package org.jetbrains.plugins.groovy.lang.completion; import com.intellij.codeInsight.completion.*; -import com.intellij.codeInsight.lookup.LookupElementBuilder; -import com.intellij.codeInsight.lookup.LookupItem; -import com.intellij.codeInsight.lookup.LookupItemUtil; +import com.intellij.codeInsight.lookup.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.highlighter.HighlighterIterator; @@ -39,6 +37,7 @@ import org.jetbrains.plugins.groovy.lang.completion.getters.ClassesGetter; import org.jetbrains.plugins.groovy.lang.completion.handlers.AfterNewClassInsertHandler; import org.jetbrains.plugins.groovy.lang.completion.handlers.ArrayInsertHandler; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; +import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; @@ -46,9 +45,11 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter; import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList; +import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; import java.util.ArrayList; import java.util.List; @@ -76,7 +77,49 @@ public class GroovyCompletionContributor extends CompletionContributor { private static final String[] THIS_SUPER = {"this", "super"}; + private static boolean isReferenceInNewExpression(PsiElement reference) { + if (!(reference instanceof GrCodeReferenceElement)) return false; + + PsiElement parent = reference.getParent(); + while (parent instanceof GrCodeReferenceElement) parent = parent.getParent(); + return parent instanceof GrNewExpression; + } + public GroovyCompletionContributor() { + extend(CompletionType.BASIC, psiElement(PsiElement.class), new CompletionProvider() { + @Override + protected void addCompletions(@NotNull CompletionParameters parameters, + ProcessingContext context, + @NotNull final CompletionResultSet result) { + final PsiElement position = parameters.getPosition(); + final PsiElement reference = position.getParent(); + if (reference == null) return; + if (isReferenceInNewExpression(reference)) { + //reference in new Expression + ((GrCodeReferenceElement)reference).processVariants(new Consumer() { + public void consume(Object element) { + if (element instanceof PsiClass) { + final PsiClass clazz = (PsiClass)element; + final MutableLookupElement lookupElement = LookupElementFactory.getInstance().createLookupElement(clazz); + result.addElement(GroovyCompletionUtil.setTailTypeForConstructor(clazz, lookupElement)); + } + else { + result.addElement(LookupItemUtil.objectToLookupItem(element)); + } + } + }); + + } + else if (reference instanceof GrReferenceElement) { + ((GrReferenceElement)reference).processVariants(new Consumer() { + public void consume(Object element) { + result.addElement(LookupItemUtil.objectToLookupItem(element)); + } + }); + } + } + }); + extend(CompletionType.SMART, AFTER_NEW, new CompletionProvider(false) { public void addCompletions(@NotNull final CompletionParameters parameters, final ProcessingContext matchingContext, diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java new file mode 100644 index 000000000000..cd1871292fdb --- /dev/null +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java @@ -0,0 +1,152 @@ +/* + * Copyright 2000-2010 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.plugins.groovy.lang.completion; + +import com.intellij.codeInsight.completion.*; +import com.intellij.codeInsight.lookup.LookupElement; +import com.intellij.codeInsight.lookup.LookupItemUtil; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.util.Computable; +import com.intellij.patterns.ElementPattern; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiType; +import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.util.Consumer; +import com.intellij.util.ProcessingContext; +import gnu.trove.THashSet; +import gnu.trove.TObjectHashingStrategy; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral; +import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider; +import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint; + +import java.util.Arrays; +import java.util.Set; + +import static com.intellij.patterns.PlatformPatterns.psiElement; + +/** + * @author Maxim.Medvedev + */ +public class GroovySmartCompletionContributor extends CompletionContributor { + private static final ElementPattern INSIDE_EXPRESSION = psiElement().withParent(GrExpression.class); + private static final TObjectHashingStrategy EXPECTED_TYPE_INFO_STRATEGY = + new TObjectHashingStrategy() { + public int computeHashCode(final TypeConstraint object) { + return object.getType().hashCode(); + } + + public boolean equals(final TypeConstraint o1, final TypeConstraint o2) { + return o1.getClass().equals(o2.getClass()) && o1.getType().equals(o2.getType()); + } + }; + + public GroovySmartCompletionContributor() { + extend(CompletionType.SMART, INSIDE_EXPRESSION, new CompletionProvider() { + @Override + protected void addCompletions(@NotNull final CompletionParameters params, + ProcessingContext context, + @NotNull final CompletionResultSet result) { + final PsiElement position = params.getPosition(); + if (position.getParent() instanceof GrLiteral) return; + + final THashSet _infos = new THashSet(); + ApplicationManager.getApplication().runReadAction(new Runnable() { + public void run() { + _infos.addAll(Arrays.asList(getExpectedTypes(params))); + } + }); + final Set infos = ApplicationManager.getApplication().runReadAction(new Computable>() { + public Set compute() { + return new THashSet(_infos, EXPECTED_TYPE_INFO_STRATEGY); + } + }); + + + final PsiElement reference = position.getParent(); + if (reference == null) return; + if (reference instanceof GrReferenceElement) { + ((GrReferenceElement)reference).processVariants(new Consumer() { + public void consume(Object variant) { + PsiType type = null; + if (variant instanceof PsiElement) { + type = getTypeByElement((PsiElement)variant, position); + } + else if (variant instanceof String) { + if ("true".equals(variant) || "false".equals(variant)) { + type = PsiType.BOOLEAN; + } + } + if (type == null) return; + for (TypeConstraint info : infos) { + if (info.satisfied(type, position.getManager(), GlobalSearchScope.allScope(position.getProject()))) { + final LookupElement lookupElement = LookupItemUtil.objectToLookupItem(variant); + result.addElement(lookupElement); + break; + } + } + + } + }); + } + } + }); + } + + @Nullable + public static TypeConstraint[] getExpectedTypes(CompletionParameters params) { + final PsiElement position = params.getPosition(); + final GrExpression expression = PsiTreeUtil.getParentOfType(position, GrExpression.class); + if (expression != null) { + return GroovyExpectedTypesProvider.calculateTypeConstraints(expression); + } + return null; + } + + @Nullable + public static PsiType getTypeByElement(PsiElement element, PsiElement context) { + //if(!element.isValid()) return null; + if (element instanceof PsiType) { + return (PsiType)element; + } + if (element instanceof PsiClass) { + return PsiType.getJavaLangClass(context.getManager(), GlobalSearchScope.allScope(context.getProject())); + } + if (element instanceof PsiMethod) { + return ((PsiMethod)element).getReturnType(); + } + if (element instanceof GrVariable) { + return ((GrVariable)element).getTypeGroovy(); + } +/* if(element instanceof PsiKeyword){ + return getKeywordItemType(context, element.getText()); + }*/ + if (element instanceof GrExpression) { + return ((GrExpression)element).getType(); + } + + return null; + } + + +} diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parameterInfo/GroovyParameterInfoHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parameterInfo/GroovyParameterInfoHandler.java index 019dfba4f977..a312c60674a0 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parameterInfo/GroovyParameterInfoHandler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parameterInfo/GroovyParameterInfoHandler.java @@ -68,7 +68,7 @@ public class GroovyParameterInfoHandler implements ParameterInfoHandler consumer); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/expressions/GrNewExpression.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/expressions/GrNewExpression.java index d2976c684a7a..648a2e418b26 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/expressions/GrNewExpression.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/expressions/GrNewExpression.java @@ -16,9 +16,7 @@ package org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions; -import com.intellij.psi.PsiMethod; import org.jetbrains.annotations.Nullable; -import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; @@ -26,19 +24,13 @@ import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; /** * @author ilyas */ -public interface GrNewExpression extends GrCallExpression { +public interface GrNewExpression extends GrCallExpression, GrConstructorCall { @Nullable GrExpression getQualifier(); @Nullable GrCodeReferenceElement getReferenceElement(); - GroovyResolveResult[] multiResolveConstructor(); - - PsiMethod resolveConstructor(); - - GroovyResolveResult resolveConstructorGenerics(); - int getArrayCount(); @Nullable diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java similarity index 63% rename from plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesUtil.java rename to plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java index 923a3fff3c41..ed726ad77086 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java @@ -15,25 +15,26 @@ */ package org.jetbrains.plugins.groovy.lang.psi.expectedTypes; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiType; +import com.intellij.psi.*; +import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrIfStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrParametersOwner; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrWhileStatement; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrIfStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrThrowStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrUnaryExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; @@ -44,10 +45,13 @@ import java.util.List; /** * @author ven */ -public class GroovyExpectedTypesUtil { +public class GroovyExpectedTypesProvider { + private GroovyExpectedTypesProvider() { + } + public static TypeConstraint[] calculateTypeConstraints(GrExpression expression) { MyCalculator calculator = new MyCalculator(expression); - ((GroovyPsiElement) expression.getParent()).accept(calculator); + ((GroovyPsiElement)expression.getParent()).accept(calculator); return calculator.getResult(); } @@ -58,117 +62,119 @@ public class GroovyExpectedTypesUtil { public MyCalculator(GrExpression expression) { myExpression = expression; - } - - public void visitElement(GroovyPsiElement element) { - makeDefault(); + myResult = new TypeConstraint[]{SubtypeConstraint.create("java.lang.Object", myExpression)}; } public void visitReturnStatement(GrReturnStatement returnStatement) { GrParametersOwner parent = PsiTreeUtil.getParentOfType(returnStatement, GrMethod.class, GrClosableBlock.class); if (parent instanceof GrMethod) { - GrTypeElement typeElement = ((GrMethod) parent).getReturnTypeElementGroovy(); + GrTypeElement typeElement = ((GrMethod)parent).getReturnTypeElementGroovy(); if (typeElement != null) { PsiType type = typeElement.getType(); - myResult = new TypeConstraint[] {SubtypeConstraint.create(type)}; - return; + myResult = new TypeConstraint[]{SubtypeConstraint.create(type)}; } } - makeDefault(); } public void visitVariable(GrVariable variable) { if (myExpression.equals(variable.getInitializerGroovy())) { PsiType type = variable.getDeclaredType(); if (type != null) { - myResult = new TypeConstraint[] {new SubtypeConstraint(type, type)}; - return; + myResult = new TypeConstraint[]{new SubtypeConstraint(type, type)}; } } - makeDefault(); } public void visitMethodCallExpression(GrMethodCallExpression methodCall) { if (myExpression.equals(methodCall.getInvokedExpression())) { myResult = new TypeConstraint[]{SubtypeConstraint.create("groovy.lang.Closure", methodCall)}; - } else { - makeDefault(); } } public void visitIfStatement(GrIfStatement ifStatement) { if (myExpression.equals(ifStatement.getCondition())) { - myResult = new TypeConstraint[] {new SubtypeConstraint(TypesUtil.getJavaLangObject(ifStatement), PsiType.BOOLEAN)}; - } else makeDefault(); + myResult = new TypeConstraint[]{new SubtypeConstraint(TypesUtil.getJavaLangObject(ifStatement), PsiType.BOOLEAN)}; + } } public void visitWhileStatement(GrWhileStatement whileStatement) { if (myExpression.equals(whileStatement.getCondition())) { - myResult = new TypeConstraint[] {new SubtypeConstraint(TypesUtil.getJavaLangObject(whileStatement), PsiType.BOOLEAN)}; - } else makeDefault(); + myResult = new TypeConstraint[]{new SubtypeConstraint(TypesUtil.getJavaLangObject(whileStatement), PsiType.BOOLEAN)}; + } } public void visitTraditionalForClause(GrTraditionalForClause forClause) { if (myExpression.equals(forClause.getCondition())) { - myResult = new TypeConstraint[] {new SubtypeConstraint(TypesUtil.getJavaLangObject(forClause), PsiType.BOOLEAN)}; - } else makeDefault(); + myResult = new TypeConstraint[]{new SubtypeConstraint(TypesUtil.getJavaLangObject(forClause), PsiType.BOOLEAN)}; + } } public void visitArgumentList(GrArgumentList list) { PsiElement parent = list.getParent(); List constraints = new ArrayList(); if (parent instanceof GrCallExpression) { - GroovyResolveResult[] variants = ((GrCallExpression) parent).getMethodVariants(); - int idx = getIndex(list); + GroovyResolveResult[] variants = ((GrCallExpression)parent).getMethodVariants(); + int idx = list.getExpressionArgumentIndex(myExpression); for (GroovyResolveResult variant : variants) { PsiElement element = variant.getElement(); + PsiParameter[] parameters = null; if (element instanceof GrParametersOwner) { - GrParameter[] parameters = ((GrParametersOwner) element).getParameters(); - if (parameters.length <= idx) continue; - PsiType parameterType = variant.getSubstitutor().substitute(parameters[idx].getType()); - constraints.add(SubtypeConstraint.create(parameterType)); + parameters = ((GrParametersOwner)element).getParameters(); } + else if (element instanceof PsiMethod) { + parameters = ((PsiMethod)element).getParameterList().getParameters(); + } + if (parameters == null || parameters.length <= idx) continue; + PsiType parameterType = variant.getSubstitutor().substitute(parameters[idx].getType()); + constraints.add(SubtypeConstraint.create(parameterType)); } } - if (constraints.isEmpty()) makeDefault(); - else { + if (!constraints.isEmpty()) { myResult = constraints.toArray(new TypeConstraint[constraints.size()]); } } - private int getIndex(GrArgumentList list) { - GrExpression[] arguments = list.getExpressionArguments(); - for (int i = 0; i < arguments.length; i++) { - if (myExpression.equals(arguments[i])) return i; - } - return -1; - } - public void visitAssignmentExpression(GrAssignmentExpression expression) { GrExpression rValue = expression.getRValue(); if (myExpression.equals(rValue)) { PsiType lType = expression.getLValue().getType(); - if (lType == null) makeDefault(); - else { + if (lType != null) { myResult = new TypeConstraint[]{SubtypeConstraint.create(lType)}; } - } else if (myExpression.equals(expression.getLValue())) { - if (rValue == null) makeDefault(); - else { + } + else if (myExpression.equals(expression.getLValue())) { + if (rValue != null) { PsiType rType = rValue.getType(); - if (rType == null) makeDefault(); - else { + if (rType != null) { myResult = new TypeConstraint[]{SupertypeConstraint.create(rType)}; } } } } - private void makeDefault() { - myResult = new TypeConstraint[]{ - SubtypeConstraint.create("java.lang.Object", myExpression) + @Override + public void visitThrowStatement(GrThrowStatement throwStatement) { + final PsiClassType trowable = PsiType.getJavaLangTrowable(myExpression.getManager(), throwStatement.getResolveScope()); + myResult = new TypeConstraint[]{SubtypeConstraint.create(trowable)}; + } + + @Override + public void visitUnaryExpression(final GrUnaryExpression expression) { + TypeConstraint constraint = new TypeConstraint(PsiType.INT) { + @Override + public boolean satisfied(PsiType type, PsiManager manager, GlobalSearchScope scope) { + return TypesUtil + .getOverloadedOperatorCandidates(TypesUtil.boxPrimitiveType(type, manager, scope), expression.getOperationTokenType(), + expression, PsiType.EMPTY_ARRAY).length > 0; + } + + @Override + public PsiType getDefaultType() { + return PsiType.INT; + } }; + myResult = new TypeConstraint[]{constraint}; } public TypeConstraint[] getResult() { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SubtypeConstraint.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SubtypeConstraint.java index ae8a10706b31..80821405f521 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SubtypeConstraint.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SubtypeConstraint.java @@ -15,9 +15,13 @@ */ package org.jetbrains.plugins.groovy.lang.psi.expectedTypes; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiType; import com.intellij.psi.PsiClassType; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiManager; +import com.intellij.psi.PsiType; +import com.intellij.psi.search.GlobalSearchScope; +import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; + import static org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType; /** @@ -31,8 +35,8 @@ public class SubtypeConstraint extends TypeConstraint { myDefaultType = defaultType; } - public boolean satisfied(PsiType type){ - return myType.isAssignableFrom(type); + public boolean satisfied(PsiType type, PsiManager manager, GlobalSearchScope scope){ + return TypesUtil.isAssignableByMethodCallConversion(getType(), type, manager, scope); } public PsiType getDefaultType() { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SupertypeConstraint.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SupertypeConstraint.java index dd43b02732a9..f982d7a069a2 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SupertypeConstraint.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/SupertypeConstraint.java @@ -15,9 +15,13 @@ */ package org.jetbrains.plugins.groovy.lang.psi.expectedTypes; -import com.intellij.psi.PsiType; -import com.intellij.psi.PsiElement; import com.intellij.psi.PsiClassType; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiManager; +import com.intellij.psi.PsiType; +import com.intellij.psi.search.GlobalSearchScope; +import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; + import static org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType; /** @@ -31,8 +35,8 @@ public class SupertypeConstraint extends TypeConstraint { myDefaultType = defaultType; } - public boolean satisfied(PsiType type){ - return type.isAssignableFrom(myType); + public boolean satisfied(PsiType type, PsiManager manager, GlobalSearchScope scope){ + return TypesUtil.isAssignableByMethodCallConversion(type, getType(), manager, scope); } public PsiType getDefaultType() { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeConstraint.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeConstraint.java index dda1bc58e69c..289041380684 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeConstraint.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeConstraint.java @@ -15,7 +15,9 @@ */ package org.jetbrains.plugins.groovy.lang.psi.expectedTypes; +import com.intellij.psi.PsiManager; import com.intellij.psi.PsiType; +import com.intellij.psi.search.GlobalSearchScope; /** * @author ven @@ -23,7 +25,7 @@ import com.intellij.psi.PsiType; public abstract class TypeConstraint { protected final PsiType myType; - public abstract boolean satisfied(PsiType type); + public abstract boolean satisfied(PsiType type, PsiManager manager, GlobalSearchScope scope); public abstract PsiType getDefaultType(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeEquals.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeEquals.java index f451ccff15ee..2f45163941d3 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeEquals.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/TypeEquals.java @@ -15,9 +15,12 @@ */ package org.jetbrains.plugins.groovy.lang.psi.expectedTypes; -import com.intellij.psi.PsiType; -import com.intellij.psi.PsiElement; import com.intellij.psi.PsiClassType; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiManager; +import com.intellij.psi.PsiType; +import com.intellij.psi.search.GlobalSearchScope; + import static org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType; /** @@ -28,7 +31,7 @@ public class TypeEquals extends TypeConstraint { super(type); } - public boolean satisfied(PsiType type){ + public boolean satisfied(PsiType type, PsiManager manager, GlobalSearchScope scope){ return type.equals(myType); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/GrLabelReference.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/GrLabelReference.java index 48447a9d028b..8d526828c7fb 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/GrLabelReference.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/GrLabelReference.java @@ -19,6 +19,7 @@ package org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; +import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; @@ -88,7 +89,7 @@ public class GrLabelReference implements PsiReference { } context = context.getContext(); } - return result.toArray(new Object[result.size()]); + return ArrayUtil.toObjectArray(result); } public boolean isSoft() { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java index fd2eabd681fc..d00322776531 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java @@ -196,26 +196,34 @@ public class GrModifierListImpl extends GroovyBaseElementImpl consumer, GrReferenceExpressionImpl refExpr) { PsiElement refParent = refExpr.getParent(); - List namedArgsVariants = getNamedArgsVariants(refParent); + processArgsVariants(consumer, refParent); final GrExpression qualifier = refExpr.getQualifierExpression(); Object[] propertyVariants = getVariantsImpl(refExpr, CompletionProcessor.createPropertyCompletionProcessor(refExpr)); @@ -85,34 +89,31 @@ public class CompleteReferenceExpression { if (type instanceof PsiClassType) { PsiClass clazz = ((PsiClassType)type).resolve(); if (clazz != null) { - Set accessedPropertyNames = new THashSet(); - List variantList = new ArrayList(getPropertyVariants(refExpr, clazz, accessedPropertyNames)); + Set accessedPropertyNames = processPropertyVariants(consumer, refExpr, clazz); for (Object variant : propertyVariants) { - if (variant instanceof PsiField && accessedPropertyNames.contains(((PsiField) variant).getName())) { + if (variant instanceof PsiField && accessedPropertyNames.contains(((PsiField)variant).getName())) { continue; } - variantList.add(variant); + consumer.consume(variant); } - - propertyVariants = variantList.toArray(new Object[variantList.size()]); } } - - propertyVariants = - ArrayUtil.mergeArrays(propertyVariants, namedArgsVariants.toArray(new Object[namedArgsVariants.size()]), Object.class); + else { + for (Object variant : propertyVariants) { + consumer.consume(variant); + } + } if (refExpr.getKind() == GrReferenceExpressionImpl.Kind.TYPE_OR_PROPERTY) { ResolverProcessor classVariantsCollector = CompletionProcessor.createClassCompletionProcessor(refExpr); final Object[] classVariants = getVariantsImpl(refExpr, classVariantsCollector); - return ArrayUtil.mergeArrays(propertyVariants, classVariants, Object.class); - } - else { - return propertyVariants; + for (Object variant : classVariants) { + consumer.consume(variant); + } } } - private static List getNamedArgsVariants(PsiElement refParent) { - List namedArgsVariants = new LinkedList(); + private static void processArgsVariants(Consumer consumer, PsiElement refParent) { if (refParent instanceof GrArgumentList) { PsiElement refPParent = refParent.getParent(); if (refPParent instanceof GrCall) { @@ -141,17 +142,18 @@ public class CompleteReferenceExpression { if (element instanceof GrMethod) { Set[] parametersArray = ((GrMethod)element).getNamedParametersArray(); for (Set namedParameters : parametersArray) { - namedArgsVariants.addAll(namedParameters); + for (String parameter : namedParameters) { + consumer.consume(parameter); + } } } } } } - return namedArgsVariants; } - private static List getPropertyVariants(GrReferenceExpression refExpr, PsiClass clazz, Set accessedPropertyNames) { - List props = new ArrayList(); + private static Set processPropertyVariants(Consumer consumer, GrReferenceExpression refExpr, PsiClass clazz) { + Set accessedPropertyNames=new THashSet(); final PsiClass eventListener = JavaPsiFacade.getInstance(refExpr.getProject()).findClass("java.util.EventListener", refExpr.getResolveScope()); for (PsiMethod method : clazz.getAllMethods()) { @@ -159,17 +161,18 @@ public class CompleteReferenceExpression { if (GroovyPropertyUtils.isSimplePropertyAccessor(method)) { String prop = GroovyPropertyUtils.getPropertyName(method); accessedPropertyNames.add(prop); - props.add(LookupElementBuilder.create(prop).setIcon(GroovyIcons.PROPERTY)); + assert prop != null; + consumer.consume(LookupElementBuilder.create(prop).setIcon(GroovyIcons.PROPERTY)); } else if (eventListener != null) { - addListenerProperties(method, eventListener, props); + consumeListenerProperties(consumer, method, eventListener); } } } - return props; + return accessedPropertyNames; } - private static void addListenerProperties(PsiMethod method, PsiClass eventListenerClass, List result) { + private static void consumeListenerProperties(Consumer consumer, PsiMethod method, PsiClass eventListenerClass) { if (method.getName().startsWith("add") && method.getParameterList().getParametersCount() == 1) { final PsiParameter parameter = method.getParameterList().getParameters()[0]; final PsiType type = parameter.getType(); @@ -180,7 +183,7 @@ public class CompleteReferenceExpression { final PsiMethod[] listenerMethods = listenerClass.getMethods(); if (InheritanceUtil.isInheritorOrSelf(listenerClass, eventListenerClass, true)) { for (PsiMethod listenerMethod : listenerMethods) { - result.add(LookupElementBuilder.create(listenerMethod.getName()).setIcon(GroovyIcons.PROPERTY)); + consumer.consume(LookupElementBuilder.create(listenerMethod.getName()).setIcon(GroovyIcons.PROPERTY)); } } } @@ -270,6 +273,7 @@ public class CompleteReferenceExpression { if (!PsiUtil.isValidReferenceName(propName)) { propName = "'" + propName + "'"; } + assert propName != null; result.add(LookupElementBuilder.create(propName).setIcon(GroovyIcons.PROPERTY)); } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java index 945e4e7cfed8..7ff2441eee21 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java @@ -31,6 +31,7 @@ import com.intellij.psi.util.PropertyUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.ArrayUtil; +import com.intellij.util.Consumer; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NonNls; @@ -599,7 +600,7 @@ public class GrReferenceExpressionImpl extends GrReferenceElementImpl implements @NotNull public Object[] getVariants() { - return CompleteReferenceExpression.getVariants(this); + return ArrayUtil.EMPTY_OBJECT_ARRAY; } @@ -645,6 +646,10 @@ public class GrReferenceExpressionImpl extends GrReferenceElementImpl implements return (GroovyResolveResult[]) getManager().getResolveCache().resolveWithCaching(this, RESOLVER, false, incomplete); } + public void processVariants(Consumer consumer) { + CompleteReferenceExpression.processVariants(consumer, this); + } + @NotNull public GroovyResolveResult[] getSameNameVariants() { return RESOLVER.resolve(this, true); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java index e3049b8a6498..41cf8c4ad425 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java @@ -93,6 +93,28 @@ public class TypesUtil { @Nullable public static PsiType getOverloadedOperatorType(PsiType thisType, String operatorName, GroovyPsiElement place, PsiType[] argumentTypes) { + final GroovyResolveResult[] candidates = getOverloadedOperatorCandidates(thisType, operatorName, place, argumentTypes); + if (candidates.length == 1) { + final PsiElement element = candidates[0].getElement(); + if (element instanceof PsiMethod) { + return candidates[0].getSubstitutor().substitute(((PsiMethod)element).getReturnType()); + } + } + return null; + } + + @NotNull + public static GroovyResolveResult[] getOverloadedOperatorCandidates(PsiType thisType, + IElementType tokenType, + GroovyPsiElement place, + PsiType[] argumentTypes) { + return getOverloadedOperatorCandidates(thisType, ourOperationsToOperatorNames.get(tokenType), place, argumentTypes); + } + @NotNull + public static GroovyResolveResult[] getOverloadedOperatorCandidates(PsiType thisType, + String operatorName, + GroovyPsiElement place, + PsiType[] argumentTypes) { if (operatorName != null) { MethodResolverProcessor processor = new MethodResolverProcessor(operatorName, place, false, thisType, argumentTypes, PsiType.EMPTY_ARRAY); @@ -101,21 +123,17 @@ public class TypesUtil { final PsiClassType.ClassResolveResult resolveResult = classtype.resolveGenerics(); final PsiClass lClass = resolveResult.getElement(); if (lClass != null) { - lClass.processDeclarations(processor, ResolveState.initial().put(PsiSubstitutor.KEY, resolveResult.getSubstitutor()), null, place); + lClass + .processDeclarations(processor, ResolveState.initial().put(PsiSubstitutor.KEY, resolveResult.getSubstitutor()), null, place); } } ResolveUtil.processNonCodeMethods(thisType, processor, place.getProject(), place, false); - final GroovyResolveResult[] candidates = processor.getCandidates(); - if (candidates.length == 1) { - final PsiElement element = candidates[0].getElement(); - if (element instanceof PsiMethod) { - return candidates[0].getSubstitutor().substitute(((PsiMethod)element).getReturnType()); - } - } + return processor.getCandidates(); } - return null; + return GroovyResolveResult.EMPTY_ARRAY; } + private static final Map ourPrimitiveTypesToClassNames = new HashMap(); private static final String NULL = "null"; private static final String JAVA_MATH_BIG_DECIMAL = "java.math.BigDecimal"; @@ -193,23 +211,17 @@ public class TypesUtil { } public static boolean isAssignable(PsiType lType, PsiType rType, PsiManager manager, GlobalSearchScope scope) { + if (isAssignableByMethodCallConversion(lType, rType, manager, scope)){ + return true; + } //all numeric types are assignable if (isNumericType(lType)) { return isNumericType(rType) || rType.equals(PsiType.NULL); } - if (rType instanceof GrTupleType) { - final GrTupleType tuple = (GrTupleType)rType; - if (tuple.getComponentTypes().length == 0) { - if (lType instanceof PsiArrayType || - InheritanceUtil.isInheritor(lType, JAVA_UTIL_LIST) || - InheritanceUtil.isInheritor(lType, JAVA_UTIL_SET)) { - return true; - } - } + else if (lType.equalsToText(JAVA_LANG_STRING)) { + return true; } - if (lType.equalsToText(JAVA_LANG_STRING)) return true; - rType = boxPrimitiveType(rType, manager, scope); lType = boxPrimitiveType(lType, manager, scope); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java index c89295c286b0..6b0016536bcb 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java @@ -16,15 +16,13 @@ package org.jetbrains.plugins.groovy.lang.psi.impl.types; -import com.intellij.codeInsight.lookup.LookupElement; -import com.intellij.codeInsight.lookup.LookupElementFactory; -import com.intellij.codeInsight.lookup.MutableLookupElement; import com.intellij.lang.ASTNode; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.ResolveCache; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtil; +import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.completion.GroovyCompletionUtil; @@ -122,6 +120,10 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement } private ReferenceKind getKind(boolean forCompletion) { + if (isClassReferenceForNew()) { + return CLASS_OR_PACKAGE; + } + PsiElement parent = getParent(); if (parent instanceof GrCodeReferenceElement) { ReferenceKind parentKind = ((GrCodeReferenceElementImpl) parent).getKind(forCompletion); @@ -197,11 +199,7 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement @NotNull public Object[] getVariants() { - if (isClassReferenceForNew()) { - return getVariantsForNewExpression(); - } - - return getVariantsImpl(getKind(true)); + return ArrayUtil.EMPTY_OBJECT_ARRAY; } private boolean isClassReferenceForNew() { @@ -210,30 +208,7 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement return parent instanceof GrNewExpression; } - private Object[] getVariantsForNewExpression() { - final Object[] classVariants = getVariantsImpl(CLASS_OR_PACKAGE); - List result = new ArrayList(); - for (Object variant : classVariants) { - if (variant instanceof PsiClass) { - final PsiClass clazz = (PsiClass) variant; - final MutableLookupElement lookupElement = LookupElementFactory.getInstance().createLookupElement(clazz); - result.add(GroovyCompletionUtil.setTailTypeForConstructor(clazz, lookupElement)); - } else if (variant instanceof LookupElement) { - final LookupElement lookupElement = (LookupElement) variant; - final Object obj = lookupElement.getObject(); - if (obj instanceof PsiClass) { - result.add(GroovyCompletionUtil.setTailTypeForConstructor((PsiClass) obj, lookupElement)); - } else { - result.add(lookupElement); - } - } else { - result.add(variant); - } - } - return result.toArray(new Object[result.size()]); - } - - private Object[] getVariantsImpl(ReferenceKind kind) { + private void processVariantsImpl(ReferenceKind kind, Consumer consumer) { switch (kind) { case STATIC_MEMBER_FQ: { final GrCodeReferenceElement qualifier = getQualifier(); @@ -241,21 +216,19 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement final PsiElement resolve = qualifier.resolve(); if (resolve instanceof PsiClass) { final PsiClass clazz = (PsiClass) resolve; - List result = new ArrayList(); for (PsiField field : clazz.getFields()) { if (field.hasModifierProperty(PsiModifier.STATIC)) { - result.add(field); + consumer.consume(field); } } for (PsiMethod method : clazz.getMethods()) { if (method.hasModifierProperty(PsiModifier.STATIC)) { - result.add(method); + consumer.consume(method); } } - - return result.toArray(new PsiElement[result.size()]); + return; } } } @@ -271,17 +244,26 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement if (parentPackage != null) { final GlobalSearchScope scope = getResolveScope(); if (kind == PACKAGE_FQ) { - return parentPackage.getSubPackages(scope); + for (PsiPackage aPackage : parentPackage.getSubPackages(scope)) { + consumer.consume(aPackage); + } + return; } else { if (kind == CLASS_FQ) { - return parentPackage.getClasses(scope); + for (PsiClass aClass : parentPackage.getClasses(scope)) { + consumer.consume(aClass); + } + return; } else { final PsiPackage[] subpackages = parentPackage.getSubPackages(scope); final PsiClass[] classes = parentPackage.getClasses(scope); - PsiElement[] result = new PsiElement[subpackages.length + classes.length]; - System.arraycopy(subpackages, 0, result, 0, subpackages.length); - System.arraycopy(classes, 0, result, subpackages.length, classes.length); - return result; + for (PsiPackage aPackage : subpackages) { + consumer.consume(aPackage); + } + for (PsiClass aClass : classes) { + consumer.consume(aClass); + } + return; } } } @@ -296,21 +278,31 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement if (qualifierResolved instanceof PsiPackage) { PsiPackage aPackage = (PsiPackage) qualifierResolved; PsiClass[] classes = aPackage.getClasses(getResolveScope()); - if (kind == CLASS) return classes; + + for (PsiClass aClass : classes) { + consumer.consume(aClass); + } + if (kind == CLASS) return; + PsiPackage[] subpackages = aPackage.getSubPackages(); - return ArrayUtil.mergeArrays(classes, subpackages, Object.class); + for (PsiPackage subpackage : subpackages) { + consumer.consume(subpackage); + } } else if (qualifierResolved instanceof PsiClass) { - return ((PsiClass) qualifierResolved).getInnerClasses(); + for (PsiClass aClass : ((PsiClass)qualifierResolved).getInnerClasses()) { + consumer.consume(aClass); + } } } else { - ResolverProcessor processor = CompletionProcessor.createClassCompletionProcessor(this); - ResolveUtil.treeWalkUp(this, processor, false); - return GroovyCompletionUtil.getCompletionVariants(processor.getCandidates()); + ResolverProcessor classProcessor = CompletionProcessor.createClassCompletionProcessor(this); + ResolveUtil.treeWalkUp(this, classProcessor, false); + + for (Object o : GroovyCompletionUtil.getCompletionVariants(classProcessor.getCandidates())) { + consumer.consume(o); + } } } } - - return ArrayUtil.EMPTY_OBJECT_ARRAY; } public boolean isSoft() { @@ -489,4 +481,8 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl implement return (GroovyResolveResult[])results; } + + public void processVariants(Consumer consumer) { + processVariantsImpl(getKind(true), consumer); + } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrEnumConstantElementType.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrEnumConstantElementType.java index 105944040d49..3b2de1cb7e9f 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrEnumConstantElementType.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrEnumConstantElementType.java @@ -21,6 +21,7 @@ import com.intellij.psi.stubs.IndexSink; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; +import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.StringRef; @@ -59,7 +60,7 @@ public class GrEnumConstantElementType extends GrStubElementType() { @@ -68,7 +69,7 @@ public class GrEnumConstantElementType extends GrStubElementType final GrModifierList modifiers = psi.getModifierList(); String[] annNames; if (modifiers == null) { - annNames = new String[0]; + annNames = ArrayUtil.EMPTY_STRING_ARRAY; } else { final GrAnnotation[] annotations = modifiers.getAnnotations(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java index 69fa1301397c..7f681e2ada76 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java @@ -348,7 +348,7 @@ public class ResolveUtil { return elements; } - public static GroovyResolveResult[] filterSameSignatureCandidates(Collection candidates) { + public static GroovyResolveResult[] filterSameSignatureCandidates(Collection candidates, int argumentCount) { GroovyResolveResult[] array = candidates.toArray(new GroovyResolveResult[candidates.size()]); if (array.length == 1) return array; @@ -365,10 +365,10 @@ public class ResolveUtil { PsiElement element = otherResolveResult.getElement(); if (element instanceof PsiMethod) { PsiMethod method = (PsiMethod)element; - if (dominated(currentMethod, array[i].getSubstitutor(), method, otherResolveResult.getSubstitutor())) { + if (dominated(currentMethod, array[i].getSubstitutor(), method, otherResolveResult.getSubstitutor(), argumentCount)) { continue Outer; } - else if (dominated(method, otherResolveResult.getSubstitutor(), currentMethod, array[i].getSubstitutor())) { + else if (dominated(method, otherResolveResult.getSubstitutor(), currentMethod, array[i].getSubstitutor(), argumentCount)) { iterator.remove(); } } @@ -384,11 +384,13 @@ public class ResolveUtil { public static boolean dominated(PsiMethod method1, PsiSubstitutor substitutor1, PsiMethod method2, - PsiSubstitutor substitutor2) { //method1 has more general parameter types thn method2 + PsiSubstitutor substitutor2, + int argumentCount) { //method1 has more general parameter types then method2 if (!method1.getName().equals(method2.getName())) return false; PsiParameter[] params1 = method1.getParameterList().getParameters(); PsiParameter[] params2 = method2.getParameterList().getParameters(); + if (argumentCount != params1.length && argumentCount == params2.length) return true; if (params1.length != params2.length) return false; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/CompletionProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/CompletionProcessor.java index 16209a63aa01..86f37a322fca 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/CompletionProcessor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/CompletionProcessor.java @@ -20,6 +20,7 @@ import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiType; import com.intellij.psi.ResolveState; +import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; @@ -53,8 +54,9 @@ public class CompletionProcessor extends ResolverProcessor { return new CompletionProcessor(place, EnumSet.of(ResolveKind.PACKAGE, ResolveKind.CLASS), null); } + @NotNull public GroovyResolveResult[] getCandidates() { if (myCandidates.size() == 0) return GroovyResolveResult.EMPTY_ARRAY; - return ResolveUtil.filterSameSignatureCandidates(myCandidates); + return ResolveUtil.filterSameSignatureCandidates(myCandidates, -1); } } \ No newline at end of file diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/MethodResolverProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/MethodResolverProcessor.java index d43dcbb5c16f..cf905db7672f 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/MethodResolverProcessor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/MethodResolverProcessor.java @@ -22,6 +22,7 @@ import com.intellij.psi.*; import com.intellij.psi.scope.JavaScopeProcessorEvent; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; @@ -207,12 +208,13 @@ public class MethodResolverProcessor extends ResolverProcessor { return rType; } + @NotNull public GroovyResolveResult[] getCandidates() { if (!myCandidates.isEmpty()) { return filterCandidates(); } if (!myInapplicableCandidates.isEmpty()) { - return ResolveUtil.filterSameSignatureCandidates(myInapplicableCandidates); + return ResolveUtil.filterSameSignatureCandidates(myInapplicableCandidates, myArgumentTypes != null ? myArgumentTypes.length : -1); } return GroovyResolveResult.EMPTY_ARRAY; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/PropertyResolverProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/PropertyResolverProcessor.java index 8b23c8277b72..2974c45b0f72 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/PropertyResolverProcessor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/PropertyResolverProcessor.java @@ -20,6 +20,7 @@ import com.intellij.openapi.util.Key; import com.intellij.psi.*; import com.intellij.psi.scope.NameHint; import com.intellij.psi.util.PsiTreeUtil; +import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; @@ -97,6 +98,7 @@ public class PropertyResolverProcessor extends ResolverProcessor { return containingClass.findFieldByName(fieldName, false) != null; } + @NotNull public GroovyResolveResult[] getCandidates() { if (myProperty != null) { if (myCandidates.isEmpty()) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/ResolverProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/ResolverProcessor.java index 21c614da63a5..ce2ca46b45e5 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/ResolverProcessor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/ResolverProcessor.java @@ -23,18 +23,19 @@ import com.intellij.psi.scope.NameHint; import com.intellij.psi.scope.PsiScopeProcessor; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; -import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement; import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyResolveResultImpl; -import static org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint.ResolveKind.*; +import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; +import static org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint.ResolveKind.*; + /** * @author ven */ @@ -110,6 +111,7 @@ public class ResolverProcessor implements PsiScopeProcessor, NameHint, ClassHint return true; } + @NotNull public GroovyResolveResult[] getCandidates() { return myCandidates.toArray(new GroovyResolveResult[myCandidates.size()]); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extractMethod/ExtractMethodUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extractMethod/ExtractMethodUtil.java index 84b041283049..57d6423fb6ac 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extractMethod/ExtractMethodUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extractMethod/ExtractMethodUtil.java @@ -101,7 +101,8 @@ public class ExtractMethodUtil { if (helper.isReturnStatement()) { return factory.createStatementFromText("return " + callExpression.getText()); } else if (name != null && mustAddVariableDeclaration(statements, name)) { - return factory.createVariableDeclaration(new String[0], callExpression, type.equalsToText("java.lang.Object") ? null : type, name); + return factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, callExpression, + type.equalsToText("java.lang.Object") ? null : type, name); } else { return factory.createExpressionFromText(name + "= " + callExpression.getText()); } @@ -239,7 +240,7 @@ public class ExtractMethodUtil { if (type != PsiType.VOID && outputName != null && !outputIsParameter && !mustAddVariableDeclaration(helper.getStatements(), outputName) && !containVariableDeclaration(helper.getStatements(), outputName)) { - GrVariableDeclaration decl = factory.createVariableDeclaration(new String[0], null, type, outputName); + GrVariableDeclaration decl = factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, null, type, outputName); buffer.append(decl.getText()).append("\n"); } if (!ExtractMethodUtil.isSingleExpression(helper.getStatements())) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyMethodInliner.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyMethodInliner.java index a7e9f19f5cda..21a3ca5ddc3e 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyMethodInliner.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyMethodInliner.java @@ -34,6 +34,7 @@ import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.usageView.UsageInfo; +import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; @@ -145,7 +146,7 @@ public class GroovyMethodInliner implements InlineHandler.Inliner { while (qualifier instanceof GrParenthesizedExpression) { qualifier = ((GrParenthesizedExpression) qualifier).getOperand(); } - qualifierDeclaration = factory.createVariableDeclaration(new String[0], qualifier, null, qualName); + qualifierDeclaration = factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, qualifier, null, qualName); innerQualifier = ((GrReferenceExpression) factory.createExpressionFromText(qualName)); } else { innerQualifier = ((GrReferenceExpression) qualifier); @@ -212,7 +213,7 @@ public class GroovyMethodInliner implements InlineHandler.Inliner { // Process method return statements if (returnCount > 1 && PsiType.VOID != methodType && !isTailMethodCall) { PsiType type = methodType != null && methodType.equalsToText("java.lang.Object") ? null : methodType; - GrVariableDeclaration resultDecl = factory.createVariableDeclaration(new String[0], null, type, resultName); + GrVariableDeclaration resultDecl = factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, null, type, resultName); GrStatement statement = ((GrStatementOwner) owner).addStatementBefore(resultDecl, anchor); PsiUtil.shortenReferences(statement); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/GroovyElementPresentation.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/GroovyElementPresentation.java deleted file mode 100644 index fc10b97d7a0e..000000000000 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/GroovyElementPresentation.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2000-2009 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.plugins.groovy.structure; - -import com.intellij.psi.*; -import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; -import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement; - -/** - * User: Dmitry.Krasilschikov - * Date: 21.05.2007 - */ -public class GroovyElementPresentation { - public static String getPresentableText(PsiElement element) { - assert element != null; - - if (element instanceof GroovyFileBase) { - return getFilePresentableText(((GroovyFileBase) element)); - - } else if (element instanceof GrTypeDefinition) { - return getTypeDefinitionPresentableText(((GrTypeDefinition) element)); - - } else if (element instanceof GrMethod) { - return getMethodPresentableText(((GrMethod) element)); - } else { - return element.getText(); - } - } - - public static String getVariablePresentableText(GrVariable variable) { - StringBuffer presentableText = new StringBuffer(); - - presentableText.append(variable.getName()); - GrTypeElement varTypeElement = variable.getTypeElementGroovy(); - - if (varTypeElement != null) { - PsiType varType = varTypeElement.getType(); - presentableText.append(":"); - presentableText.append(varType.getPresentableText()); - } - return presentableText.toString(); - } - - public static String getTypeDefinitionPresentableText(GrTypeDefinition typeDefinition) { - return typeDefinition.getNameIdentifierGroovy().getText(); - } - - public static String getMethodPresentableText(PsiMethod method) { - StringBuffer presentableText = new StringBuffer(); - presentableText.append(method.getName()); - presentableText.append(" "); - - PsiParameterList paramList = method.getParameterList(); - PsiParameter[] parameters = paramList.getParameters(); - - presentableText.append("("); - for (int i = 0; i < parameters.length; i++) { - if (i > 0) presentableText.append(", "); - presentableText.append(parameters[i].getType().getPresentableText()); - } - presentableText.append(")"); - - PsiType returnType = method.getReturnType(); - - if (returnType != null) { - presentableText.append(":"); - presentableText.append(returnType.getPresentableText()); - } - - return presentableText.toString(); - } - - public static String getFilePresentableText(GroovyFileBase file) { - return file.getName(); - } - - public static String getExpressionPresentableText(GrExpression expression) { - if (expression instanceof GrLiteral) { - final Object value = ((GrLiteral) expression).getValue(); - if (value == null || value.toString().length() == 0) return "\"\""; - } - - return expression.getText(); - } -} \ No newline at end of file diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyFileStructureViewElement.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyFileStructureViewElement.java index 75590f1e5745..d92ddcc5145e 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyFileStructureViewElement.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyFileStructureViewElement.java @@ -24,7 +24,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefini import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.GrTopStatement; import org.jetbrains.plugins.groovy.structure.elements.GroovyStructureViewElement; -import org.jetbrains.plugins.groovy.structure.itemsPresentations.impl.GroovyFileItemPresentation; +import org.jetbrains.plugins.groovy.structure.itemsPresentations.GroovyItemPresentation; import java.util.ArrayList; import java.util.List; @@ -40,7 +40,11 @@ public class GroovyFileStructureViewElement extends GroovyStructureViewElement { } public ItemPresentation getPresentation() { - return new GroovyFileItemPresentation((GroovyFileBase) myElement); + return new GroovyItemPresentation(myElement) { + public String getPresentableText() { + return ((GroovyFileBase) myElement).getName(); + } + }; } public TreeElement[] getChildren() { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyTypeDefinitionStructureViewElement.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyTypeDefinitionStructureViewElement.java index 87d733e82a58..c20258650598 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyTypeDefinitionStructureViewElement.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/elements/impl/GroovyTypeDefinitionStructureViewElement.java @@ -23,7 +23,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrSyntheticMethod; import org.jetbrains.plugins.groovy.structure.elements.GroovyStructureViewElement; -import org.jetbrains.plugins.groovy.structure.itemsPresentations.impl.GroovyTypeDefinitionItemPresentation; +import org.jetbrains.plugins.groovy.structure.itemsPresentations.GroovyItemPresentation; import java.util.ArrayList; import java.util.Arrays; @@ -35,7 +35,11 @@ public class GroovyTypeDefinitionStructureViewElement extends GroovyStructureVie } public ItemPresentation getPresentation() { - return new GroovyTypeDefinitionItemPresentation(((GrTypeDefinition)myElement)); + return new GroovyItemPresentation(myElement) { + public String getPresentableText() { + return ((GrTypeDefinition) myElement).getNameIdentifierGroovy().getText(); + } + }; } public TreeElement[] getChildren() { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyFileItemPresentation.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyFileItemPresentation.java deleted file mode 100644 index c96f6a99bebf..000000000000 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyFileItemPresentation.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2000-2009 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.plugins.groovy.structure.itemsPresentations.impl; - -import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase; -import org.jetbrains.plugins.groovy.structure.GroovyElementPresentation; -import org.jetbrains.plugins.groovy.structure.itemsPresentations.GroovyItemPresentation; - -/** - * User: Dmitry.Krasilschikov - * Date: 30.10.2007 - */ - public class GroovyFileItemPresentation extends GroovyItemPresentation { - public GroovyFileItemPresentation(GroovyFileBase myElement) { - super(myElement); - } - - public String getPresentableText() { - return GroovyElementPresentation.getFilePresentableText(((GroovyFileBase) myElement)); - } -} diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyMethodItemPresentation.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyMethodItemPresentation.java index 891962ae5458..89e5593dd4e5 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyMethodItemPresentation.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyMethodItemPresentation.java @@ -17,16 +17,16 @@ package org.jetbrains.plugins.groovy.structure.itemsPresentations.impl; import com.intellij.openapi.editor.colors.CodeInsightColors; import com.intellij.openapi.editor.colors.TextAttributesKey; -import com.intellij.openapi.util.Iconable; import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.psi.PsiMethod; -import org.jetbrains.annotations.Nullable; +import com.intellij.psi.PsiParameter; +import com.intellij.psi.PsiParameterList; +import com.intellij.psi.PsiType; import org.jetbrains.annotations.NotNull; -import org.jetbrains.plugins.groovy.structure.GroovyElementPresentation; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.structure.itemsPresentations.GroovyItemPresentation; -import javax.swing.*; - /** * User: Dmitry.Krasilschikov * Date: 31.10.2007 @@ -37,7 +37,29 @@ public class GroovyMethodItemPresentation extends GroovyItemPresentation { @NotNull @Override protected String compute() { - return GroovyElementPresentation.getMethodPresentableText(((PsiMethod) myElement)); + final PsiMethod method = (PsiMethod)myElement; + StringBuilder presentableText = new StringBuilder(); + presentableText.append(method.getName()); + presentableText.append(" "); + + PsiParameterList paramList = method.getParameterList(); + PsiParameter[] parameters = paramList.getParameters(); + + presentableText.append("("); + for (int i = 0; i < parameters.length; i++) { + if (i > 0) presentableText.append(", "); + presentableText.append(parameters[i].getType().getPresentableText()); + } + presentableText.append(")"); + + PsiType returnType = method instanceof GrMethod ? ((GrMethod)method).getDeclaredReturnType() : method.getReturnType(); + + if (returnType != null) { + presentableText.append(":"); + presentableText.append(returnType.getPresentableText()); + } + + return presentableText.toString(); } }; @@ -50,16 +72,6 @@ public class GroovyMethodItemPresentation extends GroovyItemPresentation { return myPresentableText.getValue(); } - @Nullable - public String getLocationString() { - return null; - } - - @Nullable - public Icon getIcon(boolean open) { - return myElement.getIcon(Iconable.ICON_FLAG_OPEN); - } - @Nullable public TextAttributesKey getTextAttributesKey() { return isInherit ? CodeInsightColors.NOT_USED_ELEMENT_ATTRIBUTES : null; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyTypeDefinitionItemPresentation.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyTypeDefinitionItemPresentation.java deleted file mode 100644 index efa4b1898f3b..000000000000 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/structure/itemsPresentations/impl/GroovyTypeDefinitionItemPresentation.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2000-2009 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.plugins.groovy.structure.itemsPresentations.impl; - -import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; -import org.jetbrains.plugins.groovy.structure.GroovyElementPresentation; -import org.jetbrains.plugins.groovy.structure.itemsPresentations.GroovyItemPresentation; - -/** - * User: Dmitry.Krasilschikov - * Date: 30.10.2007 - */ - public class GroovyTypeDefinitionItemPresentation extends GroovyItemPresentation { - public GroovyTypeDefinitionItemPresentation(GrTypeDefinition myElement) { - super(myElement); - } - - public String getPresentableText() { - return GroovyElementPresentation.getTypeDefinitionPresentableText((GrTypeDefinition) myElement); - } -} diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java index 347a8a03c5be..419fa4733123 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyCompletionTest.java @@ -17,9 +17,12 @@ package org.jetbrains.plugins.groovy; import com.intellij.codeInsight.completion.CompletionType; +import com.intellij.testFramework.UsefulTestCase; import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; import org.jetbrains.plugins.groovy.util.TestUtils; +import java.util.List; + /** * @author Maxim.Medvedev */ @@ -264,7 +267,30 @@ public class GroovyCompletionTest extends LightCodeInsightFixtureTestCase { } public void testPropertyWithSecondUpperLetter() throws Exception { - myFixture.testCompletionVariants(getTestName(false)+".groovy", "geteMail", "getePost"); + myFixture.testCompletionVariants(getTestName(false) + ".groovy", "geteMail", "getePost"); } + public void testSmartCompletionInAssignmentExpression() throws Throwable { + doSmartTest(); + } + + public void doSmartCompletion(String... variants) throws Exception { + myFixture.configureByFile(getTestName(false) + ".groovy"); + myFixture.complete(CompletionType.SMART); + final List list = myFixture.getLookupElementStrings(); + assertNotNull(list); + UsefulTestCase.assertSameElements(list, variants); + } + + public void testSimpleMethodParameter() throws Throwable { + doSmartCompletion("d1", "d2"); + } + + public void testReturnStatement() throws Exception { + doSmartCompletion("b", "b1", "b2", "foo"); + } + + public void testIncSmartCompletion() throws Exception { + doSmartCompletion("a", "b"); + } } diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyDebuggerEvaluatorTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyDebuggerEvaluatorTest.groovy index 702c2e7ae814..a2898ce49b07 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyDebuggerEvaluatorTest.groovy +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyDebuggerEvaluatorTest.groovy @@ -32,8 +32,26 @@ a++""", "[a:this.a] -> a" } + public void testQualifyClassNames() throws Exception { + myFixture.addFileToProject("com/Foo.groovy", """ +package com +class Foo { static bar = 2 }""") + + def bar = myFixture.addFileToProject("com/Bar.groovy", """ +package com +println 2""") + + myFixture.configureFromExistingVirtualFile bar.virtualFile + + evaluates "Foo.bar", "[:] -> com.Foo.bar" + } + private void evaluates(String text, String expression, String expected) throws IOException { myFixture.configureByText("_.groovy", text); + evaluates(expression, expected) + } + + private def evaluates(String expression, String expected) { def context = myFixture.file.findElementAt(myFixture.editor.caretModel.offset); def pair = GroovyCodeFragmentFactory.externalParameters(expression, context) diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/CompletionTestBase.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/CompletionTestBase.java index 436038ca7739..96b8da3defba 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/CompletionTestBase.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/CompletionTestBase.java @@ -5,9 +5,13 @@ import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.openapi.fileTypes.FileType; +import com.intellij.openapi.util.Condition; +import com.intellij.psi.PsiMember; import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.plugins.groovy.CompositeCompletionData; import org.jetbrains.plugins.groovy.GroovyFileType; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; import org.jetbrains.plugins.groovy.util.TestUtils; import java.util.Collections; @@ -43,6 +47,14 @@ public abstract class CompletionTestBase extends JavaCodeInsightFixtureTestCase final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myFixture.getEditor()); if (lookup != null) { List items = lookup.getItems(); + if (!addReferenceVariants()) { + items = ContainerUtil.findAll(items, new Condition() { + public boolean value(LookupElement lookupElement) { + final Object o = lookupElement.getObject(); + return !(o instanceof PsiMember) && !(o instanceof GrVariable); + } + }); + } Collections.sort(items, new Comparator() { public int compare(LookupElement o1, LookupElement o2) { return o1.getLookupString().compareTo(o2.getLookupString()); diff --git a/plugins/groovy/testdata/groovy/completion/IncSmartCompletion.groovy b/plugins/groovy/testdata/groovy/completion/IncSmartCompletion.groovy new file mode 100644 index 000000000000..ffd081ad97cc --- /dev/null +++ b/plugins/groovy/testdata/groovy/completion/IncSmartCompletion.groovy @@ -0,0 +1,15 @@ +class A{ + def next() { + return this; + } +} + +class B{ + def next() { + return this; + } +} + +A a=new A() +B b=new B() +++; \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/completion/ReturnStatement.groovy b/plugins/groovy/testdata/groovy/completion/ReturnStatement.groovy new file mode 100644 index 000000000000..fae09e457f8a --- /dev/null +++ b/plugins/groovy/testdata/groovy/completion/ReturnStatement.groovy @@ -0,0 +1,6 @@ +boolean foo(String s, Date d) { + boolean b=true; + Boolean b1= false; + def b2=false; + return +} \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/completion/SimpleMethodParameter.groovy b/plugins/groovy/testdata/groovy/completion/SimpleMethodParameter.groovy new file mode 100644 index 000000000000..74a5c2daa8f7 --- /dev/null +++ b/plugins/groovy/testdata/groovy/completion/SimpleMethodParameter.groovy @@ -0,0 +1,9 @@ +def method(Date date, String x, Date d) { + +} + +Date d1=new Date() +def d2=new Date() +String x="ds" + +method(d1, x, ) \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/completion/SmartCompletionInAssignmentExpression.groovy b/plugins/groovy/testdata/groovy/completion/SmartCompletionInAssignmentExpression.groovy new file mode 100644 index 000000000000..1be7b678d457 --- /dev/null +++ b/plugins/groovy/testdata/groovy/completion/SmartCompletionInAssignmentExpression.groovy @@ -0,0 +1,4 @@ +def foo = new Date() + +Date date +date = f \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/completion/SmartCompletionInAssignmentExpression_after.groovy b/plugins/groovy/testdata/groovy/completion/SmartCompletionInAssignmentExpression_after.groovy new file mode 100644 index 000000000000..9144559c6ccf --- /dev/null +++ b/plugins/groovy/testdata/groovy/completion/SmartCompletionInAssignmentExpression_after.groovy @@ -0,0 +1,4 @@ +def foo = new Date() + +Date date +date = foo \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/file12.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/file12.test index 9f61ae66c168..4ee2e0e4f740 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/file12.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/file12.test @@ -15,12 +15,14 @@ assert boolean byte char +class double false final float for int +k long new null diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/grvy945.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/grvy945.test index 4a6fdc84a144..c4bdfd1176dd 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/grvy945.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/grvy945.test @@ -4,4 +4,3 @@ class Category { } } ----- -Category \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/imp4.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/imp4.test index 425faa279629..7f2476687da7 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/imp4.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/imp4.test @@ -1,2 +1,6 @@ import static a.b ------ \ No newline at end of file +----- +META-INF +com +java +javax \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/mod11.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/mod11.test index ef32b89a780b..2309d8cdd4c6 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/mod11.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/mod11.test @@ -1,4 +1,5 @@ def foo = { p ppp } ------ \ No newline at end of file +----- +ppp \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var1.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var1.test index 53a404842098..1ab4dd69a70d 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var1.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var1.test @@ -25,6 +25,7 @@ for import int interface +k long native new diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var10.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var10.test index 34814a2c3c52..f1bcfebccd65 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var10.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var10.test @@ -14,6 +14,7 @@ class A { boolean byte char +class double false float diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var2.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var2.test index f9c25dc3a419..9a92104184d8 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var2.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var2.test @@ -25,6 +25,7 @@ for import int interface +k long native new diff --git a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var3.test b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var3.test index c26b3e8a7eb4..24fcb08c1220 100644 --- a/plugins/groovy/testdata/groovy/oldCompletion/keyword/var3.test +++ b/plugins/groovy/testdata/groovy/oldCompletion/keyword/var3.test @@ -10,4 +10,8 @@ class A { } } ----- +META-INF +com +java +javax static \ No newline at end of file diff --git a/plugins/groovy/testdata/highlighting/AnonymousClassAbstractMethod.groovy b/plugins/groovy/testdata/highlighting/AnonymousClassAbstractMethod.groovy index fde006d81c80..1e17619a74ec 100644 --- a/plugins/groovy/testdata/highlighting/AnonymousClassAbstractMethod.groovy +++ b/plugins/groovy/testdata/highlighting/AnonymousClassAbstractMethod.groovy @@ -6,6 +6,6 @@ def x=new ActionListener() { } - abstract void foo(); + abstract void foo(); } diff --git a/plugins/groovy/testdata/parsing/groovy/expressions/closures/final_error.test b/plugins/groovy/testdata/parsing/groovy/expressions/closures/final_error.test index daa2de0d4ad5..e59fb8978aa4 100644 --- a/plugins/groovy/testdata/parsing/groovy/expressions/closures/final_error.test +++ b/plugins/groovy/testdata/parsing/groovy/expressions/closures/final_error.test @@ -19,7 +19,7 @@ Groovy script PsiWhiteSpace(' ') PsiElement(final)('final') PsiWhiteSpace(' ') - PsiErrorElement:Duplicate modifier + PsiErrorElement:Duplicate modifier 'def' PsiElement(def)('def') PsiWhiteSpace(' ') PsiElement(identifier)('i') diff --git a/plugins/groovy/testdata/refactoring/introduceParameter/implicitDefaultConstructor/ImplicitDefaultConstructorAfter.groovy b/plugins/groovy/testdata/refactoring/introduceParameter/implicitDefaultConstructor/ImplicitDefaultConstructorAfter.groovy index 749a1ba9e734..19c1e90323eb 100644 --- a/plugins/groovy/testdata/refactoring/introduceParameter/implicitDefaultConstructor/ImplicitDefaultConstructorAfter.groovy +++ b/plugins/groovy/testdata/refactoring/introduceParameter/implicitDefaultConstructor/ImplicitDefaultConstructorAfter.groovy @@ -1,5 +1,5 @@ class B extends A { - public B() { + def B() { super(27) } diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/duplicateStringLiteral/DuplicateStringLiteralInspection.java b/plugins/java-i18n/src/com/intellij/codeInspection/duplicateStringLiteral/DuplicateStringLiteralInspection.java index b32d1cb7625f..f24409ca70c0 100644 --- a/plugins/java-i18n/src/com/intellij/codeInspection/duplicateStringLiteral/DuplicateStringLiteralInspection.java +++ b/plugins/java-i18n/src/com/intellij/codeInspection/duplicateStringLiteral/DuplicateStringLiteralInspection.java @@ -21,6 +21,7 @@ import com.intellij.codeInspection.*; import com.intellij.codeInspection.ex.BaseLocalInspectionTool; import com.intellij.codeInspection.i18n.JavaI18nUtil; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.StringUtil; @@ -111,27 +112,31 @@ public class DuplicateStringLiteralInspection extends BaseLocalInspectionTool { Set resultFiles = null; for (String word : words) { - if (word.length() >= MIN_STRING_LENGTH) { - final Set files = new THashSet(); - searchHelper.processAllFilesWithWordInLiterals(word, scope, new CommonProcessors.CollectProcessor(files)); - if (resultFiles == null) { - resultFiles = files; - } - else { - resultFiles.retainAll(files); - } - if (resultFiles.isEmpty()) return; + if (word.length() < MIN_STRING_LENGTH) { + continue; } + ProgressManager.checkCanceled(); + final Set files = new THashSet(); + searchHelper.processAllFilesWithWordInLiterals(word, scope, new CommonProcessors.CollectProcessor(files)); + if (resultFiles == null) { + resultFiles = files; + } + else { + resultFiles.retainAll(files); + } + if (resultFiles.isEmpty()) return; } if (resultFiles == null || resultFiles.isEmpty()) return; final List foundExpr = new ArrayList(); for (PsiFile file : resultFiles) { + ProgressManager.checkCanceled(); CharSequence text = file.getViewProvider().getContents(); StringSearcher searcher = new StringSearcher(stringToFind, true, true); for (int offset = LowLevelSearchUtil.searchWord(text, 0, text.length(), searcher); offset >= 0; offset = LowLevelSearchUtil.searchWord(text, offset + searcher.getPattern().length(), text.length(), searcher) ) { + ProgressManager.checkCanceled(); PsiElement element = file.findElementAt(offset); if (element == null || !(element.getParent() instanceof PsiLiteralExpression)) continue; PsiLiteralExpression expression = (PsiLiteralExpression)element.getParent(); @@ -143,6 +148,7 @@ public class DuplicateStringLiteralInspection extends BaseLocalInspectionTool { if (foundExpr.isEmpty()) return; Set classes = new THashSet(); for (PsiElement aClass : foundExpr) { + ProgressManager.checkCanceled(); do { aClass = PsiTreeUtil.getParentOfType(aClass, PsiClass.class); } @@ -168,7 +174,6 @@ public class DuplicateStringLiteralInspection extends BaseLocalInspectionTool { (thisFile ? " " + InspectionsBundle.message("inspection.duplicates.message.in.this.file") : ""); } }, ", " + BR); - } else { classList = StringUtil.join(tenClassesMost, new Function() { diff --git a/plugins/junit/src/com/intellij/execution/junit/TestObject.java b/plugins/junit/src/com/intellij/execution/junit/TestObject.java index aba51fd102b0..99a388e2448b 100644 --- a/plugins/junit/src/com/intellij/execution/junit/TestObject.java +++ b/plugins/junit/src/com/intellij/execution/junit/TestObject.java @@ -247,13 +247,16 @@ public abstract class TestObject implements JavaCommandLine { @Override public void notifyStart(TestProxy root) { super.notifyStart(root); - handler.getOut().setDispatchListener(getModel().getNotifier()); - Disposer.register(getModel(), new Disposable() { - public void dispose() { - handler.getOut().setDispatchListener(DispatchListener.DEAF); - } - }); - consoleView.attachToModel(getModel()); + final JUnitRunningModel model = getModel(); + if (model != null) { + handler.getOut().setDispatchListener(model.getNotifier()); + Disposer.register(model, new Disposable() { + public void dispose() { + handler.getOut().setDispatchListener(DispatchListener.DEAF); + } + }); + consoleView.attachToModel(model); + } } }; diff --git a/plugins/junit/src/com/intellij/execution/junit2/segments/InputObjectRegistry.java b/plugins/junit/src/com/intellij/execution/junit2/segments/InputObjectRegistry.java index 676a5d4fb418..766a77d4e81f 100644 --- a/plugins/junit/src/com/intellij/execution/junit2/segments/InputObjectRegistry.java +++ b/plugins/junit/src/com/intellij/execution/junit2/segments/InputObjectRegistry.java @@ -33,7 +33,7 @@ public class InputObjectRegistry { public TestProxy getByKey(final String key) { final TestProxy result = myKnownObjects.get(key); if (result == null) { - LOG.assertTrue(false, "Unknwon key: " + key); + LOG.error("Unknwon key: " + key); LOG.info("Known keys:"); final ArrayList knownKeys = new ArrayList(myKnownObjects.keySet()); Collections.sort(knownKeys); diff --git a/plugins/junit/src/com/intellij/execution/junit2/ui/StatisticsTable.java b/plugins/junit/src/com/intellij/execution/junit2/ui/StatisticsTable.java index 2a079c63aac2..bb8eca3b22e2 100644 --- a/plugins/junit/src/com/intellij/execution/junit2/ui/StatisticsTable.java +++ b/plugins/junit/src/com/intellij/execution/junit2/ui/StatisticsTable.java @@ -73,7 +73,7 @@ public class StatisticsTable extends ListTableModel { } public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) { - LOG.assertTrue(false, "value: " + aValue + " row: " + rowIndex + " column: " + columnIndex); + LOG.error("value: " + aValue + " row: " + rowIndex + " column: " + columnIndex); } public boolean isCellEditable(final int rowIndex, final int columnIndex) { diff --git a/plugins/junit/src/com/intellij/execution/junit2/ui/TestsPacketsReceiver.java b/plugins/junit/src/com/intellij/execution/junit2/ui/TestsPacketsReceiver.java index c22a5f248249..c5d6f3dc6f30 100644 --- a/plugins/junit/src/com/intellij/execution/junit2/ui/TestsPacketsReceiver.java +++ b/plugins/junit/src/com/intellij/execution/junit2/ui/TestsPacketsReceiver.java @@ -37,6 +37,8 @@ import com.intellij.rt.execution.junit.segments.PacketProcessor; import com.intellij.rt.execution.junit.segments.PoolOfDelimiters; import com.intellij.rt.execution.junit.states.PoolOfTestStates; import com.intellij.util.containers.HashMap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; @@ -130,8 +132,11 @@ public class TestsPacketsReceiver implements PacketProcessor, Disposable { public void notifyFinish(ObjectReader reader) { myIsTerminated = true; - myModel.getNotifier().fireRunnerStateChanged(new CompletionEvent(true, reader.readInt())); - terminateStillRunning(); + final JUnitRunningModel model = getModel(); + if (model != null) { + model.getNotifier().fireRunnerStateChanged(new CompletionEvent(true, reader.readInt())); + terminateStillRunning(model); + } } public boolean isRunning() { @@ -142,11 +147,13 @@ public class TestsPacketsReceiver implements PacketProcessor, Disposable { myIsTerminated = terminated; } + @Nullable public JUnitRunningModel getModel() { return myModel; } public void dispose() { + myModel = null; } public void checkTerminated() { @@ -156,15 +163,15 @@ public class TestsPacketsReceiver implements PacketProcessor, Disposable { final JUnitListenersNotifier notifier = model.getNotifier(); if (notifier != null) { notifier.fireRunnerStateChanged(new CompletionEvent(false, -1)); - terminateStillRunning(); + terminateStillRunning(model); } } setTerminated(true); } } - private void terminateStillRunning() { - if (myModel.getRoot() != null) { + private void terminateStillRunning(@NotNull JUnitRunningModel model) { + if (model.getRoot() != null) { final List runningTests = TestStateUpdater.RUNNING_LEAF.select(myModel.getRoot().getAllTests()); for (final AbstractTestProxy runningTest : runningTests) { final TestProxy testProxy = (TestProxy)runningTest; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java index 1330d20832cc..2b7f2c80025a 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java @@ -130,6 +130,22 @@ public class MavenDomProjectProcessorUtils { } } + @NotNull + public static Set collectManagingDependencies(@NotNull MavenDomProjectModel model) { + final Set dependencies = new HashSet(); + + Processor collectProcessor = new Processor() { + public boolean process(MavenDomDependencies mavenDomDependencies) { + dependencies.addAll(mavenDomDependencies.getDependencies()); + return false; + } + }; + + processDependenciesInDependencyManagement(model, collectProcessor, model.getManager().getProject()); + + return dependencies; + } + @Nullable public static MavenDomDependency searchManagingDependency(@NotNull final MavenDomDependency dependency, @NotNull final Project project) { final MavenDomDependency[] parent = new MavenDomDependency[]{null}; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java index 0831c343211c..fa84377f670e 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java @@ -18,7 +18,6 @@ package org.jetbrains.idea.maven.dom; import com.intellij.lang.properties.psi.PropertiesFile; import com.intellij.lang.properties.psi.Property; import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; @@ -30,8 +29,8 @@ import com.intellij.openapi.vfs.VirtualFileSystem; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; -import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.XmlElement; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; @@ -58,9 +57,9 @@ public class MavenDomUtil { if (!(file instanceof XmlFile)) return false; String name = file.getName(); - return name.equals(MavenConstants.POM_XML) - || name.endsWith("." + MavenConstants.POM_EXTENSION) - || name.equals(MavenConstants.SUPER_POM_XML); + return name.equals(MavenConstants.POM_XML) || + name.endsWith("." + MavenConstants.POM_EXTENSION) || + name.equals(MavenConstants.SUPER_POM_XML); } public static boolean isProfilesFile(PsiFile file) { @@ -88,8 +87,7 @@ public class MavenDomUtil { } public static String calcRelativePath(VirtualFile parent, VirtualFile child) { - String result = FileUtil.getRelativePath(new File(parent.getPath()), - new File(child.getPath())); + String result = FileUtil.getRelativePath(new File(parent.getPath()), new File(child.getPath())); return FileUtil.toSystemIndependentName(result); } @@ -313,16 +311,22 @@ public class MavenDomUtil { @NotNull - public static MavenDomDependency createDomDependency(MavenDomProjectModel model, MavenArtifact mavenArtifact, Editor editor) { + public static MavenDomDependency createDomDependency(MavenDomProjectModel model, + MavenArtifact mavenArtifact, + Editor editor, + boolean overriden) { MavenDomDependency domDependency = createMavenDomDependency(model, editor); domDependency.getGroupId().setStringValue(mavenArtifact.getGroupId()); domDependency.getArtifactId().setStringValue(mavenArtifact.getArtifactId()); - domDependency.getVersion().setStringValue(mavenArtifact.getVersion()); + if (!overriden) { + domDependency.getVersion().setStringValue(mavenArtifact.getVersion()); + } return domDependency; } + @NotNull private static MavenDomDependency createMavenDomDependency(@NotNull MavenDomProjectModel model, @Nullable Editor editor) { MavenDomDependencies dependencies = model.getDependencies(); @@ -359,6 +363,4 @@ public class MavenDomUtil { } return -1; } - - } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomGutterAnnotator.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomGutterAnnotator.java index 120bcbbfb52f..ce6193c30fa2 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomGutterAnnotator.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomGutterAnnotator.java @@ -24,16 +24,24 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.xml.XmlTag; +import com.intellij.util.Function; import com.intellij.util.NotNullFunction; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.DomManager; +import com.intellij.util.xml.DomUtil; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.dom.MavenDomProjectProcessorUtils; +import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.model.MavenDomDependency; import org.jetbrains.idea.maven.dom.model.MavenDomDependencyManagement; +import org.jetbrains.idea.maven.dom.model.MavenDomParent; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; +import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.project.MavenProject; +import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.utils.MavenIcons; import javax.swing.*; @@ -53,7 +61,7 @@ public class MavenDomGutterAnnotator implements Annotator { if (model != null) { String name = model.getName().getStringValue(); if (!StringUtil.isEmptyOrSpaces(name)) { - return name; + return name; } } } @@ -86,6 +94,16 @@ public class MavenDomGutterAnnotator implements Annotator { } }; + private static final NotNullFunction> MAVEN_PROJECT_CONVERTER = + new NotNullFunction>() { + + @NotNull + public Collection fun(final MavenDomProjectModel pointer) { + return ContainerUtil.createMaybeSingletonList(pointer.getXmlTag()); + } + }; + + private static void annotateDependencyUsages(@NotNull MavenDomDependency dependency, AnnotationHolder holder) { final XmlTag tag = dependency.getXmlTag(); if (tag == null) return; @@ -103,8 +121,6 @@ public class MavenDomGutterAnnotator implements Annotator { } } - - private static void annotateManagedDependency(MavenDomDependency dependency, AnnotationHolder holder) { final XmlTag tag = dependency.getXmlTag(); if (tag == null) return; @@ -142,14 +158,66 @@ public class MavenDomGutterAnnotator implements Annotator { if (element instanceof MavenDomDependency) { MavenDomDependency dependency = (MavenDomDependency)element; if (isDependencyManagementSection(dependency)) { - annotateDependencyUsages(dependency, holder); - } else { + annotateDependencyUsages(dependency, holder); + } + else { annotateManagedDependency(dependency, holder); } } + else if (element instanceof MavenDomParent) { + annotateMavenDomParent((MavenDomParent)element, holder); + } + else if (element instanceof MavenDomProjectModel) { + annotateMavenDomProjectChildren((MavenDomProjectModel)element, holder); + } } } + private static void annotateMavenDomParent(@NotNull MavenDomParent mavenDomParent, @NotNull AnnotationHolder holder) { + MavenDomProjectModel parent = findParent(mavenDomParent, mavenDomParent.getManager().getProject()); + + if (parent != null) { + NavigationGutterIconBuilder.create(MavenIcons.PARENT_PROJECT, MAVEN_PROJECT_CONVERTER). + setTargets(parent). + setTooltipText(MavenDomBundle.message("parent.pom.title")). + install(holder, mavenDomParent.getXmlElement()); + } + } + + private static void annotateMavenDomProjectChildren(MavenDomProjectModel model, AnnotationHolder holder) { + MavenProject mavenProject = MavenDomUtil.findProject(model); + if (mavenProject != null) { + final Project project = model.getManager().getProject(); + Set inheritors = MavenProjectsManager.getInstance(project).findInheritors(mavenProject); + + + List children = ContainerUtil.mapNotNull(inheritors, new Function() { + public MavenDomProjectModel fun(MavenProject childProject) { + return MavenDomUtil.getMavenDomProjectModel(project, childProject.getFile()); + } + }); + if (children.size() > 0) { + NavigationGutterIconBuilder.create(MavenIcons.CHILDREN_PROJECTS, MAVEN_PROJECT_CONVERTER). + setTargets(children). + setCellRenderer(RENDERER). + setPopupTitle(MavenDomBundle.message("navigate.children.poms.title")). + setTooltipText(MavenDomBundle.message("children.poms.title")). + install(holder, model.getXmlElement()); + } + } + } + + @Nullable + public static MavenDomProjectModel findParent(@NotNull MavenDomParent mavenDomParent, Project project) { + if (!DomUtil.hasXml(mavenDomParent)) return null; + + MavenId id = new MavenId(mavenDomParent.getGroupId().getStringValue(), mavenDomParent.getArtifactId().getStringValue(), + mavenDomParent.getVersion().getStringValue()); + MavenProject mavenProject = MavenProjectsManager.getInstance(project).findProject(id); + + return mavenProject != null ? MavenDomUtil.getMavenDomProjectModel(project, mavenProject.getFile()) : null; + } + private static boolean isDependencyManagementSection(@NotNull MavenDomDependency dependency) { return dependency.getParentOfType(MavenDomDependencyManagement.class, false) != null; } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesConverter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesConverter.java index 34eb8e1aec71..0bd0966ed633 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesConverter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesConverter.java @@ -312,7 +312,7 @@ public abstract class MavenArtifactCoordinatesConverter extends ResolvingConvert private String[] getGroupIdVariants(MavenProjectIndicesManager manager, MavenDomShortArtifactCoordinates coordinates) { if (DomUtil.hasXml(coordinates.getGroupId())) { Set strings = manager.getGroupIds(); - return strings.toArray(new String[strings.size()]); + return ArrayUtil.toStringArray(strings); } return MavenArtifactUtil.DEFAULT_GROUPS; } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyAction.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyAction.java index 8df51e6b700d..313848c9281c 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyAction.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyAction.java @@ -18,15 +18,18 @@ package org.jetbrains.idea.maven.dom.generate; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiDocumentManager; import com.intellij.util.xml.ui.actions.generate.GenerateDomElementAction; +import org.jetbrains.idea.maven.dom.MavenDomBundle; +import org.jetbrains.idea.maven.dom.model.MavenDomBuild; import org.jetbrains.idea.maven.project.MavenId; import org.jetbrains.idea.maven.dom.model.MavenDomDependency; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; import org.jetbrains.idea.maven.indices.MavenArtifactSearchDialog; import org.jetbrains.idea.maven.project.MavenProjectsManager; +import org.jetbrains.idea.maven.utils.MavenIcons; public class GenerateDependencyAction extends GenerateDomElementAction { public GenerateDependencyAction() { - super(new MavenGenerateProvider("Generate Dependency", MavenDomDependency.class) { + super(new MavenGenerateProvider(MavenDomBundle.message("generate.dependency"), MavenDomDependency.class) { @Override protected MavenDomDependency doGenerate(MavenDomProjectModel mavenModel, Editor editor) { MavenId id = MavenArtifactSearchDialog.searchForArtifact(editor.getProject()); @@ -37,7 +40,7 @@ public class GenerateDependencyAction extends GenerateDomElementAction { MavenProjectsManager manager = MavenProjectsManager.getInstance(editor.getProject()); return manager.addDependency(manager.findProject(mavenModel.getModule()), id); } - }); + }, MavenIcons.DEPENDENCY_ICON); } @Override diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java new file mode 100644 index 000000000000..d47b6fafcd54 --- /dev/null +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java @@ -0,0 +1,140 @@ +/* + * Copyright 2000-2010 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.idea.maven.dom.generate; + +import com.intellij.codeInsight.generation.ClassMember; +import com.intellij.codeInsight.generation.MemberChooserObject; +import com.intellij.codeInsight.generation.MemberChooserObjectBase; +import com.intellij.codeInsight.generation.PsiElementMemberChooserObject; +import com.intellij.ide.util.MemberChooser; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.psi.PsiFile; +import com.intellij.util.Function; +import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.idea.maven.dom.MavenDomBundle; +import org.jetbrains.idea.maven.dom.model.MavenDomDependency; +import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; +import org.jetbrains.idea.maven.utils.MavenIcons; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * @author Serega.Vasiliev + */ +public class GenerateDependencyUtil { + private GenerateDependencyUtil() { + } + + @NotNull + public static List chooseDependencies(Collection candidates, final Project project) { + List dependencies = new ArrayList(); + + MavenDomProjectModelMember[] memberCandidates = + ContainerUtil.map2Array(candidates, MavenDomProjectModelMember.class, new Function() { + public MavenDomProjectModelMember fun(MavenDomDependency dependency) { + return new MavenDomProjectModelMember(dependency); + } + }); + MemberChooser chooser = + new MemberChooser(memberCandidates, true, true, project) { + protected ShowContainersAction getShowContainersAction() { + return new ShowContainersAction(MavenDomBundle.message("chooser.show.project.files"), MavenIcons.MAVEN_PROJECT_ICON); + } + + protected String getAllContainersNodeName() { + return MavenDomBundle.message("all.dependencies"); + } + }; + + chooser.setTitle(MavenDomBundle.message("dependencies.chooser.title")); + chooser.setCopyJavadocVisible(false); + chooser.show(); + + if (chooser.getExitCode() == MemberChooser.OK_EXIT_CODE) { + final MavenDomProjectModelMember[] members = chooser.getSelectedElements(new MavenDomProjectModelMember[0]); + if (members != null) { + dependencies.addAll(ContainerUtil.mapNotNull(members, new Function() { + public MavenDomDependency fun(MavenDomProjectModelMember mavenDomProjectModelMember) { + return mavenDomProjectModelMember.getDependency(); + } + })); + } + } + + return dependencies; + } + + private static class MavenDomProjectModelMember extends MemberChooserObjectBase implements ClassMember { + private final MavenDomDependency myDependency; + + public MavenDomProjectModelMember(final MavenDomDependency dependency) { + super(dependency.toString(), MavenIcons.DEPENDENCY_ICON); + myDependency = dependency; + } + + @Override + public String getText() { + StringBuffer sb = new StringBuffer(); + + append(sb, myDependency.getGroupId().getStringValue()); + append(sb, myDependency.getArtifactId().getStringValue()); + append(sb, myDependency.getVersion().getStringValue()); + + return sb.toString(); + } + + private static void append(StringBuffer sb, String str) { + if (!StringUtil.isEmptyOrSpaces(str)) { + if (sb.length() > 0) sb.append(": "); + sb.append(str); + } + } + + public MemberChooserObject getParentNodeDelegate() { + MavenDomDependency dependency = getDependency(); + + return new MavenDomProjectModelFileMemberChooserObjectBase(dependency.getXmlTag().getContainingFile(), + getProjectName(dependency)); + } + + @Nullable + private static String getProjectName(@Nullable MavenDomDependency dependency) { + if (dependency != null) { + MavenDomProjectModel model = dependency.getParentOfType(MavenDomProjectModel.class, false); + if (model != null) { + return model.getName().getStringValue(); + } + } + return null; + } + + public MavenDomDependency getDependency() { + return myDependency; + } + + private static class MavenDomProjectModelFileMemberChooserObjectBase extends PsiElementMemberChooserObject { + + public MavenDomProjectModelFileMemberChooserObjectBase(@NotNull final PsiFile psiFile, @Nullable String projectName) { + super(psiFile, StringUtil.isEmptyOrSpaces(projectName) ? psiFile.getName() : projectName, MavenIcons.MAVEN_PROJECT_ICON); + } + } + } +} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateOverridingDependencyAction.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateOverridingDependencyAction.java new file mode 100644 index 000000000000..5e9ebb68ed12 --- /dev/null +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateOverridingDependencyAction.java @@ -0,0 +1,111 @@ +/* + * Copyright 2000-2010 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.idea.maven.dom.generate; + +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.util.Processor; +import com.intellij.util.containers.hash.HashSet; +import com.intellij.util.xml.ui.actions.generate.GenerateDomElementAction; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.idea.maven.dom.MavenDomBundle; +import org.jetbrains.idea.maven.dom.MavenDomProjectProcessorUtils; +import org.jetbrains.idea.maven.dom.model.MavenDomDependencies; +import org.jetbrains.idea.maven.dom.model.MavenDomDependency; +import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; +import org.jetbrains.idea.maven.project.MavenId; +import org.jetbrains.idea.maven.project.MavenProjectsManager; +import org.jetbrains.idea.maven.utils.MavenIcons; + +import java.util.List; +import java.util.Set; + +public class GenerateOverridingDependencyAction extends GenerateDomElementAction { + public GenerateOverridingDependencyAction() { + super(new MavenOverridingDependencyGenerateProvider(), MavenIcons.DEPENDENCY_ICON); + } + + @Override + protected boolean startInWriteAction() { + return false; + } + + private static class MavenOverridingDependencyGenerateProvider extends MavenGenerateProvider { + public MavenOverridingDependencyGenerateProvider() { + super(MavenDomBundle.message("override.dependency"), MavenDomDependency.class); + } + + @Override + protected MavenDomDependency doGenerate(MavenDomProjectModel mavenModel, Editor editor) { + Set managingDependencies = collectManagingDependencies(mavenModel); + + List dependenciesToOverride = GenerateDependencyUtil.chooseDependencies(managingDependencies, mavenModel.getManager().getProject()); + + for (MavenDomDependency parentDependency : dependenciesToOverride) { + String groupId = parentDependency.getGroupId().getStringValue(); + String artifactId = parentDependency.getArtifactId().getStringValue(); + + if (!StringUtil.isEmptyOrSpaces(groupId) && !StringUtil.isEmptyOrSpaces(artifactId)) { + MavenId id = new MavenId(groupId, artifactId, parentDependency.getVersion().getStringValue()); + + MavenProjectsManager manager = MavenProjectsManager.getInstance(editor.getProject()); + + MavenDomDependency dependency = manager.addOverridenDependency(manager.findProject(mavenModel.getModule()), id); + + dependency.getVersion().undefine(); + } + + } + + return null; + } + } + + @NotNull + public static Set collectManagingDependencies(@NotNull MavenDomProjectModel model) { + final Set dependencies = new HashSet(); + + final List existingDependencies = model.getDependencies().getDependencies(); + + Processor collectProcessor = new Processor() { + public boolean process(MavenDomDependencies mavenDomDependencies) { + for (MavenDomDependency dependency : mavenDomDependencies.getDependencies()) { + String groupId = dependency.getGroupId().getStringValue(); + String artifactId = dependency.getArtifactId().getStringValue(); + if (StringUtil.isEmptyOrSpaces(groupId) || StringUtil.isEmptyOrSpaces(artifactId)) continue; + + if (!isDependencyExist(groupId, artifactId, existingDependencies)) { + dependencies.add(dependency); + } + } + return false; + } + }; + + MavenDomProjectProcessorUtils.processDependenciesInDependencyManagement(model, collectProcessor, model.getManager().getProject()); + + return dependencies; + } + + private static boolean isDependencyExist(String groupId, String artifactId, List existingDependencies) { + for (MavenDomDependency existingDependency : existingDependencies) { + if(groupId.equals(existingDependency.getGroupId().getStringValue()) || artifactId.equals(existingDependency.getArtifactId().getStringValue())) { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateParentAction.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateParentAction.java index 5ebc26e8afc9..237e3028541a 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateParentAction.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateParentAction.java @@ -25,6 +25,7 @@ import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; import org.jetbrains.idea.maven.dom.model.MavenDomParent; import org.jetbrains.idea.maven.navigator.SelectMavenProjectDialog; import org.jetbrains.idea.maven.project.MavenProject; +import org.jetbrains.idea.maven.utils.MavenIcons; public class GenerateParentAction extends GenerateDomElementAction { public GenerateParentAction() { @@ -47,7 +48,7 @@ public class GenerateParentAction extends GenerateDomElementAction { protected boolean isAvailableForModel(MavenDomProjectModel mavenModel) { return !DomUtil.hasXml(mavenModel.getMavenParent()); } - }); + }, MavenIcons.MAVEN_PROJECT_ICON); } @Override diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java index 71234c65b98f..37ebc09c5559 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java @@ -28,6 +28,7 @@ import com.intellij.psi.xml.XmlDocument; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.intellij.psi.xml.XmlTagChild; +import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.Icons; import com.intellij.util.IncorrectOperationException; @@ -199,7 +200,7 @@ public class MavenPropertyPsiReference extends MavenPsiReference { public Object[] getVariants() { List result = new ArrayList(); collectVariants(result); - return result.toArray(new Object[result.size()]); + return ArrayUtil.toObjectArray(result); } protected void collectVariants(List result) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java index e78eebd59fc4..9ef8c87e6679 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java @@ -18,6 +18,7 @@ package org.jetbrains.idea.maven.execution; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Pair; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; @@ -75,7 +76,7 @@ public class EditMavenPropertyDialog extends DialogWrapper { } private void fillAvailableProperties() { - String[] keys = myAvailableProperties.keySet().toArray(new String[0]); + String[] keys = ArrayUtil.toStringArray(myAvailableProperties.keySet()); myNameBox.setModel(new DefaultComboBoxModel(keys)); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java index d4155ccaef0b..22b401b455a1 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java @@ -984,7 +984,16 @@ public class MavenProjectsManager extends SimpleProjectComponent return result; } + public MavenDomDependency addOverridenDependency(final MavenProject mavenProject, final MavenId id) { + return addDependency(mavenProject, id, true); + } + + public MavenDomDependency addDependency(final MavenProject mavenProject, final MavenId id) { + return addDependency(mavenProject, id, false); + } + + public MavenDomDependency addDependency(final MavenProject mavenProject, final MavenId id, final boolean overriden) { final MavenArtifact[] artifact = new MavenArtifact[1]; try { @@ -1005,7 +1014,7 @@ public class MavenProjectsManager extends SimpleProjectComponent protected void run(Result result) throws Throwable { MavenDomProjectModel model = MavenDomUtil.getMavenDomProjectModel(myProject, mavenProject.getFile()); - MavenDomDependency domDependency = MavenDomUtil.createDomDependency(model, artifact[0], getEditor()); + MavenDomDependency domDependency = MavenDomUtil.createDomDependency(model, artifact[0], getEditor(), overriden); mavenProject.addDependency(artifact[0]); result.setResult(domDependency); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenIcons.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenIcons.java index ee7ef71b30ae..0350b6dd5c9c 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenIcons.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenIcons.java @@ -22,6 +22,7 @@ import javax.swing.*; public class MavenIcons { public static final Icon MAVEN_ICON = IconLoader.getIcon("/images/mavenLogo.png"); public static final Icon MAVEN_PROJECT_ICON = IconLoader.getIcon("/images/mavenProject.png"); + public static final Icon OPEN_PROFILES_ICON = IconLoader.getIcon("/images/profilesOpen.png"); public static final Icon CLOSED_PROFILES_ICON = IconLoader.getIcon("/images/profilesClosed.png"); public static final Icon OPEN_PHASES_ICON = IconLoader.getIcon("/images/phasesOpen.png"); @@ -40,4 +41,7 @@ public class MavenIcons { public static final Icon OVERRIDING_DEPENDENCY = IconLoader.getIcon("/images/overridingDependency.png"); public static final Icon OVERRIDEN_DEPENDENCY = IconLoader.getIcon("/images/overridenDependency.png"); + + public static final Icon PARENT_PROJECT = IconLoader.getIcon("/images/parentProject.png"); + public static final Icon CHILDREN_PROJECTS = IconLoader.getIcon("/images/childrenProjects.png"); } diff --git a/plugins/maven/src/main/resources/DomBundle.properties b/plugins/maven/src/main/resources/DomBundle.properties index 3a284cc5c05b..c2375fb9e889 100644 --- a/plugins/maven/src/main/resources/DomBundle.properties +++ b/plugins/maven/src/main/resources/DomBundle.properties @@ -16,6 +16,16 @@ generate.dependency.group=Dependency (group) generate.plugin.artifact=Plugin (artifact) generate.plugin.group=Plugin (group) -overriden.dependency.title=Navigate to managing dependency + +overriden.dependency.title=Navigate to managing dependency overriding.dependency.title=Navigate to dependency usages navigate.parent.dependency.title=Choose dependency to navigate + +parent.pom.title=Navigate to parent +children.poms.title=Navigate to children projects +navigate.children.poms.title=Choose project +dependencies.chooser.title=Choose dependency +all.dependencies=All Dependencies +chooser.show.project.files=Project Files +override.dependency=Override Parent Dependency +generate.dependency=Dependency diff --git a/plugins/maven/src/main/resources/META-INF/plugin.xml b/plugins/maven/src/main/resources/META-INF/plugin.xml index 2113cd31ed00..b72eac68511c 100644 --- a/plugins/maven/src/main/resources/META-INF/plugin.xml +++ b/plugins/maven/src/main/resources/META-INF/plugin.xml @@ -351,7 +351,8 @@ - + + diff --git a/plugins/maven/src/main/resources/images/childrenProjects.png b/plugins/maven/src/main/resources/images/childrenProjects.png new file mode 100644 index 000000000000..62d6b64bbf99 Binary files /dev/null and b/plugins/maven/src/main/resources/images/childrenProjects.png differ diff --git a/plugins/maven/src/main/resources/images/parentProject.png b/plugins/maven/src/main/resources/images/parentProject.png new file mode 100644 index 000000000000..35795fd094dc Binary files /dev/null and b/plugins/maven/src/main/resources/images/parentProject.png differ diff --git a/plugins/properties/src/com/intellij/lang/properties/references/PropertyReferenceBase.java b/plugins/properties/src/com/intellij/lang/properties/references/PropertyReferenceBase.java index 479b6b701bd3..a9300721225b 100644 --- a/plugins/properties/src/com/intellij/lang/properties/references/PropertyReferenceBase.java +++ b/plugins/properties/src/com/intellij/lang/properties/references/PropertyReferenceBase.java @@ -105,7 +105,7 @@ public abstract class PropertyReferenceBase implements PsiPolyVariantReference, else {*/ ElementManipulator manipulator = ElementManipulators.getManipulator(myElement); if (manipulator == null) { - LOG.assertTrue(false, "Cannot find manipulator for " + myElement + " of class " + myElement.getClass()); + LOG.error("Cannot find manipulator for " + myElement + " of class " + myElement.getClass()); } return manipulator.handleContentChange(myElement, getRangeInElement(), newElementName); /*}*/ diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DeleteOptionsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DeleteOptionsDialog.java index c48319cb8625..6d569fce7b67 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DeleteOptionsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DeleteOptionsDialog.java @@ -18,6 +18,7 @@ package org.jetbrains.idea.svn.dialogs.browser; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.vcs.VcsConfiguration; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; @@ -92,7 +93,7 @@ public class DeleteOptionsDialog extends DialogWrapper { final ArrayList messages = VcsConfiguration.getInstance(myProject).getRecentMessages(); Collections.reverse(messages); - final String[] model = messages.toArray(new String[messages.size()]); + final String[] model = ArrayUtil.toStringArray(messages); final JComboBox messagesBox = new JComboBox(model); messagesBox.setRenderer(new MessageBoxCellRenderer()); panel.add(messagesBox, gc); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ImportOptionsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ImportOptionsDialog.java index d16e78bb0d3e..6de82420a5d8 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ImportOptionsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ImportOptionsDialog.java @@ -22,6 +22,7 @@ import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.vcs.VcsConfiguration; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.DepthCombo; @@ -165,7 +166,7 @@ public class ImportOptionsDialog extends DialogWrapper implements ActionListener final ArrayList messages = VcsConfiguration.getInstance(myProject).getRecentMessages(); Collections.reverse(messages); - final String[] model = messages.toArray(new String[messages.size()]); + final String[] model = ArrayUtil.toStringArray(messages); final JComboBox messagesBox = new JComboBox(model); messagesBox.setRenderer(new MessageBoxCellRenderer()); panel.add(messagesBox, gc); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/MkdirOptionsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/MkdirOptionsDialog.java index 5f69a79898f1..0333d4f555e3 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/MkdirOptionsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/MkdirOptionsDialog.java @@ -19,6 +19,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.vcs.VcsConfiguration; import com.intellij.ui.DocumentAdapter; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import org.tmatesoft.svn.core.SVNException; @@ -64,7 +65,7 @@ public class MkdirOptionsDialog extends DialogWrapper { final ArrayList messages = VcsConfiguration.getInstance(project).getRecentMessages(); Collections.reverse(messages); - final String[] model = messages.toArray(new String[messages.size()]); + final String[] model = ArrayUtil.toStringArray(messages); myMessagesBox.setModel(new DefaultComboBoxModel(model)); myMessagesBox.setRenderer(new MessageBoxCellRenderer()); } diff --git a/plugins/testng/src/com/theoryinpractice/testng/intention/OverrideImplementsTestNGAnnotationsHandler.java b/plugins/testng/src/com/theoryinpractice/testng/intention/OverrideImplementsTestNGAnnotationsHandler.java index f8895c2b4de7..1897355ec8b5 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/intention/OverrideImplementsTestNGAnnotationsHandler.java +++ b/plugins/testng/src/com/theoryinpractice/testng/intention/OverrideImplementsTestNGAnnotationsHandler.java @@ -21,6 +21,7 @@ package com.theoryinpractice.testng.intention; import com.intellij.codeInsight.generation.OverrideImplementsAnnotationsHandler; +import com.intellij.util.ArrayUtil; import com.theoryinpractice.testng.util.TestNGUtil; import org.jetbrains.annotations.NotNull; @@ -32,6 +33,6 @@ public class OverrideImplementsTestNGAnnotationsHandler implements OverrideImple @NotNull public String[] annotationsToRemove(@NotNull final String fqName) { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } } \ No newline at end of file diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GridDropLocation.java b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GridDropLocation.java index c66cae060f30..d4c89d4fe0ef 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GridDropLocation.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GridDropLocation.java @@ -209,9 +209,8 @@ public class GridDropLocation implements ComponentDropLocation { RadComponent old = container.findComponentInRect(row + relativeRow, column + relativeCol, rowSpan, colSpan); if (old != null) { - LOG.assertTrue(false, - "Drop rectangle not empty: (" + (row + relativeRow) + ", " + (column + relativeCol) - + ", " + rowSpan + ", " + colSpan + "), component ID=" + old.getId()); + LOG.error("Drop rectangle not empty: (" + (row + relativeRow) + ", " + (column + relativeCol) + ", " + rowSpan + ", " + colSpan + + "), component ID=" + old.getId()); } final GridConstraints constraints = c.getConstraints(); diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/IntroListModelProperty.java b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/IntroListModelProperty.java index aba673924fbb..a6b75dd86ae0 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/IntroListModelProperty.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/IntroListModelProperty.java @@ -25,6 +25,7 @@ import com.intellij.uiDesigner.propertyInspector.editors.ListModelEditor; import com.intellij.uiDesigner.propertyInspector.renderers.LabelPropertyRenderer; import com.intellij.uiDesigner.radComponents.RadComponent; import com.intellij.uiDesigner.snapShooter.SnapshotContext; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -69,7 +70,7 @@ public class IntroListModelProperty extends IntrospectedProperty { @Override public String[] getValue(final RadComponent component) { final String[] strings = (String[])component.getDelegee().getClientProperty(CLIENT_PROPERTY_KEY_PREFIX + getName()); if (strings == null) { - return new String[0]; + return ArrayUtil.EMPTY_STRING_ARRAY; } return strings; } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/LayoutManagerRegistry.java b/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/LayoutManagerRegistry.java index 0071a2b87a39..a4b79b719573 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/LayoutManagerRegistry.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/LayoutManagerRegistry.java @@ -61,7 +61,7 @@ public class LayoutManagerRegistry { } public static String[] getLayoutManagerNames() { - final String[] layoutManagerNames = ourLayoutManagerRegistry.keySet().toArray(new String[0]); + final String[] layoutManagerNames = ArrayUtil.toStringArray(ourLayoutManagerRegistry.keySet()); Arrays.sort(layoutManagerNames); return layoutManagerNames; } diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltContextProvider.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltContextProvider.java index 979dee5ddfd9..45378bd859c6 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltContextProvider.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltContextProvider.java @@ -27,6 +27,7 @@ import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.*; +import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.xml.XmlAttributeDescriptor; import com.intellij.xml.XmlElementDescriptor; @@ -264,7 +265,7 @@ public class XsltContextProvider extends ContextProvider { } //noinspection unchecked - return new Result(names, names.dependencies.toArray(new Object[names.dependencies.size()])); + return new Result(names, ArrayUtil.toObjectArray(names.dependencies)); } }, false); } diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/references/ModeReference.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/references/ModeReference.java index 27b2dfafba7f..b28d84643769 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/references/ModeReference.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/references/ModeReference.java @@ -77,7 +77,7 @@ class ModeReference extends SimpleAttributeReference implements PsiPolyVariantRe final PsiElement[] modes = ResolveUtil.collect(getMatcher().variantMatcher()); l.addAll(Arrays.asList(modes)); } - return l.toArray(new Object[l.size()]); + return ArrayUtil.toObjectArray(l); } return ArrayUtil.EMPTY_OBJECT_ARRAY; } @@ -165,7 +165,7 @@ class ModeReference extends SimpleAttributeReference implements PsiPolyVariantRe lookups.add(new NamespaceLookup(prefix)); } - return lookups.toArray(new Object[lookups.size()]); + return ArrayUtil.toObjectArray(lookups); } public void registerQuickfix(HighlightInfo highlightInfo, PrefixReference psiReference) { diff --git a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java index 1a821147747b..c00667583fa1 100644 --- a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java +++ b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java @@ -17,6 +17,7 @@ package org.intellij.plugins.xpathView; import com.intellij.find.FindProgressIndicator; import com.intellij.ide.projectView.PresentationData; +import com.intellij.lang.Language; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.LangDataKeys; @@ -38,9 +39,11 @@ import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.WindowManager; +import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; +import com.intellij.psi.templateLanguages.TemplateLanguageFileViewProvider; import com.intellij.psi.xml.XmlElement; import com.intellij.psi.xml.XmlFile; import com.intellij.usageView.UsageInfo; @@ -60,7 +63,10 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; /** *

This class implements the core action to enter, evaluate and display the results of an XPath expression.

@@ -184,6 +190,14 @@ public class XPathEvalAction extends XPathAction { if (contextNode == null) { // in XPath data model, / is the document itself, including comments, PIs and the root element contextNode = ((XmlFile)psiFile).getDocument(); + if (contextNode == null) { + FileViewProvider fileViewProvider = psiFile.getViewProvider(); + if (fileViewProvider instanceof TemplateLanguageFileViewProvider) { + Language dataLanguage = ((TemplateLanguageFileViewProvider)fileViewProvider).getTemplateDataLanguage(); + PsiFile templateDataFile = fileViewProvider.getPsi(dataLanguage); + if (templateDataFile instanceof XmlFile) contextNode = ((XmlFile)templateDataFile).getDocument(); + } + } } input = inputXPathExpression(project, contextNode); @@ -195,7 +209,7 @@ public class XPathEvalAction extends XPathAction { } HighlighterUtil.clearHighlighters(editor); - } while (evaluateExpression(input, contextNode, editor, cfg)); + } while (contextNode != null && evaluateExpression(input, contextNode, editor, cfg)); } private boolean evaluateExpression(EvalExpressionDialog.Context context, XmlElement contextNode, Editor editor, Config cfg) { @@ -235,7 +249,7 @@ public class XPathEvalAction extends XPathAction { } else if (result instanceof Boolean) { Messages.showMessageDialog(result.toString(), "XPath result (Boolean)", Messages.getInformationIcon()); } else { - LOG.assertTrue(false, "Unknown XPath result: " + result); + LOG.error("Unknown XPath result: " + result); } } catch (XPathSyntaxException e) { LOG.debug(e); diff --git a/resources/resources.iml b/resources/resources.iml index a04c7f90e067..7a87e487dc3a 100644 --- a/resources/resources.iml +++ b/resources/resources.iml @@ -9,6 +9,8 @@ + + diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java b/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java index 7912652468eb..4971ded53d23 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java @@ -38,7 +38,7 @@ public abstract class DomAnchorImpl { public static DomAnchorImpl createAnchor(@NotNull T t) { final DomElement parent = t.getParent(); if (parent == null) { - LOG.assertTrue(false, "Parent null: " + t); + LOG.error("Parent null: " + t); } if (parent instanceof DomFileElementImpl) { @@ -73,7 +73,7 @@ public abstract class DomAnchorImpl { } } diag.append("Child name: ").append(t.getXmlElementName()).append(";").append(t.getXmlElementNamespaceKey()); - LOG.assertTrue(false, diag); + LOG.error(diag); } return new IndexedAnchor(parentAnchor, description, index); } diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/DomFileElementImpl.java b/xml/dom-impl/src/com/intellij/util/xml/impl/DomFileElementImpl.java index b03360b4bc12..a4d19f215895 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/DomFileElementImpl.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/DomFileElementImpl.java @@ -270,7 +270,7 @@ public class DomFileElementImpl implements DomFileElement< if (fileElement == null) { final FileDescriptionCachedValueProvider provider = myManager.getOrCreateCachedValueProvider(myFile); String s = provider.getFileElementWithLogging(); - LOG.assertTrue(false, "Null, log=" + s); + LOG.error("Null, log=" + s); } else { assert false: this + " does not equal to " + fileElement; } diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java b/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java index fca7ce5da904..c7decb64abd3 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java @@ -79,7 +79,7 @@ public abstract class DomInvocationHandler" + parameter.getName()); + LOG.error("No converter specified: String<->" + parameter.getName()); } return converter; } @@ -139,7 +139,7 @@ public abstract class DomInvocationHandler> myAttribute2Value; - MyTemplateToken(String key) { + MyTemplateToken(String key, List> attribute2value) { myKey = key; + myAttribute2Value = attribute2value; } } @@ -77,7 +84,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } private static boolean isTemplateKeyPart(char c) { - return !Character.isWhitespace(c) && POSSIBLE_OPERATIONS.indexOf(c) < 0; + return !Character.isWhitespace(c) && OPERATIONS.indexOf(c) < 0; } private static int parseNonNegativeInt(@NotNull String s) { @@ -92,13 +99,98 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { private static String getPrefix(@NotNull String templateKey) { for (int i = 0, n = templateKey.length(); i < n; i++) { char c = templateKey.charAt(i); - if (HTML_SELECTORS.indexOf(c) >= 0) { + if (SELECTORS.indexOf(c) >= 0) { return templateKey.substring(0, i); } } return templateKey; } + @Nullable + private static Pair parseAttrNameAndValue(@NotNull String text) { + int eqIndex = text.indexOf('='); + if (eqIndex > 0) { + return new Pair(text.substring(0, eqIndex), text.substring(eqIndex + 1)); + } + return null; + } + + @Nullable + private static MyTemplateToken parseSelectors(@NotNull String text) { + String templateKey = null; + List> attributes = new ArrayList>(); + Set definedAttrs = new HashSet(); + final List classes = new ArrayList(); + StringBuilder builder = new StringBuilder(); + char lastDelim = 0; + text += MARKER; + int classAttrPosition = -1; + for (int i = 0, n = text.length(); i < n; i++) { + char c = text.charAt(i); + if (c == '#' || c == '.' || c == '[' || c == ']' || i == n - 1) { + if (c != ']') { + switch (lastDelim) { + case 0: + templateKey = builder.toString(); + break; + case '#': + if (!definedAttrs.add(ID)) { + return null; + } + attributes.add(new Pair(ID, builder.toString())); + break; + case '.': + if (builder.length() <= 0) { + return null; + } + if (classAttrPosition < 0) { + classAttrPosition = attributes.size(); + } + classes.add(builder.toString()); + break; + case ']': + if (builder.length() > 0) { + return null; + } + break; + default: + return null; + } + } + else if (lastDelim != '[') { + return null; + } + else { + Pair pair = parseAttrNameAndValue(builder.toString()); + if (pair == null || !definedAttrs.add(pair.first)) { + return null; + } + attributes.add(pair); + } + lastDelim = c; + builder = new StringBuilder(); + } + else { + builder.append(c); + } + } + if (classes.size() > 0) { + if (definedAttrs.contains(CLASS)) { + return null; + } + StringBuilder classesAttrValue = new StringBuilder(); + for (int i = 0; i < classes.size(); i++) { + classesAttrValue.append(classes.get(i)); + if (i < classes.size() - 1) { + classesAttrValue.append(' '); + } + } + assert classAttrPosition >= 0; + attributes.add(classAttrPosition, new Pair(CLASS, classesAttrValue.toString())); + } + return new MyTemplateToken(templateKey, attributes); + } + @Nullable private static List parse(@NotNull String text, @NotNull CustomTemplateCallback callback) { text += MARKER; @@ -106,7 +198,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { List result = new ArrayList(); for (int i = 0, n = text.length(); i < n; i++) { char c = text.charAt(i); - if (i == n - 1 || POSSIBLE_OPERATIONS.indexOf(c) >= 0) { + if (i == n - 1 || OPERATIONS.indexOf(c) >= 0) { String key = templateKeyBuilder.toString(); templateKeyBuilder = new StringBuilder(); int num = parseNonNegativeInt(key); @@ -121,7 +213,11 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { if (!callback.isLiveTemplateApplicable(prefix) && prefix.indexOf('<') >= 0) { return null; } - result.add(new MyTemplateToken(key)); + MyTemplateToken token = parseSelectors(key); + if (token == null) { + return null; + } + result.add(token); } result.add(i < n - 1 ? new MyOperationToken(c) : new MyMarkerToken()); } @@ -179,17 +275,54 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { return state == MyState.OPERATION || state == MyState.AFTER_NUMBER; } - public boolean isApplicable(@NotNull String key, @NotNull CustomTemplateCallback callback) { - if (callback.getFile() instanceof XmlFile) { - List tokens = parse(key, callback); - if (tokens != null) { - return check(tokens); + private static String computeKey(Editor editor, int startOffset) { + int offset = editor.getCaretModel().getOffset(); + String s = editor.getDocument().getCharsSequence().subSequence(startOffset, offset).toString(); + int index = 0; + while (index < s.length() && Character.isWhitespace(s.charAt(index))) { + index++; + } + String key = s.substring(index); + int lastWhitespaceIndex = -1; + for (int i = 0; i < key.length(); i++) { + if (Character.isWhitespace(key.charAt(i))) { + lastWhitespaceIndex = i; } } - return false; + if (lastWhitespaceIndex >= 0 && lastWhitespaceIndex < key.length() - 1) { + return key.substring(lastWhitespaceIndex + 1); + } + return key; } - public void execute(@NotNull String key, @NotNull CustomTemplateCallback callback, @Nullable TemplateInvokationListener listener) { + public String computeTemplateKey(@NotNull CustomTemplateCallback callback) { + PsiFile file = callback.getFile(); + if (file.getLanguage() instanceof XMLLanguage) { + Editor editor = callback.getEditor(); + PsiElement element = file.findElementAt(editor.getCaretModel().getOffset() - 1); + int line = editor.getCaretModel().getLogicalPosition().line; + int lineStart = editor.getDocument().getLineStartOffset(line); + int parentStart; + do { + parentStart = element != null ? element.getTextRange().getStartOffset() : 0; + int startOffset = parentStart > lineStart ? parentStart : lineStart; + String key = computeKey(editor, startOffset); + List tokens = parse(key, callback); + if (tokens != null) { + if (check(tokens)) { + return key; + } + } + if (element != null) { + element = element.getParent(); + } + } + while (element != null && parentStart > lineStart); + } + return null; + } + + public void execute(String key, @NotNull CustomTemplateCallback callback, @Nullable TemplateInvokationListener listener) { List tokens = parse(key, callback); assert tokens != null; MyInterpreter interpreter = new MyInterpreter(tokens, callback, MyState.WORD, listener); @@ -201,61 +334,53 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } @NotNull - private static String buildAttributesString(@Nullable String id, @NotNull List classes) { + private static String buildAttributesString(List> attribute2value, int numberInIteration) { StringBuilder result = new StringBuilder(); - if (id != null) { - result.append("id=\"").append(id).append('"'); - if (classes.size() > 0) { + for (Iterator> it = attribute2value.iterator(); it.hasNext();) { + Pair pair = it.next(); + String name = pair.first; + String value = pair.second.replace(NUMBER_IN_ITERATION_PLACE_HOLDER, Integer.toString(numberInIteration + 1)); + result.append(name).append("=\"").append(value).append('"'); + if (it.hasNext()) { result.append(' '); } } - if (classes.size() > 0) { - result.append("class=\""); - for (int i = 0; i < classes.size(); i++) { - result.append(classes.get(i)); - if (i < classes.size() - 1) { - result.append(' '); - } - } - result.append('"'); - } return result.toString(); } - private static boolean prepareAndInvokeTemplate(String key, - final CustomTemplateCallback callback, - final TemplateInvokationListener listener) { - String templateKey = null; - String id = null; - final List classes = new ArrayList(); - StringBuilder builder = new StringBuilder(); - char lastDelim = 0; - key += MARKER; - for (int i = 0, n = key.length(); i < n; i++) { - char c = key.charAt(i); - if (c == '#' || c == '.' || i == n - 1) { - switch (lastDelim) { - case 0: - templateKey = builder.toString(); - break; - case '#': - id = builder.toString(); - break; - case '.': - if (builder.length() > 0) { - classes.add(builder.toString()); - } - break; + private static boolean invokeTemplate(MyTemplateToken token, + final CustomTemplateCallback callback, + final TemplateInvokationListener listener, + int numberInIteration) { + String attributes = buildAttributesString(token.myAttribute2Value, numberInIteration); + attributes = attributes.length() > 0 ? ' ' + attributes : null; + Map predefinedValues = null; + if (attributes != null) { + predefinedValues = new HashMap(); + predefinedValues.put(ATTRS, attributes); + } + if (callback.isLiveTemplateApplicable(token.myKey)) { + if (attributes != null && !callback.templateContainsVars(token.myKey, ATTRS)) { + TemplateImpl newTemplate = generateTemplateWithAttributes(token.myKey, attributes, callback); + if (newTemplate != null) { + return callback.startTemplate(newTemplate, predefinedValues, listener); } - lastDelim = c; - builder = new StringBuilder(); } - else { - builder.append(c); + return callback.startTemplate(token.myKey, predefinedValues, listener); + } + else { + TemplateImpl template = new TemplateImpl("", ""); + template.addTextSegment('<' + token.myKey); + if (attributes != null) { + template.addVariable(ATTRS, "", "", false); + template.addVariableSegment(ATTRS); } + template.addTextSegment(">"); + template.addVariableSegment(TemplateImpl.END); + template.addTextSegment(""); + template.setToReformat(true); + return callback.startTemplate(template, predefinedValues, listener); } - String attributes = buildAttributesString(id, classes); - return startTemplate(templateKey, callback, listener, attributes.length() > 0 ? ' ' + attributes : null); } private static int findPlaceToInsertAttrs(@NotNull TemplateImpl template) { @@ -293,40 +418,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { return null; } - private static boolean startTemplate(String key, - CustomTemplateCallback callback, - TemplateInvokationListener listener, - @Nullable String attributes) { - Map predefinedValues = null; - if (attributes != null) { - predefinedValues = new HashMap(); - predefinedValues.put(ATTRS, attributes); - } - if (callback.isLiveTemplateApplicable(key)) { - if (attributes != null && !callback.templateContainsVars(key, ATTRS)) { - TemplateImpl newTemplate = generateTemplateWithAttributes(key, attributes, callback); - if (newTemplate != null) { - return callback.startTemplate(newTemplate, predefinedValues, listener); - } - } - return callback.startTemplate(key, predefinedValues, listener); - } - else { - TemplateImpl template = new TemplateImpl("", ""); - template.addTextSegment('<' + key); - if (attributes != null) { - template.addVariable(ATTRS, "", "", false); - template.addVariableSegment(ATTRS); - } - template.addTextSegment(">"); - template.addVariableSegment(TemplateImpl.END); - template.addTextSegment(""); - template.setToReformat(true); - return callback.startTemplate(template, predefinedValues, listener); - } - } - - private static boolean hasClosingTag(CharSequence text, CharSequence tagName, int offset, int rightBound) { + /*private static boolean hasClosingTag(CharSequence text, CharSequence tagName, int offset, int rightBound) { if (offset + 1 < text.length() && text.charAt(offset) == '<' && text.charAt(offset + 1) == '/') { CharSequence closingTagName = parseTagName(text, offset + 2, rightBound); if (tagName.equals(closingTagName)) { @@ -334,7 +426,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } } return false; - } + }*/ @Nullable private static CharSequence getPrecedingTagName(CharSequence text, int index, int leftBound) { @@ -374,7 +466,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { private final CustomTemplateCallback myCallback; private final TemplateInvokationListener myListener; private MyState myState; - private int myEndOffset = -1; + private RangeMarker myEndOffsetMarker = null; private MyInterpreter(List tokens, CustomTemplateCallback callback, @@ -387,15 +479,16 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } private void fixEndOffset() { - if (myEndOffset < 0) { - myEndOffset = myCallback.getOffset(); + if (myEndOffsetMarker == null) { + int offset = myCallback.getOffset(); + myEndOffsetMarker = myCallback.getEditor().getDocument().createRangeMarker(offset, offset); } } private void finish(boolean inSeparateEvent) { Editor editor = myCallback.getEditor(); - if (myEndOffset >= 0) { - editor.getCaretModel().moveToOffset(myEndOffset); + if (myEndOffsetMarker != null) { + editor.getCaretModel().moveToOffset(myEndOffsetMarker.getStartOffset()); } editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); if (myListener != null) { @@ -412,15 +505,15 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { CharSequence text = document.getCharsSequence(); CharSequence tagName = getPrecedingTagName(text, offset, startOfTemplate); if (tagName != null) { - if (!hasClosingTag(text, tagName, offset, endOfTemplate)) { + /*if (!hasClosingTag(text, tagName, offset, endOfTemplate)) { document.insertString(offset, "'); - } + }*/ } else if (offset != endOfTemplate) { tagName = getPrecedingTagName(text, endOfTemplate, startOfTemplate); if (tagName != null) { - fixEndOffset(); - document.insertString(endOfTemplate, "'); + /*fixEndOffset(); + document.insertString(endOfTemplate, "');*/ editor.getCaretModel().moveToOffset(endOfTemplate); } } @@ -428,14 +521,14 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { public boolean invoke(int startIndex) { final int n = myTokens.size(); - String templateKey = null; + MyTemplateToken templateToken = null; int number = -1; for (int i = startIndex; i < n; i++) { final int finalI = i; MyToken token = myTokens.get(i); switch (myState) { case OPERATION: - if (templateKey != null) { + if (templateToken != null) { if (token instanceof MyMarkerToken || token instanceof MyOperationToken) { final char sign = token instanceof MyOperationToken ? ((MyOperationToken)token).mySign : MARKER; if (sign == MARKER || sign == '+') { @@ -444,7 +537,9 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { TemplateInvokationListener listener = new TemplateInvokationListener() { public void finished(boolean inSeparateEvent) { myState = MyState.WORD; - fixEndOffset(); + if (myCallback.getOffset() != myCallback.getEndOfTemplate(key)) { + fixEndOffset(); + } if (sign == '+') { myCallback.gotoEndOfTemplate(key); } @@ -453,16 +548,16 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } } }; - if (!prepareAndInvokeTemplate(templateKey, myCallback, listener)) { + if (!invokeTemplate(templateToken, myCallback, listener, -1)) { return false; } - templateKey = null; + templateToken = null; } else if (sign == '>') { - if (!startTemplateAndGotoChild(templateKey, finalI)) { + if (!startTemplateAndGotoChild(templateToken, finalI)) { return false; } - templateKey = null; + templateToken = null; } else if (sign == '*') { myState = MyState.NUMBER; @@ -475,7 +570,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { break; case WORD: if (token instanceof MyTemplateToken) { - templateKey = ((MyTemplateToken)token).myKey; + templateToken = ((MyTemplateToken)token); myState = MyState.OPERATION; } else { @@ -495,20 +590,20 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { if (token instanceof MyMarkerToken || token instanceof MyOperationToken) { char sign = token instanceof MyOperationToken ? ((MyOperationToken)token).mySign : MARKER; if (sign == MARKER || sign == '+') { - if (!invokeTemplateSeveralTimes(templateKey, number, finalI)) { + if (!invokeTemplateSeveralTimes(templateToken, 0, number, finalI)) { return false; } - templateKey = null; + templateToken = null; } else if (number > 1) { - return invokeTemplateAndProcessTail(templateKey, i + 1, number); + return invokeTemplateAndProcessTail(templateToken, 0, number, i + 1); } else { assert number == 1; - if (!startTemplateAndGotoChild(templateKey, finalI)) { + if (!startTemplateAndGotoChild(templateToken, finalI)) { return false; } - templateKey = null; + templateToken = null; } myState = MyState.WORD; } @@ -522,7 +617,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { return true; } - private boolean startTemplateAndGotoChild(String templateKey, final int index) { + private boolean startTemplateAndGotoChild(MyTemplateToken templateToken, final int index) { final Object key = new Object(); myCallback.fixStartOfTemplate(key); TemplateInvokationListener listener = new TemplateInvokationListener() { @@ -534,44 +629,51 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } } }; - if (!prepareAndInvokeTemplate(templateKey, myCallback, listener)) { + if (!invokeTemplate(templateToken, myCallback, listener, -1)) { return false; } return true; } - private boolean invokeTemplateSeveralTimes(final String templateKey, final int count, final int index) { + private boolean invokeTemplateSeveralTimes(final MyTemplateToken templateToken, + final int startIndex, + final int count, + final int globalIndex) { final Object key = new Object(); myCallback.fixStartOfTemplate(key); - for (int i = 0; i < count; i++) { + for (int i = startIndex; i < count; i++) { final int finalI = i; TemplateInvokationListener listener = new TemplateInvokationListener() { public void finished(boolean inSeparateEvent) { myState = MyState.WORD; - fixEndOffset(); + if (myCallback.getOffset() != myCallback.getEndOfTemplate(key)) { + fixEndOffset(); + } myCallback.gotoEndOfTemplate(key); if (inSeparateEvent) { - int newCount = count - finalI - 1; - if (newCount > 0) { - invokeTemplateSeveralTimes(templateKey, newCount, index); + if (finalI + 1 < count) { + invokeTemplateSeveralTimes(templateToken, finalI + 1, count, globalIndex); } else { - invoke(index + 1); + invoke(globalIndex + 1); } } } }; - if (!prepareAndInvokeTemplate(templateKey, myCallback, listener)) { + if (!invokeTemplate(templateToken, myCallback, listener, i)) { return false; } } return true; } - private boolean invokeTemplateAndProcessTail(final String templateKey, final int tailStart, final int count) { + private boolean invokeTemplateAndProcessTail(final MyTemplateToken templateToken, + final int startIndex, + final int count, + final int tailStart) { final Object key = new Object(); myCallback.fixStartOfTemplate(key); - for (int i = 0; i < count; i++) { + for (int i = startIndex; i < count; i++) { final int finalI = i; final boolean[] flag = new boolean[]{false}; TemplateInvokationListener listener = new TemplateInvokationListener() { @@ -579,16 +681,18 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { gotoChild(key); MyInterpreter interpreter = new MyInterpreter(myTokens, myCallback, MyState.WORD, new TemplateInvokationListener() { public void finished(boolean inSeparateEvent) { - fixEndOffset(); + if (myCallback.getOffset() != myCallback.getEndOfTemplate(key)) { + fixEndOffset(); + } myCallback.gotoEndOfTemplate(key); if (inSeparateEvent) { - invokeTemplateAndProcessTail(templateKey, tailStart, count - finalI - 1); + invokeTemplateAndProcessTail(templateToken, finalI + 1, count, tailStart); } } }); if (interpreter.invoke(tailStart)) { if (inSeparateEvent) { - invokeTemplateAndProcessTail(templateKey, tailStart, count - finalI - 1); + invokeTemplateAndProcessTail(templateToken, finalI + 1, count, tailStart); } } else { @@ -596,7 +700,7 @@ public class XmlCustomLiveTemplate implements CustomLiveTemplate { } } }; - if (!prepareAndInvokeTemplate(templateKey, myCallback, listener) || flag[0]) { + if (!invokeTemplate(templateToken, myCallback, listener, i) || flag[0]) { return false; } } diff --git a/xml/impl/src/com/intellij/ide/browsers/OpenFileInBrowserAction.java b/xml/impl/src/com/intellij/ide/browsers/OpenFileInBrowserAction.java new file mode 100644 index 000000000000..f94b8f29a8cc --- /dev/null +++ b/xml/impl/src/com/intellij/ide/browsers/OpenFileInBrowserAction.java @@ -0,0 +1,67 @@ +package com.intellij.ide.browsers; + +import com.intellij.ide.BrowserUtil; +import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.project.DumbAwareAction; +import com.intellij.openapi.ui.Messages; +import com.intellij.psi.PsiFile; +import com.intellij.xml.XmlBundle; + +public class OpenFileInBrowserAction extends DumbAwareAction { + private static final Logger LOG = Logger.getInstance("#com.intellij.ide.browsers.OpenFileInBrowserAction"); + + public void update(AnActionEvent e) { + final DataContext dataContext = e.getDataContext(); + final PsiFile file = LangDataKeys.PSI_FILE.getData(dataContext); + final Presentation presentation = e.getPresentation(); + + if (file != null) { + presentation.setVisible(true); + presentation.setText(XmlBundle.message("action.OpenInBrowser.text")); + presentation.setDescription(XmlBundle.message("action.open.file.in.browser.description")); + + final WebBrowserUrlProvider browserUrlProvider = WebBrowserUrlProviders.getProvider(file); + presentation.setEnabled(browserUrlProvider != null); + + if (browserUrlProvider != null) { + final String actionText = browserUrlProvider.getOpenInBrowserActionText(file); + if (actionText != null) { + presentation.setText(actionText); + } + final String description = browserUrlProvider.getOpenInBrowserActionDescription(file); + if (description != null) { + presentation.setDescription(description); + } + } + + if (ActionPlaces.isPopupPlace(e.getPlace())) { + presentation.setVisible(presentation.isEnabled()); + } + } else { + presentation.setVisible(false); + presentation.setEnabled(false); + } + } + + public void actionPerformed(AnActionEvent e) { + final DataContext dataContext = e.getDataContext(); + final PsiFile psiFile = LangDataKeys.PSI_FILE.getData(dataContext); + LOG.assertTrue(psiFile != null); + final WebBrowserUrlProvider provider = WebBrowserUrlProviders.getProvider(psiFile); + if (provider != null) { + try { + final String url = provider.getUrl(psiFile, false); + ApplicationManager.getApplication().saveAll(); + BrowserUtil.launchBrowser(url); + } + catch (WebBrowserUrlProvider.BrowserException e1) { + Messages.showErrorDialog(e1.getMessage(), XmlBundle.message("browser.error")); + } + catch (Exception e1) { + LOG.error(e1); + } + } + } +} diff --git a/xml/impl/src/com/intellij/psi/CompositeLanguageFileViewProvider.java b/xml/impl/src/com/intellij/psi/CompositeLanguageFileViewProvider.java index 577f58b5d536..fb51b7ad2d33 100644 --- a/xml/impl/src/com/intellij/psi/CompositeLanguageFileViewProvider.java +++ b/xml/impl/src/com/intellij/psi/CompositeLanguageFileViewProvider.java @@ -193,7 +193,7 @@ public class CompositeLanguageFileViewProvider extends SingleRootFileViewProvide message += "\n contentsText:\n" + getContents().toString(); message += "\n jspText:\n" + getPsi(getBaseLanguage()).getNode().getText(); } - LOG.assertTrue(false, message); + LOG.error(message); assert false; } } diff --git a/xml/impl/src/com/intellij/psi/impl/source/parsing/xml/OldXmlParsing.java b/xml/impl/src/com/intellij/psi/impl/source/parsing/xml/OldXmlParsing.java index a4b3a4e2cc5d..4e24e7acdca3 100644 --- a/xml/impl/src/com/intellij/psi/impl/source/parsing/xml/OldXmlParsing.java +++ b/xml/impl/src/com/intellij/psi/impl/source/parsing/xml/OldXmlParsing.java @@ -938,7 +938,7 @@ public class OldXmlParsing implements XmlElementType { IElementType type = lexer.getTokenType(); if (!XML_WHITE_SPACE_OR_COMMENT_BIT_SET.contains(type)) { - LOG.assertTrue(false, "Missed token should be white space or comment:" + type); + LOG.error("Missed token should be white space or comment:" + type); throw new RuntimeException(); } diff --git a/xml/impl/src/com/intellij/psi/impl/source/xml/SchemaPrefixReference.java b/xml/impl/src/com/intellij/psi/impl/source/xml/SchemaPrefixReference.java index f95cc263521c..9bcbb28a7df4 100644 --- a/xml/impl/src/com/intellij/psi/impl/source/xml/SchemaPrefixReference.java +++ b/xml/impl/src/com/intellij/psi/impl/source/xml/SchemaPrefixReference.java @@ -21,6 +21,7 @@ import com.intellij.psi.PsiReferenceBase; import com.intellij.psi.xml.XmlAttribute; import com.intellij.psi.xml.XmlElement; import com.intellij.psi.xml.XmlTag; +import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.xml.util.XmlUtil; import org.jetbrains.annotations.NotNull; @@ -58,7 +59,7 @@ public class SchemaPrefixReference extends PsiReferenceBase { @NotNull public Object[] getVariants() { - return new Object[0]; + return ArrayUtil.EMPTY_OBJECT_ARRAY; } @Override diff --git a/xml/impl/src/com/intellij/psi/impl/source/xml/XmlEntityDeclImpl.java b/xml/impl/src/com/intellij/psi/impl/source/xml/XmlEntityDeclImpl.java index 1b3df38dd743..c64803b27d2e 100644 --- a/xml/impl/src/com/intellij/psi/impl/source/xml/XmlEntityDeclImpl.java +++ b/xml/impl/src/com/intellij/psi/impl/source/xml/XmlEntityDeclImpl.java @@ -126,7 +126,7 @@ public class XmlEntityDeclImpl extends XmlElementImpl implements XmlEntityDecl, switch (context) { default : - LOG.assertTrue(false, "Entity: " + getName() + " context: " + context); + LOG.error("Entity: " + getName() + " context: " + context); return null; case CONTEXT_ELEMENT_CONTENT_SPEC: diff --git a/xml/impl/src/com/intellij/psi/impl/source/xml/XmlEntityRefImpl.java b/xml/impl/src/com/intellij/psi/impl/source/xml/XmlEntityRefImpl.java index 0b4d68beee2d..2444863f1026 100644 --- a/xml/impl/src/com/intellij/psi/impl/source/xml/XmlEntityRefImpl.java +++ b/xml/impl/src/com/intellij/psi/impl/source/xml/XmlEntityRefImpl.java @@ -25,6 +25,7 @@ import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.*; +import com.intellij.util.ArrayUtil; import com.intellij.xml.XmlElementDescriptor; import com.intellij.xml.impl.schema.AnyXmlElementDescriptor; import com.intellij.xml.util.XmlUtil; @@ -207,7 +208,7 @@ public class XmlEntityRefImpl extends XmlElementImpl implements XmlEntityRef { } } - return new CachedValueProvider.Result(result[0], deps.toArray(new Object[deps.size()])); + return new CachedValueProvider.Result(result[0], ArrayUtil.toObjectArray(deps)); } finally { targetElement.putUserData(EVALUATION_IN_PROCESS, null); diff --git a/xml/impl/src/com/intellij/xml/impl/ExternalDocumentValidator.java b/xml/impl/src/com/intellij/xml/impl/ExternalDocumentValidator.java index da409f4e1e23..17e875218422 100644 --- a/xml/impl/src/com/intellij/xml/impl/ExternalDocumentValidator.java +++ b/xml/impl/src/com/intellij/xml/impl/ExternalDocumentValidator.java @@ -316,14 +316,9 @@ public class ExternalDocumentValidator { private static void assertValidElement(PsiElement currentElement, PsiElement originalElement, String message) { if (currentElement==null) { XmlTag tag = PsiTreeUtil.getParentOfType(originalElement, XmlTag.class); - LOG.assertTrue( - false, - "The validator message:"+ message+ " is bound to null node,\n" + - "initial element:"+originalElement.getText()+",\n"+ - "parent:" + originalElement.getParent()+",\n" + - "tag:" + (tag != null? tag.getText():"null") + ",\n" + - "offset in tag: " + (originalElement.getTextOffset() - (tag == null ? 0 : tag.getTextOffset())) - ); + LOG.error("The validator message:" + message + " is bound to null node,\n" + "initial element:" + originalElement.getText() + ",\n" + + "parent:" + originalElement.getParent() + ",\n" + "tag:" + (tag != null ? tag.getText() : "null") + ",\n" + + "offset in tag: " + (originalElement.getTextOffset() - (tag == null ? 0 : tag.getTextOffset()))); } } diff --git a/xml/impl/src/com/intellij/xml/impl/schema/XmlNSDescriptorImpl.java b/xml/impl/src/com/intellij/xml/impl/schema/XmlNSDescriptorImpl.java index afff733e8c73..1b8f70bc81c6 100644 --- a/xml/impl/src/com/intellij/xml/impl/schema/XmlNSDescriptorImpl.java +++ b/xml/impl/src/com/intellij/xml/impl/schema/XmlNSDescriptorImpl.java @@ -915,7 +915,7 @@ public class XmlNSDescriptorImpl implements XmlNSDescriptor,Validator