Quellcodebibliothek Statistik Leitseite products/Sources/formale Sprachen/C/LibreOffice/basic/source/runtime/   (Office von Apache Version 25.8.3.2©)  Datei vom 5.10.2025 mit Größe 147 kB image not shown  

Quelle  runtime.cxx   Sprache: C

 
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */


#include <stdlib.h>

#include <algorithm>
#include <string_view>
#include <unordered_map>

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XEnumerationAccess.hpp>
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/script/XDefaultMethod.hpp>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/util/SearchAlgorithms2.hpp>

#include <comphelper/processfactory.hxx>
#include <comphelper/string.hxx>
#include <o3tl/safeint.hxx>
#include <sal/log.hxx>

#include <tools/wldcrd.hxx>
#include <comphelper/diagnose_ex.hxx>

#include <utility>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>

#include <rtl/math.hxx>
#include <rtl/ustrbuf.hxx>
#include <rtl/character.hxx>

#include <svl/numformat.hxx>
#include <svl/zforlist.hxx>

#include <unicode/regex.h>

#include <basic/sbuno.hxx>

#include <codegen.hxx>
#include "comenumwrapper.hxx"
#include "ddectrl.hxx"
#include "dllmgr.hxx"
#include <errobject.hxx>
#include <image.hxx>
#include <iosys.hxx>
#include <opcodes.hxx>
#include <runtime.hxx>
#include <sb.hxx>
#include <sbintern.hxx>
#include <sbprop.hxx>
#include <sbunoobj.hxx>
#include <basic/codecompletecache.hxx>
#include <memory>

using com::sun::star::uno::Reference;

using namespace com::sun::star::uno;
using namespace com::sun::star::container;
using namespace com::sun::star::lang;
using namespace com::sun::star::script;

using namespace ::com::sun::star;

#if HAVE_FEATURE_SCRIPTING

static void lcl_clearImpl( SbxVariableRef const & refVar, SbxDataType const & eType );
static void lcl_eraseImpl( SbxVariableRef const & refVar, bool bVBAEnabled );

namespace
{
class ScopedWritableGuard
{
public:
    ScopedWritableGuard(const SbxVariableRef& rVar, bool bMakeWritable)
        : m_rVar(bMakeWritable && !rVar->CanWrite() ? rVar : SbxVariableRef())
    {
        if (m_rVar)
        {
            m_rVar->SetFlag(SbxFlagBits::Write);
        }
    }
    ~ScopedWritableGuard()
    {
        if (m_rVar)
        {
            m_rVar->ResetFlag(SbxFlagBits::Write);
        }
    }

private:
    SbxVariableRef m_rVar;
};
}

bool SbiRuntime::isVBAEnabled()
{
    SbiInstance* pInst = GetSbData()->pInst;
    return pInst && pInst->pRun && pInst->pRun->bVBAEnabled;
}

void StarBASIC::SetVBAEnabled( bool bEnabled )
{
    if ( bDocBasic )
    {
        bVBAEnabled = bEnabled;
    }
}

bool StarBASIC::isVBAEnabled() const
{
    return bDocBasic && (bVBAEnabled || SbiRuntime::isVBAEnabled());
}

struct SbiArgv {                   // Argv stack:
    SbxArrayRef    refArgv;             // Argv
    short nArgc;                        // Argc

    SbiArgv(SbxArrayRef refArgv_, short nArgc_) :
        refArgv(std::move(refArgv_)),
        nArgc(nArgc_) {}
};

struct SbiGosub {              // GOSUB-Stack:
    const sal_uInt8* pCode;         // Return-Pointer
    sal_uInt16 nStartForLvl;        // #118235: For Level in moment of gosub

    SbiGosub(const sal_uInt8* pCode_, sal_uInt16 nStartForLvl_) :
        pCode(pCode_),
        nStartForLvl(nStartForLvl_) {}
};

const SbiRuntime::pStep0 SbiRuntime::aStep0[] = { // all opcodes without operands
    &SbiRuntime::StepNOP,
    &SbiRuntime::StepEXP,
    &SbiRuntime::StepMUL,
    &SbiRuntime::StepDIV,
    &SbiRuntime::StepMOD,
    &SbiRuntime::StepPLUS,
    &SbiRuntime::StepMINUS,
    &SbiRuntime::StepNEG,
    &SbiRuntime::StepEQ,
    &SbiRuntime::StepNE,
    &SbiRuntime::StepLT,
    &SbiRuntime::StepGT,
    &SbiRuntime::StepLE,
    &SbiRuntime::StepGE,
    &SbiRuntime::StepIDIV,
    &SbiRuntime::StepAND,
    &SbiRuntime::StepOR,
    &SbiRuntime::StepXOR,
    &SbiRuntime::StepEQV,
    &SbiRuntime::StepIMP,
    &SbiRuntime::StepNOT,
    &SbiRuntime::StepCAT,

    &SbiRuntime::StepLIKE,
    &SbiRuntime::StepIS,
    // load/save
    &SbiRuntime::StepARGC,      // establish new Argv
    &SbiRuntime::StepARGV,      // TOS ==> current Argv
    &SbiRuntime::StepINPUT,     // Input ==> TOS
    &SbiRuntime::StepLINPUT,        // Line Input ==> TOS
    &SbiRuntime::StepGET,        // touch TOS
    &SbiRuntime::StepSET,        // save object TOS ==> TOS-1
    &SbiRuntime::StepPUT,       // TOS ==> TOS-1
    &SbiRuntime::StepPUTC,      // TOS ==> TOS-1, then ReadOnly
    &SbiRuntime::StepDIM,       // DIM
    &SbiRuntime::StepREDIM,         // REDIM
    &SbiRuntime::StepREDIMP,        // REDIM PRESERVE
    &SbiRuntime::StepERASE,         // delete TOS
    // branch
    &SbiRuntime::StepSTOP,          // program end
    &SbiRuntime::StepINITFOR,   // initialize FOR-Variable
    &SbiRuntime::StepNEXT,      // increment FOR-Variable
    &SbiRuntime::StepCASE,      // beginning CASE
    &SbiRuntime::StepENDCASE,   // end CASE
    &SbiRuntime::StepSTDERROR,      // standard error handling
    &SbiRuntime::StepNOERROR,   // no error handling
    &SbiRuntime::StepLEAVE,     // leave UP
    // E/A
    &SbiRuntime::StepCHANNEL,   // TOS = channel number
    &SbiRuntime::StepPRINT,     // print TOS
    &SbiRuntime::StepPRINTF,        // print TOS in field
    &SbiRuntime::StepWRITE,     // write TOS
    &SbiRuntime::StepRENAME,        // Rename Tos+1 to Tos
    &SbiRuntime::StepPROMPT,        // define Input Prompt from TOS
    &SbiRuntime::StepRESTART,   // Set restart point
    &SbiRuntime::StepCHANNEL0,  // set E/A-channel 0
    &SbiRuntime::StepEMPTY,     // empty expression on stack
    &SbiRuntime::StepERROR,     // TOS = error code
    &SbiRuntime::StepLSET,      // save object TOS ==> TOS-1
    &SbiRuntime::StepRSET,      // save object TOS ==> TOS-1
    &SbiRuntime::StepREDIMP_ERASE,// Copy array object for REDIMP
    &SbiRuntime::StepINITFOREACH,// Init for each loop
    &SbiRuntime::StepVBASET,// vba-like set statement
    &SbiRuntime::StepERASE_CLEAR,// vba-like set statement
    &SbiRuntime::StepARRAYACCESS,// access TOS as array
    &SbiRuntime::StepBYVAL,     // access TOS as array
};

const SbiRuntime::pStep1 SbiRuntime::aStep1[] = { // all opcodes with one operand
    &SbiRuntime::StepLOADNC,        // loading a numeric constant (+ID)
    &SbiRuntime::StepLOADSC,        // loading a string constant (+ID)
    &SbiRuntime::StepLOADI,     // Immediate Load (+value)
    &SbiRuntime::StepARGN,      // save a named Args in Argv (+StringID)
    &SbiRuntime::StepPAD,       // bring string to a definite length (+length)
    // branches
    &SbiRuntime::StepJUMP,      // jump (+Target)
    &SbiRuntime::StepJUMPT,     // evaluate TOS, conditional jump (+Target)
    &SbiRuntime::StepJUMPF,     // evaluate TOS, conditional jump (+Target)
    &SbiRuntime::StepONJUMP,        // evaluate TOS, jump into JUMP-table (+MaxVal)
    &SbiRuntime::StepGOSUB,     // UP-call (+Target)
    &SbiRuntime::StepRETURN,        // UP-return (+0 or Target)
    &SbiRuntime::StepTESTFOR,   // check FOR-variable, increment (+Endlabel)
    &SbiRuntime::StepCASETO,        // Tos+1 <= Case <= Tos), 2xremove (+Target)
    &SbiRuntime::StepERRHDL,        // error handler (+Offset)
    &SbiRuntime::StepRESUME,        // resume after errors (+0 or 1 or Label)
    // E/A
    &SbiRuntime::StepCLOSE,     // (+channel/0)
    &SbiRuntime::StepPRCHAR,        // (+char)
    // management
    &SbiRuntime::StepSETCLASS,  // check set + class names (+StringId)
    &SbiRuntime::StepTESTCLASS, // Check TOS class (+StringId)
    &SbiRuntime::StepLIB,       // lib for declare-call (+StringId)
    &SbiRuntime::StepBASED,     // TOS is incremented by BASE, BASE is pushed before
    &SbiRuntime::StepARGTYP,        // convert last parameter in Argv (+Type)
    &SbiRuntime::StepVBASETCLASS,// vba-like set statement
};

