<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9c_mi_scom.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed 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                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9c_mi_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_7 = 7;
constexpr uint64_t literal_16 = 16;
constexpr uint64_t literal_8 = 8;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_0x19 = 0x19;
constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_0b0000000000001000000 = 0b0000000000001000000;
constexpr uint64_t literal_0b0000000000001000 = 0b0000000000001000;
constexpr uint64_t literal_0b01 = 0b01;
constexpr uint64_t literal_5 = 5;

fapi2::ReturnCode p9c_mi_scom(const fapi2::Target<fapi2::TARGET_TYPE_MI>& TGT0,
                              const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
    {
        uint64_t l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC = literal_1;
        uint64_t l_def_ENABLE_DYNAMIC_64_128B_READS = literal_0;
        uint64_t l_def_ENABLE_ECRESP = literal_1;
        uint64_t l_def_ENABLE_AMO_CACHING = literal_1;
        uint64_t l_def_ENABLE_MCU_TIMEOUTS = literal_1;
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010810ull, l_scom_buffer ));

            l_scom_buffer.insert<46, 4, 60, uint64_t>(literal_7 );
            l_scom_buffer.insert<50, 5, 59, uint64_t>(literal_16 );
            l_scom_buffer.insert<55, 6, 58, uint64_t>(literal_8 );

            if ((l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON = 0x1;
                l_scom_buffer.insert<61, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON );
            }

            if ((l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC == literal_1))
            {
                l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_0x19 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010810ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010811ull, l_scom_buffer ));

            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_PERFMON_COMMAND_OFF = 0x0;
            l_scom_buffer.insert<48, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_PERFMON_COMMAND_OFF );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_EMERGENCY_THROTTLE_ON = 0x1;
            l_scom_buffer.insert<21, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_EMERGENCY_THROTTLE_ON );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_CHECKSTOP_COMMAND_ON = 0x1;
            l_scom_buffer.insert<22, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_CHECKSTOP_COMMAND_ON );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_TRACESTOP_COMMAND_ON = 0x1;
            l_scom_buffer.insert<23, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_TRACESTOP_COMMAND_ON );

            if ((l_def_ENABLE_DYNAMIC_64_128B_READS == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON = 0x1;
                l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON );
            }
            else if ((l_def_ENABLE_DYNAMIC_64_128B_READS == literal_0))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_OFF = 0x0;
                l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_OFF );
            }

            if ((l_def_ENABLE_ECRESP == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_ON = 0x1;
                l_scom_buffer.insert<7, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_ON );
            }

            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ASYNC_MODE_ON = 0x1;
            l_scom_buffer.insert<6, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ASYNC_MODE_ON );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5010811ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010812ull, l_scom_buffer ));

            l_scom_buffer.insert<33, 19, 45, uint64_t>(literal_0b0000000000001000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5010812ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer ));

            if ((l_def_ENABLE_AMO_CACHING == literal_1))
            {
                l_scom_buffer.insert<24, 16, 48, uint64_t>(literal_0b0000000000001000 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x501081bull, l_scom_buffer ));

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_SELECT_PB_HANG_PULSE_ON = 0x1;
                l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_SELECT_PB_HANG_PULSE_ON );
            }

            constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_SELECT_LOCAL_HANG_PULSE_OFF = 0x0;
            l_scom_buffer.insert<1, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_SELECT_LOCAL_HANG_PULSE_OFF );

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_NONMIRROR_HANG_ON = 0x1;
                l_scom_buffer.insert<32, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_NONMIRROR_HANG_ON );
            }

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_MIRROR_HANG_ON = 0x1;
                l_scom_buffer.insert<33, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_MIRROR_HANG_ON );
            }

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_APO_HANG_ON = 0x1;
                l_scom_buffer.insert<34, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_APO_HANG_ON );
            }

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_CLIB_HANG_ON = 0x1;
                l_scom_buffer.insert<35, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_CLIB_HANG_ON );
            }

            l_scom_buffer.insert<2, 2, 62, uint64_t>(literal_0b01 );

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                l_scom_buffer.insert<24, 8, 56, uint64_t>(literal_1 );
            }

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                l_scom_buffer.insert<5, 3, 61, uint64_t>(literal_7 );
            }

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                l_scom_buffer.insert<37, 3, 61, uint64_t>(literal_5 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x501081bull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>p9c.mi.scom.initfile -- default to block all sync pipelines<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9c_mi_scom.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed 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                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9c_mi_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_7 = 7;
constexpr uint64_t literal_16 = 16;
constexpr uint64_t literal_8 = 8;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_0x19 = 0x19;
constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_0b0000000000001000000 = 0b0000000000001000000;
constexpr uint64_t literal_0b0000000000001000 = 0b0000000000001000;
constexpr uint64_t literal_0b01 = 0b01;
constexpr uint64_t literal_5 = 5;

fapi2::ReturnCode p9c_mi_scom(const fapi2::Target<fapi2::TARGET_TYPE_MI>& TGT0,
                              const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
    {
        uint64_t l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC = literal_1;
        uint64_t l_def_ENABLE_DYNAMIC_64_128B_READS = literal_0;
        uint64_t l_def_ENABLE_ECRESP = literal_1;
        uint64_t l_def_ENABLE_AMO_CACHING = literal_1;
        uint64_t l_def_ENABLE_MCU_TIMEOUTS = literal_1;
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010810ull, l_scom_buffer ));

            l_scom_buffer.insert<46, 4, 60, uint64_t>(literal_7 );
            l_scom_buffer.insert<50, 5, 59, uint64_t>(literal_16 );
            l_scom_buffer.insert<55, 6, 58, uint64_t>(literal_8 );

            if ((l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON = 0x1;
                l_scom_buffer.insert<61, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON );
            }

            if ((l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC == literal_1))
            {
                l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_0x19 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010810ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010811ull, l_scom_buffer ));

            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_DISABLE_MC_SYNC_ON = 0x1;
            l_scom_buffer.insert<27, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_DISABLE_MC_SYNC_ON );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_DISABLE_MC_PAIR_SYNC_ON = 0x1;
            l_scom_buffer.insert<28, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_DISABLE_MC_PAIR_SYNC_ON );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_PERFMON_COMMAND_OFF = 0x0;
            l_scom_buffer.insert<48, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_PERFMON_COMMAND_OFF );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_EMERGENCY_THROTTLE_ON = 0x1;
            l_scom_buffer.insert<21, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_EMERGENCY_THROTTLE_ON );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_CHECKSTOP_COMMAND_ON = 0x1;
            l_scom_buffer.insert<22, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_CHECKSTOP_COMMAND_ON );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_TRACESTOP_COMMAND_ON = 0x1;
            l_scom_buffer.insert<23, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_TRACESTOP_COMMAND_ON );

            if ((l_def_ENABLE_DYNAMIC_64_128B_READS == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON = 0x1;
                l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON );
            }
            else if ((l_def_ENABLE_DYNAMIC_64_128B_READS == literal_0))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_OFF = 0x0;
                l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_OFF );
            }

            if ((l_def_ENABLE_ECRESP == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_ON = 0x1;
                l_scom_buffer.insert<7, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_ON );
            }

            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ASYNC_MODE_ON = 0x1;
            l_scom_buffer.insert<6, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ASYNC_MODE_ON );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5010811ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010812ull, l_scom_buffer ));

            l_scom_buffer.insert<33, 19, 45, uint64_t>(literal_0b0000000000001000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5010812ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer ));

            if ((l_def_ENABLE_AMO_CACHING == literal_1))
            {
                l_scom_buffer.insert<24, 16, 48, uint64_t>(literal_0b0000000000001000 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x501081bull, l_scom_buffer ));

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_SELECT_PB_HANG_PULSE_ON = 0x1;
                l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_SELECT_PB_HANG_PULSE_ON );
            }

            constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_SELECT_LOCAL_HANG_PULSE_OFF = 0x0;
            l_scom_buffer.insert<1, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_SELECT_LOCAL_HANG_PULSE_OFF );

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_NONMIRROR_HANG_ON = 0x1;
                l_scom_buffer.insert<32, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_NONMIRROR_HANG_ON );
            }

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_MIRROR_HANG_ON = 0x1;
                l_scom_buffer.insert<33, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_MIRROR_HANG_ON );
            }

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_APO_HANG_ON = 0x1;
                l_scom_buffer.insert<34, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_APO_HANG_ON );
            }

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_CLIB_HANG_ON = 0x1;
                l_scom_buffer.insert<35, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_CLIB_HANG_ON );
            }

            l_scom_buffer.insert<2, 2, 62, uint64_t>(literal_0b01 );

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                l_scom_buffer.insert<24, 8, 56, uint64_t>(literal_1 );
            }

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                l_scom_buffer.insert<5, 3, 61, uint64_t>(literal_7 );
            }

            if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1))
            {
                l_scom_buffer.insert<37, 3, 61, uint64_t>(literal_5 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x501081bull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_pll_setup.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed 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                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_mem_pll_setup.C
///
/// @brief setup PLL for MBAs
//------------------------------------------------------------------------------
// *HWP HW Owner        : Anusha Reddy Rangareddygari <anusrang@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : Sunil Kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 3
// *HWP Consumed by     : HB
//------------------------------------------------------------------------------

//## auto_generated
#include "p9_mem_pll_setup.H"

#include "p9_perv_scom_addresses.H"
#include <p9_perv_scom_addresses_fld.H>

enum P9_MEM_PLL_SETUP_Private_Constants
{
    NS_DELAY = 5000000, // unit is nano seconds
    SIM_CYCLE_DELAY = 100000, // unit is sim cycles
    OPCG_ALIGN_SCAN_RATIO = 0b00011
};

fapi2::ReturnCode p9_mem_pll_setup(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
    uint8_t l_read_attr = 0;
    fapi2::buffer<uint64_t> l_data64;
    uint8_t l_mem_bypass;
    uint8_t l_use_dmi_buckets = 0;

    FAPI_INF("Entering ...");

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_NEST_MEM_X_O_PCI_BYPASS, i_target_chip, l_mem_bypass),
             "Error from FAPI_ATTR_GET (ATTR_NEST_MEM_X_O_PCI_BYPASS");

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MC_SYNC_MODE, i_target_chip, l_read_attr),
             "Error from FAPI_ATTR_GET (ATTR_MC_SYNC_MODE)");

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_DMI_MC_PLL_SCAN_BUCKETS, i_target_chip, l_use_dmi_buckets),
             "Error from FAPI_ATTR_GET (ATTR_CHIP_EC_FEATURE_DMI_MC_PLL_SCAN_BUCKETS)");

    if ( !l_read_attr && !l_use_dmi_buckets )
    {
        for (auto l_chplt_trgt :  i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV>
             (fapi2::TARGET_FILTER_ALL_MC, fapi2::TARGET_STATE_FUNCTIONAL))
        {
            FAPI_DBG("Drop PLDY bypass of Progdelay logic");
            l_data64.flush<1>();
            //NET_CTRL1.TP_MC_PDLY_BYPASS_EN_DC = 0
            l_data64.clearBit<PERV_1_NET_CTRL1_CLK_PDLY_BYPASS_EN>();
            FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_NET_CTRL1_WAND, l_data64));

            FAPI_DBG("Drop DCC bypass of DCC logic");
            l_data64.flush<1>();
            //NET_CTRL1.TP_MC_PDLY_BYPASS_EN_DC = 0
            l_data64.clearBit<PERV_1_NET_CTRL1_CLK_DCC_BYPASS_EN>();
            FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_NET_CTRL1_WAND, l_data64));

            if (l_mem_bypass == 0)
            {
                FAPI_DBG("Drop PLL test enable");
                l_data64.flush<1>();
                //NET_CTRL0.TP_PLL_TEST_EN_DC
                l_data64.clearBit<PERV_1_NET_CTRL0_PLL_TEST_EN>();
                FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_NET_CTRL0_WAND, l_data64));

                FAPI_DBG("Drop PLL reset");
                l_data64.flush<1>();
                //NET_CTRL0.TP_PLLRST_DC
                l_data64.clearBit<PERV_1_NET_CTRL0_PLL_RESET>();
                FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_NET_CTRL0_WAND, l_data64));

                fapi2::delay(NS_DELAY, SIM_CYCLE_DELAY);

                FAPI_DBG("check PLL lock");

                //Getting PLL_LOCK_REG register value
                FAPI_TRY(fapi2::getScom(l_chplt_trgt, PERV_PLL_LOCK_REG,
                                        l_data64)); //l_read_reg = PERV.PLL_LOCK_REG
                FAPI_ASSERT(l_data64.getBit<0>() == 1,
                            fapi2::PLL_LOCK_ERR()
                            .set_TARGET_CHIPLET(l_chplt_trgt)
                            .set_TARGET_CHIP(i_target_chip)
                            .set_PLL_READ(l_data64),
                            "ERROR:MEM PLL LOCK NOT SET");

                FAPI_DBG("Drop PLL Bypass");
                l_data64.flush<1>();
                //NET_CTRL0.TP_PLLBYP_DC =  0
                l_data64.clearBit<PERV_1_NET_CTRL0_PLL_BYPASS>();
                FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_NET_CTRL0_WAND, l_data64));

                //OPCG_ALIGN.scan_ratio=0b00011
                FAPI_DBG("Set scan ratio to 4:1");
                FAPI_TRY(fapi2::getScom(l_chplt_trgt, PERV_OPCG_ALIGN, l_data64));
                l_data64.insertFromRight<PERV_1_OPCG_ALIGN_SCAN_RATIO, PERV_1_OPCG_ALIGN_SCAN_RATIO_LEN>
                (OPCG_ALIGN_SCAN_RATIO);
                FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_OPCG_ALIGN, l_data64));
            }

            //Reset PCB Slave error register
            FAPI_DBG("Reset PCB Slave error register");
            l_data64 = 0xFFFFFFFFFFFFFFFF;
            FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_ERROR_REG, l_data64));

        }
    }

    FAPI_INF("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>TP, Nest FIR updates -- DD2 updates to match RAS XML<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_pll_setup.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed 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                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_mem_pll_setup.C
///
/// @brief setup PLL for MBAs
//------------------------------------------------------------------------------
// *HWP HW Owner        : Anusha Reddy Rangareddygari <anusrang@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : Sunil Kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 3
// *HWP Consumed by     : HB
//------------------------------------------------------------------------------

//## auto_generated
#include "p9_mem_pll_setup.H"

#include "p9_perv_scom_addresses.H"
#include <p9_perv_scom_addresses_fld.H>

enum P9_MEM_PLL_SETUP_Private_Constants
{
    NS_DELAY = 5000000, // unit is nano seconds
    SIM_CYCLE_DELAY = 100000, // unit is sim cycles
    OPCG_ALIGN_SCAN_RATIO = 0b00011
};

fapi2::ReturnCode p9_mem_pll_setup(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
    uint8_t l_read_attr = 0;
    fapi2::buffer<uint64_t> l_data64;
    uint8_t l_mem_bypass;
    uint8_t l_use_dmi_buckets = 0;

    FAPI_INF("Entering ...");

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_NEST_MEM_X_O_PCI_BYPASS, i_target_chip, l_mem_bypass),
             "Error from FAPI_ATTR_GET (ATTR_NEST_MEM_X_O_PCI_BYPASS");

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MC_SYNC_MODE, i_target_chip, l_read_attr),
             "Error from FAPI_ATTR_GET (ATTR_MC_SYNC_MODE)");

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_DMI_MC_PLL_SCAN_BUCKETS, i_target_chip, l_use_dmi_buckets),
             "Error from FAPI_ATTR_GET (ATTR_CHIP_EC_FEATURE_DMI_MC_PLL_SCAN_BUCKETS)");

    if ( !l_read_attr && !l_use_dmi_buckets )
    {
        for (auto l_chplt_trgt :  i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV>
             (fapi2::TARGET_FILTER_ALL_MC, fapi2::TARGET_STATE_FUNCTIONAL))
        {
            FAPI_DBG("Drop PLDY bypass of Progdelay logic");
            l_data64.flush<1>();
            //NET_CTRL1.TP_MC_PDLY_BYPASS_EN_DC = 0
            l_data64.clearBit<PERV_1_NET_CTRL1_CLK_PDLY_BYPASS_EN>();
            FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_NET_CTRL1_WAND, l_data64));

            FAPI_DBG("Drop DCC bypass of DCC logic");
            l_data64.flush<1>();
            //NET_CTRL1.TP_MC_PDLY_BYPASS_EN_DC = 0
            l_data64.clearBit<PERV_1_NET_CTRL1_CLK_DCC_BYPASS_EN>();
            FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_NET_CTRL1_WAND, l_data64));

            if (l_mem_bypass == 0)
            {
                FAPI_DBG("Drop PLL test enable");
                l_data64.flush<1>();
                //NET_CTRL0.TP_PLL_TEST_EN_DC
                l_data64.clearBit<PERV_1_NET_CTRL0_PLL_TEST_EN>();
                FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_NET_CTRL0_WAND, l_data64));

                FAPI_DBG("Drop PLL reset");
                l_data64.flush<1>();
                //NET_CTRL0.TP_PLLRST_DC
                l_data64.clearBit<PERV_1_NET_CTRL0_PLL_RESET>();
                FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_NET_CTRL0_WAND, l_data64));

                fapi2::delay(NS_DELAY, SIM_CYCLE_DELAY);

                FAPI_DBG("check PLL lock");

                //Getting PLL_LOCK_REG register value
                FAPI_TRY(fapi2::getScom(l_chplt_trgt, PERV_PLL_LOCK_REG,
                                        l_data64)); //l_read_reg = PERV.PLL_LOCK_REG
                FAPI_ASSERT(l_data64.getBit<0>() == 1,
                            fapi2::PLL_LOCK_ERR()
                            .set_TARGET_CHIPLET(l_chplt_trgt)
                            .set_TARGET_CHIP(i_target_chip)
                            .set_PLL_READ(l_data64),
                            "ERROR:MEM PLL LOCK NOT SET");

                FAPI_DBG("Drop PLL Bypass");
                l_data64.flush<1>();
                //NET_CTRL0.TP_PLLBYP_DC =  0
                l_data64.clearBit<PERV_1_NET_CTRL0_PLL_BYPASS>();
                FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_NET_CTRL0_WAND, l_data64));

                //OPCG_ALIGN.scan_ratio=0b00011
                FAPI_DBG("Set scan ratio to 4:1");
                FAPI_TRY(fapi2::getScom(l_chplt_trgt, PERV_OPCG_ALIGN, l_data64));
                l_data64.insertFromRight<PERV_1_OPCG_ALIGN_SCAN_RATIO, PERV_1_OPCG_ALIGN_SCAN_RATIO_LEN>
                (OPCG_ALIGN_SCAN_RATIO);
                FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_OPCG_ALIGN, l_data64));
            }

            //Reset PCB Slave error register
            FAPI_DBG("Reset PCB Slave error register");
            l_data64 = 0xFFFFFFFFFFFFFFFF;
            FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_ERROR_REG, l_data64));

            // unmask PLL unlock error in PCB slave configuration register
            FAPI_DBG("Unmask PLL unlock error in PCB slave");
            FAPI_TRY(fapi2::getScom(l_chplt_trgt, PERV_SLAVE_CONFIG_REG, l_data64));
            l_data64.clearBit<12>();
            FAPI_TRY(fapi2::putScom(l_chplt_trgt, PERV_SLAVE_CONFIG_REG, l_data64));

        }
    }

    FAPI_INF("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sotdata.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-04-11 20:52:54 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SOT_DATA_HXX
#define _SOT_DATA_HXX

/*************************************************************************
*************************************************************************/

#ifndef _TOOLS_SOLAR_H
#include <tools/solar.h>
#endif

#ifndef INCLUDED_SOTDLLAPI_H
#include "sot/sotdllapi.h"
#endif

//==================class SotData_Impl====================================

class List;
class SotFactory;
class SotFactoryList;
class SotObjectList;

struct SotData_Impl
{
    UINT32              nSvObjCount;
    SotObjectList *     pObjectList;
    SotFactoryList *    pFactoryList;
    SotFactory *        pSotObjectFactory;
    SotFactory *        pSotStorageStreamFactory;
    SotFactory *        pSotStorageFactory;
    List*               pDataFlavorList;
    SotData_Impl();
};

SOT_DLLPUBLIC SotData_Impl* SOTDATA();

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.42); FILE MERGED 2008/04/01 12:41:26 thb 1.2.42.2: #i85898# Stripping all external header guards 2008/03/31 12:49:57 rt 1.2.42.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: sotdata.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SOT_DATA_HXX
#define _SOT_DATA_HXX

