Java Code Examples for com.intellij.pom.java.LanguageLevel

The following are top voted examples for showing how to use com.intellij.pom.java.LanguageLevel. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: manifold-ij   File: SomewhatLightCodeInsightFixtureTestCase.java   Source Code and License 6 votes vote down vote up
@Override
protected void setUp() throws Exception
{
  super.setUp();

  IdeaTestFixtureFactory factory = IdeaTestFixtureFactory.getFixtureFactory();
  TestFixtureBuilder<IdeaProjectTestFixture> fixtureBuilder = factory.createLightFixtureBuilder( getProjectDescriptor() );
  IdeaProjectTestFixture fixture = fixtureBuilder.getFixture();
  myFixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture( fixture, new TempDirTestFixtureImpl() );

  myFixture.setUp();
  myFixture.setTestDataPath( getTestDataPath() );

  myModule = myFixture.getModule();

  LanguageLevelProjectExtension.getInstance( getProject() ).setLanguageLevel( LanguageLevel.JDK_1_8 );
}
 
Example 2
Project: intellij-ce-playground   File: AnnotationsHighlightUtil.java   Source Code and License 6 votes vote down vote up
@Nullable
static HighlightInfo checkFunctionalInterface(@NotNull PsiAnnotation annotation, @NotNull LanguageLevel languageLevel) {
  if (languageLevel.isAtLeast(LanguageLevel.JDK_1_8) && Comparing.strEqual(annotation.getQualifiedName(), CommonClassNames.JAVA_LANG_FUNCTIONAL_INTERFACE)) {
    final PsiAnnotationOwner owner = annotation.getOwner();
    if (owner instanceof PsiModifierList) {
      final PsiElement parent = ((PsiModifierList)owner).getParent();
      if (parent instanceof PsiClass) {
        final String errorMessage = LambdaHighlightingUtil.checkInterfaceFunctional((PsiClass)parent, ((PsiClass)parent).getName() + " is not a functional interface");
        if (errorMessage != null) {
          return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(annotation).descriptionAndTooltip(errorMessage).create();
        }
      }
    }
  }
  return null;
}
 
Example 3
Project: intellij-ce-playground   File: Jdks.java   Source Code and License 6 votes vote down vote up
@Nullable
public static String getJdkHomePath(@NotNull LanguageLevel langLevel) {
  Collection<String> jdkHomePaths = new ArrayList<String>(JavaSdk.getInstance().suggestHomePaths());
  if (jdkHomePaths.isEmpty()) {
    return null;
  }
  // prefer jdk path of getJavaHome(), since we have to allow access to it in tests
  // see AndroidProjectDataServiceTest#testImportData()
  final List<String> list = new ArrayList<String>();
  String javaHome = SystemProperties.getJavaHome();

  if (javaHome != null && !javaHome.isEmpty()) {
    for (Iterator<String> it = jdkHomePaths.iterator(); it.hasNext(); ) {
      final String path = it.next();

      if (path != null && javaHome.startsWith(path)) {
        it.remove();
        list.add(path);
      }
    }
  }
  list.addAll(jdkHomePaths);
  return getBestJdkHomePath(list, langLevel);

}
 
Example 4
Project: intellij-ce-playground   File: JavaParserUtil.java   Source Code and License 6 votes vote down vote up
@Nullable
public static ASTNode parseFragment(final ASTNode chameleon, final ParserWrapper wrapper, final boolean eatAll, final LanguageLevel level) {
  final PsiElement psi = (chameleon.getTreeParent() != null ? chameleon.getTreeParent().getPsi() : chameleon.getPsi());
  assert psi != null : chameleon;
  final Project project = psi.getProject();

  final PsiBuilderFactory factory = PsiBuilderFactory.getInstance();
  final Lexer lexer = chameleon.getElementType() == JavaDocElementType.DOC_COMMENT
                      ? JavaParserDefinition.createDocLexer(level) : JavaParserDefinition.createLexer(level);
  final PsiBuilder builder = factory.createBuilder(project, chameleon, lexer, chameleon.getElementType().getLanguage(), chameleon.getChars());
  setLanguageLevel(builder, level);

  final PsiBuilder.Marker root = builder.mark();
  wrapper.parse(builder);
  if (!builder.eof()) {
    if (!eatAll) throw new AssertionError("Unexpected tokens");
    final PsiBuilder.Marker extras = builder.mark();
    while (!builder.eof()) builder.advanceLexer();
    extras.error(JavaErrorMessages.message("unexpected.tokens"));
  }
  root.done(chameleon.getElementType());

  return builder.getTreeBuilt().getFirstChildNode();
}
 