const SbiRuntime::pStep2 SbiRuntime::aStep2[] = {// all opcodes with two operands
    &SbiRuntime::StepRTL,       // load from RTL (+StringID+Typ)
    &SbiRuntime::StepFIND,      // load (+StringID+Typ)
    &SbiRuntime::StepELEM,          // load element (+StringID+Typ)
    &SbiRuntime::StepPARAM,     // Parameter (+Offset+Typ)
    // branches
    &SbiRuntime::StepCALL,      // Declare-Call (+StringID+Typ)
    &SbiRuntime::StepCALLC,     // CDecl-Declare-Call (+StringID+Typ)
    &SbiRuntime::StepCASEIS,        // Case-Test (+Test-Opcode+False-Target)
    // management
    &SbiRuntime::StepSTMNT,         // beginning of a statement (+Line+Col)
    // E/A
    &SbiRuntime::StepOPEN,          // (+StreamMode+Flags)
    // Objects
    &SbiRuntime::StepLOCAL,     // define local variable (+StringId+Typ)
    &SbiRuntime::StepPUBLIC,        // module global variable (+StringID+Typ)
    &SbiRuntime::StepGLOBAL,        // define global variable (+StringID+Typ)
    &SbiRuntime::StepCREATE,        // create object (+StringId+StringId)
    &SbiRuntime::StepSTATIC,     // static variable (+StringId+StringId)
    &SbiRuntime::StepTCREATE,    // user-defined objects (+StringId+StringId)
    &SbiRuntime::StepDCREATE,    // create object-array (+StringID+StringID)
    &SbiRuntime::StepGLOBAL_P,   // define global variable which is not overwritten
                                 // by the Basic on a restart (+StringID+Typ)
    &SbiRuntime::StepFIND_G,        // finds global variable with special treatment because of _GLOBAL_P
    &SbiRuntime::StepDCREATE_REDIMP, // redimension object array (+StringID+StringID)
    &SbiRuntime::StepFIND_CM,    // Search inside a class module (CM) to enable global search in time
    &SbiRuntime::StepPUBLIC_P,    // Search inside a class module (CM) to enable global search in time
    &SbiRuntime::StepFIND_STATIC,    // Search inside a class module (CM) to enable global search in time
};


//                              SbiRTLData

SbiRTLData::SbiRTLData()
    : nDirFlags(SbAttributes::NORMAL)
    , nCurDirPos(0)
{
}

SbiRTLData::~SbiRTLData()
{
}

//                              SbiInstance

// 16.10.96: #31460 new concept for StepInto/Over/Out
// The decision whether StepPoint shall be called is done with the help of
// the CallLevel. It's stopped when the current CallLevel is <= nBreakCallLvl.
// The current CallLevel can never be smaller than 1, as it's also incremented
// during the call of a method (also main). Therefore a BreakCallLvl from 0
// means that the program isn't stopped at all.
// (also have a look at: step2.cxx, SbiRuntime::StepSTMNT() )


void SbiInstance::CalcBreakCallLevel( BasicDebugFlags nFlags )
{

    nFlags &= ~BasicDebugFlags::Break;

    sal_uInt16 nRet;
    if (nFlags  == BasicDebugFlags::StepInto) {
        nRet = nCallLvl + 1;    // CallLevel+1 is also stopped
    } else if (nFlags == (BasicDebugFlags::StepOver | BasicDebugFlags::StepInto)) {
        nRet = nCallLvl;        // current CallLevel is stopped
    } else if (nFlags == BasicDebugFlags::StepOut) {
        nRet = nCallLvl - 1;    // smaller CallLevel is stopped
    } else {
        // Basic-IDE returns 0 instead of BasicDebugFlags::Continue, so also default=continue
        nRet = 0;               // CallLevel is always > 0 -> no StepPoint
    }
    nBreakCallLvl = nRet;           // take result
}

SbiInstance::SbiInstance( StarBASIC* p )
    : pIosys(new SbiIoSystem)
    , pDdeCtrl(new SbiDdeControl)
    , pBasic(p)
    , meFormatterLangType(LANGUAGE_DONTKNOW)
    , meFormatterDateOrder(DateOrder::YMD)
    , nStdDateIdx(0)
    , nStdTimeIdx(0)
    , nStdDateTimeIdx(0)
    , nErr(0)
    , nErl(0)
    , bReschedule(true)
    , bCompatibility(false)
    , pRun(nullptr)
    , nCallLvl(0)
    , nBreakCallLvl(0)
{
}

SbiInstance::~SbiInstance()
{
    while( pRun )
    {
        SbiRuntime* p = pRun->pNext;
        delete pRun;
        pRun = p;
    }

    try
    {
        int nSize = ComponentVector.size();
        if( nSize )
        {
            forint i = nSize - 1 ; i >= 0 ; --i )
            {
                Reference< XComponent > xDlgComponent = ComponentVector[i];
                if( xDlgComponent.is() )
                    xDlgComponent->dispose();
            }
        }
    }
    catchconst Exception& )
    {
        TOOLS_WARN_EXCEPTION("basic""SbiInstance::~SbiInstance: caught an exception while disposing the components" );
    }
}

SbiDllMgr* SbiInstance::GetDllMgr()
{
    if( !pDllMgr )
    {
        pDllMgr.reset(new SbiDllMgr);
    }
    return pDllMgr.get();
}

#endif

// #39629 create NumberFormatter with the help of a static method now
std::shared_ptr<SvNumberFormatter> const & SbiInstance::GetNumberFormatter()
{
    LanguageType eLangType = Application::GetSettings().GetLanguageTag().getLanguageType();
    SvtSysLocale aSysLocale;
    DateOrder eDate = aSysLocale.GetLocaleData().getDateOrder();
    if( pNumberFormatter )
    {
        if( eLangType != meFormatterLangType ||
            eDate != meFormatterDateOrder )
        {
            pNumberFormatter.reset();
        }
    }
    meFormatterLangType = eLangType;
    meFormatterDateOrder = eDate;
    if( !pNumberFormatter )
    {
        pNumberFormatter = PrepareNumberFormatter( nStdDateIdx, nStdTimeIdx, nStdDateTimeIdx,
                &meFormatterLangType, &meFormatterDateOrder);
    }
    return pNumberFormatter;
}

// #39629 offer NumberFormatter static too
std::shared_ptr<SvNumberFormatter> SbiInstance::PrepareNumberFormatter( sal_uInt32 &rnStdDateIdx,
    sal_uInt32 &rnStdTimeIdx, sal_uInt32 &rnStdDateTimeIdx,
    LanguageType const * peFormatterLangType, DateOrder const * peFormatterDateOrder )
{
    LanguageType eLangType;
    if( peFormatterLangType )
    {
        eLangType = *peFormatterLangType;
    }
    else
    {
        eLangType = Application::GetSettings().GetLanguageTag().getLanguageType();
    }
    DateOrder eDate;
    if( peFormatterDateOrder )
    {
        eDate = *peFormatterDateOrder;
    }
    else
    {
        SvtSysLocale aSysLocale;
        eDate = aSysLocale.GetLocaleData().getDateOrder();
    }

    std::shared_ptr<SvNumberFormatter> pNumberFormatter =
            std::make_shared<SvNumberFormatter>( comphelper::getProcessComponentContext(), eLangType );

    // Several parser methods pass SvNumberFormatter::IsNumberFormat() a number
    // format index to parse against. Tell the formatter the proper date
    // evaluation order, which also determines the date acceptance patterns to
    // use if a format was passed. NF_EVALDATEFORMAT_FORMAT restricts to the
    // format's locale's date patterns/order (no init/system locale match
    // tried) and falls back to NF_EVALDATEFORMAT_INTL if no specific (i.e. 0)
    // (or an unknown) format index was passed.
    pNumberFormatter->SetEvalDateFormat( NF_EVALDATEFORMAT_FORMAT);

    sal_Int32 nCheckPos = 0;
    SvNumFormatType nType;
    rnStdTimeIdx = pNumberFormatter->GetStandardFormat( SvNumFormatType::TIME, eLangType );

    // the formatter's standard templates have only got a two-digit date
    // -> registering an own format

    // HACK, because the numberformatter doesn't swap the place holders
    // for month, day and year according to the system setting.
    // Problem: Print Year(Date) under engl. BS
    // also have a look at: basic/source/sbx/sbxdate.cxx

    OUString aDateStr;
    switch( eDate )
    {
        default:
        case DateOrder::MDY: aDateStr = "MM/DD/YYYY"break;
        case DateOrder::DMY: aDateStr = "DD/MM/YYYY"break;
        case DateOrder::YMD: aDateStr = "YYYY/MM/DD"break;
    }
    OUString aStr( aDateStr );      // PutandConvertEntry() modifies string!
    pNumberFormatter->PutandConvertEntry( aStr, nCheckPos, nType,
        rnStdDateIdx, LANGUAGE_ENGLISH_US, eLangType, true);
    nCheckPos = 0;
    aDateStr += " HH:MM:SS";
    aStr = aDateStr;
    pNumberFormatter->PutandConvertEntry( aStr, nCheckPos, nType,
        rnStdDateTimeIdx, LANGUAGE_ENGLISH_US, eLangType, true);
    return pNumberFormatter;
}