/*************************************************************************
*************************************************************************/

#ifndef _TOOLS_SOLAR_H
#include <tools/solar.h>
#endif
#include "sot/sotdllapi.h"

//==================class SotData_Impl====================================

class List;
class SotFactory;
class SotFactoryList;
class SotObjectList;

struct SotData_Impl
{
    UINT32              nSvObjCount;
    SotObjectList *     pObjectList;
    SotFactoryList *    pFactoryList;
    SotFactory *        pSotObjectFactory;
    SotFactory *        pSotStorageStreamFactory;
    SotFactory *        pSotStorageFactory;
    List*               pDataFlavorList;
    SotData_Impl();
};

SOT_DLLPUBLIC SotData_Impl* SOTDATA();

#endif
<|endoftext|>


<commit_before>/*
 * opencog/atoms/base/Atom.cc
 *
 * Copyright (C) 2002-2007 Novamente LLC
 * All Rights Reserved
 *
 * Written by Thiago Maia <thiago@vettatech.com>
 *            Andre Senna <senna@vettalabs.com>
 *            Welter Silva <welter@vettalabs.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <set>
#include <sstream>

#ifndef WIN32
#include <unistd.h>
#endif

#include <opencog/util/misc.h>
#include <opencog/util/platform.h>

#include <opencog/atoms/base/Atom.h>
#include <opencog/atoms/proto/NameServer.h>
#include <opencog/atoms/base/Link.h>
#include <opencog/atoms/base/Node.h>

#include <opencog/atomspace/AtomSpace.h>
#include <opencog/atomspace/AtomTable.h>

//! Atom flag
#define FETCHED_RECENTLY        1  //BIT0
#define MARKED_FOR_REMOVAL      2  //BIT1
// #define MULTIPLE_TRUTH_VALUES   4  //BIT2
// #define FIRED_ACTIVATION        8  //BIT3
// #define HYPOTETHICAL_FLAG       16 //BIT4
// #define REMOVED_BY_DECAY        32 //BIT5
#define CHECKED                 64  //BIT6

//#define DPRINTF printf
#define DPRINTF(...)

#undef Type

namespace std {

// The hash of a weak pointer is just the atom type. Actually,
// it *has* to be the atom type, as otherwise the hash buckets
// won't be correct, and getIncomingByType() will fail to be fast.
opencog::Type
hash<opencog::WinkPtr>::operator()(const opencog::WinkPtr& w) const noexcept
{
    opencog::LinkPtr h(w.lock());
    if (nullptr == h) return 0;
    return h->get_type();
}

bool
equal_to<opencog::WinkPtr>::operator()(const opencog::WinkPtr& lw,
                                       const opencog::WinkPtr& rw) const noexcept
{
    opencog::Handle hl(lw.lock());
    opencog::Handle hr(rw.lock());
    return hl == hr;
}

} // namespace std

namespace opencog {

Atom::~Atom()
{
    _atom_space = nullptr;
    if (0 < getIncomingSetSize()) {
        // This can't ever possibly happen. If it does, then there is
        // some very sick bug with the reference counting that the
        // shared pointers are doing. (Or someone explcitly called the
        // destructor! Which they shouldn't do.)
        OC_ASSERT(0 == getIncomingSet().size(),
             "Atom deletion failure; incoming set not empty for %s h=%x",
             nameserver().getTypeName(_type).c_str(), get_hash());
    }
    drop_incoming_set();
}

// ==============================================================
// Whole lotta truthiness going on here.  Does it really need to be
// this complicated!?

static const Handle& truth_key(void)
{
	static Handle tk(createNode(PREDICATE_NODE, "*-TruthValueKey-*"));
	return tk;
}

void Atom::setTruthValue(const TruthValuePtr& newTV)
{
    if (nullptr == newTV) return;

    // We need to guarantee that the signal goes out with the
    // correct truth value.  That is, another setter could be changing
    // this, even as we are.  So make a copy, first.
    TruthValuePtr oldTV(getTruthValue());

    // If both old and new are e.g. DEFAULT_TV, then do nothing.
    if (oldTV.get() == newTV.get()) return;

    // ... and we still need to make sure that only one thread is
    // writing this at a time. std:shared_ptr is NOT thread-safe against
    // multiple writers: see "Example 5" in
    // http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety
    setValue (truth_key(), ProtoAtomCast(newTV));

    if (_atom_space != nullptr) {
        TVCHSigl& tvch = _atom_space->_atom_table.TVChangedSignal();
        tvch.emit(get_handle(), oldTV, newTV);
    }
}

TruthValuePtr Atom::getTruthValue() const
{
    ProtoAtomPtr pap(getValue(truth_key()));
    if (nullptr == pap) return TruthValue::DEFAULT_TV();
    return TruthValueCast(pap);
}

// ==============================================================
/// Setting values associated with this atom.
/// If the value is a null pointer, then the key is removed.
void Atom::setValue(const Handle& key, const ProtoAtomPtr& value)
{
	std::lock_guard<std::mutex> lck(_mtx);
	if (nullptr != value)
	{
		_values[key] = value;
	}
	else
	{
		// If the value is a null pointer, then the value at
		// this key should be blanked out, i.e. unset.
		_values.erase(key);
	}
}

ProtoAtomPtr Atom::getValue(const Handle& key) const
{
    // OK. The atomic thread-safety of shared-pointers is subtle. See
    // http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety
    // and http://cppwisdom.quora.com/shared_ptr-is-almost-thread-safe
    // What it boils down to here is that we must *always* make a copy
    // of the value before we use it, since it can go out of scope
    // because it can get set in another thread.  Viz, using it to
    // dereference can return a raw pointer to an object that has been
    // deconstructed.  The AtomSpaceAsyncUTest will hit this, as will
    // the multi-threaded async atom store in the SQL peristance backend.
    // Furthermore, we must make a copy while holding the lock! Got that?

    ProtoAtomPtr pap;
    std::lock_guard<std::mutex> lck(_mtx);
    auto pr = _values.find(key);
    if (_values.end() != pr) pap = pr->second;
    return pap;
}

HandleSet Atom::getKeys() const
{
    HandleSet keyset;
    std::lock_guard<std::mutex> lck(_mtx);
    for (const auto& pr : _values)
        keyset.insert(pr.first);

    return keyset;
}

void Atom::copyValues(const Handle& other)
{
    HandleSet okeys(other->getKeys());
    for (const Handle& k: okeys)
    {
        ProtoAtomPtr p = other->getValue(k);
        setValue(k, p);
    }
}

std::string Atom::valuesToString() const
{
    std::string rv;

    HandleSet keys(getKeys());
    for (const Handle& k: keys)
    {
        ProtoAtomPtr p = getValue(k);
        rv += "; key = " + k->to_string();
        rv += "; val = " + p->to_string() + "\n";
    }
    return rv;
}

// ==============================================================
// Flag stuff
bool Atom::isMarkedForRemoval() const
{
    return (_flags & MARKED_FOR_REMOVAL) != 0;
}

void Atom::unsetRemovalFlag(void)
{
    _flags &= ~MARKED_FOR_REMOVAL;
}

void Atom::markForRemoval(void)
{
    _flags |= MARKED_FOR_REMOVAL;
}

bool Atom::isChecked() const
{
    return (_flags & CHECKED) != 0;
}

void Atom::setChecked(void)
{
    _flags |= CHECKED;
}

void Atom::setUnchecked(void)
{
    _flags &= ~CHECKED;
}

// ==============================================================

void Atom::setAtomSpace(AtomSpace *tb)
{
    if (tb == _atom_space) return;

    // Either the existing _atomSpace is null, and tb is not, i.e. this
    // atom is being inserted into tb, or _atomSpace is not null, while
    // tb is null, i.e. atom is being removed from _atomSpace.  It is
    // illegal to just switch membership: one or the other of these two
    // pointers must be null.
    OC_ASSERT (nullptr == _atom_space or tb == nullptr,
               "Atom table is not null!");
    _atom_space = tb;
}

AtomTable* Atom::getAtomTable() const
{
    return &(_atom_space->_atom_table);
}

// ==============================================================
// Incoming set stuff

/// Start tracking the incoming set for this atom.
/// An atom can't know what it's incoming set is, until this method
/// is called.  If this atom is added to any links before this call
/// is made, those links won't show up in the incoming set.
///
/// We don't automatically track incoming sets for two reasons:
/// 1) std::set takes up 48 bytes
/// 2) adding and removing uses up cpu cycles.
/// Thus, if the incoming set isn't needed, then don't bother
/// tracking it.
void Atom::keep_incoming_set()
{
    if (_incoming_set) return;
    _incoming_set = std::make_shared<InSet>();
}

/// Stop tracking the incoming set for this atom.
/// After this call, the incoming set for this atom can no longer
/// be queried; it is erased.
void Atom::drop_incoming_set()
{
    if (nullptr == _incoming_set) return;
    std::lock_guard<std::mutex> lck (_mtx);
    _incoming_set->_iset.clear();
    _incoming_set = nullptr;
}

/// Add an atom to the incoming set.
void Atom::insert_atom(const LinkPtr& a)
{
    if (nullptr == _incoming_set) return;
    std::lock_guard<std::mutex> lck (_mtx);

    Type at = a->get_type();
    auto bucket = _incoming_set->_iset.find(at);
    if (bucket == _incoming_set->_iset.end())
    {
        auto pr = _incoming_set->_iset.emplace(
                   std::make_pair(at, WincomingSet()));
        bucket = pr.first;
    }
    bucket->second.insert(a);

#ifdef INCOMING_SET_SIGNALS
    _incoming_set->_addAtomSignal(shared_from_this(), a);
#endif /* INCOMING_SET_SIGNALS */
}