Example 5
Project: intellij   File: BlazeJavaSyncPlugin.java   Source Code and License 6 votes vote down vote up
private static void updateJdk(
    Project project,
    BlazeContext context,
    ProjectViewSet projectViewSet,
    BlazeProjectData blazeProjectData) {

  LanguageLevel javaLanguageLevel =
      JavaLanguageLevelHelper.getJavaLanguageLevel(
          projectViewSet, blazeProjectData, LanguageLevel.JDK_1_7);

  final Sdk sdk = Jdks.chooseOrCreateJavaSdk(javaLanguageLevel);
  if (sdk == null) {
    String msg =
        String.format(
            "Unable to find a JDK %1$s installed.\n", javaLanguageLevel.getPresentableText());
    msg +=
        "After configuring a suitable JDK in the \"Project Structure\" dialog, "
            + "sync the project again.";
    IssueOutput.error(msg).submit(context);
    return;
  }
  setProjectSdkAndLanguageLevel(project, sdk, javaLanguageLevel);
}
 
Example 6
Project: intellij-ce-playground   File: HighlightVisitorImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void visitConditionalExpression(PsiConditionalExpression expression) {
  super.visitConditionalExpression(expression);
  if (myLanguageLevel.isAtLeast(LanguageLevel.JDK_1_8) && PsiPolyExpressionUtil.isPolyExpression(expression)) {
    final PsiExpression thenExpression = expression.getThenExpression();
    final PsiExpression elseExpression = expression.getElseExpression();
    if (thenExpression != null && elseExpression != null) {
      final PsiType conditionalType = expression.getType();
      if (conditionalType != null) {
        final PsiExpression[] sides = {thenExpression, elseExpression};
        for (PsiExpression side : sides) {
          final PsiType sideType = side.getType();
          if (sideType != null && !TypeConversionUtil.isAssignable(conditionalType, sideType)) {
            myHolder.add(HighlightUtil.checkAssignability(conditionalType, sideType, side, side));
          }
        }
      }
    }
  }
}
 
Example 7
Project: intellij-ce-playground   File: JavaMethodsConflictResolver.java   Source Code and License 6 votes vote down vote up
private boolean isApplicableTo(@NotNull PsiType[] types2AtSite,
                               @NotNull PsiMethod method1,
                               @NotNull LanguageLevel languageLevel,
                               boolean varargsPosition,
                               @NotNull PsiSubstitutor methodSubstitutor1,
                               @NotNull PsiMethod method2, 
                               PsiSubstitutor siteSubstitutor1) {
  if (languageLevel.isAtLeast(LanguageLevel.JDK_1_8) && method1.getTypeParameters().length > 0 && myArgumentsList instanceof PsiExpressionList) {
    final PsiElement parent = myArgumentsList.getParent();
    if (parent instanceof PsiCallExpression) {
      return InferenceSession.isMoreSpecific(method2, method1, siteSubstitutor1,  ((PsiExpressionList)myArgumentsList).getExpressions(), myArgumentsList, varargsPosition);
    }
  }
  final PsiUtil.ApplicabilityChecker applicabilityChecker = languageLevel.isAtLeast(LanguageLevel.JDK_1_8) 
  ? new PsiUtil.ApplicabilityChecker() {
    @Override
    public boolean isApplicable(PsiType left, PsiType right,
                                boolean allowUncheckedConversion, int argId) {
      return isTypeMoreSpecific(left, right, argId);
    }
  } 
  : PsiUtil.ApplicabilityChecker.ASSIGNABILITY_CHECKER;
  final int applicabilityLevel = PsiUtil.getApplicabilityLevel(method1, methodSubstitutor1, types2AtSite, languageLevel, false, varargsPosition, applicabilityChecker);
  return applicabilityLevel > MethodCandidateInfo.ApplicabilityLevel.NOT_APPLICABLE;
}
 
Example 8
Project: intellij-ce-playground   File: Jdks.java   Source Code and License 6 votes vote down vote up
@Nullable
public static Sdk chooseOrCreateJavaSdk(@Nullable LanguageLevel langLevel) {
  if (langLevel == null) {
    langLevel = DEFAULT_LANG_LEVEL;
  }
  for (Sdk sdk : ProjectJdkTable.getInstance().getAllJdks()) {
    if (isApplicableJdk(sdk, langLevel)) {
      return sdk;
    }
  }
  String jdkHomePath = getJdkHomePath(langLevel);
  if (jdkHomePath != null) {
    return createJdk(jdkHomePath);
  }
  return null;
}
 
Example 9
Project: intellij-ce-playground   File: LanguageLevelCombo.java   Source Code and License 6 votes vote down vote up
public LanguageLevelCombo(String defaultItem) {
  myDefaultItem = defaultItem;
  for (LanguageLevel level : LanguageLevel.values()) {
    addItem(level);
  }
  setRenderer(new ColoredListCellRendererWrapper() {
    @Override
    protected void doCustomize(JList list, Object value, int index, boolean selected, boolean hasFocus) {
      if (value instanceof LanguageLevel) {
        append(((LanguageLevel)value).getPresentableText());
      }
      else if (value instanceof String) {    // default for SDK or project
        append((String)value);
        LanguageLevel defaultLevel = getDefaultLevel();
        if (defaultLevel != null) {
          append(" (" + defaultLevel.getPresentableText() + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES);
        }
      }
    }
  });
}
 