#if HAVE_FEATURE_SCRIPTING

// Let engine run. If Flags == BasicDebugFlags::Continue, take Flags over

void SbiInstance::Stop()
{
    for( SbiRuntime* p = pRun; p; p = p->pNext )
    {
        p->Stop();
    }
}

// Allows Basic IDE to set watch mode to suppress errors
static bool bWatchMode = false;

void setBasicWatchMode( bool bOn )
{
    bWatchMode = bOn;
}

void SbiInstance::Error( ErrCode n )
{
    Error( n, OUString() );
}

void SbiInstance::Error( ErrCode n, const OUString& rMsg )
{
    if( !bWatchMode )
    {
        aErrorMsg = rMsg;
        pRun->Error( n );
    }
}

void SbiInstance::ErrorVB( sal_Int32 nVBNumber, const OUString& rMsg )
{
    if( !bWatchMode )
    {
        ErrCode n = StarBASIC::GetSfxFromVBError( static_cast< sal_uInt16 >( nVBNumber ) );
        if ( !n )
        {
            n = ErrCode(nVBNumber); // force orig number, probably should have a specific table of vb ( localized ) errors
        }
        aErrorMsg = rMsg;
        SbiRuntime::translateErrorToVba( n, aErrorMsg );

        pRun->Error( ERRCODE_BASIC_COMPAT, true/*bVBATranslationAlreadyDone*/ );
    }
}

void SbiInstance::setErrorVB( sal_Int32 nVBNumber )
{
    ErrCode n = StarBASIC::GetSfxFromVBError( static_cast< sal_uInt16 >( nVBNumber ) );
    if( !n )
    {
        n = ErrCode(nVBNumber); // force orig number, probably should have a specific table of vb ( localized ) errors
    }
    aErrorMsg = OUString();
    SbiRuntime::translateErrorToVba( n, aErrorMsg );

    nErr = n;
}


void SbiInstance::FatalError( ErrCode n )
{
    pRun->FatalError( n );
}

void SbiInstance::FatalError( ErrCode _errCode, const OUString& _details )
{
    pRun->FatalError( _errCode, _details );
}

void SbiInstance::Abort()
{
    StarBASIC* pErrBasic = GetCurrentBasic( pBasic );
    pErrBasic->RTError( nErr, aErrorMsg, pRun->nLine, pRun->nCol1, pRun->nCol2 );
    StarBASIC::Stop();
}

// can be unequal to pRTBasic
StarBASIC* GetCurrentBasic( StarBASIC* pRTBasic )
{
    StarBASIC* pCurBasic = pRTBasic;
    SbModule* pActiveModule = StarBASIC::GetActiveModule();
    if( pActiveModule )
    {
        SbxObject* pParent = pActiveModule->GetParent();
        if (StarBASIC *pBasic = dynamic_cast<StarBASIC*>(pParent))
            pCurBasic = pBasic;
    }
    return pCurBasic;
}

SbModule* SbiInstance::GetActiveModule()
{
    if( pRun )
    {
        return pRun->GetModule();
    }
    else
    {
        return nullptr;
    }
}

SbMethod* SbiInstance::GetCaller( sal_uInt16 nLevel )
{
    SbiRuntime* p = pRun;
    while( nLevel-- && p )
    {
        p = p->pNext;
    }
    return p ? p->GetCaller() : nullptr;
}

//                              SbiInstance

// Attention: pMeth can also be NULL (on a call of the init-code)

SbiRuntime::SbiRuntime( SbModule* pm, SbMethod* pe, sal_uInt32 nStart )
         : rBasic( *static_cast<StarBASIC*>(pm->pParent) ), pInst( GetSbData()->pInst ),
           pMod( pm ), pMeth( pe ), pImg( pMod->pImage.get() )
{
    nFlags    = pe ? pe->GetDebugFlags() : BasicDebugFlags::NONE;
    pIosys    = pInst->GetIoSystem();
    pCode     =
    pStmnt    = pImg->GetCode() + nStart;
    refExprStk = new SbxArray;
    SetVBAEnabled( pMod->IsVBASupport() );
    SetParameters( pe ? pe->GetParameters() : nullptr );
}

SbiRuntime::~SbiRuntime()
{
    ClearArgvStack();
    ClearForStack();
}

void SbiRuntime::SetVBAEnabled(bool bEnabled )
{
    bVBAEnabled = bEnabled;
    if ( bVBAEnabled )
    {
        if ( pMeth )
        {
            mpExtCaller = pMeth->mCaller;
        }
    }
    else
    {
        mpExtCaller = nullptr;
    }
}

// tdf#79426, tdf#125180 - adds the information about a missing parameter
void SbiRuntime::SetIsMissing( SbxVariable* pVar )
{
    SbxInfo* pInfo = pVar->GetInfo() ? pVar->GetInfo() : new SbxInfo();
    pInfo->AddParam( pVar->GetName(), SbxMISSING, pVar->GetFlags() );
    pVar->SetInfo( pInfo );
}

// tdf#79426, tdf#125180 - checks if a variable contains the information about a missing parameter
bool SbiRuntime::IsMissing( SbxVariable* pVar, sal_uInt16 nIdx )
{
    return pVar->GetInfo() && pVar->GetInfo()->GetParam( nIdx ) && pVar->GetInfo()->GetParam( nIdx )->eType & SbxMISSING;
}

// Construction of the parameter list. All ByRef-parameters are directly
// taken over; copies of ByVal-parameters are created. If a particular
// data type is requested, it is converted.

void SbiRuntime::SetParameters( SbxArray* pParams )
{
    refParams = new SbxArray;
    // for the return value
    refParams->Put(pMeth, 0);

    SbxInfo* pInfo = pMeth ? pMeth->GetInfo() : nullptr;
    sal_uInt32 nParamCount = pParams ? pParams->Count() : 1;
    assert(nParamCount <= std::numeric_limits<sal_uInt16>::max());
    if( nParamCount > 1 )
    {
        for( sal_uInt32 i = 1 ; i < nParamCount ; i++ )
        {
            const SbxParamInfo* p = pInfo ? pInfo->GetParam( sal::static_int_cast<sal_uInt16>(i) ) : nullptr;

            // #111897 ParamArray
            if( p && (p->nUserData & PARAM_INFO_PARAMARRAY) != 0 )
            {
                SbxDimArray* pArray = new SbxDimArray( SbxVARIANT );
                sal_uInt32 nParamArrayParamCount = nParamCount - i;
                pArray->unoAddDim(0, nParamArrayParamCount - 1);
                for (sal_uInt32 j = i; j < nParamCount ; ++j)
                {
                    SbxVariable* v = pParams->Get(j);
                    sal_Int32 aDimIndex[1];
                    aDimIndex[0] = j - i;
                    pArray->Put(v, aDimIndex);
                }
                SbxVariable* pArrayVar = new SbxVariable( SbxVARIANT );
                pArrayVar->SetFlag( SbxFlagBits::ReadWrite );
                pArrayVar->PutObject( pArray );
                refParams->Put(pArrayVar, i);

                // Block ParamArray for missing parameter
                pInfo = nullptr;
                break;
            }

            SbxVariable* v = pParams->Get(i);
            assert(v);
            // methods are always byval!
            bool bByVal = dynamic_cast<const SbxMethod *>(v) != nullptr;
            SbxDataType t = v->GetType();
            bool bTargetTypeIsArray = false;
            if( p )
            {
                bByVal |= ( p->eType & SbxBYREF ) == 0;
                // tdf#79426, tdf#125180 - don't convert missing arguments to the requested parameter type
                if ( !IsMissing( v, 1 ) )
                {
                    t = static_cast<SbxDataType>( p->eType & 0x0FFF );
                }

                if( !bByVal && t != SbxVARIANT &&
                    (!v->IsFixed() || static_cast<SbxDataType>(v->GetType() & 0x0FFF ) != t) )
                {
                    bByVal = true;
                }

                bTargetTypeIsArray = (p->nUserData & PARAM_INFO_WITHBRACKETS) != 0;
            }
            if( bByVal )
            {
                // tdf#79426, tdf#125180 - don't convert missing arguments to the requested parameter type
                if( bTargetTypeIsArray && !IsMissing( v, 1 ) )
                {
                    t = SbxOBJECT;
                }
                SbxVariable* v2 = new SbxVariable( t );
                v2->SetFlag( SbxFlagBits::ReadWrite );
                // tdf#79426, tdf#125180 - if parameter was missing, readd additional information about a missing parameter
                if ( IsMissing( v, 1 ) )
                {
                    SetIsMissing( v2 );
                }
                *v2 = *v;
                refParams->Put(v2, i);
            }
            else
            {
                // tdf#79426, tdf#125180 - don't convert missing arguments to the requested parameter type
                if( t != SbxVARIANT && !IsMissing( v, 1 ) && t != ( v->GetType() & 0x0FFF ) )
                {
                    if( p && (p->eType & SbxARRAY) )
                    {
                        Error( ERRCODE_BASIC_CONVERSION );
                    }
                    else
                    {
                        v->Convert( t );
                    }
                }
                refParams->Put(v, i);
            }
            if( p )
            {
                refParams->PutAlias(p->aName, i);
            }
        }
    }

    // ParamArray for missing parameter
    if( !pInfo )
        return;

    // #111897 Check first missing parameter for ParamArray
    const SbxParamInfo* p = pInfo->GetParam(sal::static_int_cast<sal_uInt16>(nParamCount));
    if( p && (p->nUserData & PARAM_INFO_PARAMARRAY) != 0 )
    {
        SbxDimArray* pArray = new SbxDimArray( SbxVARIANT );
        pArray->unoAddDim(0, -1);
        SbxVariable* pArrayVar = new SbxVariable( SbxVARIANT );
        pArrayVar->SetFlag( SbxFlagBits::ReadWrite );
        pArrayVar->PutObject( pArray );
        refParams->Put(pArrayVar, nParamCount);
    }
}


