package com.yahoo.searchdefinition.processing;

import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.searchdefinition.RankProfile;
import com.yahoo.searchdefinition.RankProfileRegistry;
import com.yahoo.searchdefinition.Search;
import com.yahoo.searchlib.rankingexpression.parser.RankingExpressionParserConstants;
import com.yahoo.vespa.model.container.search.QueryProfiles;

import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;

/**
 * Issues a warning if some macro has a reserved name. This is not necessarily
 * an error, as a macro can shadow a built-in function.
 *
 * @author lesters
 */
public class ReservedMacroNames extends Processor {
    private static Set<String> reservedNames = getReservedNames();

    public ReservedMacroNames(Search search, DeployLogger deployLogger, RankProfileRegistry rankProfileRegistry, QueryProfiles queryProfiles) {
        super(search, deployLogger, rankProfileRegistry, queryProfiles);
    }

    @Override
    public void process() {
        for (RankProfile rp : rankProfileRegistry.allRankProfiles()) {
            for (String macroName : rp.getMacros().keySet()) {
                if (reservedNames.contains(macroName)) {
                    deployLogger.log(Level.WARNING, "Macro \"" + macroName + "\" " +
                            "in rank profile \"" + rp.getName() + "\" " +
                            "has a reserved name. This might mean that the macro shadows " +
                            "the built-in function with the same name."
                    );
                }
            }
        }
    }

    private static Set<String> getReservedNames() {
        Set<String> names = new HashSet<>();
        for (String token : RankingExpressionParserConstants.tokenImage) {
            String tokenWithoutQuotes = token.substring(1, token.length()-1);
            names.add(tokenWithoutQuotes);
        }
        return names;
    }
}

@@ -41,16 +41,63 @@
 ssing;%0A%0A
+import com.google.common.collect.ImmutableSet;%0A
 import c
@@ -1664,32 +1664,41 @@
  private static 
+Immutable
 Set%3CString%3E getR
@@ -1726,41 +1726,65 @@
     
-Set%3CString%3E names = new HashSet%3C%3E
+ImmutableSet.Builder%3CString%3E names = ImmutableSet.builder
 ();%0A
@@ -2009,16 +2009,24 @@
 rn names
+.build()
 ;%0A    %7D%0A

Use ImmutableSet