===============================================================================
[oorexx:bugs] Re: #2058 ::REQUIRES regression
===============================================================================

Rick 2026, Apr 21

Each loaded package needs to resolve its operating environment before it
can begin its loading process. This means obtaining all of the public
routines and classes defined in the packages referenced via ::REQUIRES.
Once that is done, then the process of actually creating the classes
defined in the packager can proceed and all of the code that needs to run
when the package is loaded can run because the references have been
obtained in a clean state.

So for a simple case of file A requiring file B and B (non circular) the
following takes place;

1) Each ::REQUIRES is processed. If the package has not already been
loaded, the file is loaded and fully initialized. After each file is
processed, the public routine and class information from the required file.

2) now that the package operating environment has been established, the
defined classes can be instantiated, which may involve running class INIT
methods and ACTIVATE methods. The classes might be subclasses of classes
defined in the requires files.

3) Once all of the classes have been created, the package prolog can be
run. Once that completes, the package is considered fully loaded and other
references to the same package name will reuse the already loaded
information.

So the important things here is the package needs to have all of its
::REQUIRES fully resolved and initialized before it can move one to step 2
of the process.

Now through in a circular reference. A causes B to load. The processing of
B requires information from A, but at this point, much of the information
in A does not exist yet (e.g. andy classes defined in A) because A first
needs to obtain information contained in B in order to complete that
process. And B can't provide the information that A requires because B is
unable to get the information from A.

There's also another problem, what if A requires more than one package? The
information contained in the other packages is part of the information that
it provides to other packages, but if B is the first package that A loads,
they when B tries to make the circular reference, none of the rest of the
requires files have been processed yet, so that information is not
available. It is only once a package has gone through the entire
initialization process can that package be used by another package.

===============================================================================
Code review to understand how ::requires works
===============================================================================

A package is loaded once.
This is managed by the interpreter instance.
See InterpreterInstance::getRequiresFile

Each package manages its own list of loaded packages.
See RexxSource::addPackage

Optimisation at the package level :
The imported routines and classes are merged in a RexxDirectory : merged_public_routines
My understanding : that avoids to walk through all the imported packages to find the routine/class.
See RexxSource::mergeRequired(RexxSource *source)


oorexx5
PackageClass.hpp
    inline StringTable *getInstalledClasses() { install(); return installedClasses; }
    inline StringTable *getInstalledPublicClasses() { install(); return installedPublicClasses; }
    inline StringTable *getImportedClasses() { install(); return mergedPublicClasses; }
    inline StringTable *getInstalledRoutines() { install(); return routines; }
    inline StringTable *getInstalledPublicRoutines() { install(); return publicRoutines; }
    inline StringTable *getImportedRoutines() { install(); return mergedPublicRoutines; }
    inline StringTable *getDefinedMethods() { install(); return unattachedMethods; }
    inline ArrayClass  *getPackages() { install(); return loadedPackages; }
    inline StringTable *getResources() { install(); return resources; }
    inline StringTable *getNamespaces() { install(); return namespaces; }