/// Remove an atom from the incoming set.
void Atom::remove_atom(const LinkPtr& a)
{
    if (nullptr == _incoming_set) return;
    std::lock_guard<std::mutex> lck (_mtx);
#ifdef INCOMING_SET_SIGNALS
    _incoming_set->_removeAtomSignal(shared_from_this(), a);
#endif /* INCOMING_SET_SIGNALS */
    Type at = a->get_type();
    auto bucket = _incoming_set->_iset.find(at);
    bucket->second.erase(a);
}

/// Remove old, and add new, atomically, so that every user
/// will see either one or the other, but not both/neither in
/// the incoming set. This is used to manage the StateLink.
void Atom::swap_atom(const LinkPtr& old, const LinkPtr& neu)
{
    if (nullptr == _incoming_set) return;
    std::lock_guard<std::mutex> lck (_mtx);

#ifdef INCOMING_SET_SIGNALS
    _incoming_set->_removeAtomSignal(shared_from_this(), old);
#endif /* INCOMING_SET_SIGNALS */
    Type ot = old->get_type();
    auto bucket = _incoming_set->_iset.find(ot);
    bucket->second.erase(old);

    Type nt = neu->get_type();
    bucket = _incoming_set->_iset.find(nt);
    if (bucket == _incoming_set->_iset.end())
    {
        auto pr = _incoming_set->_iset.emplace(
                   std::make_pair(nt, WincomingSet()));
        bucket = pr.first;
    }
    bucket->second.insert(neu);

#ifdef INCOMING_SET_SIGNALS
    _incoming_set->_addAtomSignal(shared_from_this(), neu);
#endif /* INCOMING_SET_SIGNALS */
}