// execute a P-Code

bool SbiRuntime::Step()
{
    if( bRun )
    {
        static sal_uInt32 nLastTime = osl_getGlobalTimer();

        // in any case check casually!
        if( !( ++nOps & 0xF ) && pInst->IsReschedule() )
        {
            sal_uInt32 nTime = osl_getGlobalTimer();
            if (nTime - nLastTime > 5) // 20 ms
            {
                nLastTime = nTime;
                Application::Reschedule();
            }
        }

        // #i48868 blocked by next call level?
        while( bBlocked )
        {
            if( pInst->IsReschedule() ) // And what if not? Busy loop?
            {
                Application::Reschedule();
                nLastTime = osl_getGlobalTimer();
            }
        }

        SbiOpcode eOp = static_cast<SbiOpcode>( *pCode++ );
        sal_uInt32 nOp1;
        if (eOp <= SbiOpcode::SbOP0_END)
        {
            (this->*( aStep0[ int(eOp) ] ) )();
        }
        else if (eOp >= SbiOpcode::SbOP1_START && eOp <= SbiOpcode::SbOP1_END)
        {
            nOp1 = *pCode++; nOp1 |= *pCode++ << 8; nOp1 |= *pCode++ << 16; nOp1 |= *pCode++ << 24;

            (this->*( aStep1[ int(eOp) - int(SbiOpcode::SbOP1_START) ] ) )( nOp1 );
        }
        else if (eOp >= SbiOpcode::SbOP2_START && eOp <= SbiOpcode::SbOP2_END)
        {
            nOp1 = *pCode++; nOp1 |= *pCode++ << 8; nOp1 |= *pCode++ << 16; nOp1 |= *pCode++ << 24;
            sal_uInt32 nOp2 = *pCode++; nOp2 |= *pCode++ << 8; nOp2 |= *pCode++ << 16; nOp2 |= *pCode++ << 24;
            (this->*( aStep2[ int(eOp) - int(SbiOpcode::SbOP2_START) ] ) )( nOp1, nOp2 );
        }
        else
        {
            StarBASIC::FatalError( ERRCODE_BASIC_INTERNAL_ERROR );
        }

        ErrCode nErrCode = SbxBase::GetError();
        Error( nErrCode.IgnoreWarning() );

        // from 13.2.1997, new error handling:
        // ATTENTION: nError can be set already even if !nErrCode
        // since nError can now also be set from other RT-instances

        if( nError )
        {
            SbxBase::ResetError();
        }

        // from 15.3.96: display errors only if BASIC is still active
        // (especially not after compiler errors at the runtime)
        if( nError && bRun )
        {
            ErrCode err = nError;
            ClearExprStack();
            nError = ERRCODE_NONE;
            pInst->nErr = err;
            pInst->nErl = nLine;
            pErrCode    = pCode;
            pErrStmnt   = pStmnt;
            // An error occurred in an error handler
            // force parent handler ( if there is one )
            // to handle the error
            bool bLetParentHandleThis = false;

            // in the error handler? so std-error
            if ( !bInError )
            {
                bInError = true;

                if( !bError )           // On Error Resume Next
                {
                    StepRESUME( 1 );
                }
                else if( pError )       // On Error Goto ...
                {
                    pCode = pError;
                }
                else
                {
                    bLetParentHandleThis = true;
                }
            }
            else
            {
                bLetParentHandleThis = true;
                pError = nullptr; //terminate the handler
            }
            if ( bLetParentHandleThis )
            {
                // from 13.2.1997, new error handling:
                // consider superior error handlers

                // there's no error handler -> find one farther above
                SbiRuntime* pRtErrHdl = nullptr;
                SbiRuntime* pRt = this;
                while( (pRt = pRt->pNext) != nullptr )
                {
                    if( !pRt->bError || pRt->pError != nullptr )
                    {
                        pRtErrHdl = pRt;
                        break;
                    }
                }


                if( pRtErrHdl )
                {
                    // manipulate all the RTs that are below in the call-stack
                    pRt = this;
                    do
                    {
                        pRt->nError = err;
                        if( pRt != pRtErrHdl )
                        {
                            pRt->bRun = false;
                        }
                        else
                        {
                            break;
                        }
                        pRt = pRt->pNext;
                    }
                    while( pRt );
                }
                // no error-hdl found -> old behaviour
                else
                {
                    pInst->Abort();
                }
            }
        }
    }
    return bRun;
}

void SbiRuntime::Error( ErrCode n, bool bVBATranslationAlreadyDone )
{
    if( !n )
        return;

    nError = n;
    if( !isVBAEnabled() || bVBATranslationAlreadyDone )
        return;

    OUString aMsg = pInst->GetErrorMsg();
    sal_Int32 nVBAErrorNumber = translateErrorToVba( nError, aMsg );
    SbxVariable* pSbxErrObjVar = SbxErrObject::getErrObject().get();
    SbxErrObject* pGlobErr = static_cast< SbxErrObject* >( pSbxErrObjVar );
    if( pGlobErr != nullptr )
    {
        pGlobErr->setNumberAndDescription( nVBAErrorNumber, aMsg );
    }
    pInst->aErrorMsg = aMsg;
    nError = ERRCODE_BASIC_COMPAT;
}

void SbiRuntime::Error( ErrCode _errCode, const OUString& _details )
{
    if ( !_errCode )
        return;

    // Not correct for class module usage, remove for now
    //OSL_WARN_IF( pInst->pRun != this, "basic", "SbiRuntime::Error: can't propagate the error message details!" );
    if ( pInst->pRun == this )
    {
        pInst->Error( _errCode, _details );
        //OSL_WARN_IF( nError != _errCode, "basic", "SbiRuntime::Error: the instance is expected to propagate the error code back to me!" );
    }
    else
    {
        nError = _errCode;
    }
}

void SbiRuntime::FatalError( ErrCode n )
{
    StepSTDERROR();
    Error( n );
}

void SbiRuntime::FatalError( ErrCode _errCode, const OUString& _details )
{
    StepSTDERROR();
    Error( _errCode, _details );
}

sal_Int32 SbiRuntime::translateErrorToVba( ErrCode nError, OUString& rMsg )
{
    // If a message is defined use that ( in preference to
    // the defined one for the error ) NB #TODO
    // if there is an error defined it more than likely
    // is not the one you want ( some are the same though )
    // we really need a new vba compatible error list
    // tdf#123144 - always translate an error number to a vba error message
    StarBASIC::MakeErrorText( nError, rMsg );
    rMsg = StarBASIC::GetErrorText();
    // no num? most likely then it *is* really a vba err
    sal_uInt16 nVBErrorCode = StarBASIC::GetVBErrorCode( nError );
    sal_Int32 nVBAErrorNumber = ( nVBErrorCode == 0 ) ? sal_uInt32(nError) : nVBErrorCode;
    return nVBAErrorNumber;
}

//  Stacks

// The expression-stack is available for the continuous evaluation
// of expressions.

void SbiRuntime::PushVar( SbxVariable* pVar )
{
    if( pVar )
    {
        refExprStk->Put(pVar, nExprLvl++);
    }
}

