1 /*
   2  * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 package org.graalvm.compiler.options;
  24 
  25 import java.io.PrintStream;
  26 import java.util.ArrayList;
  27 import java.util.Collections;
  28 import java.util.Formatter;
  29 import java.util.List;
  30 import java.util.Map;
  31 import java.util.ServiceLoader;
  32 import java.util.Set;
  33 import java.util.SortedMap;
  34 import java.util.TreeMap;
  35 
  36 /**
  37  * This class contains methods for parsing Graal options and matching them against a set of
  38  * {@link OptionDescriptors}. The {@link OptionDescriptors} are loaded via a {@link ServiceLoader}.
  39  */
  40 public class OptionsParser {
  41 
  42     public interface OptionConsumer {
  43         void set(OptionDescriptor desc, Object value);
  44     }
  45 
  46     /**
  47      * Parses a map representing assignments of values to options.
  48      *
  49      * @param optionSettings option settings (i.e., assignments of values to options)
  50      * @param setter the object to notify of the parsed option and value
  51      * @param loader the loader for {@linkplain #lookup(ServiceLoader, String) looking} up
  52      *            {@link OptionDescriptor}s
  53      * @throws IllegalArgumentException if there's a problem parsing {@code option}
  54      */
  55     public static void parseOptions(Map<String, String> optionSettings, OptionConsumer setter, ServiceLoader<OptionDescriptors> loader) {
  56         if (optionSettings != null && !optionSettings.isEmpty()) {
  57 
  58             for (Map.Entry<String, String> e : optionSettings.entrySet()) {
  59                 parseOption(e.getKey(), e.getValue(), setter, loader);
  60             }
  61         }
  62     }
  63 
  64     /**
  65      * Parses a given option setting string to a map of settings.
  66      *
  67      * @param optionSetting a string matching the pattern {@code <name>=<value>}
  68      */
  69     public static void parseOptionSettingTo(String optionSetting, Map<String, String> dst) {
  70         int eqIndex = optionSetting.indexOf('=');
  71         if (eqIndex == -1) {
  72             throw new InternalError("Option setting has does not match the pattern <name>=<value>: " + optionSetting);
  73         }
  74         dst.put(optionSetting.substring(0, eqIndex), optionSetting.substring(eqIndex + 1));
  75     }
  76 
  77     /**
  78      * Looks up an {@link OptionDescriptor} based on a given name.
  79      *
  80      * @param loader provides the available {@link OptionDescriptor}s
  81      * @param name the name of the option to look up
  82      * @return the {@link OptionDescriptor} whose name equals {@code name} or null if not such
  83      *         descriptor is available
  84      */
  85     private static OptionDescriptor lookup(ServiceLoader<OptionDescriptors> loader, String name) {
  86         for (OptionDescriptors optionDescriptors : loader) {
  87             OptionDescriptor desc = optionDescriptors.get(name);
  88             if (desc != null) {
  89                 return desc;
  90             }
  91         }
  92         return null;
  93     }
  94 
  95     /**
  96      * Parses a given option name and value.
  97      *
  98      * @param name the option name
  99      * @param valueString the option value as a string
 100      * @param setter the object to notify of the parsed option and value
 101      * @param loader the loader for {@linkplain #lookup(ServiceLoader, String) looking} up
 102      *            {@link OptionDescriptor}s
 103      * @throws IllegalArgumentException if there's a problem parsing {@code option}
 104      */
 105     private static void parseOption(String name, String valueString, OptionConsumer setter, ServiceLoader<OptionDescriptors> loader) {
 106 
 107         OptionDescriptor desc = lookup(loader, name);
 108         if (desc == null) {
 109             List<OptionDescriptor> matches = fuzzyMatch(loader, name);
 110             Formatter msg = new Formatter();
 111             msg.format("Could not find option %s", name);
 112             if (!matches.isEmpty()) {
 113                 msg.format("%nDid you mean one of the following?");
 114                 for (OptionDescriptor match : matches) {
 115                     msg.format("%n    %s=<value>", match.getName());
 116                 }
 117             }
 118             throw new IllegalArgumentException(msg.toString());
 119         }
 120 
 121         Class<?> optionType = desc.getType();
 122         Object value;
 123         if (optionType == Boolean.class) {
 124             if ("true".equals(valueString)) {
 125                 value = Boolean.TRUE;
 126             } else if ("false".equals(valueString)) {
 127                 value = Boolean.FALSE;
 128             } else {
 129                 throw new IllegalArgumentException("Boolean option '" + name + "' must have value \"true\" or \"false\", not \"" + valueString + "\"");
 130             }
 131         } else if (optionType == String.class || Enum.class.isAssignableFrom(optionType)) {
 132             value = valueString;
 133         } else {
 134             if (valueString.isEmpty()) {
 135                 throw new IllegalArgumentException("Non empty value required for option '" + name + "'");
 136             }
 137             try {
 138                 if (optionType == Float.class) {
 139                     value = Float.parseFloat(valueString);
 140                 } else if (optionType == Double.class) {
 141                     value = Double.parseDouble(valueString);
 142                 } else if (optionType == Integer.class) {
 143                     value = Integer.valueOf((int) parseLong(valueString));
 144                 } else if (optionType == Long.class) {
 145                     value = Long.valueOf(parseLong(valueString));
 146                 } else {
 147                     throw new IllegalArgumentException("Wrong value for option '" + name + "'");
 148                 }
 149             } catch (NumberFormatException nfe) {
 150                 throw new IllegalArgumentException("Value for option '" + name + "' has invalid number format: " + valueString);
 151             }
 152         }
 153         if (setter == null) {
 154             desc.getOptionValue().setValue(value);
 155         } else {
 156             setter.set(desc, value);
 157         }
 158     }
 159 
 160     private static long parseLong(String v) {
 161         String valueString = v.toLowerCase();
 162         long scale = 1;
 163         if (valueString.endsWith("k")) {
 164             scale = 1024L;
 165         } else if (valueString.endsWith("m")) {
 166             scale = 1024L * 1024L;
 167         } else if (valueString.endsWith("g")) {
 168             scale = 1024L * 1024L * 1024L;
 169         } else if (valueString.endsWith("t")) {
 170             scale = 1024L * 1024L * 1024L * 1024L;
 171         }
 172 
 173         if (scale != 1) {
 174             /* Remove trailing scale character. */
 175             valueString = valueString.substring(0, valueString.length() - 1);
 176         }
 177 
 178         return Long.parseLong(valueString) * scale;
 179     }
 180 
 181     /**
 182      * Wraps some given text to one or more lines of a given maximum width.
 183      *
 184      * @param text text to wrap
 185      * @param width maximum width of an output line, exception for words in {@code text} longer than
 186      *            this value
 187      * @return {@code text} broken into lines
 188      */
 189     private static List<String> wrap(String text, int width) {
 190         List<String> lines = Collections.singletonList(text);
 191         if (text.length() > width) {
 192             String[] chunks = text.split("\\s+");
 193             lines = new ArrayList<>();
 194             StringBuilder line = new StringBuilder();
 195             for (String chunk : chunks) {
 196                 if (line.length() + chunk.length() > width) {
 197                     lines.add(line.toString());
 198                     line.setLength(0);
 199                 }
 200                 if (line.length() != 0) {
 201                     line.append(' ');
 202                 }
 203                 String[] embeddedLines = chunk.split("%n", -2);
 204                 if (embeddedLines.length == 1) {
 205                     line.append(chunk);
 206                 } else {
 207                     for (int i = 0; i < embeddedLines.length; i++) {
 208                         line.append(embeddedLines[i]);
 209                         if (i < embeddedLines.length - 1) {
 210                             lines.add(line.toString());
 211                             line.setLength(0);
 212                         }
 213                     }
 214                 }
 215             }
 216             if (line.length() != 0) {
 217                 lines.add(line.toString());
 218             }
 219         }
 220         return lines;
 221     }
 222 
 223     private static final int PROPERTY_LINE_WIDTH = 80;
 224     private static final int PROPERTY_HELP_INDENT = 10;
 225 
 226     public static void printFlags(ServiceLoader<OptionDescriptors> loader, PrintStream out, Set<String> explicitlyAssigned, String namePrefix) {
 227         SortedMap<String, OptionDescriptor> sortedOptions = new TreeMap<>();
 228         for (OptionDescriptors opts : loader) {
 229             for (OptionDescriptor desc : opts) {
 230                 String name = desc.getName();
 231                 OptionDescriptor existing = sortedOptions.put(name, desc);
 232                 assert existing == null : "Option named \"" + name + "\" has multiple definitions: " + existing.getLocation() + " and " + desc.getLocation();
 233             }
 234         }
 235         for (Map.Entry<String, OptionDescriptor> e : sortedOptions.entrySet()) {
 236             OptionDescriptor desc = e.getValue();
 237             Object value = desc.getOptionValue().getValue();
 238             if (value instanceof String) {
 239                 value = '"' + String.valueOf(value) + '"';
 240             }
 241             String help = desc.getHelp();
 242             if (desc.getOptionValue() instanceof EnumOptionValue) {
 243                 EnumOptionValue<?> eoption = (EnumOptionValue<?>) desc.getOptionValue();
 244                 String evalues = eoption.getOptionValues().toString();
 245                 if (help.length() > 0 && !help.endsWith(".")) {
 246                     help += ".";
 247                 }
 248                 help += " Valid values are: " + evalues.substring(1, evalues.length() - 1);
 249             }
 250             String name = namePrefix + e.getKey();
 251             String assign = explicitlyAssigned.contains(name) ? ":=" : "=";
 252             String typeName = desc.getOptionValue() instanceof EnumOptionValue ? "String" : desc.getType().getSimpleName();
 253             String linePrefix = String.format("%s %s %s ", name, assign, value);
 254             int typeStartPos = PROPERTY_LINE_WIDTH - typeName.length();
 255             int linePad = typeStartPos - linePrefix.length();
 256             if (linePad > 0) {
 257                 out.printf("%s%-" + linePad + "s[%s]%n", linePrefix, "", typeName);
 258             } else {
 259                 out.printf("%s[%s]%n", linePrefix, typeName);
 260             }
 261 
 262             if (help.length() != 0) {
 263                 List<String> helpLines = wrap(help, PROPERTY_LINE_WIDTH - PROPERTY_HELP_INDENT);
 264                 for (int i = 0; i < helpLines.size(); i++) {
 265                     out.printf("%" + PROPERTY_HELP_INDENT + "s%s%n", "", helpLines.get(i));
 266                 }
 267             }
 268         }
 269     }
 270 
 271     /**
 272      * Compute string similarity based on Dice's coefficient.
 273      *
 274      * Ported from str_similar() in globals.cpp.
 275      */
 276     static float stringSimiliarity(String str1, String str2) {
 277         int hit = 0;
 278         for (int i = 0; i < str1.length() - 1; ++i) {
 279             for (int j = 0; j < str2.length() - 1; ++j) {
 280                 if ((str1.charAt(i) == str2.charAt(j)) && (str1.charAt(i + 1) == str2.charAt(j + 1))) {
 281                     ++hit;
 282                     break;
 283                 }
 284             }
 285         }
 286         return 2.0f * hit / (str1.length() + str2.length());
 287     }
 288 
 289     private static final float FUZZY_MATCH_THRESHOLD = 0.7F;
 290 
 291     /**
 292      * Returns the set of options that fuzzy match a given option name.
 293      */
 294     private static List<OptionDescriptor> fuzzyMatch(ServiceLoader<OptionDescriptors> loader, String optionName) {
 295         List<OptionDescriptor> matches = new ArrayList<>();
 296         for (OptionDescriptors options : loader) {
 297             for (OptionDescriptor option : options) {
 298                 float score = stringSimiliarity(option.getName(), optionName);
 299                 if (score >= FUZZY_MATCH_THRESHOLD) {
 300                     matches.add(option);
 301                 }
 302             }
 303         }
 304         return matches;
 305     }
 306 }