Example 10
Project: intellij-ce-playground   File: StubBuildingVisitor.java   Source Code and License 6 votes vote down vote up
@Override
public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
  if (index >= myIgnoreCount) {
    // long and double variables increase the index by 2, not by 1
    int paramIndex = (index - myIgnoreCount == myUsedParamSize) ? myUsedParamCount : index - myIgnoreCount;
    if (paramIndex >= myParamCount) return;

    if (ClsParsingUtil.isJavaIdentifier(name, LanguageLevel.HIGHEST)) {
      PsiParameterStubImpl parameterStub = myParamStubs[paramIndex];
      if (parameterStub != null) {
        parameterStub.setName(name);
      }
    }

    myUsedParamCount = paramIndex + 1;
    if ("D".equals(desc) || "J".equals(desc)) {
      myUsedParamSize += 2;
    }
    else {
      myUsedParamSize++;
    }
  }
}
 
Example 11
Project: intellij-ce-playground   File: PsiModificationTrackerTest.java   Source Code and License 6 votes vote down vote up
public void testLanguageLevelChange() {
  //noinspection unused
  PsiFile psiFile = myFixture.addFileToProject("Foo.java", "class Foo {}");
  GlobalSearchScope scope = GlobalSearchScope.allScope(getProject());

  PlatformTestUtil.tryGcSoftlyReachableObjects();

  PsiClass psiClass = JavaPsiFacade.getInstance(getProject()).findClass("Foo", scope);
  assertNotNull(psiClass);

  long count = PsiManager.getInstance(getProject()).getModificationTracker().getJavaStructureModificationCount();

  IdeaTestUtil.setModuleLanguageLevel(myFixture.getModule(), LanguageLevel.JDK_1_3);

  assertTrue(count != PsiManager.getInstance(getProject()).getModificationTracker().getJavaStructureModificationCount());

  psiClass = (JavaPsiFacade.getInstance(getProject()).findClass("Foo", scope));
  assertNotNull(psiClass);
  assertTrue(psiClass.isValid());
}
 
Example 12
Project: intellij-ce-playground   File: VariableResolverProcessor.java   Source Code and License 6 votes vote down vote up
public VariableResolverProcessor(@NotNull PsiJavaCodeReferenceElement place, @NotNull PsiFile placeFile) {
  super(place.getReferenceName(), ourFilter, new PsiConflictResolver[]{new JavaVariableConflictResolver()}, new SmartList<CandidateInfo>(), place, placeFile);

  PsiClass access = null;
  PsiElement qualifier = place.getQualifier();
  if (qualifier instanceof PsiExpression) {
    final JavaResolveResult accessClass = PsiUtil.getAccessObjectClass((PsiExpression)qualifier);
    final PsiElement element = accessClass.getElement();
    if (element instanceof PsiTypeParameter) {
      PsiElementFactory factory = JavaPsiFacade.getInstance(placeFile.getProject()).getElementFactory();
      final PsiClassType type = factory.createType((PsiTypeParameter)element);
      final PsiType accessType = accessClass.getSubstitutor().substitute(type);
      if (accessType instanceof PsiArrayType) {
        LanguageLevel languageLevel = PsiUtil.getLanguageLevel(placeFile);
        access = factory.getArrayClass(languageLevel);
      }
      else if (accessType instanceof PsiClassType) {
        access = ((PsiClassType)accessType).resolve();
      }
    }
    else if (element instanceof PsiClass) {
      access = (PsiClass)element;
    }
  }
  myAccessClass = access;
}
 
Example 13
Project: intellij-ce-playground   File: PsiMethodCallExpressionImpl.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
public PsiType fun(final PsiMethodCallExpression call) {
  PsiReferenceExpression methodExpression = call.getMethodExpression();
  PsiType theOnly = null;
  final JavaResolveResult[] results = methodExpression.multiResolve(false);
  LanguageLevel languageLevel = PsiUtil.getLanguageLevel(call);
  for (int i = 0; i < results.length; i++) {
    final PsiType type = getResultType(call, methodExpression, results[i], languageLevel);
    if (type == null) {
      return null;
    }

    if (i == 0) {
      theOnly = type;
    }
    else if (!theOnly.equals(type)) {
      return null;
    }
  }

  return PsiClassImplUtil.correctType(theOnly, call.getResolveScope());
}
 
Example 14
Project: intellij-ce-playground   File: ExecutionTestCase.java   Source Code and License 6 votes vote down vote up
@Override
protected void setUpModule() {
  super.setUpModule();
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      final String modulePath = getTestAppPath();
      final String srcPath = modulePath + File.separator + "src";
      VirtualFile moduleDir = LocalFileSystem.getInstance().findFileByPath(modulePath.replace(File.separatorChar, '/'));
      VirtualFile srcDir = LocalFileSystem.getInstance().findFileByPath(srcPath.replace(File.separatorChar, '/'));

      final ModuleRootManager rootManager = ModuleRootManager.getInstance(myModule);
      PsiTestUtil.removeAllRoots(myModule, rootManager.getSdk());
      PsiTestUtil.addContentRoot(myModule, moduleDir);
      PsiTestUtil.addSourceRoot(myModule, srcDir);
      IdeaTestUtil.setModuleLanguageLevel(myModule, LanguageLevel.JDK_1_8);
      PsiTestUtil.setCompilerOutputPath(myModule, VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(myModuleOutputDir.getAbsolutePath())), false);
    }
  });
}
 
