<commit_before>/*
 * Copyright 2000-2011 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jetbrains.plugins.groovy.lang.completion;

import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.codeInsight.lookup.TailTypeDecorator;
import com.intellij.patterns.PsiElementPattern;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.PairConsumer;
import com.intellij.util.ProcessingContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.extensions.ConfigSlurperSupport;
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.*;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl;
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;

import java.util.*;
import java.util.List;

import static com.intellij.patterns.PlatformPatterns.psiElement;

/**
 * @author <NAME>
 */
class GroovyConfigSlurperCompletionProvider extends CompletionProvider<CompletionParameters> {

  private final boolean myAddPrefixes;

  GroovyConfigSlurperCompletionProvider(boolean addPrefixes) {
    myAddPrefixes = addPrefixes;
  }

  public static void register(CompletionContributor contributor) {
    PsiElementPattern.Capture<PsiElement> pattern = psiElement().withParent(psiElement(GrReferenceExpression.class));

    contributor.extend(CompletionType.BASIC, pattern, new GroovyConfigSlurperCompletionProvider(true));
    contributor.extend(CompletionType.SMART, pattern, new GroovyConfigSlurperCompletionProvider(false));
  }

  @Override
  protected void addCompletions(@NotNull CompletionParameters parameters,
                                ProcessingContext context,
                                @NotNull CompletionResultSet result) {
    PsiFile file = parameters.getOriginalFile();
    if (!(file instanceof GroovyFile)) return;

    GroovyFile groovyFile = (GroovyFile)file;

    if (!groovyFile.isScript()) return;

    GrReferenceExpression ref = (GrReferenceExpression)parameters.getPosition().getParent();
    if (ref == null) return;

    final Map<String, Boolean> variants = new HashMap<String, Boolean>();
    collectVariants(new PairConsumer<String, Boolean>() {
                      @Override
                      public void consume(String s, Boolean isFinal) {
                        variants.put(s, isFinal);
                      }
                    }, ref, groovyFile);

    if (variants.isEmpty()) return;

    // Remove existing variants.
    PsiElement parent = ref.getParent();
    if (parent instanceof GrAssignmentExpression) {
      parent = parent.getParent();
    }
    if (parent == null) return;

    Set<String> processedPrefixes = new HashSet<String>();
    Set<String> prefixesInMethodCall = new HashSet<String>();

    for (PsiElement e = parent.getFirstChild(); e != null; e = e.getNextSibling()) {
      if (e instanceof GrAssignmentExpression) {
        PsiElement left = ((GrAssignmentExpression)e).getLValue();
        if (left instanceof GrReferenceExpression) {
          String s = refToString((GrReferenceExpression)left);
          if (s == null) continue;

          int dotIndex = s.indexOf('.');
          if (dotIndex > 0) {
            processedPrefixes.add(s.substring(0, dotIndex));
          }

          variants.remove(s);
        }
      }
      else if (e instanceof GrMethodCall) {
        GrMethodCall call = (GrMethodCall)e;
        if (isPropertyCall(call)) {
          String name = extractPropertyName(call);
          if (name == null) continue;

          processedPrefixes.add(name);
          prefixesInMethodCall.add(name);
          variants.remove(name);
        }
      }
    }

    // Process variants.
    for (Map.Entry<String, Boolean> entry : variants.entrySet()) {
      String variant = entry.getKey();

      int dotIndex = variant.indexOf('.');
      if (dotIndex > 0 && dotIndex < variant.length() - 1) {
        String p = variant.substring(0, dotIndex);
        if (prefixesInMethodCall.contains(p)) continue;

        if (myAddPrefixes && processedPrefixes.add(p)) {
          result.addElement(LookupElementBuilder.create(p));
        }
      }

      LookupElement lookupElement = LookupElementBuilder.create(variant);
      if (entry.getValue()) {
        lookupElement = TailTypeDecorator.withTail(lookupElement, TailType.EQ);
      }

      result.addElement(lookupElement);
    }
  }

  private static void collectVariants(@NotNull PairConsumer<String, Boolean> consumer, @NotNull GrReferenceExpression ref, @NotNull GroovyFile originalFile) {
    List<String> prefix = null;

    for (ConfigSlurperSupport configSlurperSupport : ConfigSlurperSupport.EP_NAME.getExtensions()) {
      ConfigSlurperSupport.PropertiesProvider provider = configSlurperSupport.getProvider(originalFile);
      if (provider == null) continue;

      if (prefix == null) {
        prefix = getPrefix(ref);
        if (prefix == null) return;
      }

      provider.collectVariants(prefix, consumer);
    }
  }