SbxVariableRef SbiRuntime::PopVar()
{
#ifdef DBG_UTIL
    if( !nExprLvl )
    {
        StarBASIC::FatalError( ERRCODE_BASIC_INTERNAL_ERROR );
        return new SbxVariable;
    }
#endif
    SbxVariableRef xVar = refExprStk->Get(--nExprLvl);
    SAL_INFO_IF( xVar->GetName() == "Cells""basic""PopVar: Name equals 'Cells'" );
    // methods hold themselves in parameter 0
    ifdynamic_cast<const SbxMethod *>(xVar.get()) != nullptr )
    {
        xVar->SetParameters(nullptr);
    }
    return xVar;
}

void SbiRuntime::ClearExprStack()
{
    // Attention: Clear() doesn't suffice as methods must be deleted
    while ( nExprLvl )
    {
        PopVar();
    }
    refExprStk->Clear();
}

// Take variable from the expression-stack without removing it
// n counts from 0

SbxVariable* SbiRuntime::GetTOS()
{
    short n = nExprLvl - 1;
#ifdef DBG_UTIL
    if( n < 0 )
    {
        StarBASIC::FatalError( ERRCODE_BASIC_INTERNAL_ERROR );
        return new SbxVariable;
    }
#endif
    return refExprStk->Get(static_cast<sal_uInt32>(n));
}


void SbiRuntime::TOSMakeTemp()
{
    SbxVariable* p = refExprStk->Get(nExprLvl - 1);
    if ( p->GetType() == SbxEMPTY )
    {
        p->Broadcast( SfxHintId::BasicDataWanted );
    }

    SbxVariable* pDflt = nullptr;
    if ( bVBAEnabled &&  ( p->GetType() == SbxOBJECT || p->GetType() == SbxVARIANT  ) && ((pDflt = getDefaultProp(p)) != nullptr) )
    {
        pDflt->Broadcast( SfxHintId::BasicDataWanted );
        // replacing new p on stack causes object pointed by
        // pDft->pParent to be deleted, when p2->Compute() is
        // called below pParent is accessed (but it's deleted)
        // so set it to NULL now
        pDflt->SetParent( nullptr );
        p = new SbxVariable( *pDflt );
        p->SetFlag( SbxFlagBits::ReadWrite );
        refExprStk->Put(p, nExprLvl - 1);
    }
    else if( p->GetRefCount() != 1 )
    {
        SbxVariable* pNew = new SbxVariable( *p );
        pNew->SetFlag( SbxFlagBits::ReadWrite );
        refExprStk->Put(pNew, nExprLvl - 1);
    }
}

// the GOSUB-stack collects return-addresses for GOSUBs
void SbiRuntime::PushGosub( const sal_uInt8* pc )
{
    if( pGosubStk.size() >= MAXRECURSION )
    {
        StarBASIC::FatalError( ERRCODE_BASIC_STACK_OVERFLOW );
    }
    pGosubStk.emplace_back(pc, nForLvl);
}

void SbiRuntime::PopGosub()
{
    if( pGosubStk.empty() )
    {
        Error( ERRCODE_BASIC_NO_GOSUB );
    }
    else
    {
        pCode = pGosubStk.back().pCode;
        pGosubStk.pop_back();
    }
}

// the Argv-stack collects current argument-vectors

void SbiRuntime::PushArgv()
{
    pArgvStk.emplace_back(refArgv, nArgc);
    nArgc = 1;
    refArgv.clear();
}

void SbiRuntime::PopArgv()
{
    if( !pArgvStk.empty() )
    {
        refArgv = pArgvStk.back().refArgv;
        nArgc = pArgvStk.back().nArgc;
        pArgvStk.pop_back();
    }
}


void SbiRuntime::ClearArgvStack()
{
    while( !pArgvStk.empty() )
    {
        PopArgv();
    }
}

// Push of the for-stack. The stack has increment, end, begin and variable.
// After the creation of the stack-element the stack's empty.

void SbiRuntime::PushFor()
{
    SbiForStack* p = new SbiForStack;
    p->eForType = ForType::To;
    p->pNext = pForStk;
    pForStk = p;

    p->refInc = PopVar();
    p->refEnd = PopVar();
    if (isVBAEnabled())
    {
        // tdf#150458: only calculate these once, coercing to double
        // tdf#150460: shouldn't we do it in non-VBA / compat mode, too?
        SbxVariableRef incCopy(new SbxVariable(SbxDOUBLE));
        *incCopy = *p->refInc;
        p->refInc = std::move(incCopy);
        SbxVariableRef endCopy(new SbxVariable(SbxDOUBLE));
        *endCopy = *p->refEnd;
        p->refEnd = std::move(endCopy);
    }
    SbxVariableRef xBgn = PopVar();
    p->refVar = PopVar();
    // tdf#85371 - grant explicitly write access to the index variable
    // since it could be the name of a method itself used in the next statement.
    ScopedWritableGuard aGuard(p->refVar, p->refVar.get() == pMeth);
    *(p->refVar) = *xBgn;
    nForLvl++;
}

void SbiRuntime::PushForEach()
{
    SbiForStack* p = new SbiForStack;
    // Set default value in case of error which is ignored in Resume Next
    p->eForType = ForType::EachArray;
    p->pNext = pForStk;
    pForStk = p;

    SbxVariableRef xObjVar = PopVar();
    SbxBase* pObj(nullptr);
    if (xObjVar)
    {
        SbxValues v(SbxVARIANT);
        // Here it may retrieve the value, and change the type from SbxEMPTY to SbxOBJECT
        xObjVar->Get(v);
        if (v.eType == SbxOBJECT)
            pObj = v.pObj;
    }

    if (SbxDimArray* pArray = dynamic_cast<SbxDimArray*>(pObj))
    {
        p->refEnd = reinterpret_cast<SbxVariable*>(pArray);

        sal_Int32 nDims = pArray->GetDims();
        p->pArrayLowerBounds.reset( new sal_Int32[nDims] );
        p->pArrayUpperBounds.reset( new sal_Int32[nDims] );
        p->pArrayCurIndices.reset( new sal_Int32[nDims] );
        sal_Int32 lBound, uBound;
        for( sal_Int32 i = 0 ; i < nDims ; i++ )
        {
            pArray->GetDim(i + 1, lBound, uBound);
            p->pArrayCurIndices[i] = p->pArrayLowerBounds[i] = lBound;
            p->pArrayUpperBounds[i] = uBound;
        }
    }
    else if (BasicCollection* pCollection = dynamic_cast<BasicCollection*>(pObj))
    {
        p->eForType = ForType::EachCollection;
        p->refEnd = pCollection;
        p->nCurCollectionIndex = 0;
    }
    else if (SbUnoObject* pUnoObj = dynamic_cast<SbUnoObject*>(pObj))
    {
        // XEnumerationAccess or XIndexAccess?
        Any aAny = pUnoObj->getUnoAny();
        Reference<XIndexAccess> xIndexAccess;
        Reference< XEnumerationAccess > xEnumerationAccess;
        if( aAny >>= xEnumerationAccess )
        {
            p->xEnumeration = xEnumerationAccess->createEnumeration();
            p->eForType = ForType::EachXEnumeration;
        }
        // tdf#130307 - support for each loop for objects exposing XIndexAccess
        else if (aAny >>= xIndexAccess)
        {
            p->eForType = ForType::EachXIndexAccess;
            p->xIndexAccess = std::move(xIndexAccess);
            p->nCurCollectionIndex = 0;
        }
        else if ( isVBAEnabled() && pUnoObj->isNativeCOMObject() )
        {
            uno::Reference< script::XInvocation > xInvocation;
            if ( ( aAny >>= xInvocation ) && xInvocation.is() )
            {
                try
                {
                    p->xEnumeration = new ComEnumerationWrapper( xInvocation );
                    p->eForType = ForType::EachXEnumeration;
                }
                catch(const uno::Exception& )
                {}
            }
        }
    }

    // Container variable
    p->refVar = PopVar();
    nForLvl++;
}


void SbiRuntime::PopFor()
{
    if( pForStk )
    {
        SbiForStack* p = pForStk;
        pForStk = p->pNext;
        delete p;
        nForLvl--;
    }
}


void SbiRuntime::ClearForStack()
{
    while( pForStk )
    {
        PopFor();
    }
}

SbiForStack* SbiRuntime::FindForStackItemForCollection( class BasicCollection const * pCollection )
{
    for (SbiForStack *p = pForStk; p; p = p->pNext)
    {
        SbxVariable* pVar = p->refEnd.is() ? p->refEnd.get() : nullptr;
        if( p->eForType == ForType::EachCollection
         && pVar != nullptr
         && dynamic_cast<BasicCollection*>( pVar) == pCollection  )
        {
            return p;
        }
    }

    return nullptr;
}


//  DLL-calls