size_t Atom::getIncomingSetSize() const
{
    if (nullptr == _incoming_set) return 0;
    std::lock_guard<std::mutex> lck (_mtx);

    size_t cnt = 0;
    for (const auto& pr : _incoming_set->_iset)
        cnt += pr.second.size();
    return cnt;
}

// We return a copy here, and not a reference, because the set itself
// is not thread-safe during reading while simultaneous insertion and
// deletion.  Besides, the incoming set is weak; we have to make it
// strong in order to hand it out.
IncomingSet Atom::getIncomingSet(AtomSpace* as) const
{
    static IncomingSet empty_set;
    if (nullptr == _incoming_set) return empty_set;

    if (as) {
        const AtomTable *atab = &as->get_atomtable();
        // Prevent update of set while a copy is being made.
        std::lock_guard<std::mutex> lck (_mtx);
        IncomingSet iset;
        for (const auto& bucket : _incoming_set->_iset)
        {
            for (const WinkPtr& w : bucket.second)
            {
                LinkPtr l(w.lock());
                if (l and atab->in_environ(l))
                    iset.emplace_back(l);
            }
        }
        return iset;
    }

    // Prevent update of set while a copy is being made.
    std::lock_guard<std::mutex> lck (_mtx);
    IncomingSet iset;
    for (const auto& bucket : _incoming_set->_iset)
    {
        for (const WinkPtr& w : bucket.second)
        {
            LinkPtr l(w.lock());
            if (l) iset.emplace_back(l);
        }
    }
    return iset;
}

IncomingSet Atom::getIncomingSetByType(Type type) const
{
    IncomingSet result;

    // The code below is mostly a cut-n-paste from the header file.
    // The only difference is that it works with LinkPtr instead of
    // Handle.  The primary issue is that casting from Handle back
    // to LinkPtr is slowwwwwww.  So we avoid that, here.
    if (nullptr == _incoming_set) return result;
    std::lock_guard<std::mutex> lck(_mtx);

    const auto bucket = _incoming_set->_iset.find(type);
    if (bucket == _incoming_set->_iset.cend()) return result;

    for (const WinkPtr& w : bucket->second)
    {
        LinkPtr h(w.lock());
        if (h) result.emplace_back(h);
    }
    return result;
}

std::string Atom::id_to_string() const
{
    return
        std::string("[") + std::to_string(get_hash()) + "]" +
        std::string("[") + (_atom_space? std::to_string(_atom_space->_atom_table.get_uuid()) : std::string("-1")) + "]";
}

std::string oc_to_string(const IncomingSet& iset, const std::string& indent)
{
	std::stringstream ss;
	ss << indent << "size = " << iset.size() << std::endl;
	for (unsigned i = 0; i < iset.size(); i++)
		ss << indent << "link[" << i << "]:" << std::endl
		   << iset[i]->to_string(indent + OC_TO_STRING_INDENT);
	return ss.str();
}

} // ~namespace opencog
<commit_msg>Minor optimization<commit_after>/*
 * opencog/atoms/base/Atom.cc
 *
 * Copyright (C) 2002-2007 Novamente LLC
 * All Rights Reserved
 *
 * Written by Thiago Maia <thiago@vettatech.com>
 *            Andre Senna <senna@vettalabs.com>
 *            Welter Silva <welter@vettalabs.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <set>
#include <sstream>

#ifndef WIN32
#include <unistd.h>
#endif

#include <opencog/util/misc.h>
#include <opencog/util/platform.h>

#include <opencog/atoms/base/Atom.h>
#include <opencog/atoms/proto/NameServer.h>
#include <opencog/atoms/base/Link.h>
#include <opencog/atoms/base/Node.h>

#include <opencog/atomspace/AtomSpace.h>
#include <opencog/atomspace/AtomTable.h>

//! Atom flag
#define FETCHED_RECENTLY        1  //BIT0
#define MARKED_FOR_REMOVAL      2  //BIT1
// #define MULTIPLE_TRUTH_VALUES   4  //BIT2
// #define FIRED_ACTIVATION        8  //BIT3
// #define HYPOTETHICAL_FLAG       16 //BIT4
// #define REMOVED_BY_DECAY        32 //BIT5
#define CHECKED                 64  //BIT6

//#define DPRINTF printf
#define DPRINTF(...)

#undef Type

namespace std {

// The hash of a weak pointer is just the atom type. Actually,
// it *has* to be the atom type, as otherwise the hash buckets
// won't be correct, and getIncomingByType() will fail to be fast.
opencog::Type
hash<opencog::WinkPtr>::operator()(const opencog::WinkPtr& w) const noexcept
{
    opencog::LinkPtr h(w.lock());
    if (nullptr == h) return 0;
    return h->get_type();
}

bool
equal_to<opencog::WinkPtr>::operator()(const opencog::WinkPtr& lw,
                                       const opencog::WinkPtr& rw) const noexcept
{
    opencog::Handle hl(lw.lock());
    opencog::Handle hr(rw.lock());
    return hl == hr;
}

} // namespace std

namespace opencog {

Atom::~Atom()
{
    _atom_space = nullptr;
    if (0 < getIncomingSetSize()) {
        // This can't ever possibly happen. If it does, then there is
        // some very sick bug with the reference counting that the
        // shared pointers are doing. (Or someone explcitly called the
        // destructor! Which they shouldn't do.)
        OC_ASSERT(0 == getIncomingSet().size(),
             "Atom deletion failure; incoming set not empty for %s h=%x",
             nameserver().getTypeName(_type).c_str(), get_hash());
    }
    drop_incoming_set();
}

// ==============================================================
// Whole lotta truthiness going on here.  Does it really need to be
// this complicated!?

static const Handle& truth_key(void)
{
	static Handle tk(createNode(PREDICATE_NODE, "*-TruthValueKey-*"));
	return tk;
}

void Atom::setTruthValue(const TruthValuePtr& newTV)
{
    if (nullptr == newTV) return;

    // We need to guarantee that the signal goes out with the
    // correct truth value.  That is, another setter could be changing
    // this, even as we are.  So make a copy, first.
    TruthValuePtr oldTV(getTruthValue());

    // If both old and new are e.g. DEFAULT_TV, then do nothing.
    if (oldTV.get() == newTV.get()) return;

    // ... and we still need to make sure that only one thread is
    // writing this at a time. std:shared_ptr is NOT thread-safe against
    // multiple writers: see "Example 5" in
    // http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety
    setValue (truth_key(), ProtoAtomCast(newTV));

    if (_atom_space != nullptr) {
        TVCHSigl& tvch = _atom_space->_atom_table.TVChangedSignal();
        tvch.emit(get_handle(), oldTV, newTV);
    }
}

TruthValuePtr Atom::getTruthValue() const
{
    ProtoAtomPtr pap(getValue(truth_key()));
    if (nullptr == pap) return TruthValue::DEFAULT_TV();
    return TruthValueCast(pap);
}

// ==============================================================
/// Setting values associated with this atom.
/// If the value is a null pointer, then the key is removed.
void Atom::setValue(const Handle& key, const ProtoAtomPtr& value)
{
	std::lock_guard<std::mutex> lck(_mtx);
	if (nullptr != value)
	{
		_values[key] = value;
	}
	else
	{
		// If the value is a null pointer, then the value at
		// this key should be blanked out, i.e. unset.
		_values.erase(key);
	}
}

ProtoAtomPtr Atom::getValue(const Handle& key) const
{
    // OK. The atomic thread-safety of shared-pointers is subtle. See
    // http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety
    // and http://cppwisdom.quora.com/shared_ptr-is-almost-thread-safe
    // What it boils down to here is that we must *always* make a copy
    // of the value before we use it, since it can go out of scope
    // because it can get set in another thread.  Viz, using it to
    // dereference can return a raw pointer to an object that has been
    // deconstructed.  The AtomSpaceAsyncUTest will hit this, as will
    // the multi-threaded async atom store in the SQL peristance backend.
    // Furthermore, we must make a copy while holding the lock! Got that?

    ProtoAtomPtr pap;
    std::lock_guard<std::mutex> lck(_mtx);
    auto pr = _values.find(key);
    if (_values.end() != pr) pap = pr->second;
    return pap;
}

HandleSet Atom::getKeys() const
{
    HandleSet keyset;
    std::lock_guard<std::mutex> lck(_mtx);
    for (const auto& pr : _values)
        keyset.insert(pr.first);

    return keyset;
}

void Atom::copyValues(const Handle& other)
{
    HandleSet okeys(other->getKeys());
    for (const Handle& k: okeys)
    {
        setValue(k, other->getValue(k));
    }
}

std::string Atom::valuesToString() const
{
    std::string rv;

    HandleSet keys(getKeys());
    for (const Handle& k: keys)
    {
        ProtoAtomPtr p = getValue(k);
        rv += "; key = " + k->to_string();
        rv += "; val = " + p->to_string() + "\n";
    }
    return rv;
}

// ==============================================================
// Flag stuff
bool Atom::isMarkedForRemoval() const
{
    return (_flags & MARKED_FOR_REMOVAL) != 0;
}

void Atom::unsetRemovalFlag(void)
{
    _flags &= ~MARKED_FOR_REMOVAL;
}

void Atom::markForRemoval(void)
{
    _flags |= MARKED_FOR_REMOVAL;
}

bool Atom::isChecked() const
{
    return (_flags & CHECKED) != 0;
}

void Atom::setChecked(void)
{
    _flags |= CHECKED;
}

void Atom::setUnchecked(void)
{
    _flags &= ~CHECKED;
}

// ==============================================================

void Atom::setAtomSpace(AtomSpace *tb)
{
    if (tb == _atom_space) return;

    // Either the existing _atomSpace is null, and tb is not, i.e. this
    // atom is being inserted into tb, or _atomSpace is not null, while
    // tb is null, i.e. atom is being removed from _atomSpace.  It is
    // illegal to just switch membership: one or the other of these two
    // pointers must be null.
    OC_ASSERT (nullptr == _atom_space or tb == nullptr,
               "Atom table is not null!");
    _atom_space = tb;
}

AtomTable* Atom::getAtomTable() const
{
    return &(_atom_space->_atom_table);
}

// ==============================================================
// Incoming set stuff

/// Start tracking the incoming set for this atom.
/// An atom can't know what it's incoming set is, until this method
/// is called.  If this atom is added to any links before this call
/// is made, those links won't show up in the incoming set.
///
/// We don't automatically track incoming sets for two reasons:
/// 1) std::set takes up 48 bytes
/// 2) adding and removing uses up cpu cycles.
/// Thus, if the incoming set isn't needed, then don't bother
/// tracking it.
void Atom::keep_incoming_set()
{
    if (_incoming_set) return;
    _incoming_set = std::make_shared<InSet>();
}

/// Stop tracking the incoming set for this atom.
/// After this call, the incoming set for this atom can no longer
/// be queried; it is erased.
void Atom::drop_incoming_set()
{
    if (nullptr == _incoming_set) return;
    std::lock_guard<std::mutex> lck (_mtx);
    _incoming_set->_iset.clear();
    _incoming_set = nullptr;
}

/// Add an atom to the incoming set.
void Atom::insert_atom(const LinkPtr& a)
{
    if (nullptr == _incoming_set) return;
    std::lock_guard<std::mutex> lck (_mtx);

    Type at = a->get_type();
    auto bucket = _incoming_set->_iset.find(at);
    if (bucket == _incoming_set->_iset.end())
    {
        auto pr = _incoming_set->_iset.emplace(
                   std::make_pair(at, WincomingSet()));
        bucket = pr.first;
    }
    bucket->second.insert(a);

#ifdef INCOMING_SET_SIGNALS
    _incoming_set->_addAtomSignal(shared_from_this(), a);
#endif /* INCOMING_SET_SIGNALS */
}