Example 15
Project: intellij-ce-playground   File: SwitchStatementPostfixTemplate.java   Source Code and License 6 votes vote down vote up
@Override
public boolean value(PsiElement expression) {
  if (!(expression instanceof PsiExpression)) return false;

  PsiType type = ((PsiExpression)expression).getType();

  if (type == null) return false;
  if (PsiType.INT.isAssignableFrom(type)) return true;

  if (type instanceof PsiClassType) {
    PsiClass psiClass = ((PsiClassType)type).resolve();
    if (psiClass != null && psiClass.isEnum()) return true;
  }

  if (type.equalsToText(CommonClassNames.JAVA_LANG_STRING)) {
    PsiFile containingFile = expression.getContainingFile();
    if (containingFile instanceof PsiJavaFile) {
      LanguageLevel level = ((PsiJavaFile)containingFile).getLanguageLevel();
      if (level.isAtLeast(LanguageLevel.JDK_1_7)) return true;
    }
  }

  return false;
}
 
Example 16
Project: intellij-ce-playground   File: LanguageLevelCombo.java   Source Code and License 6 votes vote down vote up
public void reset(Project project) {
  removeAllItems();
  for (LanguageLevel level : LanguageLevel.values()) {
    addItem(level);
  }
  Sdk sdk = ProjectRootManagerEx.getInstanceEx(project).getProjectSdk();
  sdkUpdated(sdk);

  LanguageLevelProjectExtension extension = LanguageLevelProjectExtension.getInstance(project);
  if (getDefaultLevel() != null && extension.isDefault()) {
    setSelectedItem(myDefaultItem);
  }
  else {
    setSelectedItem(extension.getLanguageLevel());
  }
}
 
Example 17
Project: intellij-ce-playground   File: ConcatenationToMessageFormatAction.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
  if (PsiUtil.getLanguageLevel(file).compareTo(LanguageLevel.JDK_1_4) < 0) return false;
  final PsiElement element = findElementAtCaret(editor, file);
  PsiPolyadicExpression binaryExpression = getEnclosingLiteralConcatenation(element);
  return binaryExpression != null && !AnnotationUtil.isInsideAnnotation(binaryExpression);
}
 
Example 18
Project: intellij-ce-playground   File: EffectiveLanguageLevelUtil.java   Source Code and License 5 votes vote down vote up
@NotNull
public static LanguageLevel getEffectiveLanguageLevel(@NotNull final Module module) {
  ApplicationManager.getApplication().assertReadAccessAllowed();
  LanguageLevelModuleExtension moduleLevel = LanguageLevelModuleExtensionImpl.getInstance(module);
  LanguageLevel level = moduleLevel == null ? null : moduleLevel.getLanguageLevel();
  if (level != null) return level;
  return LanguageLevelProjectExtension.getInstance(module.getProject()).getLanguageLevel();
}
 
Example 19
Project: intellij-ce-playground   File: FormSourceCodeGenerator.java   Source Code and License 5 votes vote down vote up
private static boolean lexemsEqual(final PsiClass classToBind, final PsiClass newClass) {
  Lexer oldTextLexer = JavaParserDefinition.createLexer(LanguageLevel.HIGHEST);
  Lexer newTextLexer = JavaParserDefinition.createLexer(LanguageLevel.HIGHEST);
  String oldBuffer = classToBind.getText();
  String newBuffer = newClass.getText();
  oldTextLexer.start(oldBuffer);
  newTextLexer.start(newBuffer);

  while(true) {
    IElementType oldLexem = oldTextLexer.getTokenType();
    IElementType newLexem = newTextLexer.getTokenType();
    if (oldLexem == null || newLexem == null) {
      // must terminate at the same time
      return oldLexem == null && newLexem == null;
    }
    if (oldLexem != newLexem) {
      return false;
    }
    if (oldLexem != TokenType.WHITE_SPACE && oldLexem != JavaDocElementType.DOC_COMMENT) {
      int oldStart = oldTextLexer.getTokenStart();
      int newStart = newTextLexer.getTokenStart();
      int oldLength = oldTextLexer.getTokenEnd() - oldTextLexer.getTokenStart();
      int newLength = newTextLexer.getTokenEnd() - newTextLexer.getTokenStart();
      if (oldLength != newLength) {
        return false;
      }
      for(int i=0; i<oldLength; i++) {
        if (oldBuffer.charAt(oldStart+i) != newBuffer.charAt(newStart+i)) {
          return false;
        }
      }
    }
    oldTextLexer.advance();
    newTextLexer.advance();
  }
}
 
