// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.transformations.impl;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrScriptField;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass;
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames;
import org.jetbrains.plugins.groovy.transformations.AstTransformationSupport;
import org.jetbrains.plugins.groovy.transformations.TransformationContext;

import static com.intellij.psi.impl.cache.impl.id.IdIndex.hasIdentifierInFile;

public class FieldScriptTransformationSupport implements AstTransformationSupport {
  @Override
  public void applyTransformation(@NotNull TransformationContext context) {
    if (!(context.getCodeClass() instanceof GroovyScriptClass)) return;
    final GroovyScriptClass scriptClass = (GroovyScriptClass)context.getCodeClass();
    if (!hasIdentifierInFile(scriptClass.getContainingFile(), "Field")) {
      return;
    }
    for (GrVariableDeclaration declaration : scriptClass.getContainingFile().getScriptDeclarations(true)) {
      if (declaration.getModifierList().hasAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_FIELD)) {
        for (GrVariable variable : declaration.getVariables()) {
          context.addField(new GrScriptField(variable, scriptClass));
        }
      }
    }
  }
}

@@ -18,9 +18,9 @@
 -201
-8
+9
  Jet
@@ -236,16 +236,73 @@
 otNull;%0A
+import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;%0A
 import o
@@ -908,16 +908,100 @@
 rInFile;
+%0Aimport static org.jetbrains.plugins.groovy.util.GrFileIndexUtil.isGroovySourceFile;
 %0A%0Apublic
@@ -1331,33 +1331,42 @@
     
-if (!hasIdentifierIn
+final GroovyFile containing
 File
-(
+ = 
 scri
@@ -1392,16 +1392,99 @@
 ngFile()
+;%0A    if (isGroovySourceFile(containingFile) && !hasIdentifierInFile(containingFile
 , %22Field
@@ -1554,32 +1554,17 @@
 ation : 
-scriptClass.getC
+c
 ontainin
@@ -1568,18 +1568,16 @@
 ningFile
-()
 .getScri

check if groovy file is inside sources before checking if `Field` identifier is in this file (IDEA-211117)