001// ***** This file is automatically generated from SeqIndexComparison.java.jpp
002
003package daikon.inv.unary.sequence;
004
005import daikon.*;
006import daikon.Quantify.QuantFlags;
007import daikon.inv.*;
008import daikon.inv.binary.twoSequence.*;
009import daikon.suppress.*;
010import java.util.Arrays;
011import java.util.Iterator;
012import java.util.logging.Logger;
013import org.checkerframework.checker.interning.qual.Interned;
014import org.checkerframework.checker.lock.qual.GuardSatisfied;
015import org.checkerframework.checker.nullness.qual.NonNull;
016import org.checkerframework.checker.nullness.qual.Nullable;
017import org.checkerframework.dataflow.qual.Pure;
018import org.checkerframework.dataflow.qual.SideEffectFree;
019import org.plumelib.util.Intern;
020import typequals.prototype.qual.NonPrototype;
021import typequals.prototype.qual.Prototype;
022
023/**
024 * Represents an invariant over sequences of double values between the index of an element of the
025 * sequence and the element itself. Prints as {@code x[i] < i}.
026 */
027public class SeqIndexFloatLessThan extends SingleFloatSequence {
028  // We are Serializable, so we specify a version to allow changes to
029  // method signatures without breaking serialization.  If you add or
030  // remove fields, you should change this number to the current date.
031  static final long serialVersionUID = 20040203L;
032
033  /** Debug tracer. */
034  public static final Logger debug =
035    Logger.getLogger("daikon.inv.unary.sequence.SeqIndexFloatLessThan");
036
037  // Variables starting with dkconfig_ should only be set via the
038  // daikon.config.Configuration interface.
039  /** Boolean. True iff SeqIndexFloatLessThan invariants should be considered. */
040  public static boolean dkconfig_enabled = false;
041
042  private @Prototype SeqIndexFloatLessThan() {
043    super();
044  }
045
046  protected SeqIndexFloatLessThan(PptSlice slice) {
047    super(slice);
048    assert slice != null;
049    assert var().rep_type == ProglangType.DOUBLE_ARRAY;
050  }
051
052  private static @Prototype SeqIndexFloatLessThan proto = new @Prototype SeqIndexFloatLessThan();
053
054  /** Returns the prototype invariant for SeqIndexFloatLessThan */
055  public static @Prototype SeqIndexFloatLessThan get_proto() {
056    return proto;
057  }
058
059  /** returns whether or not we are enabled */
060  @Override
061  public boolean enabled() {
062    return dkconfig_enabled && !dkconfig_SeqIndexDisableAll;
063  }
064
065  /** Check that SeqIndex comparisons make sense over these vars. */
066  @Override
067  public boolean instantiate_ok(VarInfo[] vis) {
068
069    if (!valid_types(vis)) {
070      return false;
071    }
072
073    // Don't compare indices to object addresses.
074    ProglangType elt_type = vis[0].file_rep_type.elementType();
075    if (!elt_type.baseIsFloat()) {
076      return false;
077    }
078
079    // Make sure that the indices are comparable to the elements
080    VarInfo seqvar = vis[0];
081    assert seqvar.comparability != null;
082    VarComparability elt_compar = seqvar.comparability.elementType();
083    VarComparability index_compar = seqvar.comparability.indexType(0);
084    if (!VarComparability.comparable(elt_compar, index_compar)) {
085      return false;
086    }
087
088    return true;
089  }
090
091  /** Instantiate the invariant on the specified slice. */
092  @Override
093  public SeqIndexFloatLessThan instantiate_dyn(@Prototype SeqIndexFloatLessThan this, PptSlice slice) {
094    return new SeqIndexFloatLessThan(slice);
095  }
096
097  /** returns the ni-suppressions for SeqIndexFloatLessThan */
098  @Pure
099  @Override
100  public @Nullable NISuppressionSet get_ni_suppressions() {
101    return null;
102  }
103
104  protected Invariant resurrect_done_swapped() {
105
106      return new SeqIndexFloatGreaterThan(ppt);
107  }
108
109  public String getComparator() {
110    return "<";
111  }
112
113  @SideEffectFree
114  @Override
115  public String format_using(@GuardSatisfied SeqIndexFloatLessThan this, OutputFormat format) {
116    if (format.isJavaFamily()) {
117      return format_java_family(format);
118    }
119
120    // TODO: Eliminate the unnecessary format_xxx() below if the
121    // format_java_family() can handle all the Java family output.
122
123    if (format == OutputFormat.DAIKON) {
124      return format_daikon();
125    }
126    if (format == OutputFormat.ESCJAVA) {
127      return format_esc();
128    }
129    if (format == OutputFormat.CSHARPCONTRACT) {
130      return format_csharp_contract();
131    }
132    if (format == OutputFormat.SIMPLIFY) {
133      return format_simplify();
134    }
135
136    return format_unimplemented(format);
137  }
138
139  public String format_daikon(@GuardSatisfied SeqIndexFloatLessThan this) {
140
141    // If this is an array/container and not a subsequence
142    if (var().isDerivedSubSequenceOf() == null) {
143      return var().apply_subscript("i") + " < i";
144    } else {
145      return var().name() + " < (index)";
146    }
147  }
148
149  // Bad code here: if the first index is changed from i this breaks
150  public String format_esc(@GuardSatisfied SeqIndexFloatLessThan this) {
151    String[] form = VarInfo.esc_quantify(var());
152    return form[0] + "(" + form[1] + " < i)" + form[2];
153  }
154
155  public String format_csharp_contract(@GuardSatisfied SeqIndexFloatLessThan this) {
156    String[] split = var().csharp_array_split();
157    return "Contract.ForAll(0, " + split[0] + ".Count(), i => " + split[0] + "[i]" + split[1] + " < i)";
158  }
159
160  public String format_java_family(@GuardSatisfied SeqIndexFloatLessThan this, OutputFormat format) {
161    return "daikon.Quant.eltsLtIndex("
162      + var().name_using(format) + ")";
163  }
164
165  public String format_simplify(@GuardSatisfied SeqIndexFloatLessThan this) {
166    String[] form = VarInfo.simplify_quantify(QuantFlags.include_index(),
167                                               var());
168    return form[0] + "(< " + form[1] + " " + form[2] + ")"
169      + form[3];
170  }
171
172  @Override
173  public InvariantStatus check_modified(double @Interned [] a, int count) {
174    for (int i = 0; i < a.length; i++) {
175      if (!Global.fuzzy.lt(a[i], i)) {
176        return InvariantStatus.FALSIFIED;
177      }
178    }
179    return InvariantStatus.NO_CHANGE;
180  }
181
182  @Override
183  public InvariantStatus add_modified(double @Interned [] a, int count) {
184
185    if (logDetail()) {
186      log("Entered add_modified: ppt.num_values()==%s, sample==%s",
187           ppt.num_values(), Arrays.toString(a));
188    }
189    InvariantStatus stat = check_modified(a, count);
190    if (logDetail()) {
191      log("Exiting add_modified status = %s", stat);
192    }
193
194    return stat;
195  }
196
197  @Override
198  @SuppressWarnings("UnnecessaryParentheses")  // generated code, parentheses are sometimes needed
199  protected double computeConfidence() {
200
201    // Make sure there have been some elements in the sequence
202    ValueSet.ValueSetFloatArray vs = (ValueSet.ValueSetFloatArray) ppt.var_infos[0].get_value_set();
203    if (vs.elem_cnt() == 0) {
204      return Invariant.CONFIDENCE_UNJUSTIFIED;
205    }
206
207    int num_values = ppt.num_values();
208    if (num_values == 0) {
209      return Invariant.CONFIDENCE_UNJUSTIFIED;
210    }
211
212      return 1 - Math.pow(.5, num_values);
213  }
214
215  @Pure
216  @Override
217  public boolean isSameFormula(Invariant other) {
218    return true;
219  }
220
221  @Pure
222  @Override
223  public boolean isExclusiveFormula(Invariant other) {
224    return false;
225  }
226
227  // Look up a previously instantiated invariant.
228  public static @Nullable SeqIndexFloatLessThan find(PptSlice ppt) {
229    assert ppt.arity() == 1;
230    for (Invariant inv : ppt.invs) {
231      if (inv instanceof SeqIndexFloatLessThan) {
232        return (SeqIndexFloatLessThan) inv;
233      }
234    }
235    return null;
236  }
237
238  /**
239   * Checks to see if this is obvious over the specified variables Implements the following checks:
240   *
241   * <pre>
242   *    (A[] subsequence B[]) ^ (B[i] op i) &rArr; A[i] op i
243   * </pre>
244   *
245   * JHP: Its not obvious (to me) that this is true except when the subsequence starts at index
246   * 0. If B[] = {0, 1, 2, 3, 4} and A[] = {2, 3, 4}, A[] is a subsequence of B[] and B[i] == i, but
247   * A[i] = i is not true.
248   */
249  @Pure
250  @Override
251  public @Nullable DiscardInfo isObviousDynamically(VarInfo[] vis) {
252
253    DiscardInfo super_result = super.isObviousDynamically(vis);
254    if (super_result != null) {
255      return super_result;
256    }
257
258    VarInfo seqvar = vis[0];
259
260    // For each other sequence variable, if it is a supersequence of this
261    // one and it has the same invariant, then this one is obvious.
262    // We have to check for the same equality set here, because
263    // isObviousDynamically is called for each member of the equality set.
264    // We don't want other members of our own equality set to make this obvious
265    PptTopLevel pptt = ppt.parent;
266    for (int i = 0; i < pptt.var_infos.length; i++) {
267      VarInfo vi = pptt.var_infos[i];
268      if (vi.equalitySet == seqvar.equalitySet) {
269        continue;
270      }
271      if (SubSequenceFloat.isObviousSubSequenceDynamically(this, seqvar, vi)) {
272        PptSlice1 other_slice = pptt.findSlice(vi);
273        if (other_slice != null) {
274          SeqIndexFloatLessThan other_sine = SeqIndexFloatLessThan.find(other_slice);
275          if ((other_sine != null) && other_sine.enoughSamples()) {
276            return new DiscardInfo(this, DiscardCode.obvious,
277                        "The invariant " + format() + " over var "
278                       + seqvar.name() + " also holds over "
279                       +" the supersequence " + vi.name());
280          }
281        }
282      }
283    }
284
285    return null;
286  }
287}