UnreachableCodeWorker.java

/*
** Module   : UnreachableCodeWorker.java
** Abstract : Helper routines for unreachable code processing rule-sets.
**
** Copyright (c) 2005-2022, Golden Code Development Corporation.
**
** -#- -I- --Date-- --JPRM-- ----------------Description-----------------
** 001 SIY 20050706   @21709 Created initial version.
** 002 SIY 20060312   @24992 Added support for NOT and parentheses in
**                           expression evaluator.
** 003 GES 20090518   @42382 Import change.
** 004 TJD 20220504          Java 11 compatibility minor changes
*/
/*
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU Affero General Public License for more details.
**
** You may find a copy of the GNU Affero GPL version 3 at the following
** location: https://www.gnu.org/licenses/agpl-3.0.en.html
** 
** Additional terms under GNU Affero GPL version 3 section 7:
** 
**   Under Section 7 of the GNU Affero GPL version 3, the following additional
**   terms apply to the works covered under the License.  These additional terms
**   are non-permissive additional terms allowed under Section 7 of the GNU
**   Affero GPL version 3 and may not be removed by you.
** 
**   0. Attribution Requirement.
** 
**     You must preserve all legal notices or author attributions in the covered
**     work or Appropriate Legal Notices displayed by works containing the covered
**     work.  You may not remove from the covered work any author or developer
**     credit already included within the covered work.
** 
**   1. No License To Use Trademarks.
** 
**     This license does not grant any license or rights to use the trademarks
**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
**     of Golden Code Development Corporation. You are not authorized to use the
**     name Golden Code, FWD, or the names of any author or contributor, for
**     publicity purposes without written authorization.
** 
**   2. No Misrepresentation of Affiliation.
** 
**     You may not represent yourself as Golden Code Development Corporation or FWD.
** 
**     You may not represent yourself for publicity purposes as associated with
**     Golden Code Development Corporation, FWD, or any author or contributor to
**     the covered work, without written authorization.
** 
**   3. No Misrepresentation of Source or Origin.
** 
**     You may not represent the covered work as solely your work.  All modified
**     versions of the covered work must be marked in a reasonable way to make it
**     clear that the modified work is not originating from Golden Code Development
**     Corporation or FWD.  All modified versions must contain the notices of
**     attribution required in this license.
*/

package com.goldencode.p2j.convert;

import java.util.*;
                                   
import com.goldencode.ast.*;
import com.goldencode.p2j.pattern.*;
import com.goldencode.p2j.uast.*;
import com.goldencode.p2j.util.*;

/**
 * Helper routines for the unreachable code processing rules.  This provides
 * support for constant resolution and for simple expression evaluation
 * to statically determine if a particular conditional execution path can 
 * be proven to be unreachable.
 */
