Merge remote-tracking branch 'origin/master'

This commit is contained in:
Dmitry Jemerov
2012-06-01 15:35:35 +02:00
397 changed files with 50353 additions and 250 deletions
+78 -23
View File
@@ -90,37 +90,62 @@
<XML>
<option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
</XML>
<ADDITIONAL_INDENT_OPTIONS fileType="feature">
<option name="INDENT_SIZE" value="2" />
</ADDITIONAL_INDENT_OPTIONS>
<ADDITIONAL_INDENT_OPTIONS fileType="gsp">
<option name="INDENT_SIZE" value="2" />
</ADDITIONAL_INDENT_OPTIONS>
<ADDITIONAL_INDENT_OPTIONS fileType="haml">
<option name="INDENT_SIZE" value="2" />
</ADDITIONAL_INDENT_OPTIONS>
<ADDITIONAL_INDENT_OPTIONS fileType="html">
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="4" />
<option name="TAB_SIZE" value="8" />
</ADDITIONAL_INDENT_OPTIONS>
<ADDITIONAL_INDENT_OPTIONS fileType="jsp">
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="4" />
<option name="TAB_SIZE" value="8" />
</ADDITIONAL_INDENT_OPTIONS>
<ADDITIONAL_INDENT_OPTIONS fileType="rb">
<option name="INDENT_SIZE" value="2" />
</ADDITIONAL_INDENT_OPTIONS>
<ADDITIONAL_INDENT_OPTIONS fileType="sass">
<option name="INDENT_SIZE" value="2" />
</ADDITIONAL_INDENT_OPTIONS>
<ADDITIONAL_INDENT_OPTIONS fileType="sql">
<option name="INDENT_SIZE" value="2" />
</ADDITIONAL_INDENT_OPTIONS>
<ADDITIONAL_INDENT_OPTIONS fileType="yml">
<option name="INDENT_SIZE" value="2" />
</ADDITIONAL_INDENT_OPTIONS>
<codeStyleSettings language="CFML">
<option name="KEEP_LINE_BREAKS" value="false" />
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="WHILE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
<option name="ALIGN_MULTILINE_BINARY_OPERATION" value="true" />
<option name="ALIGN_MULTILINE_TERNARY_OPERATION" value="true" />
<option name="CALL_PARAMETERS_WRAP" value="1" />
<option name="METHOD_PARAMETERS_WRAP" value="5" />
<option name="BINARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
<option name="FOR_STATEMENT_WRAP" value="5" />
<option name="ASSIGNMENT_WRAP" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="ECMA Script Level 4">
<option name="KEEP_LINE_BREAKS" value="false" />
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="WHILE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
<option name="ALIGN_MULTILINE_BINARY_OPERATION" value="true" />
<option name="ALIGN_MULTILINE_TERNARY_OPERATION" value="true" />
<option name="ALIGN_MULTILINE_EXTENDS_LIST" value="true" />
<option name="CALL_PARAMETERS_WRAP" value="1" />
<option name="METHOD_PARAMETERS_WRAP" value="5" />
<option name="EXTENDS_LIST_WRAP" value="1" />
<option name="EXTENDS_KEYWORD_WRAP" value="1" />
<option name="BINARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
<option name="FOR_STATEMENT_WRAP" value="5" />
<option name="ARRAY_INITIALIZER_WRAP" value="1" />
<option name="ASSIGNMENT_WRAP" value="1" />
<option name="IF_BRACE_FORCE" value="1" />
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="GSP">
<indentOptions>
<option name="INDENT_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Groovy">
<option name="LINE_COMMENT_AT_FIRST_COLUMN" value="false" />
<option name="BLOCK_COMMENT_AT_FIRST_COLUMN" value="false" />
@@ -201,6 +226,36 @@
<option name="TAB_SIZE" value="8" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JSP">
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="4" />
<option name="TAB_SIZE" value="8" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JavaScript">
<option name="KEEP_LINE_BREAKS" value="false" />
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="WHILE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
<option name="ALIGN_MULTILINE_BINARY_OPERATION" value="true" />
<option name="ALIGN_MULTILINE_TERNARY_OPERATION" value="true" />
<option name="CALL_PARAMETERS_WRAP" value="1" />
<option name="METHOD_PARAMETERS_WRAP" value="5" />
<option name="BINARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
<option name="FOR_STATEMENT_WRAP" value="5" />
<option name="ARRAY_INITIALIZER_WRAP" value="1" />
<option name="ASSIGNMENT_WRAP" value="1" />
<option name="IF_BRACE_FORCE" value="1" />
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="XML">
<indentOptions>
<option name="INDENT_SIZE" value="2" />
+5 -1
View File
@@ -20,7 +20,11 @@
<entry name="!*.class" />
<entry name="!*.groovy" />
</wildcardResourcePatterns>
<annotationProcessing enabled="false" useClasspath="true" />
<annotationProcessing>
<profile default="true" name="Default" enabled="false">
<processorPath useClasspath="true" />
</profile>
</annotationProcessing>
</component>
<component name="EclipseCompilerSettings">
<option name="GENERATE_NO_WARNINGS" value="true" />
+3
View File
@@ -594,6 +594,9 @@
<inspection_tool class="UtilityClassWithPublicConstructor" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="UtilityClassWithoutPrivateConstructor" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoreClassesWithOnlyMain" value="false" />
<option name="ignorableAnnotations">
<value />
</option>
</inspection_tool>
<inspection_tool class="WaitNotInLoop" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="WaitNotInSynchronizedContext" enabled="true" level="WARNING" enabled_by_default="true" />
@@ -799,6 +799,9 @@
<inspection_tool class="UtilityClassWithPublicConstructor" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="UtilityClassWithoutPrivateConstructor" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoreClassesWithOnlyMain" value="false" />
<option name="ignorableAnnotations">
<value />
</option>
</inspection_tool>
<inspection_tool class="ValidExternallyBoundObject" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="ValidatorConfigModelInspection" enabled="false" level="ERROR" enabled_by_default="false" />
+1
View File
@@ -123,6 +123,7 @@
<module fileurl="file://$PROJECT_DIR$/platform/xdebugger-impl/xdebugger-impl.iml" filepath="$PROJECT_DIR$/platform/xdebugger-impl/xdebugger-impl.iml" group="platform" />
<module fileurl="file://$PROJECT_DIR$/xml/impl/xml.iml" filepath="$PROJECT_DIR$/xml/impl/xml.iml" group="xml" />
<module fileurl="file://$PROJECT_DIR$/xml/openapi/xml-openapi.iml" filepath="$PROJECT_DIR$/xml/openapi/xml-openapi.iml" group="xml" />
<module fileurl="file://$PROJECT_DIR$/xml/tests/xml-tests.iml" filepath="$PROJECT_DIR$/xml/tests/xml-tests.iml" group="xml" />
<module fileurl="file://$PROJECT_DIR$/plugins/xpath/xpath.iml" filepath="$PROJECT_DIR$/plugins/xpath/xpath.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/plugins/xslt-debugger/xslt-debugger.iml" filepath="$PROJECT_DIR$/plugins/xslt-debugger/xslt-debugger.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/plugins/xslt-debugger/engine/xslt-debugger-engine.iml" filepath="$PROJECT_DIR$/plugins/xslt-debugger/engine/xslt-debugger-engine.iml" group="plugins" />
+1
View File
@@ -90,6 +90,7 @@
<orderEntry type="module" module-name="relaxng" />
<orderEntry type="module" module-name="gradle" />
<orderEntry type="module" module-name="rearranger" />
<orderEntry type="module" module-name="xml-tests" scope="TEST" />
</component>
</module>
@@ -142,7 +142,6 @@ public class NewProjectUtil {
if (projectBuilder != null) {
projectBuilder.commit(newProject, null, ModulesProvider.EMPTY_MODULES_PROVIDER);
newProject.save();
}
final boolean need2OpenProjectStructure = projectBuilder == null || projectBuilder.isOpenProjectSettingsAfter();
@@ -185,6 +184,7 @@ public class NewProjectUtil {
projectManager.openProject(newProject);
}
newProject.save();
}
finally {
if (projectBuilder != null) {
@@ -71,12 +71,12 @@ import static com.intellij.codeInsight.daemon.JavaHighlightingFilter.suppressed;
*/
public class HighlightUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil");
private static final Map<String, Set<String>> ourInterfaceIncompatibleModifiers;
private static final Map<String, Set<String>> ourMethodIncompatibleModifiers;
private static final Map<String, Set<String>> ourFieldIncompatibleModifiers;
private static final Map<String, Set<String>> ourClassIncompatibleModifiers;
private static final Map<String, Set<String>> ourClassInitializerIncompatibleModifiers;
private static final Set<String> ourConstructorNotAllowedModifiers;
@NotNull private static final Map<String, Set<String>> ourInterfaceIncompatibleModifiers;
@NotNull private static final Map<String, Set<String>> ourMethodIncompatibleModifiers;
@NotNull private static final Map<String, Set<String>> ourFieldIncompatibleModifiers;
@NotNull private static final Map<String, Set<String>> ourClassIncompatibleModifiers;
@NotNull private static final Map<String, Set<String>> ourClassInitializerIncompatibleModifiers;
@NotNull private static final Set<String> ourConstructorNotAllowedModifiers;
@NonNls public static final String SERIAL_VERSION_UID_FIELD_NAME = "serialVersionUID";
@NonNls private static final String SERIAL_PERSISTENT_FIELDS_FIELD_NAME = "serialPersistentFields";
@@ -218,8 +218,8 @@ public class HighlightUtil {
@Nullable
public static String getIncompatibleModifier(String modifier,
PsiModifierList modifierList,
Map<String, Set<String>> incompatibleModifiersHash) {
@Nullable PsiModifierList modifierList,
@NotNull Map<String, Set<String>> incompatibleModifiersHash) {
if (modifierList == null) return null;
// modifier is always incompatible with itself
PsiElement[] modifiers = modifierList.getChildren();
@@ -244,9 +244,9 @@ public class HighlightUtil {
/**
* make element protected/package local/public suggestion
*/
static void registerAccessQuickFixAction(PsiMember refElement,
PsiJavaCodeReferenceElement place,
HighlightInfo errorResult,
static void registerAccessQuickFixAction(@NotNull PsiMember refElement,
@NotNull PsiJavaCodeReferenceElement place,
@NotNull HighlightInfo errorResult,
final PsiElement fileResolveScope) {
PsiClass accessObjectClass = null;
PsiElement qualifier = place.getQualifier();
@@ -300,7 +300,7 @@ public class HighlightUtil {
}
@Nullable
private static PsiClass getPackageLocalClassInTheMiddle(PsiJavaCodeReferenceElement place) {
private static PsiClass getPackageLocalClassInTheMiddle(@NotNull PsiJavaCodeReferenceElement place) {
if (place instanceof PsiReferenceExpression) {
// check for package local classes in the middle
PsiReferenceExpression expression = (PsiReferenceExpression)place;
@@ -325,7 +325,7 @@ public class HighlightUtil {
@Nullable
static HighlightInfo checkInstanceOfApplicable(PsiInstanceOfExpression expression) {
static HighlightInfo checkInstanceOfApplicable(@NotNull PsiInstanceOfExpression expression) {
PsiExpression operand = expression.getOperand();
PsiTypeElement typeElement = expression.getCheckType();
if (typeElement == null) return null;
@@ -343,7 +343,7 @@ public class HighlightUtil {
@Nullable
static HighlightInfo checkInconvertibleTypeCast(PsiTypeCastExpression expression) {
static HighlightInfo checkInconvertibleTypeCast(@NotNull PsiTypeCastExpression expression) {
PsiTypeElement castTypeElement = expression.getCastType();
if (castTypeElement == null) return null;
PsiType castType = castTypeElement.getType();
@@ -363,7 +363,7 @@ public class HighlightUtil {
}
@Nullable
static HighlightInfo checkVariableExpected(PsiExpression expression) {
static HighlightInfo checkVariableExpected(@NotNull PsiExpression expression) {
PsiExpression lValue;
if (expression instanceof PsiAssignmentExpression) {
PsiAssignmentExpression assignment = (PsiAssignmentExpression)expression;
@@ -387,7 +387,7 @@ public class HighlightUtil {
@Nullable
static HighlightInfo checkAssignmentOperatorApplicable(PsiAssignmentExpression assignment) {
static HighlightInfo checkAssignmentOperatorApplicable(@NotNull PsiAssignmentExpression assignment) {
PsiJavaToken operationSign = assignment.getOperationSign();
IElementType eqOpSign = operationSign.getTokenType();
IElementType opSign = TypeConversionUtil.convertEQtoOperation(eqOpSign);
@@ -412,7 +412,7 @@ public class HighlightUtil {
@Nullable
static HighlightInfo checkAssignmentCompatibleTypes(PsiAssignmentExpression assignment) {
static HighlightInfo checkAssignmentCompatibleTypes(@NotNull PsiAssignmentExpression assignment) {
if (!"=".equals(assignment.getOperationSign().getText())) return null;
PsiExpression lExpr = assignment.getLExpression();
PsiExpression rExpr = assignment.getRExpression();
@@ -437,7 +437,7 @@ public class HighlightUtil {
return highlightInfo;
}
private static boolean isCastIntentionApplicable(PsiExpression expression, PsiType toType) {
private static boolean isCastIntentionApplicable(@NotNull PsiExpression expression, @Nullable PsiType toType) {
while (expression instanceof PsiTypeCastExpression || expression instanceof PsiParenthesizedExpression) {
if (expression instanceof PsiTypeCastExpression) {
expression = ((PsiTypeCastExpression)expression).getOperand();
@@ -453,7 +453,7 @@ public class HighlightUtil {
@Nullable
static HighlightInfo checkVariableInitializerType(PsiVariable variable) {
static HighlightInfo checkVariableInitializerType(@NotNull PsiVariable variable) {
PsiExpression initializer = variable.getInitializer();
// array initializer checked in checkArrayInitializerApplicable
if (initializer == null || initializer instanceof PsiArrayInitializerExpression) return null;
@@ -469,13 +469,13 @@ public class HighlightUtil {
}
@Nullable
static HighlightInfo checkAssignability(PsiType lType, @Nullable PsiType rType, PsiExpression expression, PsiElement elementToHighlight) {
static HighlightInfo checkAssignability(PsiType lType, @Nullable PsiType rType, PsiExpression expression, @NotNull PsiElement elementToHighlight) {
TextRange textRange = elementToHighlight.getTextRange();
return checkAssignability(lType, rType, expression, textRange);
}
@Nullable
public static HighlightInfo checkAssignability(@Nullable PsiType lType, @Nullable PsiType rType, @Nullable PsiExpression expression, TextRange textRange) {
public static HighlightInfo checkAssignability(@Nullable PsiType lType, @Nullable PsiType rType, @Nullable PsiExpression expression, @NotNull TextRange textRange) {
if (lType == rType) return null;
if (expression == null) {
if (rType == null || lType == null || TypeConversionUtil.isAssignable(lType, rType)) return null;
@@ -500,7 +500,7 @@ public class HighlightUtil {
@Nullable
static HighlightInfo checkReturnStatementType(PsiReturnStatement statement) {
static HighlightInfo checkReturnStatementType(@NotNull PsiReturnStatement statement) {
if (suppressed(Kind.RETURN_STATEMENT, statement)) return null;
PsiMethod method = null;
@@ -569,18 +569,20 @@ public class HighlightUtil {
return errorResult;
}
public static String getUnhandledExceptionsDescriptor(final Collection<PsiClassType> unhandled) {
public static String getUnhandledExceptionsDescriptor(@NotNull final Collection<PsiClassType> unhandled) {
return getUnhandledExceptionsDescriptor(unhandled, null);
}
private static String getUnhandledExceptionsDescriptor(final Collection<PsiClassType> unhandled, final String source) {
private static String getUnhandledExceptionsDescriptor(@NotNull final Collection<PsiClassType> unhandled, @Nullable final String source) {
final String exceptions = formatTypes(unhandled);
return source != null ? JavaErrorMessages.message("unhandled.close.exceptions", exceptions, unhandled.size(), source)
: JavaErrorMessages.message("unhandled.exceptions", exceptions, unhandled.size());
}
private static String formatTypes(Collection<PsiClassType> unhandled) {
@NotNull
private static String formatTypes(@NotNull Collection<PsiClassType> unhandled) {
return StringUtil.join(unhandled, new Function<PsiClassType, String>() {
@NotNull
@Override
public String fun(PsiClassType type) {
return formatType(type);
@@ -589,7 +591,7 @@ public class HighlightUtil {
}
@Nullable
static HighlightInfo checkVariableAlreadyDefined(PsiVariable variable) {
static HighlightInfo checkVariableAlreadyDefined(@NotNull PsiVariable variable) {
if (variable instanceof ExternallyDefinedPsiElement) return null;
PsiIdentifier identifier = variable.getNameIdentifier();
assert identifier != null : variable;
@@ -682,7 +684,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkUnhandledExceptions(final PsiElement element, TextRange fixRange) {
public static HighlightInfo checkUnhandledExceptions(@NotNull final PsiElement element, @Nullable TextRange fixRange) {
final List<PsiClassType> unhandledExceptions = ExceptionUtil.getUnhandledExceptions(element);
if (unhandledExceptions.isEmpty()) return null;
@@ -697,7 +699,7 @@ public class HighlightUtil {
}
@Nullable
public static HighlightInfo checkUnhandledCloserExceptions(final PsiResourceVariable resource) {
public static HighlightInfo checkUnhandledCloserExceptions(@NotNull final PsiResourceVariable resource) {
final List<PsiClassType> unhandled = ExceptionUtil.getUnhandledCloserExceptions(resource, null);
if (unhandled.isEmpty()) return null;
@@ -710,9 +712,9 @@ public class HighlightUtil {
return highlight;
}
private static void registerUnhandledExceptionFixes(final PsiElement element,
private static void registerUnhandledExceptionFixes(@NotNull final PsiElement element,
final HighlightInfo errorResult,
final List<PsiClassType> unhandled) {
@NotNull final List<PsiClassType> unhandled) {
QuickFixAction.registerQuickFixAction(errorResult, new AddExceptionToCatchFix());
QuickFixAction.registerQuickFixAction(errorResult, new AddExceptionToThrowsFix(element));
QuickFixAction.registerQuickFixAction(errorResult, new SurroundWithTryCatchFix(element));
@@ -734,7 +736,7 @@ public class HighlightUtil {
@Nullable
static HighlightInfo checkBreakOutsideLoop(PsiBreakStatement statement) {
static HighlightInfo checkBreakOutsideLoop(@NotNull PsiBreakStatement statement) {
if (statement.getLabelIdentifier() == null) {
if (new PsiMatcherImpl(statement).ancestor(EnclosingLoopOrSwitchMatcherExpression.INSTANCE).getElement() == null) {
return HighlightInfo
@@ -749,7 +751,7 @@ public class HighlightUtil {
@Nullable
static HighlightInfo checkContinueOutsideLoop(PsiContinueStatement statement) {
static HighlightInfo checkContinueOutsideLoop(@NotNull PsiContinueStatement statement) {
if (statement.getLabelIdentifier() == null) {
if (new PsiMatcherImpl(statement).ancestor(EnclosingLoopMatcherExpression.INSTANCE).getElement() == null) {
return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, statement, JavaErrorMessages.message("continue.outside.loop"));
@@ -769,7 +771,7 @@ public class HighlightUtil {
@Nullable
static HighlightInfo checkIllegalModifierCombination(PsiKeyword keyword, PsiModifierList modifierList) {
static HighlightInfo checkIllegalModifierCombination(@NotNull PsiKeyword keyword, @NotNull PsiModifierList modifierList) {
@PsiModifier.ModifierConstant String modifier = keyword.getText();
String incompatible = getIncompatibleModifier(modifier, modifierList);
@@ -785,7 +787,7 @@ public class HighlightUtil {
}
@Nullable
private static Map<String, Set<String>> getIncompatibleModifierMap(PsiModifierList modifierList) {
private static Map<String, Set<String>> getIncompatibleModifierMap(@NotNull PsiModifierList modifierList) {
PsiElement parent = modifierList.getParent();
if (parent == null || PsiUtilCore.hasErrorElementChild(parent)) return null;
return parent instanceof PsiClass
@@ -798,7 +800,7 @@ public class HighlightUtil {
}
@Nullable
public static String getIncompatibleModifier(String modifier, PsiModifierList modifierList) {
public static String getIncompatibleModifier(String modifier, @NotNull PsiModifierList modifierList) {
PsiElement parent = modifierList.getParent();
if (parent == null || PsiUtilCore.hasErrorElementChild(parent)) return null;
final Map<String, Set<String>> incompatibleModifierMap = getIncompatibleModifierMap(modifierList);
@@ -808,7 +810,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkNotAllowedModifier(PsiKeyword keyword, PsiModifierList modifierList) {
public static HighlightInfo checkNotAllowedModifier(@NotNull PsiKeyword keyword, @NotNull PsiModifierList modifierList) {
PsiElement modifierOwner = modifierList.getParent();
if (modifierOwner == null) return null;
if (PsiUtilCore.hasErrorElementChild(modifierOwner)) return null;
@@ -885,7 +887,7 @@ public class HighlightUtil {
}
@Nullable
public static HighlightInfo checkLiteralExpressionParsingError(final PsiLiteralExpression expression) {
public static HighlightInfo checkLiteralExpressionParsingError(@NotNull final PsiLiteralExpression expression) {
final Object value = expression.getValue();
final PsiElement literal = expression.getFirstChild();
assert literal instanceof PsiJavaToken : literal;
@@ -1057,7 +1059,7 @@ public class HighlightUtil {
}
// true if floating point literal consists of zeros only
public static boolean isFPZero(final String text) {
public static boolean isFPZero(@NotNull final String text) {
for (int i = 0; i < text.length(); i++) {
final char c = text.charAt(i);
if (Character.isDigit(c) && c != '0') return false;
@@ -1092,7 +1094,7 @@ public class HighlightUtil {
@NotNull
static Set<PsiClassType> collectUnhandledExceptions(final PsiTryStatement statement) {
static Set<PsiClassType> collectUnhandledExceptions(@NotNull final PsiTryStatement statement) {
final Set<PsiClassType> thrownTypes = Sets.newHashSet();
final PsiCodeBlock tryBlock = statement.getTryBlock();
@@ -1109,7 +1111,7 @@ public class HighlightUtil {
}
@Nullable
static Collection<HighlightInfo> checkExceptionThrownInTry(final PsiParameter parameter, final Set<PsiClassType> thrownTypes) {
static Collection<HighlightInfo> checkExceptionThrownInTry(@NotNull final PsiParameter parameter, @NotNull final Set<PsiClassType> thrownTypes) {
final PsiElement declarationScope = parameter.getDeclarationScope();
if (!(declarationScope instanceof PsiCatchSection)) return null;
@@ -1125,9 +1127,9 @@ public class HighlightUtil {
}
@Nullable
private static Collection<HighlightInfo> checkSimpleCatchParameter(final PsiParameter parameter,
final Collection<PsiClassType> thrownTypes,
final PsiClassType caughtType) {
private static Collection<HighlightInfo> checkSimpleCatchParameter(@NotNull final PsiParameter parameter,
@NotNull final Collection<PsiClassType> thrownTypes,
@NotNull final PsiClassType caughtType) {
if (ExceptionUtil.isUncheckedExceptionOrSuperclass(caughtType)) return null;
for (PsiClassType exceptionType : thrownTypes) {
@@ -1141,8 +1143,8 @@ public class HighlightUtil {
}
@Nullable
private static Collection<HighlightInfo> checkMultiCatchParameter(final PsiParameter parameter,
final Collection<PsiClassType> thrownTypes) {
private static Collection<HighlightInfo> checkMultiCatchParameter(@NotNull final PsiParameter parameter,
@NotNull final Collection<PsiClassType> thrownTypes) {
final List<PsiTypeElement> typeElements = PsiUtil.getParameterTypeElements(parameter);
final Collection<HighlightInfo> highlights = Lists.newArrayListWithCapacity(typeElements.size());
@@ -1170,8 +1172,8 @@ public class HighlightUtil {
@Nullable
static Collection<HighlightInfo> checkWithImprovedCatchAnalysis(final PsiParameter parameter,
final Collection<PsiClassType> thrownInTryStatement) {
static Collection<HighlightInfo> checkWithImprovedCatchAnalysis(@NotNull final PsiParameter parameter,
@NotNull final Collection<PsiClassType> thrownInTryStatement) {
final PsiElement scope = parameter.getDeclarationScope();
if (!(scope instanceof PsiCatchSection)) return null;
@@ -1194,7 +1196,7 @@ public class HighlightUtil {
// collect exceptions which are caught by this type
Collection<PsiClassType> caught = ContainerUtil.findAll(thrownTypes, new Condition<PsiClassType>() {
@Override
public boolean value(PsiClassType type) {
public boolean value(@NotNull PsiClassType type) {
return catchType.isAssignableFrom(type);
}
});
@@ -1233,7 +1235,7 @@ public class HighlightUtil {
@Nullable
static HighlightInfo checkNotAStatement(PsiStatement statement) {
static HighlightInfo checkNotAStatement(@NotNull PsiStatement statement) {
if (!PsiUtil.isStatement(statement) && !PsiUtilCore.hasErrorElementChild(statement)) {
return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, statement, JavaErrorMessages.message("not.a.statement"));
}
@@ -1242,7 +1244,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkSwitchSelectorType(PsiSwitchStatement statement) {
public static HighlightInfo checkSwitchSelectorType(@NotNull PsiSwitchStatement statement) {
final PsiExpression expression = statement.getExpression();
HighlightInfo errorResult = null;
if (expression != null && expression.getType() != null) {
@@ -1267,7 +1269,7 @@ public class HighlightUtil {
return errorResult;
}
public static boolean isValidTypeForSwitchSelector(PsiType type, final boolean languageLevel7OrHigher) {
public static boolean isValidTypeForSwitchSelector(@NotNull PsiType type, final boolean languageLevel7OrHigher) {
if (TypeConversionUtil.getTypeRank(type) <= TypeConversionUtil.INT_RANK) return true;
if (type instanceof PsiClassType) {
PsiClass psiClass = ((PsiClassType)type).resolve();
@@ -1283,7 +1285,7 @@ public class HighlightUtil {
}
@Nullable
static HighlightInfo checkPolyadicOperatorApplicable(PsiPolyadicExpression expression) {
static HighlightInfo checkPolyadicOperatorApplicable(@NotNull PsiPolyadicExpression expression) {
PsiExpression[] operands = expression.getOperands();
PsiType lType = operands[0].getType();
@@ -1306,7 +1308,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkUnaryOperatorApplicable(PsiJavaToken token, PsiExpression expression) {
static HighlightInfo checkUnaryOperatorApplicable(@Nullable PsiJavaToken token, @Nullable PsiExpression expression) {
if (token != null && expression != null && !TypeConversionUtil.isUnaryOperatorApplicable(token, expression)) {
PsiType type = expression.getType();
if (type == null) return null;
@@ -1323,8 +1325,8 @@ public class HighlightUtil {
}
@Nullable
public static HighlightInfo checkThisOrSuperExpressionInIllegalContext(PsiExpression expr,
@Nullable PsiJavaCodeReferenceElement qualifier) {
static HighlightInfo checkThisOrSuperExpressionInIllegalContext(@NotNull PsiExpression expr,
@Nullable PsiJavaCodeReferenceElement qualifier) {
if (expr instanceof PsiSuperExpression) {
final PsiElement parent = expr.getParent();
if (!(parent instanceof PsiReferenceExpression)) {
@@ -1363,9 +1365,9 @@ public class HighlightUtil {
return null;
}
private static boolean resolvesToImmediateSuperInterface(PsiExpression expr,
private static boolean resolvesToImmediateSuperInterface(@NotNull PsiExpression expr,
@Nullable PsiJavaCodeReferenceElement qualifier,
PsiClass aClass) {
@NotNull PsiClass aClass) {
if (!(expr instanceof PsiSuperExpression) || qualifier == null || !PsiUtil.isLanguageLevel8OrHigher(expr)) return false;
final PsiType superType = expr.getType();
if (!(superType instanceof PsiClassType)) return false;
@@ -1373,13 +1375,13 @@ public class HighlightUtil {
return superClass != null && aClass.equals(superClass);
}
static String buildProblemWithStaticDescription(PsiElement refElement) {
static String buildProblemWithStaticDescription(@NotNull PsiElement refElement) {
String type = LanguageFindUsages.INSTANCE.forLanguage(JavaLanguage.INSTANCE).getType(refElement);
String name = HighlightMessageUtil.getSymbolName(refElement, PsiSubstitutor.EMPTY);
return JavaErrorMessages.message("non.static.symbol.referenced.from.static.context", type, name);
}
static void registerStaticProblemQuickFixAction(@NotNull PsiElement refElement, HighlightInfo errorResult, PsiJavaCodeReferenceElement place) {
static void registerStaticProblemQuickFixAction(@NotNull PsiElement refElement, HighlightInfo errorResult, @NotNull PsiJavaCodeReferenceElement place) {
if (refElement instanceof PsiModifierListOwner) {
QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createModifierListFix((PsiModifierListOwner)refElement, PsiModifier.STATIC, true, false));
}
@@ -1393,7 +1395,7 @@ public class HighlightUtil {
}
}
private static boolean isInstanceReference(PsiJavaCodeReferenceElement place) {
private static boolean isInstanceReference(@NotNull PsiJavaCodeReferenceElement place) {
PsiElement qualifier = place.getQualifier();
if (qualifier == null) return true;
if (!(qualifier instanceof PsiJavaCodeReferenceElement)) return false;
@@ -1404,11 +1406,13 @@ public class HighlightUtil {
return qname == null || !Character.isLowerCase(qname.charAt(0));
}
static String buildProblemWithAccessDescription(final PsiJavaCodeReferenceElement reference, final JavaResolveResult result) {
static String buildProblemWithAccessDescription(@NotNull final PsiJavaCodeReferenceElement reference, @NotNull final JavaResolveResult result) {
return buildProblemWithAccessDescription(reference, result, result.getElement());
}
static String buildProblemWithAccessDescription(final PsiJavaCodeReferenceElement reference, final JavaResolveResult result, final PsiElement resolved) {
static String buildProblemWithAccessDescription(@NotNull final PsiJavaCodeReferenceElement reference,
@NotNull final JavaResolveResult result,
@NotNull final PsiElement resolved) {
assert resolved instanceof PsiModifierListOwner : resolved;
PsiModifierListOwner refElement = (PsiModifierListOwner)resolved;
String symbolName = HighlightMessageUtil.getSymbolName(refElement, result.getSubstitutor());
@@ -1459,7 +1463,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkCatchParameterIsThrowable(final PsiParameter parameter) {
public static HighlightInfo checkCatchParameterIsThrowable(@NotNull final PsiParameter parameter) {
if (parameter.getDeclarationScope() instanceof PsiCatchSection) {
final PsiType type = parameter.getType();
return checkMustBeThrowable(type, parameter, true);
@@ -1509,7 +1513,7 @@ public class HighlightUtil {
}
@Nullable
private static PsiType getArrayInitializerType(final PsiArrayInitializerExpression element) {
private static PsiType getArrayInitializerType(@NotNull final PsiArrayInitializerExpression element) {
final PsiType typeCheckResult = sameType(element.getInitializers());
if (typeCheckResult != null) {
return typeCheckResult.createArrayType();
@@ -1518,7 +1522,7 @@ public class HighlightUtil {
}
@Nullable
public static PsiType sameType(PsiExpression[] expressions) {
public static PsiType sameType(@NotNull PsiExpression[] expressions) {
PsiType type = null;
for (PsiExpression expression : expressions) {
final PsiType currentType;
@@ -1539,7 +1543,7 @@ public class HighlightUtil {
}
@Nullable
private static HighlightInfo checkArrayInitializerCompatibleTypes(PsiExpression initializer, final PsiType componentType) {
private static HighlightInfo checkArrayInitializerCompatibleTypes(@NotNull PsiExpression initializer, final PsiType componentType) {
PsiType initializerType = initializer.getType();
if (initializerType == null) {
return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, initializer,
@@ -1550,7 +1554,7 @@ public class HighlightUtil {
}
@Nullable
public static HighlightInfo checkExpressionRequired(PsiReferenceExpression expression, JavaResolveResult resultForIncompleteCode) {
public static HighlightInfo checkExpressionRequired(@NotNull PsiReferenceExpression expression, @NotNull JavaResolveResult resultForIncompleteCode) {
if (expression.getNextSibling() instanceof PsiErrorElement) return null;
PsiElement resolved = resultForIncompleteCode.getElement();
if (resolved == null) return null;
@@ -1563,7 +1567,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkArrayInitializerApplicable(PsiArrayInitializerExpression expression) {
public static HighlightInfo checkArrayInitializerApplicable(@NotNull PsiArrayInitializerExpression expression) {
/*
JLS 10.6 Array Initializers
An array initializer may be specified in a declaration, or as part of an array creation expression
@@ -1585,7 +1589,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkCaseStatement(PsiSwitchLabelStatement statement) {
public static HighlightInfo checkCaseStatement(@NotNull PsiSwitchLabelStatement statement) {
PsiSwitchStatement switchStatement = statement.getEnclosingSwitchStatement();
if (switchStatement == null) {
return HighlightInfo
@@ -1670,7 +1674,7 @@ public class HighlightUtil {
* see JLS 8.3.2.3
*/
@Nullable
public static HighlightInfo checkIllegalForwardReferenceToField(PsiReferenceExpression expression, PsiField referencedField) {
public static HighlightInfo checkIllegalForwardReferenceToField(@NotNull PsiReferenceExpression expression, @NotNull PsiField referencedField) {
PsiClass containingClass = referencedField.getContainingClass();
if (containingClass == null) return null;
if (expression.getContainingFile() != referencedField.getContainingFile()) return null;
@@ -1696,7 +1700,7 @@ public class HighlightUtil {
* @return field that has initializer with this element as subexpression or null if not found
*/
@Nullable
static PsiField findEnclosingFieldInitializer(PsiElement element) {
static PsiField findEnclosingFieldInitializer(@Nullable PsiElement element) {
while (element != null) {
PsiElement parent = element.getParent();
if (parent instanceof PsiField) {
@@ -1711,7 +1715,7 @@ public class HighlightUtil {
}
@Nullable
private static PsiClassInitializer findParentClassInitializer(PsiElement element) {
private static PsiClassInitializer findParentClassInitializer(@Nullable PsiElement element) {
while (element != null) {
if (element instanceof PsiClassInitializer) return (PsiClassInitializer)element;
if (element instanceof PsiClass || element instanceof PsiMethod) return null;
@@ -1722,7 +1726,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkIllegalType(PsiTypeElement typeElement) {
public static HighlightInfo checkIllegalType(@Nullable PsiTypeElement typeElement) {
if (typeElement == null || typeElement.getParent() instanceof PsiTypeElement) return null;
if (PsiUtil.isInsideJavadocComment(typeElement)) return null;
@@ -1742,7 +1746,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkIllegalVoidType(PsiKeyword type) {
public static HighlightInfo checkIllegalVoidType(@NotNull PsiKeyword type) {
if (!PsiKeyword.VOID.equals(type.getText())) return null;
PsiElement parent = type.getParent();
@@ -1768,7 +1772,7 @@ public class HighlightUtil {
}
@Nullable
public static HighlightInfo checkMemberReferencedBeforeConstructorCalled(PsiElement expression, PsiElement resolved) {
public static HighlightInfo checkMemberReferencedBeforeConstructorCalled(@NotNull PsiElement expression, PsiElement resolved) {
PsiClass referencedClass;
@NonNls String resolvedName;
PsiType type;
@@ -1871,7 +1875,7 @@ public class HighlightUtil {
}
@Nullable
private static HighlightInfo checkReferenceToOurInstanceInsideThisOrSuper(final PsiElement expression,
private static HighlightInfo checkReferenceToOurInstanceInsideThisOrSuper(@NotNull final PsiElement expression,
final PsiClass referencedClass,
final String resolvedName) {
if (PsiTreeUtil.getParentOfType(expression, PsiReferenceParameterList.class) != null) return null;
@@ -1918,13 +1922,13 @@ public class HighlightUtil {
return null;
}
private static HighlightInfo createMemberReferencedError(@NonNls final String resolvedName, TextRange textRange) {
private static HighlightInfo createMemberReferencedError(@NonNls final String resolvedName, @NotNull TextRange textRange) {
String description = JavaErrorMessages.message("member.referenced.before.constructor.called", resolvedName);
return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, textRange, description);
}
@Nullable
public static HighlightInfo checkImplicitThisReferenceBeforeSuper(PsiClass aClass) {
public static HighlightInfo checkImplicitThisReferenceBeforeSuper(@NotNull PsiClass aClass) {
if (aClass instanceof PsiAnonymousClass) return null;
PsiClass superClass = aClass.getSuperClass();
if (superClass == null || !PsiUtil.isInnerClass(superClass)) return null;
@@ -1946,7 +1950,7 @@ public class HighlightUtil {
return null;
}
private static boolean isSuperCalledInConstructor(final PsiMethod constructor) {
private static boolean isSuperCalledInConstructor(@NotNull final PsiMethod constructor) {
final PsiCodeBlock body = constructor.getBody();
if (body == null) return false;
final PsiStatement[] statements = body.getStatements();
@@ -1963,23 +1967,23 @@ public class HighlightUtil {
}
@Nullable
private static String getMethodExpressionName(PsiElement element) {
private static String getMethodExpressionName(@NotNull PsiElement element) {
if (!(element instanceof PsiMethodCallExpression)) return null;
PsiReferenceExpression methodExpression = ((PsiMethodCallExpression)element).getMethodExpression();
return methodExpression.getReferenceName();
}
public static boolean isSuperOrThisMethodCall(PsiElement element) {
public static boolean isSuperOrThisMethodCall(@NotNull PsiElement element) {
String name = getMethodExpressionName(element);
return PsiKeyword.SUPER.equals(name) || PsiKeyword.THIS.equals(name);
}
public static boolean isSuperMethodCall(PsiElement element) {
public static boolean isSuperMethodCall(@NotNull PsiElement element) {
String name = getMethodExpressionName(element);
return PsiKeyword.SUPER.equals(name);
}
private static boolean thisOrSuperReference(PsiExpression qualifierExpression, PsiClass aClass) {
private static boolean thisOrSuperReference(@Nullable PsiExpression qualifierExpression, PsiClass aClass) {
if (qualifierExpression == null) return true;
PsiJavaCodeReferenceElement qualifier;
if (qualifierExpression instanceof PsiThisExpression) {
@@ -1998,7 +2002,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkLabelWithoutStatement(PsiLabeledStatement statement) {
public static HighlightInfo checkLabelWithoutStatement(@NotNull PsiLabeledStatement statement) {
if (statement.getStatement() == null) {
return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, statement, JavaErrorMessages.message("label.without.statement"));
}
@@ -2007,7 +2011,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkLabelAlreadyInUse(PsiLabeledStatement statement) {
public static HighlightInfo checkLabelAlreadyInUse(@NotNull PsiLabeledStatement statement) {
PsiIdentifier identifier = statement.getLabelIdentifier();
String text = identifier.getText();
PsiElement element = statement;
@@ -2025,7 +2029,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkUnclosedComment(PsiComment comment) {
public static HighlightInfo checkUnclosedComment(@NotNull PsiComment comment) {
if (!(comment instanceof PsiDocComment) && !(comment.getTokenType() == JavaTokenType.C_STYLE_COMMENT)) return null;
if (!comment.getText().endsWith("*/")) {
int start = comment.getTextRange().getEndOffset() - 1;
@@ -2037,7 +2041,7 @@ public class HighlightUtil {
@Nullable
static Collection<HighlightInfo> checkCatchTypeIsDisjoint(final PsiParameter parameter) {
static Collection<HighlightInfo> checkCatchTypeIsDisjoint(@NotNull final PsiParameter parameter) {
if (!(parameter.getType() instanceof PsiDisjunctionType)) return null;
final Collection<HighlightInfo> result = Lists.newArrayList();
@@ -2065,7 +2069,7 @@ public class HighlightUtil {
@Nullable
static Collection<HighlightInfo> checkExceptionAlreadyCaught(final PsiParameter parameter) {
static Collection<HighlightInfo> checkExceptionAlreadyCaught(@NotNull final PsiParameter parameter) {
final PsiElement scope = parameter.getDeclarationScope();
if (!(scope instanceof PsiCatchSection)) return null;
@@ -2109,7 +2113,7 @@ public class HighlightUtil {
return result.size() > 0 ? result : null;
}
private static boolean checkMultipleTypes(final PsiClass catchClass, final List<PsiType> upperCatchTypes) {
private static boolean checkMultipleTypes(final PsiClass catchClass, @NotNull final List<PsiType> upperCatchTypes) {
for (int i = upperCatchTypes.size() - 1; i >= 0; i--) {
if (checkSingleType(catchClass, upperCatchTypes.get(i))) return true;
}
@@ -2123,7 +2127,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkTernaryOperatorConditionIsBoolean(PsiExpression expression, PsiType type) {
public static HighlightInfo checkTernaryOperatorConditionIsBoolean(@NotNull PsiExpression expression, PsiType type) {
if (expression.getParent() instanceof PsiConditionalExpression &&
((PsiConditionalExpression)expression.getParent()).getCondition() == expression && !TypeConversionUtil.isBooleanType(type)) {
return createIncompatibleTypeHighlightInfo(PsiType.BOOLEAN, type, expression.getTextRange());
@@ -2133,7 +2137,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkStatementPrependedWithCaseInsideSwitch(PsiStatement statement) {
public static HighlightInfo checkStatementPrependedWithCaseInsideSwitch(@NotNull PsiStatement statement) {
if (!(statement instanceof PsiSwitchLabelStatement) && statement.getParent() instanceof PsiCodeBlock &&
statement.getParent().getParent() instanceof PsiSwitchStatement &&
((PsiCodeBlock)statement.getParent()).getStatements().length != 0 &&
@@ -2146,7 +2150,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkAssertOperatorTypes(PsiExpression expression, PsiType type) {
public static HighlightInfo checkAssertOperatorTypes(@NotNull PsiExpression expression, @Nullable PsiType type) {
if (type == null) return null;
if (!(expression.getParent() instanceof PsiAssertStatement)) {
return null;
@@ -2165,7 +2169,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkSynchronizedExpressionType(PsiExpression expression, PsiType type) {
public static HighlightInfo checkSynchronizedExpressionType(@NotNull PsiExpression expression, @Nullable PsiType type) {
if (type == null) return null;
if (expression.getParent() instanceof PsiSynchronizedStatement) {
PsiSynchronizedStatement synchronizedStatement = (PsiSynchronizedStatement)expression.getParent();
@@ -2180,7 +2184,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkConditionalExpressionBranchTypesMatch(final PsiExpression expression, PsiType type) {
public static HighlightInfo checkConditionalExpressionBranchTypesMatch(@NotNull final PsiExpression expression, PsiType type) {
PsiElement parent = expression.getParent();
if (!(parent instanceof PsiConditionalExpression)) {
return null;
@@ -2201,7 +2205,7 @@ public class HighlightUtil {
return null;
}
private static HighlightInfo createIncompatibleTypeHighlightInfo(final PsiType lType, final PsiType rType, final TextRange textRange) {
private static HighlightInfo createIncompatibleTypeHighlightInfo(final PsiType lType, final PsiType rType, @NotNull final TextRange textRange) {
PsiType lType1 = lType;
PsiType rType1 = rType;
PsiTypeParameter[] lTypeParams = PsiTypeParameter.EMPTY_ARRAY;
@@ -2264,8 +2268,8 @@ public class HighlightUtil {
}
@Nullable
public static HighlightInfo checkSingleImportClassConflict(PsiImportStatement statement,
Map<String, Pair<PsiImportStaticReferenceElement, PsiClass>> importedClasses) {
public static HighlightInfo checkSingleImportClassConflict(@NotNull PsiImportStatement statement,
@NotNull Map<String, Pair<PsiImportStaticReferenceElement, PsiClass>> importedClasses) {
if (statement.isOnDemand()) return null;
PsiElement element = statement.resolve();
if (element instanceof PsiClass) {
@@ -2288,14 +2292,14 @@ public class HighlightUtil {
return "<font color=red><b>" + getFQName(type, true) + "</b></font>";
}
private static String getFQName(PsiType type, boolean longName) {
private static String getFQName(@Nullable PsiType type, boolean longName) {
if (type == null) return "";
return XmlStringUtil.escapeString(longName ? type.getInternalCanonicalText() : type.getPresentableText());
}
@Nullable
public static HighlightInfo checkMustBeThrowable(PsiType type, PsiElement context, boolean addCastIntention) {
static HighlightInfo checkMustBeThrowable(@Nullable PsiType type, @NotNull PsiElement context, boolean addCastIntention) {
if (type == null) return null;
PsiElementFactory factory = JavaPsiFacade.getInstance(context.getProject()).getElementFactory();
PsiClassType throwable = factory.createTypeByFQClassName("java.lang.Throwable", context.getResolveScope());
@@ -2313,7 +2317,7 @@ public class HighlightUtil {
@Nullable
private static HighlightInfo checkMustBeThrowable(PsiClass aClass, PsiElement context) {
private static HighlightInfo checkMustBeThrowable(@Nullable PsiClass aClass, @NotNull PsiElement context) {
if (aClass == null) return null;
PsiClassType type = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory().createType(aClass);
return checkMustBeThrowable(type, context, false);
@@ -2321,7 +2325,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkLabelDefined(PsiIdentifier labelIdentifier, PsiStatement exitedStatement) {
static HighlightInfo checkLabelDefined(@Nullable PsiIdentifier labelIdentifier, @Nullable PsiStatement exitedStatement) {
if (labelIdentifier == null) return null;
String label = labelIdentifier.getText();
if (label == null) return null;
@@ -2334,7 +2338,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkReference(final PsiJavaCodeReferenceElement ref, final JavaResolveResult result) {
static HighlightInfo checkReference(@NotNull final PsiJavaCodeReferenceElement ref, @NotNull final JavaResolveResult result) {
if (suppressed(Kind.REFERENCE, ref)) return null;
final PsiElement refName = ref.getReferenceNameElement();
@@ -2414,21 +2418,23 @@ public class HighlightUtil {
if (Comparing.strEqual(((PsiClass)resolved).getQualifiedName(), ((PsiClass)resolved).getName())) {
final PsiElement parent = ref.getParent();
if (parent instanceof PsiImportStaticReferenceElement || parent instanceof PsiImportStatementBase) {
return HighlightInfo.createHighlightInfo(HighlightInfoType.WRONG_REF, refName, JavaErrorMessages.message("cannot.resolve.symbol", refName.getText()));
return HighlightInfo.createHighlightInfo(HighlightInfoType.WRONG_REF, refName,
JavaErrorMessages.message("cannot.resolve.symbol", refName.getText()));
}
}
}
return highlightInfo;
}
private static String format(PsiElement element) {
@NotNull
private static String format(@NotNull PsiElement element) {
if (element instanceof PsiClass) return formatClass((PsiClass)element);
if (element instanceof PsiMethod) return formatMethod((PsiMethod)element);
if (element instanceof PsiField) return formatField((PsiField)element);
return ElementDescriptionUtil.getElementDescription(element, HighlightUsagesDescriptionLocation.INSTANCE);
}
private static boolean isInsidePackageStatement(PsiElement element) {
private static boolean isInsidePackageStatement(@Nullable PsiElement element) {
while (element != null) {
if (element instanceof PsiPackageStatement) return true;
if (!(element instanceof PsiIdentifier) && !(element instanceof PsiJavaCodeReferenceElement)) return false;
@@ -2438,9 +2444,9 @@ public class HighlightUtil {
}
@Nullable
public static HighlightInfo checkElementInReferenceList(PsiJavaCodeReferenceElement ref,
PsiReferenceList referenceList,
JavaResolveResult resolveResult) {
static HighlightInfo checkElementInReferenceList(@NotNull PsiJavaCodeReferenceElement ref,
@NotNull PsiReferenceList referenceList,
@NotNull JavaResolveResult resolveResult) {
PsiElement resolved = resolveResult.getElement();
HighlightInfo highlightInfo = null;
PsiElement refGrandParent = referenceList.getParent();
@@ -2474,13 +2480,13 @@ public class HighlightUtil {
}
public static boolean isSerializable(PsiClass aClass) {
public static boolean isSerializable(@NotNull PsiClass aClass) {
PsiManager manager = aClass.getManager();
PsiClass serializableClass = JavaPsiFacade.getInstance(manager.getProject()).findClass("java.io.Serializable", aClass.getResolveScope());
return serializableClass != null && aClass.isInheritor(serializableClass, true);
}
public static boolean isSerializationImplicitlyUsedField(PsiField field) {
public static boolean isSerializationImplicitlyUsedField(@NotNull PsiField field) {
final String name = field.getName();
if (!SERIAL_VERSION_UID_FIELD_NAME.equals(name) && !SERIAL_PERSISTENT_FIELDS_FIELD_NAME.equals(name)) return false;
if (!field.hasModifierProperty(PsiModifier.STATIC)) return false;
@@ -2489,7 +2495,7 @@ public class HighlightUtil {
}
@Nullable
public static HighlightInfo checkClassReferenceAfterQualifier(final PsiReferenceExpression expression, final PsiElement resolved) {
public static HighlightInfo checkClassReferenceAfterQualifier(@NotNull final PsiReferenceExpression expression, final PsiElement resolved) {
if (!(resolved instanceof PsiClass)) return null;
final PsiExpression qualifier = expression.getQualifierExpression();
if (qualifier == null) return null;
@@ -2512,7 +2518,7 @@ public class HighlightUtil {
}
@Nullable
static HighlightInfo checkAnnotationMethodParameters(PsiParameterList list) {
static HighlightInfo checkAnnotationMethodParameters(@NotNull PsiParameterList list) {
if (list.getParent() instanceof PsiAnnotationMethod && list.getParametersCount() > 0) {
final String message = JavaErrorMessages.message("annotation.interface.members.may.not.have.parameters");
return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, list, message);
@@ -2582,17 +2588,17 @@ public class HighlightUtil {
}
@Nullable
public static HighlightInfo checkDiamondFeature(final PsiTypeElement typeElement) {
public static HighlightInfo checkDiamondFeature(@NotNull final PsiTypeElement typeElement) {
return typeElement.getType() instanceof PsiDiamondType ? checkFeature(typeElement.getParent(), Feature.DIAMOND_TYPES) : null;
}
@Nullable
public static HighlightInfo checkMultiCatchFeature(final PsiParameter parameter) {
public static HighlightInfo checkMultiCatchFeature(@NotNull final PsiParameter parameter) {
return parameter.getType() instanceof PsiDisjunctionType ? checkFeature(parameter, Feature.MULTI_CATCH) : null;
}
@Nullable
public static HighlightInfo checkTryWithResourcesFeature(final PsiResourceVariable resourceVariable) {
public static HighlightInfo checkTryWithResourcesFeature(@NotNull final PsiResourceVariable resourceVariable) {
return checkFeature(resourceVariable.getParent(), Feature.TRY_WITH_RESOURCES);
}
@@ -44,7 +44,7 @@ public abstract class PsiClassType extends PsiType {
protected PsiClassType(LanguageLevel languageLevel) {
this(languageLevel, PsiAnnotation.EMPTY_ARRAY);
}
protected PsiClassType(LanguageLevel languageLevel, PsiAnnotation[] annotations) {
protected PsiClassType(LanguageLevel languageLevel, @NotNull PsiAnnotation[] annotations) {
super(annotations);
myLanguageLevel = languageLevel;
}
@@ -15,7 +15,6 @@
*/
package com.intellij.psi.impl.source;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
@@ -30,7 +29,6 @@ import java.util.List;
* @author dsl
*/
public class PsiImmediateClassType extends PsiClassType {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.PsiImmediateClassType");
private final PsiClass myClass;
private final PsiSubstitutor mySubstitutor;
private final PsiManager myManager;
@@ -75,20 +73,19 @@ public class PsiImmediateClassType extends PsiClassType {
}
};
public PsiImmediateClassType(PsiClass aClass, PsiSubstitutor substitutor) {
public PsiImmediateClassType(@NotNull PsiClass aClass, @NotNull PsiSubstitutor substitutor) {
this (aClass, substitutor, null);
}
public PsiImmediateClassType(final PsiClass aClass, final PsiSubstitutor substitutor, final LanguageLevel languageLevel) {
public PsiImmediateClassType(@NotNull PsiClass aClass, @NotNull PsiSubstitutor substitutor, final LanguageLevel languageLevel) {
this(aClass, substitutor,languageLevel, PsiAnnotation.EMPTY_ARRAY);
}
public PsiImmediateClassType(PsiClass aClass, PsiSubstitutor substitutor, LanguageLevel languageLevel, PsiAnnotation[] annotations) {
public PsiImmediateClassType(@NotNull PsiClass aClass, @NotNull PsiSubstitutor substitutor, LanguageLevel languageLevel, @NotNull PsiAnnotation[] annotations) {
super(languageLevel,annotations);
myClass = aClass;
myManager = aClass.getManager();
mySubstitutor = substitutor;
LOG.assertTrue(mySubstitutor != null);
}
@Override
@@ -134,7 +131,7 @@ public class PsiImmediateClassType extends PsiClassType {
public String getPresentableText() {
if (myPresentableText == null) {
final StringBuilder buffer = new StringBuilder();
buildText(myClass, buffer, false, false);
buildText(myClass, mySubstitutor, buffer, false, false);
myPresentableText = buffer.toString();
}
return myPresentableText;
@@ -144,7 +141,7 @@ public class PsiImmediateClassType extends PsiClassType {
public String getCanonicalText() {
if (myCanonicalText == null) {
final StringBuilder buffer = new StringBuilder();
buildText(myClass, buffer, true, false);
buildText(myClass, mySubstitutor, buffer, true, false);
myCanonicalText = buffer.toString();
}
return myCanonicalText;
@@ -154,30 +151,36 @@ public class PsiImmediateClassType extends PsiClassType {
public String getInternalCanonicalText() {
if (myInternalCanonicalText == null) {
final StringBuilder buffer = new StringBuilder();
buildText(myClass, buffer, true, true);
buildText(myClass, mySubstitutor, buffer, true, true);
myInternalCanonicalText = buffer.toString();
}
return myInternalCanonicalText;
}
private void buildText(PsiClass aClass, StringBuilder buffer, boolean canonical, boolean internal) {
PsiSubstitutor substitutor = mySubstitutor;
private void buildText(@NotNull PsiClass aClass,
@NotNull PsiSubstitutor substitutor,
@NotNull StringBuilder buffer,
boolean canonical,
boolean internal) {
if (aClass instanceof PsiAnonymousClass) {
ClassResolveResult baseResolveResult = ((PsiAnonymousClass) aClass).getBaseClassType().resolveGenerics();
aClass = baseResolveResult.getElement();
substitutor = baseResolveResult.getSubstitutor();
if (aClass == null) return;
PsiClass baseClass = baseResolveResult.getElement();
PsiSubstitutor baseSub = baseResolveResult.getSubstitutor();
if (baseClass != null) {
buildText(baseClass, baseSub, buffer, canonical, internal);
}
return;
}
PsiClass parentClass = null;
PsiClass enclosingClass = null;
if (!aClass.hasModifierProperty(PsiModifier.STATIC)) {
final PsiElement parent = aClass.getParent();
if (parent instanceof PsiClass && !(parent instanceof PsiAnonymousClass)) {
parentClass = (PsiClass)parent;
enclosingClass = (PsiClass)parent;
}
}
buffer.append(getAnnotationsTextPrefix());
if (parentClass != null) {
buildText(parentClass, buffer, canonical, false);
if (enclosingClass != null) {
buildText(enclosingClass, substitutor, buffer, canonical, false);
buffer.append('.');
buffer.append(aClass.getName());
}
@@ -188,11 +191,11 @@ public class PsiImmediateClassType extends PsiClassType {
}
else {
final String qualifiedName = aClass.getQualifiedName();
if (qualifiedName != null) {
name = qualifiedName;
if (qualifiedName == null) {
name = aClass.getName();
}
else {
name = aClass.getName();
name = qualifiedName;
}
}
buffer.append(name);
@@ -210,10 +213,7 @@ public class PsiImmediateClassType extends PsiClassType {
pineBuffer = null;
break;
}
if (!canonical) {
pineBuffer.append(substitutionResult.getPresentableText());
}
else {
if (canonical) {
if (internal) {
pineBuffer.append(substitutionResult.getInternalCanonicalText());
}
@@ -221,6 +221,9 @@ public class PsiImmediateClassType extends PsiClassType {
pineBuffer.append(substitutionResult.getCanonicalText());
}
}
else {
pineBuffer.append(substitutionResult.getPresentableText());
}
}
if (pineBuffer != null) {
buffer.append(pineBuffer);
@@ -7,7 +7,6 @@ import com.intellij.codeInsight.daemon.impl.quickfix.ImportClassFix;
import com.intellij.codeInsight.daemon.impl.quickfix.ImportClassFixBase;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.unusedImport.UnusedImportLocalInspection;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.WriteCommandAction;
@@ -54,7 +53,7 @@ public class ImportHelperTest extends DaemonAnalyzerTestCase {
public void testImportsInsertedAlphabetically() throws Throwable {
@NonNls String text = "class I {}";
final PsiJavaFile file = (PsiJavaFile)configureByText(StdFileTypes.JAVA, text);
assertEmpty(filter(doHighlighting(), HighlightSeverity.ERROR));
assertEmpty(highlightErrors());
CommandProcessor.getInstance().executeCommand(
getProject(), new Runnable() {
@Override
@@ -109,7 +108,7 @@ public class ImportHelperTest extends DaemonAnalyzerTestCase {
"class I {{ max(0, 0); Map.class.hashCode(); min(0,0); Component.class.hashCode(); int i = CENTER; }}";
final PsiJavaFile file = (PsiJavaFile)configureByText(StdFileTypes.JAVA, text);
assertEmpty(filter(doHighlighting(), HighlightSeverity.ERROR));
assertEmpty(highlightErrors());
CommandProcessor.getInstance().executeCommand(
getProject(), new Runnable() {
@Override
@@ -178,7 +177,7 @@ public class ImportHelperTest extends DaemonAnalyzerTestCase {
@WrapInCommand
public void testReimportConflictingClasses() throws Exception {
configureByFile(BASE_PATH+"/x/Usage.java", BASE_PATH);
assertEmpty(filter(doHighlighting(), HighlightSeverity.ERROR));
assertEmpty(highlightErrors());
CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(getProject()).clone();
settings.CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND = 2;
@@ -204,7 +203,7 @@ public class ImportHelperTest extends DaemonAnalyzerTestCase {
@WrapInCommand
public void testConflictingClassesFromCurrentPackage() throws Throwable {
final PsiFile file = configureByText(StdFileTypes.JAVA, "package java.util; class X{ Date d;}");
assertEmpty(filter(doHighlighting(), HighlightSeverity.ERROR));
assertEmpty(highlightErrors());
new WriteCommandAction.Simple(getProject()) {
@Override
@@ -229,7 +228,7 @@ public class ImportHelperTest extends DaemonAnalyzerTestCase {
type(" ");
backspace();
assertOneElement(filter(doHighlighting(), HighlightSeverity.ERROR));
assertOneElement(highlightErrors());
int offset = myEditor.getCaretModel().getOffset();
PsiReference ref = myFile.findReferenceAt(offset - 1);
@@ -244,7 +243,7 @@ public class ImportHelperTest extends DaemonAnalyzerTestCase {
assertEquals(ImportClassFixBase.Result.CLASS_AUTO_IMPORTED, result);
UIUtil.dispatchAllInvocationEvents();
assertEmpty(filter(doHighlighting(), HighlightSeverity.ERROR));
assertEmpty(highlightErrors());
}
finally {
CodeInsightSettings.getInstance().ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = old;
@@ -261,7 +260,7 @@ public class ImportHelperTest extends DaemonAnalyzerTestCase {
type(" ");
backspace();
assertEquals(2, filter(doHighlighting(), HighlightSeverity.ERROR).size());
assertEquals(2, highlightErrors().size());
UIUtil.dispatchAllInvocationEvents();
int offset = myEditor.getCaretModel().getOffset();
@@ -272,7 +271,7 @@ public class ImportHelperTest extends DaemonAnalyzerTestCase {
assertEquals(ImportClassFixBase.Result.CLASS_AUTO_IMPORTED, result);
UIUtil.dispatchAllInvocationEvents();
assertEmpty(filter(doHighlighting(), HighlightSeverity.ERROR));
assertEmpty(highlightErrors());
}
finally {
CodeInsightSettings.getInstance().ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = old;
@@ -363,7 +362,7 @@ public class ImportHelperTest extends DaemonAnalyzerTestCase {
DaemonCodeAnalyzerSettings.getInstance().setImportHintEnabled(true);
try {
List<HighlightInfo> errs = filter(doHighlighting(), HighlightSeverity.ERROR);
List<HighlightInfo> errs = highlightErrors();
assertEquals(1, errs.size());
@@ -389,7 +388,7 @@ public class ImportHelperTest extends DaemonAnalyzerTestCase {
DaemonCodeAnalyzerSettings.getInstance().setImportHintEnabled(true);
try {
List<HighlightInfo> errs = filter(doHighlighting(), HighlightSeverity.ERROR);
List<HighlightInfo> errs = highlightErrors();
assertEquals(1, errs.size());
assertEmpty(((PsiJavaFile)getFile()).getImportList().getAllImportStatements());
@@ -138,13 +138,13 @@ public class LightAdvHighlightingJdk7Test extends LightDaemonAnalyzerTestCase {
enableInspectionTool(deadCodeInspection);
doTest(true, false);
List<HighlightInfo> infos = DaemonAnalyzerTestCase.filter(doHighlighting(), HighlightSeverity.WARNING);
List<HighlightInfo> infos = doHighlighting(HighlightSeverity.WARNING);
assertEquals(2, infos.size()); // unused class and unused method
try {
point.registerExtension(extension);
infos = DaemonAnalyzerTestCase.filter(doHighlighting(), HighlightSeverity.WARNING);
infos = doHighlighting(HighlightSeverity.WARNING);
HighlightInfo info = assertOneElement(infos);
assertEquals("Class 'WithMain' is never used", info.description);
}
@@ -19,7 +19,6 @@ import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.intention.IntentionManager;
import com.intellij.concurrency.JobSchedulerImpl;
import com.intellij.lang.LanguageAnnotators;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.lang.injection.MultiHostInjector;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ex.PathManagerEx;
@@ -107,7 +106,7 @@ public class LightAdvHighlightingPerformanceTest extends LightDaemonAnalyzerTest
}
}).cpuBound().usesAllCPUCores().assertTiming();
return DaemonAnalyzerTestCase.filter(infos, HighlightSeverity.ERROR);
return highlightErrors();
}
public void testAThinlet() throws Exception {
@@ -54,8 +54,6 @@ import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.List;
import static com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase.filter;
/**
* This class is for "lightweight" tests only, i.e. those which can run inside default light project set up
* For "heavyweight" tests use AdvHighlightingTest
@@ -275,7 +273,7 @@ public class LightAdvHighlightingTest extends LightDaemonAnalyzerTestCase {
}
});
List<HighlightInfo> infos = filter(doHighlighting(), HighlightSeverity.WARNING);
List<HighlightInfo> infos = doHighlighting(HighlightSeverity.WARNING);
assertEmpty(infos);
}
@@ -327,7 +325,7 @@ public class LightAdvHighlightingTest extends LightDaemonAnalyzerTestCase {
public void testSOEForTypeOfHugeBinaryExpression() throws IOException {
configureFromFileText("a.java", "class A { String s = \"\"; }");
assertEmpty(filter(doHighlighting(), HighlightSeverity.ERROR));
assertEmpty(highlightErrors());
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
final StringBuilder sb = new StringBuilder("\"-\"");
@@ -3,13 +3,11 @@ package com.intellij.codeInsight.daemon;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.unusedSymbol.UnusedSymbolLocalInspection;
import com.intellij.idea.Bombed;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.lang.annotation.HighlightSeverity;
import java.util.Calendar;
import java.util.Collection;
public class UnusedSymbolLocalTest extends DaemonAnalyzerTestCase {
@@ -29,7 +27,7 @@ public class UnusedSymbolLocalTest extends DaemonAnalyzerTestCase {
public void testChangeInsideCodeBlock() throws Exception {
doTest();
final Document document = myEditor.getDocument();
Collection<HighlightInfo> collection = filter(doHighlighting(), HighlightSeverity.WARNING);
Collection<HighlightInfo> collection = doHighlighting(HighlightSeverity.WARNING);
assertEquals(0, collection.size());
final int offset = myEditor.getCaretModel().getOffset();
@@ -42,7 +40,7 @@ public class UnusedSymbolLocalTest extends DaemonAnalyzerTestCase {
PsiDocumentManager.getInstance(getProject()).commitDocument(document);
Collection<HighlightInfo> infos = filter(doHighlighting(), HighlightSeverity.WARNING);
Collection<HighlightInfo> infos = doHighlighting(HighlightSeverity.WARNING);
assertEquals(1, infos.size());
}
@@ -27,7 +27,7 @@ public class SliceTreeTest extends LightDaemonAnalyzerTestCase {
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
PsiElement element = new SliceHandler(true).getExpressionAtCaret(getEditor(), getFile());
assertNotNull(element);
Collection<HighlightInfo> errors = DaemonAnalyzerTestCase.filter(doHighlighting(), HighlightSeverity.ERROR);
Collection<HighlightInfo> errors = highlightErrors();
assertEmpty(errors);
SliceAnalysisParams params = new SliceAnalysisParams();
@@ -57,8 +57,6 @@ import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileFilter;
import com.intellij.openapi.vfs.impl.VirtualFilePointerManagerImpl;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
import com.intellij.profile.codeInspection.InspectionProfileManager;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
@@ -197,7 +195,7 @@ public abstract class DaemonAnalyzerTestCase extends CodeInsightTestCase {
((StartupManagerImpl)StartupManager.getInstance(getProject())).checkCleared();
((DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(getProject())).cleanupAfterTest(!LightPlatformTestCase.isLight(getProject()));
super.tearDown();
((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).assertPointersDisposed();
//((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).assertPointersDisposed();
}
protected void enableInspectionTool(InspectionProfileEntry tool){
@@ -333,8 +331,13 @@ public abstract class DaemonAnalyzerTestCase extends CodeInsightTestCase {
}
@NotNull
protected Collection<HighlightInfo> highlightErrors() {
return filter(doHighlighting(), HighlightSeverity.ERROR);
protected List<HighlightInfo> highlightErrors() {
return doHighlighting(HighlightSeverity.ERROR);
}
@NotNull
protected List<HighlightInfo> doHighlighting(@NotNull HighlightSeverity minSeverity) {
return filter(doHighlighting(), minSeverity);
}
@NotNull
@@ -121,6 +121,11 @@ public abstract class LightDaemonAnalyzerTestCase extends LightCodeInsightTestCa
};
}
@NotNull
protected List<HighlightInfo> highlightErrors() {
return doHighlighting(HighlightSeverity.ERROR);
}
@NotNull
protected List<HighlightInfo> doHighlighting() {
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
@@ -171,11 +171,11 @@ public class DefaultHighlightVisitor implements HighlightVisitor, DumbAware {
TextRange range = element.getTextRange();
String errorDescription = element.getErrorDescription();
if (!range.isEmpty()) {
final HighlightInfo highlightInfo = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, range, errorDescription);
final HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, range, errorDescription);
for(ErrorQuickFixProvider provider: Extensions.getExtensions(ErrorQuickFixProvider.EP_NAME)) {
provider.registerErrorQuickFix(element, highlightInfo);
provider.registerErrorQuickFix(element, info);
}
return highlightInfo;
return info;
}
int offset = range.getStartOffset();
PsiFile containingFile = element.getContainingFile();
@@ -40,6 +40,7 @@ import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.ex.MarkupModelEx;
import com.intellij.openapi.editor.ex.RangeHighlighterEx;
import com.intellij.openapi.editor.impl.DocumentMarkupModel;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.TextAttributes;
@@ -72,6 +73,7 @@ import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.List;
@@ -593,16 +595,17 @@ public class GeneralHighlightingPass extends ProgressableTextEditorHighlightingP
final Runnable action = new Runnable() {
@Override
public void run() {
//noinspection unchecked
boolean failed = false;
//noinspection unchecked
for (List<PsiElement> elements : new List[]{elements1, elements2}) {
int nextLimit = chunkSize;
for (int i = 0; i < elements.size(); i++) {
PsiElement element = elements.get(i);
progress.checkCanceled();
PsiElement parent = element.getParent();
if (element != myFile && !skipParentsSet.isEmpty() && element.getFirstChild() != null && skipParentsSet.contains(element)) {
skipParentsSet.add(element.getParent());
skipParentsSet.add(parent);
continue;
}
@@ -637,6 +640,7 @@ public class GeneralHighlightingPass extends ProgressableTextEditorHighlightingP
nextLimit = i + chunkSize;
}
TextRange elementRange = element.getTextRange();
//noinspection ForLoopReplaceableByForEach
for (int j = 0; j < holder.size(); j++) {
final HighlightInfo info = holder.get(j);
@@ -646,12 +650,19 @@ public class GeneralHighlightingPass extends ProgressableTextEditorHighlightingP
boolean isError = info.getSeverity() == HighlightSeverity.ERROR;
if (isError) {
if (!forceHighlightParents) {
skipParentsSet.add(element.getParent());
skipParentsSet.add(parent);
}
myErrorFound = true;
}
// if this highlight info range is exactly the same as the element range we are visiting
// that means we can clear this highlight as soon as visitors won't produce any highlights during visiting the same range next time.
info.bijective = elementRange.equalsToRange(info.startOffset, info.endOffset);
myTransferToEDTQueue.offer(info);
}
if (parent == null || !Comparing.equal(elementRange, parent.getTextRange())) {
killAbandonedHighlightsUnder(elementRange, holder, progress);
}
}
advanceProgress(elements.size() - (nextLimit-chunkSize));
if (elements == elements1) after1.run();
@@ -662,6 +673,36 @@ public class GeneralHighlightingPass extends ProgressableTextEditorHighlightingP
analyzeByVisitors(progress, visitors, holder, 0, action);
}
private void killAbandonedHighlightsUnder(@NotNull final TextRange range,
@NotNull final HighlightInfoHolder holder,
@NotNull final ProgressIndicator progress) {
DaemonCodeAnalyzerImpl.processHighlights(getDocument(), myProject, null, range.getStartOffset(), range.getEndOffset(), new Processor<HighlightInfo>() {
@Override
public boolean process(final HighlightInfo existing) {
if (existing.bijective &&
existing.group == Pass.UPDATE_ALL &&
range.equalsToRange(existing.getActualStartOffset(), existing.getActualEndOffset())) {
for (int j = 0; j < holder.size(); j++) {
HighlightInfo created = holder.get(j);
if (existing.equalsByActualOffset(created)) return true;
}
// seems that highlight info "existing" is going to disappear
// remove it earlier
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
RangeHighlighterEx highlighter = existing.highlighter;
if (!progress.isCanceled() && highlighter != null) {
highlighter.dispose();
}
}
});
}
return true;
}
});
}
private void analyzeByVisitors(@NotNull final ProgressIndicator progress,
@NotNull final HighlightVisitor[] visitors,
@NotNull final HighlightInfoHolder holder,
@@ -650,7 +650,7 @@ public class UpdateHighlightersUtil {
info.highlighter.dispose();
}
}
assertMarkupConsistent(markup, project);
if (!toRemove.isEmpty()) {
@@ -25,6 +25,7 @@ import com.intellij.ide.dnd.*;
import com.intellij.ide.dnd.aware.DnDAwareTree;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SchemesManager;
@@ -184,16 +185,22 @@ public class TemplateListPanel extends JPanel implements Disposable {
reset();
}
private final boolean isTest = ApplicationManager.getApplication().isUnitTestMode();
public boolean isModified() {
TemplateSettings templateSettings = TemplateSettings.getInstance();
if (templateSettings.getDefaultShortcutChar() != getDefaultShortcutChar()) {
if (isTest) System.err.println("LiveTemplatesConfig: templateSettings.getDefaultShortcutChar()="+templateSettings.getDefaultShortcutChar()+"; getDefaultShortcutChar()="+getDefaultShortcutChar());
return true;
}
List<TemplateGroup> originalGroups = templateSettings.getTemplateGroups();
List<TemplateGroup> newGroups = getTemplateGroups();
return !checkAreEqual(collectTemplates(originalGroups), collectTemplates(newGroups));
if (checkAreEqual(collectTemplates(originalGroups), collectTemplates(newGroups))) return false;
if (isTest) {
System.err.println("LiveTemplatesConfig: originalGroups="+originalGroups+"; collectTemplates(originalGroups)="+collectTemplates(originalGroups)+";\n newGroups="+newGroups+"; collectTemplates(newGroups)="+collectTemplates(newGroups));
}
return true;
}
public void editTemplate(TemplateImpl template) {
@@ -45,7 +45,6 @@ import com.intellij.ui.treeStructure.filtered.FilteringTreeBuilder;
import com.intellij.util.PlatformIcons;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.update.MergingUpdateQueue;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -254,13 +253,13 @@ public class DisposerDebugger implements UiDebuggerExtension, Disposable {
return value.getValue().getModification() > myModificationToFilter;
}
public void objectRegistered(Object node) {
public void objectRegistered(@NotNull Object node) {
queueUpdate();
}
public void objectExecuted(Object node) {
public void objectExecuted(@NotNull Object node) {
queueUpdate();
}
@@ -354,7 +353,7 @@ public class DisposerDebugger implements UiDebuggerExtension, Disposable {
}
else {
final ObjectTree<Disposable> tree = Disposer.getTree();
final THashSet<Disposable> root = tree.getRootObjects();
final Set<Disposable> root = tree.getRootObjects();
ArrayList<DisposerNode> children = new ArrayList<DisposerNode>(root.size());
for (Disposable each : root) {
children.add(new DisposerNode(myTree, tree.getNode(each)));
@@ -20,6 +20,7 @@ import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.UsefulTestCase;
import com.intellij.testFramework.builders.EmptyModuleFixtureBuilder;
import com.intellij.testFramework.builders.ModuleFixtureBuilder;
@@ -82,7 +83,12 @@ public abstract class CodeInsightFixtureTestCase<T extends ModuleFixtureBuilder>
*/
@NonNls
protected final String getTestDataPath() {
return PathManager.getHomePath().replace(File.separatorChar, '/') + getBasePath();
String path = isCommunity() ? PlatformTestUtil.getCommunityPath() : PathManager.getHomePath();
return path.replace(File.separatorChar, '/') + getBasePath();
}
protected boolean isCommunity() {
return false;
}
protected Project getProject() {
@@ -43,12 +43,12 @@ public class Disposer {
private static final ObjectTreeAction<Disposable> ourDisposeAction = new ObjectTreeAction<Disposable>() {
@Override
public void execute(final Disposable each) {
public void execute(@NotNull final Disposable each) {
each.dispose();
}
@Override
public void beforeTreeExecution(final Disposable parent) {
public void beforeTreeExecution(@NotNull final Disposable parent) {
if (parent instanceof Disposable.Parent) {
((Disposable.Parent)parent).beforeTreeDispose();
}
@@ -157,6 +157,7 @@ public final class IconLoader {
@Nullable
public static Icon findIcon(final String path, final ClassLoader aClassLoader) {
if (path.startsWith("AllIcons.")) return getReflectiveIcon(path);
if (!path.startsWith("/")) return null;
final URL url = aClassLoader.getResource(path.substring(1));
@@ -19,6 +19,7 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.util.Disposer;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import java.util.Collection;
@@ -35,13 +36,13 @@ public final class ObjectNode<T> {
private ObjectNode<T> myParent;
private final T myObject;
private LinkedHashSet<ObjectNode<T>> myChildren;
LinkedHashSet<ObjectNode<T>> myChildren;
private final Throwable myTrace;
private final long myOwnModification;
private long myChildModification;
public ObjectNode(ObjectTree<T> tree, ObjectNode<T> parentNode, T object, long modification) {
public ObjectNode(@NotNull ObjectTree<T> tree, ObjectNode<T> parentNode, @NotNull T object, long modification) {
myTree = tree;
myParent = parentNode;
myObject = object;
@@ -50,6 +51,7 @@ public final class ObjectNode<T> {
myOwnModification = modification;
}
@NotNull
private ObjectNode<T>[] getChildrenArray() {
synchronized (myTree.treeLock) {
if (myChildren == null || myChildren.isEmpty()) return EMPTY_ARRAY;
@@ -57,7 +59,7 @@ public final class ObjectNode<T> {
}
}
public void addChild(ObjectNode<T> child) {
public void addChild(@NotNull ObjectNode<T> child) {
synchronized (myTree.treeLock) {
ensureChildArray();
child.setParent(this);
@@ -68,7 +70,7 @@ public final class ObjectNode<T> {
}
}
public void removeChild(ObjectNode<T> child) {
public void removeChild(@NotNull ObjectNode<T> child) {
synchronized (myTree.treeLock) {
assert myChildren != null: "No children to remove child: " + this + ' ' + child;
if (myChildren.remove(child)) {
@@ -80,15 +82,14 @@ public final class ObjectNode<T> {
}
private void setParent(ObjectNode<T> parent) {
synchronized (myTree.treeLock) {
myParent = parent;
}
myParent = parent;
}
public ObjectNode<T> getParent() {
return myParent;
}
@NotNull
public Collection<ObjectNode<T>> getChildren() {
synchronized (myTree.treeLock) {
if (myChildren == null) return Collections.emptyList();
@@ -102,9 +103,10 @@ public final class ObjectNode<T> {
}
}
boolean execute(final boolean disposeTree, final ObjectTreeAction<T> action) {
ObjectTree.executeActionWithRecursiveGuard(this, new ObjectTreeAction<ObjectNode<T>>() {
public void execute(ObjectNode<T> each) {
boolean execute(final boolean disposeTree, @NotNull final ObjectTreeAction<T> action) {
ObjectTree.executeActionWithRecursiveGuard(this, myTree.getNodesInExecution(), new ObjectTreeAction<ObjectNode<T>>() {
@Override
public void execute(@NotNull ObjectNode<T> each) {
action.beforeTreeExecution(myObject);
ObjectNode<T>[] childrenArray = getChildrenArray();
@@ -144,14 +146,16 @@ public final class ObjectNode<T> {
}
}
public void beforeTreeExecution(ObjectNode<T> parent) {
@Override
public void beforeTreeExecution(@NotNull ObjectNode<T> parent) {
}
}, myTree.getNodesInExecution());
});
return true;
}
@NotNull
public T getObject() {
return myObject;
}
@@ -166,7 +170,7 @@ public final class ObjectNode<T> {
}
@TestOnly
void assertNoReferencesKept(T aDisposable) {
void assertNoReferencesKept(@NotNull T aDisposable) {
assert getObject() != aDisposable;
if (myChildren != null) {
for (ObjectNode<T> node: myChildren) {
@@ -26,9 +26,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
public final class ObjectTree<T> {
@@ -62,7 +60,7 @@ public final class ObjectTree<T> {
return myExecutedNodes;
}
public final void register(T parent, T child) {
public final void register(@NotNull T parent, @NotNull T child) {
synchronized (treeLock) {
final ObjectNode<T> childNode = getOrCreateNodeFor(child);
checkValid(childNode, child);
@@ -83,7 +81,7 @@ public final class ObjectTree<T> {
}
}
private void checkValid(ObjectNode<T> childNode, T child) {
private void checkValid(ObjectNode<T> childNode, @NotNull T child) {
boolean childIsInTree = childNode != null && childNode.getParent() != null;
if (!childIsInTree) return;
@@ -96,6 +94,7 @@ public final class ObjectTree<T> {
}
}
@NotNull
private ObjectNode<T> getOrCreateNodeFor(@NotNull T parentObject) {
final ObjectNode<T> parentNode = getNode(parentObject);
@@ -127,7 +126,9 @@ public final class ObjectTree<T> {
}
}
static <T> void executeActionWithRecursiveGuard(@NotNull T object, @NotNull final ObjectTreeAction<T> action, List<T> recursiveGuard) {
static <T> void executeActionWithRecursiveGuard(@NotNull T object,
@NotNull List<T> recursiveGuard,
@NotNull final ObjectTreeAction<T> action) {
synchronized (recursiveGuard) {
if (ArrayUtil.indexOf(recursiveGuard, object, Equality.IDENTITY) != -1) return;
recursiveGuard.add(object);
@@ -146,7 +147,7 @@ public final class ObjectTree<T> {
}
private void executeUnregistered(@NotNull final T object, @NotNull final ObjectTreeAction<T> action) {
executeActionWithRecursiveGuard(object, action, myExecutedUnregisteredNodes);
executeActionWithRecursiveGuard(object, myExecutedUnregisteredNodes, action);
}
public final void executeChildAndReplace(@NotNull T toExecute, @NotNull T toReplace, boolean disposeTree, @NotNull ObjectTreeAction<T> action) {
@@ -169,7 +170,7 @@ public final class ObjectTree<T> {
}
@TestOnly
public void assertNoReferenceKeptInTree(T disposable) {
public void assertNoReferenceKeptInTree(@NotNull T disposable) {
Collection<ObjectNode<T>> nodes = myObject2NodeMap.values();
for (ObjectNode<T> node : nodes) {
node.assertNoReferencesKept(disposable);
@@ -229,25 +230,26 @@ public final class ObjectTree<T> {
myObject2NodeMap.clear();
}
public THashSet<T> getRootObjects() {
@NotNull
public Set<T> getRootObjects() {
return myRootObjects;
}
public void addListener(ObjectTreeListener listener) {
public void addListener(@NotNull ObjectTreeListener listener) {
myListeners.add(listener);
}
public void removeListener(ObjectTreeListener listener) {
public void removeListener(@NotNull ObjectTreeListener listener) {
myListeners.remove(listener);
}
void fireRegistered(Object object) {
void fireRegistered(@NotNull Object object) {
for (ObjectTreeListener each : myListeners) {
each.objectRegistered(object);
}
}
void fireExecuted(Object object) {
void fireExecuted(@NotNull Object object) {
for (ObjectTreeListener each : myListeners) {
each.objectExecuted(object);
}
@@ -262,10 +264,13 @@ public final class ObjectTree<T> {
synchronized (treeLock) {
ObjectNode<T> parentNode = getNode(parentDisposable);
if (parentNode == null) return null;
for (ObjectNode<T> node : parentNode.getChildren()) {
T nodeObject = node.getObject();
if (nodeObject.equals(object)) {
return (D)nodeObject;
LinkedHashSet<ObjectNode<T>> children = parentNode.myChildren;
if (children != null) {
for (ObjectNode<T> node : children) {
T nodeObject = node.getObject();
if (nodeObject.equals(object)) {
return (D)nodeObject;
}
}
}
return null;
@@ -15,10 +15,12 @@
*/
package com.intellij.openapi.util.objectTree;
import org.jetbrains.annotations.NotNull;
public interface ObjectTreeAction<T> {
void execute(T each);
void execute(@NotNull T each);
void beforeTreeExecution(T parent);
void beforeTreeExecution(@NotNull T parent);
}
@@ -15,9 +15,11 @@
*/
package com.intellij.openapi.util.objectTree;
import org.jetbrains.annotations.NotNull;
public interface ObjectTreeListener {
void objectRegistered(Object node);
void objectExecuted(Object node);
void objectRegistered(@NotNull Object node);
void objectExecuted(@NotNull Object node);
}
@@ -36,8 +36,10 @@ import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferen
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.usageView.UsageInfo;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ProcessingContext;
import com.intellij.util.Processor;
import com.intellij.util.QueryExecutor;
@@ -120,6 +122,45 @@ public class IconsReferencesContributor extends PsiReferenceContributor implemen
return null;
}
@Override
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
PsiElement element = resolve();
if (element instanceof PsiFile) {
FileReference lastRef = new FileReferenceSet(element).getLastReference();
return lastRef.handleElementRename(newElementName);
}
else if (element instanceof PsiField) {
String fqn = ((PsiField)element).getContainingClass().getQualifiedName();
if (fqn.startsWith("com.intellij.icons.")) {
XmlAttribute parent = (XmlAttribute)getElement().getParent();
parent.setValue(fqn.substring("com.intellij.icons.".length()) + "." + newElementName);
return parent.getValueElement();
}
}
return super.handleElementRename(newElementName);
}
@Override
public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
if (element instanceof PsiFile) {
FileReference lastRef = new FileReferenceSet(element).getLastReference();
return lastRef.bindToElement(element);
}
else if (element instanceof PsiField) {
String fqn = ((PsiField)element).getContainingClass().getQualifiedName();
if (fqn.startsWith("com.intellij.icons.")) {
XmlAttribute parent = (XmlAttribute)getElement().getParent();
parent.setValue(fqn.substring("com.intellij.icons.".length()) + "." + ((PsiField)element).getName());
return parent.getValueElement();
}
}
return super.bindToElement(element);
}
@NotNull
@Override
public Object[] getVariants() {
@@ -18,6 +18,7 @@ package git4idea.history.browser;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationListener;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
@@ -496,10 +497,9 @@ public class GitCherryPicker {
public void execute(Collection<Change> changes, String commitMessage) {
final Collection<Document> committingDocs = markCommittingDocs();
try {
CheckinEnvironment ce = myPlatformFacade.getVcs(myProject).getCheckinEnvironment();
LOG.assertTrue(ce != null && ce instanceof GitCheckinEnvironment, "Invalid CheckinEnvironment: " + ce);
GitCheckinEnvironment ce = ServiceManager.getService(myProject, GitCheckinEnvironment.class);
try {
((GitCheckinEnvironment)ce).reset();
ce.reset();
List<VcsException> exceptions = ce.commit(myChanges, myCommitMessage);
VcsDirtyScopeManager.getInstance(myProject).filePathsDirty(ChangesUtil.getPaths(myChanges), null);
if (exceptions != null && !exceptions.isEmpty()) {
@@ -17,6 +17,7 @@
package com.intellij.uiDesigner.propertyInspector;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
@@ -231,7 +232,12 @@ public class UIDesignerToolWindowManager implements ProjectComponent {
}
public void fileClosed(FileEditorManager source, VirtualFile file) {
processFileEditorChange(getActiveFormFileEditor());
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
processFileEditorChange(getActiveFormFileEditor());
}
});
}
public void selectionChanged(FileEditorManagerEvent event) {
@@ -22,6 +22,7 @@ import com.intellij.designer.propertyTable.PropertyTablePanel;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
@@ -77,7 +78,12 @@ public final class DesignerToolWindowManager implements ProjectComponent {
@Override
public void fileClosed(FileEditorManager source, VirtualFile file) {
bindToDesigner(getActiveDesigner());
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
bindToDesigner(getActiveDesigner());
}
});
}
@Override
@@ -227,6 +227,9 @@ public abstract class DesignerEditorPanel extends JPanel implements DataProvider
if (getActiveTool() instanceof CreationTool && !(tool instanceof CreationTool)) {
PaletteManager.getInstance(getProject()).clearActiveItem();
}
if (!(tool instanceof SelectionTool)) {
hideInspections();
}
super.setActiveTool(tool);
}
@@ -255,6 +258,11 @@ public abstract class DesignerEditorPanel extends JPanel implements DataProvider
myInplaceEditingLayer.startEditing(inplaceContext);
}
@Override
public void hideInspections() {
myQuickFixManager.hideHint();
}
@Override
public void showError(@NonNls String message, Throwable e) {
DesignerEditorPanel.this.showError(message, e);
@@ -116,6 +116,7 @@ public class SelectionTool extends InputTool {
refreshCursor();
if (myTracker != null) {
myToolProvider.hideInspections();
myTracker.setToolProvider(myToolProvider);
myTracker.setArea(myArea);
myTracker.activate();
@@ -136,4 +136,6 @@ public abstract class ToolProvider {
public abstract void execute(List<EditOperation> operations, String command);
public abstract void startInplaceEditing(@Nullable InplaceContext inplaceContext);
public abstract void hideInspections();
}
@@ -0,0 +1,27 @@
package com.intellij.codeInsight;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.xml.XmlTag;
import com.intellij.testFramework.LightIdeaTestCase;
import com.intellij.util.IncorrectOperationException;
import com.intellij.xml.util.XmlUtil;
/**
* author: lesya
*/
public class SearchingInXmlTest extends LightIdeaTestCase {
public void test() throws IncorrectOperationException {
XmlTag xmlTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<root>" +
"<tag1><name>name1</name><value>1</value></tag1>" +
"<tag1><name>name2</name><value>2</value></tag1>" +
"<tag1><name>name3</name><value>3</value></tag1>" +
"<tag1><name>name4</name><value>4</value></tag1>" +
"<tag1><name>name5</name><value>5</value></tag1>" +
"<tag1><name>name6</name><value>6</value></tag1>" +
"<tag1><name>name7</name><value>7</value></tag1>" +
"</root>");
XmlTag found = XmlUtil.find("name", "name4", "tag1", xmlTag);
assertEquals("4", found.findFirstSubTag("value").getValue().getText());
}
}
@@ -0,0 +1,257 @@
/*
* @author max
*/
package com.intellij.codeInsight;
import com.intellij.psi.impl.source.parsing.xml.XmlBuilder;
import com.intellij.psi.impl.source.parsing.xml.XmlBuilderDriver;
import com.intellij.testFramework.LightCodeInsightTestCase;
import org.jetbrains.annotations.Nullable;
public class XmlBuilderTest extends LightCodeInsightTestCase {
private static class TestXmlBuilder implements XmlBuilder {
private final StringBuilder builder = new StringBuilder();
private final StringBuilder currentPhysicalText = new StringBuilder();
private final StringBuilder currentDisplayText = new StringBuilder();
private final ProcessingOrder myTagProcessingOrder;
public TestXmlBuilder(final ProcessingOrder tagsAndAttributes) {
myTagProcessingOrder = tagsAndAttributes;
}
@Override
public void attribute(final CharSequence name, final CharSequence value, final int startoffset, final int endoffset) {
flushText();
builder.append("ATT: name='").append(name).append("' value='").append(value).append("'\n");
}
@Override
public void endTag(final CharSequence localName, final String namespace, final int startoffset, final int endoffset) {
flushText();
builder.append("ENDTAG: name='").append(localName).append("' namespace='").append(namespace).append("'\n");
}
@Override
public void doctype(@Nullable final CharSequence publicId, @Nullable final CharSequence systemId, final int startOffset, final int endOffset) {
}
@Override
public ProcessingOrder startTag(final CharSequence localName, final String namespace, final int startoffset, final int endoffset,
final int headerEndOffset) {
flushText();
builder.append("TAG: name='").append(localName).append("' namespace='").append(namespace).append("'\n");
return myTagProcessingOrder;
}
@Override
public void textElement(final CharSequence display, final CharSequence physical, final int startoffset, final int endoffset) {
currentPhysicalText.append(physical);
currentDisplayText.append(display);
}
@Override
public void entityRef(final CharSequence ref, final int startOffset, final int endOffset) {
flushText();
builder.append("REF: '").append(ref).append("'\n");
}
@Override
public void error(String message, int startOffset, int endOffset) {
flushText();
builder.append("ERROR: '").append(message).append("'\n");
}
private void flushText() {
if (currentPhysicalText.length() > 0) {
builder.append("TEXT: '").append(currentPhysicalText).append("' DISPLAY: '").append(currentDisplayText).append("'\n");
currentPhysicalText.setLength(0);
currentDisplayText.setLength(0);
}
}
public String getResult() {
flushText();
return builder.toString();
}
}
public void testEmptyXml() throws Exception {
doTest("<root/>", "TAG: name='root' namespace=''\n" +
"ENDTAG: name='root' namespace=''\n", XmlBuilder.ProcessingOrder.TAGS_AND_ATTRIBUTES);
}
public void testRealJspx() throws Exception {
doTest(
/* Test: */
"<jsp:root xmlns:jsp=\"http://java.sun.com/JSP/Page\" xmlns=\"http://www.w3.org/1999/xhtml\" version=\"2.0\"\n" +
" xmlns:spring=\"http://www.springframework.org/tags\" xmlns:c=\"http://java.sun.com/jsp/jstl/core\">\n" +
"<html>\n" +
" <c:set var=\"foo\" value=\"${1}\"/>\n" +
" <c:set var=\"foobar\" value=\"${2}\"/>\n" +
" <spring:bind path=\"test.fieldName\">\n" +
" <jsp:scriptlet></jsp:scriptlet>\n" +
" </spring:bind>\n" +
"</html>\n" +
"</jsp:root>",
/* Expected result: */
"TAG: name='root' namespace='http://java.sun.com/JSP/Page'\n" +
"ATT: name='xmlns:jsp' value='http://java.sun.com/JSP/Page'\n" +
"ATT: name='xmlns' value='http://www.w3.org/1999/xhtml'\n" +
"ATT: name='version' value='2.0'\n" +
"ATT: name='xmlns:spring' value='http://www.springframework.org/tags'\n" +
"ATT: name='xmlns:c' value='http://java.sun.com/jsp/jstl/core'\n" +
"TAG: name='html' namespace='http://www.w3.org/1999/xhtml'\n" +
"TAG: name='set' namespace='http://java.sun.com/jsp/jstl/core'\n" +
"ATT: name='var' value='foo'\n" +
"ATT: name='value' value='${1}'\n" +
"ENDTAG: name='set' namespace='http://java.sun.com/jsp/jstl/core'\n" +
"TAG: name='set' namespace='http://java.sun.com/jsp/jstl/core'\n" +
"ATT: name='var' value='foobar'\n" +
"ATT: name='value' value='${2}'\n" +
"ENDTAG: name='set' namespace='http://java.sun.com/jsp/jstl/core'\n" +
"TAG: name='bind' namespace='http://www.springframework.org/tags'\n" +
"ATT: name='path' value='test.fieldName'\n" +
"TAG: name='scriptlet' namespace='http://java.sun.com/JSP/Page'\n" +
"ENDTAG: name='scriptlet' namespace='http://java.sun.com/JSP/Page'\n" +
"ENDTAG: name='bind' namespace='http://www.springframework.org/tags'\n" +
"ENDTAG: name='html' namespace='http://www.w3.org/1999/xhtml'\n" +
"ENDTAG: name='root' namespace='http://java.sun.com/JSP/Page'\n",
XmlBuilder.ProcessingOrder.TAGS_AND_ATTRIBUTES);
}
public void testRealJspxNoAttributes() throws Exception {
doTest(
/* Test: */
"<jsp:root xmlns:jsp=\"http://java.sun.com/JSP/Page\" xmlns=\"http://www.w3.org/1999/xhtml\" version=\"2.0\"\n" +
" xmlns:spring=\"http://www.springframework.org/tags\" xmlns:c=\"http://java.sun.com/jsp/jstl/core\">\n" +
"<html>\n" +
" <c:set var=\"foo\" value=\"${1}\"/>\n" +
" <c:set var=\"foobar\" value=\"${2}\"/>\n" +
" <spring:bind path=\"test.fieldName\">\n" +
" <jsp:scriptlet></jsp:scriptlet>\n" +
" </spring:bind>\n" +
"</html>\n" +
"</jsp:root>",
/* Expected result: */
"TAG: name='root' namespace='http://java.sun.com/JSP/Page'\n" +
"TAG: name='html' namespace='http://www.w3.org/1999/xhtml'\n" +
"TAG: name='set' namespace='http://java.sun.com/jsp/jstl/core'\n" +
"ENDTAG: name='set' namespace='http://java.sun.com/jsp/jstl/core'\n" +
"TAG: name='set' namespace='http://java.sun.com/jsp/jstl/core'\n" +
"ENDTAG: name='set' namespace='http://java.sun.com/jsp/jstl/core'\n" +
"TAG: name='bind' namespace='http://www.springframework.org/tags'\n" +
"TAG: name='scriptlet' namespace='http://java.sun.com/JSP/Page'\n" +
"ENDTAG: name='scriptlet' namespace='http://java.sun.com/JSP/Page'\n" +
"ENDTAG: name='bind' namespace='http://www.springframework.org/tags'\n" +
"ENDTAG: name='html' namespace='http://www.w3.org/1999/xhtml'\n" +
"ENDTAG: name='root' namespace='http://java.sun.com/JSP/Page'\n",
XmlBuilder.ProcessingOrder.TAGS);
}
public void testNamespaceOverride() throws Exception {
doTest(
"<c:x xmlns:c=\"ns1\">\n" +
" <c:y/>\n" +
" <c:x xmlns:c=\"ns2\">\n" +
" <c:y/>\n" +
" </c:x>\n" +
" <c:y/>\n" +
"</c:x>\n",
"TAG: name='x' namespace='ns1'\n" +
"ATT: name='xmlns:c' value='ns1'\n" +
"TAG: name='y' namespace='ns1'\n" +
"ENDTAG: name='y' namespace='ns1'\n" +
"TAG: name='x' namespace='ns2'\n" +
"ATT: name='xmlns:c' value='ns2'\n" +
"TAG: name='y' namespace='ns2'\n" +
"ENDTAG: name='y' namespace='ns2'\n" +
"ENDTAG: name='x' namespace='ns2'\n" +
"TAG: name='y' namespace='ns1'\n" +
"ENDTAG: name='y' namespace='ns1'\n" +
"ENDTAG: name='x' namespace='ns1'\n",
XmlBuilder.ProcessingOrder.TAGS_AND_ATTRIBUTES);
}
public void testSimpleEntityResolution() throws Exception {
doTest(
"<root>&lt;</root>",
"TAG: name='root' namespace=''\n" +
"TEXT: '&lt;' DISPLAY: '<'\n" +
"ENDTAG: name='root' namespace=''\n",
XmlBuilder.ProcessingOrder.TAGS_AND_TEXTS);
}
public void testCDATA() throws Exception {
doTest(
"<root><![CDATA[<asis/>]]></root>",
"TAG: name='root' namespace=''\n" +
"TEXT: '<![CDATA[<asis/>]]>' DISPLAY: '<asis/>'\n" +
"ENDTAG: name='root' namespace=''\n",
XmlBuilder.ProcessingOrder.TAGS_AND_TEXTS
);
}
public void testErrors() throws Exception {
doTest(
"<root>" +
"<foo>" +
"<bar" +
"<" +
"</root>",
"TAG: name='root' namespace=''\n" +
"TAG: name='foo' namespace=''\n" +
"ERROR: 'Element foo is not closed'\n" +
"ENDTAG: name='foo' namespace=''\n" +
"TAG: name='bar' namespace=''\n" +
"ERROR: 'Tag start is not closed'\n" +
"ENDTAG: name='bar' namespace=''\n" +
"TAG: name='' namespace=''\n" +
"ERROR: 'Tag name expected'\n" +
"ENDTAG: name='' namespace=''\n" +
"ENDTAG: name='root' namespace=''\n",
XmlBuilder.ProcessingOrder.TAGS_AND_TEXTS
);
}
public void testComments() throws Exception {
doTest(
"<root>" +
"<foo>" +
"<!--aa-->" +
"</foo>" +
"<foo>" +
"<!---->" +
"</foo>" +
"<foo>" +
"aaa<!--aa-->aaa" +
"</foo>" +
"<foo>" +
"\naaa\n<!--aa-->\naaa\n" +
"</foo>" +
"</root>",
"TAG: name='root' namespace=''\n" +
"TAG: name='foo' namespace=''\n" +
"ENDTAG: name='foo' namespace=''\n" +
"TAG: name='foo' namespace=''\n" +
"ENDTAG: name='foo' namespace=''\n" +
"TAG: name='foo' namespace=''\n" +
"TEXT: 'aaaaaa' DISPLAY: 'aaaaaa'\n" +
"ENDTAG: name='foo' namespace=''\n" +
"TAG: name='foo' namespace=''\n" +
"TEXT: '\naaa\n\naaa\n' DISPLAY: '\naaa\n\naaa\n'\n" +
"ENDTAG: name='foo' namespace=''\n" +
"ENDTAG: name='root' namespace=''\n",
XmlBuilder.ProcessingOrder.TAGS_AND_TEXTS
);
}
private static void doTest(String xml, String expectedEventSequence, final XmlBuilder.ProcessingOrder tagsAndAttributes) throws Exception {
final TestXmlBuilder builder = new TestXmlBuilder(tagsAndAttributes);
new XmlBuilderDriver(xml).build(builder);
assertEquals(expectedEventSequence, builder.getResult());
}
}
@@ -0,0 +1,320 @@
package com.intellij.codeInsight;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.testFramework.PsiTestCase;
import com.intellij.xml.XmlAttributeDescriptor;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlNSDescriptor;
import com.intellij.xml.impl.dtd.XmlElementDescriptorImpl;
import com.intellij.xml.impl.dtd.XmlNSDescriptorImpl;
/**
* @author Mike
*/
public class XmlDtdTest extends PsiTestCase {
public void testDocumentDescriptor1() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor("<!ELEMENT principals (#PCDATA)><!ELEMENT data-sources (#PCDATA)>");
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag("principals"));
assertNotNull(elementDescriptor);
elementDescriptor = NSDescriptor.getElementDescriptor(tag("data-sources"));
assertNotNull(elementDescriptor);
elementDescriptor = NSDescriptor.getElementDescriptor(tag("xxx"));
assertNull(elementDescriptor);
}
public void testElementDescriptor1() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor("<!ELEMENT principals (#PCDATA)><!ELEMENT data-sources (#PCDATA)>");
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag("principals"));
assertEquals("principals", elementDescriptor.getName());
elementDescriptor = NSDescriptor.getElementDescriptor(tag("data-sources"));
assertEquals("data-sources", elementDescriptor.getName());
}
public void testElementDescriptor2() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<!ELEMENT principals (#PCDATA)><!ELEMENT data-sources ANY>" +
"<!ELEMENT read-access (namespace-resource)><!ELEMENT group EMPTY>");
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag("principals"));
assertEquals(elementDescriptor.getContentType(), XmlElementDescriptor.CONTENT_TYPE_MIXED);
elementDescriptor = NSDescriptor.getElementDescriptor(tag("data-sources"));
assertEquals(elementDescriptor.getContentType(), XmlElementDescriptor.CONTENT_TYPE_ANY);
elementDescriptor = NSDescriptor.getElementDescriptor(tag("read-access"));
assertEquals(elementDescriptor.getContentType(), XmlElementDescriptor.CONTENT_TYPE_CHILDREN);
elementDescriptor = NSDescriptor.getElementDescriptor(tag("group"));
assertEquals(elementDescriptor.getContentType(), XmlElementDescriptor.CONTENT_TYPE_EMPTY);
}
public void testElementDescriptor3() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<!ELEMENT principals ANY><!ATTLIST principals path CDATA #IMPLIED smtp-host CDATA #REQUIRED>" +
"<!ATTLIST principals address CDATA #IMPLIED>");
final XmlTag tag = tag("principals");
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor attributeDescriptor = elementDescriptor.getAttributeDescriptor("path", tag);
assertNotNull(attributeDescriptor);
attributeDescriptor = elementDescriptor.getAttributeDescriptor("xxx", tag);
assertNull(attributeDescriptor);
attributeDescriptor = elementDescriptor.getAttributeDescriptor("smtp-host", tag);
assertNotNull(attributeDescriptor);
attributeDescriptor = elementDescriptor.getAttributeDescriptor("address", tag);
assertNotNull(attributeDescriptor);
XmlAttributeDescriptor[] descriptors = elementDescriptor.getAttributesDescriptors(tag);
assertEquals("path", descriptors[0].getName());
assertEquals("smtp-host", descriptors[1].getName());
assertEquals("address", descriptors[2].getName());
assertEquals(3, descriptors.length);
}
public void testElementDescriptor4() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<!ELEMENT orion-application (ejb-module*, persistence?, namespace-access)>" +
"<!ELEMENT ejb-module ANY>" +
"<!ELEMENT persistence ANY>" +
"<!ELEMENT namespace-access ANY>");
XmlTag documentTag = tag("orion-application");
XmlElementDescriptorImpl elementDescriptor = (XmlElementDescriptorImpl)NSDescriptor.getElementDescriptor(documentTag);
XmlElementDescriptor[] elements = elementDescriptor.getElementsDescriptors(documentTag);
assertEquals(3, elements.length);
assertEquals("ejb-module", elements[0].getName());
assertEquals("persistence", elements[1].getName());
assertEquals("namespace-access", elements[2].getName());
elements = elements[0].getElementsDescriptors(documentTag);
assertEquals(4, elements.length);
assertEquals("orion-application", elements[0].getName());
assertEquals("ejb-module", elements[1].getName());
assertEquals("persistence", elements[2].getName());
assertEquals("namespace-access", elements[3].getName());
}
public void testAttributeDescriptor1() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<!ELEMENT principals ANY><!ATTLIST principals path CDATA #IMPLIED>");
final XmlTag tag = tag("principals");
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor attributeDescriptor = elementDescriptor.getAttributeDescriptor("path", tag);
assertEquals("path", attributeDescriptor.getName());
assertTrue(!attributeDescriptor.isRequired());
assertTrue(!attributeDescriptor.isFixed());
assertTrue(!attributeDescriptor.isEnumerated());
assertNull(attributeDescriptor.getDefaultValue());
}
public void testAttributeDescriptor2() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<!ELEMENT principals ANY><!ATTLIST principals path CDATA #IMPLIED>");
final XmlTag tag = tag("principals");
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor attributeDescriptor = elementDescriptor.getAttributeDescriptor("path", tag);
assertTrue(!attributeDescriptor.isRequired());
assertTrue(!attributeDescriptor.isFixed());
assertTrue(!attributeDescriptor.isEnumerated());
assertNull(attributeDescriptor.getDefaultValue());
}
public void testAttributeDescriptor3() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<!ELEMENT toc ANY> <!ATTLIST toc version CDATA #FIXED \"1.0\">");
final XmlTag tag = tag("toc");
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor attributeDescriptor = elementDescriptor.getAttributeDescriptor("version", tag);
assertTrue(!attributeDescriptor.isRequired());
assertTrue(attributeDescriptor.isFixed());
assertTrue(!attributeDescriptor.isEnumerated());
assertEquals("1.0", attributeDescriptor.getDefaultValue());
}
public void testAttributeDescriptor4() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<!ELEMENT toc ANY> <!ATTLIST toc remote (true|false) \"false\">");
final XmlTag tag = tag("toc");
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor attributeDescriptor = elementDescriptor.getAttributeDescriptor("remote", tag);
assertTrue(!attributeDescriptor.isRequired());
assertTrue(!attributeDescriptor.isFixed());
assertTrue(attributeDescriptor.isEnumerated());
assertEquals("false", attributeDescriptor.getDefaultValue());
String[] values = attributeDescriptor.getEnumeratedValues();
assertEquals(2, values.length);
assertEquals("true", values[0]);
assertEquals("false", values[1]);
}
public void testAttributeDescriptor5() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<!ELEMENT toc ANY> <!ATTLIST toc remote (0|1|2) #REQUIRED>");
final XmlTag tag = tag("toc");
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor attributeDescriptor = elementDescriptor.getAttributeDescriptor("remote", tag);
assertTrue(attributeDescriptor.isRequired());
assertTrue(!attributeDescriptor.isFixed());
assertTrue(attributeDescriptor.isEnumerated());
assertNull(attributeDescriptor.getDefaultValue());
String[] values = attributeDescriptor.getEnumeratedValues();
assertEquals(3, values.length);
assertEquals("0", values[0]);
assertEquals("1", values[1]);
assertEquals("2", values[2]);
}
public void testEntityDeclElement1() throws Exception {
final XmlNSDescriptor NSDescriptor = createDescriptor(
"<!ENTITY % types \"fileset | patternset \"> <!ELEMENT project (target | taskdef | %types; | property )*> " +
"<!ELEMENT target><!ELEMENT taskdef><!ELEMENT fileset><!ELEMENT patternset><!ELEMENT property>");
XmlTag projectTag = tag("project");
final XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(projectTag);
final XmlElementDescriptor[] elements = elementDescriptor.getElementsDescriptors(projectTag);
assertEquals(5, elements.length);
}
public void testEntityDecl1() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<!ENTITY % boolean \"(true|false|on|off|yes|no)\"> <!ELEMENT toc ANY> <!ATTLIST toc remote %boolean; \"false\"");
final XmlTag tag = tag("toc");
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor attributeDescriptor = elementDescriptor.getAttributeDescriptor("remote", tag);
assertTrue(!attributeDescriptor.isRequired());
assertTrue(!attributeDescriptor.isFixed());
assertTrue(attributeDescriptor.isEnumerated());
assertEquals("false", (attributeDescriptor.getDefaultValue()));
String[] values = attributeDescriptor.getEnumeratedValues();
assertEquals(6, values.length);
assertEquals("true", values[0]);
assertEquals("false", values[1]);
assertEquals("on", values[2]);
assertEquals("off", values[3]);
assertEquals("yes", values[4]);
assertEquals("no", values[5]);
}
public void testEntityDecl2() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<!ENTITY % coreattrs \"id D #IMPLIED\"> <!ELEMENT a ANY> <!ATTLIST a %coreattrs; version CDATA #FIXED \"1.0\"");
final XmlTag tag = tag("a");
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
final XmlAttributeDescriptor[] attributes = elementDescriptor.getAttributesDescriptors(tag);
assertEquals(2, attributes.length);
assertEquals("id", attributes[0].getName());
assertEquals("version", attributes[1].getName());
}
public void testEntityDecl3() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<!ENTITY % att1 \"id1 D #IMPLIED\"> <!ENTITY % att2 \"id2 D #IMPLIED\"> <!ELEMENT a ANY> <!ATTLIST a %att1; %att2; ");
final XmlTag tag = tag("a");
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
final XmlAttributeDescriptor[] attributes = elementDescriptor.getAttributesDescriptors(tag);
assertEquals(2, attributes.length);
assertEquals("id1", attributes[0].getName());
assertEquals("id2", attributes[1].getName());
}
public void testEntityDecl4() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<!ENTITY % boolean \'(true|false|on|off|yes|no)\'> <!ENTITY % bool \"%boolean;\"> <!ELEMENT toc ANY> <!ATTLIST toc remote %bool; \"false\"");
final XmlTag tag = tag("toc");
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor attributeDescriptor = elementDescriptor.getAttributeDescriptor("remote", tag);
assertTrue(!attributeDescriptor.isRequired());
assertTrue(!attributeDescriptor.isFixed());
assertTrue(attributeDescriptor.isEnumerated());
assertEquals("false", attributeDescriptor.getDefaultValue());
String[] values = attributeDescriptor.getEnumeratedValues();
assertEquals(6, values.length);
assertEquals("true", values[0]);
assertEquals("false", values[1]);
assertEquals("on", values[2]);
assertEquals("off", values[3]);
assertEquals("yes", values[4]);
assertEquals("no", values[5]);
}
public void testEntityDecl5() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<!ENTITY % boolean \"true | false\" > <!ELEMENT foo EMPTY> <!ATTLIST foo someBoolean (%boolean;) \"true\" someString CDATA #IMPLIED >");
final XmlTag tag = tag("foo");
final XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
final XmlAttributeDescriptor[] attributes = elementDescriptor.getAttributesDescriptors(tag);
assertEquals(2, attributes.length);
assertEquals("someBoolean", attributes[0].getName());
assertEquals("someString", attributes[1].getName());
assertTrue(attributes[0].isEnumerated());
assertEquals(2, attributes[0].getEnumeratedValues().length);
assertEquals("true", attributes[0].getEnumeratedValues()[0]);
assertEquals("false", attributes[0].getEnumeratedValues()[1]);
}
public void testEmbeddedDtd1() throws Exception {
XmlFile xmlFile = (XmlFile)createDummyFile("test.xml",
"<!DOCTYPE tv [ <!ELEMENT tv (date)*> <!ELEMENT date (#PCDATA)> ]> <tv></tv>");
final XmlTag tag = xmlFile.getDocument().getRootTag();
assertNotNull(tag);
final XmlElementDescriptor desc = xmlFile.getDocument().getRootTagNSDescriptor().getElementDescriptor(tag);
assertNotNull(desc);
final XmlElementDescriptor[] elements = desc.getElementsDescriptors(tag);
assertEquals(1, elements.length);
assertEquals("date", elements[0].getName());
}
private XmlNSDescriptor createDescriptor(String dtdText) throws Exception {
PsiFile dtdFile = createDummyFile("test.dtd", dtdText);
return new XmlNSDescriptorImpl((XmlFile)dtdFile);
}
private XmlTag tag(String tagName) throws Exception {
XmlFile file = (XmlFile)PsiFileFactory.getInstance(myPsiManager.getProject()).createFileFromText("tag.xml", "<" + tagName + "/>");
return file.getDocument().getRootTag();
}
}
@@ -0,0 +1,238 @@
package com.intellij.codeInsight;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.pom.PomManager;
import com.intellij.pom.PomModel;
import com.intellij.pom.PomModelAspect;
import com.intellij.pom.event.PomChangeSet;
import com.intellij.pom.event.PomModelEvent;
import com.intellij.pom.event.PomModelListener;
import com.intellij.pom.xml.XmlAspect;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlText;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import java.io.File;
import java.io.FileNotFoundException;
public class XmlEventsTest extends LightCodeInsightTestCase {
public void test1() throws Exception{
final PomModel model = PomManager.getModel(getProject());
final Listener listener = new Listener(model.getModelAspect(XmlAspect.class));
model.addModelListener(listener);
final XmlTag tagFromText = XmlElementFactory.getInstance(getProject()).createTagFromText("<a/>");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
tagFromText.setAttribute("a", "b");
}
});
assertFileTextEquals(getTestName(false) + ".txt", listener.getEventString());
}
public void test2() throws Exception{
final PomModel model = PomManager.getModel(getProject());
final Listener listener = new Listener(model.getModelAspect(XmlAspect.class));
model.addModelListener(listener);
final XmlTag tagFromText = XmlElementFactory.getInstance(getProject()).createTagFromText("<a>aaa</a>");
final XmlTag otherTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<a/>");
final XmlText xmlText = tagFromText.getValue().getTextElements()[0];
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
xmlText.insertAtOffset(otherTag, 2);
}
});
assertFileTextEquals(getTestName(false) + ".txt", listener.getEventString());
}
public void test3() throws Exception{
final PomModel model = PomManager.getModel(getProject());
final Listener listener = new Listener(model.getModelAspect(XmlAspect.class));
model.addModelListener(listener);
final XmlTag tagFromText = XmlElementFactory.getInstance(getProject()).createTagFromText("<a>aaa</a>");
final XmlText xmlText = tagFromText.getValue().getTextElements()[0];
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
xmlText.insertText("bb", 2);
}
});
assertFileTextEquals(getTestName(false) + ".txt", listener.getEventString());
}
public void test4() throws Exception{
final PomModel model = PomManager.getModel(getProject());
final Listener listener = new Listener(model.getModelAspect(XmlAspect.class));
model.addModelListener(listener);
final XmlTag tagFromText = XmlElementFactory.getInstance(getProject()).createTagFromText("<a>a </a>");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
tagFromText.addAfter(tagFromText.getValue().getTextElements()[0], tagFromText.getValue().getTextElements()[0]);
}
});
assertFileTextEquals(getTestName(false) + ".txt", listener.getEventString());
}
public void test5() throws Exception{
final PomModel model = PomManager.getModel(getProject());
final Listener listener = new Listener(model.getModelAspect(XmlAspect.class));
model.addModelListener(listener);
final XmlTag tagFromText = XmlElementFactory.getInstance(getProject()).createTagFromText("<a>aaa</a>");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
tagFromText.delete();
}
});
assertFileTextEquals(getTestName(false) + ".txt", listener.getEventString());
}
public void testBulkUpdate() throws Exception{
final PomModel model = PomManager.getModel(getProject());
final Listener listener = new Listener(model.getModelAspect(XmlAspect.class));
model.addModelListener(listener);
final PsiFile file = createFile("a.xml", "<a/>");
new WriteCommandAction(getProject()) {
@Override
protected void run(Result result) throws Throwable {
final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(file);
((DocumentEx)document).setInBulkUpdate(true);
document.insertString(0, " ");
commitDocument(document);
((DocumentEx)document).setInBulkUpdate(false);
}
}.execute();
assertFileTextEquals(getTestName(false) + ".txt", listener.getEventString());
}
public void testDocumentChange1() throws Exception{
final String rootTagText = "<a/>";
final String stringToInsert = "b=\"c\"";
final int positionToInsert = 2;
checkEventsByDocumentChange(rootTagText, positionToInsert, stringToInsert);
}
public void testDocumentChange2() throws Exception{
final String rootTagText = "<a />";
final String stringToInsert = "b=\"c\"";
final int positionToInsert = 3;
checkEventsByDocumentChange(rootTagText, positionToInsert, stringToInsert);
}
public void testDocumentChange3() throws Exception{
final String rootTagText = "<b><a /></b>";
final String stringToInsert = "b=\"c\"";
final int positionToInsert = 6;
checkEventsByDocumentChange(rootTagText, positionToInsert, stringToInsert);
}
public void testAttributeValueReplace() throws Exception {
final String text = "<target name=\"old\"/>";
final PomModel model = PomManager.getModel(getProject());
final Listener listener = new Listener(model.getModelAspect(XmlAspect.class));
model.addModelListener(listener);
final XmlTag tag = XmlElementFactory.getInstance(getProject()).createTagFromText(text);
final XmlAttribute attribute = tag.getAttribute("name", null);
assert attribute != null;
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
attribute.setValue("new");
}
});
assertEquals(attribute.getValue(), "new");
assertEquals("(Attribute \"name\" for tag \"target\" set to \"\"new\"\")\n", listener.getEventString());
}
private void checkEventsByDocumentChange(final String rootTagText, final int positionToInsert, final String stringToInsert)
throws Exception {
final PomModel model = PomManager.getModel(getProject());
final Listener listener = new Listener(model.getModelAspect(XmlAspect.class));
model.addModelListener(listener);
final XmlTag tagFromText = ((XmlFile)createFile("file.xml", rootTagText)).getDocument().getRootTag();
final PsiFileImpl containingFile = (PsiFileImpl)tagFromText.getContainingFile();
final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
final Document document = documentManager.getDocument(containingFile);
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
document.insertString(positionToInsert, stringToInsert);
documentManager.commitDocument(document);
}
});
}
}, "", null);
assertFileTextEquals(getTestName(false) + ".txt", listener.getEventString());
}
private static class Listener implements PomModelListener{
private final XmlAspect myAspect;
private final StringBuffer myBuffer = new StringBuffer();
public Listener(XmlAspect modelAspect) {
myAspect = modelAspect;
}
@Override
public void modelChanged(PomModelEvent event) {
final PomChangeSet changeSet = event.getChangeSet(myAspect);
if(changeSet == null) return;
myBuffer.append(changeSet);
myBuffer.append("\n");
}
@Override
public boolean isAspectChangeInteresting(PomModelAspect aspect) {
return aspect == myAspect;
}
String getEventString(){
return myBuffer.toString();
}
}
private static void assertFileTextEquals(String targetDataName, String treeText) throws Exception {
String fullName = PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/')+ "/xml/tests/testData/psi/events" + File.separatorChar + targetDataName;
try{
String expectedText = loadFile(fullName);
assertEquals(expectedText.trim(), treeText.trim());
}
catch(FileNotFoundException e){
//FileUtil.writeToFile(new File(fullName), StringUtil.convertLineSeparators(treeText).getBytes("UTF-8"));
fail("No output file found. Created file "+fullName);
}
}
protected static String loadFile(String fullName) throws Exception {
String text = FileUtil.loadFile(new File(fullName)).trim();
text = StringUtil.convertLineSeparators(text);
return text;
}
}
@@ -0,0 +1,144 @@
package com.intellij.codeInsight;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.testFramework.PsiTestCase;
import com.intellij.xml.XmlAttributeDescriptor;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlNSDescriptor;
/**
* @author Mike
*/
public class XmlInsightTest extends PsiTestCase {
public void testDocumentDescriptor1() throws Exception {
XmlFile file = createFile("<root><a></a><b></b><a></a></root>");
XmlNSDescriptor descriptor = createDescriptor(file);
XmlElementDescriptor element = descriptor.getElementDescriptor(file.getDocument().getRootTag());
assertNotNull(element);
assertEquals("root", element.getName());
element = descriptor.getElementDescriptor(file.getDocument().getRootTag().getSubTags()[0]);
assertNotNull(element);
assertEquals("a", element.getName());
element = descriptor.getElementDescriptor(file.getDocument().getRootTag().getSubTags()[1]);
assertNotNull(element);
assertEquals("b", element.getName());
element = descriptor.getElementDescriptor(file.getDocument().getRootTag().getSubTags()[2]);
assertNotNull(element);
assertEquals("a", element.getName());
}
public void testElementDescriptor1() throws Exception {
XmlFile file = createFile("<root><a></a><b></b><a></a></root>");
XmlNSDescriptor descriptor = createDescriptor(file);
XmlTag rootTag = file.getDocument().getRootTag();
XmlElementDescriptor element = descriptor.getElementDescriptor(rootTag);
XmlElementDescriptor[] elements = element.getElementsDescriptors(rootTag);
assertEquals(2, elements.length);
assertEquals("a", elements[0].getName());
assertEquals("b", elements[1].getName());
}
public void testElementDescriptor2() throws Exception {
XmlFile file = createFile("<root><a><b/></a><a><c/></a></root>");
XmlNSDescriptor descriptor = createDescriptor(file);
XmlTag rootTag = file.getDocument().getRootTag();
XmlElementDescriptor element = descriptor.getElementDescriptor(rootTag);
element = element.getElementsDescriptors(rootTag)[0];
XmlElementDescriptor[] elements = element.getElementsDescriptors(rootTag.getSubTags()[0]);
assertEquals(2, elements.length);
assertEquals("b", elements[0].getName());
assertEquals("c", elements[1].getName());
}
public void testElementDescriptor3() throws Exception {
XmlFile file = createFile("<root><a><b/><c></c></a><a><c/></a></root>");
XmlNSDescriptor descriptor = createDescriptor(file);
XmlTag rootTag = file.getDocument().getRootTag();
XmlElementDescriptor element = descriptor.getElementDescriptor(rootTag);
element = element.getElementsDescriptors(rootTag)[0];
XmlElementDescriptor[] elements = element.getElementsDescriptors(rootTag.getSubTags()[0]);
assertEquals(2, elements.length);
assertEquals("b", elements[0].getName());
//assertTrue(elements[0].getContentType() == XmlElementDescriptor.CONTENT_TYPE_EMPTY);
assertEquals("c", elements[1].getName());
//assertTrue(elements[1].getContentType() == XmlElementDescriptor.CONTENT_TYPE_CHILDREN);
}
public void testElementDescriptor4() throws Exception {
XmlFile file = createFile("<root><a attr2=''></a><a attr1=''></a></root>");
XmlNSDescriptor descriptor = createDescriptor(file);
XmlTag rootTag = file.getDocument().getRootTag();
XmlElementDescriptor element = descriptor.getElementDescriptor(rootTag);
element = element.getElementsDescriptors(rootTag)[0];
XmlAttributeDescriptor[] attributes = element.getAttributesDescriptors(rootTag);
assertEquals(2, attributes.length);
assertEquals("attr1", attributes[0].getName());
assertEquals("attr2", attributes[1].getName());
}
public void testAttributeDescriptor1() throws Exception {
XmlFile file = createFile("<root><a attr1=''></a><a attr2='' attr1=''></a></root>");
XmlNSDescriptor descriptor = createDescriptor(file);
XmlTag rootTag = file.getDocument().getRootTag();
XmlElementDescriptor element = descriptor.getElementDescriptor(rootTag);
element = element.getElementsDescriptors(rootTag)[0];
XmlAttributeDescriptor[] attributes = element.getAttributesDescriptors(rootTag);
assertEquals("attr1", attributes[0].getName());
assertTrue(attributes[0].isRequired());
assertEquals("attr2", attributes[1].getName());
assertTrue(!attributes[1].isRequired());
}
public void testAttributeDescriptor2() throws Exception {
XmlFile file = createFile("<root><a c='' a=''></a></root>");
XmlNSDescriptor descriptor = createDescriptor(file);
XmlTag rootTag = file.getDocument().getRootTag();
XmlElementDescriptor element = descriptor.getElementDescriptor(rootTag);
element = element.getElementsDescriptors(rootTag)[0];
XmlAttributeDescriptor[] attributes = element.getAttributesDescriptors(rootTag);
assertEquals("c", attributes[0].getName());
assertTrue(attributes[0].isRequired());
assertEquals("a", attributes[1].getName());
assertTrue(attributes[1].isRequired());
}
private XmlFile createFile(String text) throws Exception {
return (XmlFile)createDummyFile("test.xml", text);
}
private XmlNSDescriptor createDescriptor(XmlFile file) throws Exception{
return file.getDocument().getRootTagNSDescriptor();
}
private XmlTag tag(String tagName) throws Exception {
XmlFile file = (XmlFile)PsiFileFactory.getInstance(myPsiManager.getProject()).createFileFromText("tag.xml", "<" + tagName + "/>");
return file.getDocument().getRootTag();
}
}
@@ -0,0 +1,649 @@
package com.intellij.codeInsight;
import com.intellij.lang.ASTFactory;
import com.intellij.lang.ASTNode;
import com.intellij.lang.LanguageASTFactory;
import com.intellij.lang.LanguageParserDefinitions;
import com.intellij.lang.dtd.DTDLanguage;
import com.intellij.lang.dtd.DTDParserDefinition;
import com.intellij.lang.xml.XMLLanguage;
import com.intellij.lang.xml.XMLParserDefinition;
import com.intellij.lang.xml.XmlASTFactory;
import com.intellij.lexer.FilterLexer;
import com.intellij.lexer.Lexer;
import com.intellij.lexer.XmlLexer;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.psi.impl.source.CharTableImpl;
import com.intellij.psi.impl.source.parsing.xml.OldXmlParser;
import com.intellij.psi.impl.source.tree.CompositeElement;
import com.intellij.psi.impl.source.tree.LeafElement;
import com.intellij.psi.impl.source.tree.TreeUtil;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.xml.*;
import com.intellij.testFramework.ParsingTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.util.ThrowableRunnable;
import org.jetbrains.annotations.NonNls;
import java.io.File;
/**
* @author Mike, ik
*/
public class XmlParsingTest extends ParsingTestCase {
public XmlParsingTest() {
super("psi", "???");
myLanguage = XMLLanguage.INSTANCE;
}
@Override
protected void setUp() throws Exception {
super.setUp();
addExplicitExtension(LanguageParserDefinitions.INSTANCE, XMLLanguage.INSTANCE, new XMLParserDefinition());
addExplicitExtension(LanguageParserDefinitions.INSTANCE, DTDLanguage.INSTANCE, new DTDParserDefinition());
addExplicitExtension(LanguageASTFactory.INSTANCE, XMLLanguage.INSTANCE, new XmlASTFactory());
addExplicitExtension(LanguageASTFactory.INSTANCE, DTDLanguage.INSTANCE, new XmlASTFactory());
registerExtensionPoint(new ExtensionPointName<XmlChildRole.StartTagEndTokenProvider>("com.intellij.xml.startTagEndToken"),
XmlChildRole.StartTagEndTokenProvider.class);
}
@Override
protected String getTestDataPath() {
return PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + "/xml/tests/testData/";
}
private void doTestXml(@NonNls String text) throws Exception {
myLanguage = XMLLanguage.INSTANCE;
doTest(text, "test.xml");
}
private void doTestDtd(@NonNls String text) throws Exception {
myLanguage = DTDLanguage.INSTANCE;
doTest(text, "test.dtd");
}
private void doTest(@NonNls String text, @NonNls String fileName) throws Exception {
PsiFile file = createFile(fileName, text);
checkResult("test" +getTestName(false), file);
}
public void testNewParsing1() throws Exception {
doTestXml("<a></a>");
}
public void testEmptyCommentParsing() throws Exception {
doTestXml("<!---->");
}
public void testNewParsing2() throws Exception {
doTestXml("<a> </a>");
}
public void testNewParsing3() throws Exception {
doTestXml("<a </a>");
}
public void testNewParsing4() throws Exception {
doTestXml("<a> <b> </a>");
}
public void testNewParsing5() throws Exception {
doTestXml("<a> <b/> </a>");
}
public void testNewParsing6() throws Exception {
doTestXml("<!DOCTYPE greeting SYSTEM \"hello.dtd\" [<!ELEMENT greeting EMPTY>]> <a> <b/> </a>");
}
public void testNewParsing7() throws Exception {
doTestXml("<a> <b> <c> <d> </a>");
}
public void testNewParsing8() throws Exception {
doTestXml("<a blah=\"blah\"/>");
}
public void testNewParsing9() throws Exception {
doTestXml("<a asd=\"asd\"></a>");
}
public void testNewParsing10() throws Exception {
doTestXml("<a asd=\"asd\"> <s> </a>");
}
public void testNewParsing11() throws Exception {
doTestXml("<!-- <!-- --> <a asd=\"asd\"> <s> </a>");
}
public void testNewParsing12() throws Exception {
doTestXml("<a><a ajsdg<a></a></a>");
}
public void testNewParsing13() throws Exception {
doTestXml("<a><b><c>\n" + "xxx \n" + "xxxx\n" + "<</b></a>");
}
public void testNewParsing14() throws Exception {
doTestXml("<a><a ajsdg = \"\"></a></a>");
}
public void testNewParsing15() throws Exception {
doTestXml("<!DOCTYPE a [<!ELEMENT a (a)>]> <a><a ajsdg = \"\"></a></a>");
}
public void testNewParsing19() throws Exception {
doTestXml("<!DOCTYPE aaa [" + "<!ELEMENT a #EMPTY>" + "<!ATTLIST a" + " xx CDATA #IMPLIED" + " yy #IMPLIED" + " zz CDATA #IMPLIED>]>\n" +
"<a> <b> </b> </a>");
}
public void testNewParsing20() throws Exception {
doTestXml("<!DOCTYPE root [\n" + "<!\n" + "]>\n" + "<root>\n" + "\n" + "</root>");
}
public void testEntityInAttr() throws Exception {
doTestXml("<a href=\"&n\"/>");
}
public void testEntityInContent() throws Exception {
doTestXml("<a> &n </a>");
}
public void testMultyRoots() throws Exception {
doTestXml("<a href=\"\"/> <b/>");
}
public void testMultyRootsWithErrorsBetween() throws Exception {
doTestXml("<a href=\"\"/> </ss><b/>");
}
public void testGtInTagContent() throws Exception {
doTestXml("<a>></a>");
}
public void testManyErrors() throws Exception {
doTestXml(loadFile("manyErrors.xml"));
}
public void _testLexerPerformance1() throws Exception{
final String text = loadFile("pallada.xml");
XmlLexer lexer = new XmlLexer();
doLex(lexer, text);
final FilterLexer filterLexer = new FilterLexer(new XmlLexer(),
new FilterLexer.SetFilter(LanguageParserDefinitions.INSTANCE.forLanguage(XMLLanguage.INSTANCE).getWhitespaceTokens()));
doLex(filterLexer, text);
doLex(lexer, text);
doLex(filterLexer, text);
doLex(filterLexer, text);
}
public void _testLexerPerformance2() throws Exception{
final String text = loadFile("performance2.xml");
XmlLexer lexer = new XmlLexer();
doLex(lexer, text);
final FilterLexer filterLexer = new FilterLexer(new XmlLexer(),
new FilterLexer.SetFilter(LanguageParserDefinitions.INSTANCE.forLanguage(XMLLanguage.INSTANCE).getWhitespaceTokens()));
doLex(filterLexer, text);
doLex(lexer, text);
for (int i = 0; i < 20; i++) {
doLex(filterLexer, text);
}
}
private static void doLex(Lexer lexer, final String text) {
lexer.start(text);
long time = System.currentTimeMillis();
int count = 0;
while(lexer.getTokenType() != null){
lexer.advance();
count++;
}
System.out.println("Plain lexing took " + (System.currentTimeMillis() - time) + "ms lexems count:" + count);
}
private void transformAllChildren(final ASTNode file) {
for (ASTNode child = file.getFirstChildNode(); child != null; child = child.getTreeNext()) {
transformAllChildren(child);
}
}
public void _testPerformance1() throws Exception{
final String text = loadFile("pallada.xml");
long time = System.currentTimeMillis();
final PsiFile file = createFile("test.xml", text);
transformAllChildren(file.getNode());
System.out.println("Old parsing took " + (System.currentTimeMillis() - time) + "ms");
int index = 0;
while(index++ < 10){
newParsing(text);
}
LeafElement firstLeaf = TreeUtil.findFirstLeaf(file.getNode());
index = 0;
do{
index++;
}
while((firstLeaf = TreeUtil.nextLeaf(firstLeaf, null)) != null);
System.out.println("For " + index + " lexems");
}
public void _testReparsePerformance() throws Exception {
final String text = loadFile("performance2.xml");
final PsiFile file = createFile("test.xml", text);
transformAllChildren(file.getNode());
final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file);
System.gc();
System.gc();
new WriteCommandAction(getProject(), file) {
@Override
protected void run(final Result result) throws Throwable {
PlatformTestUtil.startPerformanceTest("XML reparse using PsiBuilder", 2500, new ThrowableRunnable() {
@Override
public void run() throws Exception {
for (int i = 0; i < 10; i++) {
final long tm = System.currentTimeMillis();
doc.insertString(0, "<additional root=\"tag\"/>");
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
System.out.println("Reparsed for: " + (System.currentTimeMillis() - tm));
}
}
}).cpuBound().assertTiming();
}
}.execute();
}
public void _testPerformance2() throws Exception{
final String text = loadFile("performance2.xml");
long time = System.currentTimeMillis();
final PsiFile file = createFile("test.xml", text);
transformAllChildren(file.getNode());
System.out.println("Old parsing took " + (System.currentTimeMillis() - time) + "ms");
int index = 0;
while(index++ < 10){
newParsing(text);
}
LeafElement firstLeaf = TreeUtil.findFirstLeaf(file.getNode());
index = 0;
do{
index++;
}
while((firstLeaf = TreeUtil.nextLeaf(firstLeaf, null)) != null);
System.out.println("For " + index + " lexems");
}
private static void newParsing(final String text) {
long time = System.currentTimeMillis();
ASTFactory.lazy(XmlElementType.XML_FILE, text).getFirstChildNode(); // ensure parsed
System.out.println("parsed for " + (System.currentTimeMillis() - time) + "ms");
}
public void testXmlDecl() throws Exception {
doTestXml("<?xml version=\"1.0\" encoding='cp1251' ?>");
}
public void testXmlDecl2() throws Exception {
doTestXml("<?xml version=\"1.0\" encoding='cp1251' ?> <foo></foo>");
}
public void testXmlDecl3() throws Exception {
doTestXml("<?xml version=\"1.0\" encoding='cp1251' > <foo></foo>");
}
public void testDoctype1() throws Exception {
doTestXml("<!DOCTYPE greeting SYSTEM \"hello.dtd\">");
}
public void testDoctype2() throws Exception {
doTestXml("<!DOCTYPE toc " + "PUBLIC \"-//Sun Microsystems Inc.//DTD JavaHelp TOC Version 1.0//EN\" " +
"\"http://java.sun.com/products/javahelp/toc_1_0.dtd\">");
}
public void testDoctype3() throws Exception {
doTestXml("<!DOCTYPE greeting [" + "<!ELEMENT greeting (#PCDATA)>" + "]>");
}
public void testDoctype4() throws Exception {
doTestXml("<!DOCTYPE greeting [" + "<!ELEMENT br EMPTY>" + "]>");
}
public void testDoctype5() throws Exception {
doTestXml("<!DOCTYPE greeting [" + "<!ELEMENT p (#PCDATA|a|ul|b|i|em)*>" + "]>");
}
public void testDoctype6() throws Exception {
doTestXml("<!DOCTYPE greeting [" + "<!ELEMENT %name.para; %content.para; >" + "]>");
}
public void testDoctype7() throws Exception {
doTestXml("<?xml version='1.0' encoding='ISO-8859-1' ?>" + "<!DOCTYPE toc SYSTEM 'dtds/ejb-jar_2_0.dtd'>" + "<test>" + "</test>");
}
public void testAttlist1() throws Exception {
doTestDtd("<!ATTLIST termdef id ID #REQUIRED name CDATA #IMPLIED>");
}
public void testAttlist2() throws Exception {
doTestDtd("<!ATTLIST termdef type (bullets|ordered|glossary) \"ordered\">");
}
public void testAttlist3() throws Exception {
doTestDtd("<!ATTLIST termdef method CDATA #FIXED \"POST\">");
}
public void testAttlist4() throws Exception {
doTestDtd("<!ATTLIST termdef default-charset %CHARSET; \"iso-8859-1\">");
}
public void testComment1() throws Exception {
doTestXml("<!-- declarations for <head> & <body> -->");
}
public void testComment2() throws Exception {
doTestDtd("<!ELEMENT data-sources (#PCDATA)> <!-- abc --> <!ATTLIST data-sources path CDATA #IMPLIED");
}
public void testComment3() throws Exception {
doTestXml("<a><!--<b>--></a>");
}
public void testElements1() throws Exception {
doTestXml("<a></a>");
}
public void testElements2() throws Exception {
doTestXml("<a/>");
}
public void testElements3() throws Exception {
doTestXml("<a><b><c/><d/></b><e/><f><g/></f></a>");
}
public void testElements4() throws Exception {
doTestXml("<project name=\"IDEA_ZKM\">\n" + "<!-- set global properties for this build -->\n" + "<property value=\"off\" />\n" +
"</project>\n");
}
public void testElements5() throws Exception {
doTestXml("<ns1:a><ns2:b/></ns1:a>");
}
public void testElements6() throws Exception {
doTestXml("<!DOCTYPE project [" + "<!ENTITY targets SYSTEM \"file:../myproject/targets.xml\">" + "]>" + "<project>" + "</project>");
}
public void testAttributes1() throws Exception {
doTestXml("<a att1='val1' att2=\"val2\"></a>");
}
public void testAttributes2() throws Exception {
doTestXml("<a><b c=\"\" > </b> </a>");
}
public void testAttributes3() throws Exception {
doTestXml("<a><b c=\"a, b, c\" > </b> </a>");
}
public void testAttributes4() throws Exception {
doTestXml("<a><b c=\"a b\" > </b> </a>");
}
public void testAttributes5() throws Exception {
doTestXml("<a><b c=\"a\"d=\"\" > </b> </a>");
}
public void testManualEmptyAttributeParsing() throws Exception{
String value = "<a><b c=\"\" > </b> </a>";
final CompositeElement element = parseManually(value, XmlElementType.XML_ELEMENT_DECL, XmlEntityDecl.EntityContextType.GENERIC_XML);
checkResult("testManualEmptyAttributeParsing.txt", DebugUtil.treeToString(element, false));
}
private CompositeElement parseManually(final String value, final IElementType xmlElementDecl, XmlEntityDecl.EntityContextType parseType) {
return (CompositeElement)new OldXmlParser(value, xmlElementDecl, parseType, new CharTableImpl(), getPsiManager()).parse();
}
public void testCharacters1() throws Exception {
doTestXml("<a>someChar\nData</a>");
}
public void testEditing1() throws Exception {
doTestXml("<<a></a>");
}
public void testEditing2() throws Exception {
doTestXml("<a><b/> < <c/></a>");
}
public void testEditing3() throws Exception {
doTestXml("<a><b <c/></a>");
}
public void testEditing4() throws Exception {
doTestXml("<a><b>< <c/></a>");
}
public void testEditing5() throws Exception {
doTestXml("<a><b></ <c/></a>");
}
public void testEditing6() throws Exception {
doTestXml("<one> <two ,b\"/></one>");
}
public void testEditing7() throws Exception {
doTestXml("<one> <two a,b\"/></one>");
}
public void testEditing8() throws Exception {
doTestXml("<one> <two a b=\"\"/></one>");
}
public void testEditing9() throws Exception {
doTestXml("<one> <two a b=\"\"> ashdgjkasgd <aksjhdk></two></one>");
}
public void testCdata1() throws Exception {
doTestXml("<a><![CDATA[<greeting>Hello, world!</greeting>]]></a>");
}
public void testCdata2() throws Exception {
doTestXml("<a><![CDATA[someData <!--</greeting>--> more data]]></a>");
}
public void testDtd1() throws Exception {
doTestDtd("<!ELEMENT data-sources (#PCDATA)> <!ATTLIST data-sources path CDATA #IMPLIED>");
}
public void testElementDecl1() throws Exception {
doTestDtd("<!ELEMENT data-sources EMPTY>");
}
public void testElementDecl2() throws Exception {
doTestDtd("<!ELEMENT data-sources ANY>");
}
public void testConditionalSection1() throws Exception {
doTestDtd("<![ INCLUDE [ <!ELEMENT data-sources ANY> ]]>");
}
public void testConditionalSection2() throws Exception {
doTestDtd("<![%sgml.features;[\n" + "<![IGNORE[\n" +
"<!ENTITY % dbgenent SYSTEM \"http://www.oasis-open.org/docbook/xml/configerror.txt\">\n" + "]]>\n" + "]]>");
}
public void testConditionalSection3() throws Exception {
doTestDtd("<!ENTITY % dbhier.module \"INCLUDE\">\n" + "<![ %dbhier.module; [\n" + "<!ENTITY % dbhier PUBLIC\n" +
"\"-//OASIS//ELEMENTS DocBook Document Hierarchy V4.4//EN\"\n" + "\"dbhierx.mod\">\n" + "%dbhier;\n" + "]]>");
}
public void testEntityRef1() throws Exception {
doTestXml("<a>%types;</a>");
}
public void testEntityRef3() throws Exception {
doTestDtd("<!ELEMENT project (target | taskdef | %types; | property )*>");
}
public void testEntityRef4() throws Exception {
doTestXml("<a b=\"aa &gt; bb\" />");
}
public void testEntityRef5() throws Exception {
doTestDtd("<!ATTLIST a %coreattrs; version CDATA #FIXED \"1.0\"");
}
public void testEntityRef6() throws Exception {
doTestDtd("&common;");
}
public void testEntityRef7() throws Exception {
doTestDtd("<!ATTLIST foo someBoolean (%boolean;) \"true\" someString CDATA #IMPLIED >");
}
public void testEntityDecl1() throws Exception {
doTestDtd("<!ENTITY % types \"fileset | patternset mapper\">");
}
public void testEntityDecl2() throws Exception {
doTestDtd("<!ENTITY types \"fileset | patternset mapper\">");
}
public void testEntityDecl3() throws Exception {
doTestDtd("<!ENTITY build-common SYSTEM \"common.xml\">");
}
public void testEntityDecl4() throws Exception {
doTestDtd(
"<!ENTITY open-hatch PUBLIC \"-//Textuality//TEXT Standard open-hatch boilerplate//EN\" \"http://www.textuality.com/boilerplate/OpenHatch.xml\">");
}
public void testUnbalanced1() throws Exception {
doTestXml("<a><b></a>");
}
public void testUnbalanced2() throws Exception {
doTestXml("<a><b><c></a>");
}
public void testUnbalanced3() throws Exception {
doTestXml("<a><b></bb></a>");
}
public void testUnbalanced4() throws Exception {
doTestXml("<a><b><b/></c></a>");
}
public void testDtdUrl1() throws Exception {
XmlFile file = (XmlFile)createFile("test.xml", "<!DOCTYPE greeting SYSTEM \"hello.dtd\">");
XmlDocument document = file.getDocument();
XmlProlog prolog = document.getProlog();
XmlDoctype doctype = prolog.getDoctype();
String url = doctype.getDtdUri();
assertTrue("testDtdUrl1", "hello.dtd".equals(url));
}
public void testContent1() throws Exception {
XmlFile file = (XmlFile)createFile("test.xml", "<a> \nxxx \n</a>");
checkResult("testContent1", file);
assertTrue("xxx".equals(file.getDocument().getRootTag().getValue().getTrimmedText()));
}
public void testUnopenedTag1() throws Exception {
doTestXml("</foo>");
}
public void testUnclosedTag() throws Exception {
XmlFile file = (XmlFile)createFile("test.xml", "<a>xxx");
checkResult("testUnclosedTag", file);
assertTrue("xxx".equals(file.getDocument().getRootTag().getValue().getText()));
}
public void testUnclosedTag2() throws Exception {
doTestXml("<a");
}
public void testProcessingInstruction1() throws Exception {
doTestXml("<?This is=\"PI\"?>");
}
public void testProcessingInstruction2() throws Exception {
doTestXml("<a><?This is=\"PI\"?></a>");
}
public void testProcessingInstruction3() throws Exception {
doTestXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<?xml-stylesheet type=\"text/xsl\" href=\"document.xsl\"?>" +
"<!-- @(#) $Id$ -->" + "<!DOCTYPE api SYSTEM \"document.dtd\">" + "<api>" + "</api>");
}
public void testCharRef1() throws Exception {
doTestXml("<a>&#123;</a>");
}
public void testCharRef2() throws Exception {
doTestXml("<a>&#x123;</a>");
}
public void testCharRef3() throws Exception {
doTestXml("&#123;");
}
public void testCharRef4() throws Exception {
doTestXml("&#xaBcD123;");
}
public void testCharRef5() throws Exception {
doTestXml("<a attr=\"abc&#123;\"/>");
}
public void testNotation1() throws Exception {
doTestDtd("<!NOTATION data-sources SYSTEM \"x3\">");
}
public void testPrologInDtd() throws Exception {
doTestDtd("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + "<!ELEMENT idea-plugin>\n" + "<!ATTLIST idea-plugin\n" +
" url CDATA #IMPLIED>");
}
public void testEmptyElementsInDtd() throws Exception {
doTestDtd("<!ELEMENT >\n<!ELEMENT name (,)\n<!ATTLIST > <!ELEMENT zzz (aa?, bb)+> <!ELEMENT xxx(aaa,)>" + "<!ATTLIST %aaa;>");
}
public void testElementDeclaration() throws Exception {
doTestDtd(
"<!ELEMENT xxx EMPTY>\n<!ELEMENT xxx2 ANY>\n<!ELEMENT %name.para; %content.para; >\n<!ELEMENT xxx3 (#PCDATA | a) >\n<!ELEMENT xxx4 >");
}
public void testEntityDeclaration() throws Exception {
doTestDtd("<!ENTITY xxx > <!ENTITY >");
}
public void testEntityDeclaration2() throws Exception {
String s = "| %pre.qname; | %blockquote.qname; | %address.qname;";
CompositeElement element = parseManually(s, XmlElementType.XML_ELEMENT_CONTENT_SPEC, XmlEntityDecl.EntityContextType.ELEMENT_CONTENT_SPEC);
checkResult("testEntityDeclaration2.txt", DebugUtil.treeToString(element, false));
}
public void testEntityInAttlistDeclaration() throws Exception {
doTestDtd("<!ATTLIST %span.qname; %Common.attrib;>");
}
public void testSGMLDtd() throws Exception {
doTestDtd("<!ELEMENT name - - (%inline;)* +(A)> <!ATTLIST (A|B) >\n" +
"<!ELEMENT (E|E2) - O (%flow;)* -- table header cell, table data cell-->\n" +
"<!ELEMENT BODY O O (%block;|SCRIPT)+ +(INS|DEL) -- document body -->");
}
public void testNotation2() throws Exception {
doTestXml("<!DOCTYPE x3 [<!NOTATION data-sources SYSTEM \"x3\">]>");
}
}
@@ -0,0 +1,89 @@
/*
* Copyright (c) 2000-2006 JetBrains s.r.o. All Rights Reserved.
*/
/*
* Created by IntelliJ IDEA.
* User: Maxim.Mossienko
* Date: Sep 8, 2006
* Time: 3:40:30 PM
*/
package com.intellij.codeInsight;
import com.intellij.codeInsight.daemon.quickFix.LightQuickFixTestCase;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.actionSystem.EditorActionManager;
import com.intellij.testFramework.IdeaTestUtil;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.util.ThrowableRunnable;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* @by Maxim.Mossienko
*/
public class XmlPerformanceTest extends LightQuickFixTestCase {
private final Set<String> ourTestsWithFolding = new HashSet<String>(Arrays.asList("IndentUnindent2"));
@Override
protected String getBasePath() {
return "performance/";
}
@Override
protected String getTestDataPath() {
return PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + "/xml/tests/testData/";
}
public void testDummy() {
@SuppressWarnings({"UnusedDeclaration"})
Class clazz = IdeaTestUtil.class;
}
public void testIndentUnindent() throws Exception {
doIndentTest(2000);
}
public void testIndentUnindent2() throws Exception {
doIndentTest(2001);
}
@Override
protected boolean doFolding() {
return ourTestsWithFolding.contains(getTestName(false));
}
private void doIndentTest(int time) throws Exception {
configureByFile(getBasePath() + getTestName(false)+".xml");
doHighlighting();
myEditor.getSelectionModel().setSelection(0,myEditor.getDocument().getTextLength());
PlatformTestUtil.startPerformanceTest("Fix long indent/unindent "+time, time, new ThrowableRunnable() {
@Override
public void run() {
EditorActionManager.getInstance().getActionHandler("EditorIndentSelection").execute(myEditor, new DataContext() {
@Override
@Nullable
public Object getData(String dataId) {
return null;
}
});
EditorActionManager.getInstance().getActionHandler("EditorUnindentSelection").execute(myEditor, new DataContext() {
@Override
@Nullable
public Object getData(String dataId) {
return null;
}
});
}
}).assertTiming();
final int startOffset = myEditor.getCaretModel().getOffset();
myEditor.getSelectionModel().setSelection(startOffset,startOffset);
checkResultByFile(getBasePath() + getTestName(false)+".xml");
}
}
@@ -0,0 +1,165 @@
/*
* Created by IntelliJ IDEA.
* User: mike
* Date: Oct 4, 2002
* Time: 2:14:24 PM
* To change template for new class use
* Code Style | Class Templates options (Tools | IDE Options).
*/
package com.intellij.codeInsight;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.psi.AbstractReparseTestCase;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.psi.impl.source.xml.XmlFileImpl;
import com.intellij.psi.xml.XmlFile;
import com.intellij.testFramework.ParsingTestCase;
import com.intellij.testFramework.PlatformTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.util.IncorrectOperationException;
import java.io.File;
@PlatformTestCase.WrapInCommand
public class XmlReparseTest extends AbstractReparseTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
setFileType(StdFileTypes.XML);
}
public void test1() throws Exception{
String s1 = "<a>";
String s2 = "</a>";
prepareFile(s1, s2);
final String beforeReparse = DebugUtil.treeToString(((XmlFileImpl)myDummyFile).getTreeElement(), true);
insert("");
assertEquals("Tree changed after empty reparse", beforeReparse, DebugUtil.treeToString(((XmlFileImpl)myDummyFile).getTreeElement(), true));
}
public void testTagData1() throws Exception {
String s1 = "<a>";
String s2 = "</a>";
prepareFile(s1, s2);
insert("x");
insert(" ");
insert("xxxxx");
insert("\n");
insert("xxxxx");
}
public void testTagData2() throws Exception {
String s1 = "<a><b>\nSomeDataHere";
String s2 = "\n</b></a>";
prepareFile(s1, s2);
PsiElement element1 = ((XmlFile)myDummyFile).getDocument().getRootTag();
insert("x");
insert(" ");
insert("xxxxx");
insert("\n");
insert("xxxxx");
assertSame(element1, ((XmlFile)myDummyFile).getDocument().getRootTag());
}
public void testTagInTag1() throws Exception {
String s1 = "<a><b>";
String s2 = "</b></a>";
prepareFile(s1, s2);
insert("<");
insert("c");
insert("/");
insert(">");
}
public void testTagInTag2() throws Exception {
String s1 = "<a><b>";
String s2 = "</b></a>";
prepareFile(s1, s2);
insert("<");
insert("c");
insert(">");
insert("\nxxx \nxxxx\n");
insert("<");
insert("/");
insert("c");
insert(">");
}
public void testTagInTag3() throws Exception {
String s1 = "<a><b>";
String s2 = "</b></a>";
prepareFile(s1, s2);
insert("<");
insert("/");
insert("b");
insert(">");
}
public void testSCR5925() throws Exception {
String s1 = "<one> <two ";
String s2 = ",b\"/></one>";
prepareFile(s1, s2);
insert("a");
insert("t");
insert("t");
insert("r");
insert("=");
insert("\"");
}
public void testXmlReparseProblem() throws IncorrectOperationException {
prepareFile("<table>\n" +
" <tr>\n" +
"<td>\n" +
"<table width"," </td>\n" +
" </tr>\n" +
"</table>");
insert("=");
}
private static final String marker = "<marker>";
public void testXmlDeclDtd() throws Exception {
PsiFile file = createFile("x.xml", "<!DOCTYPE name [\n" +
" <!ELEMENT name (" + marker+ "a b c d" + marker+ ")>\n" +
" <!ELEMENT name2 (" + marker+ "%entity;" + marker+ ")>\n" +
"]>\n" +
"<name></name>");
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
Document document = documentManager.getDocument(file);
removeGarbage(document);
documentManager.commitAllDocuments();
String myFullDataPath = getTestDataPath() + "psi/";
ParsingTestCase.doCheckResult(myFullDataPath, file, true, "testXmlDeclDtd", false, false);
}
private static void removeGarbage(Document document) {
int i = document.getText().indexOf(marker);
if (i==-1) return;
document.replaceString(i,i+marker.length(),"");
removeGarbage(document);
}
@Override
protected String getTestDataPath() {
return PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + "/xml/tests/testData/";
}
}
@@ -0,0 +1,757 @@
package com.intellij.codeInsight;
import com.intellij.psi.PsiFile;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.xml.XmlAttributeDescriptor;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlNSDescriptor;
import com.intellij.xml.impl.schema.XmlElementDescriptorImpl;
import com.intellij.xml.impl.schema.XmlNSDescriptorImpl;
import com.intellij.xml.util.XmlUtil;
import org.jetbrains.annotations.NonNls;
/**
* @author Mike
*/
public class XmlSchemaTest extends LightCodeInsightTestCase {
private XmlTag SHIP_TO;
private XmlTag UNKNOWN_TAG;
@Override
protected void setUp() throws Exception {
super.setUp();
SHIP_TO = XmlTestUtil.tag("shipTo", getProject());
UNKNOWN_TAG = XmlTestUtil.tag("xxx", getProject());
}
public void testDocumentDescriptor1() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:element name=\"comment\" type=\"xsd:string\"/>" +
"</xsd:schema>");
assertNotNull(NSDescriptor);
assertNotNull(NSDescriptor.getElementDescriptor(XmlTestUtil.tag("purchaseOrder", getProject())));
assertNotNull(NSDescriptor.getElementDescriptor(XmlTestUtil.tag("comment", getProject())));
assertNull(NSDescriptor.getElementDescriptor(UNKNOWN_TAG));
}
public void testElementDescriptor1() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:element name=\"comment\" type=\"xsd:string\"/>" +
"</xsd:schema>");
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(XmlTestUtil.tag("purchaseOrder", getProject()));
assertEquals("purchaseOrder", elementDescriptor.getName());
elementDescriptor = NSDescriptor.getElementDescriptor(XmlTestUtil.tag("comment", getProject()));
assertEquals("comment", elementDescriptor.getName());
}
public void testElementDescriptor2() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"comment\" type=\"xsd:string\"/>" +
"</xsd:schema>");
XmlTag tag = XmlTestUtil.tag("comment", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlElementDescriptor[] elements = elementDescriptor.getElementsDescriptors(tag);
assertEquals(0, elements.length);
XmlAttributeDescriptor[] descriptors = elementDescriptor.getAttributesDescriptors(tag);
assertEquals(0, descriptors.length);
assertEquals(elementDescriptor.getContentType(), XmlElementDescriptor.CONTENT_TYPE_MIXED);
}
public void testElementDescriptor3() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:sequence>" +
" <xsd:element name=\"shipTo\" type=\"USAddress\"/>" +
" <xsd:element name=\"billTo\" type=\"USAddress\"/>" +
" <xsd:element name=\"items\" type=\"Items\"/>" +
" </xsd:sequence>" +
"</xsd:complexType>" +
"</xsd:schema>");
XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlElementDescriptor[] elements = elementDescriptor.getElementsDescriptors(tag);
assertEquals(3, elements.length);
assertEquals("shipTo", elements[0].getName());
assertEquals("billTo", elements[1].getName());
assertEquals("items", elements[2].getName());
assertEquals("shipTo", elementDescriptor.getElementDescriptor(SHIP_TO, null).getName());
assertNull(elementDescriptor.getElementDescriptor(UNKNOWN_TAG, null));
}
public void testElementDescriptor4() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:attribute name=\"orderDate\" type=\"xsd:date\"/>" +
" <xsd:attribute name=\"name\" type=\"xsd:string\"/>" +
"</xsd:complexType>" +
"</xsd:schema>");
final XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor[] attributes = elementDescriptor.getAttributesDescriptors(tag);
assertEquals(2, attributes.length);
assertEquals("orderDate", attributes[0].getName());
assertEquals("name", attributes[1].getName());
assertEquals("name", elementDescriptor.getAttributeDescriptor("name", tag).getName());
assertNull(elementDescriptor.getAttributeDescriptor("xxx", tag));
}
public void testElementDescriptor5() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:sequence>" +
" <xsd:element name=\"shipTo\" type=\"USAddress\"/>" +
" <xsd:element name=\"billTo\" type=\"USAddress\"/>" +
" <xsd:element name=\"items\" type=\"Items\"/>" +
" </xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:complexType name=\"USAddress\">" +
" <xsd:sequence>" +
" <xsd:element name=\"name\" type=\"xsd:string\"/>" +
" <xsd:element name=\"street\" type=\"xsd:string\"/>" +
" <xsd:element name=\"city\" type=\"xsd:string\"/>" +
" <xsd:element name=\"state\" type=\"xsd:string\"/>" +
" <xsd:element name=\"zip\" type=\"xsd:decimal\"/>" +
" </xsd:sequence>" +
" <xsd:attribute name=\"country\" type=\"xsd:NMTOKEN\" fixed=\"US\"/>" +
"</xsd:complexType>" +
"</xsd:schema>");
XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag).getElementDescriptor(SHIP_TO, null);
XmlElementDescriptor[] elements = elementDescriptor.getElementsDescriptors(tag);
assertEquals(5, elements.length);
assertEquals("name", elements[0].getName());
assertEquals("street", elements[1].getName());
assertEquals("city", elements[2].getName());
assertEquals("state", elements[3].getName());
assertEquals("zip", elements[4].getName());
final XmlTag context = tag.findFirstSubTag(elements[2].getName());
assertEquals(0, elements[2].getElementsDescriptors(context).length);
XmlAttributeDescriptor[] attributes = elementDescriptor.getAttributesDescriptors(context);
assertEquals(1, attributes.length);
assertEquals("country", attributes[0].getName());
}
public void testElementDescriptor6() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:sequence>" +
" <xsd:element name=\"shipTo\">" +
" <xsd:complexType name=\"USAddress\">" +
" <xsd:sequence>" +
" <xsd:element name=\"name\" type=\"xsd:string\"/>" +
" <xsd:element name=\"street\" type=\"xsd:string\"/>" +
" <xsd:element name=\"city\" type=\"xsd:string\"/>" +
" <xsd:element name=\"state\" type=\"xsd:string\"/>" +
" <xsd:element name=\"zip\" type=\"xsd:decimal\"/>" +
" </xsd:sequence>" +
" <xsd:attribute name=\"country\" type=\"xsd:NMTOKEN\" fixed=\"US\"/>" +
" </xsd:complexType>" +
" </xsd:element>" +
" </xsd:sequence>" +
"</xsd:complexType>" +
"</xsd:schema>");
XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag).getElementDescriptor(SHIP_TO, null);
XmlElementDescriptor[] elements = elementDescriptor.getElementsDescriptors(tag);
assertEquals(5, elements.length);
assertEquals("name", elements[0].getName());
assertEquals("street", elements[1].getName());
assertEquals("city", elements[2].getName());
assertEquals("state", elements[3].getName());
assertEquals("zip", elements[4].getName());
final XmlTag context = tag.findFirstSubTag(elements[2].getName());
assertEquals(0, elements[2].getElementsDescriptors(context).length);
XmlAttributeDescriptor[] attributes = elementDescriptor.getAttributesDescriptors(context);
assertEquals(1, attributes.length);
assertEquals("country", attributes[0].getName());
}
public void testElementDescriptor7() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\">" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:sequence>" +
" <xsd:element name=\"shipTo\">" +
" <xsd:complexType name=\"USAddress\">" +
" <xsd:sequence>" +
" <xsd:element name=\"name\" type=\"xsd:string\"/>" +
" <xsd:element name=\"street\" type=\"xsd:string\"/>" +
" <xsd:element name=\"city\" type=\"xsd:string\"/>" +
" <xsd:element name=\"state\" type=\"xsd:string\"/>" +
" <xsd:element name=\"zip\" type=\"xsd:decimal\"/>" +
" </xsd:sequence>" +
" <xsd:attribute name=\"country\" type=\"xsd:NMTOKEN\" fixed=\"US\"/>" +
" </xsd:complexType>" +
" </xsd:element>" +
" </xsd:sequence>" +
"</xsd:complexType>" +
"</xsd:element>" +
"</xsd:schema>");
XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor[] attributes = elementDescriptor.getAttributesDescriptors(tag);
assertEquals(0, attributes.length);
XmlElementDescriptor[] elements = elementDescriptor.getElementsDescriptors(tag);
assertEquals(1, elements.length);
assertEquals("shipTo", elements[0].getName());
}
public void testElementDescriptor8() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:sequence>" +
" <xsd:element ref=\"items\"/>" +
" </xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:element name=\"items\" type=\"xsd:string\"/>" +
"</xsd:schema>");
XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlElementDescriptor[] elements = elementDescriptor.getElementsDescriptors(tag);
assertEquals(1, elements.length);
assertEquals("items", elements[0].getName());
assertEquals("items", elementDescriptor.getElementDescriptor(XmlTestUtil.tag("items", getProject()), null).getName());
assertNull(elementDescriptor.getElementDescriptor(UNKNOWN_TAG, null));
}
public void testElementDescriptor9() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:sequence>" +
" <xsd:group ref=\"ddd:mainBookElements\"/>" +
" </xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:group name=\"mainBookElements\">" +
" <xsd:sequence>" +
" <xsd:element name=\"title\" type=\"nameType\"/>" +
" <xsd:element name=\"author\" type=\"nameType\"/>" +
" </xsd:sequence>" +
"</xsd:group>" +
"</xsd:schema>");
XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlElementDescriptor[] elements = elementDescriptor.getElementsDescriptors(tag);
assertEquals(2, elements.length);
assertEquals("title", elements[0].getName());
assertEquals("author", elements[1].getName());
assertEquals("title", elementDescriptor.getElementDescriptor(XmlTestUtil.tag("title", getProject()), null).getName());
assertNull(elementDescriptor.getElementDescriptor(UNKNOWN_TAG, null));
}
public void testElementDescriptor10() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:attributeGroup ref=\"ddd:bookAttributes\"/>" +
"</xsd:complexType>" +
"<xsd:attributeGroup name=\"bookAttributes\">" +
" <xsd:attribute name=\"isbn\" type=\"xs:string\" use=\"required\"/>" +
" <xsd:attribute name=\"available\" type=\"xs:string\"/>" +
"</xsd:attributeGroup>" +
"</xsd:schema>");
final XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor[] attributes = elementDescriptor.getAttributesDescriptors(tag);
assertEquals(2, attributes.length);
assertEquals("isbn", attributes[0].getName());
assertEquals("available", attributes[1].getName());
assertEquals("isbn", elementDescriptor.getAttributeDescriptor("isbn", tag).getName());
assertNull(elementDescriptor.getAttributeDescriptor("xxx", tag));
}
public void testElementDescriptor11() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:complexContent>" +
" <xsd:restriction base=\"PurchaseOrderType2\">" +
" <xsd:element name=\"shipTo2\" type=\"USAddress\"/>" +
" <xsd:element name=\"items\" type=\"Items\"/>" +
" </xsd:restriction>" +
" </xsd:complexContent>" +
"</xsd:complexType>" +
"<xsd:complexType name=\"PurchaseOrderType2\">" +
" <xsd:sequence>" +
" <xsd:element name=\"shipTo\" type=\"USAddress\"/>" +
" <xsd:element name=\"billTo\" type=\"USAddress\"/>" +
" <xsd:element name=\"items\" type=\"Items\"/>" +
" </xsd:sequence>" +
"</xsd:complexType>" +
"</xsd:schema>");
XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlElementDescriptor[] elements = elementDescriptor.getElementsDescriptors(tag);
assertEquals(4, elements.length);
assertEquals("shipTo", elements[0].getName());
assertEquals("billTo", elements[1].getName());
assertEquals("shipTo2", elements[2].getName());
assertEquals("items", elements[3].getName());
}
public void testElementDescriptor15() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:complexContent>" +
" <xsd:extension base=\"PurchaseOrderType2\">" +
" <xsd:element name=\"shipTo2\" type=\"USAddress\"/>" +
" </xsd:extension>" +
" </xsd:complexContent>" +
"</xsd:complexType>" +
"<xsd:complexType name=\"PurchaseOrderType2\">" +
" <xsd:sequence>" +
" <xsd:element name=\"shipTo\" type=\"USAddress\"/>" +
" <xsd:element name=\"billTo\" type=\"USAddress\"/>" +
" <xsd:element name=\"items\" type=\"Items\"/>" +
" </xsd:sequence>" +
"</xsd:complexType>" +
"</xsd:schema>");
XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlElementDescriptor[] elements = elementDescriptor.getElementsDescriptors(tag);
assertEquals(4, elements.length);
assertEquals("shipTo", elements[0].getName());
assertEquals("billTo", elements[1].getName());
assertEquals("items", elements[2].getName());
assertEquals("shipTo2", elements[3].getName());
}
public void testElementDescriptor12() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:complexContent>" +
" <xsd:restriction base=\"PurchaseOrderType2\">" +
" <xsd:attribute name=\"orderDate2\" type=\"xsd:date\"/>" +
" <xsd:attribute name=\"name\" type=\"xsd:date\"/>" +
" </xsd:restriction>" +
" </xsd:complexContent>" +
"</xsd:complexType>" +
"<xsd:complexType name=\"PurchaseOrderType2\">" +
" <xsd:sequence>" +
" <xsd:attribute name=\"orderDate\" type=\"xsd:date\"/>" +
" <xsd:attribute name=\"name\" type=\"xsd:string\"/>" +
" </xsd:sequence>" +
"</xsd:complexType>" +
"</xsd:schema>");
final XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor[] attributes = elementDescriptor.getAttributesDescriptors(tag);
assertEquals(3, attributes.length);
assertEquals("orderDate", attributes[0].getName());
assertEquals("orderDate2", attributes[1].getName());
assertEquals("name", attributes[2].getName());
}
public void testElementDescriptor13() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\">" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:sequence>" +
" <xsd:element ref=\"shipTo\"/>" +
" </xsd:sequence>" +
"</xsd:complexType>" +
"</xsd:element>" +
"<xsd:element name=\"shipTo\" abstract=\"true\">" +
"</xsd:schema>");
XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
final XmlElementDescriptor[] elements = elementDescriptor.getElementsDescriptors(tag);
assertEquals(0, elements.length);
}
public void testElementDescriptor14() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema targetNamespace=\"http://www.deansoft.com/AddressBook\" xmlns:ab=\"http://www.deansoft.com/AddressBook\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\">" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:sequence>" +
" <xsd:element ref=\"shipTo\"/>" +
" </xsd:sequence>" +
"</xsd:complexType>" +
"</xsd:element>" +
"<xsd:element name=\"shipTo\" abstract=\"true\">" +
" <xsd:complexType name=\"USAddress\">" +
" <xsd:attribute name=\"orderDate\" type=\"xsd:date\"/>" +
" <xsd:element name=\"items\" type=\"Items\"/>" +
" </xsd:complexType>" +
"</xsd:element>" +
"<xsd:element name=\"name\" substitutionGroup=\"ab:shipTo\"/>" +
"</xsd:schema>");
XmlTag tag = XmlTestUtil.tag("purchaseOrder", "http://www.deansoft.com/AddressBook", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
final XmlElementDescriptor[] elements = elementDescriptor.getElementsDescriptors(tag);
assertEquals(1, elements.length);
assertEquals("name", elements[0].getName());
XmlAttributeDescriptor[] attrs = elements[0].getAttributesDescriptors(tag);
assertEquals(1, attrs.length);
assertEquals("orderDate", attrs[0].getName());
XmlElementDescriptor[] element0Descriptors = elements[0].getElementsDescriptors(tag.findFirstSubTag(elements[0].getName()));
assertEquals(1, element0Descriptors.length);
assertEquals("items", element0Descriptors[0].getName());
}
public void testAttributeDescriptor1() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:attribute name=\"orderDate\" type=\"xsd:date\"/>" +
"</xsd:complexType>" +
"</xsd:schema>");
final XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor attribute = elementDescriptor.getAttributeDescriptor("orderDate", tag);
assertTrue(!attribute.isEnumerated());
assertTrue(!attribute.isFixed());
assertTrue(!attribute.isRequired());
assertNull(attribute.getDefaultValue());
}
public void testAttributeDescriptorProhibited() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:attribute name=\"orderDate\" type=\"xsd:date\" use=\"prohibited\" />" +
"</xsd:complexType>" +
"</xsd:schema>");
final XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor[] attributes = elementDescriptor.getAttributesDescriptors(tag);
assertEquals(0, attributes.length);
}
public void testAttributeDescriptorProhibited2() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:complexContent>" +
" <xsd:restriction base=\"PurchaseOrderType2\">" +
" <xsd:attribute name=\"orderDate\" type=\"xsd:date\" use=\"prohibited\"/>" +
" </xsd:restriction>" +
" </xsd:complexContent>" +
"</xsd:complexType>" +
"<xsd:complexType name=\"PurchaseOrderType2\">" +
" <xsd:sequence>" +
" <xsd:attribute name=\"orderDate\" type=\"xsd:date\"/>" +
" <xsd:attribute name=\"name\" type=\"xsd:string\"/>" +
" </xsd:sequence>" +
"</xsd:complexType>" +
"</xsd:schema>");
final XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor[] attributes = elementDescriptor.getAttributesDescriptors(tag);
assertEquals(1, attributes.length);
assertEquals("name", attributes[0].getName());
}
public void testAttributeDescriptor2() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:attribute name=\"orderDate\" type=\"xsd:date\" use=\"required\" default=\" 2002 \"/>" +
"</xsd:complexType>" +
"</xsd:schema>");
final XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor attribute = elementDescriptor.getAttributeDescriptor("orderDate", tag);
assertTrue(!attribute.isEnumerated());
assertTrue(!attribute.isFixed());
assertTrue(attribute.isRequired());
assertEquals(" 2002 ", attribute.getDefaultValue());
}
public void testAttributeDescriptor3() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:attribute name=\"orderDate\" type=\"xsd:date\" fixed=\"1 01 2001\"/>" +
"</xsd:complexType>" +
"</xsd:schema>");
final XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor attribute = elementDescriptor.getAttributeDescriptor("orderDate", tag);
assertTrue(!attribute.isEnumerated());
assertTrue(attribute.isFixed());
assertTrue(!attribute.isRequired());
assertEquals("1 01 2001", attribute.getDefaultValue());
}
public void testAttributeDescriptor4() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:attribute ref=\"orderDate\" use=\"required\"/>" +
"</xsd:complexType>" +
" <xsd:attribute name=\"orderDate\" type=\"xsd:date\" fixed=\"1 01 2001\"/>" +
"</xsd:schema>");
final XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
XmlAttributeDescriptor attribute = elementDescriptor.getAttributeDescriptor("orderDate", tag);
assertNotNull(attribute);
assertTrue(!attribute.isEnumerated());
assertTrue(attribute.isFixed());
assertTrue(attribute.isRequired());
assertEquals("1 01 2001", attribute.getDefaultValue());
}
public void testNamespace1() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" +
"<xs:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xs:element name=\"comment\" type=\"xs:string\"/>" +
"</xs:schema>");
assertNotNull(NSDescriptor);
assertNotNull(NSDescriptor.getElementDescriptor(XmlTestUtil.tag("purchaseOrder", getProject())));
assertNotNull(NSDescriptor.getElementDescriptor(XmlTestUtil.tag("comment", getProject())));
assertNull(NSDescriptor.getElementDescriptor(UNKNOWN_TAG));
}
public void testNamespace2() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema targetNamespace=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" >" +
"<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<xsd:complexType name=\"PurchaseOrderType\">" +
" <xsd:sequence>" +
" <xsd:element ref=\"xsd:items\"/>" +
" </xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:element name=\"items\" type=\"xsd:string\"/>" +
"</xsd:schema>");
XmlTag tag = XmlTestUtil.tag("purchaseOrder", "http://www.w3.org/2001/XMLSchema", getProject());
XmlElementDescriptorImpl elementDescriptor = (XmlElementDescriptorImpl)NSDescriptor.getElementDescriptor(tag);
XmlElementDescriptor[] elements = elementDescriptor.getElementsDescriptors(tag);
assertEquals(1, elements.length);
assertEquals("items", elements[0].getName());
assertEquals("items", elementDescriptor.getElementDescriptor("items").getName());
assertNull(elementDescriptor.getElementDescriptor("xxx"));
}
public void testNamespace3() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xs:schema xmlns=\"http://www.w3.org/2001/XMLSchema\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" +
"<xs:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
"<element name=\"comment\" type=\"xs:string\"/>" +
"</xs:schema>");
assertNotNull(NSDescriptor);
assertNotNull(NSDescriptor.getElementDescriptor(XmlTestUtil.tag("purchaseOrder", "http://www.w3.org/2001/XMLSchema", getProject())));
assertNotNull(NSDescriptor.getElementDescriptor(XmlTestUtil.tag("comment", "http://www.w3.org/2001/XMLSchema", getProject())));
assertNull(NSDescriptor.getElementDescriptor(UNKNOWN_TAG));
}
//public void testAny1() throws Exception {
// XmlDocumentDescriptor documentDescriptor = createDescriptorImpl(
// "<xsd:schema targetNamespace=\"http://foo\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" >" +
// " <xsd:element name=\"root\">" +
// " <xsd:complexType>" +
// " <xsd:sequence minOccurs=\"1\" maxOccurs=\"1\">" +
// " <xsd:any namespace=\"##other\" minOccurs=\"0\" maxOccurs=\"unbounded\" processContents=\"skip\"/>" +
// " </xsd:sequence>" +
// " </xsd:complexType>" +
// " </xsd:element>" +
// "</xsd:schema>"
// );
//
// XmlFile xmlFile = (XmlFile)createFile("file.xml",
// "<root xmlns=\"http://foo\">" +
// " <a:a xmlns:a=\"http://bar\" />" +
// "</root>"
// );
//
// XmlElementDescriptor rootDescriptor = documentDescriptor.getElementDescriptor(xmlFile.saveToString().getRootTag());
// assertNotNull(rootDescriptor);
//
// XmlTag aTag = xmlFile.saveToString().getRootTag().findSubTag("a:a");
// assertNotNull(aTag);
// XmlElementDescriptor aDescriptor = documentDescriptor.getElementDescriptor(aTag);
// assertNotNull(aDescriptor);
//}
public void testAny2() throws Exception {
PsiFile dtdFile = createFile("test.xml", "<xsd:schema targetNamespace=\"http://foo\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" >" +
" <xsd:element name=\"root\">" +
" <xsd:complexType>" +
" <xsd:sequence minOccurs=\"1\" maxOccurs=\"1\">" +
" <xsd:any namespace=\"##other\" minOccurs=\"0\" maxOccurs=\"unbounded\" processContents=\"skip\"/>" +
" </xsd:sequence>" +
" </xsd:complexType>" +
" </xsd:element>" +
"</xsd:schema>");
XmlNSDescriptor NSDescriptor = new XmlNSDescriptorImpl((XmlFile)dtdFile);
XmlFile xmlFile = (XmlFile)createFile("file.xml",
"<foo:root xmlns:foo=\"http://foo\">" +
" <foo:a xmlns:a=\"http://bar\" />" +
"</foo:root>"
);
XmlElementDescriptor rootDescriptor = NSDescriptor.getElementDescriptor(xmlFile.getDocument().getRootTag());
assertNotNull(rootDescriptor);
XmlTag aTag = xmlFile.getDocument().getRootTag().findFirstSubTag("foo:a");
assertNotNull(aTag);
//XmlElementDescriptor aDescriptor = NSDescriptor.getElementDescriptor(aTag);
//assertNull(aDescriptor);
}
public void testAny3() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema targetNamespace=\"http://foo\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" >" +
" <xsd:element name=\"root\">" +
" <xsd:complexType>" +
" <xsd:anyAttribute namespace=\"##other\" processContents=\"skip\"/>" +
" </xsd:complexType>" +
" </xsd:element>" +
"</xsd:schema>"
);
XmlFile xmlFile = (XmlFile)createFile("file.xml",
"<root xmlns=\"http://foo\" y:a=\"1\">" +
"</root>"
);
final XmlTag rootTag = xmlFile.getDocument().getRootTag();
XmlElementDescriptor rootDescriptor = NSDescriptor.getElementDescriptor(rootTag);
assertNotNull(rootDescriptor);
XmlAttribute attribute = rootTag.getAttribute("y:a", XmlUtil.EMPTY_URI);
assertNotNull(attribute);
XmlAttributeDescriptor aDescriptor = rootDescriptor.getAttributeDescriptor("y:a", rootTag);
assertNotNull(aDescriptor);
}
public void testAny4() throws Exception {
XmlNSDescriptor NSDescriptor = createDescriptor(
"<xsd:schema targetNamespace=\"http://foo\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" >" +
" <xsd:element name=\"root\">" +
" <xsd:complexType>" +
" <xsd:anyAttribute namespace=\"##other\" processContents=\"skip\"/>" +
" </xsd:complexType>" +
" </xsd:element>" +
"</xsd:schema>"
);
XmlFile xmlFile = (XmlFile)createFile("file.xml",
"<root xmlns=\"http://foo\" a=\"1\">" +
"</root>"
);
final XmlTag rootTag = xmlFile.getDocument().getRootTag();
XmlElementDescriptor rootDescriptor = NSDescriptor.getElementDescriptor(rootTag);
assertNotNull(rootDescriptor);
XmlAttribute attribute = rootTag.getAttribute("a", XmlUtil.EMPTY_URI);
assertNotNull(attribute);
XmlAttributeDescriptor aDescriptor = rootDescriptor.getAttributeDescriptor("a", rootTag);
assertNull(aDescriptor);
attribute = rootTag.getAttribute("a", "http://foo");
assertNull(attribute);
attribute = rootTag.getAttribute("a", XmlUtil.ANT_URI);
assertNull(attribute);
}
private static XmlNSDescriptor createDescriptor(@NonNls String dtdText) throws Exception {
PsiFile dtdFile = createFile("test.xml", dtdText);
return new XmlNSDescriptorImpl((XmlFile)dtdFile);
}
}
@@ -0,0 +1,960 @@
package com.intellij.codeInsight;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.xml.*;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.LocalTimeCounter;
import com.intellij.xml.util.XmlTagUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Arrays;
/**
* @author peter
*/
@SuppressWarnings({"ConstantConditions", "EmptyCatchBlock"})
public class XmlTagTest extends LightCodeInsightTestCase {
private static XmlTag createTag(String value) throws IncorrectOperationException {
return XmlElementFactory.getInstance(getProject()).createTagFromText("<foo>" + value + "</foo>");
}
public void testGetTextValue() throws Throwable {
assertEquals("bar", createTag("bar").getValue().getText());
}
public void testCharRefs() throws Throwable {
String[] names = XmlTagUtil.getCharacterEntityNames();
for (String name : names) {
XmlTag tag = createTag("foo&" + name + ";bar");
assertEquals("foo" + XmlTagUtil.getCharacterByEntityName(name) + "bar", tag.getValue().getTrimmedText());
}
}
public void testLocalNSDeclarations() throws Throwable {
final XmlTag tag = XmlElementFactory.getInstance(getProject()).createTagFromText("<foo xmlns='aaa' xmlns:a='bbbb'/>");
final Object[] nsPrefixes = ArrayUtil.toObjectArray(tag.getLocalNamespaceDeclarations().keySet());
Arrays.sort(nsPrefixes);
assertEquals(2, nsPrefixes.length);
assertEquals("a",nsPrefixes[1]);
assertEquals("",nsPrefixes[0]);
}
public void testCDATA() throws Throwable {
XmlTag tag = createTag("foo<![CDATA[<>&'\"]]>bar");
assertEquals("foo<>&'\"bar", tag.getValue().getTrimmedText());
}
public void testWhitespacesInAttributes() throws Throwable {
XmlTag tag = XmlElementFactory.getInstance(getProject()).createTagFromText("<a c=d>b</a>");
assertEquals("b", tag.getValue().getText());
}
public void testCreateChildTag() throws Throwable {
final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<a xmlns=\"aNamespace\"/>");
final XmlTag childTag = rootTag.createChildTag("b", "bNamespace", null, true);
assertEquals("bNamespace", childTag.getNamespace());
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
XmlTag beanTag = (XmlTag)rootTag.add(childTag);
assertEquals("bNamespace", beanTag.getNamespace());
}
});
}
public void testDeleteTag() throws Throwable {
XmlTag aTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<a><b/> </a>");
final XmlTag bTag = aTag.findFirstSubTag("b");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
bTag.delete();
}
});
assertEquals(0, aTag.getSubTags().length);
}
public void testReplaceTag() throws Throwable {
final XmlTag aTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<a><b/></a>");
final XmlTag bTag = aTag.findFirstSubTag("b");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
PsiElement cTag = bTag.replace(XmlElementFactory.getInstance(getProject()).createTagFromText("<c/>"));
assertEquals(1, aTag.getSubTags().length);
assertEquals(cTag, aTag.getSubTags()[0]);
}
});
}
public void testAddText() throws Exception{
final XmlElementFactory elementFactory = XmlElementFactory.getInstance(getProject());
final XmlTag aTag = elementFactory.createTagFromText("<a>1</a>");
final XmlText displayText = elementFactory.createDisplayText("2");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
final PsiElement psiElement = aTag.addAfter(displayText, aTag.getValue().getChildren()[0]);
assertEquals(psiElement.getContainingFile(), aTag.getContainingFile());
}
});
}
public void testWhitespaceInsideTag() throws Exception {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
XmlElementFactory.getInstance(getProject()).createTagFromText("<p/>").getValue().setText("\n");
}
});
}
public void testSetAttribute_ForXhtml() throws Exception {
XmlFile xhtmlFile = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("dummy.xhtml", "<html/>");
final XmlTag rootTag = xhtmlFile.getDocument().getRootTag();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
rootTag.setAttribute("foo", "bar");
}
});
assertEquals(1, rootTag.getAttributes().length);
assertEquals("bar", rootTag.getAttributeValue("foo"));
assertEquals("foo", rootTag.getAttributes()[0].getName());
}
public void testSetAttribute() throws Exception {
final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<html/>");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
rootTag.setAttribute("foo", "bar");
}
});
assertEquals(1, rootTag.getAttributes().length);
assertEquals("bar", rootTag.getAttributeValue("foo"));
assertEquals("foo", rootTag.getAttributes()[0].getName());
assertEquals("<html foo=\"bar\"/>", rootTag.getText());
}
public void testSetAttributeWithQuotes() throws Exception {
final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<html/>");
final String value = "a \"b\" c";
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
rootTag.setAttribute("foo", value);
}
});
assertEquals(1, rootTag.getAttributes().length);
assertEquals(value, rootTag.getAttributeValue("foo"));
assertEquals("foo", rootTag.getAttributes()[0].getName());
assertEquals("<html foo='" + value + "'/>", rootTag.getText());
}
public void testSetAttributeWithQuotes2() throws Exception {
final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<html/>");
final String value = "'a \"b\" c'";
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
rootTag.setAttribute("foo", value);
}
});
final String expected = value.replaceAll("\"", "&quot;");
assertEquals(1, rootTag.getAttributes().length);
assertEquals(expected, rootTag.getAttributeValue("foo"));
assertEquals(value, rootTag.getAttribute("foo").getDisplayValue());
assertEquals("foo", rootTag.getAttributes()[0].getName());
assertEquals("<html foo=\"" + expected + "\"/>", rootTag.getText());
}
public void testSetAttributeUpdateText() throws Exception {
final String value = "a \"b\" c";
final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<html foo='" + value + "'/>");
assertEquals(1, rootTag.getAttributes().length);
assertEquals(value, rootTag.getAttributeValue("foo"));
final XmlAttribute foo = rootTag.getAttribute("foo");
final String text = foo.getValueElement().getText();
assertEquals("'" + value + "'", text);
((PsiLanguageInjectionHost)foo.getValueElement()).updateText(text);
assertEquals("<html foo='" + value + "'/>", rootTag.getText());
}
public void testSetAttributeWithNamespaces() throws Exception {
final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<ns:tag xmlns:ns=\"xxx\"/>");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
rootTag.setAttribute("foo", "", "bar");
}
});
assertEquals(2, rootTag.getAttributes().length);
assertEquals("bar", rootTag.getAttributeValue("foo"));
assertEquals("foo", rootTag.getAttributes()[1].getName());
assertEquals("<ns:tag xmlns:ns=\"xxx\" foo=\"bar\"/>", rootTag.getText());
}
public void testTextEdit1() throws Exception {
final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<html>aaa</html>");
final XmlText xmlText = rootTag.getValue().getTextElements()[0];
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
xmlText.removeText(0, 3);
}
});
assertEquals("<html></html>", rootTag.getText());
}
public void testTextEdit2() throws Exception {
final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<html>a&lt;a</html>");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
rootTag.getValue().getTextElements()[0].removeText(0, 3);
}
});
assertEquals("<html></html>", rootTag.getText());
}
public void testTextEdit3() throws Exception {
final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<html>a&lt;a</html>");
final XmlText xmlText = rootTag.getValue().getTextElements()[0];
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
xmlText.removeText(1, 2);
}
});
assertEquals(1, xmlText.getChildren().length);
assertEquals("<html>aa</html>", rootTag.getText());
}
public void testTextEdit4() throws Exception {
final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<html>aaa</html>");
final XmlText xmlText = rootTag.getValue().getTextElements()[0];
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
xmlText.removeText(1, 2);
}
});
assertEquals(1, xmlText.getChildren().length);
assertEquals("<html>aa</html>", rootTag.getText());
}
public void testTextEdit5() throws Exception {
final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<html><x>xxx</x>\n<y>yyy</y></html>");
final XmlTag y = rootTag.findFirstSubTag("y");
final PsiFile file = y.getContainingFile();
String text = y.getValue().getText();
TextRange textRange = y.getValue().getTextRange();
assertEquals(text, textRange.substring(file.getText()));
new WriteCommandAction(getProject(), file) {
@Override
protected void run(final Result result) throws Throwable {
CodeStyleManager.getInstance(getProject()).adjustLineIndent(file, y.getTextOffset());
}
}.execute();
text = y.getValue().getText();
textRange = y.getValue().getTextRange();
assertEquals(text, textRange.substring(file.getText()));
}
public void testTextEdit6() throws Exception {
final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<html>a<b>1</b>c</html>");
final XmlTag xmlTag = rootTag.findFirstSubTag("b");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
xmlTag.delete();
}
});
assertEquals("<html>ac</html>", rootTag.getText());
}
public void testBrace() throws Exception {
final XmlTag tagFromText = XmlElementFactory.getInstance(getProject()).createTagFromText("<a/>");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
tagFromText.getValue().setText("<");
}
});
assertEquals("<", tagFromText.getValue().getTextElements()[0].getValue());
}
public void testEmptyTextRange() throws Exception {
final String text = "<a></a>";
final String name = "test.xhtml";
XmlTag rootTag = createTag(name, text);
TextRange textRange = rootTag.getValue().getTextRange();
assertEquals(3, textRange.getStartOffset());
assertEquals(3, textRange.getEndOffset());
}
public void testDeleteTagBetweenText() throws Exception {
final XmlTag tag = createTag("foo.xhtml", "<p>a<div/>b</p>");
final XmlTag div = tag.getSubTags()[0];
new WriteCommandAction(getProject(), tag.getContainingFile()) {
@Override
protected void run(final Result result) throws Throwable {
div.delete();
}
}.execute();
assertEquals("<p>ab</p>", tag.getText());
}
private static XmlTag createTag(final String name, final String text) {
final XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject())
.createFileFromText(name, StdFileTypes.XML, text, LocalTimeCounter.currentTime(), true);
return file.getDocument().getRootTag();
}
// tests whether rangemarker gets changed when texts are merged, passes
public void testRangeMarker1() throws IOException, IncorrectOperationException {
final XmlFile file = (XmlFile)createFile("file.xhtml", "<a>1234<b></b>567</a>");
final XmlTag root = file.getDocument().getRootTag();
final XmlTag tag = root.findFirstSubTag("b");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
final int offset = tag.getTextOffset();
Document document = PsiDocumentManager.getInstance(getProject()).getDocument(root.getContainingFile());
RangeMarker marker = document.createRangeMarker(offset - 3, offset);
tag.delete();
assertEquals(4, marker.getStartOffset());
assertEquals(7, marker.getEndOffset());
}
}, "", null);
}
});
}
// this one fails, the difference is that we do some manipulations before: move "234" before the tag
public void testRangeMarker2() throws IOException, IncorrectOperationException {
final XmlTag root = createTag("file.xhtml", "<a>1<b>234</b>567</a>");
final XmlTag tag = root.findFirstSubTag("b");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
Document document = PsiDocumentManager.getInstance(getProject()).getDocument(root.getContainingFile());
XmlTagChild child = tag.getValue().getChildren()[0];
assertTrue(child instanceof XmlText && child.getText().equals("234"));
try {
tag.getParent().addBefore(child, tag);
assertEquals(7, tag.getTextOffset());
RangeMarker marker = document.createRangeMarker(4, 7);
tag.delete();
assertEquals(4, marker.getStartOffset());
assertEquals(7, marker.getEndOffset());
}
catch (IncorrectOperationException e) {
}
}
}, "", null);
}
});
}
// the previous test relveals one problem with text merge, "234" in fact is not merged with "1"
public void test3() throws IOException, IncorrectOperationException {
final XmlTag root = XmlElementFactory.getInstance(getProject()).createTagFromText("<a>1<b>234</b>456</a>");
final XmlTag tag = root.findFirstSubTag("b");
final XmlTagChild child = tag.getValue().getChildren()[0];
assertTrue(child instanceof XmlText && child.getText().equals("234"));
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
assertNotNull(tag.getParent().addBefore(child, tag));
tag.delete();
}
});
assertEquals(1, root.getValue().getChildren().length);
assertEquals("1234456", root.getValue().getChildren()[0].getText());
}
public void test3XHTML() throws IOException, IncorrectOperationException {
final XmlTag root = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("<a>1<b>234</b>456</a>");
final XmlTag tag = root.findFirstSubTag("b");
final XmlTagChild child = tag.getValue().getChildren()[0];
assertTrue(child instanceof XmlText && child.getText().equals("234"));
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
assertNotNull(tag.getParent().addBefore(child, tag));
tag.delete();
}
});
assertEquals(1, root.getValue().getChildren().length);
assertEquals("1234456", root.getValue().getChildren()[0].getText());
}
public void testDisplayText() throws Throwable {
final XmlTag tag = XmlElementFactory.getInstance(getProject()).createTagFromText(" <foo/>");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
tag.add(XmlElementFactory.getInstance(getProject()).createDisplayText("aaa\nbbb"));
}
});
assertEquals("aaa\nbbb", tag.getValue().getTextElements()[0].getValue());
}
public void testXHTMLAddBefore1() throws Exception {
final XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("test.xhtml",
"<a>a <b>123</b> c</a>");
final XmlTag tagB = file.getDocument().getRootTag().findFirstSubTag("b");
final XmlTagChild[] tagElements = tagB.getValue().getChildren();
final PsiElement parent = tagB.getParent();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
PsiElement first = parent.addBefore(tagElements[0], tagB);
assertNotNull(first);
}
});
}
public void testXHTMLSetAttribute1() throws Exception {
new WriteCommandAction.Simple(getProject()) {
@Override
protected void run() throws Throwable {
final XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("test.xhtml", "<a/>");
final XmlTag tagB = file.getDocument().getRootTag();
tagB.setAttribute("a", "");
assertEquals("<a a=\"\"/>", tagB.getText());
tagB.setAttribute("b", "");
assertEquals("<a a=\"\" b=\"\"/>", tagB.getText());
tagB.setAttribute("c", "");
assertEquals("<a a=\"\" b=\"\" c=\"\"/>", tagB.getText());
tagB.getAttributes()[1].delete();
assertEquals("<a a=\"\" c=\"\"/>", tagB.getText());
}
}.execute().throwException();
}
public void testXHTMLNbsp1() throws Exception {
final XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("test.xhtml", "<a>&nbsp;</a>");
final XmlTag tagB = file.getDocument().getRootTag();
assertEquals(tagB.getValue().getTextElements().length, 1);
assertEquals(tagB.getValue().getTextElements()[0].getValue(), "\u00a0");
}
public void testDeleteTagWithMultilineWhitespace1() throws Exception {
final XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("test.xml",
"<a>\n <a/>\n</a>");
final XmlTag tagB = file.getDocument().getRootTag();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
tagB.getSubTags()[0].delete();
}
});
assertEquals("<a>\n </a>", tagB.getText());
}
public void testDeleteTagWithMultilineWhitespace2() throws Exception {
final XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject())
.createFileFromText("test.xml", "<a>\n <a>\n <b>\n hasgdgasjdgasdg asgdjhasgd</b>\n </a>\n</a>");
final XmlTag tagB = file.getDocument().getRootTag();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
tagB.getSubTags()[0].getSubTags()[0].delete();
}
});
assertEquals("<a>\n <a>\n </a>\n</a>", tagB.getText());
}
public void testXHTMLRangeMarkers2() throws Exception {
XmlTag tag = createTag("file.xhtml", "<a>xyz</a>");
PsiFile psiFile = tag.getContainingFile();
Document document = PsiDocumentManager.getInstance(psiFile.getProject()).getDocument(psiFile);
RangeMarker rangeMarker = document.createRangeMarker(5, 5);
final XmlText text = (XmlText) tag.getValue().getChildren()[0];
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
try{
text.removeText(2, 3);
}
catch(IncorrectOperationException ioe){}
}
}, "", null, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION);
}
});
assertEquals(5, rangeMarker.getStartOffset());
assertEquals(5, rangeMarker.getEndOffset());
}
public void testXHTMLTextInsert() throws Exception {
final XmlTag tag = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("<a>xyz</a>");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
tag.getValue().getTextElements()[0].insertText("<", 1);
}
});
assertEquals("<a>x&lt;yz</a>", tag.getText());
}
public void testSimpleTextInsertion() throws Throwable {
doTestSimpleInsertion("xyz", "a");
doTestSimpleInsertion(" xyz", "a");
doTestSimpleInsertion("x yz", "a");
doTestSimpleInsertion("xy z", "a");
doTestSimpleInsertion("xyz ", "a");
doTestSimpleInsertion(" xyz ", "a");
doTestSimpleInsertion(" x y z ", "a");
}
public void testWhitespaceTextInsertion() throws Throwable {
doTestSimpleInsertion("xyz", " ");
}
public void testSimpleTextDeletion() throws Throwable {
doTestSimpleDeletion("xyz");
doTestSimpleDeletion(" xyz");
doTestSimpleDeletion("x yz");
doTestSimpleDeletion("xy z");
doTestSimpleDeletion("xyz ");
doTestSimpleDeletion(" xyz ");
doTestSimpleDeletion(" x y z ");
}
public void testWhitespaceDeletion() throws Throwable {
doTestSimpleDeletion(" xyz");
doTestSimpleDeletion("x yz");
doTestSimpleDeletion("xy z");
doTestSimpleDeletion("xyz ");
doTestSimpleDeletion(" xyz ");
doTestSimpleDeletion(" x y z ");
}
private static void doTestSimpleDeletion(final String text) throws IncorrectOperationException {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
for (int i = 0; i < text.length(); i++) {
for (int j = i; j < text.length(); j++) {
XmlTag tag = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("<a>" + text + "</a>");
final PsiElement[] children = tag.getValue().getTextElements();
assertEquals(1, children.length);
final XmlText xmlText = (XmlText)children[0];
assertEquals(text, xmlText.getText());
xmlText.removeText(i, j);
final StringBuffer expected = new StringBuffer(text);
expected.delete(i, j);
assertEquals(expected.toString(), xmlText.getValue());
}
}
}
});
}
private static void doTestSimpleInsertion(final String text, final String textToInsert) throws IncorrectOperationException {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
for (int i = 0; i <= text.length(); i++) {
XmlTag tag = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("<a>" + text + "</a>");
final PsiElement[] children = tag.getValue().getTextElements();
assertEquals(1, children.length);
final XmlText xmlText = (XmlText)children[0];
assertEquals(text, xmlText.getValue());
xmlText.insertText(textToInsert, i);
final StringBuffer expected = new StringBuffer(text);
expected.insert(i, textToInsert);
assertEquals(expected.toString(), xmlText.getValue());
}
}
});
}
public void testEscapedInsertion() throws Throwable {
doTestEscapedInsertion("xyz", "&");
doTestEscapedInsertion("xyz", "&&");
doTestEscapedInsertion("xyz", "&x&");
doTestEscapedInsertion("&xyz", "a");
doTestEscapedInsertion("&xyz", " ");
doTestEscapedInsertion("x&yz", "a");
doTestEscapedInsertion("x&yz", " ");
doTestEscapedInsertion("xy&z", "a");
doTestEscapedInsertion("xy&z", " ");
doTestEscapedInsertion("xyz&", "a");
doTestEscapedInsertion("xyz&", " ");
doTestEscapedInsertion("&x&y&z&", "a");
doTestEscapedInsertion(" x&y&z&", "a");
doTestEscapedInsertion(" x y&z&", "a");
doTestEscapedInsertion("&x y&z&", "a");
doTestEscapedInsertion("&x y&z ", "a");
doTestEscapedInsertion("&x&y&z&", "<");
doTestEscapedInsertion("&x&y&z&", ">");
doTestEscapedInsertion("_xyz", "a");
doTestEscapedInsertion("x_yz", "a");
doTestEscapedInsertion("xy_z", "a");
doTestEscapedInsertion("xyz_", "a");
doTestEscapedInsertion("_xyz_", "a");
doTestEscapedInsertion("_x_y_z_", "a");
}
public static void notestEscapedDeletion() throws Throwable {
doTestEscapedDeletion("&");
doTestEscapedDeletion("&&");
doTestEscapedDeletion(" &&");
doTestEscapedDeletion(" & &");
doTestEscapedDeletion(" & & ");
doTestEscapedDeletion(" && ");
doTestEscapedDeletion("&& ");
doTestEscapedDeletion("& ");
doTestEscapedDeletion(" ");
doTestEscapedDeletion("&abc");
doTestEscapedDeletion("a&bc");
doTestEscapedDeletion("ab&c");
doTestEscapedDeletion("abc&");
doTestEscapedDeletion(" &abc");
doTestEscapedDeletion("a &bc");
doTestEscapedDeletion("ab &c");
doTestEscapedDeletion("abc &");
doTestEscapedDeletion("& abc");
doTestEscapedDeletion("a& bc");
doTestEscapedDeletion("ab& c");
doTestEscapedDeletion("abc& ");
}
private static void doTestEscapedInsertion(final String text, final String textToInsert) throws IncorrectOperationException {
String tagText = toEscapedText(text);
for (int i = 0; i <= text.length(); i++) {
XmlTag tag = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("<a>" + tagText + "</a>");
final PsiElement[] children = tag.getValue().getTextElements();
assertEquals(1, children.length);
final XmlText xmlText = (XmlText)children[0];
assertEquals(tagText, xmlText.getText());
xmlText.insertText(textToInsert, i);
final StringBuffer expectedDisplay = new StringBuffer(text.replace('_', '\u00a0'));
expectedDisplay.insert(i, textToInsert);
assertEquals(expectedDisplay.toString(), xmlText.getValue());
// final String expectedText = toEscapedText(expectedDisplay.toString());
// assertEquals(expectedText, xmlText.getText());
}
}
private static void doTestEscapedDeletion(final String text) throws IncorrectOperationException {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
String tagText = toEscapedText(text);
for (int i = 0; i < text.length(); i++) {
for (int j = i; j < text.length(); j++) {
XmlTag tag = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("<a>" + tagText + "</a>");
final PsiElement[] children = tag.getValue().getTextElements();
assertEquals(1, children.length);
final XmlText xmlText = (XmlText)children[0];
assertEquals(tagText, xmlText.getText());
xmlText.removeText(i, j);
final StringBuffer expectedDisplay = new StringBuffer(text.replace('_', ' '));
expectedDisplay.delete(i, j);
assertEquals(expectedDisplay.toString(), xmlText.getValue());
final String expectedText = toEscapedText(expectedDisplay.toString());
assertEquals(expectedText, xmlText.getText());
}
}
}
});
}
public void testWhitespacesInEmptyXHTMLTag() throws Exception{
final XmlTag tag = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("<a> <b/> </a>");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
tag.findFirstSubTag("b").delete();
}
});
assertEquals("<a> </a>", tag.getText());
}
public void test2() throws Exception {
XmlFile file = (XmlFile)createFile("file.xml", "<a>x y</a>");
XmlTag tag = file.getDocument().getRootTag();
final XmlText xmlText = tag.getValue().getTextElements()[0];
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
try {
xmlText.insertText("z", 1);
}
catch (IncorrectOperationException e) {
throw new RuntimeException(e);
}
}
}, "", null, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION);
}
});
assertEquals("<a>xz y</a>", tag.getText());
}
private static String toDisplay(String text) {
text = text.replaceAll("&lt;", "<");
text = text.replaceAll("&gt;", ">");
text = text.replaceAll("&amp;", "&");
text = text.replaceAll("&apos;", "'");
text = text.replaceAll("&quot;", "\"");
text = text.replaceAll("<!\\[CDATA\\[", "");
text = text.replaceAll("\\]\\]>", "");
return text.replaceAll("&nbsp;", "_");
}
private static String toEscapedText(String original) {
String text = original.replaceAll("<", "&lt;");
text = text.replaceAll(">", "&gt;");
text = text.replaceAll("&", "&amp;");
text = text.replaceAll("'", "&apos;");
text = text.replaceAll("\"", "&quot;");
text = text.replaceAll("_", "&nbsp;");
assertEquals(original, toDisplay(text));
return text;
}
public void testCoordinateMappingConsistent() throws Exception {
doCoordinateMappingConsistentFromDisplayText("abc");
doCoordinateMappingConsistentFromDisplayText(" abc");
doCoordinateMappingConsistentFromDisplayText(" a bc");
doCoordinateMappingConsistentFromDisplayText(" a b c");
doCoordinateMappingConsistentFromDisplayText(" a b c ");
doCoordinateMappingConsistentFromDisplayText(" ab c ");
doCoordinateMappingConsistentFromDisplayText(" abc ");
doCoordinateMappingConsistentFromDisplayText("abc ");
doCoordinateMappingConsistentFromDisplayText(" ");
doCoordinateMappingConsistentFromDisplayText("&");
doCoordinateMappingConsistentFromDisplayText("&abc");
doCoordinateMappingConsistentFromDisplayText(" &abc");
doCoordinateMappingConsistentFromDisplayText(" a& bc");
doCoordinateMappingConsistentFromDisplayText(" a &b c");
doCoordinateMappingConsistentFromDisplayText(" a b& c ");
doCoordinateMappingConsistentFromDisplayText(" ab c& ");
doCoordinateMappingConsistentFromDisplayText(" ab&c ");
doCoordinateMappingConsistentFromDisplayText("abc &");
doCoordinateMappingConsistentFromDisplayText("abc&");
doCoordinateMappingConsistentFromDisplayText("ab&c&");
doCoordinateMappingConsistentFromDisplayText("ab&c");
doCoordinateMappingConsistentFromDisplayText("a&b&c");
doCoordinateMappingConsistentFromEscapedText("<![CDATA[ ]]>");
doCoordinateMappingConsistentFromEscapedText("<![CDATA[x]]>");
doCoordinateMappingConsistentFromEscapedText("xxx<![CDATA[x]]>");
doCoordinateMappingConsistentFromEscapedText("xxx<![CDATA[x]]>xxx");
doCoordinateMappingConsistentFromEscapedText("xxx&amp;<![CDATA[x]]>xxx");
doCoordinateMappingConsistentFromEscapedText("xxx&amp;<![CDATA[x]]>&amp;xxx");
doCoordinateMappingConsistentFromEscapedText("xxx<![CDATA[x]]>&amp;xxx");
doCoordinateMappingConsistentFromEscapedText("xxx<![CDATA[xas]]>&amp;xxx");
doCoordinateMappingConsistentFromEscapedText("xxx<![CDATA[xa>s]]>&amp;xxx");
doCoordinateMappingConsistentFromEscapedText("xxx<![CDATA[x<a>s]]>&amp;xxx");
}
public void testNBSP() throws Exception {
final XmlTag tagA = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("<a>1<b>&nbsp;</b></a>");
final XmlTag tagB = tagA.findFirstSubTag("b");
final XmlTagChild nbsp = tagB.getValue().getChildren()[0];
assertEquals("&nbsp;", nbsp.getText());
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
tagA.addBefore(nbsp.copy(), tagB);
}
});
XmlTagChild nbsp1 = tagA.getValue().getChildren()[0];
assertEquals("1&nbsp;", nbsp1.getText());
}
private static void doCoordinateMappingConsistentFromDisplayText(final String text) throws IncorrectOperationException {
doCoordinateMappingConsistentFromEscapedText(toEscapedText(text));
}
private static void doCoordinateMappingConsistentFromEscapedText(final String tagText) throws IncorrectOperationException {
String text = toDisplay(tagText);
XmlTag tag = XmlElementFactory.getInstance(getProject()).createTagFromText("<a>" + tagText + "</a>");
final PsiElement[] children = tag.getValue().getTextElements();
assertEquals(1, children.length);
final XmlText xmlText = (XmlText)children[0];
assertEquals(tagText, xmlText.getText());
for (int i = 0; i <= text.length(); i++) {
final int physical = xmlText.displayToPhysical(i);
final int display = xmlText.physicalToDisplay(physical);
assertEquals("Coords mapping failed for: '" + tagText + "' - " + physical, display, i);
}
assertEquals("Coords mapping failed for: '" + tagText + "'", 0, xmlText.physicalToDisplay(0));
assertEquals(tagText.length(), xmlText.displayToPhysical(text.length()));
assertEquals(text.length(), xmlText.physicalToDisplay(tagText.length()));
}
public void testStrangeCharactesInText() throws Throwable {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
XmlElementFactory.getInstance(getProject()).createTagFromText("<a/>").getValue().setText("@#$%@$%$${${''}");
}
});
}
public void testPsiToDocumentSynchronizationFailed() throws Throwable {
String text = "<wpd><methods> </methods></wpd>";
final File tempFile = FileUtil.createTempFile("idea-test", ".xml");
tempFile.createNewFile();
final FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
fileOutputStream.write(text.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
@SuppressWarnings({"ConstantConditions"})
public void run() {
VirtualFileManager.getInstance().refresh(false);
XmlFile file ;//createTemporaryFile("wpd.xml", text));
try {
file = (XmlFile)getPsiManager().findFile(VfsUtil.findFileByURL(tempFile.toURL()));
}
catch (MalformedURLException e) {
throw new RuntimeException(e);
}
final XmlTag methodTag = file.getDocument().getRootTag().findFirstSubTag("methods");
try {
methodTag.add(XmlElementFactory.getInstance(getProject()).createTagFromText("<method/>"));
}
catch (IncorrectOperationException e) {
throw new RuntimeException(e);
}
}
}, "", null, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION);
}
});
}
public void testXmlFormattingException() throws Throwable {
final XmlTag tag = XmlElementFactory.getInstance(getProject()).createTagFromText("<foo>bar</foo>");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
tag.add(XmlElementFactory.getInstance(getProject()).createTagFromText("<bar/>"));
}
});
}
public void testSetNamespace() throws Exception {
XmlFile xhtmlFile = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("dummy.xml",
"<html><body/></html>");
final XmlTag rootTag = xhtmlFile.getDocument().getRootTag();
rootTag.getSubTags()[0].getNamespace(); // fill the cache
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
rootTag.setAttribute("xmlns", "http://www.ru");
}
});
assertEquals("http://www.ru", rootTag.getSubTags()[0].getNamespace());
}
public void testInsert() throws Exception {
String html = "<html><head /><body><hr /></body>\n</html>";
XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("xxx.xhtml", html);
XmlTag body = file.getDocument().getRootTag().findFirstSubTag("body");
final XmlTag hr = body.getSubTags()[0];
final XmlText text = XmlElementFactory.getInstance(getProject()).createDisplayText("p");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
PsiElement element = hr.getParentTag().addAfter(text, hr);
assertEquals(element.getParent(), hr.getParentTag());
}
});
}
public void testCollapse() throws IncorrectOperationException {
final XmlTag tag = XmlElementFactory.getInstance(getProject()).createTagFromText("<foo></foo>");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
tag.collapseIfEmpty();
assertEquals("<foo/>", tag.getText());
final XmlTag tag1 = XmlElementFactory.getInstance(getProject()).createTagFromText("<foo>abc</foo>");
tag1.collapseIfEmpty();
assertEquals("<foo/>", tag1.getText());
final XmlTag tag2 = XmlElementFactory.getInstance(getProject()).createTagFromText("<foo><boo/></foo>");
tag2.collapseIfEmpty();
assertEquals("<foo><boo/></foo>", tag2.getText());
}
});
}
}
@@ -0,0 +1,61 @@
package com.intellij.codeInsight;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlText;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.util.IncorrectOperationException;
import com.intellij.xml.util.XmlUtil;
/**
* @author lesya, dsl
*/
public class XmlTagWriteTest extends LightCodeInsightTestCase{
public void test1() throws IncorrectOperationException {
XmlElementFactory elementFactory = XmlElementFactory.getInstance(getProject());
final XmlTag xmlTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<tag1/>");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
xmlTag.add(xmlTag.createChildTag("tag2", XmlUtil.EMPTY_URI, null, false));
}
});
assertEquals("<tag1><tag2/></tag1>", xmlTag.getText());
XmlTag createdFromText = elementFactory.createTagFromText(xmlTag.getText());
assertEquals("tag1", createdFromText.getName());
assertEquals(1, createdFromText.getSubTags().length);
assertEquals("tag2", createdFromText.getSubTags()[0].getName());
}
public void test2() throws IncorrectOperationException {
final XmlTag xmlTag = XmlElementFactory.getInstance(getProject()).createTagFromText("<tag1></tag1>");
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
xmlTag.add(xmlTag.createChildTag("tag2", XmlUtil.EMPTY_URI, null, false));
}
});
assertEquals("<tag1><tag2/></tag1>", xmlTag.getText());
XmlTag createdFromText = XmlElementFactory.getInstance(getProject()).createTagFromText(xmlTag.getText());
assertEquals("tag1", createdFromText.getName());
assertEquals(1, createdFromText.getSubTags().length);
assertEquals("tag2", createdFromText.getSubTags()[0].getName());
}
public void test3() throws Exception{
final XmlTag tag = XmlElementFactory.getInstance(getProject()).createTagFromText("<b>\n0123456</b>");
final XmlText text = (XmlText) tag.getValue().getChildren()[0];
String textS = text.getText();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
text.insertText("lala", 2);
}
});
XmlText text2 = (XmlText)tag.getValue().getChildren()[0];
assertEquals(textS.substring(0, 2) + "lala" + textS.substring(2), text2.getText());
}
}
@@ -0,0 +1,22 @@
package com.intellij.codeInsight;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import org.jetbrains.annotations.NonNls;
public class XmlTestUtil {
public static XmlTag tag(@NonNls String tagName, Project project) throws Exception {
XmlFile file = (XmlFile)PsiFileFactory.getInstance(project).createFileFromText("tag.xml", "<" + tagName + "/>");
return file.getDocument().getRootTag();
}
public static XmlTag tag(@NonNls String tagName, @NonNls String namespace, Project project) throws Exception {
XmlFile file = (XmlFile)PsiFileFactory.getInstance(project)
.createFileFromText("tag.xml", "<" + tagName + " xmlns=\"" + namespace + "\"/>");
return file.getDocument().getRootTag();
}
}
@@ -0,0 +1,86 @@
/*
* Copyright (c) 2000-2006 JetBrains s.r.o. All Rights Reserved.
*/
package com.intellij.codeInsight;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.impl.source.codeStyle.CodeEditUtil;
import com.intellij.psi.xml.XmlElement;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlText;
import com.intellij.testFramework.LightCodeInsightTestCase;
/**
* @author mike
*/
public class XmlTextTest extends LightCodeInsightTestCase {
public void testInsertAtOffset() throws Exception {
new WriteCommandAction(getProject()) {
@Override
protected void run(final Result result) throws Throwable {
String xml = "<root>0123456789</root>";
XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject())
.createFileFromText("foo.xml", StdFileTypes.XML, xml, (long)1, true, false);
//System.out.println(DebugUtil.psiToString(file, false));
XmlTag root = file.getDocument().getRootTag();
final XmlText text1 = root.getValue().getTextElements()[0];
assertFalse(CodeEditUtil.isNodeGenerated(root.getNode()));
final XmlText text = text1;
final XmlElement element = text.insertAtOffset(XmlElementFactory.getInstance(getProject()).createTagFromText("<bar/>"), 5);
assertNotNull(element);
assertTrue(element instanceof XmlText);
assertEquals("01234", element.getText());
assertEquals("<root>01234<bar/>56789</root>", text.getContainingFile().getText());
}
}.execute();
}
public void testPhysicalToDisplayIfHasGaps2() throws Exception {
String xml = "<div>&amp;abc</div>";
XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("foo.xml", xml);
XmlTag root = file.getDocument().getRootTag();
final XmlText text = root.getValue().getTextElements()[0];
assertEquals("&abc", text.getValue());
assertEquals(0, text.physicalToDisplay(0));
assertEquals(1, text.physicalToDisplay(5));
assertEquals(2, text.physicalToDisplay(6));
assertEquals(3, text.physicalToDisplay(7));
assertEquals(4, text.physicalToDisplay(8));
}
public void testDisplayToPhysical() throws Exception {
String xml = "<div>&amp;abc</div>";
XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("foo.xml", xml);
XmlTag root = file.getDocument().getRootTag();
final XmlText text = root.getValue().getTextElements()[0];
assertEquals("&abc", text.getValue());
assertEquals(0, text.displayToPhysical(0));
assertEquals(5, text.displayToPhysical(1));
assertEquals(6, text.displayToPhysical(2));
assertEquals(7, text.displayToPhysical(3));
assertEquals(8, text.displayToPhysical(4));
}
public void testDisplayToPhysical2() throws Exception {
String xml = "<div><![CDATA[ ]]></div>";
XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("foo.xml", xml);
XmlTag root = file.getDocument().getRootTag();
final XmlText text = root.getValue().getTextElements()[0];
assertEquals(" ", text.getValue());
assertEquals(9, text.displayToPhysical(0));
assertEquals(13, text.displayToPhysical(1));
}
}
@@ -0,0 +1,23 @@
package com.intellij.codeInsight;
import com.intellij.codeInsight.daemon.quickFix.LightQuickFixTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import java.io.File;
/**
* @author spleaner
*/
public class XmlWrongClosingTagNameInspectionTest extends LightQuickFixTestCase {
public void test() throws Exception { doAllTests(); }
@Override
protected String getBasePath() {
return "/wrongClosingTagName";
}
@Override
protected String getTestDataPath() {
return PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + "/xml/tests/testData/inspections";
}
}
@@ -0,0 +1,99 @@
package com.intellij.codeInsight;
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.xml.XmlFile
import com.intellij.psi.xml.XmlTag
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.application.WriteAction
/**
* @author mike
*/
public class XmlXIncludeTest extends LightCodeInsightFixtureTestCase {
private static final String BASE_PATH = "/psi/xi";
public void testBasicXi() throws Exception {
configure();
assertSubtagNames("before", "include1", "after");
}
public void testXpointerXi1() throws Exception {
configure();
assertSubtagNames("before", "foo", "bar", "after");
}
@Override
protected String getBasePath() {
return "/xml/tests/testData/" + BASE_PATH;
}
private void assertSubtagNames(String... expectedNames) {
final XmlTag tag = ((XmlFile)myFixture.file).document.rootTag
final List<String> names = tag.getSubTags().collect { it.name }
assertEquals(
"subtags are different",
StringUtil.join(expectedNames, "\n"), StringUtil.join(names, "\n")
);
}
private void configure() throws Exception {
myFixture.configureByFiles(getName() + ".xml", "/include1.xml");
}
public void testModifyingIncludedFile() {
myFixture.configureByText 'a.xml', '''
<root xmlns:xi="http://www.w3.org/2001/XInclude">
<before/>
<xi:include href="include1.xml" xpointer="xpointer(/include1/*)"/>
<after/>
</root>
'''
def inc1 = myFixture.copyFileToProject("include1.xml")
assertSubtagNames("before", "foo", "bar", "after")
changeText inc1, '<include1><a/></include1>'
assertSubtagNames("before", "a", "after")
}
public void testModifyingTransitivelyIncludedFile() {
myFixture.configureByText 'a.xml', '''
<root xmlns:xi="http://www.w3.org/2001/XInclude">
<before/>
<xi:include href="include1.xml" xpointer="xpointer(/include1/*)"/>
<after/>
</root>
'''
myFixture.addFileToProject("include1.xml", """
<include1 xmlns:xi="http://www.w3.org/2001/XInclude">
<foo attr1="val1"> <fooChild/> </foo>
<bar/>
<xi:include href="include2.xml""/>
</include1>
""")
def inc2 = myFixture.addFileToProject("include2.xml", '<a/>')
assertSubtagNames("before", "foo", "bar", "a", "after")
changeText inc2.virtualFile, '<b/>'
assertSubtagNames("before", "foo", "bar", "b", "after")
}
private changeText(VirtualFile inc1, String s) {
def token = WriteAction.start()
try {
FileDocumentManager.instance.getDocument(inc1).setText s
PsiDocumentManager.getInstance(project).commitAllDocuments()
}
finally {
token.finish()
}
}
}
@@ -0,0 +1,121 @@
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.codeInsight.lookup.impl.LookupManagerImpl;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import java.io.File;
/**
* @author spleaner
*/
@SuppressWarnings({"ALL"})
public class XmlSmartEnterTest extends LightCodeInsightTestCase {
private static final String BASE_PATH = "/smartEnter";
private LookupElement[] myItems;
public void testSmartFinish1() throws Throwable {
doCompletionPopupTest(getTestName(false));
}
public void testSmartFinish2() throws Throwable {
boolean old = CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION;
CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = false;
try {
doCompletionPopupTest(getTestName(false));
}
finally {
CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = old;
}
}
public void testSmartFinish3() throws Exception {
doSmartEnterTest("SmartFinish1");
}
public void testSmartFinish4() throws Exception {
doSmartEnterTest("SmartFinish2");
}
public void testSmartFinish5() throws Exception {
doSmartEnterTest("SmartFinish3");
}
public void testSmartFinish_IDEADEV_29628() throws Exception {
doSmartEnterTest("IDEADEV_29628");
}
public void testSmartFinishWithWrongAttribute() throws Exception {
doSmartEnterTest("WrongAttribute");
}
public void testOpenAttribute() throws Exception {
doSmartEnterTest("OpenAttribute");
}
public void testComplete1() throws Exception {
_doTest("Tag.xml", "Tag_after.xml");
}
private void doCompletionPopupTest(String baseName) throws Exception {
_doTestCompletion(baseName + ".xml", baseName + "_after.xml");
}
private void _doTestCompletion(final String name, final String after_name) throws Exception {
configureByFile(BASE_PATH + "/" + name);
performCompletionAction();
select(Lookup.COMPLETE_STATEMENT_SELECT_CHAR);
checkResultByFile(BASE_PATH + "/" + after_name);
}
private void doSmartEnterTest(String baseName) throws Exception {
_doTest(baseName + ".xml", baseName + "_after.xml");
}
private void _doTest(String filename, String filename_after) throws Exception {
configureByFile(BASE_PATH + "/" + filename);
new WriteCommandAction(getProject()) {
protected void run(final Result result) throws Throwable {
new XmlSmartEnterProcessor().process(getProject(), getEditor(), getFile());
}
}.execute();
checkResultByFile("", BASE_PATH + "/" + filename_after, true);
}
private void performCompletionAction() {
new CodeCompletionHandlerBase(CompletionType.BASIC).invokeCompletion(getProject(), getEditor());
final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(getEditor());
myItems = lookup == null ? null : lookup.getItems().toArray(LookupElement.EMPTY_ARRAY);
}
private void select(final char c) {
if (c != '\n' && c != '\t' && c != Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
type(c);
return;
}
final LookupManagerImpl manager = (LookupManagerImpl) LookupManager.getInstance(getProject());
final Lookup lookup = manager.getActiveLookup();
if(lookup != null) {
manager.forceSelection(c, lookup.getCurrentItem());
}
}
protected String getBasePath() {
return "";
}
@Override
protected String getTestDataPath() {
return PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + "/xml/tests/testData/";
}
}
@@ -0,0 +1,66 @@
package com.intellij.codeInsight.editorActions.moveUpDown;
import com.intellij.codeInsight.CodeInsightTestCase;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.testFramework.PlatformTestUtil;
import org.jetbrains.annotations.NonNls;
import java.io.File;
/**
* @author spleaner
*/
@SuppressWarnings({"ALL"})
public class XmlMoverTest extends CodeInsightTestCase {
public void testTag() throws Exception { doTest("xml"); }
public void testTag2() throws Exception { doTest("xml"); }
public void testTag3() throws Exception { doTest("xml"); }
public void testTag4() throws Exception { doTest("xml"); }
public void testTag5() throws Exception { doTest("xml"); }
public void testTag6() throws Exception { doTest("xml"); }
public void testTag7() throws Exception { doTest("xml"); }
public void testTag8() throws Exception { doTest("xml"); }
public void testTag9() throws Exception { doTest("xml"); }
public void testTag10() throws Exception { doTest("xml"); }
public void testTag11() throws Exception { doTest("xml"); }
public void test1() throws Exception { doTest("html"); }
private void doTest(String ext) throws Exception {
final String baseName = getBasePath() + '/' + getTestName(true);
final String fileName = baseName + "."+ext;
try {
@NonNls String afterFileName = baseName + "_afterUp." + ext;
EditorActionHandler handler = new MoveStatementUpAction().getHandler();
performAction(fileName, handler, afterFileName);
afterFileName = baseName + "_afterDown." + ext;
handler = new MoveStatementDownAction().getHandler();
performAction(fileName, handler, afterFileName);
}
finally {
//CodeStyleSettingsManager.getInstance(myProject).dropTemporarySettings();
}
}
private void performAction(final String fileName, final EditorActionHandler handler, final String afterFileName) throws Exception {
configureByFile(fileName);
final boolean enabled = handler.isEnabled(myEditor, null);
assertEquals(new File(getTestDataPath(), afterFileName).exists(), enabled);
if (enabled) {
handler.execute(myEditor, null);
checkResultByFile(afterFileName);
}
}
protected String getBasePath() {
return "/mover";
}
@Override
protected String getTestDataPath() {
return PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + "/xml/tests/testData";
}
}
@@ -0,0 +1,54 @@
package com.intellij.psi.formatter;
import com.intellij.psi.impl.source.xml.XmlFileImpl;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.application.ApplicationManager;
/**
* @author yole
*/
public abstract class XmlFormatterTestBase extends XmlFormatterTestCase {
protected void checkFormattingDoesNotProduceException(String name) throws Exception {
String text = loadFile(name + ".xml", null);
final XmlFileImpl file = (XmlFileImpl)createFile(name + ".xml", text);
myTextRange = new TextRange(10000, 10001);
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
performFormatting(file);
}
});
}
}, "", "");
myTextRange = new TextRange(1000000, 1000001);
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
performFormatting(file);
}
});
}
}, "", "");
myTextRange = new TextRange(0, text.length());
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
performFormatting(file);
}
});
}
}, "", "");
}
}
@@ -0,0 +1,25 @@
package com.intellij.psi.formatter;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.formatter.xml.XmlCodeStyleSettings;
/**
* @author peter
*/
public abstract class XmlFormatterTestCase extends FormatterTestCase{
public void testDontKeepLineBreaksInText() throws Throwable {
final CodeStyleSettings settings = getSettings();
final XmlCodeStyleSettings xmlSettings = settings.getCustomSettings(XmlCodeStyleSettings.class);
settings.RIGHT_MARGIN = 15;
settings.HTML_KEEP_LINE_BREAKS_IN_TEXT = false;
xmlSettings.XML_KEEP_LINE_BREAKS_IN_TEXT = false;
doTextTest("<tag>aaa\nbbb\nccc\nddd\n</tag>", "<tag>aaa bbb\n ccc ddd\n</tag>");
settings.HTML_TEXT_WRAP = CodeStyleSettings.DO_NOT_WRAP;
xmlSettings.XML_TEXT_WRAP = CodeStyleSettings.DO_NOT_WRAP;
doTextTest("<tag>aaa\nbbb\nccc\nddd\n</tag>", "<tag>aaa bbb ccc ddd\n</tag>");
}
}
@@ -0,0 +1,28 @@
package com.intellij.psi.impl.source.html;
import com.intellij.codeInsight.completion.CompletionTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import java.io.File;
/**
* @author spleaner
*/
@SuppressWarnings({"ALL"})
public class HtmlConditionalCommentInjectionTest extends CompletionTestCase {
public void testHtmlCompletion() throws Exception {
configureByFile("complete.html");
checkResultByFile("complete_after.html");
}
public void testXhtmlCompletion() throws Exception {
configureByFile("complete.xhtml");
checkResultByFile("complete_after.xhtml");
}
@Override
protected String getTestDataPath() {
return PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + "/xml/tests/testData/commentInjection/";
}
}
@@ -0,0 +1,145 @@
package com.intellij.xml;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.Convertor;
import com.intellij.xml.actions.ValidateXmlActionHandler;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.xs.XSComplexTypeDecl;
import org.apache.xerces.impl.xs.XSElementDecl;
import org.apache.xerces.impl.xs.models.CMBuilder;
import org.apache.xerces.impl.xs.models.CMNodeFactory;
import org.apache.xerces.impl.xs.models.XSCMValidator;
import org.apache.xerces.xni.grammars.Grammar;
import org.apache.xerces.xni.grammars.XMLGrammarDescription;
import org.apache.xerces.xni.grammars.XMLGrammarPool;
import org.apache.xerces.xni.grammars.XSGrammar;
import org.apache.xerces.xs.XSComplexTypeDefinition;
import org.apache.xerces.xs.XSElementDeclaration;
import org.apache.xerces.xs.XSModel;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import java.util.Arrays;
import java.util.Map;
import java.util.Vector;
/**
* @author Dmitry Avdeev
*/
@SuppressWarnings({"UseOfObsoleteCollectionType"})
public class XmlConstraintsTest extends CodeInsightFixtureTestCase {
public void testXercesGrammar() throws Exception {
XSModel xsModel = getXSModel("test.xml", "test.xsd");
XSElementDeclaration elementDeclaration = xsModel.getElementDeclaration("a", "");
XSComplexTypeDefinition typeDefinition = (XSComplexTypeDefinition)elementDeclaration.getTypeDefinition();
CMBuilder cmBuilder = new CMBuilder(new CMNodeFactory());
XSCMValidator validator = cmBuilder.getContentModel((XSComplexTypeDecl)typeDefinition, true);
int[] ints = validator.startContentModel();
Vector vector = validator.whatCanGoHere(ints);
XSElementDecl o = (XSElementDecl)vector.get(0);
assertEquals("b", o.getName());
}
public void testXercesIncomplete() throws Exception {
XSModel xsModel = getXSModel("testIncomplete.xml", "test.xsd");
XSElementDeclaration elementDeclaration = xsModel.getElementDeclaration("a", "");
XSComplexTypeDefinition typeDefinition = (XSComplexTypeDefinition)elementDeclaration.getTypeDefinition();
CMBuilder cmBuilder = new CMBuilder(new CMNodeFactory());
XSCMValidator validator = cmBuilder.getContentModel((XSComplexTypeDecl)typeDefinition, true);
int[] ints = validator.startContentModel();
Vector vector = validator.whatCanGoHere(ints);
XSElementDecl o = (XSElementDecl)vector.get(0);
assertEquals("b", o.getName());
}
public void testXercesForCompletion() throws Exception {
XSModel xsModel = getXSModel("testCompletion.xml", "test.xsd");
PsiElement element = myFixture.getFile().findElementAt(getEditor().getCaretModel().getOffset());
XmlTag tag = PsiTreeUtil.getParentOfType(element, XmlTag.class);
assert tag != null;
XSElementDeclaration elementDeclaration = xsModel.getElementDeclaration(tag.getLocalName(), tag.getNamespace());
XSComplexTypeDefinition typeDefinition = (XSComplexTypeDefinition)elementDeclaration.getTypeDefinition();
CMBuilder cmBuilder = new CMBuilder(new CMNodeFactory());
XSCMValidator validator = cmBuilder.getContentModel((XSComplexTypeDecl)typeDefinition, true);
int[] ints = validator.startContentModel();
Vector vector = validator.whatCanGoHere(ints);
XSElementDecl o = (XSElementDecl)vector.get(0);
assertEquals("b", o.getName());
}
private XSModel getXSModel(String... files) {
myFixture.configureByFiles(files);
XmlFile file = (XmlFile)myFixture.getFile();
ValidateXmlActionHandler handler = new ValidateXmlActionHandler(false) {
@Override
protected SAXParser createParser() throws SAXException, ParserConfigurationException {
SAXParser parser = super.createParser();
parser.getXMLReader().setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE, true);
return parser;
}
};
handler.setErrorReporter(handler.new TestErrorReporter());
handler.doValidate(file);
XMLGrammarPool grammarPool = ValidateXmlActionHandler.getGrammarPool(file);
assert grammarPool != null;
Grammar[] grammars = grammarPool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA);
XSGrammar grammar = (XSGrammar)grammars[0];
return grammar.toXSModel();
}
public void testXsdConstraints() throws Exception {
Map<String, XmlElementDescriptor> map = configure("test.xml", "test.xsd");
XmlElementDescriptor a = map.get("a");
XmlElementsGroup topGroup = a.getTopGroup();
}
public void testDtdConstraints() throws Exception {
Map<String, XmlElementDescriptor> map = configure("testDtd.xml");
XmlElementDescriptor a = map.get("a");
XmlElementDescriptor b = map.get("b");
XmlElementDescriptor c = map.get("c");
XmlElementDescriptor d = map.get("d");
XmlElementDescriptor e = map.get("e");
}
private Map<String, XmlElementDescriptor> configure(String... files) {
myFixture.configureByFiles(files);
XmlTag tag = ((XmlFile)getFile()).getRootTag();
assertNotNull(tag);
XmlElementDescriptor descriptor = tag.getDescriptor();
assertNotNull(descriptor);
XmlElementDescriptor[] descriptors = descriptor.getElementsDescriptors(tag);
Map<String, XmlElementDescriptor> map =
ContainerUtil.assignKeys(Arrays.asList(descriptors).iterator(), new Convertor<XmlElementDescriptor, String>() {
@Override
public String convert(XmlElementDescriptor o) {
return o.getName();
}
});
map.put(tag.getName(), tag.getDescriptor());
return map;
}
@Override
protected String getBasePath() {
return "/xml/tests/testData/constraints";
}
@Override
protected boolean isCommunity() {
return true;
}
}
@@ -0,0 +1,249 @@
package com.intellij.xml;
import com.intellij.codeInsight.actions.OptimizeImportsProcessor;
import com.intellij.codeInsight.daemon.impl.analysis.XmlUnusedNamespaceInspection;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInspection.htmlInspections.XmlInspectionToolProvider;
import com.intellij.javaee.ExternalResourceManagerImpl;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.testFramework.IdeaTestCase;
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase;
/**
* @author Dmitry Avdeev
*/
public class XmlNamespacesTest extends CodeInsightFixtureTestCase {
@SuppressWarnings("JUnitTestCaseWithNonTrivialConstructors")
public XmlNamespacesTest() {
IdeaTestCase.initPlatformPrefix();
}
public void testUnusedNamespaces() throws Exception {
doUnusedDeclarationTest(
"<all xmlns=\"http://www.w3.org/2001/XMLSchema\" <warning descr=\"Namespace declaration is never used\">xmlns:xsi=\"http://www.w3.org/2001/XMLSc<caret>hema-instance\"</warning>/>",
"<all xmlns=\"http://www.w3.org/2001/XMLSchema\"/>", XmlUnusedNamespaceInspection.RemoveNamespaceDeclarationFix.NAME);
}
public void testUnusedDefaultNamespace() throws Exception {
doUnusedDeclarationTest("<schema:schema \n" +
" xmlns:schema=\"http://www.w3.org/2001/XMLSchema\"\n" +
" <warning descr=\"Namespace declaration is never used\">xmlns=\"http://www.w3.org/2001/X<caret>Include\"</warning>\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" <warning descr=\"Namespace location is never used\">xsi:noNamespaceSchemaLocation=\"http://www.w3.org/2001/XInclude\"</warning>>\n" +
"</schema:schema>",
"<schema:schema\n" +
" xmlns:schema=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" >\n" +
"</schema:schema>", XmlUnusedNamespaceInspection.RemoveNamespaceDeclarationFix.NAME, false);
doOptimizeImportsTest("<schema:schema \n" +
" xmlns:schema=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" >\n" +
"</schema:schema>");
}
public void testDifferentPrefixes() throws Exception {
doUnusedDeclarationTest(
"<x:all <warning descr=\"Namespace declaration is never used\">xmlns=\"http://www.w3.org/2001/XMLS<caret>chema\"</warning>\n" +
" xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" +
" <warning descr=\"Namespace declaration is never used\">xmlns:y=\"http://www.w3.org/2001/XMLSchema\"</warning>/>",
"<x:all\n" +
" xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:y=\"http://www.w3.org/2001/XMLSchema\"/>",
XmlUnusedNamespaceInspection.RemoveNamespaceDeclarationFix.NAME, false);
doOptimizeImportsTest("<x:all\n" +
" xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" +
" />");
}
public void testUnusedLocation() throws Exception {
doUnusedDeclarationTest("<x:all\n" +
" xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"<warning descr=\"Namespace location is never used\">http://www.w3.org/2001/XML<caret>Sche</warning> " +
"<warning descr=\"Namespace location is never used\">http://www.w3.org/2001/XMLSchema.xsd</warning>\"/>",
"<x:all\n" +
" xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" />",
XmlUnusedNamespaceInspection.RemoveNamespaceLocationFix.NAME);
}
public void testUnusedLocationOnly() throws Exception {
doUnusedDeclarationTest("<x:all\n" +
" xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" +
" <warning descr=\"Namespace declaration is never used\">xmlns:y=\"http://www.w3.org/2001/XInclude\"</warning>\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"<warning descr=\"Namespace location is never used\">http://www.w3.org/2001/XI<caret>nclude</warning> <warning descr=\"Namespace location is never used\">http://www.w3.org/2001/XInclude.xsd</warning>\n" +
" http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema.xsd\"/>",
"<x:all\n" +
" xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema.xsd\"/>",
XmlUnusedNamespaceInspection.RemoveNamespaceDeclarationFix.NAME);
}
public void testUnusedDefaultLocation() throws Exception {
doUnusedDeclarationTest("<x:all\n" +
" xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" <warning descr=\"Namespace location is never used\">xsi:noNamespaceSc<caret>hemaLocation=\"<error descr=\"Cannot resolve file 'zzz'\">zzz</error>\"</warning> />",
"<x:all\n" +
" xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" />",
XmlUnusedNamespaceInspection.RemoveNamespaceLocationFix.NAME);
}
public void testKeepFormatting() throws Exception {
doUnusedDeclarationTest("<xs:schema attributeFormDefault=\"unqualified\"\n" +
" <warning descr=\"Namespace declaration is never used\">xmlns:xsi=\"http://www.w3.org/20<caret>01/XMLSchema-instance\"</warning>\n" +
" elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
"\n" +
" <!-- keep formatting here-->\n" +
" <xs:element name=\"a\" type=\"aType\"/>\n" +
" <xs:complexType name=\"aType\">\n" +
"\n" +
" </xs:complexType>\n" +
"</xs:schema>",
"<xs:schema attributeFormDefault=\"unqualified\"\n" +
" elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
"\n" +
" <!-- keep formatting here-->\n" +
" <xs:element name=\"a\" type=\"aType\"/>\n" +
" <xs:complexType name=\"aType\">\n" +
"\n" +
" </xs:complexType>\n" +
"</xs:schema>",
XmlUnusedNamespaceInspection.RemoveNamespaceDeclarationFix.NAME);
}
public void testImplicitPrefixUsage() throws Exception {
myFixture.configureByText("a.xml", "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:x2=\"http://www.w3.org/2001/XMLSchema\"\n" +
" <warning descr=\"Namespace declaration is never used\">xmlns:x3=\"http://www.w3.org/2001/XMLSchema\"</warning> >\n" +
" <xs:element name=\"a\" type=\"x2:string\"/>\n" +
"</xs:schema>");
myFixture.testHighlighting();
}
public void testUnusedLocationDetection() throws Exception {
myFixture.configureByFile("web-app_2_5.xsd");
myFixture.configureByText("a.xml", "<web-app xmlns=\"http://java.sun.com/xml/ns/javaee\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" <warning descr=\"Namespace declaration is never used\">xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"</warning>\n" +
" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n" +
" web-app_2_5.xsd\"\n" +
" version=\"2.5\">\n" +
"</web-app>");
myFixture.testHighlighting();
}
public void testWSDD() throws Exception {
myFixture.configureByText("a.xml",
"<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" xmlns:java=\"http://xml.apache.org/axis/wsdd/providers/java\">\n" +
"<typeMapping deserializer=\"org.apache.axis.encoding.ser.BeanDeserializerFactory\" encodingStyle=\"\" qname=\"ns38:AxisAnalysis\" serializer=\"org.apache.axis.encoding.ser.BeanSerializerFactory\" languageSpecificType=\"java:com.pls.xactservice.axis.bindings.AxisAnalysis\"/>\n" +
"</deployment>");
myFixture.testHighlighting();
}
public void testPrefixesInTagValues() throws Exception {
myFixture.configureByText("a.xml",
"<<info descr=\"Namespace '' is not bound\">nodeTypes</info> xmlns:nt=\"<error descr=\"URI is not registered (Settings | Project Settings | Schemas and DTDs)\">http://www.jcp.org/jcr/nt/1.0</error>\" xmlns:customns=\"<error descr=\"URI is not registered (Settings | Project Settings | Schemas and DTDs)\">http://customurl</error>\">\n" +
"<nodeType name=\"customns:item\" isMixin=\"false\" hasOrderableChildNodes=\"false\">\n" +
" <supertypes>\n" +
" <supertype>nt:folder</supertype>\n" +
" </supertypes>\n" +
"</nodeType>\n" +
"</<info descr=\"Namespace '' is not bound\">nodeTypes</info>>");
myFixture.testHighlighting();
}
public void testLocallyUsedNamespace() throws Exception {
myFixture.configureByText("a.xml", "<x:all\n" +
" xmlns:x=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema.xsd\n" +
" http://www.w3.org/2001/XInclude http://www.w3.org/2001/XInclude.xsd\">\n" +
"\n" +
" <include xmlns=\"http://www.w3.org/2001/XInclude\" href=\"<error descr=\"Cannot resolve file 'a.xml'\">a.xml</error>\"/>\n" +
"</x:all>");
myFixture.testHighlighting();
}
public void testSubDirectory() throws Exception {
myFixture.testHighlighting("moved.xml", "trg/move-def.xsd");
}
public void testSuppressedOptimize() throws Exception {
myFixture.configureByFile("web-app_2_5.xsd");
String text = "<!--suppress XmlUnusedNamespaceDeclaration -->\n" +
"<web-app xmlns=\"http://java.sun.com/xml/ns/javaee\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n" +
" web-app_2_5.xsd\"\n" +
" version=\"2.5\">\n" +
"</web-app>";
myFixture.configureByText("a.xml", text);
doOptimizeImportsTest(text);
}
private void doUnusedDeclarationTest(String text, String after, String name) throws Exception {
doUnusedDeclarationTest(text, after, name, true);
}
private void doUnusedDeclarationTest(String text, String after, String name, boolean testOptimizeImports) throws Exception {
myFixture.configureByText("a.xml", text);
myFixture.testHighlighting();
IntentionAction action = myFixture.getAvailableIntention(name);
assertNotNull(name + " not found", action);
myFixture.launchAction(action);
myFixture.checkResult(after);
myFixture.configureByText("a.xml", text);
if (testOptimizeImports) {
doOptimizeImportsTest(after);
}
}
private void doOptimizeImportsTest(String after) {
myFixture.testHighlighting();
new WriteCommandAction(getProject(), getFile()) {
@Override
protected void run(Result result) throws Throwable {
new OptimizeImportsProcessor(getProject(), getFile()).runWithoutProgress();
}
}.execute();
myFixture.checkResult(after);
}
@Override
protected void setUp() throws Exception {
super.setUp();
myFixture.enableInspections(new XmlInspectionToolProvider());
ExternalResourceManagerImpl.registerResourceTemporarily("http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd",
getTestDataPath() + "/web-app_2_5.xsd", getTestRootDisposable());
ExternalResourceManagerImpl.registerResourceTemporarily("http://xml.apache.org/axis/wsdd/",
getTestDataPath() + "/wsdd.dtd", getTestRootDisposable());
ExternalResourceManagerImpl.registerResourceTemporarily("http://xml.apache.org/axis/wsdd/providers/java",
getTestDataPath() + "/wsdd_provider_java.xsd", getTestRootDisposable());
}
@Override
protected String getBasePath() {
return "/xml/tests/testData/unusedNs";
}
@Override
protected boolean isCommunity() {
return true;
}
}
@@ -0,0 +1,47 @@
package com.intellij.xml;
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase;
import com.intellij.testFramework.fixtures.CodeInsightTestUtil;
import com.intellij.xml.refactoring.SchemaPrefixRenameHandler;
/**
* @author Konstantin Bulenkov
*/
public class XmlSchemaPrefixTest extends CodeInsightFixtureTestCase {
public void testPrefixUsages() throws Exception {
doFindUsages("usages.xml", 16);
doFindUsages("usages1.xml", 16);
}
public void testRename() throws Exception {doRename();}
public void testRename1() throws Exception {doRename();}
public void testRename2() throws Exception {doRename();}
public void testRenameFromClosingTag() throws Exception {doRename();}
private void doRename() throws Exception {
doRename("xsd");
}
private void doRename(String newValue) throws Exception {
final String name = getTestName(true);
CodeInsightTestUtil.doInlineRenameTest(new SchemaPrefixRenameHandler(), name, "xml", newValue, myFixture);
}
@Override
protected String getBasePath() {
return "/xml/tests/testData/schemaPrefix";
}
@Override
protected boolean isCommunity() {
return true;
}
protected void doFindUsages(String filename, int usages) {
final int size = myFixture.testFindUsages(filename).size();
assert size == usages : "Threre should be " + usages + " usages, but found " + size + ". File: " + filename;
}
}
@@ -0,0 +1,118 @@
package com.intellij.xml;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.completion.CompletionType;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.javaee.ExternalResourceManagerImpl;
import com.intellij.testFramework.IdeaTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import java.io.File;
import java.util.Arrays;
import java.util.List;
/**
* @author Dmitry Avdeev
*/
public class XmlSmartCompletionTest extends LightPlatformCodeInsightFixtureTestCase {
@SuppressWarnings("JUnitTestCaseWithNonTrivialConstructors")
public XmlSmartCompletionTest() {
IdeaTestCase.initPlatformPrefix();
}
public void testCompletion() throws Exception {
doTest(new String[]{"testCompletion.xml", "test.xsd"}, "b");
}
public void testCompletionNext() throws Exception {
doTest(new String[]{"testCompletionNext.xml", "test.xsd"}, "c");
}
public void testCompletion3() throws Exception {
doTest(new String[]{"testCompletion3.xml", "test.xsd"}, "c", "d");
}
public void testServlet() throws Exception {
doTest(new String[]{"Servlet.xml"}, "icon", "servlet-name");
}
public void testServletName() throws Exception {
doForText("<!DOCTYPE web-app\n" +
" PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\n" +
" \"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd\">\n" +
"<web-app>\n" +
"\n" +
" <servlet>\n" +
" <s<caret>\n" +
" </servlet>\n" +
"</web-app>",
"<!DOCTYPE web-app\n" +
" PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\n" +
" \"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd\">\n" +
"<web-app>\n" +
"\n" +
" <servlet>\n" +
" <servlet-name\n" +
" </servlet>\n" +
"</web-app>");
}
public void testPrefix() throws Exception {
doForText("<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
" <ann<caret>\n" +
"</xs:schema>",
"<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
" <xs:annotation\n" +
"</xs:schema>");
}
private void doForText(String before, String after) {
myFixture.configureByText("a.xml", before);
myFixture.complete(CompletionType.SMART);
myFixture.checkResult(after);
}
private void doTest(String[] files, String... items) {
myFixture.configureByFiles(files);
LookupElement[] elements;
try {
CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION = false;
elements = myFixture.complete(CompletionType.SMART);
}
finally {
CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION = true;
}
assert elements != null;
List<String> strings = ContainerUtil.map(elements, new Function<LookupElement, String>() {
@Override
public String fun(LookupElement lookupElement) {
return lookupElement.getLookupString();
}
});
assertEquals(Arrays.asList(items), strings);
}
@Override
public void setUp() throws Exception {
super.setUp();
ExternalResourceManagerImpl.registerResourceTemporarily("http://java.sun.com/j2ee/dtds/web-app_2_3.dtd",
getTestDataPath() + "/web-app_2_3.dtd", getTestRootDisposable());
}
@Override
protected String getBasePath() {
return "/xml/tests/testData/smartCompletion";
}
@Override
protected String getTestDataPath() {
return PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + getBasePath();
}
}
@@ -0,0 +1,84 @@
package com.intellij.xml.actions;
import com.intellij.javaee.ExternalResourceManagerImpl;
import com.intellij.testFramework.IdeaTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.fixtures.CodeInsightTestUtil;
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
import java.io.File;
/**
* @author Dmitry Avdeev
*/
public class GenerateXmlTagTest extends LightPlatformCodeInsightFixtureTestCase {
public GenerateXmlTagTest() {
IdeaTestCase.initPlatformPrefix();
}
public void testGenerate() throws Exception {
myFixture.configureByFile("web-app_2_5.xsd");
doTest("generate.xml", "security-constraint");
}
public void testGenerateEmpty() throws Exception {
myFixture.configureByFile("javaee_5.xsd");
myFixture.configureByFile("web-app_2_5.xsd");
doTest("generateEmpty.xml", "distributable");
}
public void testGenerateDTD() throws Exception {
doTest("generateDTD.xml", "b");
}
public void testGenerateDTDComplex() throws Exception {
doTest("generateDTDComplex.xml", "b");
}
public void testSpring() throws Exception {
myFixture.configureByFile("spring-beans_3.0.xsd");
doTest("spring.xml", "bean");
}
public void testSpringAtCaret() throws Exception {
myFixture.configureByFile("spring-beans_3.0.xsd");
doTest("springAtCaret.xml", "bean");
}
public void testSpringAfterBean() throws Exception {
myFixture.configureByFile("spring-beans_3.0.xsd");
doTest("springAfterBean.xml", "bean");
}
public void testSpringAlias() throws Exception {
myFixture.configureByFile("spring-beans_3.0.xsd");
doTest("springAlias.xml", "alias");
}
public void testInitParam() throws Exception {
doTest("initParam.xml", "context-param");
}
private void doTest(String file, String tagName) {
GenerateXmlTagAction.TEST_THREAD_LOCAL.set(tagName);
CodeInsightTestUtil.doActionTest(new GenerateXmlTagAction(), file, myFixture);
}
@Override
public void setUp() throws Exception {
super.setUp();
ExternalResourceManagerImpl.registerResourceTemporarily("http://java.sun.com/j2ee/dtds/web-app_2_3.dtd",
getTestDataPath() + "/web-app_2_3.dtd", getTestRootDisposable());
}
@Override
protected String getBasePath() {
return "/xml/tests/testData/generateTag";
}
@Override
protected String getTestDataPath() {
return PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + getBasePath();
}
}
@@ -0,0 +1,26 @@
package com.intellij.xml.actions;
import com.intellij.codeInsight.daemon.LightIntentionActionTestCase;
import com.intellij.testFramework.PlatformTestUtil;
/**
* @author spleaner
*/
@SuppressWarnings({"ALL"})
public class SplitTagActionTest extends LightIntentionActionTestCase {
public void test() throws Exception { doAllTests(); }
@Override
protected boolean shouldBeAvailableAfterExecution() {
return true;
}
@Override
protected String getBasePath() {
return "";
}
protected String getTestDataPath() {
return PlatformTestUtil.getCommunityPath() + "/xml/tests/testData/intentions/splitTag";
}
}
@@ -0,0 +1,91 @@
package com.intellij.xml.index;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.IdeaTestCase;
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* @author Dmitry Avdeev
*/
public class XmlSchemaIndexTest extends CodeInsightFixtureTestCase {
@SuppressWarnings("JUnitTestCaseWithNonTrivialConstructors")
public XmlSchemaIndexTest() {
IdeaTestCase.initPlatformPrefix();
}
public void testBuilder() throws IOException {
VirtualFile file = myFixture.copyFileToProject("spring-beans-2.0.xsd");
assert file != null;
final Collection<String> tags = XsdTagNameBuilder.computeTagNames(file.getInputStream());
assert tags != null;
assertEquals(22, tags.size());
final String ns = XsdNamespaceBuilder.computeNamespace(file.getInputStream());
assertEquals("http://www.springframework.org/schema/beans", ns);
final VirtualFile xsd = myFixture.copyFileToProject("XMLSchema.xsd");
assert xsd != null;
final String xsns = XsdNamespaceBuilder.computeNamespace(xsd.getInputStream());
assertEquals("http://www.w3.org/2001/XMLSchema", xsns);
final Collection<String> xstags = XsdTagNameBuilder.computeTagNames(xsd.getInputStream());
assert xstags != null;
assertEquals(69, xstags.size());
assertTrue(xstags.contains("schema"));
}
public void testTagNameIndex() {
myFixture.copyDirectoryToProject("", "");
final Project project = getProject();
final Collection<String> tags = XmlTagNamesIndex.getAllTagNames(project);
assertTrue(tags.size() > 26);
final Collection<VirtualFile> files = XmlTagNamesIndex.getFilesByTagName("bean", project);
assertEquals(1, files.size());
final Collection<VirtualFile> files1 = XmlTagNamesIndex.getFilesByTagName("schema", project);
assertEquals(files1.toString(), 2, files1.size());
Collection<String> names = ContainerUtil.map(files1, new Function<VirtualFile, String>() {
@Override
public String fun(VirtualFile virtualFile) {
return virtualFile.getName();
}
});
List<String> expected = Arrays.asList("XMLSchema.xsd", "XMLSchema.xsd");
names.removeAll(expected);
assertTrue(files1.toString(), names.isEmpty());
}
public void testNamespaceIndex() {
myFixture.copyDirectoryToProject("", "");
final List<IndexedRelevantResource<String, String>> files =
XmlNamespaceIndex.getResourcesByNamespace("http://www.springframework.org/schema/beans",
getProject(),
myModule);
assertEquals(1, files.size());
}
@Override
protected String getBasePath() {
return "/xml/tests/testData/index";
}
@Override
protected boolean isCommunity() {
return true;
}
}
@@ -0,0 +1,14 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>title</title>
<!--[if IE]
<link rel="stylesheet" type="text/css" should not be highlighted href="1.css"/>
should not be highlighted
<![endif]-->
</head>
<body>
</body>
</html>
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>title</title>
<!--[if IE]
<link rel="stylesheet" type="text/css" href="1.css"/>
<![endif]-->
</head>
<body>
</body>
</html>
@@ -0,0 +1,14 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>title</title>
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="1.css"/>
should not be highlighted
<![endif-->
</head>
<body>
</body>
</html>
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>title</title>
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="1.css"/>
<![endif-->
</head>
<body>
</body>
</html>
@@ -0,0 +1,13 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>title</title>
<!--[if IE]>
<link rel="sty<caret>
<![endif]-->
</head>
<body>
</body>
</html>
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>title</title>
<!--[if IE]>
<link rel="sty<caret>
<![endif]-->
</head>
<body>
</body>
</html>
@@ -0,0 +1,13 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>title</title>
<!--[if IE]>
<link rel="stylesheet<caret>
<![endif]-->
</head>
<body>
</body>
</html>
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>title</title>
<!--[if IE]>
<link rel="stylesheet<caret>
<![endif]-->
</head>
<body>
</body>
</html>
@@ -0,0 +1,14 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>title</title>
<!--[if IE]>
<link rel="stylesheet" type="text/css" <warning>ref</warning>="1.css"/>
<link rel="stylesheet" type="text/css" href="<warning>xxx.css</warning>"/>
<![endif]-->
</head>
<body>
</body>
</html>
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>title</title>
<!--[if IE]>
<link rel="stylesheet" <error descr="Attribute typ is not allowed here">typ</error><error descr="'=' expected"> </error><error descr="Attribute e is not allowed here">e</error>="text/css" href="<warning descr="Cannot resolve file '1.css'"><error descr="Cannot resolve file '1.css'">1.css</error></warning>"/>
<link rel="stylesheet" type="text/css" href="<warning descr="Cannot resolve file '2.css'"><error descr="Cannot resolve file '2.css'">2.css</error></warning>"/>
<![endif]-->
</head>
<body>
</body>
</html>
@@ -0,0 +1,22 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<style type="text/css">
.regular {
color: <error>INVALID</error>;
}
</style>
<!--[if ie]>
<div class="ccc">something</div>
<style type="text/css">
.injected {
color: <error>INVALID</error>;
}
</style>
<![endif]-->
</body>
</html>
@@ -0,0 +1,18 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>title</title>
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="1.css"/>
<style type="text/css">
.test {
color: aqua;
}
</style>
<link rel="stylesheet" type="text/css" href="1.css"/>
<![endif]-->
</head>
<body>
</body>
</html>
@@ -0,0 +1,18 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>title</title>
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="1.css"/>
<style type="text/css">
.test {
color: aqua;
}
</style>
<link rel="stylesheet" type="text/css" href="1.css"/>
<![endif]-->
</head>
<body>
</body>
</html>
@@ -0,0 +1,36 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>title</title><!--[if IE]>
<link rel="stylesheet" type="text/css" href="1.css"/>
<style type="text/css">
.test {
color: aqua;
}
</style>
<link rel="stylesheet" type="text/css" href="1.css"/>
<![endif]--><!--[if lt IE 6]>
<style type="text/css">
.test {
color: aqua;
}
</style>
<![endif]-->
<!--[if lte IE 5.5]>
<style type="text/css">
.test {
color: aqua;
}
</style>
<![endif]-->
<!--[if gt IE 6]>
<style type="text/css">
.test {
color: aqua;
}
</style>
<![endif]--></head>
<body>
</body>
</html>
@@ -0,0 +1,36 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>title</title><!--[if IE]>
<link rel="stylesheet" type="text/css" href="1.css"/>
<style type="text/css">
.test {
color: aqua;
}
</style>
<link rel="stylesheet" type="text/css" href="1.css"/>
<![endif]--><!--[if lt IE 6]>
<style type="text/css">
.test {
color: aqua;
}
</style>
<![endif]-->
<!--[if lte IE 5.5]>
<style type="text/css">
.test {
color: aqua;
}
</style>
<![endif]-->
<!--[if gt IE 6]>
<style type="text/css">
.test {
color: aqua;
}
</style>
<![endif]--></head>
<body>
</body>
</html>
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>title</title>
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="1.css"/>
<style type="text/css">
.test {
color: aqua;
}
</style>
<link rel="stylesheet" type="text/css" href="1.css"/>
<![endif]-->
</head>
<body>
</body>
</html>
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>title</title>
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="1.css"/>
<style type="text/css">
.test {
color: aqua;
}
</style>
<link rel="stylesheet" type="text/css" href="1.css"/>
<![endif]-->
</head>
<body>
</body>
</html>
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>title</title><!--[if IE]>
<link rel="stylesheet" type="text/css" href="1.css"/>
<style type="text/css">
.test {
color: aqua;
}
</style>
<link rel="stylesheet" type="text/css" href="1.css"/>
<![endif]--><!--[if lt IE 6]>
<style type="text/css">
.test {
color: aqua;
}
</style>
<![endif]-->
<!--[if lte IE 5.5]>
<style type="text/css">
.test {
color: aqua;
}
</style>
<![endif]-->
<!--[if gt IE 6]>
<style type="text/css">
.test {
color: aqua;
}
</style>
<![endif]--></head>
<body>
</body>
</html>
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>title</title><!--[if IE]>
<link rel="stylesheet" type="text/css" href="1.css"/>
<style type="text/css">
.test {
color: aqua;
}
</style>
<link rel="stylesheet" type="text/css" href="1.css"/>
<![endif]--><!--[if lt IE 6]>
<style type="text/css">
.test {
color: aqua;
}
</style>
<![endif]-->
<!--[if lte IE 5.5]>
<style type="text/css">
.test {
color: aqua;
}
</style>
<![endif]-->
<!--[if gt IE 6]>
<style type="text/css">
.test {
color: aqua;
}
</style>
<![endif]--></head>
<body>
</body>
</html>
+3
View File
@@ -0,0 +1,3 @@
<a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="test.xsd">
</a>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified"
elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="a" type="aType"/>
<xs:complexType name="aType">
<xs:sequence>
<xs:element type="xs:string" name="b"/>
<xs:element type="xs:string" name="c" minOccurs="1" maxOccurs="5"/>
<xs:element type="xs:string" name="d" minOccurs="z" maxOccurs="x"/>
<xs:element type="xs:string" name="e" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
@@ -0,0 +1,4 @@
<a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="test.xsd">
<b></b>
<<caret>
</a>
@@ -0,0 +1,10 @@
<!DOCTYPE a [
<!ELEMENT a (b, c?, d+, e*)>
<!ELEMENT b (#PCDATA)>
<!ELEMENT c (#PCDATA)>
<!ELEMENT d (#PCDATA)>
<!ELEMENT e (#PCDATA)>
]>
<a >
</a>
@@ -0,0 +1,3 @@
<a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="test.xsd">
<
</a>
@@ -0,0 +1,8 @@
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
web-app_2_5.xsd"
version="2.5">
<caret>
</web-app>
@@ -0,0 +1,17 @@
<!DOCTYPE a [
<!ELEMENT a (b)* >
<!ELEMENT b (c, d)>
<!ELEMENT c (#PCDATA)>
<!ATTLIST b
x CDATA #REQUIRED
y CDATA #IMPLIED
>
<!ELEMENT d (#PCDATA)>
]>
<a>
<caret>
</a>
@@ -0,0 +1,19 @@
<!DOCTYPE a [
<!ELEMENT a (b)* >
<!ELEMENT b (c, d)>
<!ELEMENT c (#PCDATA)>
<!ATTLIST b
x CDATA #REQUIRED
y CDATA #IMPLIED
>
<!ELEMENT d EMPTY>
<!ATTLIST d
z CDATA #REQUIRED
>
]>
<a>
<caret>
</a>
@@ -0,0 +1,22 @@
<!DOCTYPE a [
<!ELEMENT a (b)* >
<!ELEMENT b (c, d)>
<!ELEMENT c (#PCDATA)>
<!ATTLIST b
x CDATA #REQUIRED
y CDATA #IMPLIED
>
<!ELEMENT d EMPTY>
<!ATTLIST d
z CDATA #REQUIRED
>
]>
<a>
<b x="">
<c></c>
<d z=""/>
</b>
</a>
@@ -0,0 +1,20 @@
<!DOCTYPE a [
<!ELEMENT a (b)* >
<!ELEMENT b (c, d)>
<!ELEMENT c (#PCDATA)>
<!ATTLIST b
x CDATA #REQUIRED
y CDATA #IMPLIED
>
<!ELEMENT d (#PCDATA)>
]>
<a>
<b x="">
<c></c>
<d></d>
</b>
</a>
@@ -0,0 +1,8 @@
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
web-app_2_5.xsd"
version="2.5">
<caret>
</web-app>
@@ -0,0 +1,8 @@
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
web-app_2_5.xsd"
version="2.5">
<distributable/>
</web-app>
@@ -0,0 +1,13 @@
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
web-app_2_5.xsd"
version="2.5">
<security-constraint>
<web-resource-collection>
<web-resource-name></web-resource-name>
<url-pattern></url-pattern>
</web-resource-collection>
</security-constraint>
</web-app>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>
<caret>
</web-app>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>
<context-param>
<param-name></param-name>
<param-value></param-value>
</context-param>
</web-app>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More