/// Remove an atom from the incoming set.
void Atom::remove_atom(const LinkPtr& a)
{
    if (nullptr == _incoming_set) return;
    std::lock_guard<std::mutex> lck (_mtx);
#ifdef INCOMING_SET_SIGNALS
    _incoming_set->_removeAtomSignal(shared_from_this(), a);
#endif /* INCOMING_SET_SIGNALS */
    Type at = a->get_type();
    auto bucket = _incoming_set->_iset.find(at);
    bucket->second.erase(a);
}

/// Remove old, and add new, atomically, so that every user
/// will see either one or the other, but not both/neither in
/// the incoming set. This is used to manage the StateLink.
void Atom::swap_atom(const LinkPtr& old, const LinkPtr& neu)
{
    if (nullptr == _incoming_set) return;
    std::lock_guard<std::mutex> lck (_mtx);

#ifdef INCOMING_SET_SIGNALS
    _incoming_set->_removeAtomSignal(shared_from_this(), old);
#endif /* INCOMING_SET_SIGNALS */
    Type ot = old->get_type();
    auto bucket = _incoming_set->_iset.find(ot);
    bucket->second.erase(old);

    Type nt = neu->get_type();
    bucket = _incoming_set->_iset.find(nt);
    if (bucket == _incoming_set->_iset.end())
    {
        auto pr = _incoming_set->_iset.emplace(
                   std::make_pair(nt, WincomingSet()));
        bucket = pr.first;
    }
    bucket->second.insert(neu);

#ifdef INCOMING_SET_SIGNALS
    _incoming_set->_addAtomSignal(shared_from_this(), neu);
#endif /* INCOMING_SET_SIGNALS */
}

size_t Atom::getIncomingSetSize() const
{
    if (nullptr == _incoming_set) return 0;
    std::lock_guard<std::mutex> lck (_mtx);

    size_t cnt = 0;
    for (const auto& pr : _incoming_set->_iset)
        cnt += pr.second.size();
    return cnt;
}

// We return a copy here, and not a reference, because the set itself
// is not thread-safe during reading while simultaneous insertion and
// deletion.  Besides, the incoming set is weak; we have to make it
// strong in order to hand it out.
IncomingSet Atom::getIncomingSet(AtomSpace* as) const
{
    static IncomingSet empty_set;
    if (nullptr == _incoming_set) return empty_set;

    if (as) {
        const AtomTable *atab = &as->get_atomtable();
        // Prevent update of set while a copy is being made.
        std::lock_guard<std::mutex> lck (_mtx);
        IncomingSet iset;
        for (const auto& bucket : _incoming_set->_iset)
        {
            for (const WinkPtr& w : bucket.second)
            {
                LinkPtr l(w.lock());
                if (l and atab->in_environ(l))
                    iset.emplace_back(l);
            }
        }
        return iset;
    }

    // Prevent update of set while a copy is being made.
    std::lock_guard<std::mutex> lck (_mtx);
    IncomingSet iset;
    for (const auto& bucket : _incoming_set->_iset)
    {
        for (const WinkPtr& w : bucket.second)
        {
            LinkPtr l(w.lock());
            if (l) iset.emplace_back(l);
        }
    }
    return iset;
}

IncomingSet Atom::getIncomingSetByType(Type type) const
{
    IncomingSet result;

    // The code below is mostly a cut-n-paste from the header file.
    // The only difference is that it works with LinkPtr instead of
    // Handle.  The primary issue is that casting from Handle back
    // to LinkPtr is slowwwwwww.  So we avoid that, here.
    if (nullptr == _incoming_set) return result;
    std::lock_guard<std::mutex> lck(_mtx);

    const auto bucket = _incoming_set->_iset.find(type);
    if (bucket == _incoming_set->_iset.cend()) return result;

    for (const WinkPtr& w : bucket->second)
    {
        LinkPtr h(w.lock());
        if (h) result.emplace_back(h);
    }
    return result;
}

std::string Atom::id_to_string() const
{
    return
        std::string("[") + std::to_string(get_hash()) + "]" +
        std::string("[") + (_atom_space? std::to_string(_atom_space->_atom_table.get_uuid()) : std::string("-1")) + "]";
}

std::string oc_to_string(const IncomingSet& iset, const std::string& indent)
{
	std::stringstream ss;
	ss << indent << "size = " << iset.size() << std::endl;
	for (unsigned i = 0; i < iset.size(); i++)
		ss << indent << "link[" << i << "]:" << std::endl
		   << iset[i]->to_string(indent + OC_TO_STRING_INDENT);
	return ss.str();
}

} // ~namespace opencog
<|endoftext|>


<commit_before>/* PBScoring.C
 *
 * Copyright (C) 2011 Marcel Schumann
 *
 * This program free software; you can redistribute it and/or modify
 * it under the terms of the GNU 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
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

 // ----------------------------------------------------
// $Maintainer: Marcel Schumann $
// $Authors: Marcel Schumann $
// ----------------------------------------------------

#include <BALL/SCORING/FUNCTIONS/PBScoring.h>
#include <BALL/SCORING/COMPONENTS/PB.h>

using namespace BALL;

PBScoring::PBScoring(AtomContainer& receptor, AtomContainer& ligand, Options& options)
	: ScoringFunction(receptor, ligand, options)
{
	setup();
}

PBScoring::PBScoring(AtomContainer& receptor, Vector3& hashgrid_origin, Options& options)
	: ScoringFunction(receptor, hashgrid_origin, options)
{
	setup();
}

void PBScoring::setup()
{
	ScoringFunction::setName("PBScoring");
	PB* pb = new PB(*this);
	pb->setName("PB");
	pb->setScoringFunction(*this);
	pb->setLigandIntraMolecular(0);
	scoring_components_.push_back(pb);
}

double PBScoring::getES()
{
	double es = 0;
	return es;
}
<commit_msg>Clarified licence<commit_after>// ----------------------------------------------------
// $Maintainer: Marcel Schumann $
// $Authors: Marcel Schumann $
// ----------------------------------------------------

#include <BALL/SCORING/FUNCTIONS/PBScoring.h>
#include <BALL/SCORING/COMPONENTS/PB.h>

using namespace BALL;

PBScoring::PBScoring(AtomContainer& receptor, AtomContainer& ligand, Options& options)
	: ScoringFunction(receptor, ligand, options)
{
	setup();
}

PBScoring::PBScoring(AtomContainer& receptor, Vector3& hashgrid_origin, Options& options)
	: ScoringFunction(receptor, hashgrid_origin, options)
{
	setup();
}

void PBScoring::setup()
{
	ScoringFunction::setName("PBScoring");
	PB* pb = new PB(*this);
	pb->setName("PB");
	pb->setScoringFunction(*this);
	pb->setLigandIntraMolecular(0);
	scoring_components_.push_back(pb);
}

double PBScoring::getES()
{
	double es = 0;
	return es;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *   Copyright 2007 - 2010 Craig Drummond <craig.p.drummond@gmail.com>       *
 *   Copyright 2013 - 2013 Yichao Yu <yyc1992@gmail.com>                     *
 *                                                                           *
 *   This program is free software; you can redistribute it and/or modify    *
 *   it under the terms of the GNU Lesser General Public License as          *
 *   published by the Free Software Foundation; either version 2.1 of the    *
 *   License, or (at your option) version 3, or any later version accepted   *
 *   by the membership of KDE e.V. (or its successor approved by the         *
 *   membership of KDE e.V.), which shall act as a proxy defined in          *
 *   Section 6 of version 3 of the license.                                  *
 *                                                                           *
 *   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       *
 *   Lesser General Public License for more details.                         *
 *                                                                           *
 *   You should have received a copy of the GNU Lesser General Public        *
 *   License along with this library. If not,                                *
 *   see <http://www.gnu.org/licenses/>.                                     *
 *****************************************************************************/