Example 20
Project: intellij-ce-playground   File: LanguageLevelProjectExtensionImpl.java   Source Code and License 5 votes vote down vote up
private void readExternal(final Element element) {
  String level = element.getAttributeValue(LANGUAGE_LEVEL);
  if (level == null) {
    myLanguageLevel = migrateFromIdea7(element);
  }
  else {
    myLanguageLevel = LanguageLevel.valueOf(level);
  }
  String aDefault = element.getAttributeValue(DEFAULT_ATTRIBUTE);
  setDefault(aDefault == null ? null : Boolean.parseBoolean(aDefault));
}
 
Example 21
Project: intellij-ce-playground   File: GrTraitType.java   Source Code and License 5 votes vote down vote up
public GrTraitType erasure() {
  PsiClassType exprType = (PsiClassType)TypeConversionUtil.erasure(myExprType);
  List<PsiClassType> traitTypes = ContainerUtil.map(myTraitTypes, new Function<PsiClassType, PsiClassType>() {
    @Override
    public PsiClassType fun(PsiClassType type) {
      return (PsiClassType)TypeConversionUtil.erasure(type);
    }
  });
  return new GrTraitType(myOriginal, exprType, traitTypes, myResolveScope, LanguageLevel.JDK_1_5);
}
 
Example 22
Project: intellij-ce-playground   File: JavaMethodCallElement.java   Source Code and License 5 votes vote down vote up
public static boolean mayNeedTypeParameters(@Nullable final PsiElement leaf) {
  if (PsiTreeUtil.getParentOfType(leaf, PsiExpressionList.class, true, PsiCodeBlock.class, PsiModifierListOwner.class) == null) {
    if (PsiTreeUtil.getParentOfType(leaf, PsiConditionalExpression.class, true, PsiCodeBlock.class, PsiModifierListOwner.class) == null) {
      return false;
    }
  }

  if (PsiUtil.getLanguageLevel(leaf).isAtLeast(LanguageLevel.JDK_1_8)) return false;

  final PsiElement parent = leaf.getParent();
  if (parent instanceof PsiReferenceExpression && ((PsiReferenceExpression)parent).getTypeParameters().length > 0) {
    return false;
  }
  return true;
}
 
Example 23
Project: intellij-ce-playground   File: LightAdvHighlightingJdk9Test.java   Source Code and License 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();
  enableInspectionTools(new UnusedDeclarationInspection(), new UncheckedWarningLocalInspection(), new RedundantCastInspection());
  setLanguageLevel(LanguageLevel.JDK_1_9);
  IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_9, getModule(), getTestRootDisposable());
}
 
Example 24
Project: intellij-ce-playground   File: HighlightMethodUtil.java   Source Code and License 5 votes vote down vote up
private static HighlightInfo checkInterfaceInheritedMethodsReturnTypes(@NotNull List<? extends MethodSignatureBackedByPsiMethod> superMethodSignatures,
                                                                       @NotNull LanguageLevel languageLevel) {
  if (superMethodSignatures.size() < 2) return null;
  MethodSignatureBackedByPsiMethod returnTypeSubstitutable = superMethodSignatures.get(0);
  for (int i = 1; i < superMethodSignatures.size(); i++) {
    PsiMethod currentMethod = returnTypeSubstitutable.getMethod();
    PsiType currentType = returnTypeSubstitutable.getSubstitutor().substitute(currentMethod.getReturnType());

    MethodSignatureBackedByPsiMethod otherSuperSignature = superMethodSignatures.get(i);
    PsiMethod otherSuperMethod = otherSuperSignature.getMethod();
    PsiType otherSuperReturnType = otherSuperSignature.getSubstitutor().substitute(otherSuperMethod.getReturnType());

    PsiSubstitutor unifyingSubstitutor = MethodSignatureUtil.getSuperMethodSignatureSubstitutor(returnTypeSubstitutable,
                                                                                                otherSuperSignature);
    if (unifyingSubstitutor != null) {
      otherSuperReturnType = unifyingSubstitutor.substitute(otherSuperReturnType);
      currentType = unifyingSubstitutor.substitute(currentType);
    }

    if (otherSuperReturnType == null || currentType == null || otherSuperReturnType.equals(currentType)) continue;

    if (languageLevel.isAtLeast(LanguageLevel.JDK_1_5)) {
      //http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.8 Example 8.1.5-3
      if (!(otherSuperReturnType instanceof PsiPrimitiveType || currentType instanceof PsiPrimitiveType)) {
        if (otherSuperReturnType.isAssignableFrom(currentType)) continue;
        if (currentType.isAssignableFrom(otherSuperReturnType)) {
          returnTypeSubstitutable = otherSuperSignature;
          continue;
        }
      }
      if (currentMethod.getTypeParameters().length > 0 && JavaGenericsUtil.isRawToGeneric(currentType, otherSuperReturnType)) continue;
    }
    return createIncompatibleReturnTypeMessage(currentMethod, otherSuperMethod, otherSuperReturnType,
                                               currentType, JavaErrorMessages.message("unrelated.overriding.methods.return.types"),
                                               TextRange.EMPTY_RANGE);
  }
  return null;
}
 
