001package org.clafer.frontend; 002 003import java.util.ArrayList; 004import java.util.List; 005import java.util.Map; 006 007/** 008 * The scopes that chocosolver solves an explicit model with, as the compiler 009 * writes them to the explicit model's scope file ({@code clafer -m clafer 010 * --meta-data}, {@code model.des.cfr-scope}). 011 * 012 * @param clafers the scope of every clafer, by UID, sorted, the enumerations 013 * and their literals included 014 * @param intLow the smallest integer, {@code --minint} or -128 015 * @param intHigh the largest integer, {@code --maxint} or 127 016 * @param stringLength the length of the longest string literal, with its 017 * quotes, at least 16 018 * @param decimalDigits the number of fractional digits of decimals, 0 if the 019 * model has none and no {@code --decimal-digits} 020 */ 021public record Scopes(Map<String, Long> clafers, long intLow, long intHigh, int stringLength, long decimalDigits) { 022 023 /** 024 * chocosolver's largest decimal, {@code Integer.MAX_VALUE / 100 - 1}, 025 * scaled. 026 */ 027 private static final long MaxScaledDecimal = 21474835; 028 029 /** 030 * @return the scope file, as the compiler writes it 031 * ({@code Explicit.explicitScopes}) 032 */ 033 public String scopeFile() { 034 List<String> entries = new ArrayList<>(); 035 clafers.forEach((uid, scope) -> entries.add("{\"lpqName\": \"" + uid + "\", \"scope\": " + scope + "}")); 036 entries.add("{\"defaultScope\": 1}"); 037 entries.add("{\"int\": [" + intLow + ", " + intHigh + "]}"); 038 entries.add("{\"mul\": [" + intLow + ", " + intHigh + "]}"); 039 entries.add("{\"stringLength\": " + stringLength + "}"); 040 entries.add("{\"chars\": [32, 126]}"); 041 entries.add("{\"decimalDigits\": " + decimalDigits + "}"); 042 entries.add("{\"decimal\": [" + unscaled(-MaxScaledDecimal) + ", " + unscaled(MaxScaledDecimal) + "]}"); 043 return "[\n" + String.join(",\n", entries) + "\n]\n"; 044 } 045 046 /** 047 * A scaled decimal as written, e.g., 214748.35 for 21474835 with 2 048 * digits. 049 */ 050 private String unscaled(long n) { 051 String digits = Long.toString(Math.abs(n)); 052 int scale = (int) decimalDigits; 053 String padded = "0".repeat(Math.max(0, scale + 1 - digits.length())) + digits; 054 String whole = padded.substring(0, padded.length() - scale); 055 String fraction = padded.substring(padded.length() - scale); 056 return (n < 0 ? "-" : "") + whole + (scale > 0 ? "." + fraction : ""); 057 } 058}