void SbiRuntime::DllCall
    ( std::u16string_view aFuncName,
      std::u16string_view aDLLName,
      SbxArray* pArgs,          // parameter (from index 1, can be NULL)
      SbxDataType eResType,     // return value
      bool bCDecl )         // true: according to C-conventions
{
    SbxVariable* pRes = new SbxVariable( eResType );
    SbiDllMgr* pDllMgr = pInst->GetDllMgr();
    ErrCode nErr = pDllMgr->Call( aFuncName, aDLLName, pArgs, *pRes, bCDecl );
    if( nErr )
    {
        Error( nErr );
    }
    PushVar( pRes );
}

bool SbiRuntime::IsImageFlag( SbiImageFlags n ) const
{
    return pImg->IsFlag( n );
}

sal_uInt16 SbiRuntime::GetBase() const
{
    return pImg->GetBase();
}

void SbiRuntime::StepNOP()
{}

void SbiRuntime::StepArith( SbxOperator eOp )
{
    SbxVariableRef p1 = PopVar();
    TOSMakeTemp();
    SbxVariable* p2 = GetTOS();

    // tdf#144353 - do not compute any operation with a missing optional variable
    if ((p1->GetType() == SbxERROR && IsMissing(p1.get(), 1))
        || (p2->GetType() == SbxERROR && IsMissing(p2, 1)))
    {
        Error(ERRCODE_BASIC_NOT_OPTIONAL);
        return;
    }

    p2->ResetFlag( SbxFlagBits::Fixed );
    p2->Compute( eOp, *p1 );

    checkArithmeticOverflow( p2 );
}

void SbiRuntime::StepUnary( SbxOperator eOp )
{
    TOSMakeTemp();
    SbxVariable* p = GetTOS();
    // tdf#144353 - do not compute any operation with a missing optional variable
    if (p->GetType() == SbxERROR && IsMissing(p, 1))
    {
        Error(ERRCODE_BASIC_NOT_OPTIONAL);
        return;
    }
    p->Compute( eOp, *p );
}

void SbiRuntime::StepCompare( SbxOperator eOp )
{
    SbxVariableRef p1 = PopVar();
    SbxVariableRef p2 = PopVar();

    // tdf#144353 - do not compare a missing optional variable
    if ((p1->GetType() == SbxERROR && SbiRuntime::IsMissing(p1.get(), 1))
        || (p2->GetType() == SbxERROR && SbiRuntime::IsMissing(p2.get(), 1)))
    {
        SbxBase::SetError(ERRCODE_BASIC_NOT_OPTIONAL);
        return;
    }

    // Make sure objects with default params have
    // values ( and type ) set as appropriate
    SbxDataType p1Type = p1->GetType();
    SbxDataType p2Type = p2->GetType();
    if ( p1Type == SbxEMPTY )
    {
        p1->Broadcast( SfxHintId::BasicDataWanted );
        p1Type = p1->GetType();
    }
    if ( p2Type == SbxEMPTY )
    {
        p2->Broadcast( SfxHintId::BasicDataWanted );
        p2Type = p2->GetType();
    }
    if ( p1Type == p2Type )
    {
        // if both sides are an object and have default props
        // then we need to use the default props
        // we don't need to worry if only one side ( lhs, rhs ) is an
        // object ( object side will get coerced to correct type in
        // Compare )
        if ( p1Type ==  SbxOBJECT )
        {
            SbxVariable* pDflt = getDefaultProp( p1.get() );
            if ( pDflt )
            {
                p1 = pDflt;
                p1->Broadcast( SfxHintId::BasicDataWanted );
            }
            pDflt = getDefaultProp( p2.get() );
            if ( pDflt )
            {
                p2 = pDflt;
                p2->Broadcast( SfxHintId::BasicDataWanted );
            }
        }

    }
    static SbxVariable* pTRUE = nullptr;
    static SbxVariable* pFALSE = nullptr;
    // why do this on non-windows ?
    // why do this at all ?
    // I dumbly follow the pattern :-/
    if ( bVBAEnabled && ( p1->IsNull() || p2->IsNull() ) )
    {
        static SbxVariable* pNULL = []() {
            SbxVariable* p = new SbxVariable;
            p->PutNull();
            p->AddFirstRef();
            return p;
        }();
        PushVar( pNULL );
    }
    else if( p2->Compare( eOp, *p1 ) )
    {
        if( !pTRUE )
        {
            pTRUE = new SbxVariable;
            pTRUE->PutBool( true );
            pTRUE->AddFirstRef();
        }
        PushVar( pTRUE );
    }
    else
    {
        if( !pFALSE )
        {
            pFALSE = new SbxVariable;
            pFALSE->PutBool( false );
            pFALSE->AddFirstRef();
        }
        PushVar( pFALSE );
    }
}

void SbiRuntime::StepEXP()      { StepArith( SbxEXP );      }
void SbiRuntime::StepMUL()      { StepArith( SbxMUL );      }
void SbiRuntime::StepDIV()      { StepArith( SbxDIV );      }
void SbiRuntime::StepIDIV()     { StepArith( SbxIDIV );     }
void SbiRuntime::StepMOD()      { StepArith( SbxMOD );      }
void SbiRuntime::StepPLUS()     { StepArith( SbxPLUS );     }
void SbiRuntime::StepMINUS()        { StepArith( SbxMINUS );    }
void SbiRuntime::StepCAT()      { StepArith( SbxCAT );      }
void SbiRuntime::StepAND()      { StepArith( SbxAND );      }
void SbiRuntime::StepOR()       { StepArith( SbxOR );       }
void SbiRuntime::StepXOR()      { StepArith( SbxXOR );      }
void SbiRuntime::StepEQV()      { StepArith( SbxEQV );      }
void SbiRuntime::StepIMP()      { StepArith( SbxIMP );      }

void SbiRuntime::StepNEG()      { StepUnary( SbxNEG );      }
void SbiRuntime::StepNOT()      { StepUnary( SbxNOT );      }

void SbiRuntime::StepEQ()       { StepCompare( SbxEQ );     }
void SbiRuntime::StepNE()       { StepCompare( SbxNE );     }
void SbiRuntime::StepLT()       { StepCompare( SbxLT );     }
void SbiRuntime::StepGT()       { StepCompare( SbxGT );     }
void SbiRuntime::StepLE()       { StepCompare( SbxLE );     }
void SbiRuntime::StepGE()       { StepCompare( SbxGE );     }

namespace
{
    OUString VBALikeToRegexp(std::u16string_view sIn)
    {
        OUStringBuffer sResult("\\A"); // Match at the beginning of the input

        for (auto start = sIn.begin(), end = sIn.end(); start < end;)
        {
            switch (auto ch = *start++)
            {
            case '?':
                sResult.append('.');
                break;
            case '*':
                sResult.append(".*");
                break;
            case '#':
                sResult.append("[0-9]");
                break;
            case '[':
                sResult.append(ch);
                if (start < end)
                {
                    if (*start == '!')
                    {
                        sResult.append('^');
                        ++start;
                    }
                    else if (*start == '^')
                        sResult.append('\\');
                }
                for (bool seenright = false; start < end && !seenright; ++start)
                {
                    switch (*start)
                    {
                    case '[':
                    case '\\':
                        sResult.append('\\');
                        break;
                    case ']':
                        seenright = true;
                        break;
                    }
                    sResult.append(*start);
                }
                break;
            case '.':
            case '^':
            case '$':
            case '+':
            case '\\':
            case '|':
            case '{':
            case '}':
            case '(':
            case ')':
                sResult.append('\\');
                [[fallthrough]];
            default:
                sResult.append(ch);
            }
        }

        sResult.append("\\z"); // Match if the current position is at the end of input

        return sResult.makeStringAndClear();
    }
}

void SbiRuntime::StepLIKE()
{
    SbxVariableRef refVar1 = PopVar();
    SbxVariableRef refVar2 = PopVar();

    OUString value = refVar2->GetOUString();
    OUString regex = VBALikeToRegexp(refVar1->GetOUString());

    bool bTextMode(true);
    bool bCompatibility = ( GetSbData()->pInst && GetSbData()->pInst->IsCompatibility() );
    if( bCompatibility )
    {
        bTextMode = IsImageFlag( SbiImageFlags::COMPARETEXT );
    }
    uint32_t searchFlags = UREGEX_UWORD | UREGEX_DOTALL; // Dot matches newline
    if( bTextMode )
    {
        searchFlags |= UREGEX_CASE_INSENSITIVE;
    }

    static uint32_t cachedSearchFlags = 0;
    static OUString cachedRegex;
    static std::optional<icu::RegexMatcher> oRegexMatcher;
    UErrorCode nIcuErr = U_ZERO_ERROR;
    if (regex != cachedRegex || searchFlags != cachedSearchFlags || !oRegexMatcher)
    {
        cachedRegex = regex;
        cachedSearchFlags = searchFlags;
        icu::UnicodeString sRegex(falsereinterpret_cast<const UChar*>(cachedRegex.getStr()),
                                  cachedRegex.getLength());
        oRegexMatcher.emplace(sRegex, cachedSearchFlags, nIcuErr);
        if (U_FAILURE(nIcuErr))
        {
            // Bad regex; oRegexMatcher has no pattern - would crash in RegexMatcher::reset
            oRegexMatcher.reset();
            return Error(ERRCODE_BASIC_BAD_PATTERN);
        }
    }

    icu::UnicodeString sSource(falsereinterpret_cast<const UChar*>(value.getStr()),
                               value.getLength());
    oRegexMatcher->reset(sSource);

    bool bRes = oRegexMatcher->matches(nIcuErr);
    if (nIcuErr)
    {
        Error(ERRCODE_BASIC_INTERNAL_ERROR);
    }
    SbxVariable* pRes = new SbxVariable;
    pRes->PutBool( bRes );

    PushVar( pRes );
}