Example 25
Project: intellij-ce-playground   File: CompilerUtil.java   Source Code and License 5 votes vote down vote up
public static void addSourceCommandLineSwitch(final Sdk jdk, LanguageLevel chunkLanguageLevel, @NonNls final List<String> commandLine) {
  final String versionString = jdk.getVersionString();
  if (StringUtil.isEmpty(versionString)) {
    throw new IllegalArgumentException(CompilerBundle.message("javac.error.unknown.jdk.version", jdk.getName()));
  }

  final LanguageLevel applicableLanguageLevel = getApplicableLanguageLevel(versionString, chunkLanguageLevel);
  if (applicableLanguageLevel.equals(LanguageLevel.JDK_1_8)) {
    commandLine.add("-source");
    commandLine.add("8");
  }
  else if (applicableLanguageLevel.equals(LanguageLevel.JDK_1_7)) {
    commandLine.add("-source");
    commandLine.add("1.7");
  }
  else if (applicableLanguageLevel.equals(LanguageLevel.JDK_1_6)) {
    commandLine.add("-source");
    commandLine.add("1.6");
  }
  else if (applicableLanguageLevel.equals(LanguageLevel.JDK_1_5)) {
    commandLine.add("-source");
    commandLine.add("1.5");
  }
  else if (applicableLanguageLevel.equals(LanguageLevel.JDK_1_4)) {
    commandLine.add("-source");
    commandLine.add("1.4");
  }
  else if (applicableLanguageLevel.equals(LanguageLevel.JDK_1_3)) {
    if (!(isOfVersion(versionString, "1.3") || isOfVersion(versionString, "1.2") || isOfVersion(versionString, "1.1"))) {
      //noinspection HardCodedStringLiteral
      commandLine.add("-source");
      commandLine.add("1.3");
    }
  }
}
 
Example 26
Project: intellij-ce-playground   File: GradleProjectImporter.java   Source Code and License 5 votes vote down vote up
private static void setUpProject(@NotNull final Project newProject, @Nullable final LanguageLevel initialLanguageLevel) {
  CommandProcessor.getInstance().executeCommand(newProject, new Runnable() {
    @Override
    public void run() {
      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          if (initialLanguageLevel != null) {
            final LanguageLevelProjectExtension extension = LanguageLevelProjectExtension.getInstance(newProject);
            if (extension != null) {
              extension.setLanguageLevel(initialLanguageLevel);
            }
          }

          // In practice, it really does not matter where the compiler output folder is. Gradle handles that. This is done just to please
          // IDEA.
          File compilerOutputDirPath = new File(getBaseDirPath(newProject), join(BUILD_DIR_DEFAULT_NAME, "classes"));
          String compilerOutputDirUrl = pathToIdeaUrl(compilerOutputDirPath);
          CompilerProjectExtension compilerProjectExt = CompilerProjectExtension.getInstance(newProject);
          assert compilerProjectExt != null;
          compilerProjectExt.setCompilerOutputUrl(compilerOutputDirUrl);
          setUpGradleSettings(newProject);
          // This allows to customize UI when android project is opened inside IDEA with android plugin.
          setProjectType(newProject, AndroidModuleBuilder.ANDROID_PROJECT_TYPE);
        }
      });
    }
  }, null, null);
}
 
Example 27
Project: intellij-ce-playground   File: Jdks.java   Source Code and License 5 votes vote down vote up
@Nullable
private static String getBestJdk(@NotNull List<String> jdkRoots, @NotNull LanguageLevel langLevel) {
  String bestJdk = null;
  for (String jdkRoot : jdkRoots) {
    if (JavaSdk.getInstance().isValidSdkHome(jdkRoot)) {
      if (bestJdk == null && hasMatchingLangLevel(jdkRoot, langLevel)) {
        bestJdk = jdkRoot;
      }
      else if (bestJdk != null) {
        bestJdk = selectJdk(bestJdk, jdkRoot, langLevel);
      }
    }
  }
  return bestJdk;
}
 
Example 28
Project: intellij-ce-playground   File: I18NInspectionTest.java   Source Code and License 5 votes vote down vote up
public void testEnum() throws Exception {
  final JavaPsiFacade facade = getJavaFacade();
  final LanguageLevel effectiveLanguageLevel = LanguageLevelProjectExtension.getInstance(facade.getProject()).getLanguageLevel();
  LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(LanguageLevel.JDK_1_5);
  try {
    doTest();
  }
  finally {
    LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(effectiveLanguageLevel);
  }
}
 