#include <kdeversion.h>
#if KDE_IS_VERSION(4, 3, 0)

#include <KColorScheme>
#include <KGlobalSettings>
#include <KConfig>
#include <KConfigGroup>
#include <QApplication>
#include "qtcurveshadowconfiguration.h"

namespace KWinQtCurve
{

QtCurveShadowConfiguration::QtCurveShadowConfiguration(QPalette::ColorGroup colorGroup)
                          : m_colorGroup(colorGroup)
{
    defaults();
}

void QtCurveShadowConfiguration::defaults()
{
    m_hOffset = 0;
    m_vOffset = 5;
    if(QPalette::Active==m_colorGroup)
    {
        m_size = 35;
        setColorType(CT_FOCUS);
        m_shadowType = SH_ACTIVE;
    }
    else
    {
        m_size = 30;
        setColorType(CT_GRAY);
        m_shadowType = SH_INACTIVE;
    }
}

void QtCurveShadowConfiguration::setColorType(ColorType ct)
{
    m_colorType=ct;
    switch(m_colorType)
    {
        default:
        case CT_FOCUS:
            m_color = KColorScheme(m_colorGroup).decoration(KColorScheme::FocusColor).color();
            break;
        case CT_HOVER:
            m_color = KColorScheme(m_colorGroup).decoration(KColorScheme::HoverColor).color();
            break;
        case CT_SELECTION:
            m_color = QApplication::palette().color(m_colorGroup, QPalette::Highlight);
            break;
        case CT_TITLEBAR:
            m_color = QPalette::Active==m_colorGroup
                        ? KGlobalSettings::activeTitleColor()
                        : KGlobalSettings::inactiveTitleColor();
            break;
        case CT_GRAY:
            m_color = QColor("#393835");
            break;
        case CT_CUSTOM:
            break;
    }
}

#define CFG_GROUP (QPalette::Active==m_colorGroup ? "ActiveShadows" : "InactiveShadows")

#define READ_ENTRY(name, field) do {                    \
        field = group.readEntry(name, def.field);       \
    } while (0)

void QtCurveShadowConfiguration::load(KConfig *cfg)
{
    KConfigGroup               group(cfg, CFG_GROUP);
    QtCurveShadowConfiguration def(m_colorGroup);

    READ_ENTRY("Size", m_size);
    READ_ENTRY("HOffset", m_hOffset);
    READ_ENTRY("VOffset", m_vOffset);
    READ_ENTRY("ColorType", m_colorType);
    READ_ENTRY("ShadowType", m_shadowType);

    if(CT_CUSTOM==m_colorType)
        READ_ENTRY("Color", m_color);
    if(m_size<MIN_SIZE || m_size>MAX_SIZE)
        m_size=def.shadowSize();
    if(m_hOffset<MIN_OFFSET || m_hOffset>MAX_OFFSET)
        m_hOffset=def.horizontalOffset();
    if(m_vOffset<MIN_OFFSET || m_vOffset>MAX_OFFSET)
        m_vOffset=def.verticalOffset();
    setColorType((ColorType)m_colorType);
}

#define WRITE_ENTRY(name, field) do {           \
        if (def.field == field) {               \
            group.deleteEntry(name);            \
        } else {                                \
            group.writeEntry(name, field);      \
        }                                       \
    } while (0)

void QtCurveShadowConfiguration::save(KConfig *cfg)
{
    KConfigGroup               group(cfg, CFG_GROUP);
    QtCurveShadowConfiguration def(m_colorGroup);

    WRITE_ENTRY("Size", m_size);
    WRITE_ENTRY("HOffset", m_hOffset);
    WRITE_ENTRY("VOffset", m_vOffset);
    WRITE_ENTRY("ColorType", m_colorType);
    WRITE_ENTRY("ShadowType", m_shadowType);

    if (m_colorType != CT_CUSTOM) {
        group.deleteEntry("Color");
    } else {
        WRITE_ENTRY("Color", m_color);
    }
}

}

#endif
<commit_msg>[qt5/kwin] deprecated warning<commit_after>/*****************************************************************************
 *   Copyright 2007 - 2010 Craig Drummond <craig.p.drummond@gmail.com>       *
 *   Copyright 2013 - 2013 Yichao Yu <yyc1992@gmail.com>                     *
 *                                                                           *
 *   This program is free software; you can redistribute it and/or modify    *
 *   it under the terms of the GNU Lesser General Public License as          *
 *   published by the Free Software Foundation; either version 2.1 of the    *
 *   License, or (at your option) version 3, or any later version accepted   *
 *   by the membership of KDE e.V. (or its successor approved by the         *
 *   membership of KDE e.V.), which shall act as a proxy defined in          *
 *   Section 6 of version 3 of the license.                                  *
 *                                                                           *
 *   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       *
 *   Lesser General Public License for more details.                         *
 *                                                                           *
 *   You should have received a copy of the GNU Lesser General Public        *
 *   License along with this library. If not,                                *
 *   see <http://www.gnu.org/licenses/>.                                     *
 *****************************************************************************/

#include <kdeversion.h>
#if KDE_IS_VERSION(4, 3, 0)

#include <KColorScheme>
#include <KGlobalSettings>
#include <KConfig>
#include <KConfigGroup>
#include <QApplication>
#include "qtcurveshadowconfiguration.h"

namespace KWinQtCurve
{

QtCurveShadowConfiguration::QtCurveShadowConfiguration(QPalette::ColorGroup colorGroup)
                          : m_colorGroup(colorGroup)
{
    defaults();
}

void QtCurveShadowConfiguration::defaults()
{
    m_hOffset = 0;
    m_vOffset = 5;
    if(QPalette::Active==m_colorGroup)
    {
        m_size = 35;
        setColorType(CT_FOCUS);
        m_shadowType = SH_ACTIVE;
    }
    else
    {
        m_size = 30;
        setColorType(CT_GRAY);
        m_shadowType = SH_INACTIVE;
    }
}

void QtCurveShadowConfiguration::setColorType(ColorType ct)
{
    m_colorType = ct;
    switch (m_colorType) {
    default:
    case CT_FOCUS:
        m_color = KColorScheme(m_colorGroup)
            .decoration(KColorScheme::FocusColor).color();
        break;
    case CT_HOVER:
        m_color = KColorScheme(m_colorGroup)
            .decoration(KColorScheme::HoverColor).color();
        break;
    case CT_SELECTION:
        m_color = QApplication::palette().color(m_colorGroup,
                                                QPalette::Highlight);
        break;
    case CT_TITLEBAR: {
        m_color = KColorScheme(m_colorGroup, KColorScheme::Window)
            .background(m_colorGroup == QPalette::Active ?
                        KColorScheme::ActiveBackground :
                        KColorScheme::NormalBackground)
            .color();
        break;
    }
    case CT_GRAY:
        m_color = QColor("#393835");
        break;
    case CT_CUSTOM:
        break;
    }
}

#define CFG_GROUP (QPalette::Active==m_colorGroup ? "ActiveShadows" : "InactiveShadows")

#define READ_ENTRY(name, field) do {                    \
        field = group.readEntry(name, def.field);       \
    } while (0)

void QtCurveShadowConfiguration::load(KConfig *cfg)
{
    KConfigGroup               group(cfg, CFG_GROUP);
    QtCurveShadowConfiguration def(m_colorGroup);

    READ_ENTRY("Size", m_size);
    READ_ENTRY("HOffset", m_hOffset);
    READ_ENTRY("VOffset", m_vOffset);
    READ_ENTRY("ColorType", m_colorType);
    READ_ENTRY("ShadowType", m_shadowType);

    if(CT_CUSTOM==m_colorType)
        READ_ENTRY("Color", m_color);
    if(m_size<MIN_SIZE || m_size>MAX_SIZE)
        m_size=def.shadowSize();
    if(m_hOffset<MIN_OFFSET || m_hOffset>MAX_OFFSET)
        m_hOffset=def.horizontalOffset();
    if(m_vOffset<MIN_OFFSET || m_vOffset>MAX_OFFSET)
        m_vOffset=def.verticalOffset();
    setColorType((ColorType)m_colorType);
}

#define WRITE_ENTRY(name, field) do {           \
        if (def.field == field) {               \
            group.deleteEntry(name);            \
        } else {                                \
            group.writeEntry(name, field);      \
        }                                       \
    } while (0)

void QtCurveShadowConfiguration::save(KConfig *cfg)
{
    KConfigGroup               group(cfg, CFG_GROUP);
    QtCurveShadowConfiguration def(m_colorGroup);

    WRITE_ENTRY("Size", m_size);
    WRITE_ENTRY("HOffset", m_hOffset);
    WRITE_ENTRY("VOffset", m_vOffset);
    WRITE_ENTRY("ColorType", m_colorType);
    WRITE_ENTRY("ShadowType", m_shadowType);

    if (m_colorType != CT_CUSTOM) {
        group.deleteEntry("Color");
    } else {
        WRITE_ENTRY("Color", m_color);
    }
}

}