// TOS and TOS-1 are both object variables and contain the same pointer

void SbiRuntime::StepIS()
{
    SbxVariableRef refVar1 = PopVar();
    SbxVariableRef refVar2 = PopVar();

    SbxDataType eType1 = refVar1->GetType();
    SbxDataType eType2 = refVar2->GetType();
    if ( eType1 == SbxEMPTY )
    {
        refVar1->Broadcast( SfxHintId::BasicDataWanted );
        eType1 = refVar1->GetType();
    }
    if ( eType2 == SbxEMPTY )
    {
        refVar2->Broadcast( SfxHintId::BasicDataWanted );
        eType2 = refVar2->GetType();
    }

    bool bRes = ( eType1 == SbxOBJECT && eType2 == SbxOBJECT );
    if ( bVBAEnabled  && !bRes )
    {
        Error( ERRCODE_BASIC_INVALID_USAGE_OBJECT );
    }
    bRes = ( bRes && refVar1->GetObject() == refVar2->GetObject() );
    SbxVariable* pRes = new SbxVariable;
    pRes->PutBool( bRes );
    PushVar( pRes );
}

// update the value of TOS

void SbiRuntime::StepGET()
{
    SbxVariable* p = GetTOS();
    p->Broadcast( SfxHintId::BasicDataWanted );
}

// #67607 copy Uno-Structs
static bool checkUnoStructCopy( bool bVBA, SbxVariableRef const & refVal, SbxVariableRef const & refVar )
{
    SbxDataType eVarType = refVar->GetType();
    SbxDataType eValType = refVal->GetType();

    // tdf#144353 - do not assign a missing optional variable to a property
    if (refVal->GetType() == SbxERROR && SbiRuntime::IsMissing(refVal.get(), 1))
    {
        SbxBase::SetError(ERRCODE_BASIC_NOT_OPTIONAL);
        return true;
    }

    if ( ( bVBA && ( eVarType == SbxEMPTY ) ) || !refVar->CanWrite() )
        return false;

    if ( eValType != SbxOBJECT )
        return false;
    // we seem to be duplicating parts of SbxValue=operator, maybe we should just move this to
    // there :-/ not sure if for every '=' we would want struct handling
    if( eVarType != SbxOBJECT )
    {
        if ( refVar->IsFixed() )
            return false;
    }
    // #115826: Exclude ProcedureProperties to avoid call to Property Get procedure
    else ifdynamic_cast<const SbProcedureProperty*>( refVar.get() ) != nullptr )
        return false;

    SbxObjectRef xValObj = static_cast<SbxObject*>(refVal->GetObject());
    if( !xValObj.is() || dynamic_cast<const SbUnoAnyObject*>( xValObj.get() ) != nullptr )
        return false;

    SbUnoObject* pUnoVal =  dynamic_cast<SbUnoObject*>( xValObj.get() );
    SbUnoStructRefObject* pUnoStructVal = dynamic_cast<SbUnoStructRefObject*>( xValObj.get() );
    Any aAny;
    // make doubly sure value is either a Uno object or
    // a uno struct
    if ( pUnoVal || pUnoStructVal )
        aAny = pUnoVal ? pUnoVal->getUnoAny() : pUnoStructVal->getUnoAny();
    else
        return false;
    if (  aAny.getValueTypeClass() != TypeClass_STRUCT )
        return false;

    refVar->SetType( SbxOBJECT );
    ErrCode eOldErr = SbxBase::GetError();
    // There are some circumstances when calling GetObject
    // will trigger an error, we need to squash those here.
    // Alternatively it is possible that the same scenario
    // could overwrite and existing error. Let's prevent that
    SbxObjectRef xVarObj = static_cast<SbxObject*>(refVar->GetObject());
    if ( eOldErr != ERRCODE_NONE )
        SbxBase::SetError( eOldErr );
    else
        SbxBase::ResetError();

    SbUnoStructRefObject* pUnoStructObj = dynamic_cast<SbUnoStructRefObject*>( xVarObj.get() );

    OUString sClassName = pUnoVal ? pUnoVal->GetClassName() : pUnoStructVal->GetClassName();
    OUString sName = pUnoVal ? pUnoVal->GetName() : pUnoStructVal->GetName();

    if ( pUnoStructObj )
    {
        StructRefInfo aInfo = pUnoStructObj->getStructInfo();
        aInfo.setValue( aAny );
    }
    else
    {
        SbUnoObject* pNewUnoObj = new SbUnoObject( sName, aAny );
        // #70324: adopt ClassName
        pNewUnoObj->SetClassName( sClassName );
        refVar->PutObject( pNewUnoObj );
    }
    return true;
}


// laying down TOS in TOS-1

void SbiRuntime::StepPUT()
{
    SbxVariableRef refVal = PopVar();
    SbxVariableRef refVar = PopVar();
    // store on its own method (inside a function)?
    bool bFlagsChanged = false;
    SbxFlagBits n = SbxFlagBits::NONE;
    if( refVar.get() == pMeth )
    {
        bFlagsChanged = true;
        n = refVar->GetFlags();
        refVar->SetFlag( SbxFlagBits::Write );
    }

    // if left side arg is an object or variant and right handside isn't
    // either an object or a variant then try and see if a default
    // property exists.
    // to use e.g. Range{"A1") = 34
    // could equate to Range("A1").Value = 34
    if ( bVBAEnabled )
    {
        // yet more hacking at this, I feel we don't quite have the correct
        // heuristics for dealing with obj1 = obj2 ( where obj2 ( and maybe
        // obj1 ) has default member/property ) ) It seems that default props
        // aren't dealt with if the object is a member of some parent object
        bool bObjAssign = false;
        if ( refVar->GetType() == SbxEMPTY )
            refVar->Broadcast( SfxHintId::BasicDataWanted );
        if ( refVar->GetType() == SbxOBJECT )
        {
            if  ( dynamic_cast<const SbxMethod *>(refVar.get()) != nullptr || ! refVar->GetParent() )
            {
                SbxVariable* pDflt = getDefaultProp( refVar.get() );

                if ( pDflt )
                    refVar = pDflt;
            }
            else
                bObjAssign = true;
        }
        if (  refVal->GetType() == SbxOBJECT  && !bObjAssign && ( dynamic_cast<const SbxMethod *>(refVal.get()) != nullptr || ! refVal->GetParent() ) )
        {
            SbxVariable* pDflt = getDefaultProp( refVal.get() );
            if ( pDflt )
                refVal = pDflt;
        }
    }

    if ( !checkUnoStructCopy( bVBAEnabled, refVal, refVar ) )
        *refVar = *refVal;

    if( bFlagsChanged )
        refVar->SetFlags( n );
}

namespace {

// VBA Dim As New behavior handling, save init object information
struct DimAsNewRecoverItem
{
    OUString        m_aObjClass;
    OUString        m_aObjName;
    SbxObject*      m_pObjParent;
    SbModule*       m_pClassModule;

    DimAsNewRecoverItem()
        : m_pObjParent( nullptr )
        , m_pClassModule( nullptr )
    {}

    DimAsNewRecoverItem( OUString aObjClass, OUString aObjName,
                         SbxObject* pObjParent, SbModule* pClassModule )
            : m_aObjClass(std::move( aObjClass ))
            , m_aObjName(std::move( aObjName ))
            , m_pObjParent( pObjParent )
            , m_pClassModule( pClassModule )
    {}

};


struct SbxVariablePtrHash
{
    size_t operator()( SbxVariable* pVar ) const
        { return reinterpret_cast<size_t>(pVar); }
};

}

typedef std::unordered_map< SbxVariable*, DimAsNewRecoverItem,
                              SbxVariablePtrHash >  DimAsNewRecoverHash;

namespace {

DimAsNewRecoverHash gaDimAsNewRecoverHash;

}

void removeDimAsNewRecoverItem( SbxVariable* pVar )
{
    DimAsNewRecoverHash::iterator it = gaDimAsNewRecoverHash.find( pVar );
    if( it != gaDimAsNewRecoverHash.end() )
    {
        gaDimAsNewRecoverHash.erase( it );
    }
}


// saving object variable
// not-object variables will cause errors

constexpr OUString pCollectionStr = u"Collection"_ustr;

