001package daikon;
002
003import static daikon.FileIO.VarDefinition;
004
005import daikon.Quantify.QuantFlags;
006import daikon.Quantify.QuantifyReturn;
007import daikon.VarInfoName.Prestate;
008import daikon.chicory.DaikonVariableInfo;
009import daikon.derive.Derivation;
010import daikon.derive.binary.SequenceScalarSubscript;
011import daikon.derive.binary.SequenceScalarSubsequence;
012import daikon.derive.binary.SequenceSubsequence;
013import daikon.derive.ternary.SequenceScalarArbitrarySubsequence;
014import daikon.derive.unary.SequenceInitial;
015import daikon.derive.unary.SequenceLength;
016import daikon.derive.unary.SequenceMax;
017import daikon.derive.unary.SequenceMin;
018import daikon.derive.unary.SequenceSum;
019import daikon.inv.Equality;
020import daikon.inv.Invariant;
021import daikon.inv.OutputFormat;
022import daikon.inv.ValueSet;
023import daikon.inv.binary.twoScalar.IntGreaterEqual;
024import daikon.inv.binary.twoScalar.IntGreaterThan;
025import daikon.inv.binary.twoScalar.IntLessEqual;
026import daikon.inv.binary.twoScalar.IntLessThan;
027import daikon.inv.binary.twoScalar.LinearBinary;
028import daikon.inv.unary.scalar.NonZero;
029import daikon.inv.unary.scalar.SingleScalar;
030import daikon.inv.unary.sequence.EltNonZero;
031import daikon.inv.unary.sequence.SingleScalarSequence;
032import java.io.IOException;
033import java.io.ObjectInputStream;
034import java.io.Serializable;
035import java.util.ArrayList;
036import java.util.Arrays;
037import java.util.Comparator;
038import java.util.EnumSet;
039import java.util.HashMap;
040import java.util.HashSet;
041import java.util.LinkedHashSet;
042import java.util.List;
043import java.util.Map;
044import java.util.Set;
045import java.util.StringJoiner;
046import java.util.logging.Level;
047import java.util.logging.Logger;
048import org.checkerframework.checker.formatter.qual.FormatMethod;
049import org.checkerframework.checker.interning.qual.Interned;
050import org.checkerframework.checker.lock.qual.GuardSatisfied;
051import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;
052import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
053import org.checkerframework.checker.nullness.qual.NonNull;
054import org.checkerframework.checker.nullness.qual.Nullable;
055import org.checkerframework.checker.signedness.qual.PolySigned;
056import org.checkerframework.dataflow.qual.Pure;
057import org.checkerframework.dataflow.qual.SideEffectFree;
058import org.plumelib.util.ArraysPlume;
059
060/**
061 * Represents information about a particular variable for a program point. This object doesn't hold
062 * the value of the variable at a particular step of the program point, but can get the value it
063 * holds when given a ValueTuple using the getValue() method. VarInfo also includes info about the
064 * variable's name, its declared type, its file representation type, its internal type, and its
065 * comparability.
066 */
067@SuppressWarnings({
068  "nullness", // nullness properties in this file are hairy; save for later
069  "interning"
070})
071public final @Interned class VarInfo implements Cloneable, Serializable {
072  static final long serialVersionUID = 20060815L;
073
074  /**
075   * If true, then variables are only considered comparable if they are declared with the same type.
076   * For example, java.util.List is not comparable to java.util.ArrayList and float is not
077   * comparable to double. This may miss valid invariants, but significant time can be saved and
078   * many variables with different declared types are not comparable (e.g., java.util.Date and
079   * java.util.ArrayList).
080   */
081  public static boolean dkconfig_declared_type_comparability = true;
082
083  /**
084   * If true, the treat static constants (such as MapQuick.GeoPoint.FACTOR) as fields within an
085   * object rather than as a single name. Not correct, but used to obtain compatibility with
086   * VarInfoName.
087   */
088  public static boolean dkconfig_constant_fields_simplify = true;
089
090  /** Debug missing vals. */
091  public static final Logger debugMissing = Logger.getLogger("daikon.VarInfo.missing");
092
093  /**
094   * The program point this variable is in. Is null until set by {@link PptTopLevel#init_vars} and
095   * {@link PptTopLevel#addVarInfos}.
096   */
097  public PptTopLevel ppt;
098
099  /**
100   * Name. Do not compare names of invariants from different program points, because two different
101   * program points could contain unrelated variables named "x".
102   */
103  private VarInfoName var_info_name; // interned
104
105  /**
106   * Name as specified in the program point declaration. VarInfoName sometimes changes this name as
107   * part of parsing so that VarInfoName.name() doesn't return the original name.
108   */
109  private @Interned String str_name; // interned
110
111  /** returns the interned name of the variable. */
112  @Pure
113  public @Interned String name(@GuardSatisfied VarInfo this) {
114    return str_name;
115  }
116
117  /** Returns the original name of the variable from the program point declaration. */
118  public @Interned String str_name() {
119    return str_name;
120  }
121
122  /**
123   * Type as declared in the target program. This is seldom used within Daikon as these types vary
124   * with program language and the like. It's here more for information than anything else.
125   */
126  public ProglangType type; // interned (as are all ProglangType objects)
127
128  /**
129   * Type as written in the data trace file -- i.e., it is the source variable type mapped into the
130   * set of basic types recognized by Daikon. In particular, it includes boolean and hashcode
131   * (pointer). This is the type that is normally used when determining if an invariant is
132   * applicable to a variable. For example, the less-than invariant is not applicable to booleans or
133   * hashcodes, but is applicable to integers (of various sizes) and floats. (In the variable name,
134   * "rep" stands for "representation".)
135   *
136   * <p>A variable that Daikon reads from a declaration and that is declared as a boolean has
137   * file_rep_type boolean, even if its declaration gives an integer rep type such as int; see
138   * {@link FileIO.VarDefinition#useBooleanRepType}. A VarInfo that is created in another way has
139   * the file_rep_type that its creator supplies.
140   */
141  public ProglangType file_rep_type; // interned (as are all ProglangType objects)
142
143  /**
144   * Type as internally stored by Daikon. It contains less information than file_rep_type (for
145   * example, boolean and hashcode are both stored as integers). (In the variable name, "rep" stands
146   * for "representation".)
147   *
148   * @see ProglangType#fileTypeToRepType()
149   */
150  public ProglangType rep_type; // interned (as are all ProglangType objects)
151
152  /** Comparability info. */
153  @SuppressWarnings("serial")
154  public VarComparability comparability;
155
156  /** Auxiliary info. */
157  public VarInfoAux aux;
158
159  /** The index in lists of VarInfo objects. */
160  public int varinfo_index;
161
162  /**
163   * The index in a ValueTuple (more generally, in a list of values). It can differ from
164   * varinfo_index due to constants (and possibly other factors). It is -1 iff is_static_constant or
165   * not yet set.
166   */
167  public int value_index;
168
169  /**
170   * Invariants: <br>
171   * is_static_constant == (value_index == -1);<br>
172   * is_static_constant == (static_constant_value != null).
173   */
174  // queried via isStaticConstant() method, so consider making this field private
175  public boolean is_static_constant;
176
177  /** Null if not statically constant. */
178  @SuppressWarnings("serial")
179  @Nullable @Interned Object static_constant_value;
180
181  /** True if and how derived. Null if this is not derived. */
182  public @MonotonicNonNull Derivation derived;
183
184  // Various enums used for information about variables
185  public enum RefType {
186    POINTER,
187    OFFSET
188  };
189
190  public enum LangFlags {
191    PUBLIC,
192    PRIVATE,
193    PROTECTED,
194    STATIC,
195    FINAL,
196    SYNCHRONIZED,
197    VOLATILE,
198    TRANSIENT,
199    ANNOTATION,
200    ENUM
201  };
202
203  // These enums are intentionally duplicated in Chicory and other
204  // front-ends. These values are written into decl files, and as
205  // such, should stay constant between front-ends. They should not be
206  // changed without good reason; if you do change them, make sure to
207  // also change the corresponding constants in Daikon front ends!
208  // Adding a new enum is fine, but should also be done in all locations.
209  public enum VarKind {
210    FIELD,
211    FUNCTION,
212    ARRAY,
213    VARIABLE,
214    RETURN
215  };
216
217  public enum VarFlags {
218    IS_PARAM,
219    NO_DUPS,
220    NOT_ORDERED,
221    NO_SIZE,
222    NOMOD,
223    SYNTHETIC,
224    CLASSNAME,
225    TO_STRING,
226    NON_NULL,
227    IS_PROPERTY,
228    IS_ENUM,
229    IS_READONLY
230  };
231
232  public @Nullable RefType ref_type;
233  public VarKind var_kind;
234  public EnumSet<VarFlags> var_flags = EnumSet.noneOf(VarFlags.class);
235  public EnumSet<LangFlags> lang_flags = EnumSet.noneOf(LangFlags.class);
236
237  public VarDefinition vardef;
238
239  /**
240   * For documentation, see {@link #get_enclosing_var()}. Null if no variable encloses this one --
241   * that is, this is not a field of another variable, nor a "method call" like tostring or class.
242   */
243  public @Nullable VarInfo enclosing_var;
244
245  /** Number of array dimensions (0 or 1). */
246  public int arr_dims;
247
248  /**
249   * The arguments that were used to create this function application. Null if this variable is not
250   * a function application.
251   */
252  @SuppressWarnings("serial")
253  public @MonotonicNonNull List<VarInfo> function_args = null;
254
255  /** Parent program points in ppt hierarchy (optional) */
256  @SuppressWarnings("serial")
257  public List<VarParent> parents;
258
259  /**
260   * The relative name of this variable with respect to its enclosing variable. Field name for
261   * fields, method name for instance methods.
262   */
263  public @Nullable String relative_name = null;
264
265  /**
266   * Returns true if we have encountered to date any missing values due to array indices being out
267   * of bounds. This can happen with both subscripts and subsequences. Note that this becomes true
268   * as we are running, it cannot be set in advance without a first pass.
269   *
270   * <p>This is used as we are processing data to destroy any invariants that use this variable.
271   *
272   * @see Derivation#missingOutOfBounds()
273   */
274  public boolean missingOutOfBounds() {
275    if ((derived != null) && derived.missingOutOfBounds()) {
276      return true;
277    }
278    return false;
279  }
280
281  /**
282   * True if a missing/nonsensical value was ever observed for this variable. This starts out false
283   * and is set dynamically, while reading the trace file.
284   */
285  public boolean canBeMissing = false;
286
287  /**
288   * Which equality group this belongs to. Replaces equal_to. Never null after this is put inside
289   * equalitySet.
290   */
291  public Equality equalitySet;
292
293  /** Cached value for sequenceSize() */
294  private VarInfo sequenceSize;
295
296  /**
297   * non-null if this is an orig() variable.
298   *
299   * <p><b>Do not test equality! Only use its .name slot.</b>
300   */
301  public @Nullable VarInfo postState;
302
303  /**
304   * Throws an exception if this object is malformed. Requires that the VarInfo has been installed
305   * into a program point (the {@code ppt} field is set).
306   *
307   * @throws RuntimeException if representation invariant on this is broken
308   */
309  public void checkRep() {
310    checkRepNoPpt();
311    assert ppt != null;
312    assert 0 <= varinfo_index && varinfo_index < ppt.var_infos.length;
313    assert -1 <= value_index && value_index <= varinfo_index
314        : this + " value_index=" + value_index + ", varinfo_index=" + varinfo_index;
315    assert is_static_constant == (value_index == -1);
316    assert is_static_constant || (static_constant_value == null);
317  }
318
319  /**
320   * Throws an exception if this object is malformed.
321   *
322   * <p>Does not require the {@code ppt} field to be set; can be called on VarInfos that have not
323   * been installed into a program point.
324   *
325   * @throws RuntimeException if representation invariant on this is broken
326   */
327  public void checkRepNoPpt() {
328    try {
329      assert var_info_name != null; // vin ok
330      assert var_info_name == var_info_name.intern(); // vin ok
331      assert type != null;
332      assert file_rep_type != null;
333      assert rep_type != null;
334      assert var_kind != null;
335      assert comparability != null; // anything else ??
336      assert (comparability.alwaysComparable()
337              || (((VarComparabilityImplicit) comparability).dimensions
338                  == file_rep_type.dimensions()))
339          : "Dimensions mismatch for "
340              + this
341              + ": "
342              + ((VarComparabilityImplicit) comparability).dimensions
343              + " "
344              + file_rep_type.dimensions();
345      if ((var_kind == VarKind.FIELD || var_kind == VarKind.ARRAY) && enclosing_var == null) {
346        throw new AssertionError(
347            "enclosing-var not specified for variable " + var_info_name + " of kind " + var_kind);
348      }
349    } catch (Throwable e) {
350      throw new AssertionError(
351          "checkRepNoPpt failed for variable "
352              + var_info_name
353              + (ppt == null ? "" : (" in " + ppt))
354              + ": "
355              + repr(),
356          e);
357    }
358  }
359
360  /** Returns true if rep_type is a legal type. */
361  static boolean legalRepType(ProglangType rep_type) {
362    return ((rep_type == ProglangType.INT)
363        || (rep_type == ProglangType.DOUBLE)
364        || (rep_type == ProglangType.STRING)
365        || (rep_type == ProglangType.INT_ARRAY)
366        || (rep_type == ProglangType.DOUBLE_ARRAY)
367        || (rep_type == ProglangType.STRING_ARRAY));
368  }
369
370  /** Returns true if constant_value is a legal constant. */
371  @EnsuresNonNullIf(result = false, expression = "#1")
372  static boolean legalConstant(@Nullable Object constant_value) {
373    return ((constant_value == null)
374        || (constant_value instanceof Long)
375        || (constant_value instanceof Double));
376  }
377
378  /**
379   * Returns true if file_rep_type is a legal file_rep_type. The file_rep_type matches rep_type
380   * except that it also allows the more detailed scalar types (HASHCODE, BOOLEAN, etc).
381   */
382  static boolean legalFileRepType(ProglangType file_rep_type) {
383    return (legalRepType(file_rep_type)
384        // The below types are converted into one of the rep types
385        // by ProglangType.fileTypeToRepType().
386        || (file_rep_type == ProglangType.HASHCODE)
387        || (file_rep_type == ProglangType.HASHCODE_ARRAY)
388        || ((file_rep_type.dimensions() <= 1) && file_rep_type.baseIsPrimitive()));
389  }
390
391  /**
392   * Create VarInfo from VarDefinition.
393   *
394   * <p>This does not create a fully initialized VarInfo. For example, its ppt and enclosing_var
395   * fields are not yet set. Callers need to do some work to complete the construction of the
396   * VarInfo.
397   */
398  public VarInfo(VarDefinition vardef) {
399    vardef.checkRep();
400
401    this.vardef = vardef;
402
403    // Create a VarInfoName from the external name.  This probably gets
404    // removed in the long run.
405    try {
406      var_info_name = VarInfoName.parse(vardef.name); // vin ok
407    } catch (Exception e) {
408      @SuppressWarnings("nullness") // error case, likely to crash later anyway
409      @NonNull VarInfoName vin = null;
410      var_info_name = vin;
411      System.out.printf("Warning: Can't parse %s as a VarInfoName", vardef.name);
412    }
413    str_name = vardef.name.intern();
414
415    // Copy info from vardef
416    var_kind = vardef.kind;
417    relative_name = vardef.relative_name;
418    ref_type = vardef.ref_type;
419    arr_dims = vardef.arr_dims;
420    comparability = vardef.comparability;
421    file_rep_type = vardef.rep_type;
422    type = vardef.declared_type;
423    var_flags = vardef.flags;
424    lang_flags = vardef.lang_flags;
425    parents = new ArrayList<VarParent>(vardef.parents);
426
427    // If a static constant value was specified, set it
428    if (vardef.static_constant_value != null) {
429      is_static_constant = true;
430      static_constant_value = vardef.static_constant_value;
431    } else {
432      is_static_constant = false;
433    }
434
435    // Create the rep_type from the file rep type
436    rep_type = file_rep_type.fileTypeToRepType();
437
438    // Create the VarInfoAux information
439    final List<String> auxstrs = new ArrayList<>();
440    if (var_flags.contains(VarFlags.NON_NULL)) {
441      auxstrs.add(VarInfoAux.IS_NON_NULL + "=true");
442    }
443    if (var_flags.contains(VarFlags.NO_DUPS)) {
444      auxstrs.add(VarInfoAux.HAS_DUPLICATES + "=false");
445    }
446    if (var_flags.contains(VarFlags.NOT_ORDERED)) {
447      auxstrs.add(VarInfoAux.HAS_ORDER + "=false");
448    }
449    if (var_flags.contains(VarFlags.NO_SIZE)) {
450      auxstrs.add(VarInfoAux.HAS_SIZE + "=false");
451    }
452    if (vardef.min_value != null) {
453      auxstrs.add(VarInfoAux.MINIMUM_VALUE + "=" + vardef.min_value);
454    }
455    if (vardef.max_value != null) {
456      auxstrs.add(VarInfoAux.MAXIMUM_VALUE + "=" + vardef.max_value);
457    }
458    if (vardef.min_length != null) {
459      auxstrs.add(VarInfoAux.MINIMUM_LENGTH + "=" + vardef.min_length);
460    }
461    if (vardef.max_length != null) {
462      auxstrs.add(VarInfoAux.MAXIMUM_LENGTH + "=" + vardef.max_length);
463    }
464    if (vardef.valid_values != null) {
465      auxstrs.add(VarInfoAux.VALID_VALUES + "=" + vardef.valid_values);
466    }
467    final String auxstr = String.join(", ", auxstrs);
468
469    try {
470      aux = VarInfoAux.parse(auxstr);
471    } catch (Exception e) {
472      throw new RuntimeException("unexpected aux error", e);
473    }
474  }
475
476  /**
477   * Finishes defining the variable by relating it to other variables. This cannot be done when
478   * creating the variable because the other variables it is related to, may not yet exist.
479   * Variables are related to their enclosing variables (for fields, arrays, and functions) and to
480   * their parent variables in the PptHierarchy. RuntimeExceptions are thrown if any related
481   * variables do not exist.
482   */
483  public void relate_var() {
484
485    if (vardef == null) {
486      return;
487    }
488
489    // System.out.printf("enclosing var for %s is %s%n", str_name,
490    //                   vardef.enclosing_var);
491
492    // Find and set the enclosing variable (if any)
493    if (vardef.enclosing_var_name != null) {
494      enclosing_var = ppt.find_var_by_name(vardef.enclosing_var_name);
495      if (enclosing_var == null) {
496        for (int i = 0; i < ppt.var_infos.length; i++) {
497          System.out.printf("var = '%s'%n", ppt.var_infos[i]);
498        }
499        throw new RuntimeException(
500            String.format(
501                "enclosing variable '%s' for variable '%s' in ppt '%s' cannot be found",
502                vardef.enclosing_var_name, vardef.name, ppt.name));
503      }
504    }
505
506    // Convert vardef.function_args, which is a list of Strings,
507    // into this.function_args, which is a list of VarInfos.
508    if (vardef.function_args != null) {
509      List<VarInfo> temp_function_args = new ArrayList<VarInfo>(vardef.function_args.size());
510      for (String varname : vardef.function_args) {
511        VarInfo vi = ppt.find_var_by_name(varname);
512        if (vi == null) {
513          throw new RuntimeException(
514              String.format(
515                  "function argument '%s' for variable '%s'  in ppt '%s' cannot be found",
516                  varname, vardef.name, ppt.name));
517        }
518        temp_function_args.add(vi);
519      }
520      function_args = temp_function_args;
521    }
522
523    // do something appropriate with the ppt/var hierarchy.  It may be
524    // that  this is better done within PptRelation
525  }
526
527  /**
528   * Setup information normally specified in the declaration record for derived variables where the
529   * new variable is the result of applying a function to the other variables. Much of the
530   * information is inferred from (arbitrarily) the first argument to the function.
531   *
532   * <p>The parent_ppt field is set if each VarInfo in the derivation has the same parent. The
533   * parent_variable field is set if there is a parent_ppt and one or more of the bases has a
534   * non-default parent variable. The parent variable name is formed as function_name(arg1,arg2,...)
535   * where arg1, arg2, etc are the parent variable names of each of the arguments.
536   */
537  public void setup_derived_function(String name, VarInfo... bases) {
538
539    // Copy variable info from the base.
540    // Might some of these need to be overridden later, because they are just guesses?
541    VarInfo base = bases[0];
542    ref_type = null;
543    var_flags = base.var_flags.clone();
544    lang_flags = base.lang_flags.clone();
545    for (int ii = 1; ii < bases.length; ii++) {
546      var_flags.retainAll(bases[ii].var_flags);
547      lang_flags.retainAll(bases[ii].lang_flags);
548    }
549    enclosing_var = null;
550    arr_dims = base.arr_dims;
551    var_kind = VarKind.FUNCTION;
552    function_args = Arrays.asList(bases);
553
554    // Build the string name
555    List<String> arg_names = new ArrayList<>();
556    for (VarInfo vi : bases) {
557      arg_names.add(vi.name());
558    }
559    str_name = String.format("%s(%s)", name, String.join(",", arg_names)).intern();
560
561    // The parent ppt is the same as the base if each varinfo in the
562    // derivation has the same parent
563    for (VarParent bp : base.parents) {
564      int parent_relation_id = bp.parent_relation_id;
565      String parent_ppt = bp.parent_ppt;
566
567      if (allHaveRelation(parent_relation_id)) {
568        parents.add(new VarParent(parent_ppt, parent_relation_id, null));
569      }
570    }
571
572    // If there is a parent_ppt, determine the parent_variable name.
573    // If all of the argument names are the default, then the parent_variable
574    // is the default as well.  Otherwise, build up the name from the
575    // function name and the name of each arguments parent variable name.
576    // TWS: the code doesn't appear to handle the case where some are default and some aren't.
577    for (VarParent p : parents) {
578      boolean parent_vars_specified = false;
579      for (VarInfo vi : bases) {
580        for (VarParent vp : vi.parents) {
581          if (vp.parent_variable != null && vp.parent_relation_id == p.parent_relation_id) {
582            parent_vars_specified = true;
583          }
584        }
585      }
586      if (!parent_vars_specified) {
587        p.parent_variable = null;
588      } else {
589        StringJoiner args = new StringJoiner(",");
590        for (VarInfo vi : bases) {
591          boolean found = false;
592          for (VarParent vp : vi.parents) {
593            if (vp.parent_relation_id == p.parent_relation_id) {
594              args.add(vp.parent_variable);
595              found = true;
596            }
597          }
598          if (!found) {
599            args.add(vi.name());
600          }
601        }
602        p.parent_variable = String.format("%s(%s)", name, args.toString());
603      }
604    }
605  }
606
607  /**
608   * Setup information normally specified in the declaration record for derived variables where one
609   * of the variables is the base of the derivation. In general this information is inferred from
610   * the base variable of the derived variables. Note that parent_ppt is set if each VarInfo in the
611   * derivation has the same parent, but parent_variable is not set. This has to be set based on the
612   * particular derivation.
613   */
614  public void setup_derived_base(VarInfo base, @Nullable VarInfo... others) {
615
616    // Copy variable info from the base
617    ref_type = base.ref_type;
618    var_kind = base.var_kind;
619    var_flags = base.var_flags.clone();
620    lang_flags = base.lang_flags.clone();
621    enclosing_var = base.enclosing_var;
622    arr_dims = base.arr_dims;
623    function_args = base.function_args;
624
625    // The parent ppt is the same as the base if each varinfo in the
626    // derivation has the same parent
627    for (VarParent bp : base.parents) {
628      int parent_relation_id = bp.parent_relation_id;
629      String parent_ppt = bp.parent_ppt;
630
631      if (allHaveRelation(parent_relation_id, others)) {
632        parents.add(new VarParent(parent_ppt, parent_relation_id, null));
633      }
634    }
635  }
636
637  /** Returns true if all variables have a parent relation with the specified id. */
638  private static boolean allHaveRelation(int parent_relation_id, VarInfo... vs) {
639    for (VarInfo vi : vs) {
640      if (vi == null) {
641        continue;
642      }
643      boolean hasRelId = false;
644      for (VarParent vp : vi.parents) {
645        if (parent_relation_id == vp.parent_relation_id) {
646          hasRelId = true;
647          break;
648        }
649      }
650      if (!hasRelId) {
651        return false;
652      }
653    }
654    return true;
655  }
656
657  /**
658   * Create the specified VarInfo. The resulting VarInfo does not have its ppt field set.
659   *
660   * @param name the variable name
661   * @param type type as declared in the program point
662   * @param file_rep_type the file representation type; see {@link #file_rep_type}
663   * @param comparability comparability info
664   * @param is_static_constant true if the variable always has the same, known value
665   * @param static_constant_value the static constant value, or null if not statically constant
666   * @param aux auxiliary info
667   */
668  private VarInfo(
669      VarInfoName name,
670      ProglangType type,
671      ProglangType file_rep_type,
672      VarComparability comparability,
673      boolean is_static_constant,
674      @Nullable @Interned Object static_constant_value,
675      VarInfoAux aux) {
676
677    assert name != null;
678    assert file_rep_type != null;
679    assert legalFileRepType(file_rep_type)
680        : "Unsupported representation type "
681            + file_rep_type.format()
682            + "/"
683            + file_rep_type.getClass()
684            + " "
685            + ProglangType.HASHCODE.getClass()
686            + " for variable "
687            + name;
688    assert type != null;
689    assert comparability != null;
690    // COMPARABILITY TEST
691    // assert
692    //   comparability.alwaysComparable() || ((VarComparabilityImplicit)comparability).dimensions ==
693    // file_rep_type.dimensions()
694    //   : "Types dimensions incompatibility: "
695    //     + type
696    //     + " vs. "
697    //     + file_rep_type;
698    assert aux != null;
699    assert legalConstant(static_constant_value)
700        : "unexpected constant class " + static_constant_value.getClass();
701
702    // Possibly the call to intern() isn't necessary; but it's safest to
703    // make the call to intern() rather than running the risk that a caller
704    // didn't.
705    this.var_info_name = name.intern(); // vin ok
706    this.type = type;
707    this.file_rep_type = file_rep_type;
708    this.rep_type = file_rep_type.fileTypeToRepType();
709    arr_dims = rep_type.isArray() ? 1 : 0;
710    this.comparability = comparability;
711    this.is_static_constant = is_static_constant;
712    this.static_constant_value = static_constant_value;
713    this.aux = aux;
714    this.parents = new ArrayList<VarParent>();
715
716    if (debug.isLoggable(Level.FINE)) {
717      debug.fine("Var " + name + " aux: " + aux);
718    }
719
720    // Indicates that these haven't yet been set to reasonable values.
721    value_index = -1;
722    varinfo_index = -1;
723
724    canBeMissing = false;
725  }
726
727  /** Create the specified VarInfo. */
728  public VarInfo(
729      String name,
730      ProglangType type,
731      ProglangType file_rep_type,
732      VarComparability comparability,
733      boolean is_static_constant,
734      @Nullable @Interned Object static_constant_value,
735      VarInfoAux aux) {
736    this(
737        VarInfoName.parse(name),
738        type,
739        file_rep_type,
740        comparability,
741        is_static_constant,
742        static_constant_value,
743        aux);
744    assert name != null;
745    this.str_name = name.intern();
746  }
747
748  /** Create the specified non-static VarInfo. */
749  private VarInfo(
750      VarInfoName name,
751      ProglangType type,
752      ProglangType file_rep_type,
753      VarComparability comparability,
754      VarInfoAux aux) {
755    this(name, type, file_rep_type, comparability, false, null, aux);
756  }
757
758  /** Create the specified non-static VarInfo. */
759  public VarInfo(
760      String name,
761      ProglangType type,
762      ProglangType file_rep_type,
763      VarComparability comparability,
764      VarInfoAux aux) {
765    this(name, type, file_rep_type, comparability, false, null, aux);
766    assert name != null;
767    this.str_name = name.intern();
768  }
769
770  /** Create a VarInfo with the same values as vi. */
771  public VarInfo(VarInfo vi) {
772    this(
773        vi.name(),
774        vi.type,
775        vi.file_rep_type,
776        vi.comparability,
777        vi.is_static_constant,
778        vi.static_constant_value,
779        vi.aux);
780    str_name = vi.str_name;
781    canBeMissing = vi.canBeMissing;
782    postState = vi.postState;
783    equalitySet = vi.equalitySet;
784    ref_type = vi.ref_type;
785    var_kind = vi.var_kind;
786    var_flags = vi.var_flags.clone();
787    lang_flags = vi.lang_flags.clone();
788    vardef = vi.vardef;
789    enclosing_var = vi.enclosing_var;
790    arr_dims = vi.arr_dims;
791    function_args = vi.function_args;
792    parents = new ArrayList<VarParent>();
793    for (VarParent parent : vi.parents) {
794      parents.add(
795          new VarParent(parent.parent_ppt, parent.parent_relation_id, parent.parent_variable));
796    }
797    relative_name = vi.relative_name;
798  }
799
800  // /** Creates and returns a copy of this. */
801  // // Default implementation to quiet Findbugs.
802  // @SuppressWarnings("interning")  // temporary?
803  // public VarInfo clone() throws CloneNotSupportedException {
804  //   return (VarInfo) super.clone();
805  // }
806
807  /**
808   * Create the prestate, or "orig()", version of the variable. Note that the returned value is not
809   * completely initialized. The caller is still responsible for setting some fields of it, such as
810   * enclosing_var.
811   */
812  public static VarInfo origVarInfo(VarInfo vi) {
813    // At an exit point, parameters are uninteresting, but orig(param) is not.
814    // So don't call orig(param) a parameter.
815
816    // Build a Variable Definition from the poststate vardef
817    VarDefinition result_vardef = vi.vardef.copy();
818    result_vardef.name = vi.prestate_name();
819
820    // The only hierarchy relation for orig variables is to the enter
821    // ppt.  Remove any specified relations.
822    result_vardef.clear_parent_relation();
823
824    // Fix the VarDefinition enclosing variable, if any, to point to the
825    // prestate version.  This code does not affect the VarInfo yet, but
826    // the side-effected VarDefinition will be passed to "new VarInfo".
827    if (result_vardef.enclosing_var_name != null) {
828      assert vi.enclosing_var != null
829          : "@AssumeAssertion(nullness): dependent: result_vardef was copied from vi and their"
830              + " enclosing_var fields are the same";
831      result_vardef.enclosing_var_name = vi.enclosing_var.prestate_name();
832      assert result_vardef.enclosing_var_name != null : result_vardef.toString();
833    }
834
835    // Build the prestate VarInfo from the VarDefinition.
836    VarInfo result = new VarInfo(result_vardef);
837
838    // Copy the missing flag from the original variable.  This is necessary
839    // for combined exit points which are built after processing is
840    // complete.  In most cases the missing flag will be set correctly
841    // by merging the missing flag from the numbered exit points.  But
842    // this will fail if the method terminates early each time the variable
843    // is missing.  A better fix would be to instrument early exits and
844    // merge them in as well, but this matches what we did previously.
845    result.canBeMissing = vi.canBeMissing;
846
847    // At an exit point, parameters are uninteresting, but orig(param) is not.
848    // So don't call orig(param) a parameter.
849    result.set_is_param(false);
850    return result;
851  }
852
853  /**
854   * Given an array of VarInfo objects, return an array of clones, where references to the originals
855   * have been modified into references to the new ones (so that the new set is self-consistent).
856   * The originals should not be modified by this operation.
857   */
858  public static VarInfo[] arrayclone_simple(VarInfo[] a_old) {
859    int len = a_old.length;
860    VarInfo[] a_new = new VarInfo[len];
861    for (int i = 0; i < len; i++) {
862      a_new[i] = new VarInfo(a_old[i]);
863      if (a_old[i].derived != null) {
864        assert a_new[i].derived != null;
865      }
866      a_new[i].varinfo_index = a_old[i].varinfo_index;
867      a_new[i].value_index = a_old[i].value_index;
868    }
869    return a_new;
870  }
871
872  /** Trims the collections used by this VarInfo. */
873  public void trimToSize() {
874    // if (derivees != null) { derivees.trimToSize(); }
875    // Derivation derived; probably can't be trimmed
876  }
877
878  /**
879   * Returns the name of the variable.
880   *
881   * @see #name
882   */
883  @SideEffectFree
884  @Override
885  public String toString(@GuardSatisfied VarInfo this) {
886    return name();
887  }
888
889  /**
890   * Returns the argument or, if it is null, {@code "null"}.
891   *
892   * @param o a reference
893   * @return the argument or, if it is null, {@code "null"}
894   */
895  private @PolySigned Object checkNull(
896      @GuardSatisfied VarInfo this, @Nullable @PolySigned Object o) {
897    return (o == null) ? (@PolySigned Object) "null" : o;
898  }
899
900  /**
901   * Returns a complete string description of the variable.
902   *
903   * @return a complete string description of the variable
904   */
905  public String repr() {
906    return "<VarInfo "
907        + var_info_name // vin ok
908        + ": "
909        + "type="
910        + type
911        + ",file_rep_type="
912        + file_rep_type
913        + ",rep_type="
914        + rep_type
915        + ",comparability="
916        + comparability
917        + ",value_index="
918        + value_index
919        + ",varinfo_index="
920        + varinfo_index
921        + ",is_static_constant="
922        + is_static_constant
923        + ",static_constant_value="
924        + static_constant_value
925        + ",derived="
926        + checkNull(derived)
927        + ",derivees="
928        + derivees()
929        + ",ppt="
930        // This method is only called for debugging, so let's
931        // protect ourselves from a mistake somewhere else, such as ppt being null.
932        // + ppt.name()
933        + ppt
934        + ",canBeMissing="
935        + canBeMissing
936        + (",equal_to=" + (equalitySet == null ? "null" : equalitySet.toString()))
937        + ",PostState="
938        + postState
939        + ",isCanonical()="
940        + isCanonical()
941        + ">";
942  }
943
944  /** Returns true if this variable is a static constant. */
945  @EnsuresNonNullIf(
946      result = true,
947      expression = {"constantValue()", "static_constant_value"})
948  @Pure
949  public boolean isStaticConstant() {
950    return is_static_constant;
951  }
952
953  /**
954   * Returns the static constant value of this variable. The variable must be a static constant. The
955   * result is non-null.
956   */
957  public Object constantValue() {
958    if (isStaticConstant()) {
959      assert static_constant_value != null;
960      return static_constant_value;
961    } else {
962      throw new Error("Variable " + name() + " is not constant");
963    }
964  }
965
966  /** Returns true if this is an "orig()" variable. */
967  @EnsuresNonNullIf(result = true, expression = "postState")
968  @Pure
969  public boolean isPrestate() {
970    return postState != null;
971  }
972
973  /** Returns true if this variable is derived from prestate variables. */
974  @SuppressWarnings("all:not.deterministic") // nondeterminism does not affect result
975  @Pure
976  public boolean isPrestateDerived() {
977    if (postState != null) {
978      return true;
979    }
980    if (isDerived()) {
981      for (VarInfo vi : derived.getBases()) {
982        if (!vi.isPrestate()) {
983          return false;
984        }
985      }
986      return true;
987    } else {
988      return isPrestate();
989    }
990
991    // return name.isAllPrestate();
992  }
993
994  /** Returns true if this variable is a derived variable. */
995  @EnsuresNonNullIf(result = true, expression = "this.derived")
996  @Pure
997  public boolean isDerived() {
998    return (derived != null);
999  }
1000
1001  /**
1002   * Returns the depth of derivation.
1003   *
1004   * @return the depth of derivation
1005   */
1006  public int derivedDepth() {
1007    if (derived == null) {
1008      return 0;
1009    } else {
1010      return derived.derivedDepth();
1011    }
1012  }
1013
1014  /**
1015   * Returns all derived variables that build off this one.
1016   *
1017   * @return all derived variables that build off this one
1018   */
1019  public List<Derivation> derivees() {
1020    ArrayList<Derivation> result = new ArrayList<>();
1021    // This method is only called from the debugging routine 'repr()'.
1022    // So let's protect ourselves from a mistake somewhere else.
1023    if (ppt == null) {
1024      return result;
1025    }
1026    VarInfo[] vis = ppt.var_infos;
1027    for (int i = 0; i < vis.length; i++) {
1028      VarInfo vi = vis[i];
1029      Derivation der = vi.derived;
1030      if (der == null) {
1031        continue;
1032      }
1033      if (ArraysPlume.indexOf(der.getBases(), this) >= 0) {
1034        result.add(der);
1035      }
1036    }
1037    return result;
1038  }
1039
1040  /**
1041   * Returns a list of all of the basic (non-derived) variables that are used to make up this
1042   * variable. If this variable is not derived, it is just this variable. Otherwise it is all of the
1043   * the bases of this derivation.
1044   */
1045  public List<VarInfo> get_all_constituent_vars() {
1046    List<VarInfo> vars = new ArrayList<>();
1047    if (isDerived()) {
1048      for (VarInfo vi : derived.getBases()) {
1049        vars.addAll(vi.get_all_constituent_vars());
1050      }
1051    } else {
1052      vars.add(this);
1053    }
1054    return vars;
1055  }
1056
1057  /**
1058   * Returns a list of all of the simple names that make up this variable. this includes each field
1059   * and function name in the variable. If this variable is derived it includes the simple names
1060   * from each of its bases. For example, 'this.item.a' would return a list with 'this', 'item', and
1061   * 'a' and 'this.theArray[i]' would return 'this', 'theArray' and 'i'.
1062   */
1063  public List<String> get_all_simple_names() {
1064    List<String> names = new ArrayList<>();
1065    if (isDerived()) {
1066      for (VarInfo vi : derived.getBases()) {
1067        names.addAll(vi.get_all_simple_names());
1068      }
1069    } else {
1070      VarInfo start = (isPrestate() ? postState : this);
1071      for (VarInfo vi = start; vi != null; vi = vi.enclosing_var) {
1072        if (relative_name == null) {
1073          names.add(vi.name());
1074        } else {
1075          names.add(vi.relative_name);
1076        }
1077      }
1078    }
1079    return names;
1080  }
1081
1082  @Pure
1083  public boolean isClosure() {
1084    // This should eventually turn into
1085    //   return name.indexOf("closure(") != -1;
1086    // when I rename those variables to "closure(...)".
1087    return name().indexOf('~') != -1; // XXX
1088  }
1089
1090  /** Cached value for getDerivedParam(). */
1091  public @Nullable VarInfo derivedParamCached = null;
1092
1093  /** Cached value for isDerivedParam(). */
1094  // Boolean rather than boolean so we can use "null" to indicate "not yet set".
1095  public @MonotonicNonNull Boolean isDerivedParamCached = null;
1096
1097  /**
1098   * Returns true if this is a param according to aux info, or this is a front end derivation such
1099   * that one of its bases is a param. To figure this out, what we do is get all the param variables
1100   * at this's program point. Then we search in this's name to see if the name contains any of the
1101   * variables. We have to do this because we only have name info, and we assume that x and x.a are
1102   * related from the names alone.
1103   *
1104   * <p>Effects: Sets isDerivedParamCached and derivedParamCached to values the first time this
1105   * method is called. Subsequent calls use these cached values.
1106   */
1107  @EnsuresNonNullIf(result = true, expression = "getDerivedParam()")
1108  @SuppressWarnings("all:purity") // created object is not returned
1109  @Pure
1110  public boolean isDerivedParam() {
1111    if (isDerivedParamCached != null) {
1112      // System.out.printf("var %s is-derived-param = %b%n", name(),
1113      //                   isDerivedParamCached);
1114      return isDerivedParamCached.booleanValue();
1115    }
1116
1117    boolean result = false;
1118    if (isParam() && !isPrestate()) {
1119      result = true;
1120    }
1121
1122    derivedParamCached = enclosing_param();
1123    if (derivedParamCached != null) {
1124      result = true;
1125    } else if (derived != null) {
1126      for (VarInfo vi : derived.getBases()) {
1127        derivedParamCached = vi.enclosing_param();
1128        if (derivedParamCached != null) {
1129          result = true;
1130          break;
1131        }
1132      }
1133    }
1134
1135    // System.out.printf("var %s is-derived-param = %b%n", name(), result);
1136    isDerivedParamCached = result ? Boolean.TRUE : Boolean.FALSE;
1137    return result;
1138  }
1139
1140  /** Returns the param variable that encloses this variable (if any). Returns null otherwise. */
1141  private @Nullable VarInfo enclosing_param() {
1142    // System.out.printf("Considering %s%n", this);
1143    if (isPrestate()) {
1144      return postState.enclosing_param();
1145    }
1146    for (VarInfo evi = this; evi != null; evi = evi.enclosing_var) {
1147      // System.out.printf("%s isParam=%b%n", evi, evi.isParam());
1148      if (evi.isParam()) {
1149        return evi;
1150      }
1151    }
1152    return null;
1153  }
1154
1155  /**
1156   * Returns a VarInfo that has two properties: this is a derivation of it, and it is a parameter
1157   * variable. If this is a parameter, then this is returned. For example, "this" is always a
1158   * parameter. The return value of getDerivedParam for "this.a" (which is not a parameter) is
1159   * "this".
1160   *
1161   * <p>Effects: Sets isDerivedParamCached and derivedParamCached to values the first time this
1162   * method is called. Subsequent calls use these cached values.
1163   *
1164   * @return null if the above condition doesn't hold
1165   */
1166  @Pure
1167  public @Nullable VarInfo getDerivedParam() {
1168    if (isDerivedParamCached == null) {
1169      // fill in the cache
1170      isDerivedParam();
1171    }
1172    return derivedParamCached;
1173  }
1174
1175  private @MonotonicNonNull Boolean isDerivedParamAndUninterestingCached = null;
1176
1177  /**
1178   * Returns true if a given VarInfo is a parameter or derived from one in such a way that changes
1179   * to it wouldn't be visible to the method's caller. There are 3 such cases:
1180   *
1181   * <ul>
1182   *   <li>The variable is a pass-by-value parameter "p".
1183   *   <li>The variable is of the form "p.prop" where "prop" is an immutable property of an object,
1184   *       like its type, or (for a Java array) its size.
1185   *   <li>The variable is of the form "p.prop", and "p" has been modified to point to a different
1186   *       object. We assume "p" has been modified if we don't have an invariant "orig(p) == p".
1187   * </ul>
1188   *
1189   * In any case, the variable must have a postState VarInfoName, and equality invariants need to
1190   * have already been computed.
1191   */
1192  @SuppressWarnings("all:purity") // set cache field
1193  @Pure
1194  public boolean isDerivedParamAndUninteresting() {
1195    if (isDerivedParamAndUninterestingCached != null) {
1196      return isDerivedParamAndUninterestingCached.booleanValue();
1197    } else {
1198      isDerivedParamAndUninterestingCached =
1199          _isDerivedParamAndUninteresting() ? Boolean.TRUE : Boolean.FALSE;
1200      return isDerivedParamAndUninterestingCached.booleanValue();
1201    }
1202  }
1203
1204  /** Implementation of {@link #isDerivedParamAndUninteresting()}. */
1205  @Pure
1206  private boolean _isDerivedParamAndUninteresting() {
1207    if (PrintInvariants.debugFiltering.isLoggable(Level.FINE)) {
1208      PrintInvariants.debugFiltering.fine("isDPAU: name is " + name());
1209      PrintInvariants.debugFiltering.fine("  isPrestate is " + String.valueOf(isPrestate()));
1210    }
1211
1212    // Orig variables are not considered parameters.  We only check the
1213    // first variable in a derivation because that is the sequence variable in
1214    // sequence-subscript or sequence-subsequence derivations and we don't
1215    // care if the index into the sequence is prestate or not.
1216    if (isPrestate() || (isDerived() && derived.getBase(0).isPrestate())) {
1217      return false;
1218    }
1219
1220    if (isParam()) {
1221      PrintInvariants.debugFiltering.fine("  not interesting, IS_PARAM == true for " + name());
1222      return true;
1223    }
1224    if (Global.debugSuppressParam.isLoggable(Level.FINE)) {
1225      Global.debugSuppressParam.fine("Testing isDerivedParamAndUninteresting for: " + name());
1226      Global.debugSuppressParam.fine(aux.toString());
1227      Global.debugSuppressParam.fine("At ppt " + ppt.name());
1228    }
1229    if (isDerivedParam()) {
1230      // I am uninteresting if I'm a derived param from X and X's
1231      // type or X's size, because these things are boring if X
1232      // changes (the default for the rest of the code here), and
1233      // boring if X stays the same (because it's obviously true).
1234      assert enclosing_var != null : this;
1235      assert enclosing_var != null : "@AssumeAssertion(nullness)";
1236
1237      // The class of a parameter can't change in the caller
1238      if (var_flags.contains(VarFlags.CLASSNAME) && enclosing_var.isParam()) {
1239        return true;
1240      }
1241
1242      // The size of a parameter can't change in the caller.  We shouldn't
1243      // have the shift==0 test, but need it to match the old code
1244      if (is_size() && enclosing_var.get_base_array_hashcode().isParam()) {
1245        if (((SequenceLength) derived).shift == 0) {
1246          return true;
1247        }
1248      }
1249
1250      VarInfo base = getDerivedParam();
1251      assert base != null : "can't find base for " + name();
1252      // Actually we should be getting all the derivations that could
1253      // be params, and if any of them are uninteresting, this is
1254      // uninteresting.
1255
1256      // Remember that if this is derived from a true param, then this
1257      // is a param too, so we don't need to worry.  However, if this
1258      // is derived from a derivedParam, then we need to find all
1259      // derivation parents that could possibly fail under these
1260      // rules.  Right now, we just get the first one.
1261
1262      // So if x = Foo(this.y, p.y) and this hasn't changed then we
1263      // will be ignoring the fact that y has changed.
1264
1265      // Henceforth only interesting if it's true that base = orig(base)
1266      if (base.name().equals("this")) {
1267        return false;
1268      }
1269      Global.debugSuppressParam.fine("Base is " + base.name());
1270      VarInfo origBase = ppt.find_var_by_name(base.prestate_name());
1271      if (origBase == null) {
1272        Global.debugSuppressParam.fine("No orig variable for base, returning true ");
1273        PrintInvariants.debugFiltering.fine("  not interesting, no orig variable for base");
1274        return true; // There can't be an equal invariant without orig
1275      }
1276      if (base.isEqualTo(origBase)) {
1277        Global.debugSuppressParam.fine("Saw equality.  Derived worth printing.");
1278        return false;
1279      } else {
1280        Global.debugSuppressParam.fine("Didn't see equality in base, so uninteresting");
1281        PrintInvariants.debugFiltering.fine("  didn't see equality in base");
1282        return true;
1283      }
1284
1285    } else {
1286      Global.debugSuppressParam.fine("  Not a derived param.");
1287    }
1288    return false;
1289  }
1290
1291  /** Convenience methods that return information from the ValueTuple. */
1292  @Pure
1293  public int getModified(ValueTuple vt) {
1294    if (is_static_constant) {
1295      // return ValueTuple.STATIC_CONSTANT;
1296      return ValueTuple.MODIFIED;
1297    } else {
1298      return vt.getModified(value_index);
1299    }
1300  }
1301
1302  @Pure
1303  public boolean isUnmodified(ValueTuple vt) {
1304    return ValueTuple.modIsUnmodified(getModified(vt));
1305  }
1306
1307  @Pure
1308  public boolean isModified(ValueTuple vt) {
1309    return ValueTuple.modIsModified(getModified(vt));
1310  }
1311
1312  @Pure
1313  public boolean isMissingNonsensical(ValueTuple vt) {
1314    return ValueTuple.modIsMissingNonsensical(getModified(vt));
1315  }
1316
1317  @Pure
1318  public boolean isMissingFlow(ValueTuple vt) {
1319    return ValueTuple.modIsMissingFlow(getModified(vt));
1320  }
1321
1322  @Pure
1323  public boolean isMissing(ValueTuple vt) {
1324    return isMissingNonsensical(vt) || isMissingFlow(vt);
1325  }
1326
1327  /**
1328   * Returns the value of this variable from a particular sample (ValueTuple).
1329   *
1330   * @param vt the ValueTuple from which to extract the value
1331   */
1332  public @Interned Object getValue(ValueTuple vt) {
1333    if (is_static_constant) {
1334      @SuppressWarnings("nullness") // derived: is_static_constant == true
1335      @NonNull Object result = static_constant_value;
1336      return result;
1337    } else {
1338      return vt.getValue(value_index);
1339    }
1340  }
1341
1342  /** Use of this method is discouraged. */
1343  public @Nullable @Interned Object getValueOrNull(ValueTuple vt) {
1344    if (is_static_constant) {
1345      return static_constant_value;
1346    } else {
1347      return vt.getValueOrNull(value_index);
1348    }
1349  }
1350
1351  /**
1352   * Returns the parent relation with the specified parent_relation_id; returns null if the relation
1353   * is not specified.
1354   */
1355  private @Nullable VarParent get_parent(int parent_relation_id) {
1356    for (VarParent vp : parents) {
1357      if (vp.parent_relation_id == parent_relation_id) {
1358        return vp;
1359      }
1360    }
1361    return null;
1362  }
1363
1364  /** Returns the parent variable name for the specified parent_relation_id. */
1365  private String parent_var_name(int parent_relation_id) {
1366    VarParent parent = get_parent(parent_relation_id);
1367    if (parent == null) {
1368      throw new IllegalArgumentException(
1369          "invalid parent_relation_id " + parent_relation_id + " for variable " + name());
1370    }
1371    return parent.parent_variable != null ? parent.parent_variable : name();
1372  }
1373
1374  /** Returns true iff the variable has a parent with the given parent_relation_id. */
1375  private boolean has_parent(int parent_relation_id) {
1376    return get_parent(parent_relation_id) != null;
1377  }
1378
1379  private @Nullable String parent_var(int parent_relation_id) {
1380    VarParent parent = get_parent(parent_relation_id);
1381    if (parent == null) {
1382      throw new IllegalArgumentException(
1383          "invalid parent_relation_id " + parent_relation_id + " for variable " + name());
1384    }
1385    return parent.parent_variable;
1386  }
1387
1388  /** Returns the value of this long variable (as an integer) */
1389  public int getIndexValue(ValueTuple vt) {
1390    Object raw = getValue(vt);
1391    if (raw == null) {
1392      throw new Error(
1393          "getIndexValue: getValue returned null "
1394              + this.name()
1395              + " index="
1396              + this.varinfo_index
1397              + " vt="
1398              + vt);
1399    }
1400    return ((Long) raw).intValue();
1401  }
1402
1403  /** Returns the value of this long variable (as a long) */
1404  public long getIntValue(ValueTuple vt) {
1405    Object raw = getValue(vt);
1406    if (raw == null) {
1407      throw new Error(
1408          "getIntValue: getValue returned null "
1409              + this.name()
1410              + " index="
1411              + this.varinfo_index
1412              + " vt="
1413              + vt);
1414    }
1415    return ((Long) raw).longValue();
1416  }
1417
1418  /** Returns the value of a long[] variable. */
1419  public long[] getIntArrayValue(ValueTuple vt) {
1420    Object raw = getValue(vt);
1421    if (raw == null) {
1422      throw new Error(
1423          "getIntArrayValue: getValue returned null "
1424              + this.name()
1425              + " index="
1426              + this.varinfo_index
1427              + " vt="
1428              + vt);
1429    }
1430    return (long[]) raw;
1431  }
1432
1433  /** Returns the value of a double variable. */
1434  public double getDoubleValue(ValueTuple vt) {
1435    Object raw = getValue(vt);
1436    if (raw == null) {
1437      throw new Error(
1438          "getDoubleValue: getValue returned null "
1439              + this.name()
1440              + " index="
1441              + this.varinfo_index
1442              + " vt="
1443              + vt);
1444    }
1445    return ((Double) raw).doubleValue();
1446  }
1447
1448  /** Returns the value of a double[] variable. */
1449  public double[] getDoubleArrayValue(ValueTuple vt) {
1450    Object raw = getValue(vt);
1451    if (raw == null) {
1452      throw new Error(
1453          "getDoubleArrayValue: getValue returned null "
1454              + this.name()
1455              + " index="
1456              + this.varinfo_index
1457              + " vt="
1458              + vt);
1459    }
1460    return (double[]) raw;
1461  }
1462
1463  /** Returns the value of a String variable. */
1464  public String getStringValue(ValueTuple vt) {
1465    return (String) getValue(vt);
1466  }
1467
1468  /** Return the value of a String[] array variable. */
1469  public String[] getStringArrayValue(ValueTuple vt) {
1470    Object raw = getValue(vt);
1471    if (raw == null) {
1472      throw new Error(
1473          "getDoubleArrayValue: getValue returned null "
1474              + this.name()
1475              + " index="
1476              + this.varinfo_index
1477              + " vt="
1478              + vt);
1479    }
1480    return (String[]) raw;
1481  }
1482
1483  /**
1484   * Returns true if this VarInfo is the leader of its equality set.
1485   *
1486   * @return true if this VarInfo is the leader of its equality set
1487   */
1488  @Pure
1489  public boolean isCanonical() {
1490    if (equalitySet == null) {
1491      return true;
1492    }
1493    return (equalitySet.leader() == this);
1494  }
1495
1496  /** Canonical representative that's equal to this variable. */
1497  @Pure
1498  public VarInfo canonicalRep() {
1499    if (equalitySet == null) {
1500      System.out.println("equality sets = " + ppt.equality_sets_txt());
1501      assert equalitySet != null
1502          : "Variable " + name() + " in ppt " + ppt.name() + " index = " + varinfo_index;
1503    }
1504    return equalitySet.leader();
1505  }
1506
1507  /** Returns true if this is a pointer or reference to another object. */
1508  @Pure
1509  public boolean is_reference() {
1510
1511    // This used to check to see if the item was a list and some other
1512    // odd things, but hashcode seems like the right check.
1513    return rep_type.isHashcode();
1514  }
1515
1516  /**
1517   * Returns the VarInfo for the sequence from which this was derived, or null if this wasn't
1518   * derived from a sequence. Only works for scalars.
1519   *
1520   * @return the VarInfo for the sequence from which this was derived, or null
1521   */
1522  public @Nullable VarInfo isDerivedSequenceMember() {
1523    if (derived == null) {
1524      return null;
1525    }
1526
1527    if (derived instanceof SequenceScalarSubscript) {
1528      SequenceScalarSubscript sss = (SequenceScalarSubscript) derived;
1529      return sss.seqvar();
1530    } else if (derived instanceof SequenceInitial) {
1531      SequenceInitial se = (SequenceInitial) derived;
1532      return se.seqvar();
1533    } else if (derived instanceof SequenceMax) {
1534      SequenceMax sm = (SequenceMax) derived;
1535      return sm.base;
1536    } else if (derived instanceof SequenceMin) {
1537      SequenceMin sm = (SequenceMin) derived;
1538      return sm.base;
1539    } else {
1540      return null;
1541    }
1542  }
1543
1544  @Pure
1545  public boolean isDerivedSequenceMinMaxSum() {
1546    return ((derived != null)
1547        && ((derived instanceof SequenceMax)
1548            || (derived instanceof SequenceMin)
1549            || (derived instanceof SequenceSum)));
1550  }
1551
1552  /**
1553   * Returns the original sequence variable from which this derived sequence was derived. Only works
1554   * for sequences.
1555   *
1556   * @return the VarInfo for the original sequence from which this sequence was derived, or null
1557   */
1558  public @Nullable VarInfo isDerivedSubSequenceOf() {
1559
1560    if (derived == null) {
1561      return null;
1562    }
1563
1564    if (derived instanceof SequenceScalarSubsequence) {
1565      SequenceScalarSubsequence sss = (SequenceScalarSubsequence) derived;
1566      return sss.seqvar();
1567    } else if (derived instanceof SequenceScalarArbitrarySubsequence) {
1568      SequenceScalarArbitrarySubsequence ssas = (SequenceScalarArbitrarySubsequence) derived;
1569      return ssas.seqvar();
1570    } else {
1571      return null;
1572    }
1573  }
1574
1575  /** Returns the variable (if any) that represents the size of this sequence. */
1576  public @Nullable VarInfo sequenceSize() {
1577    if (sequenceSize != null) {
1578      return sequenceSize;
1579    }
1580    assert rep_type.isArray();
1581    // we know the size follows the variable itself in the list
1582    VarInfo[] vis = ppt.var_infos;
1583    for (int i = varinfo_index + 1; i < vis.length; i++) {
1584      VarInfo vi = vis[i];
1585      if ((vi.derived instanceof SequenceLength) && (((SequenceLength) vi.derived).base == this)) {
1586        sequenceSize = vi;
1587        return sequenceSize;
1588      }
1589    }
1590    // It is possible that this VarInfo never had its size derived,
1591    // since it looked something like this.ary[..].field.  In this case,
1592    // we should return size(this.ary[..]), since it was derived and
1593    // must be the same values.
1594    VarInfo base = get_base_array();
1595    return ppt.find_var_by_name("size(" + base.name() + ")");
1596  }
1597
1598  /**
1599   * Returns true if the type in the original program is integer. Should perhaps check
1600   * Daikon.check_program_types and behave differently depending on that.
1601   */
1602  @Pure
1603  public boolean isIndex() {
1604    return (file_rep_type == ProglangType.INT) && type.isIndex();
1605  }
1606
1607  /**
1608   * Returns true if this variable is an array.
1609   *
1610   * @return true if this variable is an array
1611   */
1612  @Pure
1613  public boolean is_array() {
1614    return arr_dims > 0;
1615  }
1616
1617  /**
1618   * Returns false if this variable expression is not legal ESC syntax, except for any necessary
1619   * quantifications (subscripting). We err on the side of returning true, for now.
1620   *
1621   * @return false if this variable expression is not legal ESC syntax, except for any necessary
1622   *     quantifications (subscripting)
1623   */
1624  @Pure
1625  public boolean isValidEscExpression() {
1626    // "myList.length" is invalid
1627    if (derived instanceof SequenceLength) {
1628      SequenceLength sl = (SequenceLength) derived;
1629      if (!sl.base.type.isArray()) {
1630        // VarInfo base = sl.base;
1631        // System.out.printf("%s is not an array%n", base);
1632        // System.out.printf("type = %s%n", base.type);
1633        return false;
1634      }
1635    }
1636
1637    // "myList[]" is invalid, as is myList[foo] (when myList is a list
1638    // of some sort and not an array)
1639    for (VarInfo vi = this; vi != null; vi = vi.enclosing_var) {
1640      if (vi.file_rep_type.isArray() && !vi.type.isArray()) {
1641        return false;
1642      }
1643      if (vi.isDerived()) {
1644        VarInfo base = vi.derived.getBase(0);
1645        if (base.file_rep_type.isArray() && !base.type.isArray()) {
1646          return false;
1647        }
1648      }
1649    }
1650
1651    return true;
1652  }
1653
1654  /**
1655   * Returns true if invariants about this quantity are really properties of a pointer, but derived
1656   * variables can refer to properties of the thing pointed to. This distinction is important when
1657   * making logical statements about the object, because in the presence of side effects, the
1658   * pointed-to object can change even when the pointer doesn't. For instance, we might have "obj ==
1659   * orig(obj)", but "obj.color != orig(obj.color)". In such a case, isPointer() would be true of
1660   * obj, and for some forms of output we'd need to translate "obj == orig(obj)" into something like
1661   * "location(obj) == location(orig(obj))".
1662   */
1663  @Pure
1664  public boolean isPointer() {
1665    // This used to check whether the program type had a higher
1666    // dimension than the rep type, or if the rep type was integral
1667    // but the program type wasn't primitive. These rules worked
1668    // pretty well for Java, but not so well for C, where for instance
1669    // you might have rep_type = int and type = size_t.
1670
1671    return file_rep_type.isPointerFileRep();
1672  }
1673
1674  /**
1675   * A wrapper around VarInfoName.simplify_name() that also uses VarInfo information to guess
1676   * whether "obj" should logically be treated as just the hash code of "obj", rather than the whole
1677   * object.
1678   */
1679  public String simplifyFixup(String str) {
1680    if (isPointer()) {
1681      str = "(hash " + str + ")";
1682    }
1683    return str;
1684  }
1685
1686  public String simplifyFixedupName() {
1687    return simplifyFixup(simplify_name());
1688  }
1689
1690  // ///////////////////////////////////////////////////////////////////////////
1691  // Utility functions
1692  //
1693
1694  // Where do these really belong?
1695
1696  /**
1697   * Given two variables I and J, indicate whether it is necessarily the case that i&le;j or i&ge;j.
1698   * The variables also each have a shift, so the test can really be something like (i+1)&le;(j-1).
1699   * The test is one of:
1700   *
1701   * <ul>
1702   *   <li>i + i_shift &le; j + j_shift (if test_lessequal)
1703   *   <li>i + i_shift &ge; j + j_shift (if !test_lessequal)
1704   * </ul>
1705   *
1706   * This is a dynamic check, and so must not be called while Daikon is inferencing.
1707   */
1708  public static boolean compare_vars(
1709      VarInfo vari, int vari_shift, VarInfo varj, int varj_shift, boolean test_lessequal) {
1710
1711    // System.out.printf("comparing variables %s and %s in ppt %s%n",
1712    //        vari.name(), varj.name(), vari.ppt.name());
1713    // Throwable stack = new Throwable("debug traceback");
1714    // stack.fillInStackTrace();
1715    // stack.printStackTrace();
1716
1717    assert !Daikon.isInferencing;
1718    // System.out.println("compare_vars(" + vari.name + ", " + vari_shift + ", "+ varj.name + ", " +
1719    // varj_shift + ", " + (test_lessequal?"<=":">=") + ")");
1720    if (vari == varj) {
1721      // same variable
1722      return test_lessequal ? (vari_shift <= varj_shift) : (vari_shift >= varj_shift);
1723    }
1724    // different variables
1725    boolean samePpt = (vari.ppt == varj.ppt);
1726    assert samePpt;
1727    PptSlice indices_ppt = vari.ppt.findSlice_unordered(vari, varj);
1728    if (indices_ppt == null) {
1729      return false;
1730    }
1731
1732    boolean vari_is_var1 = (vari == indices_ppt.var_infos[0]);
1733    LinearBinary lb = LinearBinary.find(indices_ppt);
1734    long index_vari_minus_seq = -2222; // valid only if lb != null
1735    if (lb != null) {
1736      if (!lb.enoughSamples()) {
1737        lb = null;
1738      } else if (lb.core.a != 1 || lb.core.b != -1) {
1739        // Do not attempt to deal with anything but y=x+b, aka x-y+b=0.
1740        lb = null;
1741      } else {
1742        // System.out.println("justified LinearBinary: " + lb.format());
1743        // lb.b is var2()-var1().
1744
1745        // a is 1 or -1, and the values are integers, so c must be an integer
1746        long c_int = (long) lb.core.c;
1747        assert lb.core.c == c_int;
1748        index_vari_minus_seq = (vari_is_var1 ? -c_int : c_int);
1749        index_vari_minus_seq += vari_shift - varj_shift;
1750      }
1751    }
1752
1753    boolean vari_lt = false;
1754    boolean vari_le = false;
1755    boolean vari_gt = false;
1756    boolean vari_ge = false;
1757    {
1758      IntLessEqual ile = IntLessEqual.find(indices_ppt);
1759      IntLessThan ilt = IntLessThan.find(indices_ppt);
1760      IntGreaterEqual ige = IntGreaterEqual.find(indices_ppt);
1761      IntGreaterThan igt = IntGreaterThan.find(indices_ppt);
1762      if (ile != null && !ile.enoughSamples()) {
1763        ile = null;
1764      }
1765      if (ilt != null && !ilt.enoughSamples()) {
1766        ilt = null;
1767      }
1768      if (ige != null && !ige.enoughSamples()) {
1769        ige = null;
1770      }
1771      if (igt != null && !igt.enoughSamples()) {
1772        igt = null;
1773      }
1774
1775      if (vari_is_var1) {
1776        vari_lt = ilt != null;
1777        vari_le = ile != null;
1778        vari_gt = igt != null;
1779        vari_ge = ige != null;
1780      } else {
1781        vari_lt = igt != null;
1782        vari_le = ige != null;
1783        vari_gt = ilt != null;
1784        vari_ge = ile != null;
1785      }
1786    }
1787
1788    // System.out.println("test_lessequal=" + test_lessequal
1789    //                    + ", vari_can_be_lt=" + vari_can_be_lt
1790    //                    + ", vari_can_be_eq=" + vari_can_be_eq
1791    //                    + ", vari_can_be_gt=" + vari_can_be_gt);
1792
1793    if (test_lessequal) {
1794      if (lb != null) {
1795        return (index_vari_minus_seq <= 0);
1796      } else {
1797        return ((vari_le && (vari_shift <= varj_shift))
1798            || (vari_lt && (vari_shift - 1 <= varj_shift)));
1799      }
1800    } else {
1801      if (lb != null) {
1802        return (index_vari_minus_seq >= 0);
1803      } else {
1804        return ((vari_ge && (vari_shift >= varj_shift))
1805            || (vari_gt && (vari_shift + 1 >= varj_shift)));
1806      }
1807    }
1808  }
1809
1810  /** Check if two VarInfos are truly (non guarded) equal to each other right now. */
1811  @Pure
1812  public boolean isEqualTo(VarInfo other) {
1813    assert equalitySet != null;
1814    return this.equalitySet == other.equalitySet;
1815  }
1816
1817  /** Debug tracer. */
1818  private static final Logger debug = Logger.getLogger("daikon.VarInfo");
1819
1820  /** Enable assertions that would otherwise reduce run time performance. */
1821  private static final Logger debugEnableAssertions =
1822      Logger.getLogger("daikon.VarInfo.enableAssertions");
1823
1824  // This is problematic because it also enables some debugging output.
1825  // I need something that only enables assertions.
1826  // Slightly gross implementation, using a logger; but the command-line
1827  // options processing code already exists for it:
1828  // --dbg daikon.VarInfo
1829  public static boolean assertionsEnabled() {
1830    return debugEnableAssertions.isLoggable(Level.FINE);
1831  }
1832
1833  /**
1834   * Two variables are "compatible" if their declared types are castable and their comparabilities
1835   * are comparable. This is a reflexive relationship, because it calls
1836   * ProglangType.comparableOrSuperclassEitherWay. However, it is not transitive because it might
1837   * not hold for two children of a superclass, even though it would for each child and the
1838   * superclass.
1839   */
1840  public boolean compatible(VarInfo var2) {
1841    VarInfo var1 = this;
1842    // Can only compare in the same ppt because otherwise
1843    // comparability info may not make sense.
1844    boolean samePpt = (var1.ppt == var2.ppt);
1845    assert samePpt;
1846
1847    if (!comparableByType(var2)) {
1848      return false;
1849    }
1850
1851    if (!Daikon.ignore_comparability && !VarComparability.comparable(var1, var2)) {
1852      return false;
1853    }
1854
1855    return true;
1856  }
1857
1858  /**
1859   * Returns true if this sequence variable's element type is compatible with the scalar variable.
1860   */
1861  public boolean eltsCompatible(VarInfo sclvar) {
1862    VarInfo seqvar = this;
1863    if (Daikon.check_program_types) {
1864      ProglangType elttype = seqvar.type.elementType();
1865      if (!elttype.comparableOrSuperclassEitherWay(sclvar.type)) {
1866        // System.out.printf("eltsCompatible: bad program types; elttype(%s)=%s, scltype(%s)=%s%n",
1867        //                   seqvar, elttype, sclvar, sclvar.type);
1868        return false;
1869      }
1870    }
1871    if (!Daikon.ignore_comparability) {
1872      if (!VarComparability.comparable(seqvar.comparability.elementType(), sclvar.comparability)) {
1873        // System.out.printf("eltsCompatible: eltcomp(%s;%s)=%s, sclcomp(%s)=%s%n",
1874        //                   seqvar, seqvar.comparability.elementType(),
1875        //                   seqvar.comparability.elementType(), sclvar, sclvar.comparability);
1876        return false;
1877      }
1878    }
1879    return true;
1880  }
1881
1882  /**
1883   * Without using comparability info, check that this is comparable to var2. This is a reflexive
1884   * relationship, because it calls ProglangType.comparableOrSuperclassEitherWay. However, it is not
1885   * transitive because it might not hold for two children of a superclass, even though it would for
1886   * each child and the superclass. Does not check comparabilities.
1887   */
1888  public boolean comparableByType(VarInfo var2) {
1889    VarInfo var1 = this;
1890
1891    // System.out.printf("comparableByType(%s, %s)%n", var1, var2);
1892
1893    // the check ensures that a scalar or string and elements of an array of the same type are
1894    // labelled as comparable
1895    if (Daikon.check_program_types
1896        && (var1.file_rep_type.isArray() && !var2.file_rep_type.isArray())) {
1897
1898      // System.out.printf("comparableByType: case 1 %s%n", var1.eltsCompatible(var2));
1899      if (var1.eltsCompatible(var2)) {
1900        return true;
1901      }
1902    }
1903
1904    // the check ensures that a scalar or string and elements of an array of the same type are
1905    // labelled as comparable
1906    if (Daikon.check_program_types
1907        && (!var1.file_rep_type.isArray() && var2.file_rep_type.isArray())) {
1908
1909      // System.out.printf("comparableByType: case 2 %s%n", var2.eltsCompatible(var1));
1910      if (var2.eltsCompatible(var1)) {
1911        return true;
1912      }
1913    }
1914
1915    if (Daikon.check_program_types && (var1.file_rep_type != var2.file_rep_type)) {
1916      // System.out.printf("comparableByType: case 4 return false%n");
1917      return false;
1918    }
1919
1920    // If the file rep types match then the variables are comparable unless
1921    // their dimensions are different.
1922    if (!dkconfig_declared_type_comparability) {
1923      if (var1.type.dimensions() != var2.type.dimensions()) {
1924        // debug_print_once ("types %s and %s are not comparable",
1925        //                    var1.type, var2.type);
1926        return false;
1927      }
1928      return true;
1929    }
1930
1931    if (Daikon.check_program_types && !var1.type.comparableOrSuperclassEitherWay(var2.type)) {
1932      // debug_print_once ("types %s and %s are not comparable",
1933      //                     var1.type, var2.type);
1934      return false;
1935    }
1936    // debug_print_once ("types %s and %s are comparable",
1937    //                  var1.type, var2.type);
1938
1939    // System.out.printf("comparableByType: fallthrough return true%n");
1940    return true;
1941  }
1942
1943  /**
1944   * Without using comparability info, check that this is comparable to var2. This is a reflexive
1945   * and transitive relationship. Does not check comparabilities.
1946   *
1947   * @param var2 the variable to test comparability with
1948   * @return true if this is comparable to var2
1949   */
1950  public boolean comparableNWay(VarInfo var2) {
1951    VarInfo var1 = this;
1952    if (Daikon.check_program_types && !var1.type.comparableOrSuperclassOf(var2.type)) {
1953      return false;
1954    }
1955    if (Daikon.check_program_types && !var2.type.comparableOrSuperclassOf(var1.type)) {
1956      return false;
1957    }
1958    if (Daikon.check_program_types && (var1.file_rep_type != var2.file_rep_type)) {
1959      return false;
1960    }
1961    return true;
1962  }
1963
1964  /** Returns true if this sequence's first index type is compatible with the scalar variable. */
1965  public boolean indexCompatible(VarInfo sclvar) {
1966    VarInfo seqvar = this;
1967    if (Daikon.check_program_types) {
1968      if (!seqvar.is_array() || !sclvar.isIndex()) {
1969        return false;
1970      }
1971    }
1972    if (!Daikon.ignore_comparability) {
1973      if (!VarComparability.comparable(seqvar.comparability.indexType(0), sclvar.comparability)) {
1974        return false;
1975      }
1976    }
1977    return true;
1978  }
1979
1980  // Interning is lost when an object is serialized and deserialized.
1981  // Manually re-intern any interned fields upon deserialization.
1982  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
1983    in.defaultReadObject();
1984    var_info_name = var_info_name.intern(); // vin ok
1985    str_name = str_name.intern();
1986
1987    for (VarParent parent : parents) {
1988      parent.parent_ppt = parent.parent_ppt.intern();
1989      if (parent.parent_variable != null) {
1990        parent.parent_variable = parent.parent_variable.intern();
1991      }
1992    }
1993
1994    if (relative_name != null) {
1995      relative_name = relative_name.intern();
1996    }
1997  }
1998
1999  // /**
2000  //  * It is <b>not</b> safe in general to compare based on VarInfoName
2001  //  * alone, because it is possible for two different program points to have
2002  //  * unrelated variables of the same name.
2003  //  */
2004  // public static class LexicalComparator implements Comparator<VarInfo> {
2005  //   @Pure
2006  //   public int compare(VarInfo vi1, VarInfo vi2) {
2007  //     VarInfoName name1 = vi1.name;
2008  //     VarInfoName name2 = vi2.name;
2009  //     return name1.compareTo(name2);
2010  //   }
2011  // }
2012
2013  // Is this property always guaranteed to be true?  It's placed in a
2014  // slice, but then might it get printed or treated as true?
2015  /**
2016   * Create a guarding predicate for this VarInfo, that is, an invariant that ensures that this
2017   * object is available for access to variables that reference it, such as fields. (The invariant
2018   * is placed in the appropriate slice.) Returns null if no guarding is needed.
2019   */
2020  // Adding a test against null is not quite right for C programs, where *p
2021  // could be nonsensical (uninitialized or freed) even when p is non-null.
2022  // But this is a decent approximation to start with.
2023  public @Nullable Invariant createGuardingPredicate(boolean install) {
2024    // Later for the array, make sure index in bounds
2025    if (!(type.isArray() || type.isObject())) {
2026      String message =
2027          String.format("Unexpected guarding based on %s with type %s%n", name(), type);
2028      System.err.print(message);
2029      throw new Error(message);
2030    }
2031
2032    // For now associating with the variable's PptSlice
2033    PptSlice slice = ppt.get_or_instantiate_slice(this);
2034
2035    Invariant result = Invariant.find(NonZero.class, slice);
2036
2037    // Check whether the predicate already exists
2038    if (result == null) {
2039      // If it doesn't, create a "fake" invariant, which should
2040      // never be printed.  Is it a good idea even to set
2041      // result.falsified to true?  We know it's true because
2042      // result's children were missing.  However, some forms of
2043      // filtering might remove it from slice.
2044      VarInfo[] vis = slice.var_infos;
2045      if (SingleScalar.valid_types_static(vis)) {
2046        result = NonZero.get_proto().instantiate(slice);
2047      } else if (SingleScalarSequence.valid_types_static(vis)) {
2048        result = EltNonZero.get_proto().instantiate(slice);
2049      } else {
2050        throw new Error("Bad VarInfos");
2051      }
2052      if (result == null) {
2053        // Return null if NonZero invariant is not applicable to this variable.
2054        return null;
2055      }
2056      result.isGuardingPredicate = true;
2057      // System.out.printf("Created a guarding predicate: %s at %s%n", result, slice);
2058      // new Error().printStackTrace(System.out);
2059      if (install) {
2060        slice.addInvariant(result);
2061      }
2062    }
2063
2064    return result;
2065  }
2066
2067  /**
2068   * Finds a list of variables that must be guarded for this VarInfo to be guaranteed to not be
2069   * missing. This list never includes "this", as it can never be null. The variables are returned
2070   * in the order in which their guarding prefixes are supposed to print.
2071   *
2072   * <p>For example, if this VarInfo is "a.b.c", then the guarding list consists of the variables
2073   * "a" and "a.b". If "a" is null or "a.b" is null, then "a.b.c" is missing (does not exist).
2074   *
2075   * @return a list of variables that must be guarded
2076   */
2077  public List<VarInfo> getGuardingList() {
2078
2079    List<VarInfo> result = new ArrayList<>();
2080
2081    if (Daikon.dkconfig_guardNulls == "never") { // interned
2082      return result;
2083    }
2084
2085    // If this is never missing, nothing to guard
2086    if ((Daikon.dkconfig_guardNulls == "missing") // interned
2087        && !canBeMissing) {
2088      return result;
2089    }
2090
2091    // Create a list of variables to be guarded from the list of all
2092    // enclosing variables.
2093    for (VarInfo vi : get_all_enclosing_vars()) {
2094      // if (var_flags.contains(VarFlags.CLASSNAME)) {
2095      //   System.err.printf(
2096      //       "%s file_rep_type = %s, canbemissing = %b%n", vi, vi.file_rep_type,
2097      // vi.canBeMissing);
2098      // }
2099      if (!vi.file_rep_type.isHashcode()) {
2100        continue;
2101      }
2102      result.add(0, vi);
2103      if ((Daikon.dkconfig_guardNulls == "missing") // interned
2104          && !vi.canBeMissing) {
2105        break;
2106      }
2107    }
2108    return result;
2109  }
2110
2111  /**
2112   * Returns a list of all of the variables that enclose this one. If this is derived, this includes
2113   * all of the enclosing variables of all of the bases.
2114   */
2115  public List<VarInfo> get_all_enclosing_vars() {
2116    List<VarInfo> result = new ArrayList<>();
2117    if (isDerived()) {
2118      for (VarInfo base : derived.getBases()) {
2119        result.addAll(base.get_all_enclosing_vars());
2120      }
2121    } else { // not derived
2122      for (VarInfo vi = this.enclosing_var; vi != null; vi = vi.enclosing_var) {
2123        result.add(vi);
2124      }
2125    }
2126    return result;
2127  }
2128
2129  /** Compare names by index. */
2130  public static final class IndexComparator implements Comparator<VarInfo>, Serializable {
2131    // This needs to be serializable because Equality invariants keep
2132    // a TreeSet of variables sorted by theInstance.
2133
2134    // We are Serializable, so we specify a version to allow changes to
2135    // method signatures without breaking serialization.  If you add or
2136    // remove fields, you should change this number to the current date.
2137    static final long serialVersionUID = 20050923L;
2138
2139    private IndexComparator() {}
2140
2141    @Pure
2142    @Override
2143    public int compare(VarInfo vi1, VarInfo vi2) {
2144      if (vi1.varinfo_index < vi2.varinfo_index) {
2145        return -1;
2146      } else if (vi1.varinfo_index == vi2.varinfo_index) {
2147        return 0;
2148      } else {
2149        return 1;
2150      }
2151    }
2152
2153    public static IndexComparator getInstance() {
2154      return theInstance;
2155    }
2156
2157    public static final IndexComparator theInstance = new IndexComparator();
2158  }
2159
2160  /**
2161   * Class used to contain a pair of VarInfos and their sample count. Currently used for equality
2162   * set merging as a way to store pairs of equal variables. The variable with the smaller index is
2163   * always stored first.
2164   *
2165   * <p>Pairs are equal if both of their VarInfos are identical. Note that the content of the
2166   * VarInfos are not compared, only their pointer values.
2167   */
2168  public static class Pair {
2169
2170    public VarInfo v1;
2171    public VarInfo v2;
2172    public int samples;
2173
2174    public Pair(VarInfo v1, VarInfo v2, int samples) {
2175      if (v1.varinfo_index < v2.varinfo_index) {
2176        this.v1 = v1;
2177        this.v2 = v2;
2178      } else {
2179        this.v1 = v2;
2180        this.v2 = v1;
2181      }
2182      this.samples = samples;
2183    }
2184
2185    @EnsuresNonNullIf(result = true, expression = "#1")
2186    @Pure
2187    @Override
2188    public boolean equals(@GuardSatisfied Pair this, @GuardSatisfied @Nullable Object obj) {
2189      if (!(obj instanceof Pair)) {
2190        return false;
2191      }
2192
2193      Pair o = (Pair) obj;
2194      return (o.v1 == v1) && (o.v2 == v2);
2195    }
2196
2197    @Pure
2198    @Override
2199    public int hashCode(@GuardSatisfied Pair this) {
2200      return v1.hashCode() + v2.hashCode();
2201    }
2202
2203    @SideEffectFree
2204    @Override
2205    public String toString(@GuardSatisfied Pair this) {
2206      return v1.name() + " = " + v2.name();
2207    }
2208  }
2209
2210  /** Returns the set of values that have been seen so far for this variable. */
2211  public ValueSet get_value_set() {
2212
2213    // Static constants don't have value sets, so we must make one
2214    if (is_static_constant) {
2215      ValueSet vs = ValueSet.factory(this);
2216      assert static_constant_value != null
2217          : "@AssumeAssertion(nullness): dependent: is_static_constant";
2218      vs.add(static_constant_value);
2219      return vs;
2220    }
2221
2222    return ppt.value_sets[value_index];
2223  }
2224
2225  public String get_value_info() {
2226    return name() + "- " + get_value_set().repr_short();
2227  }
2228
2229  /**
2230   * Returns the number of elements in the variable's equality set. Returns 1 if the equality
2231   * optimization is turned off.
2232   */
2233  public int get_equalitySet_size() {
2234    if (equalitySet == null) {
2235      return 1;
2236    } else {
2237      return equalitySet.size();
2238    }
2239  }
2240
2241  /**
2242   * Returns the vars_info in the variable's equality set. Returns a set with just itself if the
2243   * equality optimization is turned off.
2244   */
2245  public Set<VarInfo> get_equalitySet_vars() {
2246    if (equalitySet == null) {
2247      HashSet<VarInfo> set = new HashSet<>();
2248      set.add(this);
2249      return set;
2250    } else {
2251      return equalitySet.getVars();
2252    }
2253  }
2254
2255  /**
2256   * Returns the leader in the variable's equality set. Returns itself if the equality optimization
2257   * is turned off.
2258   */
2259  public VarInfo get_equalitySet_leader() {
2260    // if (equalitySet == null && VarInfo.use_equality_optimization == false) {  // match } for vim
2261    if (equalitySet == null) {
2262      return this;
2263    } else {
2264      return equalitySet.leader();
2265    }
2266  }
2267
2268  private static Set<String> out_strings = new LinkedHashSet<>();
2269
2270  /** If the message is new print it, otherwise discard it. */
2271  @FormatMethod
2272  static void debug_print_once(String format, @Nullable Object... args) {
2273    String msg = String.format(format, args);
2274    if (!out_strings.contains(msg)) {
2275      System.out.println(msg);
2276      out_strings.add(msg);
2277    }
2278  }
2279
2280  /**
2281   * Returns true if this variable is a parameter to a method, or derived from a parameter to a
2282   * method. By default, if p is a parameter, then some EXIT invariants related to p aren't printed.
2283   * However, this does not affect the computation of invariants.
2284   *
2285   * <p>Front ends are responsible for setting whether p is a parameter and whether p.a is a
2286   * parameter. In Java, p.a is not a parameter, whereas in IOA, it is.
2287   *
2288   * @return true if this variable is a parameter
2289   */
2290  @Pure
2291  public boolean isParam() {
2292    return var_flags.contains(VarFlags.IS_PARAM);
2293  }
2294
2295  /** Set this variable as a parameter. */
2296  public void set_is_param() {
2297    // System.out.printf("setting is_param for %s %n", name());
2298    var_flags.add(VarFlags.IS_PARAM);
2299  }
2300
2301  /** Set whether or not this variable is a parameter. */
2302  public void set_is_param(boolean set) {
2303    if (set) {
2304      set_is_param();
2305    } else {
2306      var_flags.remove(VarFlags.IS_PARAM);
2307    }
2308  }
2309
2310  /** Adds a subscript (or sequence) to an array variable, by substituting it for "..". */
2311  public String apply_subscript(String subscript) {
2312    assert arr_dims == 1 : "Can't apply subscript to " + name();
2313    return name().replace("..", subscript);
2314  }
2315
2316  /** Adds a subscript (or subsequence) to an array name, by substituting it for "..". */
2317  public static String apply_subscript(String sequence, String subscript) {
2318    return sequence.replace("[..]", "[" + subscript + "]");
2319  }
2320
2321  /**
2322   * For array variables, returns the variable that is a simple array. If this variable is a slice,
2323   * it returns the array variable that is being sliced. If this variable is a simple array itself,
2324   * returns this.
2325   */
2326  public VarInfo get_array_var() {
2327    assert file_rep_type.isArray();
2328    if (isDerived()) {
2329      return derived.get_array_var();
2330    } else {
2331      return this;
2332    }
2333  }
2334
2335  /**
2336   * Returns the VarInfo that represents the base array of this array. For example, if the array is
2337   * a[].b.c, returns a[].
2338   */
2339  @Pure
2340  public VarInfo get_base_array() {
2341    assert file_rep_type.isArray() : this;
2342    VarInfo var = this;
2343    while (var.var_kind != VarKind.ARRAY) {
2344      if (var.enclosing_var == null) {
2345        // error condition; print some debugging output before assertion failure
2346        for (VarInfo vi = this; vi != null; vi = vi.enclosing_var) {
2347          System.out.printf("%s %s%n", vi, vi.var_kind);
2348        }
2349        assert var.enclosing_var != null : this + " " + var;
2350      }
2351      assert var.enclosing_var != null : "@AssumeAssertion(nullness): just tested";
2352      var = var.enclosing_var;
2353    }
2354    return var;
2355  }
2356
2357  /**
2358   * Returns the VarInfo that represents the hashcode of the base array of this array. For example,
2359   * if the array is a[].b.c, returns a. Returns null if there is no such variable.
2360   */
2361  @Pure
2362  public @Nullable VarInfo get_base_array_hashcode() {
2363    return get_base_array().enclosing_var;
2364  }
2365
2366  /** Returns the lower bound of the array or slice. */
2367  public Quantify.Term get_lower_bound() {
2368    assert file_rep_type.isArray() : "var " + name() + " rep " + file_rep_type;
2369    if (isDerived()) {
2370      return derived.get_lower_bound();
2371    } else {
2372      return new Quantify.Constant(0);
2373    }
2374  }
2375
2376  /** Returns the upper bound of the array or slice. */
2377  public Quantify.Term get_upper_bound() {
2378    assert file_rep_type.isArray();
2379    if (isDerived()) {
2380      return derived.get_upper_bound();
2381    } else {
2382      return new Quantify.Length(this, -1);
2383    }
2384  }
2385
2386  /**
2387   * Returns the length of this array. The array can be an array or a list. It cannot be a slice.
2388   */
2389  public Quantify.Term get_length() {
2390    assert file_rep_type.isArray() && !isDerived() : this;
2391    return new Quantify.Length(this, 0);
2392  }
2393
2394  /**
2395   * Updates any references to other variables that should be within this ppt by looking them up
2396   * within the ppt. Necessary if a variable is moved to a different program point or if cloned
2397   * variable is placed in a new program point (such as is done when combined exits are created).
2398   */
2399  public void update_after_moving_to_new_ppt() {
2400    if (enclosing_var != null) {
2401      // enclosing_var exists but is in the wrong ppt; update it
2402      enclosing_var = ppt.find_var_by_name(enclosing_var.name());
2403      assert enclosing_var != null;
2404    }
2405  }
2406
2407  /**
2408   * Temporary to let things compile now that name is private. Eventually this should be removed.
2409   */
2410  public VarInfoName get_VarInfoName() {
2411    return var_info_name; // vin ok
2412  }
2413
2414  private static boolean isStatic(String variable, String enclosing) {
2415    return !variable.startsWith(enclosing) || variable.charAt(enclosing.length()) != '.';
2416  }
2417
2418  // Map java objects to C# objects.
2419  private static final Map<String, String> csharp_types = new HashMap<>();
2420
2421  static {
2422    csharp_types.put("java.lang.String", "string");
2423    csharp_types.put("java.lang.String[]", "string[]");
2424    csharp_types.put("java.lang.Object", "object");
2425    csharp_types.put("java.lang.Object[]", "object[]");
2426    csharp_types.put("boolean", "bool");
2427  }
2428
2429  /** Transforms a Daikon type representation into a valid C# type. */
2430  public static String fix_csharp_type_name(String type) {
2431    if (csharp_types.containsKey(type)) {
2432      return csharp_types.get(type);
2433    } else {
2434      return type;
2435    }
2436  }
2437
2438  /**
2439   * If the variable is an array, returns a valid C# 'Select' statement representing the array. For
2440   * example, this.Array[].field would become this.Array.Select(x &rArr; x.field)
2441   *
2442   * <p>If the variable is not an array, csharp_name() is returned.
2443   */
2444  public String csharp_collection_string() {
2445    String[] split = csharp_array_split();
2446    if (split[1].equals("")) {
2447      return split[0];
2448    } else {
2449      return split[0] + ".Select(x => x" + split[1] + ")";
2450    }
2451  }
2452
2453  /**
2454   * Splits an array variable into the array and field portions. For example, if the variable
2455   * this.Array[].field then
2456   *
2457   * <pre>
2458   * result[0] = this.Array[]
2459   * result[1] = field
2460   * </pre>
2461   *
2462   * If the variable is not an array then
2463   *
2464   * <pre>
2465   * result[0] = csharp_name()
2466   * result[1] = ""
2467   * </pre>
2468   *
2469   * (there is no splitting).
2470   */
2471  public String[] csharp_array_split() {
2472    String[] results = new String[2];
2473
2474    if (!is_array()) {
2475      results[0] = csharp_name();
2476      results[1] = "";
2477      return results;
2478    }
2479
2480    String fields = "";
2481    VarInfo v = this;
2482    // Go backwards from v until we reach the array portion.
2483    while (v.var_kind != VarInfo.VarKind.ARRAY && v.enclosing_var != null) {
2484      if (v.relative_name != null) {
2485        if (v.relative_name.equals("GetType()")) {
2486          fields = "." + v.relative_name;
2487        } else {
2488          fields = "." + v.relative_name + fields;
2489        }
2490      }
2491      v = v.enclosing_var;
2492    }
2493
2494    results[0] = v.csharp_name();
2495    results[1] = fields;
2496    return results;
2497  }
2498
2499  /** Returns the name of this variable in the specified format. */
2500  public String name_using(OutputFormat format) {
2501    if (format == OutputFormat.DAIKON) {
2502      return name();
2503    }
2504    if (format == OutputFormat.SIMPLIFY) {
2505      return simplify_name();
2506    }
2507    if (format == OutputFormat.ESCJAVA) {
2508      return esc_name();
2509    }
2510    if (format == OutputFormat.JAVA) {
2511      return java_name();
2512    }
2513    if (format == OutputFormat.JML) {
2514      return jml_name();
2515    }
2516    if (format == OutputFormat.DBCJAVA) {
2517      return dbc_name();
2518    }
2519    if (format == OutputFormat.CSHARPCONTRACT) {
2520      return csharp_name();
2521    }
2522    throw new UnsupportedOperationException("Unknown format requested: " + format);
2523  }
2524
2525  /** Returns the name of this variable as a valid C# Code Contract. */
2526  @SideEffectFree
2527  public String csharp_name() {
2528    return csharp_name(null);
2529  }
2530
2531  /**
2532   * Returns the name of this variable as a valid C# Code Contract.
2533   *
2534   * @param index an array index. Must be null for a non-array variable.
2535   * @return the name of this variable as a valid C# Code Contract
2536   */
2537  @SideEffectFree
2538  public String csharp_name(@Nullable String index) {
2539    if (index != null) {
2540      assert file_rep_type.isArray();
2541    }
2542
2543    if (postState != null) {
2544      return "Contract.OldValue(" + postState.csharp_name(index) + ")";
2545    }
2546
2547    if (derived != null) {
2548      return derived.csharp_name(index);
2549    }
2550
2551    switch (var_kind) {
2552      case FIELD:
2553        assert relative_name != null : this;
2554
2555        if (enclosing_var != null) {
2556          if (isStatic(str_name, enclosing_var.name())) {
2557            return str_name;
2558          }
2559          return enclosing_var.csharp_name(index) + "." + relative_name;
2560        }
2561
2562        return str_name;
2563
2564      case FUNCTION:
2565        if (var_flags.contains(VarFlags.TO_STRING)) {
2566          return enclosing_var.csharp_name(index);
2567        }
2568
2569        if (var_flags.contains(VarFlags.CLASSNAME)) {
2570          if (arr_dims > 0) {
2571            return csharp_collection_string();
2572          } else {
2573            return enclosing_var.csharp_name(index) + ".GetType()";
2574          }
2575        }
2576
2577        if (enclosing_var != null) {
2578
2579          if (isStatic(str_name, enclosing_var.name())) {
2580            String qualifiedName = str_name.substring(0, str_name.indexOf('('));
2581            return qualifiedName + "(" + enclosing_var.csharp_name(index) + ")";
2582          } else if (var_flags.contains(VarFlags.IS_PROPERTY)) {
2583            return enclosing_var.csharp_name(index) + "." + relative_name;
2584          } else {
2585            return enclosing_var.csharp_name(index) + "." + relative_name + "()";
2586          }
2587        } else {
2588          return str_name;
2589        }
2590
2591      case ARRAY:
2592        if (index == null) {
2593          return enclosing_var.csharp_name(null);
2594        }
2595        return enclosing_var.csharp_name(null) + "[" + index + "]";
2596
2597      case VARIABLE:
2598        assert enclosing_var == null;
2599        return str_name;
2600
2601      case RETURN:
2602        return "Contract.Result<" + fix_csharp_type_name(type.toString()) + ">()";
2603
2604      default:
2605        throw new Error("can't drop through switch statement.");
2606    }
2607  }
2608
2609  /** Returns the name in Java format. This is the same as JML. */
2610  public String java_name() {
2611    return jml_name();
2612  }
2613
2614  /** Returns the name in DBC format. This is the same as JML. */
2615  public String dbc_name() {
2616    return jml_name();
2617  }
2618
2619  /** Returns the name of this variable in ESC format. */
2620  @SideEffectFree
2621  public String esc_name() {
2622    return esc_name(null);
2623  }
2624
2625  /**
2626   * Returns the name of this variable in ESC format. If an index is specified, it is used as an
2627   * array index. It is an error to specify an index on a non-array variable.
2628   */
2629  @SideEffectFree
2630  public String esc_name(@Nullable String index) {
2631
2632    // System.out.printf("esc_name for %s, flags %s, enclosing-var %s "
2633    //                  + " poststate %s index %s rname %s ppt %s%n", str_name,
2634    //                    var_flags, enclosing_var, postState, index,
2635    //                    relative_name, ppt.name());
2636    if (index != null) {
2637      assert file_rep_type.isArray();
2638    }
2639
2640    // If this is an orig variable, use the post version to generate the name
2641    if (postState != null) {
2642      return "\\old(" + postState.esc_name(index) + ")";
2643    }
2644
2645    // If this is a derived variable, the derivations builds the name
2646    if (derived != null) {
2647      return derived.esc_name(index);
2648    }
2649
2650    // Build the name by processing back through all of the enclosing variables
2651    switch (var_kind) {
2652      case FIELD:
2653        assert relative_name != null : this;
2654        if (enclosing_var != null) {
2655          return enclosing_var.esc_name(index) + "." + relative_name;
2656        }
2657        return str_name;
2658      case FUNCTION:
2659        // function_args      assert function_args == null : "function args not implemented";
2660        if (var_flags.contains(VarFlags.CLASSNAME)) {
2661          return ("\\typeof(" + enclosing_var.esc_name(index) + ")");
2662        }
2663        if (var_flags.contains(VarFlags.TO_STRING)) {
2664          return enclosing_var.esc_name(index) + ".toString";
2665        }
2666        if (enclosing_var != null) {
2667          return enclosing_var.esc_name(index) + "." + relative_name + "()";
2668        }
2669        return str_name;
2670      case ARRAY:
2671        if (index == null) {
2672          return enclosing_var.esc_name(null) + "[]";
2673        }
2674        return enclosing_var.esc_name(null) + "[" + index + "]";
2675      case VARIABLE:
2676        assert enclosing_var == null;
2677        return str_name;
2678      case RETURN:
2679        return "\\result";
2680      default:
2681        throw new Error("can't drop through switch statement");
2682    }
2683  }
2684
2685  /** Returns the name of this variable in JML format. */
2686  @SideEffectFree
2687  public String jml_name() {
2688    return jml_name(null);
2689  }
2690
2691  /**
2692   * Returns the name of this variable in JML format.
2693   *
2694   * @param index an array index. Must be null for a non-array variable.
2695   * @return the name of this variable in JML format
2696   */
2697  public String jml_name(@Nullable String index) {
2698
2699    if (index != null) {
2700      assert file_rep_type.isArray();
2701    }
2702
2703    // If this is an orig variable, use the post version to generate the name
2704    if (postState != null) {
2705      return "\\old(" + postState.jml_name(index) + ")";
2706    }
2707
2708    // If this is a derived variable, the derivations builds the name
2709    if (derived != null) {
2710      return derived.jml_name(index);
2711    }
2712
2713    // If this is an array of fields, collect the fields into a collection
2714    if ((arr_dims > 0) && (var_kind != VarKind.ARRAY) && !var_flags.contains(VarFlags.CLASSNAME)) {
2715      String field_name = relative_name;
2716      ;
2717      VarInfo vi = this.enclosing_var;
2718      for (; vi.var_kind != VarKind.ARRAY; vi = vi.enclosing_var) {
2719        field_name = vi.relative_name + "." + field_name;
2720      }
2721      return String.format("daikon.Quant.collectObject(%s, \"%s\")", vi.jml_name(), field_name);
2722    }
2723
2724    // Build the name by processing back through all of the enclosing variables
2725    switch (var_kind) {
2726      case FIELD:
2727        assert relative_name != null : this;
2728        if (enclosing_var != null) {
2729          return enclosing_var.jml_name(index) + "." + relative_name;
2730        }
2731        return str_name;
2732      case FUNCTION:
2733        // function_args      assert function_args == null : "function args not implemented";
2734        if (var_flags.contains(VarFlags.CLASSNAME)) {
2735          if (arr_dims > 0) {
2736            return String.format("daikon.Quant.typeArray(%s)", enclosing_var.jml_name(index));
2737          } else {
2738            return enclosing_var.jml_name(index) + DaikonVariableInfo.class_suffix;
2739          }
2740        }
2741        if (var_flags.contains(VarFlags.TO_STRING)) {
2742          return enclosing_var.jml_name(index) + ".toString()";
2743        }
2744        if (enclosing_var != null) {
2745          return enclosing_var.jml_name(index) + "." + relative_name + "()";
2746        }
2747        return str_name;
2748      case ARRAY:
2749        if (index == null) {
2750          return enclosing_var.jml_name(null);
2751        }
2752        return enclosing_var.jml_name(null) + "[" + index + "]";
2753      case VARIABLE:
2754        assert enclosing_var == null;
2755        return str_name;
2756      case RETURN:
2757        return "\\result";
2758      default:
2759        throw new Error("can't drop through switch statement");
2760    }
2761  }
2762
2763  /** Returns the name of this variable in simplify format. */
2764  @SideEffectFree
2765  public String simplify_name() {
2766    return simplify_name(null);
2767  }
2768
2769  /**
2770   * Returns the name of this variable in simplify format. If an index is specified, it is used as
2771   * an array index. It is an error to specify an index on a non-array variable.
2772   */
2773  public String simplify_name(@Nullable String index) {
2774    assert (index == null) || file_rep_type.isArray() : index + " " + name();
2775
2776    // If this is a derived variable, the derivations builds the name
2777    if (derived != null) {
2778      return derived.simplify_name();
2779    }
2780
2781    // Build the name by processing back through all of the enclosing variables
2782    switch (var_kind) {
2783      case FIELD:
2784        assert relative_name != null : this;
2785        return String.format("(select |%s| %s)", relative_name, enclosing_var.simplify_name(index));
2786      case FUNCTION:
2787        // function_args      assert function_args == null : "function args not implemented";
2788        if (var_flags.contains(VarFlags.CLASSNAME)) {
2789          return ("(typeof " + enclosing_var.simplify_name(index) + ")");
2790        }
2791        if (var_flags.contains(VarFlags.TO_STRING)) {
2792          return String.format("(select |toString| %s)", enclosing_var.simplify_name(index));
2793        }
2794        if (enclosing_var != null) {
2795          return enclosing_var.simplify_name(index) + "." + relative_name + "()";
2796        }
2797        return str_name;
2798      case ARRAY:
2799        if (index == null) {
2800          return String.format("(select elems %s)", enclosing_var.simplify_name());
2801        }
2802        // if (index.equals("|0|")) {
2803        //   System.err.printf("index = %s%n", index);
2804        //   Throwable t = new Throwable();
2805        //   t.printStackTrace();
2806        // }
2807        return String.format("(select (select elems %s) %s)", enclosing_var.simplify_name(), index);
2808      case VARIABLE:
2809        if (dkconfig_constant_fields_simplify && str_name.contains(".")) {
2810          String sel;
2811          String[] fields;
2812          if (postState != null) {
2813            fields = postState.name().split("\\.");
2814            sel = String.format("(select |%s| |__orig__%s|)", fields[1], fields[0]);
2815          } else { // not orig variable
2816            fields = str_name.split("\\.");
2817            sel = String.format("(select |%s| |%s|)", fields[1], fields[0]);
2818          }
2819          for (int ii = 2; ii < fields.length; ii++) {
2820            sel = String.format("(select |%s| %s)", fields[ii], sel);
2821          }
2822          return sel;
2823        }
2824
2825        assert enclosing_var == null;
2826        if (postState != null) {
2827          return "|__orig__" + postState.name() + "|";
2828        }
2829        return "|" + str_name + "|";
2830      case RETURN:
2831        return "|return|";
2832      default:
2833        throw new Error("can't drop through switch statement");
2834    }
2835  }
2836
2837  /** Returns the name of this variable in its prestate (orig). */
2838  @SideEffectFree
2839  public @Interned String prestate_name() {
2840    return ("orig(" + name() + ")").intern();
2841  }
2842
2843  /**
2844   * Returns the name of the size variable that corresponds to this array variable in simplify
2845   * format. Returns null if this variable is not an array or the size name can't be constructed for
2846   * other reasons. Note that isArray seems to distinguish between actual arrays and other sequences
2847   * (such as java.util.list). Simplify uses (it seems) the same length approach for both, so we
2848   * don't check isArray().
2849   */
2850  public @Nullable String get_simplify_size_name() {
2851    if (!file_rep_type.isArray() || isDerived()) {
2852      return null;
2853    }
2854    return get_length().simplify_name().intern();
2855  }
2856
2857  /**
2858   * Returns true if this variable contains a simple variable whose name is varname. A pre-state
2859   * variable such as "orig(x)" contains "x", as does a variable derived from "x".
2860   *
2861   * @param varname the name of a simple variable
2862   * @return true if this variable contains a simple variable whose name is varname
2863   */
2864  public boolean includes_simple_name(String varname) {
2865    if (postState != null) {
2866      return postState.includes_simple_name(varname);
2867    } else if (isDerived()) {
2868      for (VarInfo base : derived.getBases()) {
2869        if (base.includes_simple_name(varname)) {
2870          return true;
2871        }
2872      }
2873    } else {
2874      for (VarInfo vi = this; vi != null; vi = vi.enclosing_var) {
2875        if ((vi.var_kind == VarKind.VARIABLE) && vi.name().equals(varname)) {
2876          return true;
2877        }
2878      }
2879    }
2880    return false;
2881  }
2882
2883  /**
2884   * Quantifies over the specified array variables in ESC format. Returns an array with 2 more
2885   * elements than the argument. Element 0 is the quantification, Element 1 is the indexed form of
2886   * variable 1, Element 2 is the indexed form of variable 3, and Element 4 is syntax such as close
2887   * parentheses.
2888   */
2889  public static String[] esc_quantify(VarInfo... vars) {
2890    return esc_quantify(true, vars);
2891  }
2892
2893  /**
2894   * Quantifies over the specified array variables in ESC format. Returns an array with 2 more
2895   * elements than the argument. Element 0 is the quantification, Element 1 is the indexed form of
2896   * variable 1, Element 2 is the indexed form of variable 3, and Element 4 is syntax such as close
2897   * parentheses.
2898   */
2899  public static String[] esc_quantify(boolean elementwise, VarInfo... vars) {
2900
2901    Quantify.ESCQuantification quant =
2902        new Quantify.ESCQuantification(Quantify.get_flags(elementwise), vars);
2903    if (vars.length == 1) {
2904      return new String[] {quant.get_quantification(), quant.get_arr_vars_indexed(0), ")"};
2905    } else if ((vars.length == 2) && vars[1].file_rep_type.isArray()) {
2906      return new String[] {
2907        quant.get_quantification(),
2908        quant.get_arr_vars_indexed(0),
2909        quant.get_arr_vars_indexed(1),
2910        ")"
2911      };
2912    } else {
2913      return new String[] {
2914        quant.get_quantification(), quant.get_arr_vars_indexed(0), vars[1].esc_name(), ")"
2915      };
2916    }
2917  }
2918
2919  /**
2920   * Returns a string array with 3 elements. The first element is the sequence, the second element
2921   * is the lower bound, and the third element is the upper bound. Returns null if this is not a
2922   * direct array or slice.
2923   */
2924  public String @Nullable [] simplifyNameAndBounds() {
2925    String[] results = new String[3];
2926    if (is_direct_non_slice_array() || (derived instanceof SequenceSubsequence)) {
2927      results[0] = get_base_array_hashcode().simplify_name();
2928      results[1] = get_lower_bound().simplify_name();
2929      results[2] = get_upper_bound().simplify_name();
2930      return results;
2931    }
2932
2933    return null;
2934  }
2935
2936  /**
2937   * Returns the upper and lower bounds of the slice in simplify format. The implementation is
2938   * somewhat different that simplifyNameAndBounds (I don't know why).
2939   */
2940  public String @Nullable [] get_simplify_slice_bounds() {
2941    String[] results;
2942    if (derived instanceof SequenceSubsequence) {
2943      results = new String[2];
2944      results[0] = get_lower_bound().simplify_name().intern();
2945      results[1] = get_upper_bound().simplify_name().intern();
2946    } else {
2947      results = null;
2948    }
2949
2950    return results;
2951  }
2952
2953  /**
2954   * Returns a string in simplify format that will select the (index_base + index_off)-th element of
2955   * the sequence specified by this variable.
2956   *
2957   * @param simplify_index_name name of the index. If free is false, this must be a number or null
2958   *     (null implies an index of 0).
2959   * @param free true of simplify_index_name is variable name
2960   * @param index_off offset from the index
2961   */
2962  public String get_simplify_selectNth(String simplify_index_name, boolean free, int index_off) {
2963
2964    // Remove the simplify bars if present from the index name
2965    if ((simplify_index_name != null)
2966        && simplify_index_name.startsWith("|")
2967        && simplify_index_name.endsWith("|"))
2968      simplify_index_name = simplify_index_name.substring(1, simplify_index_name.length() - 1);
2969
2970    // Calculate the index (including the offset if non-zero)
2971    String complete_index;
2972    if (!free) {
2973      int index = 0;
2974      if (simplify_index_name != null) {
2975        index = Integer.decode(simplify_index_name);
2976      }
2977      index += index_off;
2978      complete_index = String.format("%d", index);
2979    } else {
2980      if (index_off != 0) {
2981        complete_index = String.format("(+ |%s| %d)", simplify_index_name, index_off);
2982      } else {
2983        complete_index = String.format("|%s|", simplify_index_name);
2984      }
2985    }
2986
2987    // Return the array properly indexed
2988    return simplify_name(complete_index);
2989  }
2990
2991  /**
2992   * Returns a string in simplify format that will select the index_off element in a sequence that
2993   * has a lower bound.
2994   *
2995   * @param index_off offset from the index
2996   */
2997  public String get_simplify_selectNth_lower(int index_off) {
2998
2999    // Calculate the index (including the offset if non-zero)
3000    String complete_index;
3001    Quantify.Term lower = get_lower_bound();
3002    String lower_name = lower.simplify_name();
3003    if (!(lower instanceof Quantify.Constant)) {
3004      lower_name = String.format("|%s|", lower_name);
3005    }
3006    if (index_off != 0) {
3007      if (lower instanceof Quantify.Constant) {
3008        complete_index = String.format("%d", ((Quantify.Constant) lower).get_value() + index_off);
3009      } else {
3010        complete_index = String.format("(+ %s %d)", lower_name, index_off);
3011      }
3012    } else {
3013      complete_index = String.format("%s", lower_name);
3014    }
3015
3016    // Return the array properly indexed
3017    // System.err.printf("lower bound type = %s [%s] %s%n", lower,
3018    //                   lower.getClass(), complete_index);
3019    return simplify_name(complete_index);
3020  }
3021
3022  /** Get a fresh variable name that doesn't appear in the given variable in simplify format. */
3023  public static String get_simplify_free_index(VarInfo... vars) {
3024    // Get a free variable for each variable and return the first one
3025    QuantifyReturn[] qret = Quantify.quantify(vars);
3026    return qret[0].index.simplify_name();
3027  }
3028
3029  /** Get a 2 fresh variable names that doesn't appear in the given variable in simplify format. */
3030  public static String[] get_simplify_free_indices(VarInfo... vars) {
3031    // Get a free variable for each variable
3032    if (vars.length == 1) {
3033      vars = new VarInfo[] {vars[0], vars[0]};
3034    }
3035    QuantifyReturn qret[] = Quantify.quantify(vars);
3036    return new String[] {qret[0].index.simplify_name(), qret[1].index.simplify_name()};
3037  }
3038
3039  /**
3040   * Quantifies over the specified array variables in Simplify format. Returns a string array that
3041   * contains the quantification, indexed form of each variable, optionally the index itself, and
3042   * the closer.
3043   *
3044   * <p>If elementwise is true, include the additional constraint that the indices (there must be
3045   * exactly two in this case) refer to corresponding positions. If adjacent is true, include the
3046   * additional constraint that the second index be one more than the first. If distinct is true,
3047   * include the constraint that the two indices are different. If includeIndex is true, return
3048   * additional strings, after the roots but before the closer, with the names of the index
3049   * variables.
3050   */
3051  public static String[] simplify_quantify(EnumSet<QuantFlags> flags, VarInfo... vars) {
3052
3053    Quantify.SimplifyQuantification quant = new Quantify.SimplifyQuantification(flags, vars);
3054    boolean include_index = flags.contains(QuantFlags.INCLUDE_INDEX);
3055    if ((vars.length == 1) && include_index) {
3056      return new String[] {
3057        quant.get_quantification(),
3058        quant.get_arr_vars_indexed(0),
3059        quant.get_index(0),
3060        quant.get_closer()
3061      };
3062    } else if (vars.length == 1) {
3063      return new String[] {
3064        quant.get_quantification(), quant.get_arr_vars_indexed(0), quant.get_closer()
3065      };
3066    } else if ((vars.length == 2) && include_index) {
3067      return new String[] {
3068        quant.get_quantification(),
3069        quant.get_arr_vars_indexed(0),
3070        quant.get_arr_vars_indexed(1),
3071        quant.get_index(0),
3072        quant.get_index(1),
3073        quant.get_closer()
3074      };
3075    } else { // must be length 2 and no index
3076      return new String[] {
3077        quant.get_quantification(),
3078        quant.get_arr_vars_indexed(0),
3079        quant.get_arr_vars_indexed(1),
3080        quant.get_closer()
3081      };
3082    }
3083  }
3084
3085  /**
3086   * See {@link #simplify_quantify(EnumSet, VarInfo[])}.
3087   *
3088   * @see #simplify_quantify(EnumSet, VarInfo[])
3089   */
3090  public static String[] simplify_quantify(VarInfo... vars) {
3091    return simplify_quantify(EnumSet.noneOf(QuantFlags.class), vars);
3092  }
3093
3094  /**
3095   * Returns a rough indication of the complexity of the variable. Higher numbers indicate more
3096   * complexity.
3097   */
3098  public int complexity() {
3099    int cnt = 0;
3100    if (isDerived()) {
3101      cnt += derived.complexity();
3102      VarInfo[] bases = derived.getBases();
3103      for (VarInfo vi : bases) {
3104        cnt += vi.complexity();
3105      }
3106      // Adjust for the complexity change when a prestate is nested in
3107      // another prestate.  This is just done to match the old version
3108      if ((bases.length == 2) && bases[0].isPrestate()) {
3109        if (bases[1].isPrestate()) {
3110          cnt--;
3111        } else {
3112          cnt++;
3113        }
3114      }
3115    } else {
3116      if (isPrestate()) {
3117        cnt++;
3118      }
3119      for (VarInfo vi = this; vi != null; vi = vi.enclosing_var) {
3120        cnt++;
3121      }
3122    }
3123
3124    // int old_cnt = var_info_name.inOrderTraversal().size();
3125    // if (cnt != old_cnt)
3126    //   System.out.printf("var %s, new cnt = %d, old cnt = %d [%s]%n",
3127    //                 name(), cnt, old_cnt, var_info_name.inOrderTraversal());
3128    return cnt;
3129  }
3130
3131  /**
3132   * Returns true if this variable can be assigned to. Currently this is presumed true of all
3133   * variable except the special variable for the type of a variable and the size of a sequence. It
3134   * should include pure functions as well.
3135   */
3136  @Pure
3137  public boolean is_assignable_var() {
3138    return !(is_typeof() || is_size());
3139  }
3140
3141  /**
3142   * Returns true if this variable represents the type of a variable (eg, a.getClass().getName()).
3143   * Note that this will miss prestate variables such as 'orig(a.getClass().getName())'.
3144   */
3145  @Pure
3146  public boolean is_typeof() {
3147    // The isPrestate check doesn't seem necessary, but is required to
3148    // match old behavior.
3149    return !isPrestate() && var_flags.contains(VarFlags.CLASSNAME);
3150  }
3151
3152  /**
3153   * Returns true if this variable represents the type of a variable (eg, a.getClass().getName()).
3154   * This version finds prestate variables such as 'org(a.getClass().getName())'.
3155   */
3156  public boolean has_typeof() {
3157    if (isPrestate()) {
3158      return postState.has_typeof();
3159    }
3160    return is_typeof();
3161  }
3162
3163  /** Returns true if this variable is the 'this' variable. */
3164  @Pure
3165  public boolean is_this() {
3166    return name().equals("this");
3167    // return get_VarInfoName().equals(VarInfoName.THIS);
3168  }
3169
3170  /**
3171   * Returns true if this variable is the 'this' variable. True for both normal and prestate
3172   * versions of the variable.
3173   */
3174  @Pure
3175  public boolean isThis() {
3176    return var_info_name.isThis();
3177  }
3178
3179  /** Returns true if this is a size of an array or a prestate thereof. */
3180  @Pure
3181  public boolean is_size() {
3182    return (derived instanceof SequenceLength);
3183  }
3184
3185  /** Returns whether or not this variable is a field. */
3186  @Pure
3187  public boolean is_field() {
3188    return (var_info_name instanceof VarInfoName.Field);
3189  }
3190
3191  /** Returns true if this variable has an integer offset (eg, a+2) */
3192  @Pure
3193  public boolean is_add() {
3194    return (var_info_name instanceof VarInfoName.Add);
3195  }
3196
3197  /**
3198   * Returns the integer offset if this variable is an addition such as a+2. Throws an exception of
3199   * this variable is not an addition.
3200   *
3201   * @see #is_add()
3202   */
3203  public int get_add_amount() {
3204    return ((VarInfoName.Add) var_info_name).amount;
3205  }
3206
3207  /**
3208   * Returns true if this variable is an actual array as opposed to an array that is created over
3209   * fields/methods of an array. For example, 'a[]' is a direct array, but 'a[].b' is not.
3210   */
3211  @Pure
3212  public boolean is_direct_array() {
3213    // Must be an array to be a direct array
3214    if (!rep_type.isArray()) {
3215      return false;
3216    }
3217
3218    // If $Field or $Type appears before $Elements, false.
3219    // System.out.printf("%s flatten %s%n", name(), name);
3220    for (VarInfoName node : new VarInfoName.InorderFlattener(var_info_name).nodes()) {
3221      if (node instanceof VarInfoName.Field) {
3222        return false;
3223      }
3224      if (node instanceof VarInfoName.TypeOf) {
3225        return false;
3226      }
3227      if (node instanceof VarInfoName.Elements) {
3228        break;
3229      }
3230    }
3231
3232    return true;
3233  }
3234
3235  /**
3236   * Returns true if this variable is an actual array as opposed to an array that is created over
3237   * fields/methods of an array or a slice. For example, 'a[]' is a direct array, but 'a[].b' and
3238   * 'a[i..]' are not.
3239   */
3240  @Pure
3241  public boolean is_direct_non_slice_array() {
3242    return (var_info_name instanceof VarInfoName.Elements);
3243  }
3244
3245  /**
3246   * Returns true if two variables have the same enclosing variable. If either variable is not a
3247   * field, returns false.
3248   */
3249  public boolean has_same_parent(VarInfo other) {
3250    if (!is_field() || !other.is_field()) {
3251      return false;
3252    }
3253
3254    VarInfoName.Field name1 = (VarInfoName.Field) var_info_name;
3255    VarInfoName.Field name2 = (VarInfoName.Field) other.var_info_name;
3256
3257    return name1.term.equals(name2.term);
3258  }
3259
3260  /**
3261   * Returns the variable that encloses this one. For example if this variable is 'x.a.b', the
3262   * enclosing variable is 'x.a'.
3263   */
3264  public @Nullable VarInfo get_enclosing_var() {
3265    return enclosing_var;
3266  }
3267
3268  /**
3269   * Creates a VarInfo that is a subsequence that begins at begin and ends at end with the specified
3270   * shifts. The begin or the end can be null, but a non-zero shift is only allowed with non-null
3271   * variables.
3272   */
3273  public static VarInfo make_subsequence(
3274      VarInfo seq, @Nullable VarInfo begin, int begin_shift, @Nullable VarInfo end, int end_shift) {
3275
3276    String begin_str = inside_name(begin, seq.isPrestate(), begin_shift);
3277    if (begin_str.equals("")) { // interned if the null string, not interned otherwise
3278      begin_str = "0";
3279    }
3280    String end_str = inside_name(end, seq.isPrestate(), end_shift);
3281
3282    VarInfoName begin_name;
3283    String parent_format = "%s..";
3284    if (begin == null) {
3285      begin_name = null;
3286    } else {
3287      begin_name = begin.var_info_name;
3288      if (begin_shift == -1) {
3289        begin_name = begin_name.applyDecrement();
3290        parent_format = "%s-1..";
3291      } else if (begin_shift == 1) {
3292        begin_name = begin_name.applyIncrement();
3293        parent_format = "%s+1..";
3294      } else {
3295        assert begin_shift == 0;
3296      }
3297    }
3298
3299    VarInfoName end_name;
3300    if (end == null) {
3301      end_name = null;
3302      parent_format += "%s";
3303    } else {
3304      end_name = end.var_info_name;
3305      if (end_shift == -1) {
3306        end_name = end_name.applyDecrement();
3307        parent_format += "%s-1";
3308      } else if (end_shift == 1) {
3309        end_name = end_name.applyIncrement();
3310        parent_format += "%s+1";
3311      } else {
3312        assert end_shift == 0;
3313        parent_format += "%s";
3314      }
3315    }
3316
3317    VarInfoName new_name = seq.var_info_name.applySlice(begin_name, end_name);
3318
3319    VarInfo vi = new VarInfo(new_name, seq.type, seq.file_rep_type, seq.comparability, seq.aux);
3320    vi.setup_derived_base(seq, begin, end);
3321    vi.str_name =
3322        seq.apply_subscript(String.format("%s..%s", begin_str, end_str))
3323            .intern(); // interning bugfix
3324
3325    // If there is a parent ppt (set in setup_derived_base), set the
3326    // parent variable accordingly.  If all of the original variables used
3327    // the default name, this can as well.  Otherwise, build the parent
3328    // name.
3329    for (VarParent parent : vi.parents) {
3330      int rid = parent.parent_relation_id;
3331
3332      if ((seq.get_parent(rid) == null)
3333          && ((begin == null) || !begin.has_parent(rid) || (begin.parent_var(rid) == null))
3334          && ((end == null) || !end.has_parent(rid) || (end.parent_var(rid) == null))) {
3335
3336        parent.parent_variable = null;
3337      } else {
3338        String begin_pname =
3339            (begin == null || !begin.has_parent(rid)) ? "0" : begin.parent_var_name(rid);
3340        String end_pname = (end == null || !end.has_parent(rid)) ? "" : end.parent_var_name(rid);
3341        @SuppressWarnings(
3342            "formatter") // format string is constructed above using make_subsequence's arguments
3343        String res =
3344            apply_subscript(
3345                seq.parent_var_name(rid), String.format(parent_format, begin_pname, end_pname));
3346        parent.parent_variable = res;
3347        // System.out.printf("-- set parent var from '%s' '%s' '%s' '%s'%n",
3348        //       seq.parent_var_name(), parent_format, begin_pname, end_pname);
3349      }
3350      // System.out.printf("Parent for %s:%s is %s:%s%n",
3351      //                ((seq.ppt != null)? seq.ppt.name() : "none"), vi.name(),
3352      //                  vi.parent_ppt, vi.parent_variable);
3353    }
3354
3355    return vi;
3356  }
3357
3358  /**
3359   * Returns the name to use for vi inside of an array reference. If the array reference is orig,
3360   * then orig is implied. This removes orig from orig variables and adds post to post variables.
3361   */
3362  private static String inside_name(@Nullable VarInfo vi, boolean in_orig, int shift) {
3363    if (vi == null) {
3364      return "";
3365    }
3366
3367    String shift_str = "";
3368    if (shift != 0) {
3369      shift_str = String.format("%+d", shift);
3370    }
3371
3372    if (in_orig) {
3373      if (vi.isPrestate()) {
3374        return vi.postState.name() + shift_str;
3375      } else {
3376        return String.format("post(%s)%s", vi.name(), shift_str);
3377      }
3378    } else {
3379      return vi.name() + shift_str;
3380    }
3381  }
3382
3383  /**
3384   * Creates a VarInfo that is an index into a sequence. The type, file_rep_type, etc are taken from
3385   * the element type of the sequence.
3386   */
3387  public static VarInfo make_subscript(VarInfo seq, @Nullable VarInfo index, int index_shift) {
3388
3389    String index_str = inside_name(index, seq.isPrestate(), index_shift);
3390
3391    VarInfoName index_name;
3392    if (index == null) {
3393      index_name = VarInfoName.parse(String.valueOf(index_shift));
3394    } else {
3395      index_name = index.var_info_name;
3396      if (index_shift == -1) {
3397        index_name = index_name.applyDecrement();
3398      } else {
3399        assert index_shift == 0 : "bad shift " + index_shift + " for " + index;
3400      }
3401    }
3402
3403    VarInfoName new_name = seq.var_info_name.applySubscript(index_name);
3404    VarInfo vi =
3405        new VarInfo(
3406            new_name,
3407            seq.type.elementType(),
3408            seq.file_rep_type.elementType(),
3409            seq.comparability.elementType(),
3410            VarInfoAux.getDefault());
3411    vi.setup_derived_base(seq, index);
3412    vi.var_kind = VarInfo.VarKind.FIELD;
3413    vi.str_name = seq.apply_subscript(index_str).intern(); // interning bugfix
3414    for (VarParent parent : vi.parents) {
3415      int rid = parent.parent_relation_id;
3416
3417      if ((seq.parent_var(rid) == null)
3418          && ((index == null) || !index.has_parent(rid) || (index.parent_var(rid) == null))) {
3419        parent.parent_variable = null;
3420      } else { // one of the two bases has a different parent variable name
3421        String subscript_parent = String.valueOf(index_shift);
3422        if (index != null && index.has_parent(rid)) {
3423          subscript_parent = index.parent_var_name(rid);
3424
3425          if (seq.isPrestate() && !index.isPrestate()) {
3426            // Wrap the index in POST if the sequence is original
3427            subscript_parent = VarInfoName.parse(subscript_parent).applyPoststate().name_impl();
3428          } else if (seq.isPrestate() && index.isPrestate()) {
3429            // Remove redundant ORIG
3430            subscript_parent = ((Prestate) VarInfoName.parse(subscript_parent)).term.name_impl();
3431          }
3432
3433          if (index_shift == -1) {
3434            subscript_parent = subscript_parent + "-1";
3435          }
3436        }
3437        parent.parent_variable = apply_subscript(seq.parent_var_name(rid), subscript_parent);
3438      }
3439    }
3440    return vi;
3441  }
3442
3443  /**
3444   * Create a VarInfo that is a function over one or more other variables. The type, rep_type, etc.
3445   * of the new function are taken from the first variable.
3446   */
3447  public static VarInfo make_function(String function_name, VarInfo... vars) {
3448
3449    VarInfoName[] vin = new VarInfoName[vars.length];
3450    for (int ii = 0; ii < vars.length; ii++) {
3451      vin[ii] = vars[ii].var_info_name;
3452    }
3453
3454    VarInfo vi =
3455        new VarInfo(
3456            VarInfoName.applyFunctionOfN(function_name, vin),
3457            vars[0].type,
3458            vars[0].file_rep_type,
3459            vars[0].comparability,
3460            vars[0].aux);
3461    vi.setup_derived_function(function_name, vars);
3462    return vi;
3463  }
3464
3465  /**
3466   * Creates the derived variable func(seq) from seq.
3467   *
3468   * @param func_name name of the function
3469   * @param type return type of the function. If null, the return type is the element type of the
3470   *     sequence.
3471   * @param seq sequence variable
3472   * @param shift value to add or subtract from the function. Legal values are -1, 0, and 1.
3473   */
3474  public static VarInfo make_scalar_seq_func(
3475      String func_name, @Nullable ProglangType type, VarInfo seq, int shift) {
3476
3477    VarInfoName viname = seq.var_info_name.applyFunction(func_name);
3478    if (func_name.equals("size")) {
3479      viname = seq.var_info_name.applySize();
3480    }
3481    String shift_name = "";
3482    if (shift == -1) {
3483      viname = viname.applyDecrement();
3484      shift_name = "_minus1";
3485    } else if (shift == 1) {
3486      viname = viname.applyIncrement();
3487      shift_name = "_plus1";
3488    } else {
3489      assert shift == 0;
3490    }
3491
3492    @NonNull ProglangType ptype = type;
3493    @NonNull ProglangType frtype = type;
3494    VarComparability comp = seq.comparability.indexType(0);
3495    VarInfoAux aux = VarInfoAux.getDefault();
3496    if (type == null) {
3497      ptype = seq.type.elementType();
3498      frtype = seq.file_rep_type.elementType();
3499      comp = seq.comparability.elementType();
3500      aux = seq.aux;
3501    }
3502    VarInfo vi = new VarInfo(viname, ptype, frtype, comp, aux);
3503    vi.setup_derived_base(seq);
3504    vi.var_kind = VarInfo.VarKind.FUNCTION;
3505    vi.enclosing_var = seq;
3506    vi.arr_dims = 0;
3507    // null is initial value:  vi.function_args = null;
3508    vi.relative_name = func_name + shift_name;
3509
3510    // Calculate the string to add for the shift.
3511    String shift_str = "";
3512    if (shift != 0) {
3513      shift_str = String.format("%+d", shift);
3514    }
3515
3516    // Determine whether orig should be swapped with the function.
3517    // The original VarInfoName code did this only for the size
3518    // function (though it makes the same sense for all functions over
3519    // sequences).
3520    boolean swap_orig =
3521        func_name.equals("size") && seq.isPrestate() && !VarInfoName.dkconfig_direct_orig;
3522
3523    // Force orig to the outside if specified.
3524    if (swap_orig) {
3525      vi.str_name =
3526          String.format("orig(%s(%s))%s", func_name, seq.postState.name(), shift_str)
3527              .intern(); // interning bugfix
3528    } else {
3529      vi.str_name =
3530          String.format("%s(%s)%s", func_name, seq.name(), shift_str).intern(); // interning bugfix
3531    }
3532
3533    for (VarParent parent : vi.parents) {
3534      int rid = parent.parent_relation_id;
3535      if (!seq.has_parent(rid) || seq.parent_var(rid) == null) {
3536        parent.parent_variable = null;
3537      } else {
3538        if (func_name.equals("size")) {
3539          // Special handling for the case where the parent var name is orig(array[...]).
3540          // With swapping, the parent should be orig(size(array[..])), however it's stored
3541          // as a string so the swap can't be done textually.
3542          VarInfoName parentName = VarInfoName.parse(seq.parent_var_name(rid));
3543
3544          // Can't use the more general applyFunction method here because it doesn't take into
3545          // account prestate values as the applySize method explicitly does
3546          parentName = parentName.applySize();
3547
3548          parent.parent_variable = String.format("%s%s", parentName.name(), shift_str);
3549        } else {
3550          assert !swap_orig : "swap orig with parent " + vi;
3551          parent.parent_variable =
3552              String.format("%s(%s)%s", func_name, seq.parent_var_name(rid), shift_str);
3553        }
3554      }
3555    }
3556    return vi;
3557  }
3558
3559  /**
3560   * Creates the derived variable func(str) from string.
3561   *
3562   * @param func_name name of the function
3563   * @param type return type of the function
3564   * @param str sequence variable
3565   */
3566  public static VarInfo make_scalar_str_func(String func_name, ProglangType type, VarInfo str) {
3567
3568    VarInfoName viname = str.var_info_name.applyFunction(func_name);
3569
3570    ProglangType ptype = type;
3571    ProglangType frtype = type;
3572    VarComparability comp = str.comparability.string_length_type();
3573    VarInfoAux aux = VarInfoAux.getDefault();
3574    VarInfo vi = new VarInfo(viname, ptype, frtype, comp, aux);
3575    vi.setup_derived_base(str);
3576    vi.var_kind = VarInfo.VarKind.FUNCTION;
3577    vi.enclosing_var = str;
3578    vi.arr_dims = 0;
3579    // null is initial value:  vi.function_args = null;
3580    vi.relative_name = func_name;
3581
3582    vi.str_name = String.format("%s.%s()", str.name(), func_name).intern(); // interning bugfix
3583
3584    for (VarParent parent : vi.parents) {
3585      int rid = parent.parent_relation_id;
3586      if (str.get_parent(rid).parent_variable == null) {
3587        parent.parent_variable = null;
3588      } else {
3589        parent.parent_variable =
3590            String.format("%s.%s()", str.get_parent(rid).parent_variable, func_name);
3591      }
3592    }
3593    return vi;
3594  }
3595
3596  /**
3597   * Returns true if vi is the prestate version of this. If this is a derived variable, vi must be
3598   * the same derivation using prestate versions of each base variable.
3599   */
3600  @Pure
3601  public boolean is_prestate_version(VarInfo vi) {
3602
3603    // If both variables are not derived
3604    if ((derived == null) && (vi.derived == null)) {
3605
3606      // true if vi is the prestate version of this
3607      return !isPrestate() && vi.isPrestate() && name().equals(vi.postState.name());
3608
3609      // else if both variables are derived
3610    } else if ((derived != null) && (vi.derived != null)) {
3611
3612      return derived.is_prestate_version(vi.derived);
3613
3614      // one is derived and the other isn't
3615    } else {
3616      return false;
3617    }
3618  }
3619
3620  /** Returns true if this is an array or a slice. */
3621  @Pure
3622  public boolean isArray() {
3623    return type.isArray();
3624  }
3625
3626  /** Returns true if this is a slice. */
3627  @Pure
3628  public boolean isSlice() {
3629    return isArray() && isDerived();
3630  }
3631
3632  /** Converts a variable name or expression to the old style of names. */
3633  public static String old_var_names(String name) {
3634    if (PrintInvariants.dkconfig_old_array_names) {
3635      return name.replace("[..]", "[]");
3636    } else {
3637      return name;
3638    }
3639  }
3640
3641  /** Returns the old style variable name for this name. */
3642  public String old_var_name() {
3643    return old_var_names(name());
3644  }
3645
3646  /** Rough check to ensure that the variable name and derivation match up. */
3647  public void var_check() {
3648
3649    if (false) {
3650      if (derived instanceof SequenceSubsequence) {
3651        if (name().contains("-1")) {
3652          SequenceSubsequence ss = (SequenceSubsequence) derived;
3653          // System.out.printf("checking %s [%s] with derived %s[%s]%n",
3654          //                   this, System.identityHashCode(this), derived,
3655          //                   System.identityHashCode(derived));
3656          assert ss.index_shift == -1
3657              : "bad var "
3658                  + this
3659                  + " derived "
3660                  + derived
3661                  + " shift "
3662                  + ss.index_shift
3663                  + " in ppt "
3664                  + ppt.name();
3665        }
3666      }
3667    }
3668  }
3669}