#endif
<|endoftext|>


<commit_before>/*
    Copyright 2012 Joe Hermaszewski. All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "AS IS" AND ANY EXPRESS OR
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
    EVENT SHALL JOE HERMASZEWSKI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
    THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

    The views and conclusions contained in the software and documentation are
    those of the authors and should not be interpreted as representing official
    policies, either expressed or implied, of Joe Hermaszewski.
*/

#include "return_statement.hpp"

#include <cassert>
#include <memory>

#include <compiler/code_generator.hpp>
#include <compiler/complete_type.hpp>
#include <compiler/parser.hpp>
#include <compiler/sema_analyzer.hpp>
#include <compiler/shader_writer.hpp>
#include <compiler/terminal_types.hpp>
#include <compiler/tokens/expressions/expression.hpp>
#include <compiler/tokens/statements/statement.hpp>

namespace JoeLang
{
namespace Compiler
{

//------------------------------------------------------------------------------
// ReturnStatement
//------------------------------------------------------------------------------

ReturnStatement::ReturnStatement( Expression_up expression )
    :Statement( TokenTy::ReturnStatement )
    ,m_Expression( std::move(expression) )
{
}

ReturnStatement::~ReturnStatement()
{
}

bool ReturnStatement::AlwaysReturns() const
{
    return true;
}

std::set<Function_sp> ReturnStatement::GetCallees() const
{
    if( m_Expression )
        return m_Expression->GetCallees();
    else
        return std::set<Function_sp>{};
}

std::set<Variable_sp> ReturnStatement::GetVariables() const
{
    if( m_Expression )
        return m_Expression->GetVariables();
    else
        return std::set<Variable_sp>{};
}

std::set<Variable_sp> ReturnStatement::GetWrittenToVariables() const
{
    if( m_Expression )
        return m_Expression->GetWrittenToVariables();
    else
        return std::set<Variable_sp>{};
}

void ReturnStatement::PerformSema( SemaAnalyzer& sema,
                                   const CompleteType& return_type )
{
    // If we need a return value make sure we have one
    if( !m_Expression )
    {
        if( return_type.GetBaseType() != Type::VOID )
            sema.Error( "No return expression in function returning non-void" );
        return;
    }

    m_Expression->ResolveIdentifiers( sema );

    // Cast the return type to what we want if this fails, sema will know
    m_Expression = CastExpression::Create( return_type,
                                           std::move(m_Expression),
                                           false );
    m_Expression->PerformSema( sema );
}

void ReturnStatement::CodeGen( CodeGenerator& code_gen )
{
    code_gen.CreateReturnStatement( m_Expression );
}

void ReturnStatement::Write( ShaderWriter& shader_writer ) const
{
    shader_writer << "return";
    if( m_Expression )
        shader_writer << " " << *m_Expression;
    shader_writer << ";";
}

bool ReturnStatement::Parse( Parser& parser, ReturnStatement_up& token )
{
    // Try and parse the return keyword
    if( !parser.ExpectTerminal( TerminalType::RETURN ) )
        return false;

    // Parse the optional expression
    Expression_up expression;
    parser.Expect<Expression>( expression );
    CHECK_PARSER;

    if( !parser.ExpectTerminal( TerminalType::SEMICOLON ) )
    {
        parser.Error( "Expected ';' after return expression" );
        return false;
    }

    token.reset( new ReturnStatement( std::move(expression) ) );
    return true;
}

} // namespace Compiler
} // namespace JoeLang
<commit_msg>[+] returning on sema fail<commit_after>/*
    Copyright 2012 Joe Hermaszewski. All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "AS IS" AND ANY EXPRESS OR
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
    EVENT SHALL JOE HERMASZEWSKI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
    THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

    The views and conclusions contained in the software and documentation are
    those of the authors and should not be interpreted as representing official
    policies, either expressed or implied, of Joe Hermaszewski.
*/

#include "return_statement.hpp"

#include <cassert>
#include <memory>

#include <compiler/code_generator.hpp>
#include <compiler/complete_type.hpp>
#include <compiler/parser.hpp>
#include <compiler/sema_analyzer.hpp>
#include <compiler/shader_writer.hpp>
#include <compiler/terminal_types.hpp>
#include <compiler/tokens/expressions/expression.hpp>
#include <compiler/tokens/statements/statement.hpp>

namespace JoeLang
{
namespace Compiler
{

//------------------------------------------------------------------------------
// ReturnStatement
//------------------------------------------------------------------------------

ReturnStatement::ReturnStatement( Expression_up expression )
    :Statement( TokenTy::ReturnStatement )
    ,m_Expression( std::move(expression) )
{
}

ReturnStatement::~ReturnStatement()
{
}

bool ReturnStatement::AlwaysReturns() const
{
    return true;
}

std::set<Function_sp> ReturnStatement::GetCallees() const
{
    if( m_Expression )
        return m_Expression->GetCallees();
    else
        return std::set<Function_sp>{};
}

std::set<Variable_sp> ReturnStatement::GetVariables() const
{
    if( m_Expression )
        return m_Expression->GetVariables();
    else
        return std::set<Variable_sp>{};
}

std::set<Variable_sp> ReturnStatement::GetWrittenToVariables() const
{
    if( m_Expression )
        return m_Expression->GetWrittenToVariables();
    else
        return std::set<Variable_sp>{};
}

void ReturnStatement::PerformSema( SemaAnalyzer& sema,
                                   const CompleteType& return_type )
{
    // If we need a return value make sure we have one
    if( !m_Expression )
    {
        if( return_type.GetBaseType() != Type::VOID )
            sema.Error( "No return expression in function returning non-void" );
        return;
    }

    if( !m_Expression->ResolveIdentifiers( sema ) )
        return;

    // Cast the return type to what we want if this fails, sema will know
    m_Expression = CastExpression::Create( return_type,
                                           std::move(m_Expression),
                                           false );
    m_Expression->PerformSema( sema );
}

void ReturnStatement::CodeGen( CodeGenerator& code_gen )
{
    code_gen.CreateReturnStatement( m_Expression );
}

void ReturnStatement::Write( ShaderWriter& shader_writer ) const
{
    shader_writer << "return";
    if( m_Expression )
        shader_writer << " " << *m_Expression;
    shader_writer << ";";
}

bool ReturnStatement::Parse( Parser& parser, ReturnStatement_up& token )
{
    // Try and parse the return keyword
    if( !parser.ExpectTerminal( TerminalType::RETURN ) )
        return false;

    // Parse the optional expression
    Expression_up expression;
    parser.Expect<Expression>( expression );
    CHECK_PARSER;

    if( !parser.ExpectTerminal( TerminalType::SEMICOLON ) )
    {
        parser.Error( "Expected ';' after return expression" );
        return false;
    }

    token.reset( new ReturnStatement( std::move(expression) ) );
    return true;
}

} // namespace Compiler
} // namespace JoeLang
<|endoftext|>


<commit_before>/*
 * Satisfier.cc
 *
 * Copyright (C) 2015 Linas Vepstas
 *
 * Author: Linas Vepstas <linasvepstas@gmail.com>  January 2009
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <opencog/atomspace/AtomSpace.h>
#include <opencog/atoms/pattern/PatternLink.h>

#include "BindLinkAPI.h"
#include "Satisfier.h"

using namespace opencog;

bool Satisfier::grounding(const HandleMap &var_soln,
                          const HandleMap &term_soln)
{
	// PatternMatchEngine::print_solution(var_soln, term_soln);
	_result = TruthValue::TRUE_TV();

	// Record the grounding; we cache this later.
	if (1 == _varseq.size())
	{
		_ground = var_soln.at(_varseq[0]);
	}
	else
	{
		// If more than one variable, encapsulate in sequential order,
		// in a ListLink.
		HandleSeq vargnds;
		for (const Handle& hv : _varseq)
		{
			vargnds.push_back(var_soln.at(hv));
		}
		_ground = createLink(vargnds, LIST_LINK);
	}

	// No need to look for more groundings as _result isn't going to change
	// and opencog::satisfaction_link only needs the value of _result.
	return true;
}

/// This method handles the case of SequentialAnd, SequentialOr with
/// embedded AbsentLinks, NotLink-PresentLink and some weird
/// combinations of NotLink-ChoiceLink, and so-on.  The idea here is
/// that, if the pattern matcher ran to exhaustion, and NO groundings
/// at all were found, then pattern evaluation may still need to
/// trigger evaluatable clauses that evaluate only when exhaustive
/// search fails.  So, indeed, we do that here.
///
/// Of course, if the pattern had no variables (e.g. a SequenceLink or
/// FallbackLink with only evaluatables), then there cannot be a
/// grounding failure, by definition.  And if there was a grounding,
/// there can be no grounding failure, either. So we only process the
/// case where there are variables, and grounding failed.
bool Satisfier::search_finished(bool done)
{
	if (done) return done;

	// If there were no variables to be grounded, we have nothing to do.
	if (not _have_variables) return done;

	// If there was a grounding, then don't re-run; we're here
	// only to handle the no-groundings case.
	if (TruthValue::TRUE_TV() == _result) return done;

	// _optionals_present will be set to true if some optional clause
	// was grounded. Ergo, its not the no-grounding case.
	if (_optionals_present) return done;

	// Multi-component patterns will not have distinct bodies.
	// A failure to match one of the components is benign, and is
	// treated appropriately upstream. Just return.
	if (nullptr == _pattern_body) return done;

	// Evaluating the pattern body only makes sense if it is sequential
	// (ordered) -- if the body is an unordered AndLink, or if its a
	// ChoiceLink, etc, this makes no sense.
	Type btype = _pattern_body->get_type();
	if (SEQUENTIAL_AND_LINK != btype and SEQUENTIAL_OR_LINK != btype)
		return done;

	HandleMap empty;
	bool rc = eval_sentence(_pattern_body, empty);
	if (rc)
		_result = TruthValue::TRUE_TV();

	return rc;
}

// ===========================================================

bool SatisfyingSet::grounding(const HandleMap &var_soln,
                              const HandleMap &term_soln)
{
	// PatternMatchEngine::log_solution(var_soln, term_soln);

	// Do not accept new solution if maximum number has been already reached
	if (_satisfying_set.size() >= max_results)
		return true;

	if (1 == _varseq.size())
	{
		_satisfying_set.emplace(var_soln.at(_varseq[0]));

		// If we found as many as we want, then stop looking for more.
		return (_satisfying_set.size() >= max_results);
	}

	// If more than one variable, encapsulate in sequential order,
	// in a ListLink.
	HandleSeq vargnds;
	for (const Handle& hv : _varseq)
	{
		vargnds.push_back(var_soln.at(hv));
	}
	_satisfying_set.emplace(createLink(vargnds, LIST_LINK));

	// If we found as many as we want, then stop looking for more.
	return (_satisfying_set.size() >= max_results);
}

TruthValuePtr opencog::satisfaction_link(AtomSpace* as, const Handle& hlink)
{
	PatternLinkPtr plp(PatternLinkCast(hlink));

	Satisfier sater(as);
	plp->satisfy(sater);

#define PLACE_RESULTS_IN_ATOMSPACE
#ifdef PLACE_RESULTS_IN_ATOMSPACE
	// Shoot. XXX FIXME. Most of the unit tests require that the atom
	// that we return is in the atomspace. But it would be nice if we
	// could defer this indefinitely, until its really needed.
	Handle satgrd = as->add_atom(sater._ground);
#endif /* PLACE_RESULTS_IN_ATOMSPACE */

	// Cache the variable groundings. OpenPsi wants this.
	plp->set_groundings(satgrd);

	return sater._result;
}

