Property.java

/*
** Module   : Property.java
** Abstract : Implementation of the Progress.Reflect.Property builtin class.
**
** Copyright (c) 2020-2025, Golden Code Development Corporation.
**
** -#- -I- --Date-- --------------------------------------Description---------------------------------------
** 001 ME  20200422 First version.
** 002 CA  20210221 Fixed 'qualified', 'extent' and 'returns' annotations at the legacy
**                  signature.
** 003 ME  20230905 Removed 4gl ctor.
** 004 CA  20231130 Do not use 'TypeFactory.object' in cases where the skeleton class is not instantiated via
**                  ObjectOps (like the reflection classes), as this will force pending ObjectOps scopeable 
**                  registration, which never gets executed, as the legacy constructors are not used.
** 005 ES  20250521 Added runtime support for Progress.Reflect.Property.
*/

/*
** 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.oo.reflect;

import com.goldencode.p2j.oo.lang.*;
import com.goldencode.p2j.util.*;

import static com.goldencode.p2j.report.ReportConstants.*;
import static com.goldencode.p2j.util.InternalEntry.Type;

import java.lang.reflect.*;

/**
 * Implementation of the Progress.Reflect.Property builtin class.
 */
@LegacyResource(resource = "Progress.Reflect.Property")
@LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_PARTIAL)
public class Property
extends Variable
{
   private object<? extends AccessMode> getterAccessMode = new object<>(AccessMode.class);

   private logical canRead = TypeFactory.logical();

   private logical canWrite = TypeFactory.logical();

   private logical isAbstract = TypeFactory.logical();

   private logical isIndexed = TypeFactory.logical();

   private logical isOverride = TypeFactory.logical();

   private object<? extends AccessMode> setterAccessMode = new object<>(AccessMode.class);
   
   private InternalEntry getter = null;
   
   private InternalEntry setter = null;
   
   /**
    * Create a new legacy class object.
    * 
    * @param    cls
    *           The originating legacy class.
    * @param    field
    *           The field (reflection).
    * @param    getter
    *           The method (reflection).
    * @param    setter
    *           The method (reflection).
    * 
    */
   public Property (LegacyClass cls, Field field, Method getter, Method setter)
   {
      super(cls, getter, setter);
      
      this.canRead.assign(getter != null);
      this.canWrite.assign(setter != null);
      this.isAbstract.assign(field == null);
      
      object<? extends LegacyClass> superClass = getOriginatingClass().ref().getSuperClass();
      object<? extends Property> parentProperty = !superClass.isUnknown() ? superClass.ref().getProperty(getName()) : 
                                                                            new object<>();
      
      this.isOverride.assign(!parentProperty.isUnknown());
      
      this.getterAccessMode.assign(getter != null ? AccessMode.getEnum(getter.getModifiers()) : new object<>(AccessMode.class));
      this.setterAccessMode.assign(setter != null ? AccessMode.getEnum(setter.getModifiers()) : new object<>(AccessMode.class));
      this.getter = SourceNameMapper.buildInternalEntry(_getSignature(getter,  InternalEntry.Type.GETTER), getter);
      this.setter = SourceNameMapper.buildInternalEntry(_getSignature(setter,  InternalEntry.Type.SETTER), setter);
   }
   
   @LegacySignature(returns = "OBJECT", qualified = "Progress.Reflect.AccessMode", type = Type.GETTER, name = "GetterAccessMode")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public object<? extends AccessMode> getGetterAccessMode()
   {
      return getterAccessMode.duplicate();
   }

   @LegacySignature(returns = "LOGICAL", type = Type.GETTER, name = "CanRead")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public logical getCanRead()
   {
      return canRead.duplicate();
   }

   @LegacySignature(returns = "LOGICAL", type = Type.GETTER, name = "CanWrite")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public logical getCanWrite()
   {
      return canWrite.duplicate();
   }

   @LegacySignature(returns = "LOGICAL", type = Type.GETTER, name = "IsAbstract")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public logical getIsAbstract()
   {
      return isAbstract.duplicate();
   }

   @LegacySignature(returns = "LOGICAL", type = Type.GETTER, name = "IsIndexed")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public logical getIsIndexed()
   {
      return isIndexed.duplicate();
   }

   @LegacySignature(returns = "LOGICAL", type = Type.GETTER, name = "IsOverride")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public logical getIsOverride()
   {
      return isOverride.duplicate();
   }

   @LegacySignature(returns = "OBJECT", qualified = "Progress.Reflect.AccessMode", type = Type.GETTER, name = "SetterAccessMode")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public object<? extends AccessMode> getSetterAccessMode()
   {
      return setterAccessMode.duplicate();
   }
   
   @Override
   @LegacySignature(type = Type.METHOD, name = "Get", returns = "BDT", parameters = 
   {
      @LegacyParameter(name = "instance", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT")
   })
   public BaseDataType get()
   {      
      if (getter == null)
      {
         String msg = String.format("Cannot access %s because it is a property that is write-only.", getName().getValue());
         
         ErrorManager.recordOrThrowError(13823, msg, false);
         return BaseDataType.generateUnknown(getClass());
      }
      
      Class<? extends _BaseObject_> cls = getDeclaringClass().ref().getJavaClass();
      Object referent = ObjectOps.getStaticInstance(cls);
      
      Class<?> retType = getter.getMethod().getReturnType();
      
      object<? extends ParameterList> _params = ObjectOps.newInstance(com.goldencode.p2j.oo.lang.ParameterList.class, "I", 0);
      ParameterList params = _params.ref();   
      
      BaseDataType[] retVal = new BaseDataType[1];
      Runnable task = () -> retVal[0] = (BaseDataType) ControlFlowOps.invokeLegacyMethod(getter, 
                  retType == void.class || retType == Void.class, 
                  referent, getDeclaringClass().getTypeName(), getName().getValue(), params.getModes(), params.getArgs());
         
      LegacyClass.invokeImpl(params, task);
         
      return retVal[0];
   }
   
   @Override
   @LegacySignature(type = Type.METHOD, name = "Get", returns = "BDT", parameters = 
   {
      @LegacyParameter(name = "instance", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT")
   })
   public BaseDataType get(final object<? extends _BaseObject_> _instance)
   {      
      if (getter == null)
      {
         String msg = String.format("Cannot access %s because it is a property that is write-only.", getName().getValue());
         
         ErrorManager.recordOrThrowError(13823, msg, false);
         return BaseDataType.generateUnknown(getClass());
      }
      
      Class<?> retType = getter.getMethod().getReturnType();
      
      object<? extends ParameterList> _params = ObjectOps.newInstance(com.goldencode.p2j.oo.lang.ParameterList.class, "I", 0);
      ParameterList params = _params.ref();   
      
      BaseDataType[] retVal = new BaseDataType[1];
      Runnable task = () -> retVal[0] = (BaseDataType) ControlFlowOps.invokeLegacyMethod(getter, 
                  retType == void.class || retType == Void.class, 
                  _instance.ref(), getOriginatingClass().getTypeName(), getName().getValue(), params.getModes(), params.getArgs());
         
      LegacyClass.invokeImpl(params, task);
         
      return retVal[0];
   }
   
   @LegacySignature(type = Type.METHOD, name = "Set", parameters = 
   {
      @LegacyParameter(name = "value", type = "BDT", mode = "INPUT")
   })
   public void set(final Object _value)
   {
      if (setter == null)
      {
         String msg = String.format("Cannot update %s because it is a property that is read-only.", getName().getValue());
         
         ErrorManager.recordOrThrowError(13824, msg, false);
         return;
      }
      
      Class<? extends _BaseObject_> cls = getDeclaringClass().ref().getJavaClass();
      Object referent = ObjectOps.getStaticInstance(cls);
      
      object<? extends ParameterList> _params = ObjectOps.newInstance(com.goldencode.p2j.oo.lang.ParameterList.class, "I", 1);
      _params.ref().setParameter(new integer(1),
                                 new character(((BaseDataType) _value).getTypeName()),
                                 new character("INPUT"),
                                 BaseDataType.variable((BaseDataType) _value));
      ParameterList params = _params.ref();
      
      Runnable task = () -> ControlFlowOps.invokeLegacyMethod(setter, 
                                                              true, 
                                                              referent, 
                                                              getDeclaringClass().getTypeName(), 
                                                              getName().getValue(), 
                                                              params.getModes(), 
                                                              params.getArgs());
         
      LegacyClass.invokeImpl(params, task);
   }
   
   @LegacySignature(type = Type.METHOD, name = "Set", parameters = 
   {
      @LegacyParameter(name = "instance", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT"),
      @LegacyParameter(name = "value", type = "BDT", mode = "INPUT")
   })
   public void set(final object<? extends com.goldencode.p2j.oo.lang._BaseObject_> _instance, final Object _value)
   {  
      if (setter == null)
      {
         String msg = String.format("Cannot update %s because it is a property that is read-only.", getName().getValue());
         
         ErrorManager.recordOrThrowError(13824, msg, false);
         return;
      }
      
      object<? extends ParameterList> _params = ObjectOps.newInstance(com.goldencode.p2j.oo.lang.ParameterList.class, "I", 1);
      _params.ref().setParameter(new integer(1),
                                 new character(((BaseDataType) _value).getTypeName()),
                                 new character("INPUT"),
                                 BaseDataType.variable((BaseDataType) _value));
      ParameterList params = _params.ref();
      
      Runnable task = () -> ControlFlowOps.invokeLegacyMethod(setter, 
                                                              true, 
                                                              _instance.ref(), 
                                                              getDeclaringClass().getTypeName(), 
                                                              getName().getValue(), 
                                                              params.getModes(), 
                                                              params.getArgs());
         
      LegacyClass.invokeImpl(params, task);
   }     
   
   /**
    * Get the LegacySignature annotation for the Java field.
    * 
    * @param   field 
    *          The field.
    * @return  The annotation if present or null.      
    */
   private static LegacySignature _getSignature(Field field) 
   {
      if (field != null) 
      {
         LegacySignature lsig = field.getAnnotation(LegacySignature.class);
         if (lsig != null && lsig.type() == InternalEntry.Type.PROPERTY)
         {
            return lsig;
         }
      }
      
      return null;
   }
   
   /**
    * Get the LegacySignature annotation for the Java field.
    * 
    * @param   javaMethod 
    *          The method.
    * @return  The annotation if present or null.      
    */
   private static LegacySignature _getSignature(Method javaMethod, InternalEntry.Type type) 
   {
      if (javaMethod != null) 
      {
         LegacySignature lsig = javaMethod.getAnnotation(LegacySignature.class);
         if (lsig != null && lsig.type() == type)
         {
            return lsig;
         }
      }
      
      return null;
   }
   
   /**
    * Check if the field has a valid LegacySignature (type is PROPERTY).
    * 
    * @param field 
    *        the java method
    * 
    * @return <code>true</code> if the field has a valid signature
    */
   public static boolean isProperty (Field field)
   {
      return _getSignature(field) != null;
   }
   
   /**
    * Check if the field has a valid LegacySignature (type is PROPERTY).
    * 
    * @param field 
    *        the java method
    * 
    * @return <code>true</code> if the field has a valid signature
    */
   public static boolean isSetter (Method method)
   {
      return _getSignature(method, InternalEntry.Type.SETTER) != null;
   }
   
   /**
    * Check if the field has a valid LegacySignature (type is PROPERTY).
    * 
    * @param field 
    *        the java method
    * 
    * @return <code>true</code> if the field has a valid signature
    */
   public static boolean isGetter (Method method)
   {
      return _getSignature(method, InternalEntry.Type.GETTER) != null;
   }
   
   /**
    * Gets the access mode of the 4GL PROPERTY.
    * 
    * @param javaMethod 
    *        Java method (GETTER / SETTER) related to property.
    * 
    * @param flags 
    *        The Flags enum to use as selection criteria
    * 
    * @return Flag indicating the access mode of the Property.
    */
   public static object<? extends Flags> getAccesMode(Method method)
   {  
      if (Modifier.isPublic(method.getModifiers()))
      {
         return Flags.public_;
      }
      else if (Modifier.isProtected(method.getModifiers()))
      {
         return Flags.protected_;
      }
      else
      {
         return Flags.private_;
      }
   }
   
   /**
    * Gets the getters method of the property.
    * 
    * @return See above.
    */
   public Method getter()
   {
      return getter.getMethod();
   }
   
   /**
    * Gets the setters method of the property.
    * 
    * @return See above.
    */
   public Method setter()
   {
      return setter.getMethod();
   }
   
   /**
    * Reports if the given instance is managed as part of the legacy 4GL object life cycle. This
    * includes reference counting, linking in the SESSION object chain, managed construction and
    * destruction.
    *
    * @return   Always {@code true}.
    */
   @Override
   public boolean isTracked()
   {
      return false;
   }
}