public final class UnreachableCodeWorker
extends AbstractPatternWorker
{
   /** Expression evaluates to <code>false</code>. */
   private static final long RES_FALSE = 2;

   /** Expression evaluates to <code>true</code>. */
   private static final long RES_TRUE = 1;
   
   /** Expression cannot be evaluated statically. */
   private static final long RES_UNKNOWN = 0;
   
   /**
    * Default constructor which initializes libraries.
    */
   public UnreachableCodeWorker()
   {
      super();
      setLibrary(new Helper());
   }
   
   /**
    * Resolve constant name into its value.
    * 
    * @param   constant
    *          Name of the constant.
    * 
    * @return  Value for the known constant name or <code>null</code> if
    *          the name is unknown.
    */
   public Object resolveConstant(String constant)
   {
      if("RES_FALSE".equalsIgnoreCase(constant))
         return Long.valueOf(RES_FALSE);
      
      if("RES_TRUE".equalsIgnoreCase(constant))
         return Long.valueOf(RES_TRUE);
      
      if("RES_UNKNOWN".equalsIgnoreCase(constant))
         return Long.valueOf(RES_UNKNOWN);
      
      return null;
   }
   
   /**
    * Provides user-level APIs necessary for unreachable code processing.
    */
   public class Helper
   {
      /** Information about known variables */
      HashMap varPool = new HashMap();
      
      /**
       * Add a variable to the pool of known variables. A variable consists
       * of a name and a list of values.  If the variable is already known
       * in the pool, then a new value is added to the array of known values.
       * <p>
       * At this time, all variables must be of type VAR_CHAR and the values
       * must be the Java version of the Progress STRING.
       * 
       * @param   variable
       *          Variable name. Must not be <code>null</code>.
       * @param   value
       *          New variable value. Must not be <code>null</code>.
       * 
       * @return  <code>true</code> if operation was successful.
       */
      public boolean addKnownVarValue(String variable, String value)
      {
         if (variable == null || value == null)
            return false;
         
         variable = variable.toLowerCase();
         
         List data = (List)varPool.get(variable);
         
         if (data == null)
            data = new LinkedList();
            
         data.add(value);
         
         varPool.put(variable, data);
         
         return true;
      }

      /**
       * Try to evaluate the expression defined by the passed AST node. If
       * this can be done then return result of evaluation.
       * <p>
       * At present only the following expressions are recognized:
       * <p>
       * <ol>
       *    <li>TRUE</li>
       *    <li>FALSE</li>
       *    <li>VAR_CHAR = STRING</li>
       *    <li>STRING = VAR_CHAR</li>
       *    <li>VAR_CHAR &lt;&gt; STRING</li>
       *    <li>STRING &lt;&gt; VAR_CHAR</li>
       * </ol>
       * 
       * @param   node
       *          Expression root node.
       * 
       * @return  <code>RES_UNKNOWN</code> if the expression cannot be
       *          evaluated, <code>RES_TRUE</code> if the result is
       *          <code>true</code> and <code>RES_FALSE</code> if the result
       *          is <code>false</code>.
       */
      public long tryEval(Aast node)
      {
         if (node == null ||
             node.getType() != ProgressParserTokenTypes.EXPRESSION ||
             node.getFirstChild() == null)
         {
            return RES_UNKNOWN;   // Result is unknown
         }

         return tryEvalNode((AnnotatedAst) node.getFirstChild());
      }

      /**
       * Try to evaluate CASE-WHEN-THEN statement expression which compares
       * a <code>VAR_CHAR</code> to a <code>STRING</code>.
       * 
       * @param   var
       *          CASE statement variable name of type <code>VAR_CHAR</code>.
       * 
       * @param   value
       *          THEN statement value of type <code>STRING</code>. 
       * 
       * @return  <code>true</code> if variable contains specified value.
       */
      public boolean tryEvalCase(String var, String value)
      {
         List list = getKnownValues(var);
         
         if (list == null)
            return false;

         value = character.progressToJavaString(value);
         
         if (list.indexOf(value) >= 0)
            return true;
         
         return false;
      }
      
      /**
       * Get list of known values of the variable for the expression
       * evaluator.
       * 
       * @param   var
       *          Variable name (will be automatically translated to lower
       *          case).
       * 
       * @return  Array with the variable values or <code>null</code> if no
       *          such variable defined.
       */
      private List getKnownValues(String var)
      {
         if (varPool == null)
            return null;
         
         return (List)varPool.get(var.toLowerCase());
      }
      
      /**
       * Expression evaluation worker.
       * 
       * @param   node
       *          Expression root node.
       * 
       * @return  <code>RES_UNKNOWN</code> if the expression cannot be
       *          evaluated, <code>RES_TRUE</code> if the result is
       *          <code>true</code> and <code>RES_FALSE</code> if the result
       *          is <code>false</code>.
       */
      private long tryEvalNode(AnnotatedAst node)
      {
         if (node == null || 
             node.getNumberOfChildren() > 1)
         {
            return RES_UNKNOWN;
         }

         AnnotatedAst child = (AnnotatedAst) node.getFirstChild();
         
         int type = node.getType();
         
         if (child != null)
         {
            if (type == ProgressParserTokenTypes.LPARENS)
               return tryEvalNode(child);
            
            if (type == ProgressParserTokenTypes.KW_NOT)
            {
               long res = tryEvalNode(child);
               
               if (res == RES_FALSE)
                  return RES_TRUE;
               
               if (res == RES_TRUE)
                  return RES_FALSE;
               
               return res;
            }
            
            return RES_UNKNOWN;
         }
         
         if (type == ProgressParserTokenTypes.BOOL_TRUE)
            return RES_TRUE;

         if (type == ProgressParserTokenTypes.BOOL_FALSE)
            return RES_FALSE;

         if (type == ProgressParserTokenTypes.EQUALS || 
             type == ProgressParserTokenTypes.NOT_EQ)
         {
            boolean isEq = (type == ProgressParserTokenTypes.EQUALS);
            AnnotatedAst tmp = (AnnotatedAst) node.getFirstChild();
            
            if (tmp == null)
               return RES_UNKNOWN;
            
            String var  = null;
            String data = null;

            while (tmp != null)
            {
               int ttype = tmp.getType();
               
               if (ttype ==  ProgressParserTokenTypes.VAR_CHAR)
                  var = tmp.getText();
               
               if (ttype == ProgressParserTokenTypes.STRING)
                  data = character.progressToJavaString(tmp.getText());
               
               tmp = (AnnotatedAst) tmp.getNextSibling();
            }
            
            if (var == null || data == null)
               return RES_UNKNOWN;

            List list = getKnownValues(var);

            if (list == null)
               return RES_UNKNOWN;
            
            if (list.indexOf(data) >= 0)
               return isEq ? RES_TRUE : RES_FALSE;
            
            return isEq ? RES_FALSE : RES_TRUE;
         }
         
         return RES_UNKNOWN;   // Result is unknown
      }
   }
}