Handle opencog::satisfying_set(AtomSpace* as, const Handle& hlink, size_t max_results)
{
	// Special case the BindLink. We probably shouldn't have to, and
	// the C++ code for handling this case could maybe be refactored
	// to handle BindLink as well as GetLink in one place... but right
	// now, it doesn't.
	Type blt = hlink->get_type();
	if (BIND_LINK == blt)
	{
		return bindlink(as, hlink, max_results);
	}
	if (DUAL_LINK == blt)
	{
		return recognize(as, hlink);
	}

	// If we are here, then we are a GET_LINK, right?
	if (GET_LINK != blt)
		throw RuntimeException(TRACE_INFO,
			"Unexpected SatisfyingLink type!");

	PatternLinkPtr bl(PatternLinkCast(hlink));

	SatisfyingSet sater(as);
	sater.max_results = max_results;
	bl->satisfy(sater);

	// Ugh. We used an std::set to avoid duplicates. But now, we need a
	// vector.  Which means copying. Got a better idea?
	HandleSeq satvec;
	for (const Handle& h : sater._satisfying_set)
		satvec.push_back(h);

	// Create the satisfying set, and cache it.
	Handle satset(createLink(satvec, SET_LINK));

#define PLACE_RESULTS_IN_ATOMSPACE
#ifdef PLACE_RESULTS_IN_ATOMSPACE
	// Shoot. XXX FIXME. Most of the unit tests require that the atom
	// that we return is in the atomspace. But it would be nice if we
	// could defer this indefinitely, until its really needed.
	satset = as->add_atom(satset);
#endif /* PLACE_RESULTS_IN_ATOMSPACE */
	bl->set_groundings(satset);

	return satset;
}

/* ===================== END OF FILE ===================== */
<commit_msg>Add debugging support<commit_after>/*
 * Satisfier.cc
 *
 * Copyright (C) 2015 Linas Vepstas
 *
 * Author: Linas Vepstas <linasvepstas@gmail.com>  January 2009
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <opencog/atomspace/AtomSpace.h>
#include <opencog/atoms/pattern/PatternLink.h>

#include "BindLinkAPI.h"
#include "Satisfier.h"

using namespace opencog;

bool Satisfier::grounding(const HandleMap &var_soln,
                          const HandleMap &term_soln)
{
	// PatternMatchEngine::print_solution(var_soln, term_soln);
	_result = TruthValue::TRUE_TV();

	// Record the grounding; we cache this later.
	if (1 == _varseq.size())
	{
		_ground = var_soln.at(_varseq[0]);
	}
	else
	{
		// If more than one variable, encapsulate in sequential order,
		// in a ListLink.
		HandleSeq vargnds;
		for (const Handle& hv : _varseq)
		{
			vargnds.push_back(var_soln.at(hv));
		}
		_ground = createLink(vargnds, LIST_LINK);
	}

	// No need to look for more groundings as _result isn't going to change
	// and opencog::satisfaction_link only needs the value of _result.
	return true;
}

/// This method handles the case of SequentialAnd, SequentialOr with
/// embedded AbsentLinks, NotLink-PresentLink and some weird
/// combinations of NotLink-ChoiceLink, and so-on.  The idea here is
/// that, if the pattern matcher ran to exhaustion, and NO groundings
/// at all were found, then pattern evaluation may still need to
/// trigger evaluatable clauses that evaluate only when exhaustive
/// search fails.  So, indeed, we do that here.
///
/// Of course, if the pattern had no variables (e.g. a SequenceLink or
/// FallbackLink with only evaluatables), then there cannot be a
/// grounding failure, by definition.  And if there was a grounding,
/// there can be no grounding failure, either. So we only process the
/// case where there are variables, and grounding failed.
bool Satisfier::search_finished(bool done)
{
	if (done) return done;

	// If there were no variables to be grounded, we have nothing to do.
	if (not _have_variables) return done;

	// If there was a grounding, then don't re-run; we're here
	// only to handle the no-groundings case.
	if (TruthValue::TRUE_TV() == _result) return done;

	// _optionals_present will be set to true if some optional clause
	// was grounded. Ergo, its not the no-grounding case.
	if (_optionals_present) return done;

	// Multi-component patterns will not have distinct bodies.
	// A failure to match one of the components is benign, and is
	// treated appropriately upstream. Just return.
	if (nullptr == _pattern_body) return done;

	// Evaluating the pattern body only makes sense if it is sequential
	// (ordered) -- if the body is an unordered AndLink, or if its a
	// ChoiceLink, etc, this makes no sense.
	Type btype = _pattern_body->get_type();
	if (SEQUENTIAL_AND_LINK != btype and SEQUENTIAL_OR_LINK != btype)
		return done;

	HandleMap empty;
	bool rc = eval_sentence(_pattern_body, empty);
	if (rc)
		_result = TruthValue::TRUE_TV();

	return rc;
}

// ===========================================================

bool SatisfyingSet::grounding(const HandleMap &var_soln,
                              const HandleMap &term_soln)
{
	// PatternMatchEngine::log_solution(var_soln, term_soln);

	// Do not accept new solution if maximum number has been already reached
	if (_satisfying_set.size() >= max_results)
		return true;

	if (1 == _varseq.size())
	{
		// std::map::at() can throw. Rethrow for easier deubugging.
		try
		{
			_satisfying_set.emplace(var_soln.at(_varseq[0]));
		}
		catch (...)
		{
			throw AssertionException(TRACE_INFO,
				"Internal error: ungrounded variable %s\n",
				_varseq[0]->to_string().c_str());
		}

		// If we found as many as we want, then stop looking for more.
		return (_satisfying_set.size() >= max_results);
	}

	// If more than one variable, encapsulate in sequential order,
	// in a ListLink.
	HandleSeq vargnds;
	for (const Handle& hv : _varseq)
	{
		vargnds.push_back(var_soln.at(hv));
	}
	_satisfying_set.emplace(createLink(vargnds, LIST_LINK));

	// If we found as many as we want, then stop looking for more.
	return (_satisfying_set.size() >= max_results);
}

TruthValuePtr opencog::satisfaction_link(AtomSpace* as, const Handle& hlink)
{
	PatternLinkPtr plp(PatternLinkCast(hlink));

	Satisfier sater(as);
	plp->satisfy(sater);

#define PLACE_RESULTS_IN_ATOMSPACE
#ifdef PLACE_RESULTS_IN_ATOMSPACE
	// Shoot. XXX FIXME. Most of the unit tests require that the atom
	// that we return is in the atomspace. But it would be nice if we
	// could defer this indefinitely, until its really needed.
	Handle satgrd = as->add_atom(sater._ground);
#endif /* PLACE_RESULTS_IN_ATOMSPACE */

	// Cache the variable groundings. OpenPsi wants this.
	plp->set_groundings(satgrd);

	return sater._result;
}

Handle opencog::satisfying_set(AtomSpace* as, const Handle& hlink, size_t max_results)
{
	// Special case the BindLink. We probably shouldn't have to, and
	// the C++ code for handling this case could maybe be refactored
	// to handle BindLink as well as GetLink in one place... but right
	// now, it doesn't.
	Type blt = hlink->get_type();
	if (BIND_LINK == blt)
	{
		return bindlink(as, hlink, max_results);
	}
	if (DUAL_LINK == blt)
	{
		return recognize(as, hlink);
	}

	// If we are here, then we are a GET_LINK, right?
	if (GET_LINK != blt)
		throw RuntimeException(TRACE_INFO,
			"Unexpected SatisfyingLink type!");

	PatternLinkPtr bl(PatternLinkCast(hlink));

	SatisfyingSet sater(as);
	sater.max_results = max_results;
	bl->satisfy(sater);

	// Ugh. We used an std::set to avoid duplicates. But now, we need a
	// vector.  Which means copying. Got a better idea?
	HandleSeq satvec;
	for (const Handle& h : sater._satisfying_set)
		satvec.push_back(h);

	// Create the satisfying set, and cache it.
	Handle satset(createLink(satvec, SET_LINK));

#define PLACE_RESULTS_IN_ATOMSPACE
#ifdef PLACE_RESULTS_IN_ATOMSPACE
	// Shoot. XXX FIXME. Most of the unit tests require that the atom
	// that we return is in the atomspace. But it would be nice if we
	// could defer this indefinitely, until its really needed.
	satset = as->add_atom(satset);
#endif /* PLACE_RESULTS_IN_ATOMSPACE */
	bl->set_groundings(satset);

	return satset;
}

/* ===================== END OF FILE ===================== */
<|endoftext|>