Example 29
Project: intellij-ce-playground   File: GroovyPsiElementFactoryImpl.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public PsiClassType createType(@NotNull PsiClass resolve,
                               @NotNull PsiSubstitutor substitutor,
                               @NotNull LanguageLevel languageLevel,
                               @NotNull PsiAnnotation[] annotations) {
  return JavaPsiFacade.getElementFactory(myProject).createType(resolve, substitutor, languageLevel, annotations);
}
 
Example 30
Project: intellij-ce-playground   File: JavadocFormatterTest.java   Source Code and License 5 votes vote down vote up
public void testParagraphTagGeneration() {
  // Inspired by IDEA-61811
  getSettings().getRootSettings().ENABLE_JAVADOC_FORMATTING = true;
  getSettings().getRootSettings().JD_P_AT_EMPTY_LINES = true;
  LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7);
  doTextTest(
    "/**\n" +
    " * line 1\n" +
    " *\n" +
    " * line 2\n" +
    " * <pre>\n" +
    " *   line 3\n" +
    " *\n" +
    " *   line 4\n" +
    " * </pre>\n" +
    " */\n" +
    "class Test {\n" +
    "}",
    "/**\n" +
    " * line 1\n" +
    " * <p/>\n" +
    " * line 2\n" +
    " * <pre>\n" +
    " *   line 3\n" +
    " *\n" +
    " *   line 4\n" +
    " * </pre>\n" +
    " */\n" +
    "class Test {\n" +
    "}"
  );
}
 
Example 31
Project: intellij-ce-playground   File: SafeDeleteTest.java   Source Code and License 5 votes vote down vote up
public void testParameterFromFunctionalInterface() throws Exception {
  try {
    LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_8);
    doSingleFileTest();
    fail("Conflict was not detected");
  }
  catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
    String message = e.getMessage();
    assertEquals("class <b><code>SAM</code></b> has 1 usage that is not safe to delete.", message);
  }
}
 
Example 32
Project: intellij-ce-playground   File: PossibleHeapPollutionVarargsInspection.java   Source Code and License 5 votes vote down vote up
@Override
public void visitMethod(PsiMethod method) {
  super.visitMethod(method);
  if (!PsiUtil.getLanguageLevel(method).isAtLeast(LanguageLevel.JDK_1_7)) return;
  if (AnnotationUtil.isAnnotated(method, "java.lang.SafeVarargs", false)) return;
  if (!method.isVarArgs()) return;

  final PsiParameter[] parameters = method.getParameterList().getParameters();
  final PsiParameter psiParameter = parameters[parameters.length - 1];
  if (!psiParameter.isVarArgs()) return;

  final PsiType type = psiParameter.getType();
  LOG.assertTrue(type instanceof PsiEllipsisType, "type: " + type.getCanonicalText() + "; param: " + psiParameter);

  final PsiType componentType = ((PsiEllipsisType)type).getComponentType();
  if (JavaGenericsUtil.isReifiableType(componentType)) {
    return;
  }
  for (PsiReference reference : ReferencesSearch.search(psiParameter)) {
    final PsiElement element = reference.getElement();
    if (element instanceof PsiExpression && !PsiUtil.isAccessedForReading((PsiExpression)element)) {
      return;
    }
  }
  final PsiIdentifier nameIdentifier = method.getNameIdentifier();
  if (nameIdentifier != null) {
    //if (method.hasModifierProperty(PsiModifier.ABSTRACT)) return;
    //final PsiClass containingClass = method.getContainingClass();
    //if (containingClass == null || containingClass.isInterface()) return; do not add
    registerProblem(method, nameIdentifier);
  }
}
 
Example 33
Project: intellij-ce-playground   File: JavaAPIUsagesInspectionTest.java   Source Code and License 5 votes vote down vote up
public void testOverrideAnnotation() throws Exception {
  IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_1_6, new Runnable() {
    @Override
    public void run() {
      doTest();
    }
  });
}
 
Example 34
Project: intellij-ce-playground   File: SwitchUtils.java   Source Code and License 5 votes vote down vote up
private static PsiExpression determinePossibleSwitchExpressions(PsiExpression expression, LanguageLevel languageLevel, boolean nullSafe) {
  expression = ParenthesesUtils.stripParentheses(expression);
  if (expression == null) {
    return null;
  }
  if (languageLevel.isAtLeast(LanguageLevel.JDK_1_7)) {
    final PsiExpression jdk17Expression = determinePossibleStringSwitchExpression(expression, nullSafe);
    if (jdk17Expression != null) {
      return jdk17Expression;
    }
  }
  if (!(expression instanceof PsiPolyadicExpression)) {
    return null;
  }
  final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)expression;
  final IElementType operation = polyadicExpression.getOperationTokenType();
  final PsiExpression[] operands = polyadicExpression.getOperands();
  if (operation.equals(JavaTokenType.OROR) && operands.length > 0) {
    return determinePossibleSwitchExpressions(operands[0], languageLevel, nullSafe);
  }
  else if (operation.equals(JavaTokenType.EQEQ) && operands.length == 2) {
    final PsiExpression lhs = operands[0];
    final PsiExpression rhs = operands[1];
    if (canBeCaseLabel(lhs, languageLevel)) {
      return rhs;
    }
    else if (canBeCaseLabel(rhs, languageLevel)) {
      return lhs;
    }
  }
  return null;
}
 
