# ParameterList.java

    /*
    ** Module   : ParameterList.java
    ** Abstract : Implementation of the Progress.Lang.ParameterList builtin class.
    **
    ** Copyright (c) 2018-2025, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description----------------------------------------
    ** 001 CA  20181213 First version.
    ** 002 CA  20190219 First pass at implementation (missing setParameter method).
    ** 003 CA  20190527 Added annotations for property accessors and class event methods.
    ** 005 CA  20190720 Emit the 'this' reference for the BlockManager APIs.
    ** 006 CA  20191024 Added method support levels and updated the class support level.
    ** 007 CA  20210113 Renamed clear() to clear_(), to follow NameConverter's rules.
    **     CA  20210216 Methods which have an int parameter must use the BlockManager API for top-level block.
    ** 008 CA  20210221 Fixed 'qualified', 'extent' and 'returns' annotations at the legacy signature.
    ** 009 ME  20210507 Improve parameter validation (call syntax uses '-' as separator instead space).
    ** 010 GES 20220511 Match changes in CallMode and ParameterOption.
    ** 011 ME  20230503 Reconvert skeleton and getSignatureList and new setParameter method. (#6410).
    **     ME  20230905 Make getModes/getArgs methods public (used by reflection).
    **                  Add isComplete method for validation on reflection invoke.
    **     ME  20230919 Added `return` after throwing errors through the ErrorManager.
    ** 012 CA  20231113 The 'execute' method must be annotated with LegacySignature Type.Execute, and also can be
    **                  dropped if is a no-op.
    ** 013 CA  20231107 Fixed string representation of the call mode, which must not include any option.
    ** 014 CA  20240327 Allow FieldReference or PropertyReference with handle type, for dataset/table-handle.
    ** 015 ES  20250603 Removed function block from the setParameter method.
    */

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

    import static com.goldencode.p2j.util.BlockManager.*;

    import com.goldencode.p2j.persist.*;

    import static com.goldencode.p2j.report.ReportConstants.*;

    import com.goldencode.p2j.util.*;
    import com.goldencode.p2j.util.BlockManager.Action;
    import com.goldencode.p2j.util.BlockManager.Condition;
    import com.goldencode.p2j.util.InternalEntry.Type;

    /**
     * Implementation of the Progress.Lang.ParameterList builtin class.
     */
    @LegacyResource(resource = "Progress.Lang.ParameterList")
    @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_BASIC)
    public final class ParameterList
    extends BaseObject
    {

       /** The registered parameters. */
       private CallParameter[] parameters = new CallParameter[0];

       /**
        * The 'execute' method.  No-op, but it must exist.
        */
       @LegacySignature(type = Type.EXECUTE)
       public void __lang_ParameterList_execute__()
       {
          onBlockLevel(Condition.ERROR, Action.THROW);
       }

       /**
        * Implicit, no parameter, method associated with the implicit legacy constructor for the
        * <code>Progress.Lang.ParameterList</code> class.
        */
       @LegacySignature(type = Type.CONSTRUCTOR)
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void __lang_ParameterList_constructor__()
       {
          __lang_BaseObject_constructor__();
       }

       /**
        * Method associated with the implicit legacy constructor for the
        * <code>Progress.Lang.ParameterList</code> class.
        */
       @LegacySignature(type = Type.CONSTRUCTOR, parameters =
       {
          @LegacyParameter(name = "numParams", type = "INTEGER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void __lang_ParameterList_constructor__(integer numParams)
       {
          __lang_BaseObject_constructor__();

          setNumParameters(numParams);
       }

       /**
        * Destructor for this class.  Cleanup/delete any created resources.
        */
       @LegacySignature(type = Type.DESTRUCTOR)
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void __lang_ParameterList_destructor__()
       {
          clear_();
       }

       /**
        * Getter for the NUM-PARAMETERS property.
        *
        * @return   See above.
        */
       @LegacySignature(returns = "INTEGER", type = Type.GETTER, name = "NumParameters")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public integer getNumParameters()
       {
          return integer.of(parameters.length);
       }

       /**
        * Setter for the NUM-PARAMETERS property.
        *
        * @param   num
        *          The new value.
        */
       @LegacySignature(type = Type.SETTER, name = "NumParameters", parameters =
       {
          @LegacyParameter(name = "var", type = "INTEGER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void setNumParameters(integer num)
       {
          clear_();

          if (num.isUnknown() || num.intValue() < 0)
          {
             ErrorManager.recordOrThrowError(15672, "The argument to the ParameterList Constructor, and " +
                                                    "the value for ParameterList:NumParameters, must be a " +
                                                    "valid non-negative integer", false);
             return;
          }

          this.parameters = new CallParameter[num.intValue()];
       }

       /**
        * Implementation of the CLEAR method.
        *
        * @return   <code>true</code> if the call was successfull.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "clear")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical clear_()
       {
          this.parameters = new CallParameter[0];

          return logical.of(true);
       }

       @LegacySignature(type = Type.METHOD, name = "SetParameter", returns = "LOGICAL", parameters =
       {
          @LegacyParameter(name = "pos", type = "INTEGER", mode = "INPUT"),
          @LegacyParameter(name = "val", type = "BDT", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_STUB)
       public logical setParameter(final integer pos, final Object val)
       {
          int idx = pos.isUnknown() ? 0 : pos.intValue();
          CallParameter param = null;

          if (idx > 0 && idx <= this.getNumParameters().intValue())
          {
             param = parameters[idx - 1];

             if (param == null)
             {
                String msg = "The SetParameter overload with 2 parameters is not allowed unless the ParameterList has been initialized previously for parameter " + pos.intValue() + ".";
                ErrorManager.recordOrThrowError(15294, msg, false);
                return logical.of(false);
             }
          }

          return logical.of(setParameter(idx, param != null ? param.dataType : null, param != null ? param.mode : null, val));
       }

       /**
        * Implementation of the SET-PARAMETER method.
        *
        * @param    pos
        *           The 1-based parameter index.
        * @param    type
        *           The parameter's data type.
        * @param    mode
        *           The parameter's mode (INPUT, OUTPUT, INPUT-OUTPUT, with -APPEND or -BY-REFERENCE
        *           suffix).
        * @param    val
        *           The argument's value.   Can be only a variable/field-ref or extent, if mode is
        *           OUTPUT or INPUT-OUTPUT.
        *
        * @return   <code>true</code> if the parameter was set successfully.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "setParameter", parameters =
       {
          @LegacyParameter(name = "pos",  type = "INTEGER",   mode = "INPUT"),
          @LegacyParameter(name = "type", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "mode", type = "CHARACTER", mode = "INPUT"),
          @LegacyParameter(name = "val",  type = "BDT",       mode = "INPUT"),
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_BASIC)
       public logical setParameter(integer pos, character type, character mode, Object val)
       {
          // space is used as separator instead of '-' for call, trailing spaces are allowed
          CallMode cmode = CallMode.buildMode(TextOps.replaceAll(TextOps.rightTrim(mode), " ", "-"));

          return logical.of(setParameter(pos.isUnknown() ? 0 : pos.intValue(), type.getValue(), cmode, val));
       }

       private boolean setParameter(int pos, String type, CallMode cmode, Object val) {
          if (pos <= 0 || pos > this.getNumParameters().intValue())
          {
             String msg = "SetParameter position must be 1 based and less than or equal to " + this.getNumParameters().intValue() + ".";
             ErrorManager.recordOrThrowError(15293, msg, false);
             return false;
          }

          if (type == null)
          {
             ErrorManager.recordOrThrowError(15295, "Unusable datatype for SetParameter method.", false);
             return false;
          }

          if (!validCallMode(cmode, type, val))
          {
             String msg = "SetParameter IOmode parameter is required in the overload"
                      + " being used, and should be 'INPUT', 'OUTPUT', 'INPUT-OUTPUT'"
                      + " and so on.";
             ErrorManager.recordOrThrowError(15297, msg, false);
             return false;
          }

          if (!cmode.input && !Call.validOutputParameter(pos, val))
          {
             ErrorManager.recordOrThrowError(15311,
                      "SetParameter value for OUTPUT parameters may not be a function or any expression unsuitable for output, nor a database field.",
                      false);
             return false;
          }

          CallParameter param = Call.createParameter(type, cmode, val, false, true);

          if (param == null)
          {
             return false;
          }

          parameters[pos - 1] = param;

          return true;
       }

       private boolean validCallMode(CallMode cmode, String type, Object val)
       {
          if (cmode != null)
          {
             if (val instanceof BaseDataTypeVariable)
             {
                val = ((BaseDataTypeVariable) val).get();
             }

             boolean needDataStructure = false;

             switch (cmode.mode)
             {
                // by-value is not accepted although it's default
                case BY_VALUE:
                   return false;
                case BIND:
                   if (cmode.inputOutput)
                      return false;
                case BY_REFERENCE:
                   needDataStructure = true;
             }

             needDataStructure = needDataStructure || cmode.mode == ParameterOption.APPEND;

             if (needDataStructure)
             {
                return ("TABLE".equalsIgnoreCase(type)        ||
                        "TABLE-HANDLE".equalsIgnoreCase(type) ||
                        "DATASET".equalsIgnoreCase(type)      ||
                        "DATASET-HANDLE".equalsIgnoreCase(type)) &&
                       (val instanceof TableParameter   ||
                        val instanceof DataSetParameter ||
                        val instanceof handle           ||
                        ((val instanceof FieldReference && ((FieldReference) val).getType() == handle.class) ||
                         (val instanceof PropertyReference && ((PropertyReference) val).getType() == handle.class)));
             }

             return true;
          }

          return false;
       }

       /**
        * Get the argument modes.
        *
        * @return   See above.
        */
       public String getModes()
       {
          String modes = "";
          for (CallParameter cparam : parameters)
          {
             modes = modes + cparam.mode.asString();
          }
          return modes;
       }

       /**
        * Get the arguments.
        *
        * @return   See above.
        */
       public Object[] getArgs()
       {
          Object[] args = new Object[parameters.length];
          for (int i = 0; i < args.length; i++)
          {
             args[i] = parameters[i].getArgument();
          }
          return args;
       }

       /**
        * Get the registered parameters.
        *
        * @return   the {@link #parameters}.
        */
       public CallParameter[] getParameters()
       {
          return parameters;
       }

       @LegacySignature(type = Type.GETTER, name = "SignatureList", returns = "CHARACTER")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_STUB)
       public character getSignatureList()
       {
          return new character();
       }

       /**
        * Check if the parameter list is complete.
        *
        * @return  Return true if all parameters are defined.
        */
       public boolean isComplete()
       {
          for (int i = 0; i < parameters.length; i++)
          {
             if (parameters[i] == null)
             {
                return false;
             }
          }

          return true;
       }
    }