  @Nullable
  private static String refToString(GrReferenceExpression ref) {<commit_msg>Bug fix: All Grails properties can be used with "environment.*." prefix.<commit_after>/*
 * Copyright 2000-2011 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jetbrains.plugins.groovy.lang.completion;

import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.codeInsight.lookup.TailTypeDecorator;
import com.intellij.patterns.PsiElementPattern;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.PairConsumer;
import com.intellij.util.ProcessingContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.extensions.ConfigSlurperSupport;
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.*;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl;
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;

import java.util.*;
import java.util.List;

import static com.intellij.patterns.PlatformPatterns.psiElement;

/**
 * @author <NAME>
 */
class GroovyConfigSlurperCompletionProvider extends CompletionProvider<CompletionParameters> {

  private final boolean myAddPrefixes;

  GroovyConfigSlurperCompletionProvider(boolean addPrefixes) {
    myAddPrefixes = addPrefixes;
  }

  public static void register(CompletionContributor contributor) {
    PsiElementPattern.Capture<PsiElement> pattern = psiElement().withParent(psiElement(GrReferenceExpression.class));

    contributor.extend(CompletionType.BASIC, pattern, new GroovyConfigSlurperCompletionProvider(true));
    contributor.extend(CompletionType.SMART, pattern, new GroovyConfigSlurperCompletionProvider(false));
  }

  @Override
  protected void addCompletions(@NotNull CompletionParameters parameters,
                                ProcessingContext context,
                                @NotNull CompletionResultSet result) {
    PsiFile file = parameters.getOriginalFile();
    if (!(file instanceof GroovyFile)) return;

    GroovyFile groovyFile = (GroovyFile)file;

    if (!groovyFile.isScript()) return;

    GrReferenceExpression ref = (GrReferenceExpression)parameters.getPosition().getParent();
    if (ref == null) return;

    final Map<String, Boolean> variants = new HashMap<String, Boolean>();
    collectVariants(new PairConsumer<String, Boolean>() {
                      @Override
                      public void consume(String s, Boolean isFinal) {
                        variants.put(s, isFinal);
                      }
                    }, ref, groovyFile);

    if (variants.isEmpty()) return;

    // Remove existing variants.
    PsiElement parent = ref.getParent();
    if (parent instanceof GrAssignmentExpression) {
      parent = parent.getParent();
    }
    if (parent == null) return;

    Set<String> processedPrefixes = new HashSet<String>();
    Set<String> prefixesInMethodCall = new HashSet<String>();

    for (PsiElement e = parent.getFirstChild(); e != null; e = e.getNextSibling()) {
      if (e instanceof GrAssignmentExpression) {
        PsiElement left = ((GrAssignmentExpression)e).getLValue();
        if (left instanceof GrReferenceExpression) {
          String s = refToString((GrReferenceExpression)left);
          if (s == null) continue;

          int dotIndex = s.indexOf('.');
          if (dotIndex > 0) {
            processedPrefixes.add(s.substring(0, dotIndex));
          }

          variants.remove(s);
        }
      }
      else if (e instanceof GrMethodCall) {
        GrMethodCall call = (GrMethodCall)e;
        if (isPropertyCall(call)) {
          String name = extractPropertyName(call);
          if (name == null) continue;

          processedPrefixes.add(name);
          prefixesInMethodCall.add(name);
          variants.remove(name);
        }
      }
    }

    // Process variants.
    for (Map.Entry<String, Boolean> entry : variants.entrySet()) {
      String variant = entry.getKey();

      int dotIndex = variant.indexOf('.');
      if (dotIndex > 0 && dotIndex < variant.length() - 1) {
        String p = variant.substring(0, dotIndex);
        if (prefixesInMethodCall.contains(p)) continue;

        if (myAddPrefixes && processedPrefixes.add(p)) {
          result.addElement(LookupElementBuilder.create(p));
        }
      }

      LookupElement lookupElement = LookupElementBuilder.create(variant);
      if (entry.getValue()) {
        lookupElement = TailTypeDecorator.withTail(lookupElement, TailType.EQ);
      }

      result.addElement(lookupElement);
    }
  }

  private static void collectVariants(@NotNull PairConsumer<String, Boolean> consumer, @NotNull GrReferenceExpression ref, @NotNull GroovyFile originalFile) {
    List<String> prefix = getPrefix(ref);
    if (prefix == null) return;

    for (ConfigSlurperSupport configSlurperSupport : ConfigSlurperSupport.EP_NAME.getExtensions()) {
      ConfigSlurperSupport.PropertiesProvider provider = configSlurperSupport.getProvider(originalFile);
      if (provider == null) continue;

      provider.collectVariants(prefix, consumer);
    }
  }

  @Nullable
  private static String refToString(GrReferenceExpression ref) {
{'fraction_non_alphanumeric': 0.10177025657022537, 'fraction_numerical': 0.0026514856117913124, 'mean_word_length': 3.6063218390804597, 'pattern_counts': {'":': 0, '<': 31, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1379622', 'n_tokens_mistral': 3694, 'n_tokens_neox': 3497, 'n_words': 777}