11package org .jetbrains .plugins .scala .annotator .element
22
3- import com .intellij .openapi .application .ApplicationManager
4- import org .jetbrains .plugins .scala .{ScalaBundle , ScalaFileType }
3+ import org .jetbrains .plugins .scala .ScalaBundle
54import org .jetbrains .plugins .scala .annotator .ScalaAnnotationHolder
65import org .jetbrains .plugins .scala .extensions .{ObjectExt , PsiElementExt }
76import org .jetbrains .plugins .scala .lang .lexer .ScalaTokenTypes
7+ import org .jetbrains .plugins .scala .lang .psi .api .ScPackageLike
88import org .jetbrains .plugins .scala .lang .psi .api .statements .{ScFunction , ScTypeAlias , ScValueOrVariable }
99import org .jetbrains .plugins .scala .lang .psi .api .toplevel .typedef .ScMember
10- import org .jetbrains .plugins .scala .lang .psi .impl .ScalaFileImpl
1110
1211object ScMemberAnnotator extends ElementAnnotator [ScMember ] {
1312
@@ -16,15 +15,18 @@ object ScMemberAnnotator extends ElementAnnotator[ScMember] {
1615 annotateWrongTopLevelMembers(element)
1716 }
1817
19- // TODO package private
2018 private def annotateWrongTopLevelMembers (element : ScMember )
2119 (implicit holder : ScalaAnnotationHolder ): Unit = {
2220 if (
2321 element.isTopLevel &&
2422 cannotBeTopLevelMemberInScala2(element) &&
2523 element.scalaLanguageLevel.exists(_.isScala2) &&
26- element.containingScalaFile.exists(file => file.getFileType == ScalaFileType .INSTANCE && ! file.isWorksheetFile) &&
27- ! ApplicationManager .getApplication.isUnitTestMode
24+ // The problem is that we have many situations when it's not clear whether top-level definitions are allowed,
25+ // because we are not in a real scala file, but some unittest or scripting editor.
26+ // We know, however, that when a definition is in a package then it's not allowed.
27+ // This fix might not be 100% correct, but I think the false positives are much worse than the false negatives.
28+ // So it's better not to annotate a top-level val that is not allowed in scala 2 than annotating one that is allowed.
29+ element.parents.exists(_.is[ScPackageLike ])
2830 ) {
2931 val elementToAnnotate = element.depthFirst().find(c => keywords(c.elementType)).getOrElse(element)
3032 holder.createErrorAnnotation(elementToAnnotate, ScalaBundle .message(" cannot.be.a.top.level.definition.in.scala.2" ))
0 commit comments