Example 35
Project: intellij-ce-playground   File: PsiClassImplUtil.java   Source Code and License 5 votes vote down vote up
public static boolean processDeclarationsInClass(@NotNull PsiClass aClass,
                                                 @NotNull final PsiScopeProcessor processor,
                                                 @NotNull ResolveState state,
                                                 @Nullable Set<PsiClass> visited,
                                                 PsiElement last,
                                                 @NotNull PsiElement place,
                                                 @NotNull LanguageLevel languageLevel,
                                                 boolean isRaw) {
  return processDeclarationsInClass(aClass, processor, state, visited, last, place, languageLevel, isRaw, place.getResolveScope());
}
 
Example 36
Project: intellij-ce-playground   File: AndroidProjectDataServiceTest.java   Source Code and License 5 votes vote down vote up
public void testImportData() {
  String jdkPath = Jdks.getJdkHomePath(LanguageLevel.JDK_1_6);

  if (jdkPath != null) {
    VfsRootAccess.allowRootAccess(jdkPath);
  }
  List<DataNode<IdeaAndroidProject>> nodes = Lists.newArrayList();
  Key<IdeaAndroidProject> key = AndroidProjectKeys.IDE_ANDROID_PROJECT;
  nodes.add(new DataNode<IdeaAndroidProject>(key, myIdeaAndroidProject, null));

  assertEquals(key, service.getTargetDataKey());

  final IdeModifiableModelsProviderImpl modelsProvider = new IdeModifiableModelsProviderImpl(myProject);
  // ModuleCustomizers should be called.
  //noinspection ConstantConditions
  myCustomizer1.customizeModule(eq(myProject), eq(myModule), eq(modelsProvider), eq(myIdeaAndroidProject));
  expectLastCall();

  //noinspection ConstantConditions
  myCustomizer2.customizeModule(eq(myProject), eq(myModule), eq(modelsProvider), eq(myIdeaAndroidProject));
  expectLastCall();

  replay(myCustomizer1, myCustomizer2);

  service.importData(nodes, null, myProject, modelsProvider);
  modelsProvider.commit();

  verify(myCustomizer1, myCustomizer2);
}
 
Example 37
Project: intellij-ce-playground   File: StaticPseudoFunctionalStyleMethodTest.java   Source Code and License 5 votes vote down vote up
@Override
protected void tuneFixture(JavaModuleFixtureBuilder moduleBuilder) throws Exception {
  moduleBuilder.setLanguageLevel(LanguageLevel.JDK_1_8);
  moduleBuilder.addLibraryJars("guava-17.0.jar", PathManager.getHomePath().replace(File.separatorChar, '/') + "/community/lib/",
                               "guava-17.0.jar");
  moduleBuilder.addLibraryJars("guava-17.0.jar-2", PathManager.getHomePath().replace(File.separatorChar, '/') + "/lib/",
                               "guava-17.0.jar");
  moduleBuilder.addJdk(IdeaTestUtil.getMockJdk18Path().getPath());
}
 
Example 38
Project: intellij-ce-playground   File: StructuralReplaceTestCase.java   Source Code and License 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();

  StructuralSearchUtil.ourUseUniversalMatchingAlgorithm = false;

  LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_4);

  options = new ReplaceOptions();
  options.setMatchOptions(new MatchOptions());
  replacer = new Replacer(getProject(), null);
}
 
Example 39
Project: intellij-ce-playground   File: PsiResolveHelper.java   Source Code and License 5 votes vote down vote up
@NotNull
PsiSubstitutor inferTypeArguments(@NotNull PsiTypeParameter[] typeParameters,
                                  @NotNull PsiParameter[] parameters,
                                  @NotNull PsiExpression[] arguments,
                                  @NotNull PsiSubstitutor partialSubstitutor,
                                  @NotNull PsiElement parent,
                                  @NotNull ParameterTypeInferencePolicy policy,
                                  @NotNull LanguageLevel languageLevel);
 
Example 40
Project: intellij-ce-playground   File: ClsClassImpl.java   Source Code and License 5 votes vote down vote up
@Override
public boolean processDeclarations(@NotNull PsiScopeProcessor processor,
                                   @NotNull ResolveState state,
                                   PsiElement lastParent,
                                   @NotNull PsiElement place) {
  if (isEnum()) {
    if (!PsiClassImplUtil.processDeclarationsInEnum(processor, state, myInnersCache)) return false;
  }

  LanguageLevel level = processor instanceof MethodsProcessor ? ((MethodsProcessor)processor).getLanguageLevel() : PsiUtil.getLanguageLevel(place);
  return PsiClassImplUtil.processDeclarationsInClass(this, processor, state, null, lastParent, place, level, false);
}