void SbiRuntime::StepSET_Impl( SbxVariableRef& refVal, SbxVariableRef& refVarbool bHandleDefaultProp )
{
    // #67733 types with array-flag are OK too

    // Check var, !object is no error for sure if, only if type is fixed
    SbxDataType eVarType = refVar->GetType();
    if( !bHandleDefaultProp && eVarType != SbxOBJECT && !(eVarType & SbxARRAY) && refVar->IsFixed() )
    {
        Error( ERRCODE_BASIC_INVALID_USAGE_OBJECT );
        return;
    }

    // Check value, !object is no error for sure if, only if type is fixed
    SbxDataType eValType = refVal->GetType();
    if( !bHandleDefaultProp && eValType != SbxOBJECT && !(eValType & SbxARRAY) && refVal->IsFixed() )
    {
        Error( ERRCODE_BASIC_INVALID_USAGE_OBJECT );
        return;
    }

    // Getting in here causes problems with objects with default properties
    // if they are SbxEMPTY I guess
    if ( !bHandleDefaultProp || eValType == SbxOBJECT )
    {
    // activate GetObject for collections on refVal
        SbxBase* pObjVarObj = refVal->GetObject();
        if( pObjVarObj )
        {
            SbxVariableRef refObjVal = dynamic_cast<SbxObject*>( pObjVarObj );

            if( refObjVal.is() )
            {
                refVal = std::move(refObjVal);
            }
            else if( !(eValType & SbxARRAY) )
            {
                refVal = nullptr;
            }
        }
    }

    // #52896 refVal can be invalid here, if uno-sequences - or more
    // general arrays - are assigned to variables that are declared
    // as an object!
    if( !refVal.is() )
    {
        Error( ERRCODE_BASIC_INVALID_USAGE_OBJECT );
    }
    else
    {
        bool bFlagsChanged = false;
        SbxFlagBits n = SbxFlagBits::NONE;
        if( refVar.get() == pMeth )
        {
            bFlagsChanged = true;
            n = refVar->GetFlags();
            refVar->SetFlag( SbxFlagBits::Write );
        }
        SbProcedureProperty* pProcProperty = dynamic_cast<SbProcedureProperty*>( refVar.get() );
        if( pProcProperty )
        {
            pProcProperty->setSet( true );
        }
        if ( bHandleDefaultProp )
        {
            // get default properties for lhs & rhs where necessary
            // SbxVariable* defaultProp = NULL; unused variable
            // LHS try determine if a default prop exists
            // again like in StepPUT (see there too ) we are tweaking the
            // heuristics again for when to assign an object reference or
            // use default members if they exist
            // #FIXME we really need to get to the bottom of this mess
            bool bObjAssign = false;
            if ( refVar->GetType() == SbxOBJECT )
            {
                if ( dynamic_cast<const SbxMethod *>(refVar.get()) != nullptr || ! refVar->GetParent() )
                {
                    SbxVariable* pDflt = getDefaultProp( refVar.get() );
                    if ( pDflt )
                    {
                        refVar = pDflt;
                    }
                }
                else
                    bObjAssign = true;
            }
            // RHS only get a default prop is the rhs has one
            if (  refVal->GetType() == SbxOBJECT )
            {
                // check if lhs is a null object
                // if it is then use the object not the default property
                SbxObject* pObj = dynamic_cast<SbxObject*>( refVar.get() );

                // calling GetObject on a SbxEMPTY variable raises
                // object not set errors, make sure it's an Object
                if ( !pObj && refVar->GetType() == SbxOBJECT )
                {
                    SbxBase* pObjVarObj = refVar->GetObject();
                    pObj = dynamic_cast<SbxObject*>( pObjVarObj );
                }
                SbxVariable* pDflt = nullptr;
                if ( pObj && !bObjAssign )
                {
                    // lhs is either a valid object || or has a defaultProp
                    pDflt = getDefaultProp( refVal.get() );
                }
                if ( pDflt )
                {
                    refVal = pDflt;
                }
            }
        }

        // Handle Dim As New
        bool bDimAsNew = bVBAEnabled && refVar->IsSet( SbxFlagBits::DimAsNew );
        SbxBaseRef xPrevVarObj;
        if( bDimAsNew )
        {
            xPrevVarObj = refVar->GetObject();
        }
        // Handle withevents
        bool bWithEvents = refVar->IsSet( SbxFlagBits::WithEvents );
        if ( bWithEvents )
        {
            Reference< XInterface > xComListener;

            SbxBase* pObj = refVal->GetObject();
            SbUnoObject* pUnoObj = dynamic_cast<SbUnoObject*>( pObj );
            if( pUnoObj != nullptr )
            {
                Any aControlAny = pUnoObj->getUnoAny();
                OUString aDeclareClassName = refVar->GetDeclareClassName();
                OUString aPrefix = refVar->GetName();
                SbxObjectRef xScopeObj = refVar->GetParent();
                xComListener = createComListener( aControlAny, aDeclareClassName, aPrefix, xScopeObj );

                refVal->SetDeclareClassName( aDeclareClassName );
                refVal->SetComListener( xComListener, &rBasic );        // Hold reference
            }

        }

        // lhs is a property who's value is currently (Empty e.g. no broadcast yet)
        // in this case if there is a default prop involved the value of the
        // default property may in fact be void so the type will also be SbxEMPTY
        // in this case we do not want to call checkUnoStructCopy 'cause that will
        // cause an error also
        if ( !checkUnoStructCopy( bHandleDefaultProp, refVal, refVar ) )
        {
            *refVar = *refVal;
        }
        if ( bDimAsNew )
        {
            ifdynamic_cast<const SbxObject*>( refVar.get() ) == nullptr )
            {
                SbxBase* pValObjBase = refVal->GetObject();
                if( pValObjBase == nullptr )
                {
                    if( xPrevVarObj.is() )
                    {
                        // Object is overwritten with NULL, instantiate init object
                        DimAsNewRecoverHash::iterator it = gaDimAsNewRecoverHash.find( refVar.get() );
                        if( it != gaDimAsNewRecoverHash.end() )
                        {
                            const DimAsNewRecoverItem& rItem = it->second;
                            if( rItem.m_pClassModule != nullptr )
                            {
                                SbClassModuleObject* pNewObj = new SbClassModuleObject(*rItem.m_pClassModule);
                                pNewObj->SetName( rItem.m_aObjName );
                                pNewObj->SetParent( rItem.m_pObjParent );
                                refVar->PutObject( pNewObj );
                            }
                            else if( rItem.m_aObjClass.equalsIgnoreAsciiCase( pCollectionStr ) )
                            {
                                BasicCollection* pNewCollection = new BasicCollection( pCollectionStr );
                                pNewCollection->SetName( rItem.m_aObjName );
                                pNewCollection->SetParent( rItem.m_pObjParent );
                                refVar->PutObject( pNewCollection );
                            }
                        }
                    }
                }
                else
                {
                    // Does old value exist?
                    bool bFirstInit = !xPrevVarObj.is();
                    if( bFirstInit )
                    {
                        // Store information to instantiate object later
                        SbxObject* pValObj = dynamic_cast<SbxObject*>( pValObjBase );
                        if( pValObj != nullptr )
                        {
                            OUString aObjClass = pValObj->GetClassName();

                            SbClassModuleObject* pClassModuleObj = dynamic_cast<SbClassModuleObject*>( pValObjBase );
                            if( pClassModuleObj != nullptr )
                            {
                                SbModule& rClassModule = pClassModuleObj->getClassModule();
                                gaDimAsNewRecoverHash[refVar.get()] =
                                    DimAsNewRecoverItem( aObjClass, pValObj->GetName(), pValObj->GetParent(), &rClassModule );
                            }
                            else if( aObjClass.equalsIgnoreAsciiCase( "Collection" ) )
                            {
                                gaDimAsNewRecoverHash[refVar.get()] =
                                    DimAsNewRecoverItem( aObjClass, pValObj->GetName(), pValObj->GetParent(), nullptr );
                            }
                        }
                    }
                }
            }
        }

        if( bFlagsChanged )
        {
            refVar->SetFlags( n );
        }
    }
}

void SbiRuntime::StepSET()
{
    SbxVariableRef refVal = PopVar();
    SbxVariableRef refVar = PopVar();
    StepSET_Impl( refVal, refVar, bVBAEnabled ); // this is really assignment
}

void SbiRuntime::StepVBASET()
{
--> --------------------

--> maximum size reached

--> --------------------

95%


¤ Dauer der Verarbeitung: 0.25 Sekunden  ¤

*© Formatika GbR, Deutschland






Wurzel

Suchen

Beweissystem der NASA

Beweissystem Isabelle

NIST Cobol Testsuite

Cephes Mathematical Library

Wiener Entwicklungsmethode

Haftungshinweis

Die Informationen auf dieser Webseite wurden nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit, noch Qualität der bereit gestellten Informationen zugesichert.

Bemerkung:

Die farbliche Syntaxdarstellung ist noch experimentell.