Example #1
0
  /**
   * Check that each non static final field has been initialized exactly once, taking into account
   * the fact that constructors may call other constructors.
   *
   * @param cb The ClassBody of the class declaring the fields to check.
   * @throws SemanticException
   */
  protected void checkNonStaticFinalFieldsInit(ClassBody cb) throws SemanticException {
    // for each non-static final field instance, check that all
    // constructors intialize it exactly once, taking into account constructor calls.
    for (Iterator iter = currCBI.currClassFinalFieldInitCounts.keySet().iterator();
        iter.hasNext(); ) {
      FieldInstance fi = (FieldInstance) iter.next();
      if (fi.flags().isFinal() && !fi.flags().isStatic()) {
        // the field is final and not static
        // it must be initialized exactly once.
        // navigate up through all of the the constructors
        // that this constructor calls.

        boolean fieldInitializedBeforeConstructors = false;
        MinMaxInitCount ic = (MinMaxInitCount) currCBI.currClassFinalFieldInitCounts.get(fi);
        if (ic != null && !InitCount.ZERO.equals(ic.getMin())) {
          fieldInitializedBeforeConstructors = true;
        }

        for (Iterator iter2 = currCBI.allConstructors.iterator(); iter2.hasNext(); ) {
          ConstructorDecl cd = (ConstructorDecl) iter2.next();
          ConstructorInstance ciStart = cd.constructorInstance();
          ConstructorInstance ci = ciStart;

          boolean isInitialized = fieldInitializedBeforeConstructors;

          while (ci != null) {
            Set s = (Set) currCBI.fieldsConstructorInitializes.get(ci);
            if (s != null && s.contains(fi)) {
              if (isInitialized) {
                throw new SemanticException(
                    "field \"" + fi.name() + "\" might have already been initialized",
                    cd.position());
              }
              isInitialized = true;
            }
            ci = (ConstructorInstance) currCBI.constructorCalls.get(ci);
          }
          if (!isInitialized) {
            throw new SemanticException(
                "field \"" + fi.name() + "\" might not have been initialized", ciStart.position());
          }
        }
      }
    }
  }