PackageClass::mergeRequired
    PackageClass::addPackage
        PackageClass::loadRequires (2 methods)
            RequiresDirective::install
                PackageClass::processInstall
                    PackageClass::install (inline in PackageClass.hpp
                        RexxCode::install (inline)
                            RexxActivation::run
                                RexxCode::call
                                    RoutineClass::call
                                        PackageClass::runProlog
                                            InterpreterInstance::loadRequires
                                                PackageClass::loadRequires
                                                    RequiresDirective::install
        PackageClass::addPackageRexx
        LibraryPackage::loadRoutines

10/08/2022
https://sourceforge.net/p/oorexx/bugs/1837/
https://sourceforge.net/p/oorexx/code-0/12499/
Rick applied a fix to raise an error in case of cicular ::requires
For
p0 --> p1 --> p2 --+       from p1, C1 and C2 are visble
       ^           |       from p2, C1 is not visble, C2 is visible
       +-----------+
we have now
    10 *-* ::requires "p1.cls"
    10 *-* ::requires "p2.cls"
    23 *-* ::requires "p1.cls"
Error 98 running /local/rexx/oorexx/scripts/visibilty/p2.cls line 10:  Execution error.
Error 98.952:  Circular ::REQUIRES references detected with /local/rexx/oorexx/scripts/visibilty/p1.cls.

----------

void RequiresDirective::install(RexxActivation *context)
{
    context->loadRequires(name, this);
}


PackageClass *RexxActivation::loadRequires(RexxString *target, RexxInstruction *instruction)
{
    // this will cause the correct location to be used for error reporting
    this->current = instruction;

    // the loading/merging is done by the source object
    return getSourceObject()->loadRequires(activity, target);
}


PackageClass *RexxSource::loadRequires(RexxActivity *activity, RexxString *target)
{
    // we need the instance this is associated with
    InterpreterInstance *instance = activity->getInstance();

    // get a fully resolved name for this....we might locate this under either name, but the
    // fully resolved name is generated from this source file context.
    RexxString *fullName = resolveProgramName(activity, target);
    ProtectedObject p(fullName);

    // if we've already loaded this in this instance, just return it.
    PackageClass *packageInstance = instance->loadRequires(activity, target, fullName);

    if (packageInstance == OREF_NULL)       /* couldn't create this?             */
    {
        /* report an error                   */
        reportException(Error_Routine_not_found_requires, target);
    }
    // add this to the source context
    addPackage(packageInstance);
    return packageInstance;
}


PackageClass *InterpreterInstance::loadRequires(RexxActivity *activity, RexxString *shortName, RexxString *fullName)
{

    // if we've already loaded this in this instance, just return it.
    PackageClass *package = getRequiresFile(activity, shortName);
    if (package != OREF_NULL)
    {
        return package;
    }

    // if there is a fully resolved full name, check this next
    if (fullName != OREF_NULL)
    {
        // if we've already loaded this in this instance, just return it.
        package = getRequiresFile(activity, fullName);
        if (package != OREF_NULL)
        {
            // add this to the cache using the short name, since they resolve to the same
            addRequiresFile(shortName, OREF_NULL, package);
            return package;
        }
    }

    // add the package manager to load this
    ProtectedObject p;
    RoutineClass *requiresFile = PackageManager::loadRequires(activity, shortName, fullName, p);

    if (requiresFile == OREF_NULL)             /* couldn't create this?             */
    {
        /* report an error                   */
        reportException(Error_Routine_not_found_requires, shortName);
    }

    package = requiresFile->getPackage();
    // make sure we lock this package until we finish running the requires.
    GuardLock lock(activity, package, ThePackageClass);
    // add this to the instance cache too, under both the long
    // name and the fullName (if it was resolved)
    addRequiresFile(shortName, fullName, package);
    // for any requires file loaded to this instance, we run the prolog within the instance.
    runRequires(activity, fullName != OREF_NULL ? fullName : shortName, requiresFile);

    return package;
}


PackageClass *InterpreterInstance::getRequiresFile(RexxActivity *activity, RexxString *name)
{
    WeakReference *ref = (WeakReference *)requiresFiles->get(name);
    if (ref != OREF_NULL)
    {
        PackageClass *resolved = (PackageClass *)ref->get();
        if (resolved != OREF_NULL)
        {
            // get the guard lock on this...this will ensure that
            // the initializer is run before we grab this from the cache
            GuardLock lock(activity, resolved, ThePackageClass);
            return resolved;
        }
        // this was garbage collected, remove it from the table
        requiresFiles->remove(name);
    }
    return OREF_NULL;
}


void RexxSource::addPackage(PackageClass *p)
{
    // force the directives to be processed first
    install();
    // we only create this on the first use
    if (loadedPackages == OREF_NULL)
    {
        loadedPackages = new_list();
    }
    else
    {
        // we only add a given package item once.
        if (loadedPackages->hasItem(p) == TheTrueObject)
        {
            return;
        }
    }

    // add this to the list and merge the information
    loadedPackages->append(p);
    // not merge all of the info from the imported package
    mergeRequired(p->getSourceObject());
}


JLF : this is another entry point to add a package
Here, the package is already loaded, since passed as a parameter.
So the interpreter instance is not sollicited.
Only the package to which the other package is added is sollicited.

RexxObject *PackageClass::addPackage(PackageClass *package)
{
    classArgument(package, ThePackageClass, "package");
    source->addPackage(package);
    return this;
}


==========================================================================

InterpreterInstance.hpp
public:
    PackageClass *getRequiresFile(RexxActivity *activity, RexxString *name);
    PackageClass *loadRequires(RexxActivity *activity, RexxString *shortName, const char *data, size_t length);
    PackageClass *loadRequires(RexxActivity *activity, RexxString *shortName, RexxArray *source);
    PackageClass *loadRequires(RexxActivity *activity, RexxString *shortName, RexxString *fullName);
    void          runRequires(RexxActivity *activity, RexxString *name, RoutineClass *code);
    void          addRequiresFile(RexxString *shortName, RexxString *fullName, PackageClass *package);
protected:
    RexxDirectory       *requiresFiles;      // our list of requires files used by this instance


InterpreterInstance.cpp
void InterpreterInstance::initialize(RexxActivity *activity, RexxOption *options)
{
    ...
    requiresFiles = new_directory();   // our list of loaded requires packages


InterpreterInstance.cpp
PackageClass *InterpreterInstance::getRequiresFile(RexxActivity *activity, RexxString *name)
{
    WeakReference *ref = (WeakReference *)requiresFiles->get(name);


JLF : a package is registered with 2 names : short & full
InterpreterInstance.cpp
void InterpreterInstance::addRequiresFile(RexxString *shortName, RexxString *fullName, PackageClass *package)
{
    WeakReference *ref = new WeakReference(package);
    requiresFiles->put(ref, shortName);
    if (fullName != OREF_NULL)
    {
        requiresFiles->put(ref, fullName);
    }
}


InterpreterInstance.cpp
PackageClass *InterpreterInstance::loadRequires(RexxActivity *activity, RexxString *shortName, RexxString *fullName)
{

    // if we've already loaded this in this instance, just return it.
    PackageClass *package = getRequiresFile(activity, shortName);


PackageManager.cpp
 * Retrieve a ::REQUIRES file.  This will cache the entries so
 * that the same requires entry is returned for every request.
RoutineClass *PackageManager::loadRequires(RexxActivity *activity, RexxString *shortName, RexxString *resolvedName, ProtectedObject &result)
{
    ...
        return getRequiresFile(activity, resolvedName, securityManager, result);


PackageClass *loadRequires(RexxActivity *activity, RexxString *shortName, const char *data, size_t length);
    called by :
    PackageClass *PackageClass::loadPackage(RexxString *name, RexxArray *s)
    PackageClass *PackageClass::newRexx(
    PackageClass *RexxSource::loadRequires(RexxActivity *activity, RexxString *target)
